for Robot Artificial Inteligence

1. ROBOTIC FUNDAMENTAL

|

Corrdinate Systems

  • he coordinate systems relate to each other hierarchically, where the origin of each coordinate system is defined as a position in one of its ancestries(祖宗). Below are descriptions of commonly used coordinate systems, starting at the top of the hierarchy.
  • World coordinate system
    • The world coordinate system represents the entire station or robot cell. This is the top of the hierarchy to which all other coordinate systems are related.
  • Task frame coordinate system
    • The task frame coordinate system is useful to define within a station or robot cell, in particular with multiple robots or mechanisms. One task frame can coordinate the placement of several mechanisms, whereas several task frames are suitable when working with MultiMove Independent.
  • Base frame coordinate system
    • Each robot in the station has a base coordinate system, which is always located at the base of the robot.
  • Tool-centre point (TCP) coordinate system
    • The tool center point coordinate system, also called TCP, is the center point of the tool. Several different TCPs may be defined for one robot. All robots have one predefined TCP at the robot’s tool mounting point, called tool0. When a program runs, the robot moves the TCP to the programmed position.
  • WorkObject coordinate system
    • The workobject normally represents the physical work piece. It is composed of two coordinate systems: the User frame and the Object frame, where the latter is a child to the former. RobotStudio Developer Center

Robot 특성

  • joint axes and TCP related to each other
  • the process of finidng position and orientation of the TCP given the actual joint values is called Forward Kinemetic
  • Finding out the joint values that correspond to a given TCP position and orientation is solved by Inverse Kinematic
  • Robot movements
    • point to point (PTP)
    • Line
    • Circle
  • Speed Definition
    • Linear Speed in mm/s
    • Angular speed in deg/s
    • or combination of two
  • Work Space
    • Safe zone
    • Forbidden zones (if the TCP or joint is out of safe zone)

Frame

  • A frame is essentially a coordinate system with a specific position and orientation
  • Frame are the geometrical foundation of the robot arm and understand how to handle them is a critical systems
  • Global coordinate system(GCS)
  • Machine coordinate system(MCS)
  • Tool coordinate system(TCS)
  • Workspace coordinate system(WCS)
    • all the programmed points and movements refer to this system (Product coordinate system)

Comment  Read more

1.Introduction to Optimization

|

1. Introduction

what is optimization?

  • An important tool in daily life, business and engineer
    • Running a business: to maximize profit, minimize loss, maximize efficiency, or minimize risk.
    • Design: minimize the weight of a bridge, and maximize the strength, within the design constrains; airplane engineering such as shape design and material selection, packing transistors in a computer chip in a functional way.
    • Planning: select a flight route to minimize time or fuel consumption of an airplane
    • Supermarket pricing and logistic
    • Big data/AI
  • Formal definition: to minimize (or maximize) a real function by deciding the values of free variables from within an allowed set.

Classification of optimization problems

  • Continuous vs Discrete
  • Constrained vs Unconstrained
  • Global vs Local
  • Stochastic vs Deterministic
  • Convex vs Nonconvex
    • Stochastic : random variable(DSPG)
  • Convex has a lot of problem come in
  • Convex form in range
    • λ ∈ {0,1} (0~1)

Mathematical optimization

  • optimal solution $x^*$ has smallest value of $f_0$ among all vectors that satisfy the constraints

Examples

  • portfolio optimization
    • variables: amounts invested in different assets
    • constraints: budget, max./min. investment per asset, minimum return
      • max/min : minimum could be zero, so we’re not allowed to actually purchase
      • minimum return: we expect from this collection from this portfolio
    • objective: overall risk or return variance
      • ex) 500 stocks in can invest in, in my mean return absolutely muse excess 11% period
  • device sizing in electronic circuits
    • variables: device widths and lengths
    • constraints: manufacturing limits, timing requirements, maximum area
    • objective: power consumption
  • data fitting
    • variables: model parameters
    • constraints: prior information, parameter limits
    • objective: measure of misfit or prediction error

Examples

