<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Erdem Uysal on Medium]]></title>
        <description><![CDATA[Stories by Erdem Uysal on Medium]]></description>
        <link>https://medium.com/@erdemuysalx?source=rss-e869ac665292------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*y-N83uqjLrLu1DQdVMistg.jpeg</url>
            <title>Stories by Erdem Uysal on Medium</title>
            <link>https://medium.com/@erdemuysalx?source=rss-e869ac665292------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:38:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@erdemuysalx/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SLAM and Navigation in ROS]]></title>
            <link>https://erdemuysalx.medium.com/slam-and-navigation-in-ros-ec51c444a6b3?source=rss-e869ac665292------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec51c444a6b3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[aml]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[robot-operating-system]]></category>
            <dc:creator><![CDATA[Erdem Uysal]]></dc:creator>
            <pubDate>Sat, 21 Sep 2024 07:32:01 GMT</pubDate>
            <atom:updated>2024-09-21T07:32:01.512Z</atom:updated>
            <content:encoded><![CDATA[<p>Can you imagine a robot that cannot locate itself, map its surroundings, or navigate? Such a robot would hardly be useful. These essential capabilities make robots indispensable in many applications. But does every robotics software developer need to be an expert in SLAM (Simultaneous Localization and Mapping) and navigation, which are distinct research areas, to implement these features? Fortunately, the answer is no, thanks to ROS.</p><p>In this article, we will explore how to tackle complex tasks such as SLAM and navigation using ROS. Even if these topics are not directly applicable to your specific robot, I believe this guide will serve as a valuable starting point and help you build a solid technical foundation.</p><h3>SLAM and Navigation Using ROS</h3><p>While SLAM and navigation are complex and challenging fields, ROS simplifies them conceptually and provides algorithms that can be integrated into your robotics application with minimal adjustments. Some commonly used algorithms and nodes include:</p><ul><li><a href="http://wiki.ros.org/amcl">amcl </a>(Adaptive Monte Carlo Localization)</li><li><a href="http://wiki.ros.org/gmapping">gmapping</a></li><li><a href="http://wiki.ros.org/move_base">move_base</a></li></ul><p>Behind the scenes, ROS processes data from odometry and sensors, such as LiDAR or cameras, converting this information into velocity commands that are sent to the robot’s controller. However, implementing ROS’s navigation algorithms on an arbitrary robot can be more involved. Before starting navigation, the robot must be running ROS, have a properly configured TF transform tree, and publish odometry and sensor data using the appropriate ROS message types.</p><h3>Essential Requirements for Effective Robot Navigation</h3><p>Before a robot can navigate effectively, several prerequisites must be met to ensure smooth operation and accurate performance. These include:</p><ul><li><strong>URDF (Universal Robot Description File)</strong>: The robot’s URDF must be error-free, as it provides a detailed description of the robot’s physical structure, which is essential for proper navigation.</li><li><strong>Localization</strong>: The robot needs to know its exact position relative to its environment. This can be achieved using various sensors, such as LiDAR or cameras, to accurately localize the robot.</li><li><strong>Obstacle Avoidance</strong>: During navigation, unexpected obstacles may appear. The robot should be capable of detecting and dynamically avoiding these obstacles in real-time.</li><li><strong>Path Planning</strong>: To move from point A to point B, the robot must be able to calculate an efficient and collision-free route using path planning algorithms.</li></ul><h3>Configuring the Robot for the ROS Navigation Stack</h3><p>The ROS Navigation Stack comprises several essential components that work together to enable a robot to move autonomously. Each component plays a critical role in ensuring accurate localization, path planning, and motion control. Below is an explanation of the key components in the navigation stack:</p><ul><li><strong>Sensor Transforms (tf)</strong>: The data collected from various sensors must be referenced to a common frame, typically base_link, to accurately compare information from different sensors. The robot should publish the relationship between its main coordinate frame and its sensors&#39; frames using ROS tf.</li><li><strong>Sensor Sources</strong>: Sensors serve two main purposes in navigation: localizing the robot on the map (e.g., using a laser scanner) and detecting obstacles in its path (using lasers, sonars, or point clouds).</li><li><strong>Odometry Source</strong>: Odometry data provides the robot’s position relative to its starting point. The main sources of odometry are wheel encoders, IMUs, and 2D/3D cameras (for visual odometry). The odometry value must be published to the navigation stack using the nav_msgs/Odometry message type, which can contain both the robot&#39;s position and velocity.</li><li><strong>Base Controller</strong>: The base controller’s primary function is to take the output of the navigation stack (a geometry_msgs/Twist message) and convert it into motor commands, setting the robot&#39;s velocity to execute the desired motion.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*CoQ4AoG1hPt4lahe0_jscg.png" /><figcaption>ROS Navigation Stack Architecture</figcaption></figure><p>If you haven’t done so already, create a new package named robot_navigation inside the workspace ros_ws:</p><pre>cd .../ros_ws/src<br>catkin_create_pkg robot_navigation std_msgs roscpp</pre><h4>Implementing SLAM Using the gmapping ROS Node</h4><p>ROS provides powerful tools to assist in the SLAM process, such as acml and gmapping, for enabling robots to understand and navigate their environments which uses SLAM techniques to build a map from sensor data. Below are the steps required to configure and run the gmapping node for SLAM purposes.</p><p><strong>Step 1.</strong> Create a new file named gmapping.launch in the package robot_navigation, located in the folder .../robot_navigation/launch. Paste the code below into gmapping.launch:</p><pre>&lt;launch&gt;<br><br>  &lt;arg name=&quot;use_gazebo&quot; default=&quot;false&quot; /&gt;<br><br>  &lt;!-- Gazebo --&gt;<br>  &lt;group if=&quot;$(arg use_gazebo)&quot;&gt;<br>      &lt;param name=&quot;use_sim_time&quot; value=&quot;true&quot; /&gt;<br>      &lt;include file=&quot;$(find robot_bringup)/launch/robot.launch&quot;&gt;<br>          &lt;arg name=&quot;world&quot; value=&quot;maze&quot; /&gt;<br>      &lt;/include&gt;<br>  &lt;/group&gt;<br><br>  &lt;!-- SLAM --&gt;<br>  &lt;node pkg=&quot;gmapping&quot; type=&quot;slam_gmapping&quot; name=&quot;gmapping&quot;&gt;<br>      &lt;param name=&quot;base_frame&quot;            value=&quot;base_link&quot;/&gt;<br>      &lt;param name=&quot;odom_frame&quot;            value=&quot;odom&quot; /&gt;<br>      &lt;param name=&quot;map_update_interval&quot;   value=&quot;3.0&quot;/&gt;<br>      &lt;param name=&quot;maxUrange&quot;             value=&quot;15.0&quot;/&gt;<br>  &lt;/node&gt;<br><br>  &lt;!-- Teleoperation - keyboard control --&gt;<br>  &lt;node pkg=&quot;teleop_twist_keyboard&quot; type=&quot;teleop_twist_keyboard.py&quot; name=&quot;teleop_twist_keyboard&quot; output=&quot;screen&quot;/&gt;<br><br>&lt;/launch&gt;</pre><p><strong>Step 2. </strong>Configure parameters such as base_frame, odom_frame, map_update_interval, and maxUrange manually in the launch file according to your hardware. Alternatively, you can write parameters into the gmapping.yaml file and link it to the launch file:</p><pre>&lt;rosparam file=&quot;$(find gmapping_package)/launch/gmapping.yaml&quot; command=&quot;load&quot;/&gt;</pre><p><strong>Step 3. </strong>Launch the gmapping node:</p><pre>roslaunch robot_navigation gmapping.launch</pre><p><strong>Step 4.</strong> Track the map in RViz:</p><pre>rosrun rviz rviz</pre><p><strong>Step 5. </strong>Using the teleop_twist_keyboard node and your PC&#39;s keyboard, drive the mobile robot around to build a complete map of the environment in which it operates.</p><p><strong>Step 6. </strong>Once the mapping is complete, save the map:</p><pre>rosrun map_server map_saver -f map</pre><p>This will generate two files:</p><ul><li>A PGM image file of the map</li><li>A YAML file containing metadata about the map</li></ul><p><strong>Step 7.</strong> To make the map available to other nodes, serve the map data by running the following ROS service:</p><pre>rosrun map_server map_server map.yaml</pre><p>This will create two topics: /map and /map_metadata, which other nodes can subscribe to.</p><h4>Implementing Navigation Using move_base ROS Node</h4><p>In ROS, path planning is performed using the occupancy map, previously generated by the gmapping node. The next step is to create a cost map, which allows for the calculation of an optimal trajectory. Once the best path is identified, appropriate control mechanisms can be applied to follow the path efficiently. Both path planning and velocity control are managed by the move_base node. This node utilizes two cost maps—one for the global planner and another for the local planner (from the <a href="https://wiki.ros.org/costmap_2d">costmap_2d </a>package). These components need to be properly configured to enable the move_base node to function effectively. Below are the steps to configure and run the move_base node for navigation.</p><p><strong>Step 1. </strong>The first component of the move_base node is the cost map. The cost map is a grid where each cell is assigned a value representing the “cost” based on its distance from obstacles. The closer the obstacle, the higher the cost. Two types of costs are used:</p><ul><li><strong>Global Cost Map</strong>: Helps the global planner calculate the shortest path between two points using previously gathered sensor data.</li><li><strong>Local Cost Map</strong>: Assists the local planner in dynamically controlling smaller sections of the path.</li></ul><p>To configure the costmap parameters, create and edit the following files.</p><p>/robot_navigation/config/costmap_common.yaml for common cost map parameters:</p><pre>global_frame: map<br>robot_base_frame: base_link<br>footprint: [[0.14, 0.14], [0.14, -0.14], [-0.14, -0.14], [-0.14, 0.14]]<br>rolling_window: true<br><br>inflation_radius: 0.5<br>cost_scaling_factor: 4.0<br><br>track_unknown_space: true<br>observation_sources: scan<br>scan: {sensor_frame: laser, data_type: LaserScan, topic: scan, marking: true, clearing: true}</pre><p>/robot_navigation/config/costmap_global.yaml for global cost map parameters:</p><pre>global_costmap:<br>    update_frequency: 2.0<br>    publish_frequency: 1.0<br><br>    obstacle_range: 5.0<br>    raytrace_range: 5.0<br>    static_map: true<br><br>    width: 15.0<br>    height: 15.0</pre><p>/robot_navigation/config/costmap_local.yaml for local cost map parameters:</p><pre>local_costmap:<br>    update_frequency: 5.0<br>    publish_frequency: 2.0<br><br>    obstacle_range: 2.5<br>    raytrace_range: 2.5<br>    static_map: false<br><br>    width: 2.5<br>    height: 2.5<br>    resolution: 0.02</pre><p><strong>Step 2. </strong>The second component of the move_base node is the planner. The planner’s role is to reach the target position while avoiding obstacles within a user-defined tolerance. It uses the costmap to generate a path through the cells with the lowest cost. The move_base node utilizes two planners:</p><ul><li><strong>Global Planner</strong>: Finds the optimal path using the global costmap.</li><li><strong>Local Planner</strong>: Selects controls to guide the robot along the path by adjusting velocities.</li></ul><p>Configure the planner parameters in the following files:</p><p>/robot_navigation/config/planner_global.yaml for global planner parameters:</p><pre># Reff: http://wiki.ros.org/navfn<br>base_global_planner : navfn/NavfnROS</pre><p>/robot_navigation/config/planner_local.yaml for local planner parameters:</p><pre># Reff: http://wiki.ros.org/base_local_planner<br>base_local_planner: base_local_planner/TrajectoryPlannerROS<br><br>TrajectoryPlannerROS:<br>    min_vel_x: 0.1<br>    max_vel_x: 0.3<br>    min_vel_theta: -0.7<br>    max_vel_theta: 0.7<br>    min_in_place_vel_theta: 0.4<br>    escape_vel: -0.1<br><br>    acc_lim_theta: 1.0<br>    acc_lim_x: 1.0<br><br>    holonomic_robot: false<br><br>    xy_goal_tolerance: 0.1<br>    yaw_goal_tolerance: 0.2<br><br>    meter_scoring: true<br>    path_distance_bias: 20<br>    goal_distance_bias: 15<br>    occdist_scale:  0.01<br><br>    sim_time: 2.0</pre><p><strong>Step 3.</strong> Now that the cost maps and planners are configured, create a new file named move_base.launch in the robot_navigation package, located in the folder .../robot_navigation/launch. Insert the following code into move_base.launch:</p><pre>&lt;launch&gt;<br><br>   &lt;arg name=&quot;use_gazebo&quot; default=&quot;false&quot; /&gt;<br>   &lt;arg name=&quot;map_name&quot; default=&quot;map.yaml&quot;/&gt;<br><br>   &lt;!-- Localization --&gt;<br>   &lt;include file=&quot;$(find robot_navigation)/launch/gmapping.launch&quot;&gt;<br>      &lt;arg name=&quot;use_gazebo&quot; value=&quot;$(arg use_gazebo)&quot; /&gt;<br>      &lt;arg name=&quot;map_name&quot; default=&quot;$(arg map_name)&quot;/&gt;<br>   &lt;/include&gt;<br><br>   &lt;!-- Path planning --&gt;<br>   &lt;node pkg=&quot;move_base&quot; type=&quot;move_base&quot; respawn=&quot;false&quot; name=&quot;move_base&quot; output=&quot;screen&quot;&gt;<br>      &lt;rosparam file=&quot;$(find robot_navigation)/config/move_base.yaml&quot; command=&quot;load&quot; /&gt;<br>      &lt;rosparam file=&quot;$(find robot_navigation)/config/costmap_common.yaml&quot; command=&quot;load&quot; ns=&quot;global_costmap&quot; /&gt;<br>      &lt;rosparam file=&quot;$(find robot_navigation)/config/costmap_common.yaml&quot; command=&quot;load&quot; ns=&quot;local_costmap&quot; /&gt;<br>      &lt;rosparam file=&quot;$(find robot_navigation)/config/costmap_global.yaml&quot; command=&quot;load&quot; /&gt;<br>      &lt;rosparam file=&quot;$(find robot_navigation)/config/costmap_local.yaml&quot; command=&quot;load&quot; /&gt;<br>      &lt;rosparam file=&quot;$(find robot_navigation)/config/planner_global.yaml&quot; command=&quot;load&quot; /&gt;<br>      &lt;rosparam file=&quot;$(find robot_navigation)/config/planner_local.yaml&quot; command=&quot;load&quot; /&gt;<br>   &lt;/node&gt;<br><br>   &lt;node pkg=&quot;rviz&quot; type=&quot;rviz&quot; name=&quot;rviz&quot; args=&quot;-d $(find robot_navigation)/rviz/move_base.rviz&quot;/&gt;<br><br>&lt;/launch&gt;</pre><p><strong>Step 4. </strong>Launch the move_base node:</p><pre>roslaunch robot_navigation move_base.launch</pre><p>In this article, we covered the essential steps to set up SLAM and navigation in ROS using the gmapping and the move_base nodes. By leveraging ROS&#39;s navigation stack, you can create autonomous robots capable of localization, mapping, and navigation in dynamic environments. While additional tuning might be required for specific applications, this guide provides an introductory foundation to get you started on your ROS navigation journey.</p><h3>References</h3><ul><li>[1] <a href="https://wiki.ros.org/navigation/Tutorials/RobotSetup">https://wiki.ros.org/navigation/Tutorials/RobotSetup</a></li><li>[2] <a href="https://wiki.ros.org/map_server">https://wiki.ros.org/map_server</a></li><li>[3] <a href="http://wiki.ros.org/costmap_2d">http://wiki.ros.org/costmap_2d</a></li><li>[4] <a href="https://husarion.com/tutorials/ros-tutorials/8-slam/">https://husarion.com/tutorials/ros-tutorials/8-slam/</a></li><li>[5] <a href="https://husarion.com/tutorials/ros-tutorials/9-navigation/#cost-map">https://husarion.com/tutorials/ros-tutorials/9-navigation/#cost-map</a></li><li>[6] <a href="https://web.fs.uni-lj.si/lampa/rosin/ROS%20Summer%20School/Day%203/mapping/#">https://web.fs.uni-lj.si/lampa/rosin/ROS%20Summer%20School/Day%203/mapping/#</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec51c444a6b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running ROS Across Multiple Machines]]></title>
            <link>https://erdemuysalx.medium.com/running-ros-across-multiple-machines-1060a4f498?source=rss-e869ac665292------2</link>
            <guid isPermaLink="false">https://medium.com/p/1060a4f498</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[robot-operating-system]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Erdem Uysal]]></dc:creator>
            <pubDate>Sat, 21 Sep 2024 07:31:59 GMT</pubDate>
            <atom:updated>2024-09-21T07:31:59.553Z</atom:updated>
            <content:encoded><![CDATA[<p>The Robot Operating System (ROS) is an open-source framework widely used in robotics research and development for building, developing, and deploying robot software. In both development and deployment, there may be situations where you need to access a robot’s computational resources remotely. For example, in multi-robot systems, individual robots often need to communicate over a shared network to collaboratively solve tasks. To enable this, ROS instances running on different machines must be configured to communicate, provided that all machines are connected to the same network.</p><p>This tutorial will walk you through the process of setting up ROS to communicate over a local area network (LAN) with multiple machines. This setup is useful for creating a network of machines — whether they represent robots or workstations — working together under ROS.</p><h3>Configuring ROS for LAN Communication</h3><p>To properly configure ROS across multiple machines in a LAN, consider the following key points:</p><ul><li>Only one master is needed, so choose a single machine to run roscore.</li><li>All nodes must be set to use the same master by configuring the ROS_MASTER_URI environment variable.</li><li>Bi-directional connectivity between all machines is crucial for communication.</li><li>Each machine must advertise itself using a hostname that all other machines can resolve.</li></ul><p>For example, let’s say you’re connecting your workstation to a robot to retrieve and store sensor readings. In this setup, we’ll refer to the machines as the robot (master) and the workstation (slave). The robot and workstation will have symbolic IP addresses of 192.168.0.1 and 192.168.0.2, respectively.</p><h4>Testing Network Connectivity</h4><p>To verify that both the master and slave are connected to the same network, you can use the ping command. Open a terminal on either machine and ping the IP address of the other device to check connectivity.</p><p><strong>Robot (master):</strong></p><pre>ping 192.168.0.2</pre><p><strong>Workstation (slave):</strong></p><pre>ping 192.168.0.1</pre><h4>Testing Port Connectivity</h4><p>For full connectivity, machines must be able to communicate over all necessary ports. To ensure this, you can use the netcat (nc) command in the terminal of either machine as shown below:</p><p><strong>Robot (master):</strong></p><pre>netcat -l 1234<br>netcat 192.168.0.2</pre><p><strong>Workstation (slave):</strong></p><pre>netcat -l 1234<br>netcat 192.168.0.1</pre><h4>Configuring Name Resolution</h4><p>For machines to communicate effectively over the network, they must have addressable names, typically in the form of hostnames. Follow the steps below to configure name resolution from the terminal of each machine:</p><p><strong>Robot (master):</strong></p><pre>export ROS_IP=192.168.0.1<br>export ROS_HOSTNAME=192.168.0.1</pre><p><strong>Workstation (slave):</strong></p><pre>export ROS_IP=192.168.0.2<br>export ROS_HOSTNAME=192.168.0.2</pre><p>Alternatively, you can modify the /etc/hosts file on each machine to manually associate hostnames with their corresponding IP addresses. This file serves as a local directory that instructs each machine on how to resolve specific hostnames into IP addresses, ensuring reliable communication between machines on the network.</p><pre>sudo nano /etc/hosts<br>192.168.0.1 robot<br>192.168.0.2 workstation</pre><p>Now, we can refer to the machines by their hostnames, robot and workstation, for communication.</p><h4>Connecting Machines in LAN</h4><p>Once all configurations are in place, the machines are ready to communicate with each other over the network, enabling seamless interaction and data exchange.</p><p><strong>Robot (master):</strong></p><pre>export ROS_MASTER_URI=http://robot:11311 <br>roscore &amp;&amp; rosrun rospy_tutorials listener.py</pre><p><strong>Workstation (slave):</strong></p><pre>export ROS_MASTER_URI=http://robot:11311 <br>rosrun rospy_tutorials talker.py</pre><p>In this article, we covered how to configure ROS to run across multiple machines, enabling seamless communication over a network. I hope this guide proves useful in setting up your ROS projects and facilitates efficient multi-machine operations.</p><h3>References</h3><ul><li>[1] <a href="https://wiki.ros.org/ROS/Tutorials/MultipleMachines">https://wiki.ros.org/ROS/Tutorials/MultipleMachines</a></li><li>[2] <a href="https://wiki.ros.org/ROS/NetworkSetup#Configuring_.2Fetc.2Fhosts">https://wiki.ros.org/ROS/NetworkSetup#Configuring_.2Fetc.2Fhosts</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1060a4f498" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ROS File System]]></title>
            <link>https://erdemuysalx.medium.com/ros-file-system-bf6347b6ace3?source=rss-e869ac665292------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf6347b6ace3</guid>
            <category><![CDATA[roses]]></category>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[robot-operating-system]]></category>
            <category><![CDATA[filesystem]]></category>
            <dc:creator><![CDATA[Erdem Uysal]]></dc:creator>
            <pubDate>Thu, 02 Mar 2023 20:37:26 GMT</pubDate>
            <atom:updated>2024-09-03T13:48:39.294Z</atom:updated>
            <content:encoded><![CDATA[<p>The Robot Operating System (ROS) is a flexible and powerful platform for developing software components for robotic systems. At its core, ROS operates through a network of nodes that communicate with each other, with these nodes organized into packages. These packages follow a specific file system convention recommended by Open Robotics, the organization behind ROS. A package serves as a root directory containing all the ROS-related files necessary for a particular project. In this article, we will explore the ROS file system and what you can expect to find within these packages. Understanding the ROS file system is crucial for the efficient development and organization of robotic software.</p><h3><strong>ROS Package</strong></h3><p>At the most fundamental level, nodes are the smallest executable building blocks of ROS. These nodes are designed to carry out specific tasks, such as control, navigation, and more, and they communicate with each other through messages. Nodes that serve similar purposes are typically grouped within a ROS package. A node generally consists of source code, messages, and services.</p><h3><strong>Manifest Files</strong></h3><p>ROS packages contain important files known as manifests, such as package.xml and CMakeLists.txt, which provide metadata and essential information about the ROS node.</p><h3><strong>package.xml</strong></h3><p>This file defines the properties of a package, including its name, version numbers, authors, maintainers, and dependencies on other catkin packages. Every ROS package must contain onepackage.xml file.</p><h4><strong>CMakeLists.txt</strong></h4><p>This file serves as an input to the CMake build system, which is used for building software packages. Any CMake-compliant package contains one or more CMakeLists.txt files that describe how to compile the code and where to install it. The CMakeLists.txt file used in a Catkin project is essentially a standard CMakeLists file with a few additional constraints. Like package.xml, every ROS package must include a CMakeLists.txt file.</p><h3>Source Code and Assets</h3><p>Source code files that are part of ROS nodes, typically written in C++ or Python, should be placed in a folder named src, which is specifically designated for source code. Any script files that are not directly part of a node should be stored in a separate scripts folder.</p><p>Descriptions of request and response data structures for services provided by each ROS process are stored in the srv folder. Similarly, custom messages used by nodes should be placed in the msg folder.</p><p>Files that define how to start a ROS node are called launch files, and these are essential for initiating ROS nodes as specified. The ROS core uses these launch files to start the nodes.</p><p>The Gazebo simulation tool requires certain asset files, such as .world files and .urdf files. The .world files define the 3D simulation environment, while the .urdf files specify the robot model. These files should be placed in the worlds folder.</p><p>The overall folder structure typically looks as follows:</p><pre>└── dummy_ros_pkg<br>    ├── README.md<br>    ├── CMakeLists.txt<br>    ├── package.xml<br>    ├── launch<br>    │   └── robot.launch<br>    ├── worlds<br>    │   └── sim.world<br>    └── src<br>        ├── foo_node.cpp<br>        └── bar_node.py<br>    │<br>    └── scripts<br>            ├── foo_scipt.py<br>            └── bar_script.py<br>    │<br>    ├── msg<br>            └── dummy.msg</pre><p><strong>Continue reading this series of articles:</strong></p><ul><li><a href="https://erdemuysalx.medium.com/robotics-i-ros-in-a-nutshell-c36c27acebe7">ROS Conceptual Design Patterns</a></li></ul><h3>References</h3><p>[1] <a href="https://hub.packtpub.com/ros-architecture-and-concepts/#:~:text=Similar%20to%20an%20operating%20system,create%20a%20program%20within%20ROS">https://hub.packtpub.com/ros-architecture-and-concepts/#:~:text=Similar%20to%20an%20operating%20system,create%20a%20program%20within%20ROS</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf6347b6ace3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ROS Conceptual Design Patterns]]></title>
            <link>https://erdemuysalx.medium.com/robotics-i-ros-in-a-nutshell-c36c27acebe7?source=rss-e869ac665292------2</link>
            <guid isPermaLink="false">https://medium.com/p/c36c27acebe7</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[robots]]></category>
            <category><![CDATA[autonomous-cars]]></category>
            <category><![CDATA[robot-operating-system]]></category>
            <dc:creator><![CDATA[Erdem Uysal]]></dc:creator>
            <pubDate>Thu, 27 Jan 2022 11:43:16 GMT</pubDate>
            <atom:updated>2024-09-20T21:18:58.809Z</atom:updated>
            <content:encoded><![CDATA[<p>Throughout my career, I’ve had the opportunity to work with robotics on several occasions, and it has become a passion of mine. This enthusiasm has inspired me to start a new series of articles focused on robotics. In this series, I will primarily concentrate on robotics software and control, rather than the hardware aspects.</p><p>To kick off this series, I decided to write an introductory article on the Robot Operating System (ROS). Although there are already many resources available on ROS, I believe that providing an overview will be a fitting way to begin this journey into robotics.</p><p>The content of this article will cover the following topics:</p><ul><li>Overview of ROS</li><li>ROS Concepts and Design Patterns</li><li>ROS vs ROS 2</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qtOzaq_LiIJ33lqaw5X8g.jpeg" /><figcaption>NASA Opportunity Mars Exploration Rover. The figure is taken from <a href="https://www.jpl.nasa.gov/missions/mars-exploration-rover-opportunity-mer/">https://www.jpl.nasa.gov/missions/mars-exploration-rover-opportunity-mer/</a></figcaption></figure><h3>Overview of ROS</h3><p>What exactly is ROS? Despite what its name might suggest, ROS is not a traditional operating system. While it provides utility functions similar to those of a general-purpose operating system — such as hardware abstraction, low-level hardware control, interprocess message-passing, and package management — it is a middleware suite, not a true operating system.</p><p>As a middleware suite, ROS offers developers a collection of software frameworks, libraries, and tools designed to facilitate the development of robust robotics applications that can integrate with diverse hardware and software clusters.ROS Concepts and Design Patterns</p><h3>Understanding ROS Conceptual Design Patterns</h3><p>This subtitle introduces the reader to the conceptual design patterns within the ROS framework and provides context for the detailed explanations that follow.</p><h4>Nodes<a href="https://husarion.com/tutorials/ros-tutorials/1-ros-introduction#nodes">​</a></h4><p>In ROS, the fundamental building blocks are called nodes. Each node is responsible for specific tasks, such as controlling devices and sensors or executing computational algorithms. Ideally, each node handles a separate task, whether it’s for low-level processes like hardware control or high-level processes like decision-making algorithms. Nodes communicate with each other through topics or services, enabling a modular and distributed architecture.</p><p>There are two primary types of nodes: publishers and subscribers. As the names suggest, publishers are responsible for sending messages to topics, while subscribers receive messages from these topics by subscribing to them. This structure allows ROS to efficiently manage and distribute software across different nodes.</p><h4>Topics<a href="https://husarion.com/tutorials/ros-tutorials/1-ros-introduction#topics">​</a></h4><p>Inter-node communication in ROS is facilitated through topics. A topic is a communication channel that describes a data stream used to exchange information between different nodes. Topics are used to send streams of messages of a single type, such as sensor data or camera images. Nodes can publish messages to topics or subscribe to them to receive messages.</p><p>The number of nodes that can publish to or subscribe to a topic is generally limited by system resources, particularly RAM. Each topic has a unique name and a defined message type, ensuring that the correct data is routed to the appropriate nodes. In ROS 1, the relationship between nodes and topics is managed by the ROS master, while in ROS 2, this role is handled by the Data Distribution Service (DDS), a management middleware.</p><h4>Services<a href="https://husarion.com/tutorials/ros-tutorials/1-ros-introduction#services">​</a></h4><p>Services in ROS provide an alternative communication method between nodes, resembling the server-client architecture model, similar to a remote procedure call (RPC). In this setup, a client node sends a request, and a server node responds to that request. This establishes a bidirectional communication channel between the client and server nodes. However, unlike topics, which allow continuous data streaming, services are designed for one-time communication and are typically used to invoke specific actions.</p><h4><strong>Actions</strong></h4><p>For tasks that require time-extended operations, ROS introduces the concept of actions. Actions are designed to handle more complex tasks that go beyond the immediate request-response model of services. A ROS action is defined by three key messages: goal, result, and feedback.</p><ul><li><strong>Goal</strong>: This message represents the desired state or objective that the action aims to achieve.</li><li><strong>Result</strong>: This message provides the actual output or outcome after the action has been completed.</li><li><strong>Feedback</strong>: This message is sent periodically during the execution of the action to track and report the progress of the task.</li></ul><h4>Parameters</h4><p>In ROS, the robot’s environment and runtime variables are stored on the ROS parameter server. These parameters are organized as key-value pairs, similar to dictionary data structures. Since the parameter server is not optimized for high-performance operations, it is best suited for managing configuration parameters, such as static, and non-binary data.</p><h4>ROS Package</h4><p>A ROS package is typically developed to perform a specific task, such as control or navigation. A package can contain one or multiple nodes, and it may also include related messages and services. Each package is designed to encapsulate all the necessary components to accomplish its designated task.</p><h3>ROS vs ROS 2</h3><p>In recent years, intensive efforts have been made within the Open Source Robotics Foundation’s (OSRF) ROS community to enhance the durability and real-time sensitivity of ROS. These efforts are now bearing fruit, leading to the release of a new generation of ROS, known as ROS 2.</p><p>The primary difference between ROS 2 and its predecessor, ROS, lies in the underlying communication architecture. In ROS 2, the publisher/subscriber communication model has shifted from the TCP/UDP multicast-based ROS master to the Data Distribution Service (DDS). DDS provides powerful features that significantly strengthen ROS 2’s capabilities, making it more suitable for designing production-grade, real-time robotic systems.</p><p>Moreover, ROS 2 offers broader compatibility with operating systems, including Windows, macOS, and Real-Time Operating Systems (RTOS), expanding its usability across different platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2Aeb4GlN-Y7QKMcU1t5Bg.png" /><figcaption>ROS1 vs ROS2 Component Stack</figcaption></figure><h4>ROS Computation Graph</h4><p>Let’s consider designing a robot that follows a particular object using its onboard sensors. The system we need to build involves several components:</p><ol><li><strong>Camera Device</strong>: To capture images of the object, the robot requires a camera.</li><li><strong>Perception System</strong>: This system processes the camera images to determine the object’s location. It analyzes the visual data to extract relevant information about the object’s position.</li><li><strong>Control System</strong>: Based on the information from the perception system, the control system makes decisions about the direction in which the robot should move. It translates the object’s location into movement commands.</li><li><strong>Motors</strong>: To execute these commands, the robot uses motors that drive the wheels and allow the robot to move toward the object.</li></ol><p>Using ROS, we might construct this system as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnKf4vFYdGXq8h0VDFr-cQ.png" /><figcaption>Example Computation Graph</figcaption></figure><p>Each subsystem in our robot design can be represented as a ROS node. Therefore, we will have four distinct nodes, each handling a specific executable function:</p><ol><li><strong>Camera Driver Node</strong>: This node is responsible for fetching raw images from the camera device and publishing these images to the relevant topic.</li><li><strong>Object Detector Node</strong>: This node subscribes to the topic where raw images are published. It processes these frames to extract useful information about the object being followed, such as its location. The node then publishes this information to another topic with an appropriate message type.</li><li><strong>Target Follower Node</strong>: Based on the object location data received from the object detector node, this node calculates the commands required to steer the robot toward the object. It subscribes to the object location topic, processes the information, and publishes movement commands to a separate topic.</li><li><strong>Motor Driver Node</strong>: This low-level control node receives movement commands from the target follower node and uses them to control the motors, thereby steering the robot’s wheels.</li></ol><p>This concludes the discussion on ROS Conceptual Design Patterns, which is the first article in our robotics series. In my next posts, I plan to delve into the ROS file system and the ROS navigation stack. Stay tuned!</p><p><strong>Continue reading this series of articles:</strong></p><ul><li><a href="https://erdemuysalx.medium.com/ros-file-system-bf6347b6ace3">ROS File System</a></li></ul><h3>References</h3><ul><li>[1] <a href="http://wiki.ros.org/">http://wiki.ros.org/</a></li><li>[2] <a href="https://index.ros.org/doc/ros2/">https://index.ros.org/doc/ros2/</a></li><li>[3] <a href="http://wiki.ros.org/gazebo">http://wiki.ros.org/gazebo</a></li><li>[4] Quigley, Morgan, et al. “ROS: an open-source Robot Operating System.” <em>ICRA workshop on open source software</em>. Vol. 3. №3.2. 2009.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c36c27acebe7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux Process Isolation and Docker Containers]]></title>
            <link>https://erdemuysalx.medium.com/linux-process-isolation-and-docker-containers-1d134ebb796c?source=rss-e869ac665292------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d134ebb796c</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[containerization]]></category>
            <dc:creator><![CDATA[Erdem Uysal]]></dc:creator>
            <pubDate>Sat, 18 Sep 2021 17:41:18 GMT</pubDate>
            <atom:updated>2024-09-20T21:24:04.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekWrA5PWqYMHgc_82A5BNQ.png" /><figcaption>The figure is taken from <a href="https://www.brandnewbox.com/notes/2019/09/docker-volume-cached/whale-containers.png">https://www.brandnewbox.com/notes/2019/09/docker-volume-cached/whale-containers.png</a></figcaption></figure><p>In today’s rapidly evolving technological landscape, managing software environments and ensuring consistency across various systems are paramount. This need has led to the widespread adoption of containerization — a method that provides a lightweight, efficient solution for isolating applications and their dependencies. Containers have become a cornerstone of modern software development and deployment, offering significant advantages over traditional virtual machines.</p><p>This article delves into the fundamentals of Linux process isolation and how Docker containers leverage this concept. We will explore the key techniques that enable process isolation, such as chroot, namespaces, and cgroups, and compare them with virtual machines to understand the distinct advantages of containers. Additionally, we will cover practical aspects of Docker, from installation to managing containers, illustrating how it simplifies application deployment and enhances development workflows. By understanding these concepts, we can appreciate why containers are a preferred choice for many developers and organizations today.</p><h3><strong>Containers</strong></h3><p>Containers are an abstraction at the app layer that packages code and dependencies together. Multiple containers can run on the same machine and share the OS kernel with other containers, each running as isolated processes in user space. In the end, the container is a process that runs on the OS kernel but with a little extra isolation.</p><h3><strong>Virtual Machines</strong></h3><p>Virtual machines (VMs) are an abstraction of physical hardware turning one server into many servers, the hypervisor allows multiple VMs to run on a single machine. Each VM includes a full copy of an operating system, the application, necessary binaries, and libraries - taking up tens of GBs. VMs can also be slow to boot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VgBN-MJj_eXYjEtY.png" /><figcaption>The figure is taken from <a href="https://k21academy.com/docker-kubernetes/docker-vs-virtual-machine/">https://k21academy.com/docker-kubernetes/docker-vs-virtual-machine/</a></figcaption></figure><h4>Why Containers?</h4><ul><li>Isolation: Containers are independent of the OS behind the container.</li><li>Repeatability: Containers will run the same in another machine since everything your app needs is packaged within the container.</li><li>Security: A container can not access either processes or containers on the OS, each one has an individual process namespace.</li><li>Clean setup/remove: Set up or remove the whole app and its dependencies with only one command.</li></ul><h4>Advantages of Containers</h4><ul><li>Run in seconds instead of minutes.</li><li>Consuming fewer resources results in less disk space.</li><li>Uses less memory.</li><li>Does not need a full OS.</li><li>Provide faster deployment.</li><li>Quick testing.</li></ul><h4>How do Containers work?</h4><p>There is no such concept as the container in Linux. We can verify this by grepping the source code of Linux. But then how do these containers work? We as developers, use interfaces called container runtimes such as Docker to create what we call containers in a more user-friendly way. These container runtimes are just programs that make system calls to the OS kernel. Therefore Docker is a program that makes system calls to the Linux kernel for creating containers easily as we desire. Docker is not the main thing behind the containers, it is just an interface that presents our containers in a language that we can understand. So how the containers are implemented in the Linux kernel?</p><h4><strong>1. Isolation</strong></h4><p>Restricting what the process sees.</p><p><strong>chroot: </strong>The chroot is an operation on Unix-based operating systems that changes the current root directory, as its name refers to it (change root), for the selected running process and children of that process. It is the oldest restriction/isolation operation in Unix-based operating systems among the other utility operations. It creates an illusionistic root directory that isolates the specific command i.e. process from the other processes. This illusionistic fake root directory is often called <em>chroot jail</em>.</p><p><strong>unshare: </strong>The unshare is an operation that has been a part of the Linux kernel since 2002 that helps us create namespaces. Just like the chroot operation, the unshare operation also provides isolation between processes. There are different types of namespaces as follows:</p><ul><li>User Namespace</li><li>Process ID (PID) Namespace</li><li>Network Namespace</li><li>Mount Namespace</li><li>Interprocess Communication (IPC) Namespace</li></ul><p>Each namespace type has its unique properties that differ from others.</p><h4>2. Resource Controls</h4><p>Restricting the resources used by the process.</p><p><strong>cgroups: </strong>The cgroups, also known as change groups, is a Linux kernel operation that allows the creation of a hierarchy for a selected set of processes. The key feature of the cgroups operation that distinguishes it from the others is hierarchical management and allocation of system resources like CPU, memory, and storage for the selected process instances of the groups.</p><h3>What is Docker?</h3><ul><li>Docker is a tool for running applications in an isolated environment.</li><li>It is similar to a virtual machine.</li><li>The app runs in the same environment regardless of which machine it is since it is isolated.</li><li>The app works on any machine regardless of which OS it uses, what type of hardware is equipped with etc.</li><li>Docker is a standard for software deployment nowadays.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*pebo5ZC35HDY6osrty5F8A.png" /><figcaption>The figure is taken from <a href="https://www.researchgate.net/profile/Yahya-Al-Dhuraibi/publication/308050257/figure/fig1/AS:433709594746881@1480415833510/High-level-overview-of-Docker-architecture.png">https://www.researchgate.net/profile/Yahya-Al-Dhuraibi/publication/308050257/figure/fig1/AS:433709594746881@1480415833510/High-level-overview-of-Docker-architecture.png</a></figcaption></figure><h4>Install Docker</h4><p>Since there are a bunch of sources about this on the internet, I will not cover it in this article. I recommend you follow the official <a href="https://docs.docker.com/get-docker/">Docker page</a> for the installation.</p><h4>Docker Image</h4><p>Image is a template for creating an environment of your choice (DB, web app, or others). It is a snapshot of your application that has everything needed to run it.</p><h4>Container</h4><p>Running instances of images called containers.</p><h4>Pulling an Image</h4><pre>docker pull nginx<br>docker images  # list the images on your machine<br>docker image ls  # list the images on your machine</pre><h4>Running a Container</h4><pre>docker run nginx:latest  # run the container<br>docker run — name given_name nginx:latest  #give a name to container<br>docker container ls or docker ps  # list the running containers</pre><h4>Exposing Ports</h4><p>Since containers work in an isolated environment, most of the time, you might want to expose some ports in order to view or interact with your applications.</p><p><strong>-p</strong> flag manages the port relations of your Docker container. For example, the following command line exposes port 80 of the Docker container and maps it to localhost’s 8080 port:</p><pre>docker run -d -p 8080:80 nginx:latest</pre><p>We can also expose multiple ports for a single Docker container using more than one <strong>-p</strong> flag. See the following command line:</p><pre>docker run -d -p 3000:80 -p 8080:80 nginx:latest</pre><h4>Managing Containers</h4><pre>docker ps  # list the running container<br>docker ps -a  # list all containers<br>docker ps -q  # list the containers with only numeric ids<br>docker stop container_id  # stops the container with indicated id<br>docker start container_id  # starts the container with indicated id<br>docker rm container_id  # delete the container with indicated id</pre><h4>Volumes</h4><p>Volumes are the utility functions for Docker containers that allow sharing of data, files &amp; folders, between host and container or between containers.</p><p><strong>Volumes Between Host and Container</strong></p><pre>docker -run — name cwebsite -v /Users/user/Desktop/website:/usr/share/nginx/html:ro -d -p 8080:80 nginx:latest</pre><ul><li><strong>ro:</strong> read-only (container only allowed to read files and folders)</li><li><strong>wo:</strong> write-only (container only allowed to write files and folders)</li></ul><p>If you don&#39;t specify it will allow both writing and reading. If we create a folder or a file in the host that will appear in the container as well.</p><p><strong>Volumes Between Containers</strong></p><pre>docker run --name website-copy --volumes-from website -d -p 8081:80 nginx:latest</pre><h4>Docker Specific Files</h4><p><strong>Dockerfile: </strong>A Dockerfile is a kind of manifest that describes what should that docker image contain, and how it should be constructed.</p><ul><li>Allow us to build our images.</li><li>Series of steps that define your Docker image.</li><li>Dockerfile keywords: FROM, WORKDIR, ADD, RUN, CMD, etc.</li></ul><p>To create an image with a Dockerfile we simply run this command:</p><pre>docker build -t tag:version path_of_dockerfile</pre><p><strong>.dockerignore: </strong>You have designed an app and coded it with your favorite programming language. Now you want to deploy it using Docker containerization technology. At the same time, you pushed your project to GitHub, thus your project folder contains some .git folders that are required for the GitHub repository. These types of folders or files are unnecessary for the deployment process. That’s why we do not want to include them in our Docker image. For this sake, we simply add the names of folders and files that we do not want to include in our Docker image to the .dockerignore file.</p><h4>Build an Image for Your Python App</h4><p>Let’s say you want to have a web app written with Python programming language using the Flask framework.</p><pre>$ cd /path/to/python-docker<br>$ pip3 install Flask<br>$ pip3 freeze &gt; requirements.txt<br>$ touch app.py</pre><p>After following the steps above, you have created a Python file and you are ready to write your code. In this article, for the sake of simplicity, we are going to write a few lines of code that make a simple web request, a Hello World web app. Now you can open your project file with your favorite IDE or text editor selection like VSCode or Sublime, etc., and put the code below inside the file.</p><pre>from flask import Flask<br>app = Flask(__name__)<br><br>@app.route(&#39;/&#39;)<br>def hello_world():<br>    return &#39;Hello, Docker!&#39;</pre><p>You have tested the app by typing the run command python3 -m flask run . When you run this command it lists that the app is running on your local machine with a port number 5000. You tested and confirmed that the app is working properly as you desired by opening a new browser and navigating to <a href="http://localhost:5000.">http://localhost:5000.</a></p><p>Now you want to launch and serve this web app to users around the world. The traditional way of doing this is serving your app on a server like Amazon, Google, etc. Using this way is working, but it is not efficient because when you need updates or bug fixes you need to connect to the server for example via SSH and do what you need just like on your local machine which causes interruption on your served app.</p><p>Therefore you decided to deploy your app using much more modern technology i.e. Docker. Of course, there are more advanced ways of deploying apps using different stacks of technologies like Docker + Kubernetes + Jenkins CI/CD tools, etc. but these are not within the scope of this article and will not be covered here. Now your deployment technology is Docker and for deploying your web app using Docker, you will eventually need a Dockerfile which we discussed in earlier titles.</p><pre>FROM python:3.8-slim-buster<br>WORKDIR /app<br>COPY requirements.txt requirements.txt<br>RUN pip3 install -r requirements.txt<br>COPY . .<br>CMD [ &quot;python3&quot;, &quot;-m&quot; , &quot;flask&quot;, &quot;run&quot;, &quot;--host=0.0.0.0&quot;]</pre><p>You can now build your web app’s Docker image using the Dockerfile above and by typing the command docker build -t python-docket:v0 . Afterward, you achieve a Docker image that wraps your web app and it is ready to deploy.</p><p>Thank you for reading this article, and I will see you in the next one!</p><h3>References</h3><ul><li>[1] <a href="https://man7.org/linux/man-pages/man2/chroot.2.html">https://man7.org/linux/man-pages/man2/chroot.2.html</a></li><li>[2] <a href="https://www.ibm.com/docs/en/zos/2.2.0?topic=descriptions-chroot-change-root-directory-execution-command">https://www.ibm.com/docs/en/zos/2.2.0?topic=descriptions-chroot-change-root-directory-execution-command</a></li><li>[3] <a href="https://man7.org/linux/man-pages/man1/unshare.1.html">https://man7.org/linux/man-pages/man1/unshare.1.html</a></li><li>[4] <a href="https://www.nginx.com/blog/what-are-namespaces-cgroups-how-do-they-work/">https://www.nginx.com/blog/what-are-namespaces-cgroups-how-do-they-work/</a></li><li>[5] <a href="https://man7.org/linux/man-pages/man7/cgroups.7.html">https://man7.org/linux/man-pages/man7/cgroups.7.html</a></li><li>[6] <a href="https://www.ibm.com/docs/en/spectrum-symphony/7.3.0?topic=limits-control-groups-cgroups-limiting-resource-usage-linux">https://www.ibm.com/docs/en/spectrum-symphony/7.3.0?topic=limits-control-groups-cgroups-limiting-resource-usage-linux</a></li><li>[7] <a href="https://docs.docker.com/get-started/overview/">https://docs.docker.com/get-started/overview/</a></li><li>[8] <a href="https://docs.docker.com/engine/reference/builder/">https://docs.docker.com/engine/reference/builder/</a></li><li>[9] <a href="https://docs.docker.com/language/python/build-images/">https://docs.docker.com/language/python/build-images/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d134ebb796c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Are Real-Time Systems and Real-Time Operating Systems?]]></title>
            <link>https://erdemuysalx.medium.com/what-are-real-time-system-and-real-time-operating-system-6cf2caf7042e?source=rss-e869ac665292------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cf2caf7042e</guid>
            <category><![CDATA[latency]]></category>
            <category><![CDATA[real-time-systems]]></category>
            <category><![CDATA[throughput]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Erdem Uysal]]></dc:creator>
            <pubDate>Sun, 12 Sep 2021 12:36:43 GMT</pubDate>
            <atom:updated>2024-09-20T21:11:17.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*wc2mgaPW9wianNSrXf951Q.jpeg" /><figcaption>The figure is taken from <a href="https://www.wallpaperbetter.com/de/hd-wallpaper-fuhzp">https://www.wallpaperbetter.com/de/hd-wallpaper-fuhzp</a></figcaption></figure><p>Hello, everyone. In this article, I will talk about what is a real-time, real-time system, and real-time operating system means. This article will be relatively different from the others and I will be explaining the meanings of a few terms. I think it is a big plus for us to be developing our technical thesaurus because; even if we do not use these terms directly, someday if we are involved in a project that uses some of these terms, and if we encounter a problem when the day comes, we can easily find out which term it originated from and find the relevant solution by researching this term. In summary, when we have a wide technical term treasury, it saves us time and speed in our projects and makes it easier for us to detect errors. Now let’s move on to our main topic.</p><h3>What is a Real-Time System?</h3><p>We can summarize it as follows; the systems that produce an output in a certain time to the inputs from outside are called real-time systems. For example; unmanned aerial vehicles react in a very short time to the commands we give from the radio controller. Therefore, unmanned aerial vehicles are real-time systems, in the same way, the airbags in our cars are real systems since they produce instantaneous responses to the given input. Examples of non-real-time systems would be computers or washing machines. Because in these systems, there is no concern about producing instant output to the given input. It is an important distinction in terms of design that the system we will design is real-time or not real-time because there are differences between designing real-time systems and designing non-real-time systems.</p><p>There are two types of real-time systems;</p><ul><li><strong>Hard Real-Time:</strong> The degree of tolerance of a possible delay in the completion of the tasks to be performed by the system is very low (zero or a manufacturer-defined threshold). Tasks that cannot be completed on time are critical to the system and have devastating effects.</li><li><strong>Soft Real-Time: </strong>The completion time of the tasks to be performed by the system is not as critical as in hard real-time or the system can tolerate it during the latency period.</li></ul><p>Response time does not determine whether a system is hard or soft in real time. The criterion that determines this is what happens if the system does not respond. For example, a video game that we play at 60 FPS will draw the graphics in 1/60th of a second after our commands, but if the drawing process is delayed for any reason, this will not have a devastating effect. Of course, it will affect the efficiency of playing the game, but it is not a critical problem, it can be ignored depending on the situation. But if we are talking about a competitive esports game, the consequences of delays in the game can be seen as devastating, so we can also assume it is a hard real-time system. Unlike video games, if surgical robots or airbag systems respond later than the threshold response time set by the manufacturer, it can cause that patient or driver injury or even death, so such situations are very critical.</p><p>Below are examples of hard real-time and soft real-time.</p><ul><li><strong>Hard Real-Time:</strong> A medical robot, a surgical robot. If it cannot respond to the inputs given by the doctor within the specified time (milliseconds, microseconds), it is very inefficient, and devastating results may occur. The response time must be under a certain limit.</li><li><strong>Soft Real-Time:</strong> In a video game, when we give input from the keyboard to give the jump command to the character, the jump animation graphics drawn on the screen, based on 30 FPS, should be drawn on the screen in 1/30th of a second after the command we give, which is soft real-time.</li></ul><h3>Throughput vs Latency</h3><p>It is very important to understand these two terms. In a team discussion or product demonstration, we need to understand what is meant when the statement “We made concessions from delay to increase the transfer speed”. Now let’s try to understand these two terms.</p><p><strong>Latency:</strong> The time it takes for a package to be transported to its destination.</p><p>For example, if we consider the package as a physical product on the conveyor belt, the time taken for the package to complete its operations on the conveyor belt and exit the belt is equivalent to a delay. Or, when we click to open a new page on a website, the time it takes for the data packet of the page to be opened from the server to the client is called latency.</p><p><strong>Throughput:</strong> The number of packets sent and received per unit time.</p><p>If we continue with the conveyor belt example, the number of packages that will leave the conveyor belt at one time, let’s say one minute, after the first package reaches the destination, gives the transfer rate. Likewise, the total amount of packets that a web server sends to the client in one minute is also called the transfer rate.</p><p>Below is a visualization of the terms latency and throughput in the web server-client example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R7LoaJr0M-l0jILV.jpeg" /><figcaption>Resource: <a href="https://www.comparitech.com/net-admin/latency-vs-throughput/">https://www.comparitech.com/net-admin/latency-vs-throughput/</a></figcaption></figure><h3>OS and RTOS</h3><h3>What is an Operating System (OS)?</h3><p>An operating system is a computer program that supports the basic functions of the computer and serves other programs and applications running on the computer. Applications provide the functionality that the computer user wants or needs, while the services provided by the operating system make the execution of applications faster, simpler, and easier. For example, if you are reading a web page, you are using a web browser, which can be thought of as an application program that provides the functionality you are interested in, and that will run in an operating system-provided environment.</p><h3>What is Real-Time Operating System (RTOS)?</h3><p>Most operating systems seem to allow multiple programs to run simultaneously. This is called multitasking. In reality, each processor core can only run a single program, thread, or task thread at any one time. The component called the task scheduler, which is part of the operating system, is responsible for deciding which program to run when and quickly switches between each program, giving the user the illusion of simultaneous execution.</p><p>The type of operating system is determined by the way the task scheduler decides in what order to run the programs to be executed. For example, in a multi-user operating system, like Unix, the scheduler used ensures that each user gets a fair amount of processing time. For another example, on a desktop operating system, like Windows, the task scheduler tries to keep the computer responsive to its user.</p><p>The programmer in a real-time operating system (RTOS) is designed to provide a predictable (deterministic) execution pattern. This is especially important for embedded systems because embedded systems often have real-time requirements. Real-time requirements are requirements that specify that the embedded system must respond to a specific event within a certain threshold time. A guarantee of fulfilling real-time requirements can only be made if the behavior of the operating system’s scheduler is predictable, that is, deterministic. Some of the most widely used RTOS are LynxOS, OSE, QNX, RTLinux, VxWorks, Windows CE, eCos, and FreeRTOS.</p><p><strong>Deterministic System:</strong> In mathematics and physics, it is defined as systems that do not have randomness in the development of their future states. Therefore a deterministic system always produces the same output from a given initial condition or initial state.</p><h3>Classification of RTOS</h3><p>RTOS can be divided into three types:</p><ul><li><strong>Hard RTOS:</strong> The degree of tolerance of the delay in the completion of tasks is quite small (zero or close to zero). Tasks not done on time have a devastating effect on the system.</li><li><strong>Firm RTOS:</strong> Delays in the completion of tasks are unacceptable, but tasks that cannot be completed on time do not have a devastating effect on the system, they may cause a quality reduction.</li><li><strong>Soft RTOS:</strong> Delays in the completion of tasks may not be significant and losses in this time can be tolerated. Decreases in system quality due to delays are acceptable.</li></ul><h3>What is a Task Scheduler?</h3><p>Task Scheduler keeps status logs of each task and selects the task that is ready to be executed, then allocates the processor to that task. The task scheduler ensures the most efficient use of the CPU in multi-tasking programs. Thus, it reduces the waiting time. There are generally two types of task schedulers.</p><ul><li><strong>Non-Preemptive Scheduling:</strong> There is no priority order between tasks and all tasks are considered with the same priority. When a task begins to be executed, another task begins to be executed upon the completion of this task.</li><li><strong>Preemptive Scheduling: </strong>Always the processor checks for high-priority tasks. If a high-priority task is ready to be processed, the task on the processor is immediately suspended and control of the processor is given to the higher-priority task.</li><li><strong>Dispatcher: </strong>It is used to give control of the processor to the task selected by the task scheduler. In this way, the execution flow is changed. Anytime an RTOS is running, its execution flow passes through the task program code, and interrupts the service routine(ISR), or kernel.</li></ul><h3>References</h3><ul><li>[1] Fan, Xiaocong. Real-Time Embedded Systems: Design Principles and Engineering Practices. Newnes, 2015.</li><li>[2] Jane Liu. Real-Time Systems. Integre Technical Publishing Co., Inc., 2000.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cf2caf7042e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gerçek Zamanlı Sistem ve Gerçek Zamanlı İşletim Sistemi Nedir?]]></title>
            <link>https://medium.com/deeplab-tech/ger%C3%A7ek-zamanl%C4%B1-sistem-ve-ger%C3%A7ek-zamanl%C4%B1-i%CC%87%C5%9Fletim-sistemi-nedir-838f6a40b9a5?source=rss-e869ac665292------2</link>
            <guid isPermaLink="false">https://medium.com/p/838f6a40b9a5</guid>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[embedded-linux]]></category>
            <category><![CDATA[teknoloji]]></category>
            <category><![CDATA[real-time-systems]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <dc:creator><![CDATA[Erdem Uysal]]></dc:creator>
            <pubDate>Sun, 04 Apr 2021 06:02:46 GMT</pubDate>
            <atom:updated>2021-06-21T18:20:22.142Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psoGmcnZwpmFqHuwT6q09g.png" /></figure><p>Merhaba arkadaşlar. Bu bölümde sizlerle gerçek zaman ne demek, gerçek zamanlı sistem nedir, bunların üzerine konuşacağız. Bu yazımız diğerlerine göre nispeten daha farklı olacak ve bir kaç terimin anlamlarını açıklıyor olacağım. Teknik terim hazinemizi geliştiriyor olmanın bizler için büyük bir artı olduğunu düşünüyorum çünkü doğrudan bu terimleri kullanmıyor olsak bile bu terimleri içeren bir projede yer alıyorsak ve günü geldiğinde herhangi bir problem ile karşılaşırsak onun hangi terimden kaynaklandığını tespit edip ilgili çözüme bu terim üzerine araştırmalar yaparak rahatça ulaşabiliriz. Özetle teknik terim hazinemizin geniş olması projelerimizde bizlere hız ve zaman kazandırırken, hata tespiti yapmamızı da kolaylaştırır. Şimdi asıl konumuza geçelim.</p><h4>Gerçek Zamanlı Sistem Nedir?</h4><p>Aslında bunu şu şekilde özetleyebiliriz; herhangi bir şekilde dışarıdan bir girdi aldığı zaman bu girdiye belirli bir zaman içerisinde çıktı üreten sistemler gerçek zamanlı sistemdir. Örnek vermek gerekirse; insansız hava araçları bizim kontrol kumandasından verdiğimiz komutlara çok kısa süre içerisinde tepki verirler. Bu yüzden insansız hava araçları gerçek zamanlı sistemlerdir, aynı şekilde otomobillerimizde bulunan hava yastıkları da oluşan girdiye anlık olarak tepki üretir. Gerçek zamanlı olmayan sistemlere örnek ise, bilgisayarlar veya çamaşır yıkama makineleri olabilir. çünkü bu sistemlerde verilen girdiye anlık olarak çıktı üretme kaygısı bulunmamaktadır. Tasarımın yapacağımız sistemin gerçek zamanlı veya gerçek zamanlı olmaması tasarım açısından önemli bir ayrımdır çünkü gerçek zamanlı sistemler tasarlamak ile gerçek zamanlı olmayan sistemler tasarlamak arasında farklılıklar var.</p><p>İki tür gerçek zamanlı sistem vardır;</p><ul><li><strong><em>Hard Real-Time:</em></strong><em> Sistemin gerçekleştireceği görevlerin bitirilme zamanında olası bir gecikmenin tolerans derecesi bir hayli düşüktür (sıfır veya üretici tanımlı bir eşik değeri). Zamanında bitirilemeyen görevler sistem için kritiktir ve yıkıcı etkiler ortaya çıkarırlar.</em></li><li><strong><em>Soft Real-Time: </em></strong><em>Sistemin gerçekleştireceği görevlerin bitirilme zamanı hard real-time’daki kadar kritik değildir veya gecikme süresi boyunca sistem bunu tolere edebilir.</em></li></ul><p>Tepki verme süresi bir sistemin hard veya soft real-time olduğunu belirlemez. Bunu belirleyen kriter sistem tepki vermezse ne olacağıdır. Şöyle, örneğin 60 FPS ile oynadığımız bir video oyunu, grafikleri bizim verdiğimiz komutlardan sonra saniyenin 60&#39;da 1&#39;i içerisinde çizdiriyor olacaktır fakat herhangi bir nedenden dolayı çizim işlemi biraz daha gecikirse bu yıkıcı bir etkiye yol açmaz, elbette oyunu oynama verimini etkiler fakat çok kritik bir durum değildir, duruma göre göz ardı edilebilir. Fakat rekabetçi bir e-spor oyunundan bahsediyorsak, oyundaki gecikmelerin sonuçları yıkıcı olarak görülebilir, öyleyse bunu hard real-time olarak da varsayabiliriz .Video oyunlarının aksine ameliyat robotları veya hava yastık sistemleri üreticinin belirlediği eşik tepki süresinden daha geç bir tepki verirse, bu hastanın veya sürücünün yaralanmasına hatta ölümüne yol açabilir dolayısıyla bu tarz durumlar hayli kritiktir.</p><p>Aşağıda hard real-time ve soft real-time örnekleri görülmektedir.</p><ul><li><strong><em>Hard Real-Time:</em></strong><em> Medikal bir robot, ameliyat robotu. Doktorun verdiği girdilere belirlenen zaman içerisinde (mili saniye, mikro saniye) tepki veremiyorsa, bu çok verimsiz bir durumdur. Tepki süresinin bir sınırın altında olması çok kritiktir.</em></li><li><strong><em>Soft Real-Time:</em></strong><em> Bir video oyununda, karaktere zıpla komutunu vermek amacıyla klavyeden girdi verdiğimizde ekranda çizdirilen zıplama animasyonu grafikleri, 30 FPS baz alındığında, verdiğimiz komutun ardından saniyenin 30&#39;da 1&#39;i kadarında ekrana çizdirilmesi gerekir bu da soft real-time’dır.</em></li></ul><h4>Aktarım Hızı ve Gecikme (Throughput vs Latency)</h4><p>Bu iki terimi anlamakta çok önemli. Çünkü bir takım tartışmasında veya ürün tanıtımında “Aktarım hızını artırmak amacıyla gecikmeden taviz verdik” söyleminde bulunulduğunda ne kastedildiğini anlamamız gerekir. Şimdi gelin bu iki terimi anlamaya çalışalım.</p><ul><li><strong><em>Gecikme (Latency): </em></strong><em>Bir paketin, varış hedefine taşınana kadar ki geçen zamandır.</em></li></ul><p><em>Örneğin paketi, konveyör banttaki fiziksel bir ürün olarak düşünürsek, paketin konveyör bantta ki işlemlerinin tamamlanıp banttan çıkışına kadar geçen zaman gecikmeye denktir. Veya bir internet sitesinde yeni bir sayfa açmak için tıklama yaptığımızda, açılacak sayfanın veri paketinin sunucudan istemciye gelene kadar geçen zaman gecikme olarak adlandırılır.</em></p><ul><li><strong><em>Aktarım Hızı (Throughput):</em></strong><em> Birim zaman içerisinde gönderilen ve alınan paket miktarıdır.</em></li></ul><p><em>Yine konveyör bant örneğinden devam edecek olursak, ilk paketin hedefe ulaşmasından itibaren biri zamanda, hadi bir dakika olsun, konveyör banttan çıkış yapacak paket sayısı aktarım hızını verir. Aynı şekilde bir dakika içerisinde bir web sunucusunun istemciye gönderdiği toplam paket miktarı da aktarım hızı olarak adlandırılmaktadır.</em></p><p>Aşağıda web sunucu-istemci örneğinde gecikme ve aktarım hızı terimlerinin bir görselleştirmesi bulunmaktadır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R0LHy-VbZYbi-L33dKa0DA.jpeg" /><figcaption><a href="https://www.comparitech.com/net-admin/latency-vs-throughput/">https://www.comparitech.com/net-admin/latency-vs-throughput/</a></figcaption></figure><h4>OS ve RTOS Karşılaştırması</h4><h4>Genel Amaçlı İşletim Sistemi (OS) Nedir?</h4><p>İşletim sistemi, bilgisayarın temel işlevlerini destekleyen ve bilgisayarda çalışan diğer programlara ve uygulamalara hizmet veren bir bilgisayar programıdır. Uygulamalar, bilgisayar kullanıcısının istediği veya ihtiyaç duyduğu işlevselliği sağlarken, işletim sistemi tarafından sağlanan hizmetler, uygulamaların daha hızlı, daha basit ve daha kolay bir şekilde yürütülmesini sağlar. Örneğin, eğer bir web sayfasını okuyorsanız, bir işletim sistemi tarafından sağlanan ortamda çalışacak olan bir web tarayıcısı (ilgilendiğiniz işlevselliği sağlayan herhangi bir uygulama programı olarak düşünülebilir) kullanıyorsunuzdur.</p><h4>Gerçek Zamanlı İşletim Sistemi (Real Time Operating System -RTOS) Nedir?</h4><p>Çoğu işletim sistemi birden fazla programın aynı anda çalışmasına izin veriyor gibi görünmektedir. Buna çoklu görev dağılımı denir. Gerçekte, her bir işlemci çekirdeği, herhangi bir zamanda yalnızca tek bir program, iş veya görev parçacığını çalıştırabilir. İşletim sisteminin bir parçası olan ve görev zamanlayıcı (task scheduler) olarak adlandırılan bileşen, hangi programın ne zaman çalıştırılacağına karar vermekten sorumludur ve her program arasında hızla geçiş yaparak kullanıcıya eş zamanlı yürütme yanılsamasını sağlar.</p><p>Bir işletim sisteminin türü, görev zamanlayıcısının, yürütülecek programların hangi sırayla çalıştırılacağına karar verme şekli ile belirlenir. Örneğin, çok kullanıcılı bir işletim sisteminde, Unix gibi, kullanılan zamanlayıcı her kullanıcının işlem süresinin adil bir miktarını almasını sağlar. Başka bir örnek olarak masa üstü bir işletim sisteminde, Windows gibi, görev zamanlayıcı bilgisayarın kullanıcısına karşı duyarlı kalmasını sağlamaya çalışır.</p><p>Gerçek Zamanlı İşletim Sistemindeki (RTOS) programlayıcı, öngörülebilir (deterministik olarak da tanımlanır) bir yürütme modeli sağlamak için tasarlanmıştır. Bu durum özellikle gömülü sistemler için çok önemlidir, çünkü gömülü sistemler çoğu zaman gerçek zaman gereksinimlerine sahiptir. Gerçek zaman gereksinimleri, gömülü sistemin kesin bir eşik süresi içerisinde belirli bir olaya yanıt vermesi gerektiğini belirten bir gereksinimlerdir. Gerçek zaman gereksinimlerini yerine getirme garantisi yalnızca işletim sisteminin zamanlayıcısının davranışı tahmin edilebilirse, yani deterministik ise yapılabilir.</p><ul><li><strong><em>Deterministik Sistem:</em></strong> Matematik ve fizikte, gelecekteki durumlarının gelişmesinde rastgelelik bulunmayan sistemler olarak tanımlanır. Bu nedenle deterministik bir sistem, belirli bir başlangıç ​​koşulundan veya başlangıç ​​durumundan her zaman aynı çıktıyı üretir.</li></ul><p>En yaygın kullanılan RTOS’lardan bazıları: LynxOS, OSE, QNX, RTLinux, VxWorks, Windows CE, eCos, FreeRTOS’tir.</p><h4>RTOS’un Sınıflandırılması</h4><p>RTOS üç tipe ayrılabilir:</p><ul><li><strong><em>Hard RTOS:</em></strong> Görevlerin bitirilme zamanında meydana gelen gecikmenin tolerans derecesi oldukça küçüktür (sıfır ya da sıfıra yakın). Zamanında yapılmayan görevler sistem için yıkıcı etki oluştururlar.</li><li><strong><em>Firm RTOS: </em></strong>Görevlerin bitirilme zamanında meydana gelen gecikmeler kabul edilemez, ancak zamanında bitirilemeyen görevler sistem için yıkıcı etki de oluşturmazlar, kalite azalmasına neden olabilirler.</li><li><strong><em>Soft RTOS:</em></strong> Görevlerin bitirilme zamanında meydana gelen gecikmeler çok önemli olmayabilir ve bu süredeki kayıplar tolere edilebilir. Gecikmelerden kaynaklanan sistem kalitesindeki azalmalar kabul edilebilir.</li></ul><h4>Görev Zamanlayıcı Nedir?</h4><p><em>Görev Zamanlayıcı</em><strong><em> </em></strong>her bir görevin durum kayıtlarını tutar ve yürütülmeye hazır olan görevi seçer, daha sonra işlemeciyi bu göreve tahsis eder. Görev zamanlayıcı çok görev içeren programlarda CPU’nun en etkin şekilde kullanılmasını sağlar. Böylece bekleme zamanını azaltır. Genel olarak iki tür görev zamanlayıcı bulunur.</p><ul><li><strong><em>Önceliksiz Görev Zamanlayıcı (Non-Preemptive </em>Scheduling)<em> :</em></strong> Görevler arasında öncelik sırası yoktur ve bütün görevler aynı öncelikli olarak kabul edilir. Bir görev yürütülmeye başlandığında diğer bir görev bu görevin bitmesi ile yürütülmeye başlar.</li><li><strong><em>Öncelikli Görev Zamanlayıcı (Preemtive </em>Scheduling)<em>:</em></strong> Her zaman işlemci yüksek öncelikli görevleri kontrol eder. Eğer yüksek öncelikli bir görev işlenmek için hazır ise işlemci üzerindeki görev hemen askıya alınır ve işlemcinin kontrolü yüksek öncelikli göreve verilir.</li><li><strong><em>Dispatcher:</em></strong> Görev zamanlayıcı tarafından seçilmiş göreve işlemcinin kontrolünü vermek için kullanılır. Bu sayede yürütme akışı değiştirilmiş olur. Bir RTOS’in çalıştığı herhangi bir zamanda yürütme akışı task program code, interrupt service routine(ISR) veya kernel’den geçer.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=838f6a40b9a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deeplab-tech/ger%C3%A7ek-zamanl%C4%B1-sistem-ve-ger%C3%A7ek-zamanl%C4%B1-i%CC%87%C5%9Fletim-sistemi-nedir-838f6a40b9a5">Gerçek Zamanlı Sistem ve Gerçek Zamanlı İşletim Sistemi Nedir?</a> was originally published in <a href="https://medium.com/deeplab-tech">DeepLab.Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Music Generation with LSTM Based RNN]]></title>
            <link>https://medium.com/analytics-vidhya/music-generation-with-lstm-based-rnn-3fa967bc1f37?source=rss-e869ac665292------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fa967bc1f37</guid>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[rnn]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Erdem Uysal]]></dc:creator>
            <pubDate>Sat, 03 Apr 2021 22:02:21 GMT</pubDate>
            <atom:updated>2024-09-20T21:22:52.809Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone. In this article, I will try to explain what I know about music generation with LSTM (long short-term memory) based RNN (recursive neural networks). Let’s first examine what kind of information contains the dataset I have used in the training phase of the model.</p><h4>About the Dataset</h4><p>As we all know, music is represented by notes. I preferred to use an alternative note system in the dataset, known as the ABC notation, instead of the classical notes in the style of Do, Re, Mi, etc. In ABC notation, numbers, and special characters are used along with letter notations from A to G to represent the given notes. Each letter corresponds to classical notes such as Do, Re, and Mi in classical notes. In addition to the notes that make up the melody, other units are used as additional information; reference number, composer, origin, note length, tempo, rhythm key, ornament, etc. Each of these values ​​constitutes the features of our data set. The ABC notation is often used to represent traditional folk music. The dataset I have used is compiled from <a href="https://cobb.ece.wisc.edu/irish/Tunebook.html">Cobb’s Irish Folk Music</a> [1]. Below you will see sample music expressed with ABC notation from the dataset.</p><pre>X:1 <br>T:Alexander&#39;s <br>Z: id:dc-hornpipe-1 <br>M:C| <br>L:1/8 <br>K:D Major<br>(3ABc|dAFA DFAd|fdcd FAdf|gfge fefd|(3efe (3dcB A2 (3ABc|! dAFA DFAd|fdcd FAdf|gfge fefd|(3efe dc d2:|! AG|FAdA FAdA|GBdB GBdB|Acec Acec|dfaf gecA|! FAdA FAdA|GBdB GBdB|Aceg fefd|(3efe dc d2:|!</pre><h4>Implementation</h4><p>Here, we are facing a problem: Can our computers make sense of data that contains letters and special characters? Since we are going to multiply the features by the weight values, B x 0.23 would be an illogical operation, it seems unlikely, doesn&#39;t it? For this reason, we must bring the data into a format that the computer can understand. Just as computers represent images as matrices containing pixel values, we will assign a numerical value to each note in the data set, whether it is a letter or a special character. This operation is known as encoding in the literature.</p><p>To perform the encoding process, we first collect all the songs in a single list with the help of the code snippet below. After extracting each original character in this list and sorting it from small to large, we throw it into the vocab variable. The vocab variable contains unique characters that carry information and represent our songs. Then we define the operations that allow us to assign numerical values to these unique characters, that is, to perform the encoding process: char2id, which maps characters to numbers, and, idx2charwhich maps numbers to characters.</p><pre># Join our list of song strings into a single string containing all songs<br>songs_joined = &quot;\n\n&quot;.join(songs) <br># Find and then sort all unique characters in the joined string<br>vocab = sorted(set(songs_joined))<br>print(&quot;There are&quot;, len(vocab), &quot;unique characters in the dataset&quot;)<br><br>### Define numerical representation of text data so that can be process by computer ###<br><br># Create a mapping from character to unique index.<br># For example, to get the index of the character &quot;d&quot;, <br># we can evaluate `char2idx[&quot;d&quot;]`.  <br>char2idx = {char:id for id, char in enumerate(vocab)}<br><br># Create a mapping from indices to characters. This is<br># the inverse of char2idx and allows us to convert back<br># from unique index to the character in our vocabulary.<br>idx2char = np.array(vocab)<br><br>print(&#39;{&#39;)<br>for char,_ in zip(char2idx, range(20)):<br>  print(&#39;  {:4s}: {:3d},&#39;.format(repr(char), char2idx[char]))<br>print(&#39;  ...\n}&#39;)</pre><p>Below you can see each unique character in the dataset and their corresponding numerical value.</p><pre>{   <br>   &#39;\n&#39;:   0,<br>   &#39; &#39; :   1,<br>   &#39;!&#39; :   2,<br>   &#39;&quot;&#39; :   3,<br>   &#39;#&#39; :   4,<br>   &quot;&#39;&quot; :   5,<br>   &#39;(&#39; :   6,<br>   &#39;)&#39; :   7,<br>   &#39;,&#39; :   8,<br>   &#39;-&#39; :   9,<br>   &#39;.&#39; :  10,<br>   &#39;/&#39; :  11,<br>   &#39;0&#39; :  12,<br>   &#39;1&#39; :  13,<br>   &#39;2&#39; :  14,<br>   &#39;3&#39; :  15,<br>   &#39;4&#39; :  16,<br>   &#39;5&#39; :  17,<br>   &#39;6&#39; :  18,<br>   &#39;7&#39; :  19,<br>   ... <br>}</pre><p>Let’s combine the above-mentioned operations into a function to be more modular and organized.</p><pre>def encode_string(string):<br>  &quot;&quot;&quot; A function to convert all the song strings <br>      to a vectorized and numeric representation.<br>  Arguments:<br>  string -- List of strings<br>  Return:<br>  encodeded_string -- Encoded list of strings<br>  <br>  NOTE: the output of the `vectorize_string` function <br>  should be a np.array with `N` elements, where `N` is<br>  the number of characters in the input string<br>  &quot;&quot;&quot;<br>  <br>  encodeded_string = np.array([char2idx[char] for char in string])<br>  return encodeded_string<br><br>encodeded_songs = encode_string(songs_joined)<br><br>print (&#39;{} &lt;--- characters mapped to int ---&gt; {}&#39;.format(repr(songs_joined[:10]), encodeded_songs[:10]))<br># Check that vectorized_songs is a numpy array<br>assert isinstance(encodeded_songs, np.ndarray), &quot;returned result should be a numpy array&quot;</pre><p>Following the character encoding process according to the assignments stated before, our sample data including letters, numbers, and special characters transformed like below. In this way, after preprocessing operations performed on our dataset, we now made our dataset ready to use.</p><pre>&#39;X:1\nT:Alex&#39; &lt;---encoding---&gt; [49 22 13  0 45 22 26 67 60 79]</pre><p>Our next step is to break down the text containing the songs into sample batches that we will use during the actual training. Each input string in which we feed our model contains as many characters from the text as the number of seq_length. Also, to predict the next character, we need to define a target sequence for each input sequence to be used in the training of the model. For each input string, the corresponding target string will contain characters of the same length, except if one character has been shifted to the right.</p><p>To do this, we have to divide the text into seq_length + 1. Assuming the variable seq_lengthis 3 and our text is <em>Helsinki</em>, our input string will be <em>Hel</em> and the target string will be <em>els</em>. The function, whose definition you can see below, allows us to convert this string stream into arrays of the desired size.</p><pre>def get_batch(encodeded_songs, seq_length, batch_size):<br>  &quot;&quot;&quot; Batch definition to create training examples<br>  &quot;&quot;&quot;<br>  <br>  # The length of the vectorized songs string<br>  n = encodeded_songs.shape[0] - 1<br>  # Randomly choose the starting indices for the examples in the training batch<br>  idx = np.random.choice(n-seq_length, batch_size)<br><br>  # A list of input sequences for the training batch<br>  input_batch = [encodeded_songs[i : i+seq_length] for i in idx]<br>  # A list of output sequences for the training batch<br>  output_batch = [encodeded_songs[i+1 : i+seq_length+1] for i in idx]<br><br>  # x_batch, y_batch provide the true inputs and targets for network training<br>  x_batch = np.reshape(input_batch, [batch_size, seq_length])<br>  y_batch = np.reshape(output_batch, [batch_size, seq_length])<br>    <br>  return x_batch, y_batch<br><br>x_batch, y_batch = get_batch(encodeded_songs, seq_length=5, batch_size=1)<br><br><br>for i, (input_idx, target_idx) in enumerate(zip(np.squeeze(x_batch), np.squeeze(y_batch))):<br>    print(&quot;Step {:3d}&quot;.format(i))<br>    print(&quot;  input: {} ({:s})&quot;.format(input_idx, repr(idx2char[input_idx])))<br>    print(&quot;  expected output: {} ({:s})&quot;.format(target_idx, repr(idx2char[target_idx])))</pre><p>Sample input series on batch created for trial purposes and expected values:</p><pre>Step   0   input: 18 (&#39;6&#39;)   expected output: 0 (&#39;\n&#39;) <br>Step   1   input: 0 (&#39;\n&#39;)   expected output: 45 (&#39;T&#39;) <br>Step   2   input: 45 (&#39;T&#39;)   expected output: 22 (&#39;:&#39;) <br>Step   3   input: 22 (&#39;:&#39;)   expected output: 32 (&#39;G&#39;) <br>Step   4   input: 32 (&#39;G&#39;)   expected output: 73 (&#39;r&#39;)</pre><p>Now it’s time to design our model. We could use classical artificial neural networks (ANNs) in our model, but since the melodies we call music consist of a series of repeating notes, the classical ANNs using the feed-forward technique are somewhat dysfunctional for this problem. The notes that make up our music are not independent of each other, on the contrary, they are arranged one after the other in a way to adapt to the previous one. That is why in our model we will use RNN, which is a more advanced artificial neural network algorithm, that provides a very good solution to such sequence and repetition problems. In addition to classical neural networks, this algorithm can take the output of the previous node as input, while at the same time taking its output as an input for the nodes that are in parallel and after it. Below you can find a diagram where you can see the difference between feed-forward neural networks and RNNs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/0*xu3Kg282H1n2KKwe.png" /><figcaption>Feedforward NN vs Recurrent NN. The figure is taken from <a href="https://www.researchgate.net/figure/Feed-forward-and-recurrent-ANN-architecture_fig1_315111480">https://www.researchgate.net/figure/Feed-forward-and-recurrent-ANN-architecture_fig1_315111480</a>)</figcaption></figure><p>Although it offers a great solution for some problems, RNNs have some missing points. One of them is the ability to carry the information of array elements up to a certain past point to the next steps, in other words, their memory is very short and the algorithm starts to be difficult when it comes to using the previous elements. As a solution to this, gate cells have been developed aiming to solve exactly such problems. There are several types of door cells, for example, LSTM and GRU. We will use LSTM of these, and I avoid going into the details of this because it involves some complex mathematical operations and these are not our focus now. But for some intuition, I leave below a visualized LSTM gate cell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/0*k6TQJrYrBARnCjsr.gif" /><figcaption>Working principle of an LSTM cell. The figure is taken from h<a href="https://becominghuman.ai/long-short-term-memory-part-1-3caca9889bbc">ttps://becominghuman.ai/long-short-term-memory-part-1-3caca9889bbc</a>)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4d1ff7eea06a17c0e1154ba19ab1b74/href">https://medium.com/media/b4d1ff7eea06a17c0e1154ba19ab1b74/href</a></iframe><p>You can see the summary of our model below.</p><pre>    Model: &quot;sequential&quot;<br>    _________________________________________________________________<br><br>    Layer (type)                 Output Shape              Param #    <br><br>    =================================================================<br><br>    embedding (Embedding)        (32, None, 256)           21248      <br>    _________________________________________________________________<br><br>    lstm (LSTM)                  (32, None, 1024)          5246976    <br>    _________________________________________________________________<br><br>    dense (Dense)                (32, None, 83)            85075    <br>    <br>    =================================================================<br><br>    Total params: 5,353,299 Trainable params: 5,353,299 Non-trainable<br><br>    params: 0<br>    _________________________________________________________________<br></pre><p>When the training is over, the model presents us with the pieces of music produced by the based RNN model as a string. We copy this sequence and paste it into a notebook that we will open on the computer and save it as .abc extension. After this process, you can listen to the music track. Remember, the model may not produce a successful result every time, it may be necessary to produce several times to produce a melody with a nice sound. Have a nice try.</p><p>Unique music pieces that emerged at the end of the training:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Fusers%252F315972119%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Ferdem-uysal-578262330&amp;image=https%3A%2F%2Fi1.sndcdn.com%2Favatars-000320697837-bkgam5-t500x500.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1563f32375db651d6508feb1002e668/href">https://medium.com/media/d1563f32375db651d6508feb1002e668/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F824756467%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Ferdem-uysal-578262330%2Firish-folk-by-lstm-based-rnn-2&amp;image=https%3A%2F%2Fi1.sndcdn.com%2Fartworks-X953pbbwBuGpnK9j-lzSAsQ-t500x500.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/5297f102a3590fc181ee76825cb11f6b/href">https://medium.com/media/5297f102a3590fc181ee76825cb11f6b/href</a></iframe><p>I did not want to share all the codes here because the article will be too long. However, I shared the dataset and the notebook on [GitHub](https://github.com/erdemuysalx/ComposerAI) for everyone to experiment. See you in the next article.</p><h3>Resources</h3><p>[1] <a href="https://cobb.ece.wisc.edu/irish/Tunebook.html">https://cobb.ece.wisc.edu/irish/Tunebook.html</a></p><p>[2] <a href="https://machinelearningmastery.com/how-to-prepare-categorical-data-for-deep-learning-in-python/">https://machinelearningmastery.com/how-to-prepare-categorical-data-for-deep-learning-in-python/</a></p><p>[3] <a href="http://introtodeeplearning.com/">http://introtodeeplearning.com/</a></p><p>[4] <a href="https://stanford.edu/~shervine/l/tr/teaching/cs-230/cheatsheet-recurrent-neural-networks">https://stanford.edu/~shervine/l/tr/teaching/cs-230/cheatsheet-recurrent-neural-networks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fa967bc1f37" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/music-generation-with-lstm-based-rnn-3fa967bc1f37">Music Generation with LSTM Based RNN</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LSTM Tabanlı RNN ile Müzik Üretimi]]></title>
            <link>https://medium.com/deep-learning-turkiye/lstm-tabanl%C4%B1-rnn-ile-m%C3%BCzik-%C3%BCretimi-231b1295826a?source=rss-e869ac665292------2</link>
            <guid isPermaLink="false">https://medium.com/p/231b1295826a</guid>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Erdem Uysal]]></dc:creator>
            <pubDate>Sat, 30 May 2020 10:27:44 GMT</pubDate>
            <atom:updated>2021-04-03T22:12:50.464Z</atom:updated>
            <content:encoded><![CDATA[<p>Herkese selamlar. Bu yazımda sizlere LSTM (Long Short Term Memory) tabanlı Yinelemeli Sinir Ağları (RNN) ile müzik üretimi üzerine bildiklerimi aktarmaya çalışacağım. Gelin öncelikle modeli geliştirmekte kullandığımız veri setinin temelde ne tür bilgiler içerdiğini irdeleyelim.</p><h3>Veri Seti Üzerine</h3><p>Hepimizin de bildiği üzere müzikler notalar ile temsil edilmektedir. Ben veri seti olarak Do, Re, Mi tarzında klasik notaların yerine, ABC gösterimi olarak bilinen alternatif bir nota sistemini kullanmayı tercih ettim. ABC gösteriminde, verilen notaları temsil etmek için A’dan G’ye kadar olan harf gösterimleri ile beraber sayılar ve özel karakterler kullanılmaktadır. Her bir harf klasik notalarda bulunan Do, Re, Mi gibi klasik notalara karşılık gelmektedir. Melodiyi oluşturan notaların yanında ek bilgiler olarak diğer öğelerde kullanılmaktadır; referans numarası, besteci, köken, nota uzunluğu, tempo, ritim anahtar, süsleme vb. Bu değerlerin her biri veri setimizin özniteliklerini (features) oluşturmaktadır. ABC gösterimi genelde geleneksel halk müziklerini temsil etmek için kullanılmaktadır. Benim kullandığım veri seti de <a href="https://cobb.ece.wisc.edu/irish/Tunebook.html">İrlanda </a><a href="https://cobb.ece.wisc.edu/irish/Tunebook.html">Cobb</a> <a href="https://cobb.ece.wisc.edu/irish/Tunebook.html">halk müziklerinde</a>n¹ derlenmiş bir veri setidir. Aşağıda ABC gösterimi ile ifade edilen bir müzik örneği görmektesiniz.</p><pre>X:1 <br>T:Alexander&#39;s <br>Z: id:dc-hornpipe-1 <br>M:C| <br>L:1/8 <br>K:D Major<br>(3ABc|dAFA DFAd|fdcd FAdf|gfge fefd|(3efe (3dcB A2 (3ABc|! dAFA DFAd|fdcd FAdf|gfge fefd|(3efe dc d2:|! AG|FAdA FAdA|GBdB GBdB|Acec Acec|dfaf gecA|! FAdA FAdA|GBdB GBdB|Aceg fefd|(3efe dc d2:|!</pre><p>Burada bir problem ile karşılaşmaktayız: bilgisayarlarımız harfleri ve özel karakterler içeren bir veriden anlam çıkarabilir mi? Öznitelikleri ağırlık (weights) değerleri ile çarpacağımızdan dolayı, B x 0.23 mantıksız bir işlem olacaktır, bu pek de mümkün görünmüyor öyle değil mi? İşte bu sebeple verileri bilgisayarın anlayabileceği bir formata getirmeliyiz. Tıpkı bilgisayarların resimleri piksel değerlerini içeren matrisler olarak temsil etmesi gibi,veri seti içerisinde bulunan her notaya, bir harfe veya bu özel karakter de olabilir, bir sayısal değer ataması gerçekleştireceğiz. Bu operasyona literatürde kodlama² (encoding) adı verilmektedir.</p><p>Kodlama işlemini gerçekleştirebilmek için öncelikle aşağıdaki kod parçası yardımıyla bütün şarkıları tek bir liste içerisinde topluyoruz. Bu liste içerisinde ki her bir özgün karakteri ayıklayıp küçükten büyüğe doğru sıraladıktan sonra vocab değişkenine atıyoruz. vocab değişkeni bizim şarkılarımızı temsil eden ve bilgi taşıyan eşsiz karakterleri içermektedir. Daha sonra bu eşsiz karakterlere nümerik değerleri atama yani kodlama işlemini gerçekleştirmemize izin veren: karakterleri sayılarla eşleyen char2id ve diğeri de sayıları karakterlerle eşleyen idx2char işlemlerini tanımlıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac5c42be305be032a6c8b1e062d8be9e/href">https://medium.com/media/ac5c42be305be032a6c8b1e062d8be9e/href</a></iframe><p>Aşağıda, veriler içerisinde bulunan her bir karakteri ve o karaktere karşılık gelen nümerik değeri görmektesiniz.</p><pre>{   <br>   &#39;\n&#39;:   0,<br>   &#39; &#39; :   1,<br>   &#39;!&#39; :   2,<br>   &#39;&quot;&#39; :   3,<br>   &#39;#&#39; :   4,<br>   &quot;&#39;&quot; :   5,<br>   &#39;(&#39; :   6,<br>   &#39;)&#39; :   7,<br>   &#39;,&#39; :   8,<br>   &#39;-&#39; :   9,<br>   &#39;.&#39; :  10,<br>   &#39;/&#39; :  11,<br>   &#39;0&#39; :  12,<br>   &#39;1&#39; :  13,<br>   &#39;2&#39; :  14,<br>   &#39;3&#39; :  15,<br>   &#39;4&#39; :  16,<br>   &#39;5&#39; :  17,<br>   &#39;6&#39; :  18,<br>   &#39;7&#39; :  19,<br>   ... <br>}</pre><p>Yukarıda bahsi geçen işlemleri daha düzenli olmaları açısında bir fonksiyon içerisinde bir araya getirelim.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41bbff3ddd7e95c0dbd50ebec81c8d0c/href">https://medium.com/media/41bbff3ddd7e95c0dbd50ebec81c8d0c/href</a></iframe><p>Daha önce belirtilen atamalara göre karakter kodlama işlemi sonrasında harfler, sayılar ve özel karakterler içeren örnek verimiz aşağıda hale geliyor.</p><pre>&#39;X:1\nT:Alex&#39; &lt;---kodlama işlemi---&gt; [49 22 13  0 45 22 26 67 60 79]</pre><p>Bu şekilde bir miktar veri ön işleme yaptıktan sonra artık veri setimizi kullanılabilir hale getirmiş oluyoruz.</p><p>Bir sonraki adımımız, şarkıları içeren metini asıl eğitim sırasında kullanacağımız örnek dizilere (batch) ayırmaktır. RNN’mizi beslediğimiz her girdi dizisi, metinden seq_length sayısı kadar karakter içermektedir. Ayrıca, bir sonraki karakteri tahmin etmek için RNN’nin eğitiminde kullanılmak üzere her bir giriş dizisi için ayrıca bir hedef dizi tanımlamamız gerekmektedir. Her giriş dizisi için, karşılık gelen hedef dizisi, bir karakter sağa kaydırılmış olması durumu dışında aynı uzunlukta karakter içerecektir.</p><p>Bunu yapmak için metni seq_length + 1 sayısınca parçalara bölmeliyiz. seq_length değişkeninin 3 ve metnimizin “Ankara” olduğunu varsayarsak, girdi dizimiz “Ank” ve hedef dizi “nka” olacaktır.</p><p>Aşağıda tanımını görmekte olduğunuz fonksiyon, bu karakter dizisi akışını istenen boyuttaki dizilere dönüştürmemizi sağlamaktadır.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a11af421d5ced5ebcf7d3dc1eb0c97b5/href">https://medium.com/media/a11af421d5ced5ebcf7d3dc1eb0c97b5/href</a></iframe><p>Deneme amaçlı oluşturulan batch üzerinden örnek girdi dizisi ve ardından beklenen değerler;</p><pre>Step   0   input: 18 (&#39;6&#39;)   expected output: 0 (&#39;\n&#39;) <br>Step   1   input: 0 (&#39;\n&#39;)   expected output: 45 (&#39;T&#39;) <br>Step   2   input: 45 (&#39;T&#39;)   expected output: 22 (&#39;:&#39;) <br>Step   3   input: 22 (&#39;:&#39;)   expected output: 32 (&#39;G&#39;) <br>Step   4   input: 32 (&#39;G&#39;)   expected output: 73 (&#39;r&#39;)</pre><p>Şimdi sıra modelimizi tasarlamakta. Modelimizde klasik Yapay Sinir Ağlarını kullanabilirdik, fakat müzik olarak adlandırdığımız melodiler, birbirini yineleyen bir dizi notalardan oluştuğu için, ileri besleme (feed-forward) tekniğini kullanan klasik Yapay Sinir Ağları bu problem için biraz işlevsiz kalıyor. Çünkü bizim müziği oluşturan notalar birbirinden bağımsız değil, tam aksine bir öncekine uyum sağlayacak şekilde birbiri ardına diziliyorlar. İşte bu yüzden modelimizde bu tarz dizi ve yineleme problemlerine çok güzel bir çözüm sağlayan ve daha gelişmiş bir yapay sinir ağı algoritması olan RNN yani Yinelemeli Sinir Ağlarını kullanacağız. Bu algoritma klasik sinir ağlarına ek olarak, girdi olarak bir önceki düğümün çıktısını alırken aynı zamanda paralelinde olan ve kendinden sonra gelen düğümlerinde çıktısını girdi olarak alabilmektedir. Aşağıda ileri beslemeli sinir ağları ile yinelemeli sinir ağlarının (RNN) farkını görebileceğiniz bir diyagramı bulabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*edoo-1OI4uAIhi5wzD7u4A.png" /><figcaption>Feedforward NN vs Recurrent NN (resim kaynağı: <a href="https://www.researchgate.net/figure/Feed-forward-and-recurrent-ANN-architecture_fig1_315111480">https://www.researchgate.net/figure/Feed-forward-and-recurrent-ANN-architecture_fig1_315111480</a>)</figcaption></figure><p>Her ne kadar bazı problemler için müthiş bir çözüm sunuyor olsada, RNN’lerinde bazı eksik noktaları var. Bunlardan bir tanesi, belli bir geçmiş noktaya kadar olan dizi elemanlarının bilgilerini sonra ki adımlara taşıyabiliyor olmaladır, bir diğer deyişle hafızaları oldukça kısa ve iş çok önceki elemanları kullanmaya geldiğinde algoritma zorlanmaya başlıyor. Buna çözüm olarak tam da bu tarz sorunları çözmeyi hedefleyen kapı hücreleri (gate cells) geliştirilmiştir. Bir kaç çeşit kapı hücresi tipi bulunmaktadır, örneğin LSTM (Long Short Term Memory) ve GRU. Biz bunlardan LSTM’i kullanacağız ve bunun detaylarına girmekten kaçınıyorum çünkü bir takım karmaşık matematiksel işlemler içeriyor ve şimdiki odak noktamız bunlar değil. Ama bir miktar önsezi olması açısından görselleştirilmiş bir LSTM kapı hücresini aşağıya bırakıyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*cmv5EOAd6iWMzWvHrZbl-w.gif" /><figcaption>LSTM Çalışma Prensibi (gif kaynağı: <a href="https://becominghuman.ai/long-short-term-memory-part-1-3caca9889bbc">https://becominghuman.ai/long-short-term-memory-part-1-3caca9889bbc</a>)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4d1ff7eea06a17c0e1154ba19ab1b74/href">https://medium.com/media/b4d1ff7eea06a17c0e1154ba19ab1b74/href</a></iframe><p>Modelimizin özetinin çıktısını aşağıda görmektesiniz.</p><pre>Model: &quot;sequential&quot; _________________________________________________________________ Layer (type)                 Output Shape              Param #    ================================================================= embedding (Embedding)        (32, None, 256)           21248      _________________________________________________________________ lstm (LSTM)                  (32, None, 1024)          5246976    _________________________________________________________________ dense (Dense)                (32, None, 83)            85075      ================================================================= Total params: 5,353,299 Trainable params: 5,353,299 Non-trainable params: 0 _________________________________________________________________</pre><p>Eğitim sona erdiğinde model bize kendi üretmiş olduğu müzik parçasını bir string dizisi olarak sunmaktadır. Bu diziyi kopyalayıp bilgisayarda açacağımız bir not defterine yapıştırıyor ve .abc uzantılı olarak kaydediyoruz. Bu işlemden sonra müzik parçasını dinleyebilirsiniz. Unutmayın, model her seferinde başarılı bir sonuç üretemeyebilir, hoş tınısı olan bir melodi için bir kaç kez üretim yapmak gerekebilir. İyi denemeler.</p><p>Eğitim sonunda ortaya çıkan eşsiz müzik parçaları:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F824756473%26show_artwork%3Dtrue%26in%3Derdem-uysal-578262330%252Fsets%252Firish-folk-music-by-lstm-based-rnn&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Ferdem-uysal-578262330%2Fir-sh-folk-by-lstm-based-rnn%3Fin%3Derdem-uysal-578262330%2Fsets%2Firish-folk-music-by-lstm-based-rnn&amp;image=https%3A%2F%2Fi1.sndcdn.com%2Fartworks-X953pbbwBuGpnK9j-lzSAsQ-t500x500.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/510a372caee6314ed65894ffa09498e8/href">https://medium.com/media/510a372caee6314ed65894ffa09498e8/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fw.soundcloud.com%2Fplayer%2F%3Furl%3Dhttps%253A%252F%252Fapi.soundcloud.com%252Ftracks%252F824756467%26show_artwork%3Dtrue&amp;display_name=SoundCloud&amp;url=https%3A%2F%2Fsoundcloud.com%2Ferdem-uysal-578262330%2Firish-folk-by-lstm-based-rnn-2&amp;image=https%3A%2F%2Fi1.sndcdn.com%2Fartworks-X953pbbwBuGpnK9j-lzSAsQ-t500x500.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=soundcloud" width="800" height="166" frameborder="0" scrolling="no"><a href="https://medium.com/media/5297f102a3590fc181ee76825cb11f6b/href">https://medium.com/media/5297f102a3590fc181ee76825cb11f6b/href</a></iframe><p>Yazı çok uzayacağından dolayı kodların tamamını burada paylaşmak istemedim. Fakat herkesin deneyimleyebilmesi için veri seti ve noteboouku GitHub üzerinde paylaştım, aşağıdan ulaşabilirsiniz. Bir sonraki yazıda görüşmek üzere.</p><p><a href="https://github.com/erd3muysal/Music_Generation_with_LSTM_Based_RNN">erd3muysal/Music_Generation_with_LSTM_Based_RNN</a></p><h4>Kaynakça</h4><p>[1] <a href="https://cobb.ece.wisc.edu/irish/Tunebook.html">https://cobb.ece.wisc.edu/irish/Tunebook.html</a></p><p>[2] <a href="https://machinelearningmastery.com/how-to-prepare-categorical-data-for-deep-learning-in-python/">https://machinelearningmastery.com/how-to-prepare-categorical-data-for-deep-learning-in-python/</a></p><p>[3] <a href="http://introtodeeplearning.com/">http://introtodeeplearning.com/</a></p><p>[4] <a href="https://stanford.edu/~shervine/l/tr/teaching/cs-230/cheatsheet-recurrent-neural-networks">https://stanford.edu/~shervine/l/tr/teaching/cs-230/cheatsheet-recurrent-neural-networks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=231b1295826a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/deep-learning-turkiye/lstm-tabanl%C4%B1-rnn-ile-m%C3%BCzik-%C3%BCretimi-231b1295826a">LSTM Tabanlı RNN ile Müzik Üretimi</a> was originally published in <a href="https://medium.com/deep-learning-turkiye">Deep Learning Türkiye</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning: Key Terminology]]></title>
            <link>https://erdemuysalx.medium.com/machine-learning-key-terminology-b03ec15329e3?source=rss-e869ac665292------2</link>
            <guid isPermaLink="false">https://medium.com/p/b03ec15329e3</guid>
            <category><![CDATA[keywords]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Erdem Uysal]]></dc:creator>
            <pubDate>Thu, 21 May 2020 01:09:31 GMT</pubDate>
            <atom:updated>2024-09-20T21:24:57.409Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning Key Terminology</h3><p>The machine learning domain is very fascinating and it is becoming a very powerful and useful technology in today’s world. Even if you are not directly working on machine learning, somehow you can touch some parts of machine learning in any project. Since machine learning is a very wide open space, it is not possible to learn all of the keywords and the theory behind it for those who do not have expertise area on ML. This is why I am writing this article, to make those people understand or simply give them an insight into simple concepts in machine learning. I explained the general aspects of AI, Machine Learning, and Deep Learning in my previous article, <a href="https://medium.com/@erdemuysal13/the-rise-of-ai-what-is-ai-d3f796a1c153">Introduction to AI, ML, and DL</a>. So this will be involved with only Machine Learning. Let’s begin!</p><h3>Key Terminology</h3><p><strong>Supervised Learning:</strong> Supervised learning is where you have features and corresponding labels and you use an algorithm to learn the parameters for mapping function from the features to the labels.</p><p><strong>Unsupervised Learning: </strong>Unsupervised learning is where you have features but not corresponding labels.</p><p><strong>Semi-Supervised Learning: </strong>Semi-supervised learning is where you have features with corresponding labels and without labels. Generally, these kinds of models have more unlabeled examples than labeled ones.</p><p><strong>Regression: </strong>A regression model predicts continuous, or numerical values. The numerical value could be the price of a house, the temperature of the weather, etc. Regression models can be grouped under supervised learning. Some of the regression algorithms are Linear and Polynomial Regression, Decision Trees, and Random Forest.</p><p><strong>Classification: </strong>A classification model predicts discrete, or categorical values. The categorical value could be dog or cat, disease or not disease, etc. Classification models can be grouped under supervised learning. Some of the classification algorithms are KNN (K-Nearest Neighbour), Trees, SVM and Logistic Regression.</p><p><strong>Clustering: </strong>A clustering model discovers the inherent groupings in continuous data according to similar features. An example could be the grouping of customers by purchasing behavior. Clustering models can be grouped under unsupervised learning. Some of the Clustering algorithms are K-Means and PCA.</p><p><strong>Association:</strong> An association model discovers rules that describe large partitions of categorical data. An example could be: people that who buy suits also tend to buy ties. Hidden Markov Model and FP-Growth. Association models can be grouped under unsupervised learning.</p><p><strong>Models:</strong> A model defines the mapping relationship between features and labels. The model uses the parameters to make a prediction.</p><p><strong>Labels</strong>: A label is the resultant value or category variable we are predicting (mostly denoted as ‘y’) as a result of the machine learning model. The label could be the object shown in an image, the future temperature value of weather, or the next word in a text or music lyrics.</p><p><strong>Features</strong>: A feature is an input variable (mostly denoted as ‘x’) that we use for feeding the machine learning model. The features could be the pixels of an image, past temperature and humidity values of weather, or words in a text or music lyrics.</p><p><strong>Examples</strong>: An example is the set of features and its corresponding label. An example could be the pixels of an image(features) and the object (label) inside this image.</p><p><strong>Parameters:</strong> Parameters are the weights and biases that we are trying to calculate and set their most appropriate values to make a good prediction at the end of the learning process.</p><p><strong>Hyper-Parameters:</strong> Hyper-parameters are the parameters that you are tuning by hand to make the model more predictive. Some of them are learning rate, epoch, batch size, and so on.</p><p><strong>Accuracy: </strong>Accuracy is the one of model metrics that tell us how good our model is at making predictions.</p><h3><strong>References</strong></h3><ul><li>[1] <a href="https://machinelearningmastery.com/classification-versus-regression-in-machine-learning/">https://machinelearningmastery.com/classification-versus-regression-in-machine-learning/</a></li><li>[2] <a href="https://developers.google.com/machine-learning/crash-course">https://developers.google.com/machine-learning/crash-course</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b03ec15329e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>