<?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 Stephane K. on Medium]]></title>
        <description><![CDATA[Stories by Stephane K. on Medium]]></description>
        <link>https://medium.com/@stephanekp?source=rss-cbd975d1d26a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FCgbeQsWRdqlrFP5.jpg</url>
            <title>Stories by Stephane K. on Medium</title>
            <link>https://medium.com/@stephanekp?source=rss-cbd975d1d26a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:06:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stephanekp/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[LabVIEW Dashboards: Why you should not use LabVIEW Graphs as Dashboards.]]></title>
            <link>https://stephanekp.medium.com/labview-dashboards-why-you-should-not-use-labview-graphs-as-dashboards-818fd33092f?source=rss-cbd975d1d26a------2</link>
            <guid isPermaLink="false">https://medium.com/p/818fd33092f</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[labview]]></category>
            <category><![CDATA[national-instruments]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[arduino]]></category>
            <dc:creator><![CDATA[Stephane K.]]></dc:creator>
            <pubDate>Mon, 11 Jul 2022 08:36:51 GMT</pubDate>
            <atom:updated>2022-07-11T08:36:51.068Z</atom:updated>
            <content:encoded><![CDATA[<p>A case for moving away from LabVIEW Graphs to using dedicated dashboards engines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*JWf3oubRc8J8hlOrK2bdkg.png" /><figcaption>Banner</figcaption></figure><h3>Background</h3><p>A couple of years ago, I was building this control and monitoring system using LabVIEW. And after hours of tweaking the graph, and fixing the functionality powering it up, I got this result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4RuiJBP8YUdESFWQjbwNA.png" /></figure><p>And I was pretty happy with myself. The application would run for hours unmanned, switching between different states. It would log measurements and events into files.</p><p>Fast forward 4 years… I had a similar project in which we were stress-testing an embedded Processing Unit. The tests also had to run for hours, unmanned and this is what I came up with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1TAGxEN-4mE30TTvMZru5g.png" /><figcaption>Embedded CPU Stress Test: Client Dashboard</figcaption></figure><h3>My Case</h3><blockquote>I’m going to make a case for not using LabVIEW to draw dashboards in situations where:<br> (i) the test that generates the data takes more than a couple of minutes, <br>(ii) the data on the LabVIEW graphs is anyway stored somewhere else (no matter where really), <br>(iii) one of the end goal of the project involves diving deep into that data to gain insight from it. I.e. the client would ask questions, and write queries to answer them).</blockquote><blockquote>It’s my case that there are more appropriate tools for these scenarios. And I’m going to propose <a href="https://grafana.com/">Grafana </a>as an alternative. In their own words: “<strong>(Grafana is)… Operational dashboards for your data here, there, or anywhere</strong>”. It is a web application, it is open source, it has a ridiculously low barrier to entry and small learning curve for a user. It takes only a couple of minutes to setup.</blockquote><blockquote>The second portion of this article “<strong>Setup</strong>” will walk you through setting all of this up. And believe me, you only need to add an extra 5 minutes to have all of this in place.</blockquote><p>So the original system I built didn’t lack in functionality. It was perfectly suited for its intended purpose. However, the second approach offered more value to the customer. It would have been a superior deliverable to the client:</p><ol><li><strong>Billing Hours</strong></li></ol><p>In the former project, it took a couple of back and forth between me and the client so a requirement for the information displayed on the interface would become fully articulated. The client wasn’t sure and later in the project that requirement changed a couple of times.</p><p>On the other side, these LabVIEW graphs aren’t the most flexible. Tweaking and making them look nice is time consuming.</p><p>What I’m proposing is a simple tool that empowers the client to draw and update dashboards at will. The client can even own these dashboards, thus, lessening your maintenance needs. It <em>enables </em>the client in his end goal and makes life easier for the developer.</p><blockquote><strong>It’s a win-win for everybody</strong></blockquote><p><strong>2. User Experience</strong></p><p>Let’s keep it real for a moment, it can be difficult to easily and consistently build user experience in LabVIEW. Web development has set a high bar for the level of UX that users are accustomed to. In the best cases, LabVIEW UIs seem out-of-place-in-time. In the other cases, they seem very much rustic. This can convey the impression to most users that they shouldn’t even be looking at it. It suggests that the UI is for the technically inclined professional. That might not be the case… Don’t get me wrong, I love LabVIEW but it’s not about me but the client.</p><p>On top of a better end user experience, the developer user experience is not left as an after-thought. Working and developing with a tool like Grafana is pretty awesome. As you will see in a couple of minutes…</p><blockquote><strong>Higher UX and UI quality for the client, Better developer experience for you.</strong></blockquote><p><strong>3. Gaining Insight from the Data.</strong></p><p>Usually, as was in both projects, the articulated requirements consists of:</p><ul><li>(i) a dashboard / graph to provide instant information about the system and</li><li>(ii) storage requirements to allow offline analysis.</li></ul><p>Practically, if the data is stored, say, in a CSV File, it means that the client will have to use a second tool like Excel. This tool would allow him to load the data, ask questions, dive deep into, and gain insight from the data.</p><p>A tool like Grafana, provides the client with the same autonomy as with a tool like Excel. Moreover, it also allows the client to perform his analysis in real-time.</p><blockquote><strong>The client has as much autonomy as with a Tool like Excel. The system empowers the user to ask questions, build as many dashboards as needed to answer them. He is enabled to perform his analysis in real-time.</strong></blockquote><p><strong>4. Loose Coupling, High Cohesion</strong></p><p>Adoption of a tool like Grafana forces this omnipresent principle in engineering work:</p><blockquote><strong>Loose Coupling, High Cohesion: Your reporting system and your tests system are separate and each obey the Single Responsibility Principle. That’s good engineering right there.</strong></blockquote><blockquote>Development, Maintenance activities greatly benefit from a system built with these principles in mind.</blockquote><p>A by-product of this architecture is that the client can do interact with his system from any “web-enabled” device. Many users can concurrently look in real time at the system from various locations. It makes for a more “observable” system.</p><p>Consider this scenario: <em>On my way home, I can open my phone and look at the current state in real-time. I can send an email to a supervisor with a link to the dashboard to signal possible issues. He is able to open the link on his laptop. All of this happens, while the system is running in some potentially remote location. It continues to operate unaffected and unburdened by all this traffic.</em></p><p>You don’t need LabVIEW licenses for this, and Grafana is open-source. It also comes with a lot of functionality out of the box:</p><ul><li>Authentication / Authorization.</li><li>Grafana will typically be configured with Read-Only access to your data.</li><li>Can pull data from LabVIEW and effortlessly <strong>combine </strong>it with other sources of data. <strong><em>This one is a huge plus from the feedback received from the client.</em></strong></li></ul><h3>The Setup and The “How does this Work?”</h3><p>Okay, so hopefully I have done a not so terrible job at picking your interest. So, let’s see how this would fit into your normal LabVIEW workflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*khtznl977kOULCV_yJoVsQ.png" /><figcaption>Proposed Setup</figcaption></figure><p>These are the 3 steps that we will go through:</p><blockquote>- Develop the <strong>LabVIEW Application</strong></blockquote><blockquote>- Enable the LabVIEW <strong>Web Server</strong></blockquote><blockquote>- Setup <strong>Grafana</strong></blockquote><p>Let’s dive into it:</p><h4>LabVIEW Application</h4><p>So you write your application as you would normally without consideration for all this Grafana stuff. Let’s also say you are saving test data in a CSV file on disk (<strong><em>data.csv</em></strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*cXXIymkzr0Z7Rf20SXg4nw.png" /><figcaption>Sample CSV file</figcaption></figure><h4>Web Server</h4><p>So, Grafana can load data from <a href="https://grafana.com/docs/grafana/latest/datasources/">various sources</a>. This includes SQL databases, JSON files, CSV files… In the case of a CSV file as a data source, we need a server that will “serve” the CSV file or data.</p><p>In essence, <em>we need a server so a HTTP client (like your browser or Grafana) can make a HTTP request to this web server to get the CSV data.</em></p><p>We could setup a web server (with Apache, NodeJS or Python,…) for this very purpose, but we don’t need to. The LabVIEW environment already comes with a production-grade server that we can use. See <a href="https://www.ni.com/docs/en-US/bundle/labview/page/lvconcepts/webservices.html">here for more information and restrictions</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*5Fhi9fcLiO3ClV3F1zpOKA.png" /><figcaption>Project Setup</figcaption></figure><blockquote><strong>Setup a LabVIEW Web Service:</strong></blockquote><blockquote><strong>- Create the web service</strong>: Right Click on <strong><em>My Computer &gt; New &gt; Web Service</em></strong>, give it the name “grafana-test-server”. Note that this name will be used in the URL of the file / data.</blockquote><blockquote><strong>- Setup web server content</strong>: Right Click on the web service <strong><em>“grafana-test-server” &gt; Add Public Content Folder</em></strong> and select the folder containing “<strong><em>data.csv</em></strong>”.</blockquote><blockquote><strong>- Start web server</strong>: Then right click on the web service <strong><em>“grafana-test-server” &gt; Start.</em></strong></blockquote><blockquote><strong>- Verify web server</strong>: Access the CSV file using a <strong>web browser</strong> at its URL <a href="http://127.0.0.1:8001/grafana-test-server/data.csv"><strong>http://127.0.0.1:8001/grafana-test-server/data.csv</strong></a>. If you can download the file, then everything is in order.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*3kDE1WmgfE1uH2vbTCKwSA.png" /><figcaption>Web Service Setup</figcaption></figure><p>Note:</p><ul><li>If your system do not meet the requirements listed <a href="https://www.ni.com/docs/en-US/bundle/labview/page/lvconcepts/webservices.html">here</a>, you would have to setup a third party server to serve that CSV file over HTTP(s).</li><li>The LabVIEW web server is available in both development and run-time environment..</li></ul><h4>Grafana</h4><p>As stated earlier, <a href="https://grafana.com/">Grafana </a>is a dashboard engine “…Operational dashboards for your data here, there, or anywhere…”. It comes as two version an Enterprise Edition and an Open Source Version. It installs on Windows and Linux (even in docker). On Windows, it installs as a service, accessible by default at <a href="http://localhost:3000.">http://localhost:3000</a>. Its defaults credentials are <strong><em>admin </em></strong>and <strong><em>admin.</em></strong></p><p>By default, Grafana can load from a huge number of <a href="https://grafana.com/docs/grafana/latest/datasources/">data source types</a>. However, to read data from a CSV source, an extra plugin must be installed. It can be downloaded from the official website at <a href="https://grafana.com/grafana/plugins/marcusolsson-csv-datasource/?tab=installation">https://grafana.com/grafana/plugins/marcusolsson-csv-datasource/?tab=installation</a>. Plugins must be unzipped in the plugins directory at:</p><ul><li><strong><em>/var/lib/grafana/</em>plugins </strong>on a Linux system or</li><li><strong><em>C:\Program Files\GrafanaLabs\grafana\data\plugins</em></strong> on Windows.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*1GfvUmkQ4-ntxlEqS8lNWA.png" /><figcaption>Data Source Setup</figcaption></figure><blockquote><strong>Download and Install Grafana</strong> on a machine on the same network as the machine running LabVIEW. You could even put it on the same machine for reduced latency. See <a href="https://grafana.com/docs/grafana/latest/setup-grafana/installation/">the official website</a> and use the open source version.</blockquote><blockquote><strong>Create a Data Source</strong>: Download CSV plugin from <a href="https://grafana.com/grafana/plugins/marcusolsson-csv-datasource/?tab=installation">here</a>, and unzip it in the plugins directory. Then in the <a href="http://localhost:3000/?orgId=1">Grafana UI</a>, click <strong>Configurations &gt; Data Sources &gt; Enter “CSV” &gt; Add Data Source. </strong>Fill Details as per image below, Click on<strong> “Save And Test”. </strong>Expect “Success”</blockquote><blockquote><strong>Create Dashboard: </strong>Then in the <a href="http://localhost:3000/?orgId=1">Grafana UI</a>, click <strong>Dashboards &gt; New Dashboard. Then click on “Add Panel” &gt; Add a New Panel. </strong>Fill Details as per images below, Click on<strong> “Save”</strong></blockquote><blockquote><strong>Access Dashboard: </strong>Navigate to this URL: <a href="http://localhost:3000/d/qxQ3Wb67k/labview-from-csv">http://localhost:3000/d/qxQ3Wb67k/labview-from-csv</a> from a browser running on Grafana’s host or <a href="http://localhost:3000/d/qxQ3Wb67k/labview-from-csv">http://&lt;host-ip&gt;:3000/d/qxQ3Wb67k/labview-from-csv</a> from any other machine (computer, smartphone,…) on the same network as Grafana’s host.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*0VlL3bI9FT2ZuKHtt7HBKw.png" /><figcaption>Dashboard Setup | Query Tab: Select Datasource created earlier, specify columns to display from CSV data and other parameters needed for parsing the CSV data</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*1GXEGQhITzmfbdEOidiPEg.png" /><figcaption>Dashboard Setup | Transform Tab: Filter out lines without timestamp entry, Convert timestamp from string to time (time format parsing follows <a href="https://momentjs.com/docs/#/displaying/">moment.js</a> formats), Sort entries by time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkntbW1T6T2jktfNQhjkig.png" /><figcaption>Resulting Dashboard</figcaption></figure><p>Et voila…</p><p>All the code presented here can be accessed from <a href="https://github.com/KMurphs/labview-csv-grafana">this Github Repository</a>.</p><p>Some resources to explore LabVIEW Web Services can be found <a href="https://www.ni.com/docs/en-US/bundle/labview-2021/page/lvhowto/web_service_tutorial.html">here </a>and <a href="https://www.ni.com/docs/en-US/bundle/labview/page/lvhowto/ws_enable_web_server.html">there</a>.</p><p>This was a very simple setup to get you started. From thereon, there are interesting things you could do. I will name a few:</p><ul><li>Use <a href="https://www.influxdata.com/">InfluxDB</a> to store the time series data instead of a CSV file. Actually, this is the talk that opened my eye to the information in this post. You can consult the original content <a href="https://github.com/johanvandenbroek/InfluxDB-Client-LabVIEW">here</a>, <a href="https://labviewwiki.org/wiki/GLA_Summit_2020/Rapid_Dashboard_Prototyping_for_Data_Presentation_and_Analytics">there</a> and <a href="https://www.youtube.com/watch?v=3NRXAG0K-YA&amp;t=1885s">there</a>.</li><li>Setup a Web UI for your LabVIEW application using modern frameworks like ReactJS, SvelteJS… The <a href="https://github.com/KMurphs/labview-csv-grafana/blob/main/handlers/csv.vi">GitHub repository</a> for this post explores Global Variables for this purpose.</li></ul><blockquote>The main technical issue is transferring data (control signals and indicator states) between your LabVIEW Application and the HTTP Request Handlers in your LabVIEW Web Service.</blockquote><blockquote>From there any protocol like JSON can be established between the Web interface and the HTTP Request Handlers.</blockquote><p>Obviously, what I’m proposing is not a silver bullet. The tradeoffs involve, at the very least, a system that has more complexity to it. <em>There is no free lunch.</em></p><p>That’s it for me. I hope you enjoyed it. Leave a comment if you feel like it. I’m always happy to engage with the community.</p><p>From a fellow problem solver.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=818fd33092f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LabVIEW and Arduino: Get Started in Minutes.]]></title>
            <link>https://stephanekp.medium.com/labview-and-arduino-get-started-in-minutes-fd30964cc954?source=rss-cbd975d1d26a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd30964cc954</guid>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[electronics]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[labview]]></category>
            <category><![CDATA[esp32]]></category>
            <dc:creator><![CDATA[Stephane K.]]></dc:creator>
            <pubDate>Wed, 06 Jul 2022 21:30:36 GMT</pubDate>
            <atom:updated>2022-07-06T21:30:36.924Z</atom:updated>
            <content:encoded><![CDATA[<p>A couple of weeks ago, as I was changing jobs, my (now) former employer asked me to give a crash course in LabVIEW. The audience consisted of interns who would possibly take over my LabVIEW work.</p><p>After thinking about it, I thought: “<em>Let’s pull in some cheap hardware (An Arduino) and hook it up with LabVIEW… That should keep these young spirits engaged</em>”. So I want to share that experience with anyone who is trying to do the same thing.</p><h3>The Plan</h3><p>So the first exercise was to have LabVIEW show an LED that would follow the Arduino’s On-Board LED:</p><ul><li><strong><em>There is already a standard sketch to “blink” an LED for Arduino Devices.</em></strong> We only have to send the state of the LED over Serial Communication for LabVIEW to intercept and update accordingly.</li><li><strong><em>On LabVIEW side, there is already the standard “Serial Communication” example</em></strong>. It can be modified to incorporate a loop, a stop button and a LED that turns ON or OFF following the Arduino’s lead.</li></ul><p>Time to completion: Less than 10 minutes.</p><h3>Phase 1: Arduino</h3><p>Remember:</p><blockquote>The Best Code is the Code not written…</blockquote><p>So in the Arduino IDE:</p><ul><li>Select the “Blink” Example (File &gt; Example &gt; 01 Basics).</li><li>Setup parameters (Board Type, Comport,…) in the IDE for your board (Any board that runs Arduino will do).</li><li>Download the sketch on your device, and verify you have a LED that blinks.</li></ul><p>If it does, we can move to the next step:</p><h4>Update Blink LED Sketch</h4><p>In the Setup section, we will initialize Serial Communication at 9600 Baud Rate. We will then publish a message just after the LED state changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3H5NnHyWGPlw7z_psUIvQ.png" /><figcaption>Publish LED State on Change</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2341e1be2adfb7fa5a8efc4035edff00/href">https://medium.com/media/2341e1be2adfb7fa5a8efc4035edff00/href</a></iframe><h3>Phase 2: LabVIEW</h3><p>As stated previously, there is already an example shipping with all versions of LabVIEW. It does most of what we need.</p><blockquote>Close the Arduino Serial Monitor before proceeding… since LabVIEW is going to try to open that Comport too.</blockquote><ul><li>Navigate to LabVIEW Example (Help &gt; Find Examples), and look for “<strong><em>Simple Serial.vi</em></strong>”</li><li>Open this VI, setup Comport to match configuration in Arduino IDE (see above)</li><li>Run the VI, and you should see the message published by the Arduino device.</li></ul><p>If that worked then we can proceed to updating the VI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*X72zEupTwXlfyzXozVSPbA.png" /></figure><h4>Update “Simple Serial.vi”</h4><p>See all updates made to the “Simple Serial.vi” in blue below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YCuo1ebC7SjpPOewVpzT9g.png" /><figcaption>VI Snippet. LabVIEW monitors Serial Comport and update its LED indicator according to Message Received.</figcaption></figure><p>In essence,</p><ul><li>We clear the I/O Rx Buffer every time our application starts, since the device pushes messages even when no one is listening. This buffer will fill up and create a backlog for LabVIEW that needs to be fully processed before its LED state (named “Remote LED State”) follows in Real Time the state of the Arduino LED.</li><li>We add a while loop and stop button and make sure to exit the loop on error. Also, close the VISA session references outside the loop.</li><li>We parse the message received from the Arduino. If it contains “<strong>ON</strong>” we <strong>switch on</strong> the LabVIEW LED.</li><li>We handle a corner case: <strong><em>Since we read from the serial port faster than the device publishes messages, what do we do with our LabVIEW LED when we haven’t received anything?</em></strong> One Simple solution is to remember the previous valid value (using the shift register) and use that instead.</li></ul><p>Et Voila…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*vI1gt-An7vJVjmuw6H66bQ.png" /><figcaption>LabVIEW VI and Arduino Sketch. LabVIEW LED indicator follows physical state of Arduino on-board LED.</figcaption></figure><p>Okay, that’s the gist of it. The idea is that someone who is just getting his feet wet using these two technologies can find some (hopefully) helpful resource here to get him started.</p><h3>Bonus</h3><p>The scenario above has the Arduino device controlling the LED and LabVIEW acting as an indicator for its state. Let’s turn things around and let LabVIEW control the LED now.</p><h4>Arduino Sketch</h4><p>Once again, we will update an Example shipping with the Arduino Installation (File &gt; Examples &gt; Communications &gt; ReadASCIIString).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/081887a9127ae0d7a4ca0cd474f85eef/href">https://medium.com/media/081887a9127ae0d7a4ca0cd474f85eef/href</a></iframe><h4>LabVIEW VI</h4><p>We will update the previous VI to include sending command to the Arduino. See comment in Green.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJiMrEbWaRvEotVrPL1Fvg.png" /><figcaption>LabVIEW controls physical LED and update LED indicator from Serial Communication.</figcaption></figure><p>And that’s it! Now, changing the state of the control button in LabVIEW forces a change of state on the Arduino device which then publishes its new state on the comport. LabVIEW then updates its own LED to follow the content of the message published. Easy Peasy,…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*zxpn4m-UIB0Tw7wcf8_HVQ.png" /><figcaption>LabVIEW controls Arduino LED</figcaption></figure><p>As I said, previously, I had to put together this small tutorial as a means to get new interns to started with LabVIEW. I’m documenting it here for public use.</p><p>That’s it for me. If you have questions / comments / remarks, get in touch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd30964cc954" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Priority Queues. From scratch. For Dummies. In under 5 Minutes.]]></title>
            <link>https://stephanekp.medium.com/priority-queues-from-scratch-for-dummies-in-under-5-minutes-c3d74468213f?source=rss-cbd975d1d26a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3d74468213f</guid>
            <category><![CDATA[priority-queue]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[heapsort]]></category>
            <category><![CDATA[faang]]></category>
            <dc:creator><![CDATA[Stephane K.]]></dc:creator>
            <pubDate>Wed, 06 Jul 2022 16:41:15 GMT</pubDate>
            <atom:updated>2022-07-06T16:41:15.139Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VUJovvD8WGpSovL8" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Ever had to implement a priority queue from scratch? In less than 5 minutes?? Well, it might be the case that you don’t fully understand what it is and why you would ever want one… If so, read up. The story I want to tell you today comes from a recent interview I went through. And one of the question I got asked called for a “Priority Queue”. And, it got me stuck. Because I didn’t know off-the-bat a library in Python to import for it.</p><p>Hence, <em>ever had to implement one from scratch in less than 5 minutes?</em> Let me walk you through it.</p><h3>The problem</h3><p>I am going to change the interview question a little bit since I don’t remember it “word for word” and to keep it anonymous.</p><p>Caution! It is going to be <em>wildly </em>hypothetical, like… “way out there”. Here is how it goes:</p><blockquote>“You have N machines in a factory with some given electrical consumption (in a simple array). And you have decided to reduce the total consumption of your factory by half. So you did some research and you heard about these “magical” fans (I told you it would be wild, but bear with me). Their magic is that: you install one and, just like that, consumption of your machine if halved.</blockquote><blockquote>Like I said, these fans are magical. When you install one the amount of power consumption of the machine is halved. If you install two on the same machine, the amount of power consumption is divided by 4, …</blockquote><blockquote>Now these “magical” fans are expensive. And, you have to decide what is the <strong><em>minimum </em></strong>number of these… “fans” you should install. The ideal goal is to bring down the total consumption of your factory by a factor of 2 at least.”</blockquote><p>Note: Before we continue, like I said, it’s going to be a hypothetical, and thought experiment. We’re not going to ask questions about the inner workings of these fans, or the amount of power THEY consume. All of that is irrelevant. <em>To be fair, the actual scenario I was given made more sense</em>. But as I’m writing this post, I can’t unfortunately think of a better similar scenario. So for now, this is the best I can come up with.</p><p>Okay, so, if you think about the problem for a moment, you will realize one obvious solution. <strong><em>You can install a fan on each machine to get the desired effect</em></strong>. So N fans, one for each machine, will bring down the power consumption by half <strong><em>which is the goal</em></strong>. So,</p><ol><li>N must be the worst case number of fans you can install. This hints to an ideal solution with an O(N) time complexity. That is if you <strong>instantly </strong>know on which machine to install the next fan.</li><li>The real question then is to come up with some heuristic to reduce this number of fans to a minimum.</li></ol><p>After thinking a little bit more about this, I settled for the following consideration.</p><blockquote>We want to be greedy about our “fan placing” strategy.</blockquote><blockquote>Seek to install a fan on the machine that will have the greatest impact. This will result in the largest decrease on the total consumption. In other words,</blockquote><blockquote>1. Find the biggest contributor,</blockquote><blockquote>2. Install a fan there. And just like that we have the biggest impact on total consumption that any fan can make.</blockquote><blockquote>3. Then,.. rinse and repeat until the goal is met.</blockquote><h3>The Initial Approach: A Greedy Algorithm</h3><p>Okay, that sounded like a good strategy. But before I start writing code I try to get more insight into the problem and my proposed solution. See if I can come up with possible improvements, critical drawbacks,… All the good stuff, that you need to tell your interviewer and keep him happy.</p><p>One problem to solve with this approach is obviously<strong> <em>how to find the greatest contributor</em></strong>. The “<strong>array</strong>” of consumption given doesn’t lend itself to finding a maximum or minimum easily. <em>In fact, you need an </em><em>O(N) algorithm to find a maximum</em>. That is, you need to visit each element of the array at least once to find it. So given that you have to place N fans in the worst case and for each fan you need to do in average N/2 movements, you effectively have an O(N²) algorithm.</p><p>“Can we do it better?”, I asked myself. Here better, for me, meant, finding the greatest contributor either in O(1) or O(Log(N)). Doing so will bring down the time complexity to O(N) or O(N Log(N)) respectively. That’s when the priority queue first popped into my mind.</p><p>Theoretically, you can extract a maximum / minimum from a priority queue in O(1). That’s awesome and <strong><em>that’s in a nutshell what they are used for</em></strong>… If only I knew which library in Python gives you an implementation for it. And, as I realized that I didn’t know any, I also realized that even if I could divine that library “import”, I didn’t know its API. So, right there and then, I realized that I never actually had to deal with priority queues in Python before. “I should have prepared more…”, I thought to myself.</p><blockquote>Now, since I didn’t know one to use off-the-bat, what about we implement one from scratch.</blockquote><p>And I don’t know whether it was because I was already 3 coding tasks into the interview. Or because my time was running out. Or because it was just the pressure of the task. I could not for the life of me figure out how to implement a priority queue from scratch in under 5 minutes.</p><p>“We are going with the O(N²) algorithm” I decided. At least, we would have some working code. And, if we have time at the end, maybe we try the priority queues again.</p><p>So this is my initial / brute force approach</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e997f89fad6dc73c1c2b5d7c1f22e7e/href">https://medium.com/media/5e997f89fad6dc73c1c2b5d7c1f22e7e/href</a></iframe><h3>Priority Queues: What are they?</h3><blockquote>In computer science, a priority queue is <strong>an abstract data-type similar to a regular queue</strong> or stack data structure in which each element additionally has a “priority” associated with it. In a priority queue, an element with high priority is served before an element with low priority.</blockquote><p>In other words, a “Priority Queue” is a fancy term for a data structure (or <strong>any data structure really</strong>) that can give the “highest priority” element in really competitive time complexity. Ideally, O(1).</p><p>Practically, if the “<strong><em>maximum</em></strong>” or “<strong><em>minimum</em></strong>” of a dataset is your definition of “<strong><em>highest priority</em></strong>”. Then it gives you the maximum or minimum of that dataset in constant time. And that’s pretty awesome.</p><h4>Priority Queues: Complexities</h4><p>One popular implementation of a priority queue makes use of a heap.</p><blockquote>A heap is:</blockquote><blockquote>1. A Binary tree: Each node has two children at the most</blockquote><blockquote>2. A Complete tree: Each level of tree are fully filled except maybe the last level. For a more concise answer see <a href="https://stackoverflow.com/a/66020848">this SO answer</a></blockquote><blockquote>3. A heap satisfies the heap property. i.e. For a “max heap” the value of a parent node is always greater than those of its children. And by consequence, the value of a parent node is greater than the value of any of its descendants.</blockquote><p>When using a “<strong><em>max binary heap</em></strong>”, the maximum node is at the root. It is also the handle of the data structure, so</p><ul><li>You find it in O(1).</li><li>You extract it in O(Log(N)) (Well if you think about it it’s O(1) although technically, you need to fix your tree since it no longer has a root, and you do that in O(Log(N)).</li><li>You insert a new node in O(Log(N)).</li><li>You delete a node in O(Log(N)).</li><li>You find an arbitrary node in O(N) (Yes, you don’t want to look for things in a heap, rather use a binary search tree instead, and do it in O(Log(N)))</li></ul><blockquote>Note: Remark that a <strong><em>heap </em></strong>does not tell you anything about the comparison between siblings, or cousins or nodes from the same “generation”. For example, <em>it is not guaranteed (nor required really) that the left child node is greater or smaller than the right child node</em>. A heap doesn’t care about that</blockquote><blockquote>This is not the case for a binary search tree for example. <em>For a b</em><strong><em>inary search tree</em></strong><em>, the left node is smaller than the parent which itself is smaller than the right node</em>. As a consequence, everything rooted at the left node have values smaller than that of the parent. Everything rooted at the left node will have values smaller than any thing rooted at the right node.</blockquote><h4>Priority Queues: A popular Implementation</h4><p>As quoted above, the priority queue is an “<strong><em>abstract type</em></strong>”. I.e. <em>you can implement its “functionality” however you want using any data structure you want</em>. It just happens that the <strong><em>binary heap</em></strong> is particularly well fitted for this use case.</p><p>This is so true, that there is a very simple sorting algorithm that will give you, <em>for the price of one</em>, not only the ability to simply sort things in O(NLog(N)) but also the implementation of a very simple priority queue. <em>One that you can “whip up” in a couple of minutes</em>. And for a couple of cheap tests, assure yourself that it is working.</p><h3>Heapsort and “One Free” Priority Queue</h3><p>How does heapsort work?</p><ol><li><strong>You store your heap in a simple list:</strong> aka a (dynamic) array. You use the index of the element in the list to find parents and children.</li><li><strong>You use a 6 lines “</strong><strong>heapify” function:</strong> That will fix your tree so all its nodes abide by the heap property.</li><li><strong>You build your tree.</strong></li></ol><p><strong>Easy-peasy…:</strong> Then, you extract the maximum at the root and fix your tree by calling heapify. You rinse and repeat this last step. This will give you an ordered sequence of numbers from highest to lowest. Sorting complete.</p><p><strong>Cooking Time</strong>: <em>Less than 1 minute</em></p><h4>Before we continue</h4><p>One thing is important about the indices:</p><blockquote><strong>If a parent is at index </strong><strong>n, its left child will be at index </strong><strong>2 * n + 1. Its right child will be at index </strong><strong>2 * n + 2.</strong></blockquote><p>That’s the most important thing to remember aside from what the “heap property” is. (i.e. “<strong><em>A parent value will always be higher that its children</em></strong>”.)</p><p>If you remember these two. You can rebuild this algorithm whenever you want… or need.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/096bcb289d40e0c5aff982b7ed812c62/href">https://medium.com/media/096bcb289d40e0c5aff982b7ed812c62/href</a></iframe><h4>Priority Queue</h4><p>What heapsort above does is use the priority queue to extract the max and rebuild the heap so all its elements abide by the heap property.</p><p>Now you could build a proper API for it (with insert, find, delete, peek,…), but for my use case and given the time I had, heapify is already doing most of the work. I just need to use it and be clever about it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6941fb2dfa1b0ce125859837166042e8/href">https://medium.com/media/6941fb2dfa1b0ce125859837166042e8/href</a></iframe><p>Now I was able to look up this pesky import. And imagine what? As I should have expected from the <strong>zen of python</strong>, it’s as simple as from queue import PriorityQueue. And the API? Annoyingly simple.</p><pre>from queue import PriorityQueue</pre><pre><strong>pq = PriorityQueue()</strong></pre><pre># Insert<br><strong>for element in A: <br>   ranked_machines.put(-1 * machine)</strong> <br>   # The implementation is that of a min-heap where each parent <br>   # value is SMALLER than its children. So we have be a bit clever <br>   # about it to use it as max heap. i.e. Multiply by -1</pre><pre># Retrieve<br><strong>worse_machine = -1 * ranked_machines.get()</strong></pre><p>Okay, that’s it for me. <strong><em>Note that I am not claiming that this is the only way of solving this or that this is the best method in any way</em></strong>. That said, if you happened to have a better one, I would ACTUALLY be very curious, impressed and keen in looking at it. Get in touch.</p><p>I hope you enjoyed it. Leave a comment if you feel like it. I’m always happy to engage with the community.</p><p>From a fellow problem solver.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3d74468213f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Introduction for Firmata and its use with Test Systems]]></title>
            <link>https://stephanekp.medium.com/an-introduction-for-firmata-and-its-use-with-test-systems-ddf5aeb94ffa?source=rss-cbd975d1d26a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddf5aeb94ffa</guid>
            <category><![CDATA[arduino]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[firmata]]></category>
            <category><![CDATA[labview]]></category>
            <dc:creator><![CDATA[Stephane K.]]></dc:creator>
            <pubDate>Mon, 14 Feb 2022 17:25:43 GMT</pubDate>
            <atom:updated>2022-02-14T17:25:43.165Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*40q-uompx9uaRbr_" /><figcaption>Photo by <a href="https://unsplash.com/@jorgedevs?utm_source=medium&amp;utm_medium=referral">Jorge Ramirez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I recently wrote about <a href="https://micropython.org/">micropython</a>, a library that allows python 3.x to run on constrained / embedded systems. This was particularly interesting with regards to test systems. As a matter of fact, using the library has reduced the development of test code for embedded devices. This is particularly helpful in a manufacturing / production environment. I even presented <a href="https://github.com/KMurphs/labview-client-for-micropython">a client library</a> for <a href="https://www.ni.com/en-za/shop/labview.html">LabVIEW </a>and <a href="https://www.ni.com/en-za/shop/electronic-test-instrumentation/application-software-for-electronic-test-and-instrumentation-category/what-is-teststand.html">TestStand</a>, since these two are particularly prevalent in this industry.</p><p>Today, I want to introduce a different library, <a href="https://github.com/firmata/protocol">Firmata</a>. This library is, very much, a different beast from the previous one. But, just as micropython, it also aims to provide an abstraction for the target it is running on. It enables the reuse of the same interfaces, clients and APIs to interact with a wide variety of different embedded systems. A test system can interact with any embedded device that implements the library. In fact, any PC/Laptop can interact with devices that are running with the <a href="https://github.com/firmata/protocol">Firmata</a> protocol.</p><h3><a href="https://github.com/firmata/protocol">Firmata</a>: What is it?</h3><blockquote>Firmata is a generic protocol for communicating with microcontrollers from software on a host computer. It is intended to work with any host computer software package. …The aim is to allow people to completely control the Arduino from software on the host computer</blockquote><p>Let’s talk a little bit about the problem this library tries to solve.</p><p>Say, your team is developing a new product that consists of an actual PCB and a MCU running on it. From experience, your team will spend an appreciable amount of time bringing up the different peripherals of the board. Once they are all up and running, you will then develop the field application as per requirements.</p><p>In parallel, your test team will spend a similar amount of time bringing up these peripherals. This is so they can develop a test application. The test application is used during the manufacture of this board. It allows test systems to assess whether the board and its different peripherals are functional. It will test the different features of your product against a set of specifications.</p><p>It is quite a lot of code and time spent on this. Firmata proposes to considerably reduce that:</p><ul><li>For <strong>the field application</strong>, Firmata can be used as a rapid proof of concept. This allows quick validation of ideas, hardware, specifications and requirements for the project.</li><li>For <strong>the test application</strong>, Firmata can be used as is. This is possible since<em> it exposes much of the hardware functionality over a communication link</em>. This link can be a serial communication port for example.</li></ul><blockquote>Firmata is a protocol for communicating with microcontrollers from software on a host computer. The<a href="https://github.com/firmata/protocol"> protocol</a> can be implemented in firmware on any microcontroller architecture as well as software on any host computer software package.</blockquote><h3>Getting Started</h3><p>How easy is it to get started? Well, it is very easy. You need:</p><ol><li>A embedded device running Firmata. To start, <strong>any </strong>arduino will do fine.</li><li>A communication link to your Laptop / PC. The easiest is the standard serial communication link over USB. Since it is the available with all Arduino boards.</li></ol><p>3. A Client for the laptop / PC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*b1s1YSS0-LamUmxSivmQ1Q.png" /><figcaption><em>Windows Remote Arduino Experience. Written by Microsoft, uses Firmata to interact with embedded devices.</em></figcaption></figure><ul><li>On a windows system, open Microsoft Store. Search and install “<strong><em>Windows Remote Arduino Experience</em></strong>”. It’s a piece of software written by Microsoft. It makes use of Firmata to allow your PC to interact with the outside world.</li><li>Or, you can choose and download a client from a list spanning many programming languages. There are quite a few to choose from. <strong><em>Python, .NET, JavaScript, Clojure, GO, </em></strong>… A list of client implementation (and languages) is provided <a href="https://github.com/firmata/protocol">here</a>. Whatever language you choose, there is probably going to be an implementation. The client will typically come with a public GitHub repository and a “how to get started” guide.</li></ul><h3><a href="https://github.com/firmata/protocol">Firmata</a>: High Level Overview</h3><p>The number one feature of the library that made me fall in love with it is its abstraction of the transport layer. In other world, you can use a serial communication link, or Bluetooth or WiFi,… And the project is very much alive. It is open for growth and there are new proposals to expand its functionality.</p><p>But, let’s take a step back and look at the big picture.</p><p>If you look a little bit closely at what the <strong><em>Arduino project</em></strong> is, you will see that it is:</p><blockquote>An open source and extensible project.</blockquote><p>It is an abstraction layer for your board hardware. And it does a very good job at doing that - as seen by its popularity. You are not directly interacting with the low level components of your target. Its quirks, peculiarities are hidden, abstracted away, behind a common interface. This makes it possible to use the same sketch/arduino code on different hardware with some minimal customization.</p><blockquote>Arduino is an open-source electronics platform …</blockquote><blockquote><strong>Open source and extensible software</strong> — The Arduino software is published as open source tools, available for extension by experienced programmers. …</blockquote><blockquote><strong>Open source and extensible hardware</strong> — The plans of the Arduino boards are published under a Creative Commons license, so experienced circuit designers can make their own version of the module, extending it and improving it….</blockquote><p>What the quote above doesn’t make too clear (at least not for me), is that <strong><em>you can develop and configure any board to run with Arduino</em></strong>. You wouldn’t be incorrect in assuming that the Arduino project is more a specification than a particular product. In other words, you can adapt any board to integrate the Arduino ecosystem.</p><p>Most Arduino boards consist of an<a href="https://en.wikipedia.org/wiki/Atmel"> Atmel</a> 8-bit<a href="https://en.wikipedia.org/wiki/AVR_microcontroller"> AVR microcontroller.</a> Typically, ATmega8, ATmega168,<a href="https://en.wikipedia.org/wiki/ATmega328"> ATmega328</a>, ATmega1280, or ATmega2560. But you can adapt other micro-controllers to run with Arduino (see <a href="https://hackaday.io/project/165881-attiny-1-series-with-arduino-support/log/164339-adding-a-custom-board-to-arduino-setting-up-io">here</a> for a tutorial). You can also adapt a completely different family of controllers altogether so it integrate in the Arduino ecosystem. (See the <a href="https://github.com/stm32duino/Arduino_Core_STM32">official project for STM32</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nLBBjwMJkr6yD3U2" /><figcaption>Photo by <a href="https://unsplash.com/@nicklbaert?utm_source=medium&amp;utm_medium=referral">Niclas Illg</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>How is all of that relevant for Firmata? Well, what Firmata does, is that <strong><em>it builds another abstraction layer on top of the Arduino Implementation.</em></strong> Arduino is a mature technology involved in many projects across various industries, expertise, use cases. <em>The Firmata project builds upon all of that maturity.</em></p><p>In practice, as in my personal case, this previous paragraphs mean that if you have a custom board (mine was running STM32 hosts):</p><ol><li>You want to find an implementation of Arduino for your host. Hopefully, your manufacturer has already done that.</li></ol><p>2. Then adapt the Firmata layer to run on top of it.</p><p>It can sound like a very arduous thing to do, but it’s not. One thing that I have noticed though is that documentation of the process is seriously lacking. Tutorials that walk you through the process are rare, and I’m planning to write on that nearly.</p><p>One other architectural aspect of the protocol, that I absolutely love, is that it aims at abstracting the transport method. This allows you to reuse the same client (running on your laptop) over different medias. Serial Communication, WiFi, Ethernet, Bluetooth are all supported possibilities. The only requirement really is that there is a communication link between both devices.</p><h3><a href="https://github.com/firmata/protocol">Firmata</a>: Features</h3><p>As I explained previously:</p><blockquote>Firmata exposes the internal peripherals of your target device to the client.</blockquote><p>Some of the modes or functionality that can be accessed and interacted with:</p><ol><li><em>Digital Inputs, Digital Outputs, Analog Inputs, Input Pull-ups</em>.</li><li><em>PWM, Servo and Tone</em>: All these modes are flavors of PWM. The servo is specialized to control servo motors. While the tone is used with a speaker or piezo buzzer to generate sounds. This latter is an advanced mode of the library.</li><li><em>Shift</em>: This mode enables pushing and retrieving data from shift registers on the device.</li><li><em>I2C</em>: The client can remotely send and retrieve data from devices on the I2C bus on the target board.</li><li><em>One-Wire</em>: This protocol is very similar to I2C - Only one wire (and another for ground) is used to communicate between the (one) master and the other (N slaves) devices on the bus.</li><li><em>Stepper</em>: Specialized protocol to control stepper motors.</li><li><em>Encoder</em>: Encoders are sensors that generate digital signals in response to (linear or rotational) movements. These signals can convey information such as speed or position. This mode allows the client to obtain that information.</li><li><em>Serial</em>: Exposes UARTs (up to 4) on the remote device to the client on the laptop / PC.</li></ol><p>Below are some advanced modes:</p><ol><li><em>SPI</em>: Sending and retrieving data from devices on the SPI bus on the target board.</li><li><em>Sonar</em>: Interacts with a “sonar” sensor to obtain distance information about some obstacle situated in the “vicinity” of the sensor.</li><li><em>Tone</em>: see PWM above</li><li><em>DHT</em>: To interact with a “Digital-output relative humidity and temperature” sensor/module</li></ol><h3>Relevance for Test Systems</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ol1_oWmlLTW4BAIN" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=medium&amp;utm_medium=referral">National Cancer Institute</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As I explained earlier, the library is particularly interesting to a test system.</p><ul><li>It can cut, by a factor of 2 or 3, the time your test team is spending to put together test code for embedded products.</li><li>In the long run, i<em>t limits the risks issues related to maintainability and bugs</em>. This is possible because the library can be considered a mature one.</li><li>Company-wise, <em>it enables reuse of client “test codebases” across different projects</em>… If they all use Firmata. The library can even be extended to support specialized forms of transports, if necessary.</li></ul><h3>A Firmata Client in LabVIEW and TestStand</h3><p>My initial use case involved the implementation of a test system with <a href="https://www.ni.com/en-us/shop/electronic-test-instrumentation/application-software-for-electronic-test-and-instrumentation-category/what-is-teststand.html">TestStand </a>from <a href="https://www.ni.com/en-za.html">National Instruments</a> as a Test Executive and <a href="https://www.ni.com/en-za/shop/labview.html">LabVIEW </a>as the primary programming language. However, at the time, there was no client implemented in <a href="https://www.ni.com/en-za/shop/labview.html">LabVIEW</a>. As a result, I developed one to address that shortcoming. This client implementation is made publicly available <a href="https://github.com/KMurphs/labview-client-for-firmata">here</a>.</p><p>The next sections will give an overview of this client and its integration with a Test Executive such as <a href="https://www.ni.com/en-us/shop/electronic-test-instrumentation/application-software-for-electronic-test-and-instrumentation-category/what-is-teststand.html">TestStand</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NjYPyp61x584rEZmTkG6qg.png" /><figcaption><a href="https://github.com/KMurphs/labview-client-for-firmata">labview-client-for-firmata</a> Library: Architectural Overview</figcaption></figure><h4>The client is written in <a href="https://www.ni.com/en-za/shop/labview.html">LabVIEW</a>.</h4><blockquote><a href="https://www.ni.com/en-za/shop/labview.html">LabVIEW</a> is a Graphical Programming Language developed by <a href="https://www.ni.com/en-za.html">National Instruments</a>.</blockquote><p>Architecturally, this project decouples transport layer from the client interacting with the embedded device. This is follows pretty much a flavor of “micro-service”. In this setting, each of these transport “micro-service” is addressable via the uniquely named queue associated with it. <em>This allows multiple devices to be available at the same time. It then also enables one client to decide, on the fly, at run-time, which device to interact with</em>. The appropriate queue can then be chosen to transmit / receive messages.</p><p>The <a href="https://github.com/firmata/protocol/blob/master/protocol.md">main messages</a>, as specified by the protocol, are implemented as a set of API functions / Public VIs. These will interact directly with the remote object via the associated queue.</p><p>The transport layer also offers the ability to push data to a UI Service with, possibly, state persistence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OciOTROpmn0hTpVksL7I8A.png" /><figcaption>LabvIEW UI For Firmata Library</figcaption></figure><h4>Integrating with the Test Executive</h4><p>In the case of <a href="https://www.ni.com/en-us/shop/electronic-test-instrumentation/application-software-for-electronic-test-and-instrumentation-category/what-is-teststand.html">TestStand</a>, the API functions / Public VIs provided should be enough. An example sequence file is included in the GitHub repository.</p><p>The relevant transport VIs must be separately initialized beforehand and cleaned-up afterward. A transport VI will accept the name of its queue as an input argument. The queue name can be used later on to interact with the associated remote object.</p><p>From thereon, the API / Public VIs can be called with the correct queue name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*cxj9ScdClvgGH4nbKTIfyQ.png" /><figcaption>Firmata Library with TestStand</figcaption></figure><p>That’s it… The intention is to convey that, especially in the case of a Test System, Firmata can bring huge benefits on the table. It will standardize test code bases across a company and its project. And in the process, the projects will benefit from a mature and stable test library. This will increase the quality of the overall test systems and products.</p><p>That’s it for me. I hope you enjoyed it. Leave a comment if you feel like it. I’m always happy to engage with the community.</p><p>From a fellow problem solver.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddf5aeb94ffa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can you run python on an IoT device?]]></title>
            <link>https://stephanekp.medium.com/can-you-run-python-on-an-iot-device-b17fca080368?source=rss-cbd975d1d26a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b17fca080368</guid>
            <dc:creator><![CDATA[Stephane K.]]></dc:creator>
            <pubDate>Sun, 06 Feb 2022 13:46:39 GMT</pubDate>
            <atom:updated>2022-02-06T13:46:39.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caTlEJc6bbFvbbs6MPvShg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hiteshchoudhary?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Hitesh Choudhary</a> on <a href="https://unsplash.com/s/photos/python-embedded?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Imagine for a moment this, the ability to run Python on an IoT device, i.e. an embedded device such as a microcontroller. You might not have an appreciation for the problem, but developing for embedded systems is notoriously difficult. For our embedded developer friends, it means imagining not having to sift as much through datasheets and manuals. Imagine the amount of time, energy that teams would gain because of all that.</p><p>Last year, I read about <a href="https://www.micropython.org/">micropython</a>. It’s a library that allows a stripped down version of Python 3.x to run on constrained systems such as IoT devices. It took me a couple of minutes to understand the ramifications of such a feat. I am going to walk you through some of its advantages.</p><blockquote>MicroPython is a lean and efficient implementation of the<a href="http://www.python.org/"> Python 3</a> programming language that includes a small subset of the Python standard library and is optimised to run on microcontrollers and in constrained environments … giving you a low-level Python operating system that can be used to control all kinds of electronic projects. — <a href="https://micropython.org/">https://micropython.org/</a></blockquote><h3>Introduction</h3><p>There is not argument about the fact that developing for embedded systems is notoriously difficult. Well, to be technically correct, I guess it is at least as difficult as any engineering project can be. But, in this particular context, many of the difficulties in the development of embedded systems come from dealing with the bare-metal hardware. This adds complexity to a the developer’s life, it requires him to sift through datasheets and manuals. And, then, he has to get everything to play nice with everything else. I am telling you, it’s not for the “faint of heart”.</p><blockquote>Traditionally, embedded development make use of low level languages such as C. As such, they do not come with all the abstractions, features that higher level languages such as Python or Java have. This makes developing with C considerably more difficult to accomplish the same tasks.</blockquote><p>The need for low-level control have made the use of low-level programming languages such as C the de-facto standard in the industry. As a consequence, out of the box, our developer friends do not have access to abstractions, or classes. They do not have access to many of the features that software running on servers and personal computers enjoy. I’m speaking of useful paradigms such as Object Orientation and Functional Programming. These have become industry standards and are not readily available on embedded and IoT devices. Our friend struggle their way without them and manage to built reliable, safe, critical, real-time systems. It is always a gigantic feat of engineering. And I take my hat off to all our embedded developer friends. You are unsung heroes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*otKMPrK4MhHXlj_UOs3fgA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jorgedevs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jorge Ramirez</a> on <a href="https://unsplash.com/s/photos/iot?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>However, on the other side, things are changing, our ability to fit more and more space and RAM into cheaper and cheaper constrained systems have increased. This has brought forward the emergence of sophisticated constructs such as abstraction layers,… These have empowered code reuse, and development speed up.</p><p>The difficulties mentioned earlier are only one aspect of the problems in embedded systems. Usually, and especially, in a manufacturing environment, there are stringent requirements on testing. This is to ensure stability and integrity. Practically, teams must spend a similar effort in developing a twin code base used for testing the actual hardware / IoT device. One code base for field application, one code base for production testing. The extra test code base will make sure that the microcontroller is 100% functional. It will make sure that it is properly integrated in the PCB where it seats. But, in total, that is two code bases, and that is a lot. — Two code bases to develop and maintain.</p><blockquote>Good programmers write good code. Great programmers write no code.</blockquote><h3>Micropython: How does it help?</h3><p>Well first of all, although it is a stripped down version of Python, it’s still very much Python. All a sudden, you have access to most of the features of the language. This includes the paradigms the language supports. Object Oriented and Classes, Functional Programming and Immutability, amongst others.</p><p>Usually, this means that a considerable effort shifts away from your team to, say, the manufacturer of the microcontroller. The manufacturer develops the abstraction layer whose API is micropython. He knows more about this piece of technology than your team does (hopefully). He is therefore better equipped to write and maintain this abstraction. For you and your team, this leads to a better and more robust system. Moreover, this abstraction layer is Open Source and shared across thousands of teams. They will report and work to fix issues, improve the quality of the abstraction. You and your team get all that richness, experience for free. You don’t need two code bases. This abstraction layer can emulate the entire microcontroller making it almost test ready.</p><blockquote><strong>The only other thing you then need, is a client for your test system and a set of functions that the test system will remotely invoke on the target IoT device (i.e the microcontroller)</strong></blockquote><h3>Micropython: In a nutshell</h3><p>If you look a the documentation</p><blockquote>Micropython implements the entire Python 3.4 syntax (including exceptions, with, yield from, etc., and additionally async/await keywords from Python 3.5). The following core datatypes are provided: str (including basic Unicode support), bytes, bytearray, tuple, list, dict, set, frozenset, array.array, collections.namedtuple, classes and instances. Builtin modules include sys, time, and struct, etc. Select ports have support for _thread module (multithreading). Note that only a subset of Python 3 functionality is implemented for the data types and modules.</blockquote><p>What you also get is a very useful interactive prompt over the serial port. This means that as soon as the board has power and you have access to its serial port, you can interact in real-time (yes, no compiling) with it, and its pins, and its peripherals, and its eeprom,… And for that, you can use <strong>any </strong>application. Any application that can send and receive packets on a serial port can interact with it. This means your test system can run any language in any framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*g3IdUsShhKYPGGIYjuZAHw.png" /><figcaption>Putty running on a laptop — And a Python REPL running on the remote device over serial port - The interactive prompt gives you control over the device and all its peripherals. And you can run Python Commands</figcaption></figure><h4>Getting started</h4><p>Getting started is extremely easy.</p><p>To get started one needs a board that runs micropython. Officially, the library promotes the <a href="https://github.com/micropython/pyboard">PyBoard</a>. But the documentation provide some other alternatives like the affordable and popular <a href="https://docs.micropython.org/en/latest/esp32/quickref.html">ESP32</a>.</p><p>Then using any serial application (Arduino IDE, Putty, Docklight) open a serial communication session to the device comport, and you will get the interactive REPL prompt as shown above. From thereon, happy hacking.</p><h3>Micropython: Advantages</h3><p>I have already listed a few of the advantages that the library brings.</p><p>Now, it is true that this library is not a silver bullet. It might not be appropriate for any and all project requirements and characteristics. Yet, for a vast amount of electronic projects this should, at the very least, provide a <strong><em>fast, reliable and easy startup point and proof of concept</em></strong>.</p><p>The library caters for Python paradigms such as OOP and FP. It supports classes, mutable and immutable data types. It also implements generator, string manipulation, arbitrary precision integers. Closures, list comprehension, exception handling are more of the language features.</p><blockquote><strong><em>Micropython provides a fast, reliable and easy startup point and proof of concept</em></strong>.</blockquote><p>Did I mention the absolutely, extremely useful interactive prompt over the serial port? I feel like I haven’t. Let me… <em>It does feature an awesome, very useful, (dare I say, ground breaking?) interactive prompt over the serial port. And that makes debugging so much easier.</em></p><h3>Test Systems And Test Executives</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*N21EO5b0Kj6tQ7BqPqmcdw.png" /><figcaption>Test Systems</figcaption></figure><p>Test System development is definitely a good use case for micropython. Personally, I have been able to port this system to 4 different test products within a week. They run of STM32F405xxxx targets. And since then, I haven’t had to touch that code base ever again. This means no bug fixes, no new feature development,… In essence, limited maintenance requirements.</p><p>Now the only thing that’s left is a client for your test system. That’s one of the tasks I had to tackle while developing the test system mentioned earlier. I wrote a client for a Test Executive / Test System that will interact with micropython.</p><p>I have made that library public so that it can, in a similar way, speed up development on that front. The library is written in <a href="https://www.ni.com/en-za/shop/labview.html">LabVIEW</a>, to be optionally integrated with <a href="https://www.ni.com/en-za/shop/electronic-test-instrumentation/application-software-for-electronic-test-and-instrumentation-category/what-is-teststand.html">TestStand</a>.</p><blockquote><a href="https://www.ni.com/en-za/shop/labview.html">LabVIEW</a> is a graphical programming language developed by <a href="https://www.ni.com/">National Instruments</a>. It has a strong representation in Test Environments. And it seamlessly integrate with the Test Executive <a href="https://www.ni.com/en-za/shop/electronic-test-instrumentation/application-software-for-electronic-test-and-instrumentation-category/what-is-teststand.html">TestStand</a>.</blockquote><blockquote><a href="https://www.ni.com/en-za/shop/electronic-test-instrumentation/application-software-for-electronic-test-and-instrumentation-category/what-is-teststand.html">TestStand</a> is also developed by <a href="https://www.ni.com/">National Instruments</a>. It is in the same way widely adopted in the manufacturing industry as a Test Executive.</blockquote><p><strong><em>My hope is that you get as much fun as I did while working on this Test System. Using micropython makes your life easier on all fronts. This is especially true for the testing component of your project.</em></strong></p><p>You can find the documentation for micropython <a href="https://docs.micropython.org/en/latest/">here</a>. The open sourced GitHub repository for the project is <a href="https://github.com/micropython/micropython">here</a>. And the official website at <a href="https://micropython.org/">https://micropython.org/</a></p><p>For the client library, you can find it in my repository <a href="https://github.com/KMurphs/labview-client-for-micropython">here</a>.</p><p>That’s it for me. I hope you enjoyed it. Leave a comment if you feel like it. I’m always happy to engage with the community.</p><p>From a fellow problem solver.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b17fca080368" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithms and Heuristics, Some things you should know]]></title>
            <link>https://stephanekp.medium.com/algorithms-and-heuristics-some-things-you-should-know-fb206252c500?source=rss-cbd975d1d26a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb206252c500</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[travelling-salesman]]></category>
            <category><![CDATA[heuristics]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Stephane K.]]></dc:creator>
            <pubDate>Tue, 15 Jun 2021 21:33:18 GMT</pubDate>
            <atom:updated>2021-06-15T21:33:18.145Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gmNunOZ86_URtnzuOA7oNg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@syinq?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Susan Q Yin</a> on <a href="https://unsplash.com/s/photos/maze?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Algorithm: Word used by programmers when… They do not want to explain what they did.</p><p>You might find the joke above of poor taste but I have come to realize that there is a disconcerting truth to it. I will tell you the story of a problem. One very much like a problem you might face on a Monday morning, as you come into your office ready for the week.</p><p>It goes like this: Your boss calls you into his office, and tells you of this problem that your company(and you) have in your production facility. You (and your company) would like to optimize throughput across the factory, by reducing the amount of time your “next-gen” automated soldering arms spend… well soldering. The idea:</p><p><em>Given a set of points the soldering arm has to visit, write a program that will come up with a path that minimizes the amount of time spent traveling between these points.</em></p><h3>What is an algorithm?</h3><blockquote>It is a recipe to solve a problem. It is a set of instructions describing what to perform to come up with the solution to the problem.</blockquote><p>That program your boss wants you to write? It <strong>implements </strong>the algorithm. An algorithm can be written and expressed in many different languages. Beyond the syntax of your programming language of choice, the ideas and instructions that make up the algorithm are still there. <em>The algorithm is language agnostic</em>.</p><p>As a good engineer, you sit with a piece of paper, prompting yourself to come up with a possible recipe. This algorithm… what could it be? One idea would be to start at some point, solder it then visit the nearest point and solder there. Then find the nearest point from that new position, solder it, and so on…</p><p>Not bad! It seems you have things under control… or so it appears.</p><h3>What makes a good algorithm?</h3><p>So far, what you have is an algorithm, and it is <strong>also based </strong>on a<strong> </strong><em>heuristic, </em>which, in this case, might not even be a good one.</p><p>Before we look at the definition of a heuristic: There are usually many ways (or algorithms) to solve a problem. A <strong>good </strong>algorithm, however, is a little bit of a different beast.</p><blockquote>A good algorithm must be <strong><em>correct</em></strong>, <strong><em>efficient, </em></strong>and <strong><em>easy to implement.</em></strong></blockquote><h4>Correct</h4><p>If there is one thing to remember from this post, let it be this: You might very well be able to come up with an algorithm. One that solves the problem for the current input, or possible inputs you might think of. It doesn’t make it correct.</p><p>Correctness must be shown. It must be proved and demonstrated. We will come back to this in a bit. It can be scary to realize that usually, in the industry, a program that is right in most cases and does not slow down the application is regarded as acceptable. Even if a better solution for the same problem exists. It is only after it causes major issues (legal, performance,…), that the qualities listed above are revisited and enforced.</p><p>“Obviousness” is your enemy when it comes to “correctness”. Be wary of an algorithm that you want to say is <em>obviously </em>correct.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*OELedf3eyKbbh1C2aZPoLA.png" /><figcaption>The soldering order as prescribed by the “nearest-neighbor” algorithm</figcaption></figure><p>Back to our not-so-hypothetical problem. The image above shows a case where the algorithm is on-point! <strong>But…</strong> what if the first point was not the most left?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*GUSVzJmqgZaIafWuWqZKUA.png" /><figcaption>When the starting point is random. Not the optimal solution here</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*SpDJfUKJKSZTDhFI2XiMzA.png" /><figcaption>A purposefully devious input. Points are arranged in such a way that the solution jumps from left to right to left…</figcaption></figure><p>As can be seen, in the examples above, our algorithm doesn’t do a very good job all the time. You might interject and say: “Wait, all our problems come from the fact that the starting point is random. Let’s put a constraint that it always starts on the most left point.” Good point (pun intended), I had a similar thought. But then…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*vtdalBqTCe6Ycm0qmA9utw.png" /><figcaption>The “nearest-neighbor” algorithm is just… bad</figcaption></figure><p>So that’s it. This “nearest-neighbor” algorithm doesn’t cut it. Here again, you might say: “Except in very particular cases, the algorithm does a pretty good job… overall”. And I tend to agree. In the industry, this approach would be acceptable. It would be refined and made a little bit more robust, then pushed to production…</p><p>Until someone decides to make a product out of your code and state: “Guaranteed to always find the <strong>best </strong>path”. But that’s another story and another problem.</p><p>In summary, what we have here is an algorithm, albeit an incorrect one. <em>It follows a heuristic</em>.</p><blockquote>A heuristic usually does a good job at coming up with a solution. A good heuristic for the problem at hand, will get you as close as possible to the best solution.</blockquote><blockquote>It does <strong>not offer any guarantees </strong>that its solution is the best or how far from this best solution it is. It will be content with making an <strong>informed, educated guess </strong>about what that best solution could be.</blockquote><p>In short, it is not a correct algorithm, but it is one that in practice will give good enough results.</p><h4>Efficient</h4><blockquote>Efficiency refers to the time and space complexity of an algorithm</blockquote><p>This problem is actually famous. One for which there is no efficient, correct solution. It is known as the “<em>Traveling Salesman Problem</em>”.</p><p>As a matter of fact, to solve this correctly, you need to explore all possible paths and compute their lengths, then pick the shortest path, i.e the best solution. For a problem with 10 points, there are 10! possibilities. And problems with O(N!) time complexity are some of the worst to brute-force your way to a solution.</p><p>So, in practice, everybody would be happy to settle for a <strong>good </strong>heuristic. Yes, not all heuristics are created equal.</p><h4><strong>Easy to Implement</strong></h4><blockquote>Good algorithms are correct, efficient, and easy to implement.</blockquote><p>If, by some miracle, another algorithm of your creation could solve correctly and efficiently this well-known intractable problem but required tons of lines of code, hundreds of files… Let’s just say, it might not be worth it… depending on the case at hand.</p><h3>Heuristics. What are they?</h3><p>Let’s say, for some obscure reason, you were placed in unknown territory and asked to find the highest point of the land. Let’s also say that, for even more obscure reasons, you had to do it… blindfolded!</p><p>If you had all the time in the world, you could devise a way to map the land, exhaustively exploring each of its square meters. In the end, the map would tell you where that highest point would be.</p><p>If you didn’t have all that time, you would be content with finding a good enough solution as fast as possible. That could entail, identifying the direction with the highest slope from where you are initially, then moving in that direction. You would rinse and repeat until you got to <strong>a</strong> maximum.</p><p>Now, nothing tells you that you are at the highest point. But this solution is definitely better than where you started. You could even make the argument that given the resources at your disposal and constraints you were subjected to, this is good enough.</p><p><strong>That </strong>is a heuristic and a prime example of why they are important. It’s these shortcut we find to problems when finding the best, correct solution seems too difficult.</p><p>The literature identifies 5 main instances where using heuristics appears to make sense to <strong><em>humans</em></strong>:</p><ul><li><strong>When one is faced with too much information</strong>: Here exhaustively searching for the best solution is just not practical.</li><li><strong>When one is faced with very little information to make a decision</strong>: You are required to make a decision but you know nothing of the problem space or the consequences of your decision. One is forced to rely on previous experiences, rule of thumbs,… and hope for the best</li><li><strong>When the time allowed before making a decision is limited</strong>: Here also, exhaustively searching for the best solution is just not practical.</li><li><strong>When finding a good enough solution is… good enough</strong>: Maybe your application does not need to solve the equation and get to<strong> “π” </strong>as the answer. Your heuristic leads you to “3.14” and you are happy.</li><li><strong>When the appropriate heuristic happens to come to mind as one is looking for a solution.</strong></li></ul><p>More formally, <strong><em>computer scientists</em></strong> use heuristics when trying to solve hard problems. Those are problems whose solutions run in <em>super-polynomial</em> <em>time. </em>In essence, it takes a long time to find the solution for those problems.</p><p>The “<em>Traveling Salesman Problem</em>” is one of these problems. Finding the best solution for 4 points is near-instantaneous, finding the solution for 11 points can take 5 seconds, for 50 points it will take… forever — Well, not actually forever, but an insane amount of time. It’s bigger than anything we can conceive. In such cases, a good enough answer now within a few seconds is better than none for millenniums while the algorithm is bravely “wrestling” with this.</p><blockquote>A Heuristic is a problem solving framework rather than an algorithm to find a solution.</blockquote><blockquote>The Heuristic guides an algorithm in finding good choices. So, it does not need to exhaustively search the problem space for the best solution. It is a sacrifice of correctness and accuracy for efficiency.</blockquote><blockquote>Some heuristic can be quite advanced and integrate past experiences, learning from them or using them to predict policies for “better moves”. They are generally opinionated about where to go next in order to converge toward better solutions. They might use deterministic and stochastic components. Many of them are cleverly constructed to use landscape information and history for better selections.</blockquote><p>It is important to stress the fact that heuristics make assumptions. Therefore, the quality of solutions obtained with a heuristic will considerably depend on how much the problem you are trying to solve matches these assumptions. For example, there are instances where greedy algorithms will actually give you the exact, correct solution to a problem. For others ones, they can lead to bad, suboptimal solutions (Typically, it’s the problem of local vs global optimums)</p><h4>Some heuristics in the wild</h4><p><em>One way to come up with a heuristic is to consider how a human would tackle that problem. Humans do not always research all possible solutions before coming up with the best one. They do not like to waste unnecessary efforts and are pretty good at coming up with shortcuts that give good enough solutions.</em></p><p>Some heuristics in real life include:</p><ul><li><strong>Working Backward</strong>: When trying to derive a solution from the input is too difficult, one can try constructing a solution by starting from what the output should be and working backward.</li><li><strong>Solve a bigger problem, by solving its smaller parts</strong>: Combining the solution of the smaller problems is believed to bring a solution to the bigger one.</li></ul><p>Some heuristics in computer science:</p><ul><li><strong>Greedy Algorithms</strong>: These algorithms believe that making the best decisions now, to maximize some immediate reward, will lead to an overall solution that shadows the best solution.</li><li><strong>Local Search Methods</strong>: The algorithm will choose a somewhat arbitrary initial solution. It will then iteratively make some tweaks to it, thereby incrementally increasing the quality of the resulting solution.</li><li><strong>Genetic Algorithms</strong>: These are quite fascinating. They believe that principles from the <em>Darwinian Theory of Evolution</em> can be adopted by an algorithm. These will enable it to converge toward an approximation of the best solution. An initial generation of possible candidate solutions is generated and evaluated. The finest candidates are “reproduced” with small stochastic variations to mimic the “survival of the fittest”. This new generation is once again evaluated, and its best candidates reproduced. The process is repeated until the resulting solutions satisfy some criteria.</li><li><strong>Tabu Search Algorithms</strong>: As the algorithm works, it will dynamically partition the problem space into areas that are marked as “tabu”. These are areas that have already been processed or are believed to lead to bad solutions. The algorithm is then incentivized to look for solutions away from these “tabu” regions. These “tabu” regions will expand while the area that is believed to contain the solution shrinks around it.</li><li><strong>Simulated Annealing Algorithms</strong>: Here the algorithm will mimic the annealing process in metallurgy. It consists of cycles of controlled heating and cooling on a material to increase the size of its crystals and reduce their defects. In essence, a solution is chosen, then modified with a non-deterministic component (i.e “heating up” the system). This non-deterministic component causes lesser and lesser effects as the “temperature” goes down. This modification scheme generates multiple possible solutions. The first one that meets some criterion is chosen for the next cycle. The “temperature” of the system is then decreased. This, therefore, constrains future solutions to smaller and smaller regions around current solutions. And the cycle is repeated.</li></ul><p>That’s it for me. I hope you enjoyed it. Leave a comment if you feel like it. I’m always happy to engage with the community.</p><p>From a fellow problem solver.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb206252c500" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>