Examples

  • Find two nonnegative numbers whose sum is up to 6 so that their product is a maximum.
  • It is equivalent to find the largest area of a rectangular region provided that its perimeter is no greater than 12.
  • Problem: let the two numbers be x, y, solve

Examples

  • Find a line that “best” fit three given points (x1, y1) = (2, 1), (x2, y2) = (3, 6) and (x3, y3) = (5, 4).
  • Problem: let the line equation be y = ax + b, in the following least square sense:

Traveling sales man problem (TSMP)

  • A salesman needs to visit a number (n) of cities, denoted by city 1, 2, · · · , n.
  • The distances between cities are known, i.e. d_ij denotes the distance between city i and city j.
  • The salesman wants to travel each city once in turn and in the meantime minimize the total travel distance.
  • What order should be used?
  • Problem: denote the order of travelling by ($i_1$, · · · , $i_n$), model
  • this is polynomial time

Solving optimization problems

  • general optimization problem (find a point: global optimization)
    • very difficult to solve
    • methods involve some compromise, e.g., very long computation time, or not always finding the solution
  • exceptions : certain problem classes can be solved efficiently and reliably (Global solution)
    • least-squares problems (we get the answer in period)
    • linear programming problems (we get the answer in period)
    • convex optimization problems (Global solution)
  • most problem can not be optimized, but we use convex optimization solve the problem
    • ex) singular values, principal component analysis

Convex optimization problem

  • objective and constraint functions are convex:
  • includes least-squares problems and linear programs as special cases
  • linear function are right on the boundary they have zero curvature(弯曲)
  • so one way to say convex is just positive curvature(can solve problem)

Convex optimization problem

  • linear square problems

Convex optimization problem

  • solving convex optimization problems
    • no analytical solution
    • reliable and efficient algorithms
    • computation time (roughly) proportional to max{n3, n2m, F}, where F is cost of evaluating $f_i$’s and their first and second derivatives(this is basically square)
    • almost a technology
  • using convex optimization
    • often difficult to recognize
    • surprisingly many problems can be solved via convex optimization

Convex optimization example

  • I have surface here with patches and I have some lamps here and we are going to choose the illumination powers in the lamps. that’s our variable. we’ll say the illumination on a patch here is going to be a sum of illumination from the lamps and it is going to be following proportional to the lamp power. and proportionality constant can be an inverse square law. R is the distance between patch and lamp, and there will be something which is a shading effect because obviously if we are coming in straight on. we get full power if this lamp for examples, put little illumination on here and if this were below it’s horizon if there were a lamp here, it would be not illuminate this patch at all

Least squares problems

  • A is structured like sparse(稀少的)(image processing like transformation)

Variants of Least squares

Linear Programming

  • huge amount of qualitative intelligent things about linear program what we can not do is we can not write down formula for solution
  • solving linear programs
    • no analytical formula for solution ( there is no formula, there is no a transpose A inverse a transpose B)
    • reliable and efficient algorithms and software
    • computation time proportional to $n^2$m if m >= n; less with structure (same as least square)
      • m : number of contain
    • a mature technology
    • a few standard tricks used to convert problems into linear programs
      • e.g., problems involving $l_1$- or $l_∞$- norms, piecewise(分段)-linear functions

Graphic optimization in 2D

Example: The transportation problem

Optimal transport

Optimal transport: LP

Global vs local solution

Global vs local solution

Graph

Reference

Optimization method - Standford University

Comment  Read more

Move_base_msgsConfig error

|

problem statement

CMake Warning at /opt/ros/kinetic/share/catkin/cmake/catkinConfig.cmake:76 (find_package):
  Could not find a package configuration file provided by "move_base_msgs"
  with any of the following names:

    move_base_msgsConfig.cmake
    move_base_msgs-config.cmake

  Add the installation prefix of "move_base_msgs" to CMAKE_PREFIX_PATH or set
  "move_base_msgs_DIR" to a directory containing one of the above files.  If
  "move_base_msgs" provides a separate development package or SDK, be sure it
  has been installed.
Call Stack (most recent call first):
  neo_driver/neo_watchdogs/CMakeLists.txt:7 (find_package)


-- Could not find the required component 'move_base_msgs'. The following CMake error indicates that you either need to install the package with the same name or change your environment so that it can be found.
CMake Error at /opt/ros/kinetic/share/catkin/cmake/catkinConfig.cmake:83 (find_package):
  Could not find a package configuration file provided by "move_base_msgs"
  with any of the following names:

    move_base_msgsConfig.cmake
    move_base_msgs-config.cmake

  Add the installation prefix of "move_base_msgs" to CMAKE_PREFIX_PATH or set
  "move_base_msgs_DIR" to a directory containing one of the above files.  If
  "move_base_msgs" provides a separate development package or SDK, be sure it
  has been installed.
Call Stack (most recent call first):
  neo_driver/neo_watchdogs/CMakeLists.txt:7 (find_package)

Solution

  • it is not installed move_base msg, therefore need to install
    sudo apt-get ros-kinetic-navigation
    

Comment  Read more

31. Auto Pointer

|

Auto Pointer

  • Smart Pointer라고도 불립니다.
  • C++ 프로그램에서 new 키워드를 사용하여 동적으로 할당받은 메모리는, 반드시 delete 키워드를 사용하여 해제해야 합니다.
  • C++에서는 메모리 누수(memory leak)로부터 프로그램의 안전성을 보장하기 위해 스마트 포인터를 제공하고 있습니다.
  • 스마트 포인터(smart pointer)란 포인터처럼 동작하는 클래스 템플릿으로, 사용이 끝난 메모리를 자동으로 해제해 줍니다.

Auto Pointer 동작

  • 보통 new 키워드를 사용해 기본 포인터(raw pointer)가 실제 메모리를 가리키도록 초기화한 후에, 기본 포인터를 스마트 포인터에 대입하여 사용합니다.
  • 이렇게 정의된 스마트 포인터의 수명이 다하면, 소멸자는 delete 키워드를 사용하여 할당된 메모리를 자동으로 해제합니다.
  • 따라서 new 키워드가 반환하는 주소값을 스마트 포인터에 대입하면, 따로 메모리를 해제할 필요가 없어집니다.

Auto Pointer 종류

  • C++11 이전에는 auto_ptr이라는 스마트 포인터를 사용하여 이 작업을 수행하였습니다.
  • 하지만 C++11부터는 다음과 같은 새로운 스마트 포인터를 제공하고 있습니다
    1. unique_ptr
    2. shared_ptr
    3. weak_ptr
  • 스마트 포인터는 memory 헤더 파일에 정의되어 있습니다.

unique_ptr

  • unique_ptr은 하나의 스마트 포인터만이 특정 객체를 소유할 수 있도록, 객체에 소유권 개념을 도입한 스마트 포인터입니다
  • 이 스마트 포인터는 해당 객체의 소유권을 가지고 있을 때만, 소멸자가 해당 객체를 삭제할 수 있습니다.
  • unique_ptr 인스턴스는 move() 멤버 함수를 통해 소유권을 이전할 수는 있지만, 복사할 수는 없습니다.
  • 소유권이 이전되면, 이전 unique_ptr 인스턴스는 더는 해당 객체를 소유하지 않게 재설정됩니다.

예제

unique_ptr<int> ptr01(new int(5)); // int형 unique_ptr인 ptr01을 선언하고 초기화함.

auto ptr02 = move(ptr01);          // ptr01에서 ptr02로 소유권을 이전함.

// unique_ptr<int> ptr03 = ptr01;  // 대입 연산자를 이용한 복사는 오류를 발생시킴.

ptr02.reset();                     // ptr02가 가리키고 있는 메모리 영역을 삭제함.

ptr01.reset();                     // ptr01가 가리키고 있는 메모리 영역을 삭제함.
  • 보통의 C++ 객체에 대해 스마트 포인터가 필요한 상황에서는 주로 unique_ptr을 사용하면 됩니다.

make_unique

  • C++14 이후부터 제공되는 make_unique() 함수를 사용하면 unique_ptr 인스턴스를 안전하게 생성할 수 있습니다.
  • make_unique() 함수는 전달받은 인수를 사용해 지정된 타입의 객체를 생성하고, 생성된 객체를 가리키는 unique_ptr을 반환합니다.
  • 이 함수를 사용하면, 예외 발생에 대해 안전하게 대처할 수 있습니다.

예제

#include <iostream>

#include <memory>

using namespace std;



class Person

{

private:

    string name_;

    int age_;

public:

    Person(const string& name, int age); // 기초 클래스 생성자의 선언

    ~Person() { cout << "소멸자가 호출되었습니다." << endl; }

    void ShowPersonInfo();

};



int main(void)

{

    unique_ptr<Person> hong = make_unique<Person>("길동", 29);

    hong->ShowPersonInfo();

    return 0;

}



Person::Person(const string& name, int age) // 기초 클래스 생성자의 정의

{

    name_ = name;

    age_ = age;

    cout << "생성자가 호출되었습니다." << endl;

}



void Person::ShowPersonInfo() { cout << name_ << "의 나이는 " << age_ << "살입니다." << endl; }

결과

생성자가 호출되었습니다.

길동의 나이는 29살입니다.

소멸자가 호출되었습니다.

shared_ptr

  • shared_ptr은 하나의 특정 객체를 참조하는 스마트 포인터가 총 몇 개인지를 참조하는 스마트 포인터입니다.
  • 이렇게 참조하고 있는 스마트 포인터의 개수를 참조 횟수(reference count)라고 합니다
  • 참조 횟수는 특정 객체에 새로운 shared_ptr이 추가될 때마다 1씩 증가하며, 수명이 다할 때마다 1씩 감소합니다.
  • 따라서 마지막 shared_ptr의 수명이 다하여, 참조 횟수가 0이 되면 delete 키워드를 사용하여 메모리를 자동으로 해제합니다.

예제

shared_ptr<int> ptr01(new int(5)); // int형 shared_ptr인 ptr01을 선언하고 초기화함.

cout << ptr01.use_count() << endl; // 1

auto ptr02(ptr01);                 // 복사 생성자를 이용한 초기화

cout << ptr01.use_count() << endl; // 2

auto ptr03 = ptr01;                // 대입을 통한 초기화

cout << ptr01.use_count() << endl; // 3  
  • 위의 예제에서 사용된 use_count() 멤버 함수는 shared_ptr 객체가 현재 가리키고 있는 리소스를 참조 중인 소유자의 수를 반환해 줍니다.
  • 위와 같은 방법 이외에도 make_shared() 함수를 사용하면 shared_ptr 인스턴스를 안전하게 생성할 수 있습니다.
  • make_shared() 함수는 전달받은 인수를 사용해 지정된 타입의 객체를 생성하고, 생성된 객체를 가리키는 shared_ptr을 반환합니다.
  • 이 함수를 사용하면, 예외 발생에 대해 안전하게 대처할 수 있습니다.

예제

shared_ptr<Person> hong = make_shared<Person>("길동", 29);

cout << "현재 소유자 수 : " << hong.use_count() << endl; // 1

auto han = hong;

cout << "현재 소유자 수 : " << hong.use_count() << endl; // 2

han.reset(); // shared_ptr인 han을 해제함.

cout << "현재 소유자 수 : " << hong.use_count() << endl; // 1

weak_ptr

  • weak_ptr은 하나 이상의 shared_ptr 인스턴스가 소유하는 객체에 대한 접근을 제공하지만, 소유자의 수에는 포함되지 않는 스마트 포인터입니다.
  • shared_ptr은 참조 횟수(reference count)를 기반으로 동작하는 스마트 포인터입니다.
  • 만약 서로가 상대방을 가리키는 shared_ptr를 가지고 있다면, 참조 횟수는 절대 0이 되지 않으므로 메모리는 영원히 해제되지 않습니다.
  • 이렇게 서로가 상대방을 참조하고 있는 상황을 순환 참조(circular reference)라고 합니다.
  • weak_ptr은 바로 이러한 shared_ptr 인스턴스 사이의 순환 참조를 제거하기 위해서 사용됩니다.

Exercise

#include <iostream>
#include <memory>

using namespace std;

class Test {
public:
	Test() {
		cout << "created" << endl;
	}

	void greet() {
		cout << "Hello" << endl;
	}

	~Test() {
		cout << "destroyed" << endl;
	}
};

class Temp {
private:
	unique_ptr<Test[]> pTest;

public:
	Temp(): pTest(new Test[1]) {

	}
};

int main() {

	Temp temp;

	unique_ptr<Test[]> pTest(new Test[1]); // create array 0,1

	pTest[0].greet();

	cout << "Finished" << endl;

	return 0;
}

Result

REFERENCE

TCP School

Comment  Read more

Ubuntu 16.04 Lite에 가상 환경 python3 설치하기

|

저와 같이 반복 학습으로 로봇을 훈련시키거나 다른 이유로 python3 가상환경을 만들어서 사용하려고 하시는분들에게 ROS 는 Python 2.7버전밖에 제공하지 못하여 프로젝트를 꺼려하시는 분들께 가상 환경 설치및 Ros에서 임시로 제공하는 python 3 프로젝트 파일을 만들어 보겠습니다.

  1. ROS python 3 프로젝트 파일 만들기

첫번쨰로 python3 환경을 만들기 위해 라이브러리로 부터 셋업을 합니다.

sudo apt-get install python3-pip python3-yaml
sudo pip3 install virtualenv
virtualenv -p python3 dnn_venv
sudo pip3 install rospkg catkin_pkg

홈 다이렉터리에 가면 dnn_venv폴더가가 생긴 것을 볼 수 있습니다. python 3 활성화를 위해서 아래와 같이 따라합니다.

cd dnn_venv/bin
source activate

그러면 python3가 활성화 된것을 볼 수 있습니다. 비활성화 command는

deactivate하면 비활성화가 됩니다.
  1. Catkin 폴더 만들기 이제 Catkin 폴더를 만들얼 보겠습니다.
    cd ..
    sudo pip3 install rosdep
    sudo pip3 install rosinstall_generator
    sudo pip3 install rosinstall
    

catkin 폴더를 설정하겠습니다.

catkin config --init
sudo pip3 install wstool
catkin config -DCMAKE_BUILD_TYPE=Release
git clone https://github.com/tkruse/vcstools
cd vcstools
git checkout mock_server_tar_test
python setup.py develop
cd ..
git clone https://github.com/vcstools/wstool
cd wstool
python setup.py develop
rosinstall_generator ros_comm --rosdistro kinetic --deps --tar > kinetic-ros_comm.rosinstall
wstool init -j8 src kinetic-ros_comm.rosinstall

만약 설치중 오류가 뜨면

wstool update -j 4 -t src

Catkin 하기전에 export를 해줍니다.

export ROS_PYTHON_VERSION=3

그리고 몇가지 dependencies를 설치해줍니다

sudo apt install python3-empy
sudo apt install libgpgme11-dev
catkin build
source install/setup.bash --extend

3. Opencv 설치

cd src
git clone -b kinetic https://github.com/ros-perception/vision_opencv.git
cd ~/catkin_build_ws
catkin build cv_bridge
source install/setup.bash --extend

[Reference]

(https://stackoverflow.com/questions/49221565/unable-to-use-cv-bridge-with-ros-kinetic-and-python3)

https://answers.ros.org/question/237613/how-to-define-ros-kinetic-to-use-python3-instead-of-python27/

https://medium.com/@beta_b0t/how-to-setup-ros-with-python-3-44a69ca36674

https://github.com/ros/ros/issues/158

https://github.com/OTL/cozmo_driver#super-hack-to-run-rospy-from-python3

Comment  Read more