<?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 Peter Sels on Medium]]></title>
        <description><![CDATA[Stories by Peter Sels on Medium]]></description>
        <link>https://medium.com/@henk-celcius?source=rss-84f80ed927ed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*6bp5SPJ-RWkVEGIVpUkhIA.jpeg</url>
            <title>Stories by Peter Sels on Medium</title>
            <link>https://medium.com/@henk-celcius?source=rss-84f80ed927ed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:04:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@henk-celcius/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[A Mnemonic-less C-Mimicking Assembly Language]]></title>
            <link>https://henk-celcius.medium.com/a-mnemonic-less-c-mimicking-assembly-language-6f87bd5f8765?source=rss-84f80ed927ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f87bd5f8765</guid>
            <category><![CDATA[imec]]></category>
            <category><![CDATA[instruction-set]]></category>
            <category><![CDATA[fpga-design]]></category>
            <category><![CDATA[digital-design]]></category>
            <category><![CDATA[parser]]></category>
            <dc:creator><![CDATA[Peter Sels]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 10:41:04 GMT</pubDate>
            <atom:updated>2026-08-05T10:22:54.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*774uwraY6BWHmJSiKux5Rg.png" /><figcaption>Fugasm assembly instruction set overlayed on quite random electronics. ‘Courtesy’ of Open AI’s DALL-E.</figcaption></figure><p>Revisiting a self designed Processor Instruction Set. Are its back then innovative [1] Mnemonic-avoiding, [2] C-Mimicking and [3] source, computation destination instruction nature(s) still rare? Still relevant?</p><h3>1. Introduction</h3><p>In 1993, <a href="https://www.imec.be/">Imec</a> Leuven, Belgium asked us, my <a href="https://drive.google.com/file/d/1rfYI-C8jvqj0MUrEzXI-mPUcpbX5b3dH/view?usp=drive_link">Masters Thesis</a> mate <a href="https://www.linkedin.com/in/ramsesvalvekens">Ramses Valvekens</a> and <a href="https://www.linkedin.com/in/petersels">myself</a>, to add programmable logic to a CMOS based image chip they developed, called FUGA. Back then image chips in commercial camera’s: camcorders and picture camera’s where usually CCD based. The idea was that IMECs CMOS based image chips had a comparative advantage with respect to CCDs in that the CMOS technology allowed some intelligence to be put on the same chip, since logic is easily put on CMOS but not on a CCD chip. Back in 1993, this was a quite novel idea.</p><blockquote>Also, only much later, in retrospect, <a href="https://www.linkedin.com/in/bart-dierickx-a8a4703/?locale=nl_NL">Bart Dierickx</a>, the CMOS image chip inventor and designer of the FUGA series, thought that this project was probably one of the first to put a full processor as a soft core inside an <a href="https://en.wikipedia.org/wiki/Field-programmable_gate_array">FPGA</a>. This only became popular many years later.</blockquote><h3>2. The FUGA Camera Board</h3><p>IMEC developed a printed circuit board (PCB) that is best described by this specification page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mWAf-ZZIK-7rBxtK6Dt-w.png" /></figure><p>So from this, you see the Fuge chip has a x address of 8 bits and a y address of 8 bits. This means it has 256 on 256 pixels. It sends back an 8 bit grey level intensity. Note that the grey level is gray-code encoded. This is to avoid that during sampling the output, bits flip and wrong answers are received. It also means our FPGA logic needs to contain a gray encoding to normal binary encoding convertor.</p><h3>3. The Processor board</h3><p>We designed a board that was to contain all that expected logic into an FPGA. Of course, apart from the FPGA we needed some peripherals, like pins to program the FPGA via an <a href="http://www1.pldworld.com/@xilinx/html/technote/TOOL/MANUAL/15i_doc/alliance/hug/hug3_2.htm">Xilinx XChecker cable</a> from our PC, some external RAM, a BNC connector to feed the board with a clock, some debugging leds and 7 segment displays to show for example the program counter, a button to step through the program, a serial and parallel interface. So schematically, the board looked like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_LO-IH54xul_xXRmPornA.png" /></figure><p>We did not turn this board into a PCB but implemented it as a prototype board and wire wrapped it.</p><p>The FUGA chip sat on a separate board, discussed in the previous section. Interconnection between the two boards with a flat cable clicked onto the SC-FUGA connector show in the picture above.</p><p>These are two pictures of how our ptototype board looked in real life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EY7MuruhOiDwVcmM7tCMGw.png" /></figure><p>Yes, in black and white still. :) So this being the processor-board, we need to fill the FPGA on it with the processor and some interface logic to the peripherals on the board. The processor requires an instruction set.</p><h3>4. Processor Instruction Set Design</h3><p>Rather than adding some limited programmability, via some configurable parameters, or via some macros, we indeed went for the addition of a custom designed full processor.</p><p>This processor would then need to be able to:</p><ul><li>read any pixel from the image chip. (The chip had 256 random addressable rows and dito columns. It gave back an 8 bit word representing a grey value that was 0 at the blackest level and 255 at whitest level.</li><li>write to and read from some register set. (We chose b, c, d as 3 8 bit registers, so it could contain any grey level or 8 bit image chip address. Register ‘a’ was chosen as the larger word, so we could accumulate the grey values of a whole image into it, so all 2⁸ * 2⁸ = 2¹⁶ 8 bit words, so maximum the value of 2⁸ * 2⁸ * (2⁸ -1) &lt;= 2²⁴-1 in it. So it needed to be a 24 bits wide ‘accumulator’ register. It’s best to choose register ‘a’ for that because ‘accumulator’ start off with ‘a’. :)</li><li>write to and read from RAM. (We chose the RAM to be structured as a series of image structured portions. So you can apply a RAM address to it, like you can address the image chip. So there is an 8 bit xram and an 8 bit yram address, where you could for example store an entire image, so you could process an image ‘in-place’ in RAM, for example for edge detection or so. Then we added an 8 bit zram address and that then allowed you to have 256 images next to each other. Of course, one can consider the concatenated xram, yram, zram word as one full 24 word RAM address and without thinking about its division in 8 bit parts. :)</li><li>carry out addition and subtraction of gray values; addition for calculating averages, subtraction for comparison of intensities or calibration of images.</li><li>use fixed constants. A user may program something like b+= 2 or b+=5, say in a for loop. Then the constant 2 or 5 needs to come from somewhere. We designed a constant bank of 32 constants to provide for that. The assembler/compiler would have to pick up from the starting code, that if the programmer wrote b+=5, that a constant with contents 5 should be provided, say const9 and also that the line b+=5 would have to be replaced with b+=const9.</li><li>read a program from ROM. Yes, a program has to be stored somewhere. In fact, since we design the whole system in an FPGA, the ROM bits makes is a part of the bit string that is used to program the FPGA.</li><li>execute goto jumps based on no condition or on some conditions. We had chosen to always compare the ‘a’ regsiter with a comp(arator) register and provided jumps depending on equality, non-equality, and larger-or-equal and smaller-than-equal. Rather than inventing quite unintuitive <em>mnemonics</em>, as for instruction set design, was all the rage back then, and in fact still is, we wondered why, and found this better since more easily understood phrases like ‘if(acc!=comp)goto’ and if ‘(acc≤com)goto’ and such.</li><li>read in from and write to a parellel as well as serial interface</li><li>read in the setting from a DIP switch</li><li>write out an internal number to a a 2 7-segment displays</li></ul><p>So with all these requirements, and a lot of more fun tinkering and crafting we came to this as the instruction set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYt7Eg7kritrd5UH_SRt_Q.png" /><figcaption>Fugasm Instruction set on page 11² of our 1993–1994 Thesis at IMEC, Belgium</figcaption></figure><p>We called this assembly language ‘Fugasm’ as a contraction of FUGA, which was the name of the CMOS image sensor series developed at IMEC in the days and Asm as a contraction of or also commonly used file extension for Assembly language files.</p><p>As you can see, there is a division in two columns. A left part, which we call the <em>destination part</em>, and a right part, which we call the<em> source part</em>. Any full instruction is constructed from taking a left part, and a right part. So take b+=128-var3, then this will do b=b+128-var3, as if it was pure C code.</p><p>We were quite <em>satisfied</em> with this result, because:</p><blockquote>[1] to understand our Fugasm language, and programs written in it, you just need to know C. You do not need to learn any additional assembly language specific cryptic mnemonics. Questions arising for beginning programmers in any other, mnemonic based, assembly languages like, what was the mnemonic again for store: STO or STR?… I wonder why getting rid of menmonics was never done before. Was it a first? Why? Was it a last? Why?</blockquote><blockquote>[2] the fact that an instruction could be composed of any left column part with any right columns part, made that it had in fact about 2⁶ * 2⁶ = 2¹² = about 4096 possible instructions. (Some exceptions exist because of the not_used occurrences.) What instruction set has that variety?² And it’s not that you have to remember 4096 instructions, you just have to learn the left column and the right column and you’re done. So that’s only 128 things to remember, and they are very structured and each of them intuitive, meaning one can guess what their meaning is.</blockquote><p>Because we implemented the instruction design and the whole instruction decoding logic (in Xilinx XBLOX electronic schematics) needed for that in pretty much the same few days, we had both co-optimised at once. This led to things like: if you define a+= as 000100, it’s intuitive and nicely structured to define b+=, c+= and d+= as well as the sequential words 000101, 000110, 000111 and the decoding of the last two bits in these destination half instruction is straightforward. The prefix 0001 just means the result has to be added to some target register. The suffix of 2 buts just determines which register. So it is a nice separation of concerns and as a consequence, the decoding logic takes in as few bits as possible. Also, from the binary nature of these systems it makes a lot of sense to define 4 registers and not, say 3 or 5. Solving that puzzle optimally or at least efficiently was a lot of fun.</p><p>The whole exercise of instruction set definition was informed by marrying:</p><ul><li>what we had as peripherals (image sensor, serial/parallel port)</li><li>the FPGA internal XBLOX library components/resources (RAM (variables), ROM (constants)), multiplexers of n bits, buses of 2^n bits, the computation primitives (addition, subtraction, shifting left and right)</li><li>and what we had as programmability requirements from a user (‘software programmer’) perspective.</li></ul><p>This exercise proved to be intellectually and aesthetically satisfying and so was the result, for us, and we also hope, for you. Hence this article.</p><h3>5. Programming in the Fugasm Assembly language</h3><p>It really looks like programming in C as you will see from the next example program. The program in flow chart form is given in this figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n7nUPK-rJyV6Hy5ChAqM9w.png" /></figure><p>This program reads in the FUGA image. Depending on the mode, which is read from som on board DIP switches, it reads a raw image only, or it reads that multiple time and averages it (to reduce noise to signal ratio), or also subtracts the calibration image from it. A calibration image is made by directing the FUGA camera to an even grey surface. In every case, the resulting image is send over the serial port to a connected PC.</p><p>This C-like Fugasm code program looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XHENZXe8SVXAitxP-yA9yg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vBsPNnqYpdFkuvFsQc8TQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJ_8ovL0edexwNEOkBXfBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p3h4IF0VWZyT_fXkCK5ldQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wnYQ9RQDRXchKIGAaJSSZQ.png" /></figure><h3>6. The C-Compiler Mimicking Assembler</h3><p>The C-mimicking program above, composed by the user/programmer, is then automatically translated with the assembler to the binary code below.</p><p>For documentation, we automatically produce a header that says what source files the generated code has been produced with.</p><p>Note that a string like for example: 2#110110_100111# represents a Fugam instruction consisting of the destination 110110, meaning xfuga= and the source 100111, meaning const7, so this instruction assigns the value in constant 7 to the xfuga register.</p><p>For back-annotation we also add the original line the programmer has entered as a comments for its corresponding binary instruction.</p><p>This then gives the result below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6oQt6Sfeuql4gvHg_Edcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wNJDW_NJ1rMCnLACW8-aQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yelWh0eIE1tKPDdeIrykw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpNDYATXEdUNHYkm2bLjVw.png" /></figure><p>The constant numbers that the programmer uses directly in his code, together with the constant line numbers where labels are found, are collected and put into a file that is later processed into a ROM block in the design. The ROM description for this program is given here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLe9qwbA8O4AX22JU-YuBg.png" /></figure><p>Notice that the ROM block contains up to 32 8 bit words. All but the last one are used here by this program. Constant 7 has value 10000000 here, which the assembler has deduced from the programmer Fugasm statement xfuga = middle; and the preprocessor declaration #define const7 middle. :)</p><p>As documentation to the programmer, we defined the FUGASM language in a <a href="https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form">Backus Naur Form (BNF)</a> file as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FNWiOB_g5oAzSSIvUynKZg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sXEqrH7n0Enw7MYAdk9e2w.png" /></figure><p>This BNF file is only FUGASM language documentation for the programmer to read. We do not need a tool that parses it.</p><p>In the above program, you will have noticed that the programmer (me) also has added C/C++ like comments for readability in his code. The parser also has to be able to process this, well to ignore and skip this really. For this it needs a <a href="https://en.wikipedia.org/wiki/Finite-state_machine">‘finite state machine’ (FSM)</a> to remember that it is in comment or not in comment state. This looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JaGw5N3YQhrSrJZMu-vGmQ.png" /></figure><p>Apart from comment and non-comment states, some further states are defined to be able to track where the parser is inside [&lt;binary_number&gt;] strings.</p><p>We now designed a language and that assumes a processor that should execute programs in that language. Let’s design that processor.</p><h3>7. Schematic designs to fill the FPGA</h3><p>We used XBLOX primitives from the Xilinx library. XBLOX back in 1994 had the then novel feature that you could use primitives with a parameter specifying the bus width of inputs.</p><p>We show some examples here.</p><h4>7.1. Top Level Overview sheet</h4><p>The overview of the whole collection of interconnected self designed schematic blocks that we put in the FPGA looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S_82iW7RdPXUHyIn9eQcnw.png" /></figure><p>So we have the address busses DEST and SOURCE as well as the DATA bus connecting all main modules. These modules are:</p><ul><li>an ALU for computational tasks on data,</li><li>a CONTROL_UNIT containing a (program) ROM of 256 12 bit instruction words¹ that contains the program,</li><li>a CONSTANT_ROM for constants the programmer has used (either in code directly or as labels to jump to in code),</li><li>a VARIABLE_RAM that contains the registers (inside the FPGA)</li><li>a FUGA interface to read pixel intensities from the FUGA board connected to the flat cable</li><li>a RAM interface to read from and write to RAM chips external to the FPGA but still on the prototype board</li><li>serial_in and serial_out interfaces</li><li>parallel_in and parallel_out interfaces</li></ul><p>We select a few of these blocks to discuss.</p><h4>7.2. Controller sheet</h4><p>An interesting design part is the ‘controller’ sheet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w4BXvE7igaiN41DuctF7ZQ.png" /></figure><p>As one may expect, it shows how the program ‘COUNTER’ value is used as input into the program ROM (‘PROM’), so that the instruction comes out. One can see and appreciate that the 12 bit wide output ‘ADRESS’ is split via a ‘SLICE’ into a ‘SOURCE’ (6 bit wide) word and into an also 6 bit wide ‘DESTINATION’ word. Also, notice that the (loadable counter XBLOX module) called ‘COUNTER’ contains a ‘LOAD’ 1 bit signal and an 8 bit wide D_in port that can receive a program address and that this comes from a block we designed and called ‘IFGOTO’ block. This is of course the block that decides if a jump to another program line has to be made, in which case the program counter goes there instead of just incrementing with 1.</p><h4>7.3. Arithmetical Logical Unit (ALU)</h4><p>As defined by the desired instruction set, we wanted 4 registers a,b,c,d, where each is 8 bit wide, except for the register a wich we want to be 24 bits wide. A high level block diagram is given here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Ja4OPw8OQA-HWaZOfjyMw.png" /></figure><p>You will see the central newadder block which contains the real XBLOX addition primitive. It is a 24 bit based one since a is 24 bits wide. When 8 bit addition is done, only the lowest 8 bits are extracted from the 24 bit newadder result. You can see that the result is fed back to the input of the a, b, c, d registers and can be clocked in. Selection of the register defined in the source and destination instruction halves is done by the (‘control enable’) 1 bit signals: CE_a, CE_b, CE_c, C_d. Of course only 1 of them will be active at each time. There are decoded in the ‘address decoder’ from its input source and dest.</p><p>The actual implementation of this module in ‘Workview’, the application Xilinx provided for schematic entry design looks a bit more complex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ak_Tn94ccprC0py9pGjZ7g.png" /></figure><p>The separate Workview sheet, for the instruction decoding only, so one more hierarchy level down in the ‘design tree’ of blocks, looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fBwPS1LtLdChPhwiZ0M5A.png" /></figure><p>From this structure, one can appreciate that the source and destination words coming in on the left are decoded by quite simple combinatorial logic and sometimes some additional delaying flip flop or 2 to the 1 bit signals needed on the right. The fact that this logic is ‘simple’ hangs together with a ‘good/consistent/simply structured’ division of the instruction words into subgroups of bits, where each subgroup only steers a selection of functions, like addition or subtraction (the ‘ADD/SUB output signal), or the register selection (the one hot 4 output ‘chip enable’ bits: CE_D, CE_C, CE_B, CE_A) from 2 input bits.</p><h4>7.4. FPGA Pinout</h4><p>From all these blocks realised on the inside of the FPGA, results this pinout schema towards the rest of the components on the prototype board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHhGM0jUEj-tuKib5q19xg.png" /></figure><p>Assignment of the signals to the pin set available, was also a kind of a fun manual optimisation game. Concerns were to put signals on pins close to the peripherals of the FPGA the signals need to come from or go to. Some pins are reserved for VCC and GND.</p><p>This XC4010 FPGA had a ball grid array. Mounting it on a real PCB normally means that all soldering balls need to be melted at the same time and so this would mean advanced soldering method using an oven. Instead, we mounted it in a <a href="https://en.wikipedia.org/wiki/Zero_insertion_force">zero insertion force (ZIF) socket </a>which avoided that we needed to do any soldering at all.</p><h3>8. Conclusion</h3><p>The instruction set we designed, in my mind, had 3 quite innovative aspects:</p><ul><li>it avoided mnemonic abbreviations and adapted to more intuitive syntax</li><li>it mimicked the C-syntax (for example the use of the += operator) as such leveraging the biggest programmer community at the time</li><li>from the previous point automatically followed that it combined a source and destination part, resulting in a fetch from anywhere, potential computation and storage anywhere being done in 1 instead of typically two clock cycles</li></ul><p>During this 1993–1994 master in EE thesis, we learned system design, computer language design, instruction set design, finite state machine design, schematic entry, parser design and assembler and compiler design basics. Defining and testing all this up to a fully operational system was a lot fun back then, and fun again to revisit now, for old times’ sake. :)</p><p>The basic design principles are still valid of course, even if today, digital systems, GPUs, like cloud computing servers and AI systems are much larger, they all still use, the same primitives, probably excluding wire wrapping. ;)</p><p>2⁵ years after the facts, we want to thank Bart Dierickx and Ramses Valvekens again for this fun collaboration. :)</p><p>—</p><p>Epilogue:</p><p>Ramses and I later joined the digital ASIC design house <a href="http://easics.com/">Easics</a> (pronounce as ‘easy ks’, stands for ‘<strong>E</strong>ngineering <strong>ASIC</strong>s’), spin off of <a href="https://www.imec-int.com/en">IMEC</a>, Belgium. ‘<a href="https://www.staatsbladmonitor.be/bedrijfsfiche.html?ondernemingsnummer=0444501015#publicaties">Easics 1</a>’ was founded in 1995 by <a href="https://www.linkedin.com/in/janzegers/?originalSubdomain=be">Jan Zegers</a>, <a href="https://www.linkedin.com/in/jan-decaluwe-8401731/?originalSubdomain=be">Jan Decaluwe</a>, <a href="https://www.limburgstartup.be/nieuws/blooloc-verhoogt-kapitaal-met-22-miljoen-euro-voor-digitale-revolutie-in-de-logistiek/">Ivo Vandeweerdt</a> and <a href="https://www.linkedin.com/in/dirk-callaerts/?originalSubdomain=be">Dirk Calaerts</a>. Rather than using schematic design, Easics specialised in <a href="https://en.wikipedia.org/wiki/VHDL">VHDL</a> (<a href="https://en.wikipedia.org/wiki/Very_High_Speed_Integrated_Circuit_Program">VHSIC</a> hardware description language) based digital design services, implementing in both FPGAs and ASICs. Easics grew to a team of about 35 design engineers. In 2001, Easics was bought by <a href="https://semiengineering.com/entities/transwitch-corp/">Transwitch</a>. In 2004, Ramses and <a href="https://www.linkedin.com/in/steven-c-745746/">Steven Coenen</a> did a management buy out. ‘Easics 2’ grew again to a team of more than 40 digital design engineers. In 2024, Easics was bought by <a href="https://jobs.keysight.com/location-belgium">Keysight</a>.</p><p>—</p><p><em>Footnotes:</em></p><p>¹ <a href="https://www.computerworld.com/article/1563853/the-640k-quote-won-t-go-away-but-did-gates-really-say-it.html">“256 words should be enough for anyone!”</a> ;) Of course, the program ROM can be easily enlarged by changing the corresponding XC 4010 FPGA parameter value for it.</p><p>² Yes, you could downplay this argument by saying that other instruction sets typically do the same in 2 instructions what we do in 1 instruction, for example a load from memory and then an accumulation of that fetched value into a register. But the thing is that we also do these two things in one clock cycle, so it’s quite clock cycle efficient.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f87bd5f8765" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minimising Time to Rescue in the Beach Business with GPT4]]></title>
            <link>https://henk-celcius.medium.com/minimising-time-to-rescue-in-the-beach-business-with-gpt4-63df58fa420c?source=rss-84f80ed927ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/63df58fa420c</guid>
            <category><![CDATA[gpt-4]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[beach]]></category>
            <dc:creator><![CDATA[Peter Sels]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 09:30:17 GMT</pubDate>
            <atom:updated>2023-09-01T09:30:17.409Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I dialogued for 2 days with GPT 4 in </em><a href="https://chat.openai.com/share/c61447ac-becd-4065-b7b5-c53f00248223"><em>this session</em></a><em>. The results are the flawless mathematical derivations (!) and the fully working Python code (!) below in this article. 80% of code and derivations was GPT4 generated. I tweaked and curated and rewrote about 40% of that and added 20% of my own doing. As for the article’s English text itself, GPT4 could generate anything I asked, but I still wrote/rewrote most of it myself. </em><a href="https://www.instagram.com/donfrodo/"><em>donfrodo</em></a><em> supplied the pictures using </em><a href="https://www.midjourney.com/"><em>Midjourney</em></a><em>.</em></p><blockquote><em>This experiment is meant as an example case of how AI </em><a href="https://en.wikipedia.org/wiki/Large_language_model"><em>LLMs</em></a><em> and humans can collaborate and achieve correct, valuable and more appealing results faster compared to working alone. GPT4 is truly astounding in many areas: natural language comprehension and production, a high degree of reasoning, mathematical derivation, computer code understanding, production and manipulation.</em></blockquote><blockquote><em>GPT4 certainly passes the </em><a href="https://en.wikipedia.org/wiki/Turing_test"><em>Turing test</em></a><em> in the context of this article. Or rather, fails it! Indeed, the Turing test was originally formulated as “should be </em>indistinguishable<em> from a human”. Clearly, Turing, in his era, only expected </em>under<em>-performance and not </em>over-<em>performance of machines. But in the sense that GPT4&#39;s answers are clearly </em>better<em> and come </em>quicker<em> compared to a human respondent, its non-human nature is easily detected. Turing test failure is a plus here.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F_58x9VTpgR3KATsoK3S3g.png" /><figcaption><em>Drowning Damsel due to Digital Distraction. I</em>mage generated by <a href="https://www.instagram.com/donfrodo/"><em>donfrodo</em></a> using <a href="https://www.midjourney.com/"><em>Midjourney</em></a><em>.</em></figcaption></figure><h3>1. Beach Business Introduction (not GPT generated)</h3><p>At sea, a damsel is in distress. A lifeguard on the beach or already in the water wants to save her.</p><p>Always inclined to solve any problem to full optimality, the lifeguard realises that, given his different speeds on sand (higher) and in water (lower), the straight line from him to her is not always the quickest route.</p><p>He reasons he will spend less total time if he spends some more time running and some less time swimming, compared to that one straight line.</p><p>The point where to ideally transition from sand to water first has to be determined. He approaches the problem mathematically to determine the best strategy.</p><p>This is his story.</p><h3>2. Sand to Water Case</h3><h4>2.1 Deriving the Route and its Total Time (maths derivation was GPT4 generated)</h4><p>Given the scenario where the lifeguard would transition from sand to water, the total time taken can be derived based on the distance covered on sand and water, as well as their respective speeds.</p><p>Let’s assume the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/0*DhzpBkjIpEyscbme.png" /></figure><p>The time taken for the sand portion from (x1, y1) to (x3, 0) is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/0*C-8Xkl7P-8vBmxQN.png" /></figure><p>and for the water portion from (x3, 0) to (x2, y2):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/0*QTNAF6pNWwUvxng_.png" /></figure><p>The total time is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/0*4ZlL0i2-soxWQviZ.png" /></figure><h4>2.2 Derivation of the Derivative and its Roots (maths derivation was GPT4 generated</h4><p>By differentiating <em>Ttotal</em> with respect to <em>x</em>3 and setting the result to zero, one can find the optimal value of <em>x</em>3 that minimizes the total time.</p><p>Starting from:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*CcmVv4Nro_KpxM1D.png" /></figure><p>Multiplying through by the common denominator gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/0*4FxWBmY-OV3f6BaX.png" /></figure><p>Now, we’ll square both sides to eliminate the square roots:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/0*eiTeZL1xM1gYFjan.png" /></figure><p>Expanding both sides and equating them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*dOz1JTpg77KGtwz9.png" /></figure><p>Grouping terms by their power of <em>x</em>3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/0*LhLBzqvCs2xDyhPt.png" /></figure><p>From the above grouping, the coefficients are derived as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*0R1EZMjvOoO7EJ1N.png" /></figure><p>Putting it all together, we have the <em>quartic equation</em> in <em>x</em>3:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/0*w2hW-rPjAaQDI9uZ.png" /></figure><p>Given the complexity of quartic equations, finding its roots can be challenging, especially if it doesn’t factor conveniently. Hence, we employ numerical methods to find the optimal value of <em>x</em>3.</p><p>This can be seen in the python function find_optimal_x3 below, which calls the minimize function from the Python library scipy.optimize. So this results in a single variable optimisation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc21e0ae08fc123370dab8de9d94db69/href">https://medium.com/media/fc21e0ae08fc123370dab8de9d94db69/href</a></iframe><h4>2.3 Some Sand to Water Example Scenario’s (Python code to generate figures was GPT4 generated)</h4><p>Figure <a href="#fig:sand_to_water">1</a> displays some sand to water scenario’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LbsluPCllyk9UbBkm2nag.png" /><figcaption>Figure 1: Sand to Water Scenario’s. Determining Direct Dispatch to Deliverance</figcaption></figure><p>In columns 3 of figure 1, we assume the lifeguard can swim as quickly as he can run on the beach. In that case, the path with the least time is a straight line.</p><p>Compared to that scenario 3, in the two leftmost columns, we assume that the lifeguard runs faster than he can swim. The results is that for the least-time-path in those cases, he spends more time on the beach compared to the scenario 3 in columns 3.</p><p>In column 4, we assume the probably somewhat unrealistic case that our lifeguard swims faster than he runs. In that case he avoids spending too much time on the sand, where he is slower than in the water.</p><h3>3 Water to Water Case</h3><h4>3.1 Deriving the Routes and their Total Time</h4><h4>3.1.1 Direct Swim Scenario (latex for maths was GPT4 generated)</h4><p>Given the scenario where a person swims directly to the target point in the water, the time taken can be expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/0*rLjHaClIR7oB74PK.png" /></figure><p>Where <em>x</em>1, <em>y</em>1 are the coordinates of the starting point in water, <em>x</em>2, <em>y</em>2 are the coordinates of the target point in water, and <em>vwater</em> is the speed of the person in water. This time does not have to be optimised as it is not a function of any variable, rather a function of constants only. However, its time value will be compared to the time taken for another route, as described in the next section.</p><h4>3.1.2 Swim to Coast, then Run, then Swim Scenario (latex for maths was GPT4 generated)</h4><p>Given the scenario where a person first swims to the coast, runs on the sand, and then swims again to reach the target point, the total time taken for the total route from (x2, y2) to (x3, 0) to (x4, 0) to (0, y1) is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*aKMTljbibf8NT-Do.png" /></figure><p>where:</p><ul><li><em>x</em>1, <em>y</em>1 are the coordinates of the starting point in water.</li><li><em>x</em>2, <em>y</em>2 are the coordinates of the target point in water.</li><li><em>x</em>3 is the horizontal coordinate where the person exits the water onto the coast.</li><li><em>x</em>4 is the horizontal coordinate where the person enters the water again after running on the sand.</li><li><em>vsand</em> is the speed of the person on sand.</li><li><em>vwater</em> is the speed of the person in water.</li></ul><p>The optimization problem aims to find the values of <em>x</em>3 and <em>x</em>4 (where the person enters the water again) that minimize <em>Tcombined</em>. This problem can’t be easily solved symbolically, necessitating the use of numerical and here also <em>multivariable </em>optimization techniques. This can be seen in the python function find_optimal_x3_x4 below, which calls the minimize function from the Python library scipy.optimize on a vector x. This vector contains the 2 variables x3 and x4. So this results in a multivariable optimisation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9de1ebf4488f6abfa23f03b8c03171c1/href">https://medium.com/media/9de1ebf4488f6abfa23f03b8c03171c1/href</a></iframe><h4>3.2 Some Water to Water Example Scenario’s (Python code to generate figures was GPT4 generated)</h4><p>Figure <a href="#fig:water_to_water">2</a> displays some water to water scenario’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v09KeHWAynTUrl5riR3hjw.png" /><figcaption>Figure 2: Water to Water Scenario’s. Blueprinting Brisk Bridges to Bailout in the Beach Business.</figcaption></figure><p>In the left two columns of figure 2, the lifeguard’s running speed over sand is larger than his swimming speed in water, so he benefits from swimming to land, then running along the shoreline and then swimming the last bit to his damsel.</p><p>In the right two columns his swimming speed is assumed equal respectively larger than his running speed. In those cases, the indirect route going over the beach will avoid running any distance on the beach and x3 and x4 will be equal. This then means that the direct swimming route is the faster option.</p><h3>4. Python Code, 90% GPT 4 Generated</h3><p>The following python code implements all scenario’s and also produces the figures <a href="#fig:sand_to_water">1</a> and <a href="#fig:water_to_water">2</a> as output pdfs and pngs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/614219634de53b6e3dd36d38c6531adf/href">https://medium.com/media/614219634de53b6e3dd36d38c6531adf/href</a></iframe><h3>5. The Making of this Article</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*3Bzq9AsXM06YDiynlFaVrg.png" /><figcaption>Beach Business Buoyancy Battles, <em>I</em>mage generated by <a href="https://www.instagram.com/donfrodo/"><em>donfrodo</em></a> using <a href="https://www.midjourney.com/"><em>Midjourney</em></a></figcaption></figure><p>As mentioned, I used the OpenAI’s chatGPT website, configured with the GPT 4 model. I used <a href="https://chat.openai.com/share/c61447ac-becd-4065-b7b5-c53f00248223">this chat session</a> where you can follow all my prompts and each chat GPT4&#39;s answer.</p><p>Note that at least today on August 22th 2023, you need to pay 20 USD a month for a chatGPT Plus account. This account type allows you to also use chatGPT with the GPT 4 i.o. only the free GPT 3.5 model.</p><p>I could not do the mathematical derivation with GPT 3.5. For example, it made this derivation error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BrOZHJzHUZmloSPyzhm8fg.png" /><figcaption>Wrong derivation by GPT 3.5</figcaption></figure><p>and I could not resolve it prompting with GPT 3.5. GPT 4 also made a sign error once, but I could resolve it with some more prompts. See these more general <a href="https://openai.com/research/gpt-4">benchmarks comparison</a> between GTP 3.5 and GPT4.</p><p>Almost all LaTeX maths snippets were generated by chat GPT 4. I then pasted them in <a href="https://quicklatex.com/">https://quicklatex.com/</a> , pressed the render button there, and copy-pasted the generated image in medium article here.</p><p>The files: BeachBiz26.py, BeachBiz26.tex and compile_latex.sh can all be found in the git repo at: <a href="https://github.com/PeterSels/OnComputation/tree/master/BeachBiz">https://github.com/PeterSels/OnComputation/tree/master/BeachBiz</a></p><p>Figures 1 and 2 are generated by running: python BeachBiz26.py</p><p>A file BeachBiz.pdf, containing more or less the same as this article but in pdf form is generated by running: ./compile_latex.sh</p><p>Python code was pasted in this article via first making a gist from BeachBiz26.py on GitHub.</p><blockquote>As for the producing the code and maths derivations, given that I am more productive (I estimate by a factor 2 to 3 in time) using GPT4 than not using it, this way of producing code and maths is simply unstoppable. Forbidding it would be equivalent to protesting against gravity.</blockquote><blockquote>For generating the natural language in the article itself, GPT4 is helpful and did produce a story that is syntactically, semantically and grammar-wise correct, written in a coherent, balanced and consistent but neutral writing style. (I did not ask it for a particular style.) However, I still rewrote most of it to make it more attractive to human readers. That includes the structuring into sections and paragraphs.</blockquote><p>Peter Sels, August 22nd, 2023.</p><p>Copyright © 2023 <a href="https://www.logicallyyours.com/">Logically Yours BV</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63df58fa420c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing TensorFlow on an Intel Mac with AMD Radeon R9 M395 2 GB GPU and CPU versus GPU testing]]></title>
            <link>https://henk-celcius.medium.com/installing-tensorflow-on-an-intel-mac-with-amd-radeon-r9-m395-2-gb-gpu-cpu-versus-gpu-testing-ea70444f5258?source=rss-84f80ed927ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea70444f5258</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[machine-learning-python]]></category>
            <category><![CDATA[intel-macbook]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[gpu]]></category>
            <dc:creator><![CDATA[Peter Sels]]></dc:creator>
            <pubDate>Sat, 10 Sep 2022 11:36:29 GMT</pubDate>
            <atom:updated>2022-09-10T11:58:52.216Z</atom:updated>
            <content:encoded><![CDATA[<p>I have a 2015 Intel based iMac available and wonder how good its AMD Radeon GPU would be on machine learning tasks compared to its CPU. To fin out, we install Tensorflow on this iMac and run some CPU &amp; GPU tests.</p><h4>1. Download my Yaml file for conda</h4><p>I constructed a conda environment yaml file and published it here on Github for you to download. You can also download from Github this <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/TensorFlowMNistTest.py">TensorFlowMNistTest.py script</a>, (which is an evolved version of the code on <a href="https://caffeinedev.medium.com/how-to-install-tensorflow-on-m1-mac-8e9b91d93706">this page</a>). You will also need to download the <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/EagerCpuGpuConfig.py">EagerCpuGpuConfig.py</a> script which contains a class to make your Gpu visible or invisible to ML computations.</p><h4>2. How I generated the yaml file</h4><p>I generated this yaml file as follows:</p><pre>$ sw_vers -productVersion</pre><pre>11.6</pre><p>¹</p><p>From the very beginning of <a href="https://developer.apple.com/metal/tensorflow-plugin/">https://developer.apple.com/metal/tensorflow-plugin/</a> we learn we need at least OS X 12 for this tensorflow installation to work.</p><p>So I upgraded to 12.5.1 by using Apples software update (started by pressing the left upper apple icon on my screen and then ‘about this Mac’ and ‘software update’’ and following instructions. OS X version 12 is the minimum needed for the sequel. This then gave me:</p><pre>$ sw_vers -productVersion</pre><pre>12.5.1</pre><p>Ok. <a href="https://developer.apple.com/metal/tensorflow-plugin/">https://developer.apple.com/metal/tensorflow-plugin/</a> <strong>Step 1</strong>, mentions to use a virtual environment via venv, but we will do this via conda.</p><p>So go create a <a href="https://docs.conda.io/en/latest/">conda envrionment</a> that will shield installed python libraries from your general system as well as from other conda projects where you may prefer or have to stick to other version of the same libraries:</p><pre>$ conda create --name TensorFlowMacIntel python=3<br>$ conda activate TensorFlowMacIntel<br>$ (TensorFlowMacIntel) python -m pip install --upgrade pip<br>$ (TensorFlowMacIntel) python -m pip install tensorflow_datasets<br>$ (TensorFlowMacIntel) python -m pip install protobuf==3.19.4</pre><p>¹</p><p>You need to have at least python 3.8 so put python=3.8 if the above would have given you something lower than that.</p><p>The <a href="https://developer.apple.com/metal/tensorflow-plugin/">same page</a>, in <strong>Step 2</strong>, says that |”If using conda environment built against pre-macOS 11 SDK use, you should add the SYSTEM_VERSION_COMPAT=0 prefix”. I did build my conda env with OS X 11, and if I leave out the prefix, I get an error, so lets try this then:</p><pre>$ (TensorFlowMacIntel) python -m pip install -U pip<br>$ (TensorFlowMacIntel) SYSTEM_VERSION_COMPAT=0 python -m pip install tensorflow-macos</pre><p>this gave:</p><pre>(TensorFlowMacIntel) Dogmatix:TensorFlowM1 peter$ SYSTEM_VERSION_COMPAT=0 python -m pip install tensorflow-macos</pre><pre>Collecting tensorflow-macos</pre><pre>Downloading tensorflow_macos-2.9.2-cp38-cp38-macosx_11_0_x86_64.whl (237.5 MB)</pre><pre>━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 237.5/237.5 MB 4.1 MB/s eta 0:00:00</pre><pre>Requirement already satisfied: absl-py&gt;=1.0.0 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from tensorflow-macos) (1.2.0)<br>...<br>Requirement already satisfied: oauthlib&gt;=3.0.0 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from requests-oauthlib&gt;=0.7.0-&gt;google-auth-oauthlib&lt;0.5,&gt;=0.4.1-&gt;tensorboard&lt;2.10,&gt;=2.9-&gt;tensorflow-macos) (3.2.0)</pre><pre>Installing collected packages: tensorflow-macos</pre><pre>WARNING: The scripts estimator_ckpt_converter, import_pb_to_tensorboard, saved_model_cli, tensorboard, tf_upgrade_v2, tflite_convert, toco and toco_from_protos are installed in &#39;/Library/Frameworks/Python.framework/Versions/3.8/bin&#39; which is not on PATH.</pre><pre>Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.</pre><pre>Successfully installed tensorflow-macos-2.9.2</pre><pre>(TensorFlowMacIntel) Dogmatix:TensorFlowM1 peter$</pre><p>Ok, so this worked out fine.</p><p>The <a href="https://developer.apple.com/metal/tensorflow-plugin/">same page</a>, in <strong>Step 3</strong> mentions does not mention setting the same environment variable, but I needed to, so I did:</p><pre>(TensorFlowMacIntel) Dogmatix:TensorFlowM1 peter$ SYSTEM_VERSION_COMPAT=0 python -m pip install tensorflow-metal</pre><pre>Collecting tensorflow-metal</pre><pre>Downloading tensorflow_metal-0.5.0-cp38-cp38-macosx_11_0_x86_64.whl (1.5 MB)</pre><pre>━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.5/1.5 MB 8.7 MB/s eta 0:00:00</pre><pre>Requirement already satisfied: wheel~=0.35 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from tensorflow-metal) (0.37.1)</pre><pre>Requirement already satisfied: six~=1.15.0 in /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages (from tensorflow-metal) (1.15.0)</pre><pre>Installing collected packages: tensorflow-metal</pre><pre>Successfully installed tensorflow-metal-0.5.0</pre><pre>(TensorFlowMacIntel) Dogmatix:TensorFlowM1 peter$</pre><p>After the above, I then, from within the TensorFlowMacIntel, exported the environment to a yaml file via:</p><pre>$ (TensorFlowMacIntel) conda env export &gt; TensorFlowMacIntel.yml</pre><h4>3. Testing the GPU versus the CPU</h4><p>If you did not install the above mentioned tensorflow-macos or tensorflow-macos in section 2, and you run the below test, you will see that it does not detect the GPU and so the code still runs, regardless wether you disable or enable the GPU, but it will only execute on the CPU, so you will not notice any significant change in performance.</p><p>When you now download, from my GitHub repo, the 2 python files <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/TensorFlowMNistTest.py">TensorFlowMNistTest.py</a> and <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/EagerCpuGpuConfig.py">EagerCpuGpuConfig</a>.py, you can run the following</p><pre>$ (TensorFlowMacIntel) python TensorFlowMNistTest.py</pre><p>To see how much faster tensorflow runs on a GPU than on a CPU we ran 4 tests, where we varied switching the GPU on (by making it visible/invisible to tensorflow code) or off and switching a mode called ‘eager’ on or off. You switch these on line 9 via setting the booleans</p><pre>eagerly=False<br>disable_gpu_visibility=False</pre><p>in the file <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/TensorFlowMNistTest.py">TensorFlowMNistTest.py</a>. (Best leave disable_cpu_visibility to False though.)</p><p>The summary² of the output of the 4 runs is:</p><pre>---<br>disable_cpu_visibility = False<br>disable_gpu_visibility = False<br>eagerly = False<br>0:02:51.319595<br>---<br>disable_cpu_visibility = False<br>disable_gpu_visibility = False<br>eagerly = True<br>0:04:50.110275<br>---<br>disable_cpu_visibility = False<br>disable_gpu_visibility = True<br>eagerly = False<br>0:07:30.041130<br>---<br>disable_cpu_visibility = False<br>disable_gpu_visibility = True<br>eagerly = True<br>0:10:38.660720<br>---</pre><p>Putting these results in a <a href="https://docs.google.com/spreadsheets/d/14JPpZS8jYu_O54l7FMs0aKGlyzwpwylzxBojhI5Dfx8/edit#gid=0">google spreadsheet</a>, together with the experiments we did earlier on an <a href="https://henk-celcius.medium.com/installing-and-cpu-vs-gpu-testing-tensorflow-on-an-apple-mac-m1-arm-native-via-miniforge-90d49eaf05ea">Apple M1 Mac</a> and on a <a href="https://henk-celcius.medium.com/installing-tensorflow-on-a-wintel-machine-with-quadro-t1000-gpu-performance-comparison-with-and-c64b6c1b9cd1">Wintel machine with NVIDIA Quadro T1000 GPU</a>, gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukc-6-7tulDcdUMxbHoTpg.png" /><figcaption>Runtimes for 3 machines, for (eager, non eager) * (GPU, no GPU).</figcaption></figure><p>and making bar graphs of it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*isEJ4KmAsMmc__hjGN64NQ.png" /><figcaption>For the two most recent systems (Mac M1 from 2021 and Wintel with Quadro T1000 (2019), using their GPU improves speed by a bout a factor 4. For the older system (the Intel based iMac with AMD GPU from 2015), the GPU helps by a factor 3 in non-eager mode and 5 in eager mode.</figcaption></figure><p>shows that for the older iMac, the GPU helps by a factor 3 in non-eager mode and 5 in eager mode. It’s quite similar, on average, for the newer machines (running OS X or Windows), where mapping the tensorflow computations on the GPU rather than CPU gave a speedup of about a factor 4.</p><p><em>Footnotes</em>:</p><ol><li>The installation of tensorflow_datasets gave an error reporting a conflict with the, today, latest version of protobuf.</li></ol><pre>ERROR: pip&#39;s dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.</pre><pre>tensorflow 2.9.2 requires protobuf&lt;3.20,&gt;=3.9.2, but you have protobuf 3.20.1 which is incompatible.</pre><pre>tensorboard 2.9.1 requires protobuf&lt;3.20,&gt;=3.9.2, but you have protobuf 3.20.1 which is incompatible.</pre><p>This could be fixed by installing the version 3.19.4 of protobuf i.o. the latest, as follows:</p><pre>$ (TensorFlowMacIntel) python -m pip install protobuf==3.19.4</pre><pre>(TensorFlowMacIntel) Dogmatix:TensorFlowM1 peter$ python -m pip install protobuf==3.19.4<br>Collecting protobuf==3.19.4<br>Downloading protobuf-3.19.4-cp38-cp38-macosx_10_9_x86_64.whl (961 kB)<br>━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 961.7/961.7 kB 7.5 MB/s eta 0:00:00<br>Installing collected packages: protobuf<br>Attempting uninstall: protobuf<br>Found existing installation: protobuf 3.20.1<br>Uninstalling protobuf-3.20.1:<br>Successfully uninstalled protobuf-3.20.1<br>Successfully installed protobuf-3.19.4</pre><p>2. The logs of the 4 runs are on <a href="https://github.com/PeterSels/OnComputation/tree/master/TensorFlowM1">GitHub</a> as Maci7AmdRadeon*Eager*Gpu.log</p><p><em>Written by </em><a href="https://www.linkedin.com/in/petersels/"><em>Peter Sels</em></a><em> on Sep 10th 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea70444f5258" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing TensorFlow on a Wintel machine with Quadro T1000 GPU and CPU versus GPU Testing]]></title>
            <link>https://henk-celcius.medium.com/installing-tensorflow-on-a-wintel-machine-with-quadro-t1000-gpu-performance-comparison-with-and-c64b6c1b9cd1?source=rss-84f80ed927ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/c64b6c1b9cd1</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[nvidia-gpu]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[conda-environment]]></category>
            <dc:creator><![CDATA[Peter Sels]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 13:40:50 GMT</pubDate>
            <atom:updated>2022-09-10T12:00:24.602Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>A. Installation</strong></h3><p>This tutorial results in giving you my <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/windows_tensorflow_20220828.yml">conda environment file</a> for installing TensorFlow on Windows. An environment based on this file can also run programs addressing the GPU. The python script <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/TensorFlowMNistTest.py">here</a> also tells you how to let the GPU participate or not in the computations. (Note that before the conda stuff, you’d best already install the CUDA toolkit 11.7. See below for instructions.)</p><p>As usual, you can just make a conda environment with it by</p><pre>$ conda deactivate<br>$ conda env create --file=windows_tensorflow_20220828.yml --name=windows_tensorflow</pre><p>I explain here how I constructed this yaml file (and also the error messages I encountered on the way and their solutions, so that Google can bring you here to the solution).</p><p>With a first ‘plain vanilla’ installation of the packages tensor-flow, when running a TensorFlow test, I received the <strong>W</strong>arning (hence the ‘W’ prefix):</p><pre>W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library ‘cudart64_110.dll’; dlerror: cudart64_110.dll not found<br>I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.</pre><p>I have a Quadro T1000 GPU (<a href="https://www.nvidia.com/content/dam/en-zz/Solutions/design-visualization/productspage/quadro/quadro-desktop/proviz-print-nvidia-T1000-datasheet-us-nvidia-1670054-r4-web.pdf">which has 896 cuda cores</a>), which is about 56% of the performance of the top of the line RTX 3090 GPUs (<a href="https://www.nvidia.com/fr-be/geforce/graphics-cards/30-series/rtx-3090-3090ti/">which has 10496 cuda cores</a>) today as you can see from<a href="https://www.adhnk.com/?product_id=95676583_58"> this graph</a> here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9I4uAsbD02gya06BKkhF2A.png" /><figcaption>Performance of my Quadro GPU versus the RTX 3090 top of the line GPU.</figcaption></figure><p>NVIDIA gives performance numbers <a href="https://developer.nvidia.com/cuda-gpus">here</a>. So it’s worth solving this warning.</p><p>I could solve this by:</p><ul><li>downloading the CUDA toolkit 11.7 installer exe file cuda_11.7.1_windows_network.exe form from <a href="https://developer.nvidia.com/cuda-downloads?target_os=Windows&amp;target_arch=x86_64&amp;target_version=10&amp;target_type=exe_network">here</a>. Make the right selections for your system. I selected cuda-rt version 11.7 which was the most recent.</li><li>running it resulted in some screens saying some things were installed and some, due to absence of Visual Studio on my system, were not.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnbg7gvlkvEJzKuyD73kEw.png" /><figcaption>Some things not installed due to lack of a Visual Studio compiler on my system</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vTPRNDonYvjSyOpo07nVEg.png" /><figcaption>In the end, quite some components were installed.</figcaption></figure><ul><li>doing a system restart and</li><li>When running my TensorFlow test again, the warning about cuda-rt was gone. :)</li></ul><p>The next error was:</p><pre>tensorflow.python.framework.errors_impl.InvalidArgumentError: Multiple OpKernel registrations match NodeDef at the same priority</pre><p>After quite some googling and a few trials I found this ‘TensorFlow install via pip’-page <a href="https://www.tensorflow.org/install/pip">here</a>. It mentions</p><pre><strong>Caution:</strong> The current TensorFlow version, <strong>2.10</strong>, is the <strong>last</strong> TensorFlow release that will support GPU on native-Windows. Starting with TensorFlow <strong>2.11</strong>, you will need to install <a href="https://tensorflow.org/install/pip#windows-wsl2">TensorFlow in WSL2</a>, or install <strong>tensorflow_cpu</strong> and, optionally, try the <a href="https://github.com/microsoft/tensorflow-directml-plugin#tensorflow-directml-plugin-">TensorFlow-DirectML-Plugin</a>&quot;</pre><p>But we will for now ignore this warning and do what it says below:</p><pre>conda install -c conda-forge cudatoolkit=11.2 cudnn=8.1.0<br>python -m pip install tensorflow<br># Verify install:<br>python -c &quot;import tensorflow as tf; print(tf.config.list_physical_devices(&#39;GPU&#39;))&quot;</pre><p>All went well for me and the last line returns</p><pre>[PhysicalDevice(name=&#39;/physical_device:GPU:0&#39;, device_type=&#39;GPU&#39;)]</pre><p>so yes it finds the GPU now and we get rid of any errors/warnings. :)</p><h3><strong>B. Test TensorFlowMNistTest.py</strong></h3><p>Running again <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/TensorFlowMNistTest.py">our own test script</a> 4 times, once for <a href="https://www.tensorflow.org/guide/intro_to_graphs">eager mode</a> and once for non-eager mode, and for each: once with GPU made invisible and once with GPU made visible, gave as performance results.</p><pre>WinQuadroT1000EagerCpuNoGpu.log:    0:11:05.841665<br>WinQuadroT1000NotEagerCpuNoGpu.log: 0:07:03.279670<br>Wini7QuadroT1000EagerCpuGpu.log:    0:02:09.316872<br>Wini7QuadroT1000NotEagerCpuGpu.log: 0:01:22.671263</pre><p>In eager mode, switching on the GPU makes the fitting time go down from 11:05 to 2:09. In non-eager mode, switching on the GPU makes it go down from 7:03 to 1:22. So the GPU makes the execution time go down by about a factor 5.5.</p><h3><strong>C. Extra Comparison</strong></h3><p>We performed two extra installations and comparison benchmarks. One with the <a href="https://henk-celcius.medium.com/installing-and-cpu-vs-gpu-testing-tensorflow-on-an-apple-mac-m1-arm-native-via-miniforge-90d49eaf05ea">Apple M1 chip</a> and one with an older <a href="https://henk-celcius.medium.com/installing-tensorflow-on-an-intel-mac-with-amd-radeon-r9-m395-2-gb-gpu-cpu-versus-gpu-testing-ea70444f5258">Apple Intel iMac from 2015</a>. Runtimes for 3 machines, for (eager, non eager) * (GPU, no GPU) were:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LKmyBnT3Jfd6UT9a.png" /></figure><p>Making bar graphs of it gives</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/0*d-Fx1ZgrMT5VTsay.png" /></figure><p>For the two most recent systems (Mac M1 from 2021 and Wintel with Quadro T1000 (2019), using their GPU improves speed by a bout a factor 4. For the older system (the Intel based iMac with AMD GPU from 2015), the GPU helps by a factor 3 in non-eager mode and 5 in eager mode.</p><p>This shows that for the older iMac, the GPU helps by a factor 3 in non-eager mode and 5 in eager mode. It’s quite similar, on average, for the newer machines (running OS X or Windows).</p><p>We get that the M1 Max chip (with 2 performance, 2 efficiency CPU cores) and embedded GPU with 32 cores) is about twice as fast in all modes as the i7 with the Quadro T1000 GPU chip having 896 cuda cores.</p><p><em>Written by </em><a href="https://www.linkedin.com/in/petersels/"><em>Peter Sels</em></a><em> on Aug 28th 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c64b6c1b9cd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing TensorFlow on an Apple M1 (ARM native via Miniforge) and CPU versus GPU Testing]]></title>
            <link>https://henk-celcius.medium.com/installing-and-cpu-vs-gpu-testing-tensorflow-on-an-apple-mac-m1-arm-native-via-miniforge-90d49eaf05ea?source=rss-84f80ed927ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/90d49eaf05ea</guid>
            <category><![CDATA[machine-learning-python]]></category>
            <category><![CDATA[apple-m1-chip]]></category>
            <category><![CDATA[gpu]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[performance-testing]]></category>
            <dc:creator><![CDATA[Peter Sels]]></dc:creator>
            <pubDate>Sun, 28 Aug 2022 23:17:44 GMT</pubDate>
            <atom:updated>2022-09-10T11:59:48.425Z</atom:updated>
            <content:encoded><![CDATA[<p>The <em>relevance</em> of trying to install TensorFlow on an Apple Mac M1 is that:</p><ol><li>Googles <a href="https://www.tensorflow.org/">TensorFlow</a> machine learning library is a very flexible and widely used one</li><li>Tensorflow runs best on a high end GPU and the M1 contains a great GPU.</li></ol><p>On the latter, Apple used to insinuate on their website by the graphic mentioned in this <a href="https://www.macrumors.com/2022/03/17/m1-ultra-nvidia-rtx-3090-comparison/#:~:text=iPhone%2014%20Pro-,M1%20Ultra%20Doesn&#39;t%20Beat%20Out%20Nvidia&#39;s,3090%20GPU%20Despite%20Apple&#39;s%20Charts&amp;text=Despite%20Apple&#39;s%20claims%20and%20charts,testing%20performed%20by%20The%20Verge.">Macrumors article</a>, that the <a href="https://www.apple.com/benl/newsroom/2022/03/apple-unveils-m1-ultra-the-worlds-most-powerful-chip-for-a-personal-computer/">M1 Ultra</a> (the most powerful M1 GPU at the time of writing, 27 Aug 2022), has the same maximum performance as the most performant discrete graphics card around, the <a href="https://www.nvidia.com/fr-be/geforce/graphics-cards/30-series/rtx-3090-3090ti/">NVIDIA 3090 series</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmK9ixcLfOIxHL-NB-Rmhg.png" /><figcaption>The Highest-end discrete GPU curve here is in fact incomplete and in reality continues to higher performance than the M1 max performance, as evident from the next independent Geekbench 5 test results.</figcaption></figure><p>However, according to the same MacRumors page, the performance of the NVIDIA RTX 3090 GPU is found to be at least <a href="https://www.macrumors.com/2022/03/17/m1-ultra-nvidia-rtx-3090-comparison/#:~:text=iPhone%2014%20Pro-,M1%20Ultra%20Doesn&#39;t%20Beat%20Out%20Nvidia&#39;s,3090%20GPU%20Despite%20Apple&#39;s%20Charts&amp;text=Despite%20Apple&#39;s%20claims%20and%20charts,testing%20performed%20by%20The%20Verge.">2 times</a> that of the M1 Ultra in an independent Geekbench 5 test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hqtCi4W4IwK82zBa-Kt9Kw.png" /></figure><p>Nevertheless, the Mac Studio (Ultra) has almost 50% of the performance of the best discrete graphics card around, already embedded in your motherboard and that is an impressive feat.</p><p>According to the above bar chart, my MacBook Pro 14-inch with an M1 Max should have 30% of the RTX 3090 maximum performance.</p><p>So let’s get this GPU <em>beast</em> working!</p><p><em>There are</em> a few <em>tutorials</em> online on how to install TensorFlow on a Mac with an Apple ARM M1 chip (instead of an Intel one), <em>but</em> I had to piece about 6 of them together to make it work for my setup. This resulted in a publicly downloadable <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/apple_tensorflow_20220828.yml">apple_tensorflow_20220828.yml</a> file for conda environment creation, which you can simply install by:</p><pre>$ conda env create --file=apple_tensorflow_20220828.yml --name=apple_tensorflow</pre><p>If you want to know how I generated this file, read on.</p><p>The installation method depends on two <em>requirements</em> I had, and you may also have.</p><ul><li>I want to use native ARM code rather than the Rosetta x86 Intel to ARM translation layer on top, mimicking an Intel machine, since removing this extra layer may increase <em>performance </em>a bit, much needed for machine learning training and inference (and I am not sure if as of today, 27 Aug 2022, it’s even possible to get TensorFlow working via Rosetta on an M1.)</li><li>I want to <em>isolate</em> the environment from my other python projects, for which I use Anaconda. I am happy to use Miniforge as well, but I don’t want to touch all my other Anaconda projects where python packages are Intel based. <a href="https://www.youtube.com/watch?v=w2qlou7n7MA&amp;ab_channel=JeffHeaton">Turns out</a> you can run [Anaconda (or Miniconda)] and [Miniforge] next to each other on the same system after all. (See section C for details.) For the relation between conda, Anaconda vs. Miniconda and Minconda vs Miniforge, check these footnotes¹ ² ³.</li></ul><p>For the semi-hurried, I start in section A with my resulting installation instructions and, in section B, show a test proving that it works (for me). In section C, I mention other installation tutorials for the same, but where I got blocked when trying them out, how I sometimes got no solution and needed a workaround, and sometimes did find a direct solution.</p><h3><strong>A. Installing Tensorflow and Prerequisites</strong></h3><p>We assume below that everything happens in an OS X Terminal application set to the bash shell.</p><p><strong>1. update your MacOS</strong></p><pre>$ sw_vers -productVersion</pre><pre>12.5.1</pre><p>is what I get on 27th Aug 2022. For Tensorflow, you need at least version 11 (Big Sur). If you have version 10 or lower, you must upgrade to a version ≥ 11 from the macOS App Store.</p><p><strong>2. Install / update x-code tools</strong></p><pre>$ xcode-select -install</pre><p><strong>3. Miniforge</strong></p><p>Miniforge allows you to install apple arm packages via miniconda.</p><p>From <a href="https://github.com/conda-forge/miniforge#miniforge3">https://github.com/conda-forge/miniforge#miniforge3</a>, download <a href="https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh">Miniforge3-MacOSX-arm64</a></p><pre>$ cd ~/Downloads<br>$ chmod a+x Miniforge3-MacOSX-arm64.sh<br>$ ./Miniforge3-MacOSX-arm64.sh</pre><p>for me, since I accepted the default settings in the dialogue that followed, this installed miniforge3 in /Users/peter/miniforge3.</p><p>So check this with:</p><pre>$ which conda</pre><pre>/Users/peter/miniforge3/condabin/conda</pre><p>So conda points to the Miniconda one inside the Miniforge3 directory rather than my Anaconda conda one inside /Users/peter/opt/anaconda3. If want to use the anaconda one I can use ~/opt/anaconda3/condabin/conda explicitly or create two aliases via:</p><pre>$ alias anaconda=~/opt/anaconda3/bin/conda<br>$ alias miniforge=~/miniforge3/condabin/conda</pre><p>so that I can use Anaconda and Miniforge now. A somewhat cleaner approach to obtain the same is mentioned in section C.3 below.</p><p><strong>4. Setup a conda environment</strong></p><p>You can download my <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/apple_tensorflow_20220828.yml">apple_tensorflow_20220828.yml</a> file from this <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/apple_tensorflow_20220828.yml">GitHub link</a>. Then, make sure that conda refers to Miniforge (as in ~/miniforge3/condabin/conda or so) and do:</p><pre>$ conda deactivate<br>$ conda env create --file=apple_tensorflow_20220828.yml --name=apple_tensorflow</pre><p>Apart from some comments, the above, when successful, should end in:</p><pre>Preparing transaction: done<br>Verifying transaction: done<br>Executing transaction: done</pre><pre>Retrieving notices: …working… done</pre><p>You can then check:</p><pre>$ conda env list</pre><p>and</p><pre>/Users/peter/miniforge3/envs/apple_tensorflow</pre><p>should be a line appearing in the list returned. Do</p><pre>$ conda activate apple_tensorflow</pre><p>The next three commands you can skip since the yml file above now includes these 2 pip libs.</p><pre>(apple_tensorflow) $ python3 -m pip install --upgrade pip<br>(apple_tensorflow) $ pip install tensorflow-macos<br>(apple_tensorflow) $ pip install tensorflow-metal</pre><p>If, when running an ML program, you would encounter problems with protobuf, as in:</p><pre>tensorflow-metadata 1.10.0 requires protobuf&lt;4,&gt;=3.13, but you have protobuf 4.21.5 which is incompatible.</pre><pre>tensorflow-macos 2.9.2 requires protobuf.20,&gt;=3.9.2, but you have protobuf 4.21.5 which is incompatible.</pre><p>, do the following:</p><pre>(apple_tensorflow) $ pip install protobuf==3.19.4</pre><p>and rerun.</p><p>Now your TensorFlow environment installation is complete and you will want to test it.</p><h3>B. Testing Tensorflow</h3><p><strong>1. Further install requirements</strong></p><p>In the same conda environment “apple_tensorflow”, activated by</p><pre>$ conda activate apple_tensorflow</pre><p>and you should not see an additional (apple_tensorflow) in your shell prompt. This incidates you are ‘iside’ the conda environment with this name. We now additionally install for testing purposes:</p><pre>(apple_tensorflow) $ pip install pandas<br>(apple_tensorflow) $ pip install tensorflow_datasets</pre><p><strong>2. Test TensorFlow</strong></p><p>As a “hello world” test of TensorFlow, we use the MNIST problem. That’s part of the tensorflow_datasets you just installed. It is a bunch of raster pictures of hand-written digits from 0 to 9. We will try to categorise and then recognise them. This is sort of the Hello World problem of machine learning. A nice, very visual as well as full mathematical explanation of this problem and its solution method is on <a href="http://colah.github.io/posts/2014-10-Visualizing-MNIST/">this page</a> by “chrisolah”. A more hands on interactive Jupyter tutorial for it is <a href="https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/quickstart/beginner.ipynb#scrollTo=y7suUbJXVLqP">here</a> at Google.</p><p>You can now download from Github this <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/TensorFlowMNistTest.py">TensorFlowMNistTest.py script</a>, (which is an evolved version of the code on <a href="https://caffeinedev.medium.com/how-to-install-tensorflow-on-m1-mac-8e9b91d93706">this page</a>). You will also need to download the <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/EagerCpuGpuConfig.py">EagerCpuGpuConfig.py</a> script which contains a class to make your Gpu visible or invisible to ML computations.</p><p>The <a href="https://github.com/PeterSels/OnComputation/blob/master/TensorFlowM1/TensorFlowMNistTest.py">TensorFlowMNistTest.py</a> code splits the MNIST data into train and test data. Then, it builds a tensorflow keras model and compiles it. Lastly it performs 12 epochs of [fitting the model to the test data and validation] ending up with 99.07% validation accuracy. This means that, theoretically, there is also 99.07% probability that in <a href="https://www.xilinx.com/applications/ai-inference/difference-between-deep-learning-training-and-inference.html#:~:text=In%20the%20training%20phase%2C%20a,data%20to%20produce%20actionable%20results."><em>inference</em></a>, the next received digit will be mapped to the correct category from 0 to 9.</p><p>Save these two python files in the same directory. Then do:</p><pre>(apple_tensorflow)$ python TensorFlowMnistTest.py</pre><p>This should lead to a computation taking between 1 and 5 minutes on an Apple M1 Max. Collecting the outputs for 4 cases: (switching run eagerly on/off) * (switching GPU visible/invisible) by the 2 booleans ‘disable_gpu_visibility’ and ‘eagerly’ in the code, we get the 4 log files as shown on GitHub <a href="https://github.com/PeterSels/OnComputation/tree/master/TensorFlowM1">here</a>. As timings for the ‘fit’ function, so for the training we get:</p><pre>MacM1MaxEagerCpuNoGpu.log:          0:05:13.037244<br>MacM1MaxEagerCpuGpu.log:            0:01:33.897871<br>So 3.4 times faster with than without GPU.</pre><pre>MacM1MaxNotEagerCpuNoGpu.log:       0:03:58.723621<br>MacM1MaxNotEagerCpuGpu.log:         0:00:51.107395<br>So 4.6 times faster with than without GPU.</pre><p>These time savings of a factor 4 on the Apple M1 when including the GPU are pretty impressive. For larger problems, further speedup could be sought by <a href="https://alex-vaith.medium.com/this-is-why-you-want-to-consider-an-egpu-for-deep-learning-on-your-mobile-work-station-a26dc9ed8673">plugging in an external GPU via thunderbolt3</a>. Both on Linux and on MacOs, one can <a href="https://developer.nvidia.com/blog/accelerating-machine-learning-on-a-linux-laptop-with-an-external-gpu/">get this to work</a>. Note that on a Mac, at the time of writing, <a href="https://developer.apple.com/metal/tensorflow-plugin/">this Apple developer page on tensorflow-metal</a> warns that more than one GPU is not supported. So one cannot distribute the work over more than 1 GPU yet via metal. Another option is of course to use the services of <a href="https://geekflare.com/best-cloud-gpu-platforms/">GPU heavy cloud computers</a> tuned to perform best at that and likely be cost efficient at the same time.</p><p>So I hope the above writeup has saved you time. Please let me know if it did and also any typos you’d have found.</p><p>You may want to check out some other <a href="https://www.tensorflow.org/tutorials/customization/custom_training_walkthrough">Tensorflow tutorials</a> now.</p><h3>C. Inspiring ReferenceTutorials</h3><p>Thanks to all who published inspiring tutorials before. These are:</p><ol><li><a href="https://caffeinedev.medium.com/how-to-install-tensorflow-on-m1-mac-8e9b91d93706">https://caffeinedev.medium.com/how-to-install-tensorflow-on-m1-mac-8e9b91d93706</a> from Prabhat Suma Sahu was the first one I found, but I did <br>the miniforge installation via</li></ol><pre>$ git clone <a href="https://github.com/conda-forge/miniforge">https://github.com/conda-forge/miniforge</a><br>$ build_miniforge_osx.sh</pre><p>which did not work, since it saw my anaconda installation and stopped right there with:</p><pre>ERROR: File or directory already exists: ‘/Users/peter/conda’<br>If you want to update an existing installation, use the -u option.<br>$</pre><p>2. Then I found Prabhats <a href="https://www.youtube.com/watch?v=bLYKwBZZg-Q&amp;ab_channel=CaffeineDev">video</a> and at minute 1:00 he showed to instead download the script. That download also resulted in a Miniforge3-MacOSX-arm64.sh file, but did run to completion.</p><p>3. Jeff Heaton’s different <a href="https://www.youtube.com/watch?v=5DgWvU0p2bk&amp;ab_channel=JeffHeaton">video</a>s telling me how to install Miniforge and selecting the arm i.o intel version. He also after talking on installing Miniforge and TensorFlow on the M1 in this <a href="https://www.youtube.com/watch?v=w2qlou7n7MA&amp;ab_channel=JeffHeaton">video</a>, at minute 14 starts on the topic of running Anaconda and Miniconda on one machine next to each other.</p><p>Let me summarise this for you.</p><p>Basically, you can install anaconda (or Miniconda) on your Apple for your projects where you do not need the ARM level instructions and just want to work at the Intel level (with Rosetta implicitly below) for maximum compatibility with, say your colleagues who are still on Intel machines. Also there are of course still more python libraries available for the x86 Intel platform than for the Apple M1 platform.</p><p>You can also, before or after Anaconda (or Miniconda) installation, install Miniforge (see above for instructions). So, say you have installed both.</p><p>Say you have Anaconda installed in /Users/peter/opt/anaconda3. The conda executable then typically is at /Users/peter/opt/anaconda3/bin/conda. Then do</p><pre>$ cd ~/opt/anaconda3/bin<br>$ ./conda init</pre><p>Note that the ./ in the last command is important, since this calls the conda in the local directory rather than the (possible other/Miniforge) conda found in the PATH system environment variable. This last command generates a .bash_profile script (or a .zshrc script if you use the zsh i.o. bash) in your home directory (which are called when you start a new bash respectively zsh shell). This script looks like</p><pre># &gt;&gt;&gt; conda initialize &gt;&gt;&gt;<br># !! Contents within this block are managed by &#39;conda init&#39; !!<br>__conda_setup=&quot;$(&#39;/Users/peter/opt/anaconda3/bin/conda&#39; &#39;shell.bash&#39; &#39;hook&#39; 2&gt; /dev/null)&quot;</pre><pre>if [ $? -eq 0 ]; then<br>    eval &quot;$__conda_setup&quot;<br>else<br>    if [ -f &quot;/Users/peter/opt/anaconda3/etc/profile.d/conda.sh&quot; ]; then<br>        . &quot;/Users/peter/opt/anaconda3/etc/profile.d/conda.sh&quot;<br>    else<br>        export PATH=&quot;/Users/peter/opt/anaconda3/bin:$PATH&quot;<br>    fi<br>fi<br>unset __conda_setup<br># &lt;&lt;&lt; conda initialize &lt;&lt;&lt;</pre><p>and it just maps the command “conda” to anaconda. This is something we want to keep under a separately callable command. So copy it as such</p><pre>$ cd ~<br>$ cp bash_profile start_anaconda.sh<br># chmod a+x start_anaconda.sh</pre><p>Now do the same for Miniforge, so</p><pre>$ cd ~/miniforge3/condabin<br>$ ./conda init</pre><p>Again, don’t forget the ./!</p><p>This generates/overwrites the ~/.bash_profile file which you then copy as in</p><pre>$ cd ~<br>$ cp bash_profile start_miniforge.sh<br># chmod a+x start_miniforge.sh</pre><p>You now have 2 scripts. You can use the following to switch towards your Intel x86 based conda projects by doing:</p><pre>$ source ~/start_anaconda.sh</pre><p>and the next command to switch towards your ARM M1 based conda projects by doing:</p><pre>$ source ~/start_miniforge.sh</pre><p>So you can run more than one shell with each a project with different target architecture next to each other, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNYGvxZb-U34pJzliTJPEg.png" /><figcaption>Anaconda Intel base project in one shell</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JUL6MHDiXIx4u-eFtnPeMw.png" /><figcaption>Miniforge ARM Apple M1 base project in another shell</figcaption></figure><p>By the ‘miniforge3’ or ‘anaconda3’ substring in the environment path, you can see with which conda tool you should activate the environment. Note that both conda tools show their own environments but also the environments of the other tool. If you try to activate a Miniforge environment with Anaconda, Anaconda won’t let you and gives a clear error message, as you can see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xaDQqbcWd90kTzukVAd0Aw.png" /><figcaption>Anaconda won’t activate a Miniforge environment. The environment is a Miniforge created one, so naturally, you should activate it with Miniforge.</figcaption></figure><p>The same is true for trying to open an Anaconda environment with Miniforge.</p><p>4. This github tensorflow issue 153 <a href="https://github.com/apple/tensorflow_macos/issues/153">page</a> explaining the procedure, up to the point I got an “ERROR not a supported wheel on this platform”.</p><p>5. This <a href="https://stackoverflow.com/questions/70221643/got-stuck-trying-to-install-tensorflow-on-mac-m1">page</a> for seeing other people also having problems with the error:</p><pre>ERROR: tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl is not a supported wheel on this platform</pre><p>strangely had no solution to it, but made me realise that just avoiding specifying specific wheel (.whl) files and doing</p><pre>$ pip install tensorflow-macos</pre><p>solved this problem.</p><p>6. A reminder on <a href="https://developer.apple.com/forums/thread/683757">this Apple developer forum page</a> to ensure to first do</p><pre>$ python3 -m pip install --upgrade pip</pre><p>before pip installing tensorflow-macos was a time saver too.</p><h4>D. Extra Comparison with both a Wintel and a Mac Intel Machine</h4><p>We also installed TensorFlow and ran the same program on an Intel based machine with an NVIDIA GPU as well as with a Mac Intel machine and described the processes <a href="https://henk-celcius.medium.com/installing-tensorflow-on-a-wintel-machine-with-quadro-t1000-gpu-performance-comparison-with-and-c64b6c1b9cd1">here</a> and <a href="https://henk-celcius.medium.com/installing-tensorflow-on-an-intel-mac-with-amd-radeon-r9-m395-2-gb-gpu-cpu-versus-gpu-testing-ea70444f5258">here</a>. Runtimes for 3 machines, for (eager, non eager) * (GPU, no GPU) are</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BLUl8rKF2KORPq82.png" /><figcaption>Runtimes for 3 machines, for (eager, non eager) * (GPU, no GPU).</figcaption></figure><p>In bar graphs this gives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*isEJ4KmAsMmc__hjGN64NQ.png" /><figcaption>For the two most recent systems (Mac M1 from 2021 and Wintel with Quadro T1000 (2019), using their GPU improves speed by a bout a factor 4. For the older system (the Intel based iMac with AMD GPU from 2015), the GPU helps by a factor 3 in non-eager mode and 5 in eager mode.</figcaption></figure><p>We get that the 2021 M1 Max chip (with 2 performance, 2 efficiency CPU cores) and embedded GPU with 32 cores) is about twice as fast in all modes as the 2019 Wintel i7 when considering CPUs. As for the executions on GPUs, the time reduction is about 30%. Compared to the Intel Mac from 2015, the CPU time reduction is about a factor 2 and the GPU time reduction about a factor 2 in all modes.</p><p><em>Footnotes</em>:</p><ol><li><a href="https://docs.conda.io/en/latest/">Conda</a> is an open source environment and package manager. <a href="https://docs.conda.io/en/latest/miniconda.html">Miniconda</a> is a free installer for Conda, Python, and a few other useful packages. <a href="https://docs.anaconda.com/anacondaorg/faq/">Anaconda</a> is also a package manager that has a much larger number of packages that you can install. <a href="https://rc-docs.northeastern.edu/en/latest/software/conda.html">Reference</a></li><li>Should I use Anaconda or Miniconda? See this <a href="https://docs.conda.io/projects/conda/en/latest/user-guide/install/download.html#anaconda-or-miniconda">docs.conda.io page</a>.</li><li><strong>miniforge</strong> is the community (conda-forge) driven minimalistic conda installer. Subsequent package installations come thus from conda-forge channel. <strong>miniconda</strong> is the Anaconda (company) driven minimalistic conda installer. Subsequent package installations come from the anaconda channels (default or otherwise). <a href="https://stackoverflow.com/questions/60532678/what-is-the-difference-between-miniconda-and-miniforge#:~:text=miniforge%20is%20the%20community%20(conda,channels%20(default%20or%20otherwise).">Reference</a>. Miniforge is applicable here because it provides packages <a href="https://pypi.org/project/tensorflow-macos/">tensorflow-macos</a> and <a href="https://pypi.org/project/tensorflow-metal/">tensorflow-metal</a> to get the most out of the M1 chip at ARM level.</li></ol><p><em>Written by </em><a href="https://www.linkedin.com/in/petersels/"><em>Peter Sels</em></a><em> on Aug 27th 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90d49eaf05ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Achieving Quantum Advantage at Solving Super Sudokus with D-Wave]]></title>
            <link>https://medium.com/data-science/achieving-quantum-advantage-at-solving-super-sudokus-with-d-wave-a7d2ae97d534?source=rss-84f80ed927ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7d2ae97d534</guid>
            <category><![CDATA[computation]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[sudoku-solver]]></category>
            <category><![CDATA[quantum-supremacy]]></category>
            <category><![CDATA[quantum-advantage]]></category>
            <dc:creator><![CDATA[Peter Sels]]></dc:creator>
            <pubDate>Sat, 04 Sep 2021 16:46:23 GMT</pubDate>
            <atom:updated>2021-09-06T15:18:22.225Z</atom:updated>
            <content:encoded><![CDATA[<h4>Of Sudokus, Humans, Classical and Quantum Computers</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejGFj1coYSeEYx-Vop7nFw.jpeg" /><figcaption>Fig 1: The central part of the D-Wave annealing quantum computer, not cooled down to 15 mK in this picture. <a href="https://www.dwavesys.com/company/media-resources/">Media courtesy of D-Wave.</a></figcaption></figure><h3>Of Sudokus, Humans, Classical and Quantum Computers</h3><p>Sudokus are puzzles <a href="https://time.com/4078049/seizure-sudoku-puzzles/">some people enjoy solving manually</a>. It’s a 9x9 (or (3*3)*(3*3)) puzzle, where in each of the squares, you are supposed to fill out a number from 1 to 9. Each row and column as well as each of the marked 3x3 sub-squares can only contain each number from 1 to 9 once.</p><p>The most trained humans solve the 9x9 version in a few minutes, by trial and error, or in computer science terms, by a backtracking algorithm.</p><p>Some people prefer to let computers solve sudokus. However, computers find traditional (3*3)*(3*3) Sudokus laughably easy. With a classical Mixed Integer Programming approach these are typically solved in about 15 ms. To increase the challenge, we considered larger (n*n)*(n*n) for n &gt;=4, ‘super’ or ‘meta’ sudokus. When n gets bigger, (n*n)*(n*n) gets bigger at a much faster rate. So at n around 6, 7, 8 classical computers start to struggle, meaning they need hours or days to solve such a sudoku.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5PixoDabM7RpFQ24NskoVg.png" /><figcaption>Fig 2. A 9*9 (=(3*3) * (3*3)) sudoku is destined for humans, to keep them occupied for some minutes. At 15ms typical solving times, it represents no challenge for classical computers, so we scale them up in size drastically, like to this (7*7) * (7*7) Super Sudoku and then put classical and quantum computers at work to solve them.</figcaption></figure><p>This is where, potentially, quantum computers could perform better.</p><p>Researching that question is the topic of this article.</p><h3>What is Quantum Computation?</h3><p>Thanks to the quantum phenomena (1) <a href="https://en.wikipedia.org/wiki/Quantum_superposition"><em>superposition</em></a> (unlike classical bits that are either 1 or 0 at any time, a quantum bit or <em>qubit</em> can have two states at a time (yes, that’s weird!)) and (2) <a href="https://en.wikipedia.org/wiki/Quantum_entanglement"><em>entanglement</em></a> (multiple qubits at a distance can have guaranteed the same or the opposite state at the same time (‘spooky action at a distance’ said Einstein, yes, weird again!)), quantum computers can try multiple potential solutions at a time and so can be faster at it than classical computers that have to go through each, be it <em>educated</em> guess sequentially.</p><p>So far for the quantum computation theory. But has it been demonstrated in practice yet? You can read <a href="https://en.wikipedia.org/wiki/Quantum_supremacy">here</a> and <a href="https://pubsonline.informs.org/do/10.1287/LYTX.2021.06.02/full/">here</a> that the answer to the question of ‘<em>quantum supremacy’</em> more modestly called ‘<em>quantum advantage</em>’ is still subject to controversy.</p><h3>Why Sudokus?</h3><p>To pitch classical versus quantum computers on a concrete problem, we took the sudoku puzzle because (1) it is the most widely known optimisation problem around and (2) it is easy to scale up to arbitrary large and so arbitrary difficult versions so that an advantage on either system, classical or quantum, if at all present, can be blown up to arbitrarily large proportions.</p><p>The relevance of solving sudokus in an automated or even optimally fast way, to the world at large, with all its <a href="https://en.wikipedia.org/wiki/List_of_global_issues">serious problems</a>, may look futile. However, sudokus are just one instance of a large class of problems called ‘optimisation problems’ (more specifically, <a href="https://en.wikipedia.org/wiki/Integer_programming">Mixed Integer Programming</a> or ‘<em>MIP</em>’ problems). In that class, more practically relevant problems reside, like <a href="https://en.wikipedia.org/wiki/Supply_chain_optimization">supply chain optimisation problems</a>, <a href="https://www.sciencedirect.com/science/article/abs/pii/S0191261515002684">train schedule optimisation problems</a>, <a href="https://en.wikipedia.org/wiki/Nurse_scheduling_problem">nurse scheduling problems</a>, <a href="https://www.cired-repository.org/bitstream/handle/20.500.12455/327/CIRED%202019%20-%201158.pdf?isAllowed=y&amp;sequence=1">automated energy market trading problems</a> and more. Today, solving some of these problems can take hours or days on classical computers and so, prevent their application in real time, as well as consume large amounts of electricity. Some think that, soon, or already today, quantum computers could/can save time and energy in solving these problems.</p><p>So let’s get to our challenge now.</p><h3>1. We solved Super Sudokus on a Classical Computer</h3><p>As mentioned, with a classical MIP approach, solving times rise quickly with n getting larger. The model used and the calculation times we obtained, are reported in <a href="https://henk-celcius.medium.com/supersudoku-b5f0419c220">this article</a> from March 2020, for the Sudoku sizes n in [1, .. 7]. We redid the experiments, now for n in [1,..8], with an updated version of the MIP solver Gurobi, v9.1.0. The newly experienced solver times are given in Table 1 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Sx71VHyTyI5NUfTH5q-XQ.png" /><figcaption>Table 1: The calculation times we got per Sudoku case from our Gurobi MIP model implementations on a classical computer. 1e99 stands for no result yet. model_build times are small. model solve times dominate. The phases time is the sum of both and so the total duration. The top half shows cases without any pre-filled squares, while the bottom half show cases with some pre-filled squares. These calculation times will be compared with times of calculation on the D-Wave Quantum Annealing machine in table 2 below. We ran the same cases on both systems.</figcaption></figure><p>The top half of Table 1 shows Sudokus without any squares having preset values. So the solver has maximal freedom, and any accidental classical versus quantum bias due to ‘specifically hard/easy square value choosing’ can be avoided.</p><p>In the MIP model, the solver has to decide on the 0 or 1 value of exactly n⁶ bits and also must take care that 4 types of constraints are satisfied, each of them occurring n⁴ times. (See below for the model variables and constraints that will make this clear.) This is why the time in the solve_model column increases quickly with increasing n.</p><p>The lower half of Table 1 reports calculation times for sudokus of the same sizes, but with some squares having pre-filled values. Compared with no preset values above, this is sometimes harder (e.g. for n=6) but sometimes easier (e.g. for n=7) and sometimes extremely hard. Yes, after 80 hours there was no result yet while for the case with no pre-filled squares case for n=8 it really only took 6s, no reporting mistake there!</p><h3>2. We Solved Super Sudokus on Quantum Computers</h3><p>We took a Quantum Computing course from IBM and one from D-Wave and the D-Wave implementation suite of hardware (and software) very clearly looked most promising, the main factor being that D-Wave chips using the <a href="https://en.wikipedia.org/wiki/Quantum_annealing#D-Wave_implementations">quantum annealing model</a>, contain up to 5000 qubits while the IBM, Google and other quantum computers which use the <a href="https://en.wikipedia.org/wiki/Quantum_logic_gate">quantum gate model</a> are at around 50 to 60 qubits.</p><p>We then looked around if people had attacked the Meta-Sudoku problem before us, and a few had.</p><p>2.0 Prior Work vs Our Work Here</p><p>2.0.1 Online Code From D-Wave: Works up to Sudokus of size (3*3)*(3*3)</p><p>D-Wave itself has published code online at <a href="https://github.com/dwave-examples/sudoku">https://github.com/dwave-examples/sudoku</a>. We tried this out and it correctly solves a (3*3)*(3*3) sudoku case that is given in the supplied <a href="https://github.com/dwave-examples/sudoku/blob/master/problem.txt">problem.txt</a> file. The code is written in a way that depends on the parameter n, so it can theoretically solve any (n*n)*(n*n) sudoku. However, when we tried it out for n&gt;3, it quite consistently returned invalid solutions.</p><p>2.0.2 Article explaining Quantum Supremacy compared to Classical Simulated Annealing on Sudokus of size (2*2)*(2*2)</p><p>At <a href="https://towardsdatascience.com/solving-sudoku-with-a-quantum-power-up-5bb4f64f3944">https://towardsdatascience.com/solving-sudoku-with-a-quantum-power-up-5bb4f64f3944</a>, Julian Hatski described how quantum annealing on a D-Wave pure quantum (so QPU, and non-hybrid) machine is faster by about a factor of 5 than a certain classical simulated annealing algorithm on a (2*2)*(2*2) sudoku. He experienced, as did we, that the standard (3*3)*(3*3) sudoku cannot be automatically embedded yet on a QPU.</p><p>2.0.3. Article showing an Experiment with a 4x4 Sudoku</p><p><a href="https://medium.com/mit-6-s089-intro-to-quantum-computing/quantum-sudoku-solver-d8d6844b82d1">This Medium article</a> by Eyan Fosythe explains how a Sudoku with 16 squares (so a (2*2)*(2*2) one) can be solved with a quantum computer based on the gate model. The solution returned is not always valid and scaling it up to larger sudokus is currently impossible due to lack of more qubits in quantum computers based on that model. Eyan mentions that the classical complexity of a sudoku with m undecided squares is of order O(N^m) and a non-trivial theoretical result that quantum computing <a href="https://www.academia.edu/39751312/Solving_Sudoku_Game_Using_Quantum_Computation">has been shown</a> to be of complexity order O(log(n)), so demonstrating exponential speedup. Note that it would not depend on m at all! Academic publications <a href="https://www.academia.edu/39751312/Solving_Sudoku_Game_Using_Quantum_Computation">here</a> and <a href="https://epljournal.edpsciences.org/articles/epl/abs/2019/22/epl19934/epl19934.html">here</a> show the same practical results for boards of at most 16 squares.</p><p>2.0.4 This article: Scaling up and Using Hybrid Solver, Comparing to MIP Gurobi solving times</p><p>We intend to use D-Wave systems for larger Sudokus, up to (8*8)*(8*8) and to compare solving times to what we got on classical computers with Mixed Integer Programming (MIP) solvers. We use <a href="https://www.gurobi.com/">Gurobi</a>, which in our experiments, was <a href="https://henk-celcius.medium.com/supersudoku-b5f0419c220">the fastest available solver for this kind of problems</a>. There may be algorithms dedicated to solve Sudokus that get to results quicker than Gurobi with its algorithms dedicated to solve the general class of MIP problems, but they require a lot of development time. We think comparing a general Quantum solver (with QUBO models) to a general classical solver (with MIP models) is the most fair one from the following viewpoints.</p><p>(1) The <em>development time</em> of classical MIP models and quantum QUBO algorithms is similar (if you use the newest D-Wave ocean libraries with add_variable, add_linear_constraint).</p><p>(2) The <em>financial cost</em> of use is similar (classical 1 PC, 10 minutes of ‘cloud’ quantum time during the D-Wave course at 700 USD for the course).</p><p>(3) So if the above (1) and (2) are similar and the <em>time to solution</em> is better for quantum than classical, then there is a very practical and concrete <em>quantum advantage</em>.</p><p><em>2.1 Converting MIP constraints to Objective Function terms of a QUBO: General Principle</em></p><p>We have to cast the Sudoku MIP model into its Quadratic Unconstrained Binary Optimisation (QUBO) equivalent model form, which is the format needed to be able to program a <a href="https://www.dwavesys.com/">d-wave</a> <a href="https://docs.dwavesys.com/docs/latest/c_gs_2.html">quantum annealing</a> machine.</p><p>2.1.1 Performing the Conversion Algebra</p><p>The QUBO format allows only an objective (function) and, unlike a MIP model, does not directly allow constraints. Constraints can be converted into terms of the objective function via the well known principle of <a href="https://en.wikipedia.org/wiki/Lagrange_multiplier">Lagrange multipliers</a>. So a say linear constraint f(<strong>b</strong>)=c, with <strong>b</strong> a vector of some of the binary variables in the MIP problem, is converted to a term 𝜆 (f(<strong>b</strong>)-c)². 𝜆 is a weight and can be chosen higher than the value of other terms in the objective, when the minimisation of (f(<strong>b</strong>)-c)² (so consequently, the near-satisfaction of f(<strong>b</strong>)=c) is more important than the minimisation of other objective function terms.</p><p>Working out the expression (f(<strong>b</strong>)-c)², when f(<strong>b</strong>) is linear in each b in <strong>b</strong> is easy. To save time, effort and avoid mistakes, one can use <a href="https://www.wolframalpha.com/">Wolfram Alpha</a> for that. For example, the constraint b1+b2+b3=1 converts to (b1+b2+b3-1)² and can be expanded by WolframAlpha by this <a href="https://www.wolframalpha.com/input/?i=%28b1+%2B+b2+%2B+b3+-+1%29%5E2">link</a>. This returns the expanded form of the expression: b1² + b2² +b3² + 2 b1 b2 + 2 b1 b3 + 2 b2 b3 -2 b1 -2 b2 -2 b3+ 1.</p><p>Now, because any binary value b squared is equal to the binary variable b itself (since 1²=1 and 0²=0), we can simplify this down to (2 b1 b2 + 2 b1 b3 + 2 b2 b3) +(-b1-b2-b3) + 1, and one can see that this expression is composed of quadratic terms in the binary variable cross terms plus linear terms in the binary variables.</p><p>For generality, note that also constraints that are inequalities i.o. equalities, so of the form f(<strong>b</strong>) ≤ c can be converted to f(<strong>b</strong>) + c’ * b’ = c with b’ a newly introduced binary variable, and can then be converted to an objective function term (f(<strong>b</strong>)+ c’ * b’ -c)², which can be worked out similarly to an expression consisting of linear terms and cross product terms and then be converted to a QUBO problem with one new and fresh variable b’.</p><p>So any linear constraint in a MIP problem can be converted into linear and quadratic terms in the objective function of its QUBO form.</p><p><em>2.1.2 Constructing the QUBO matrix</em></p><p>The quantum computer needs a QUBO in the form of a matrix. (This is in fact similar to the MPS format from the early days of MIP solver APIs.) If q is the amount of qubits used in the QUBO problem, the QUBO matrix is of dimension q*q. Its diagonal contains the coefficients of the linear terms bi and the upper right triangle contains the coefficients of the terms bi bj, where i&lt;j. (In fact one can also supply a symmetric matrix, where the i&gt;j elements will be added to the i&lt;j matrix elements before the D-Wave machine consumes it.)</p><p>Now, with the understanding of this QUBO matrix encoding, loosely formulated, the physical workings of a QUBO based quantum annealing computer are as follows. Nature in general, and so also the physics of the quantum system strives for minimal energy, which corresponds to minimising the objective function. A positive QUBO coefficient wants the binary (+bi) or binary product (+bi * bj) with this coefficient to be zero since the whole objective represents energy of the encoded system and will be minimised, while a negative coefficient will push the thing following (bi or bi * bj) to be 1. Coefficients that are larger than others will push harder for their terms than these other terms are pushed. As such (1) individual terms (of shape bi, so on the diagonal) can be pushed up or down, and cross terms (bi * bj, off-diagonal) (representing constraints) can pushed up or down, and the relevant importance can be ‘weighted’.</p><p>More formally, the following expression representing the objective function is minimised.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPUvRVP6_SG9cnl9Rh-h0Q.png" /><figcaption>The energy function of the quantum annealing machine, also called the ‘Hamiltonian’. This is the expression that ‘quantum <em>nature</em>’ will minimise for us. bi are the quantum bits (qubits), cii (ci) are the on diagonal QUBO elements and cij are the off diagonal QUBO matrix elements. So the ‘c’ coefficients form the ‘quantum program’ and the ‘b’ form the quantum qubit hardware.</figcaption></figure><p>‘I’ is the set of qubit indices. So #(I) is the number of qubits in the problem, which is n⁶. The bi are the qubits, the value of which has to be determined. The ci and cij are the fixed coefficients. The QUBO matrix consists of the ci and cij constants, representing the encoded problem.</p><p>Remember that the MIP objective and each constraint in the MIP problem is transformed, as described above, in an expression that contributes to the cii and cij values. Per expression, weights can be chosen.</p><p>The question can arise whether, per constraint, correct weights can always be found, and it seems that it has been proven that this is not the case. However, in practice, it seems that for quite some problems, reaching satisfaction of all constraints can be attained by some experimenting with these weights. For the sudokus for n≤7 without pre-filled squares, we found out that this works out fine with all weights (Lagrange parameter values) of all constraints set equal. For the cases with pre-filled squares, we had to set the weights of the fixed squares satisfaction constraints to a higher number than the weight of all the other constraints for a n in [1,2] on a QPU and do the opposite for n in [3,..7] on a hybrid D-Wave system. Figuring this out takes experimentation time and this is something that is not needed with a classical MIP solver where constraints don’t need weights specified by the user.</p><p><em>2.2 Converting MIP constraints to Objective Function terms of a QUBO: Sudoku Application</em></p><p>Summarized, we get for the MIP model for a #(R) rows * #(C) columns-sized Sudoku to be filled out with the #(N) numbers from N=[1..#N], where #N=#R=#C and D=#(S) where D²=#N:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1uZONrhh3jN26zgmN7oRg.png" /><figcaption>A Super Sudoku MIP Model, directly solvable by MIP solvers like Gurobi on classical computers. It needs to be converted to a QUBO model for the D-Wave Quantum Annealing model</figcaption></figure><p>The top 3 constraints together ensure that each of the numbers in N only occurs once per row and column. The fourth constraint enforces uniqueness of each number in N occurs only once per subsquare. The last constraint imposes the preset values per square, if there are any.</p><p>For the sub-board constraint, in a standard sudoku D=3 and S=[0,1,2].</p><p>For the preset squares, f(r,c) is a function that maps some (row,column) indices to the value that square should contain. Not all rows and squares will have preset values, since that would be too easy to solve. dom(f(r,c)) is the domain of f, so the set of (r,c) couples for which we have preset values. For the quantum version, the model only contains binaries and the last constraint is omitted. The integer values (n+1) to fill in the squares are (trivially) computed post-optimisation in a classical way.</p><p>Note that the indices of b here are still relatively simple formulae thanks to the fact of having offset 0 for rows and columns.</p><p>For the top 4 constraints, we can see that we have n⁴ (with n=3 for a classical 9*9 Sudoku) of each type because #(R)=#(C)=#(N)=#(S)*#(S)=n and for example for the first type, we have a number of #(R)*#(C)=n²*n² of them. So in total we have 4 n⁴ constraints, excluding the square-preset constraints.</p><p>We can indeed see that all the above constraints are convertible to QUBO form with the general principles described in section 2.1.</p><p>After applying these rules in a pretty mechanical way, which is reflected by the following Python code, we arrived at our QUBO model. We believe it the process described above applied to a sudoku will be clear from the comments in the code.</p><p>2.3 Python code constructing the QUBO</p><p>The below code contains all functions to solve Sudokus both classically and quantumly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd8c3aac8067fd9840bde04832ffed1f/href">https://medium.com/media/bd8c3aac8067fd9840bde04832ffed1f/href</a></iframe><p>See the fully executable (and executed) notebook at <a href="https://gist.github.com/PeterSels/0ef625b0340598fde4f2f2b6f3a8e5d6">https://gist.github.com/PeterSels/0ef625b0340598fde4f2f2b6f3a8e5d6</a></p><p>All cases executed split into 4 categories: (without/with preset squares) * (with Gurobi/with D-Wave). To keep code size and execution times small and modular, we put each of these 4 cases in a separate notebook that includes the above notebook via the command %run QuantumSudokuLib.py.</p><p><strong>(1) No Pre-filled Squares, Classical Gurobi:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f92aa8f8df7bf91c269c0206e1cb4fee/href">https://medium.com/media/f92aa8f8df7bf91c269c0206e1cb4fee/href</a></iframe><p>For the full gist of the test runs, so including both code and test result output, see <a href="https://gist.github.com/PeterSels/139f8477133c4604dcac8399e231788e">https://gist.github.com/PeterSels/139f8477133c4604dcac8399e231788e</a> .</p><p>We could run all the n in [1,..8] experiments here.</p><p><strong>(2) No Pre-filled Squares, Quantum D-Wave</strong></p><p>See <a href="https://gist.github.com/PeterSels/8364118a8f3d1275a69eafe290ff1d96">https://gist.github.com/PeterSels/8364118a8f3d1275a69eafe290ff1d96</a> for the notebook gist of the test runs.</p><p>For this case, we could do our experiments for n in [1..5], but not redo our n in [6, 7] experiments we ran earlier. We ran out of quantum time on our account.</p><p>But we rely on our output log of Python code (prior to plugging it in a notebook). We refer to these 3 logs here. The code in the notebook should regenerate similar results if sufficient quantum time is available.</p><p><strong>Our logs for n=6, no preset squares, quantum</strong></p><p>We published the whole log <a href="https://github.com/PeterSels/OnComputation/blob/master/QuantumSudoku/QuantumDwaveHybridSolveOfSudokuDim6WithoutPresetSquaresIn22Min5Sec.log">here on GitHub</a> so that you can verify that it is correct. The summary is this:</p><pre>(ocean) $ time python helper_functions.py sudokuDim6.json dwave<br>...<br>is_correct check done.<br>Sudoku correctly solved. :)<br>tests: [&#39;solver&#39;] done<br>real    22m4.531s<br>user    0m20.908s<br>sys     0m2.179s<br>(ocean) $</pre><p>So one can see from “real 22m4.531s”, that this took just over 22 minutes for n=6. The “Sudoku correctly solved. :)” indicates that the solution returned is checked (on a classical computer) and indeed valid.</p><p>We did the experiment again, again for n=6 and achieved a valid solution again in 22 minutes 50 seconds. The full log is present <a href="https://github.com/PeterSels/OnComputation/blob/master/QuantumSudoku/QuantumDwaveHybridSolveOfSudokuDim6WithoutPresetSquaresIn22Min50Sec.log">here on GitHub</a>, with summary:</p><pre>(ocean) $ time python helper_functions.py sudokuDim6.json dwave<br>...<br>is_correct check done.<br>Sudoku correctly solved. :)<br>tests: [&#39;solver&#39;] done<br>real    22m20.279s<br>user    0m23.123s<br>sys     0m2.560s<br>(ocean) $</pre><p><strong>Our log for n=7, no preset squares, quantum</strong></p><p>The full log is <a href="https://github.com/PeterSels/OnComputation/blob/master/QuantumSudoku/QuantumDwaveHybridSolveOfSudokuDim7WithoutPresetSquaresIn44Min29Sec.log">here on GitHub</a>, with summary:</p><pre>(ocean) $ time python helper_functions.py sudokuDim7.json dwave<br>...<br>Sudoku correctly solved. :)<br>tests: [&#39;solver&#39;] done<br>real    44m28.992s<br>user    1m27.995s<br>sys     0m7.025s<br>(ocean) $</pre><p>So the “real 44m28.992s” indicates it took 44 and a half minutes for n=7. The “Sudoku correctly solved. :)” indicates that the solution returned is checked (on a classical computer) and indeed valid.</p><p>We also had an older experiment for n=8. For that one, after (only!) 20 minutes and 50 seconds, we received an invalid sudoku solution from the hybrid method. Note that this is not a mistake in hardware or software, but the (sometimes multiple) solutions returned by D-Wave systems are solutions with low energy but it might not always be the one with the absolutely lowest energy, since the physical process of quantum sampling is a <em>stochastic</em> (and so a non-deterministic) one. ¹ A solution with an energy that is not the absolutely minimal one, corresponds to one where some <em>objective function terms</em> will <em>not</em> be totally <em>minimised (to zero)</em>, corresponding to ‘<em>constraints</em>’ that are ‘<em>slightly violated</em>’.</p><p>A remedy to get around this issue of invalid solutions is to readout multiple times in one run or to rerun the whole process. However, we ran through our D-Wave quantum developer and training time budgets to do just this.</p><p><strong>(3) Some Pre-filled Squares, Classical Gurobi:</strong></p><p>See <a href="https://gist.github.com/PeterSels/104002759f94ea45c1dd8684d98f1d27">https://gist.github.com/PeterSels/104002759f94ea45c1dd8684d98f1d27</a> for the notebook gist of the test runs.</p><p>We could run all the n in [1,..7] experiments here. But the n=8 case gave no result yet even after 80 hours.</p><p><strong>(4) Some Pre-filled Squares, Quantum D-Wave</strong></p><p>See <a href="https://gist.github.com/PeterSels/ff076c92e8d006ae95d4605ab818a0ef">https://gist.github.com/PeterSels/ff076c92e8d006ae95d4605ab818a0ef</a> for the notebook gist of the test runs.</p><p>We could run the cases n in [1..5], but for n in [6,7,8], we ran out of quantum time on our accounts.</p><p>2.4. Fitting/Embedding the QUBO on a D-Wave system</p><p>Our MIP model as well as our quantum QUBO model use n⁶ (qu)bits for a sudoku of (n*n)*(n*n) squares. This is the case because for each square, we need a number of between 1 and n*n. So we construct a full (n*n)*(n*n) sudoku-plane for each number N in 1 to n*n that holds a boolean set to true in a particular square if the number N is decided to appear in that position in the final sudoku. So, since 4⁶ = 4096, a QPU with 5000 qubits should be able to hold all 4096 qubits for a Sudoku of size (4*4)*(4*4) and certainly one of size (3*3)*(3*3), which only requires 3⁶ = 729 qubits. However the function that has to find the embedding of the problem instance graph onto the D-Wave quantum chip graph seems to fail at that, which is why we have to use the D-Wave hybrid method for n≥3.</p><p><em>2.5 Results from our Quantum Sudoku Experiments</em></p><p>Quantum calculation times for the same range of sudoku sizes as for the classical cases are shown in the below table in column ‘D-Wave total (s). Note the ‘QPU’ (for pure Quantum Processing Unit, for n in [1,2]) and the ‘Hybrid’ for n≥3 for an approach where the problem is decomposed and was then mapped to a combination of classical and quantum computers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6ZowVb40UZ3PrMNbDm-FA.png" /><figcaption>Table 2: The calculation times we got per Sudoku case from our D-Wave QUBO model implementations on the quantum and hybrid systems from D-Wave. 1e99 stands for no result yet. model_build times and find_embedding times are small. model solve times dominate. The 3 phases time is the sum of those three columns and so the total duration. The top half shows cases without any pre-filled squares, while the bottom half show cases with some pre-filled squares. These calculation times are compared with times from running Gurobi on a classical machine in table 1 above. We ran the same cases.</figcaption></figure><p>For each value of n, the total D-Wave time is the sum of the columns model_build, find_embedding and model_solve. Most notably is that at low values of n the quantum solver is slower and for n ≥ 6 it gets faster. The quantum calculation time reduction starts there. At n=6, we reach a time reduction of 31.2% and at n=7 one of 82.9%, a clear and large <em>quantum advantage</em>.</p><p>We report the files where you can verify the results we obtained in table 3 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5aIFezZtTYaIvs5RSrw7A.png" /><figcaption>Table 3: This table shows the file or files per case in which it was implemented. All files can be found and downloaded from GitHub.</figcaption></figure><h3>3. Classical vs. Quantum Time Visualised</h3><p>To get a better feel for proportions, we put our results into some charts in the Figure below. The left two charts have linear time in seconds on the vertical axis, and the right pair has a logarithmic time scale on the vertical axis. The top half represents the sudokus without preset squares and the bottom half the ones with preset squares. Blue means classical MIP Gurobi, red means quantum/hybrid QUBO D-Wave.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MguJ6Pimlyx1dcpyot46zA.png" /><figcaption>Figure 3: Per sudoku case, we show the calculation time comparison between classical (blue) and quantum/hybrid (red). The upper half is without pre-filled squares in the Sudokus. The lower half is with some squares pre-filled. The left half has linear time in seconds on the vertical axis. The right half has log of time in seconds on the vertical axis. Cases dim=6 and dim=7 in the upper left figure clearly show the time savings of 31% and 82%, which points to the achieved quantum value or quantum advantage. The lower left part shows that for super sudokus with pre-filled squares we have no achieve a quantum advantage yet, but we lacked sufficient quantum calculation on our accounts to complete the cases for n=6 and n=7. The right half is only put on a vertical logarithmic scale to be able to zoom in on the cases with lowe calculation times.</figcaption></figure><p>On the left upper corner, since time is in plain seconds, proportions are kept. Note that the number of variables when going from n=6 to n=7 goes from 6⁶=46656 to 7⁶=117649 so roughly rises by a factor 2.5 and the number of constraints rises from 4 * 6⁴ =5184 to 4 * 7⁴=9604, so by about a factor 1.8. So, loosely speaking, we could say the the <strong><em>complexity of the problem rises roughly by a factor </em></strong>2.5 * 1.8 =<strong><em> 4.7</em></strong>.</p><p>Gurobi’s solving time goes from 1924s for=6 to 15596s for n=7, so rises by a factor 8.1. So roughly, 2 problem complexity doubling gives rise to <strong><em>3 solving time doublings on a classical system</em></strong>.</p><p>D-Wave’s hybrid setup solving time for the same 2 doublings of problem complexity goes from 1324s for n=6 to 2669s for n=7, <em>so almost exactly </em><strong><em>only 1</em></strong><em> </em><strong><em>solving time doubling on a quantum system</em></strong>.</p><p>The charts on the right show a vertical axis on a logarithmic scale to allow for more resolution for the lower times for lower n.</p><p>Note that, independent of whether the vertical scale is in seconds or log(seconds), the <em>horizontal axis</em> is in fact <em>highly compressed</em>. Indeed consider that, if we would have put the horizontal axis in terms of <em>fundamental problem complexity</em>, we should have set a scale proportional to #variables*# constraints ~ n⁶ * 4 n⁴ which is equivalent to n¹⁰. That would have resulted in a much more ‘wide and flat’ curve.</p><p>Note that the reported D-Wave hybrid times still have classical computation components which may still increase harder with increasing n than their quantum sibling components. Having a pure quantum device where an n≥8 sudoku would be quickly embeddable, would be the <em>next attainable holy grail for quantum sudoku solving</em>!</p><h3>4. Conclusions</h3><p>For the super/meta-sudoku problem, the D-Wave <em>pure quantum chips</em> (called Quantum Processing Unit or QPU) which, today, have up to 5000 qubits can embed small sudokus up to size n=2. However, for these small problems, <em>no quantum advantage</em> is achieved yet.</p><p>The D-Wave <em>hybrid approach</em> where problems are decomposed over classical and quantum chips can embed larger problems (n≥3) and the two largest ones we could try, for sudoku dimensions 6 and 7 <em>do show a significant quantum advantage (31.2% and 82.9% respectively)</em>. To the best of our knowledge, this is the first time this has been demonstrated on a quantum machine for meta sudokus.</p><p>Note that finding the ‘embedding’ (function find_embedding in the code) of the problem graph onto the graph representing the quantum chip (or hybrid system) is done classically and also takes time, and that this time increases with size n. With increasing n, the hope is that the quantum subsystem of the hybrid method will not rise much or not at all and that the classical time component will not dominate the total time.</p><p>If we could arrange for additional quantum time on D-Wave machines, we could try sudokus of size n≥8 again on current systems. We are also curious to see what will happen when the classical embedding-finding function gets better (and fits more on a QPU) and when the D-Wave chips with more qubits will be released in the near future.</p><p><em>Footnotes:</em></p><ol><li>Classical MIP solvers like Gurobi are constructed to be <em>deterministic</em>. This means they will always return the same answer (solution if feasible) if the input is the same and the machine is the same (or equivalently, the number of cores, number of threads and operating system is the same). This does not mean that in selecting a certain problem instance, <em>good luck</em> or <em>bad luck</em> is ruled out. For example, running Gurobi v9.1.0 on our model for a sudoku of size (8*8)*(8*8), without any pre-filled squares, we discovered it was solved in 6 seconds all-in, while the smaller case of (7*7)*(7*7) without pre-filled squares took 15596 seconds.</li><li>O(n¹⁰) rises more slowly with increasing n than O(exp(n)) does, but it rises quickly anyway.</li></ol><h3>5. Running Quantum D-Wave Machines from your own Computer … for Free</h3><p>The full Python jupyter notebooks in this article are all available on GitHub <a href="https://github.com/PeterSels/OnComputation/tree/master/QuantumSudoku">here</a>. <em>pip install </em>should install all libraries needed here because it will look into the supplied file <em>requirements.txt</em> which holds all requirements. You can then run the notebooks yourself by adapting <em>have_gurobi</em> and <em>have_dwave</em> to what software and licenses you have available. You can <a href="https://cloud.dwavesys.com/leap/signup/">setup your own free leap account at D-Wave</a>. With <a href="https://www.gurobi.com/documentation/9.1/quickstart_mac/cs_using_pip_to_install_gr.html"><em>pip install gurobipy</em></a> (included in <em>pip install</em>) you can install a version of Gurobi that solves small problems up to a number of variables or constraints. For bigger ones you will need a license.</p><p>The 5 notebooks gists, containing all code but also containing all interleaved output we generated, are available at the links mentioned above in this article.</p><p>And the best thing is, you can get a minute of D-Wave quantum time (which is a lot considering that small problems are solved in milliseconds) <em>for free, renewed </em>each month if you <a href="https://www.dwavesys.com/build/getting-started/">register as a developer</a> and publish your code openly, say on GitHub or so.</p><p>So now you can avoid getting <a href="https://time.com/4078049/seizure-sudoku-puzzles/">seizures</a> from trying to solve sudokus yourself.</p><p>Peter Sels and Edward Mulier, Tuesday August 31st, 2021.</p><p>All code and gists on GitHub referred to here were created by the authors of this article and all tests described where run by them.</p><p>Full Disclosure: This article is not sponsored by D-Wave, nor did we receive any payments from D-Wave ever. We admit to being enthusiastic users of their technologies, since they enable us to solve big computational challenges faster.</p><p>Copyright © 2021 <a href="https://www.logicallyyours.com/">Logically Yours BV</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7d2ae97d534" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/achieving-quantum-advantage-at-solving-super-sudokus-with-d-wave-a7d2ae97d534">Achieving Quantum Advantage at Solving Super Sudokus with D-Wave</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Geometric Optimisation for Industrial Challenges]]></title>
            <link>https://henk-celcius.medium.com/geometric-optimisation-for-industrial-challenges-be7cf35d225d?source=rss-84f80ed927ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/be7cf35d225d</guid>
            <category><![CDATA[mathematical-optimization]]></category>
            <category><![CDATA[mixed-integer-programming]]></category>
            <category><![CDATA[consultancy-services]]></category>
            <dc:creator><![CDATA[Peter Sels]]></dc:creator>
            <pubDate>Sat, 30 Jan 2021 10:54:48 GMT</pubDate>
            <atom:updated>2021-01-30T12:44:37.294Z</atom:updated>
            <content:encoded><![CDATA[<p>with <a href="https://www.gurobi.com/">Gurobi</a> as the Model Solver</p><p>As a consultant to <a href="https://blog.flandersmake.be/en">FlandersMake</a>, I get to help the Flemish Industry with innovation. In particular, the FM CodesignS department offers mathematical optimisation experience to calculate optimal solutions to industry problems. We present two examples from different projects for different sectors, where we find optimal or near-optimal solutions to geometric puzzles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*p7xJq_v3wMcDa2BDT7LO2w.jpeg" /><figcaption>Packing circles in the desert. This rectangular grid is not the most dense packing possible though. A <a href="https://mathworld.wolfram.com/CirclePacking.html">hexagonal grid would be</a>, assuming all radii are equal and space is unlimited. <a href="https://www.nature.com/articles/srep28341">Bees know that … or do they?</a></figcaption></figure><p><strong>Optimization of a Production Process</strong></p><p>The manufacturing industry needs to plan (1) which resources (operators, robots and other tools) need to be deployed in the different production steps that are part of the entire production process towards one or more end products. (2) These resources must also be able to carry out this assembly process with sufficient freedom of movement in a space that has to be constrained in size. In order to plan this process ‘optimally’, FlandersMake can leverage its knowledge of production processes (problem domain) as well as mathematical optimization techniques (solution domain).</p><p>Specifically, in the FlexAs project, a mathematical model was set up for the task-to-resource allocation, which finds various good allocations in a few minutes and visualizes them in terms of cost and production turnaround time. For each of these solutions, an efficient solution for the spatial positioning of these resources was also found via a second mathematical model. Both (Mixed Integer Programming) models were implemented in <a href="https://www.gurobi.com/">Gurobi</a>. This commercial solver solved the first problems in an average of 3 minutes while the open source alternatives CBC and SCIP took 3 to 12 hours to achieve the same solution.</p><p>As for solutions to the second problem, two examples of a positioning of resources (blue circles: 2 operators, 2 robots, 2 tables, 3 recipients) and also of the components that are part of the final product (red circles: 1 housing, 1 cover, 2*3 bolts) are shown below. The yellow circles represent the reach of the entity. The reach of a table is the table surface itself. The reach of a human operator corresponds to a circle with radius equal to his arm’s length. The first one indicates a starting position where all helper-resources like recipients as well as all components are present. Housing and cover are each on their own table and the bolts are in trays per 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E4IOY06mViLmBvJcuWgS5w.png" /><figcaption>FlexAs Optimization of Positioning of Resources and Components: time step 0s.</figcaption></figure><p>The relationship of what ‘parent-entity’ is holding what ‘child-entity’ is represented by a tree data structure, and this for each time step, but without unnecessary duplication of nodes nor edges. This <a href="https://greycat.ai/doc/start/temporal.html">temporal graph</a> evolves from event to the next event. An event occurs whenever an entity is picked up by another one or mounted on another one.</p><p>A second positioning, some events later, is presented below. It occurs 10 seconds later, where one robot is holding the cover, where next, the operator has to insert the bolts and another robot transfers the housing to the other operator who will slide it under the cover later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0rRhk8X_FerxV9qvaCMp3w.png" /><figcaption>FlexAs Optimization of Positioning of Resources and Components: time step 10s</figcaption></figure><p>For each event we will output a positioning, also taking care that all entities can move with a speed below their maximum speed (which is 0m/s for tables), from one positioning to the next within the room (cell) and unhindered by other entities. The result is a complete plan of steps that directly leads to a production plan.</p><p><strong>Covid-19 Proof Placement of Tables and Chairs</strong></p><p>For a second project, the question is whether for the restaurant, event, healthcare and educational sector, automatically, for example via a website, a corona-proof table and seat setting can be generated according to the current corona rules. In Belgium, for example, people at different tables, have to be kept at least 1.5 meters apart. With FM CodesignS, we modeled this problem. Our current benchmarks indicate that automatic table-positioning is indeed possible for typical restaurant settings, in a calculation time of a few seconds, which is workable in a website context. This can help the restaurant and event sector to place people safely and thus avoid fines for the organizer.</p><p>An example of Covid-safe table placement in a restaurant is shown below. This is a table and chair placement for a restaurant with a fixed buffet in the center, an open kitchen on the lower left, and 5 table types: 3 rectangular tables (for 4, 6 and 9 people, assuming that bubbles up to 9 people are allowed) and 2 round tables (for 5 and 6 people). The restaurant owner has more tables than can be placed because the new Covid distance rules make that the restaurant capacity decreases. The round table for 5 people was not even used in this example. The objective is to still be able to seat as many people as possible. Here, the tool calculates that we can install 1 table for 9 people, 4 tables for 6 people and 3 tables for 4 people. Resulting in a total capacity of 45 people. Our tool also shows that there is no solution with more seats. Thus, the restaurant owner is assured of maximum utilisation of the available space according to the rules. The social rules such as the maximum bubble size and the minimum spacing between people from different bubbles, are captured as input parameters for our model. This means that, even if the rules change, our tool can still be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*tFluZ76Iu2pXYPP-nudz5w.png" /><figcaption>An optimal table and seat positioning with 45 seats for a small scale restaurant with different table types.</figcaption></figure><p>Calculating this optimal table setting took less than 2 seconds. It took into account 45 chairs, different table types and different zones where no tables can be placed. The social distancing, where we keep people at different tables at least one and a half meters apart, is ensured by forbidding overlap between their respective yellow circles.</p><p>A more complex setting with more door zones, buffets, pillars and heating spaces along the walls is given in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8Gvgx6ttUFHOm2QKsY2Kg.png" /><figcaption>An optimal solution created in 20 seconds calculation time for a more complex restaurant setting. A suboptimal by 20% solution already was produced after 2 seconds.</figcaption></figure><p><strong>Conclusion</strong></p><p>Mathematical optimisation can help the industry with problems by mathematically formulating goals and constraints to then find a solution that meets all these ‘soft’ and ‘hard’ requirements and is therefore (1) valid, and (2) optimizes a KPI or a combination of several KPIs at the same time. <a href="https://www.gurobi.com/">Gurobi</a> as a solver tool helps us to quickly find these good or even optimal solutions.</p><p>This story was also published by <a href="https://blog.flandersmake.be/en">Flanders Make</a> on their <a href="https://blog.flandersmake.be/en/geometric-optimisation-industrial-challenges">blog</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be7cf35d225d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“A New Kind of Science” … Kind of.]]></title>
            <link>https://henk-celcius.medium.com/a-new-kind-of-science-kind-of-269b185ac6?source=rss-84f80ed927ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/269b185ac6</guid>
            <category><![CDATA[computation]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[cellular-automata]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[wolfram]]></category>
            <dc:creator><![CDATA[Peter Sels]]></dc:creator>
            <pubDate>Sat, 08 Aug 2020 10:20:02 GMT</pubDate>
            <atom:updated>2020-08-08T15:06:55.713Z</atom:updated>
            <content:encoded><![CDATA[<h3>“A New Kind of Science”. Kind of New. Kind of Science.</h3><p>In 2002 Stephen Wolfram published his 1197 page book called <a href="https://en.wikipedia.org/wiki/A_New_Kind_of_Science#:~:text=Proposed%20examples%20of%20such%20systems,simple%20are%20of%20equivalent%20sophistication.">“A New Kind of Science”</a> which, generously, is completely available online <a href="https://www.wolframscience.com/nks/">here</a> and from which we took some screenshots for this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ks942i2IsXJAiEaxGkBmcA.png" /><figcaption>Stephen Wolfram’s 1197 page thick <a href="https://www.wolframscience.com/nks/">book</a>, published in 2002.</figcaption></figure><p>It’s 2020 now. So in retrospect, let’s shed a new light on this book. Did it influence or even revolutionize science? Here is my summary.</p><h3>1. Complexity From Simplicity</h3><p>In the book, Wolfram mainly proposes and defends the thesis that, with very simple rules, simple programs running those rules, a lot of visual patterns can be generated, some of them showing high complexity. To know if this is true, it is important to define <em>simple</em> and to define <em>complexity</em>. We’ll come to that.</p><p>However, for best understanding of context, we start with the examples from the book Wolfram calls <em>crucial</em>.</p><h4>1.1 Wolfram’s Computational Experiments</h4><p>The first example Wolfram gives is one which he has run when he was 12 years old, while clearly inquisitive already, which occurred in 1959+12=1971.</p><p>The ‘computationally generative system’-setup is that we create a vector of a certain number of squares, where each square is either black or white. This vector represents the initial condition or first generation. Then a ‘simple program’ will take such a generation as input and using a <em>fixed rule</em>, will generate the next generation, which is a vector of the same length. The fixed rule is always of the type that the color of each square in the vector depends on the color of the squares in the previous vector that are in the immediate neighbourhood. So there is <em>only</em> <em>local influence</em>. It turns out that this is already enough to generate a variation of patterns in the results.</p><p><em>1.1.1 Experiment 0: ‘Nothing’ Results</em></p><p>The zero-th experiment he, I think added retroactively, tested was the rule, “a square in generation n+1 becomes black if itself or either neighbour was black in generation n”.</p><p>Quite obviously, even without executing the computer program, one can imagine that this leads to spreading of black squares and never is a white square generated. So we get a black pyramidal structure as in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6V8i56O0cacX4V-sCAop2A.png" /><figcaption>The 0th experiment: The rule generates a black pyramid without any interesting structure.</figcaption></figure><p>The result is not very exciting. What happens if we change the generative rule just a bit?</p><p>1.1.2 Experiment 1: Periodicity Results</p><p>The second rule is indicated in the below picture on the right and the result is given on the left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZSF0NClRuoVwSfRVJ_SJnQ.png" /><figcaption>The 1st experiment: The rule generates a Chessboard Pattern</figcaption></figure><p>This may be surprising or not to people. If one reads the rule itself “cell gets black if either of its neighbours were black”, “cell gets white if both its neighbours were white”, one understands that this already encodes the tendency for the same color to spread according to diagonals. <em>Understanding</em> that may take away ‘<em>the magic</em>’ for some. It will please the others, I think, essentially because they capture that a very simple exact rule can generate a relatively complex structure; the alteration of black and white.</p><p><em>1.1.3 Experiment 2: Self-Similarity Results</em></p><p>Wolfram then shows an experiment with exactly the same setup but just a slightly different fixed rule, where the modification in the rule means that two black neighbours generate a white square in the next generation i.o a black one in the previous experiment, all else being equal. Obviously that will generate fewer black squares than the previous experiment for given triangle depth. The resulting figure is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ELT1RE3fmaZbWrydlEzdfA.png" /><figcaption>The 2nd experiment: The rule generates a Pattern that has Self Similarity like a Fractal has</figcaption></figure><p>This picture displays an object property called <em>self similarity</em>. This is defined roughly as that an object has similar structure from afar as when one zooms in on some parts of it. (One could argue that the previous picture possesses the same property, but it would be self-similarity of less complex, smaller structures, so it is less obvious there.)</p><p>This pattern in the second experiment will be surprising more people than the result of the first experiment, because it is just harder to predict, because (1) the rule is <em>somewhat</em> more complex and (2) the result is <em>a lot more</em> complex. That makes it more surprising and so also more interesting. One could also call the result more <em>beautiful</em>, and hence more satisfying, but that’s of course subjective. ¹</p><p><em>1.1.4 Experiment 3: Apparent/True PseudoRandomness Results</em></p><p>A further Wolfram experiment leads to a new feature in the result: apparent randomness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qyf9zcxCPJ_O5jR1izvCug.png" /><figcaption>Generating apparent randomness</figcaption></figure><p>It turns out that, after some 2780 steps a fairly simple repetitive structure emerges, as one can see in the following two pictures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zNbiAd4ewVFh2E4eFooIag.png" /><figcaption>More iterations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WaucACk4vNiYBojY6K4B2w.png" /><figcaption>Even more iterations</figcaption></figure><p>Wolfram also gives examples of programs that generate structures without discernible periodicity at all.</p><p>Whether (a bit of) randomness is more beautiful than recognisable periodicity is subjective, but it certainly adds variation to regularity and so seems to add complexity.²</p><p><em>1.1.5 Are you Surprised?</em></p><p>Are the results of the experiments of Wolfram mentioned here surprising or not? The black pyramid is not surprising. The chess-board pattern is not either, since from the rule itself it’s easy to predict. The self-similar pattern is harder to predict, so that’s quite surprising. Even more unpredictable is the apparent randomness from the third experiment.</p><h4>1. 2 Non-Wolfram Computational Experiments</h4><p>Wolfram does not mention experiments performed by others. So what if we ask the somewhat more general questions: can one generate complex pattern from simpler patterns? Can we come up with some of ourselves or from others?</p><p><em>1.2.1 Overlapping Equidistant Lines/Concentric Circles Generate a Surprising Moir</em>é<em> Pattern</em></p><p>When I was 16 and started programming, one of the first programs I cooked up was a graphical one where you draw straight lines with varying slope over each other. In the area where these lines cross a certain surprising pattern could be detected.</p><p>Similarly, as demonstrated on <a href="https://en.wikipedia.org/wiki/Moir%C3%A9_pattern">this wikipedia page</a>, two sets of lines overlapping each other or two sets of concentric circles with increasing radius overlapping each other can generate Moiré patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*4UtJsMw7XAODZ0VzjzLAtw.gif" /><figcaption>Two sets of concentric circles overlapping generates Moiré patterns: animation.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WwsQJaA9HxipFmF1hIMBxQ.png" /><figcaption>Two sets of collinear lines overlapping generate curved patterns: snapshot. Note that there is even an extra dynamic pattern occurring in the center of this figure when your scroll it up and down, due to the interaction with the pixel resolution of your screen.</figcaption></figure><p>One could consider this also as two simple patterns generating complex patterns. These are certainly hard to predict, unless one has seen this before.</p><p>Remarkably or not, in <a href="https://en.wikipedia.org/wiki/Magnetic_field#/media/File:VFPt_dipole_electric.svg">magnetic fields</a>, so ‘in nature’, the field lines occur along exactly the same pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TOr6OcR4LD75NkLakGgg2g.png" /><figcaption>Magnetic field lines between two opposite point charges.</figcaption></figure><p><em>1.2.2 Unsurprising Self-Similarity: The Koch Curve</em></p><p>Self Similarity is an interesting property to explore in itself. Digging a bit into it, outside of Wolframs book, there is a more accurate definition of it on <a href="https://en.wikipedia.org/wiki/Self-similarity#:~:text=In%20mathematics%2C%20a%20self%2Dsimilar,statistical%20properties%20at%20many%20scales.">Wikipedia</a>. More captivating than the definitions are the <em>examples</em> mentioned there, because one discovers that they come in two kinds. The ones where the definition of the rules already contain self-similarity and the ones where self-similarity of the result is non-obvious or in other words, surprising.</p><p>An example of the first category is the <a href="https://larryriddle.agnesscott.org/ifs/kcurve/kcurve.htm">Koch curve</a>, after the Swede <a href="https://mathshistory.st-andrews.ac.uk/Biographies/Koch/">Helge von Koch</a> (1970–1924). This curve’s constructive definition is also expressed in terms of its generations. The Koch curve of the initial generation is just a line segment of finite length. The next generation is constructed/computed from the previous, by dividing each existing segment in the previous generation in three equal parts, and only for the middle part, replace the segment with a regular triangle of which the base is the replaced segment, then leave out that base segment. Visually, this leads to the following first three generations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmVt4I5xYEe4a_nUPWOGfw.png" /><figcaption>Iterative construction of the three first generations towards the Koch curve</figcaption></figure><p>The following animated GIF from <a href="https://en.wikipedia.org/wiki/Self-similarity#:~:text=In%20mathematics%2C%20a%20self%2Dsimilar,statistical%20properties%20at%20many%20scales.">wikipedia</a> shows an infinite amount of generations, that is, if you would have infinite time to watch it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*rihFhOwq55zc_Yhaq4_Z8Q.gif" /></figure><p>Apart from dizzifying, this may seem ‘magic’ to some. In fact, the self similarity should not surprise you, once you realise that it is already ‘obviously’ present in the definition of the curve. It was ‘<em>set-up’</em> to be self similar. It was constructed / <em>invented </em>to be self-similar<em>.</em></p><p>This is, at least as far as I see, not the case in the next type of structures.</p><p><em>1.2.3 Surprising Self-Similarity: The Mandelbrot Set</em></p><p>An example of the surprising category are pictures generated based on the Mandelbrot-set. For our argument, it is of course important to understand how the rule assigning a color to a pixel in the picture is defined at its base.</p><p><a href="https://en.wikipedia.org/wiki/Mandelbrot_set">Wikipedia</a> defines the Mandelbrot-set as the collection of complex numbers c for which the iterative mapping from complex number z to complex number f_c(0), to f_c(f_c(0)), f_c(f_c(f_c(0))), … does not diverge to infinity.</p><p>The function f_c is not just an arbitrary one, but is defined as the ‘<em>very simple</em>’ f_c(z) = z²+c.</p><p>The practical way to calculate and show the Mandelbrot set and the surrounding pixels not being part of it, is to select a rectangle in the complex plane, (say from c=x + iy with -1≤ x ≤+1 and -1≤y≤+1, representing x,y in the generated picture) and for each pixel (x,y), apply the function z1= f_c(0), z2 = f_c(z1), z3=f_c(z2) until the a |zi|=sqrt(x²+y²), measuring the distance of zi to (0,0) in the complex plane, for some i can be considered diverging, so larger than a certain threshold, say 100 or so. For each c, one then assigns a color to c that depends on the number i at which zi first got outside the radius 100 circle around the origin. When a chosen, fixed maximum number of iterations is reached for a certain c without divergence, the pixel is part of the Mandelbrot set and gets assigned the ‘color black’.</p><p>Clearly, there is no self similarity directly imposed in this iterative procedure to construct it or should we at least say that, it is not clear that self-similarity is directly imposed in the formulation.</p><p>Yet, consider the following resulting picture, and what happens when we zoom in to explore substructures…</p><p>As a GIF obtained from Simpsons contributor at English Wikipedia — Transferred from en.wikipedia to Commons by Franklin.vp using CommonsHelper., Public Domain, <a href="https://commons.wikimedia.org/w/index.php?curid=9277589">https://commons.wikimedia.org/w/index.php?curid=9277589</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*ctnk1jvanBWOvdCFLppo-A.gif" /><figcaption>Colorful Mandelbrot set zoom-in by an animated GIF. Note that it gets shaky in the end, likely due to accuracy problems due to very small numbers and then restarts at the beginning.</figcaption></figure><p>or as a youtube video</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FPD2XgQOyCCk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPD2XgQOyCCk&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FPD2XgQOyCCk%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e976fefcab53af9a0d470ca6ac6bdf45/href">https://medium.com/media/e976fefcab53af9a0d470ca6ac6bdf45/href</a></iframe><p>or for another rendering, including some entertaining music :)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fu1pwtSBTnPU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Du1pwtSBTnPU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fu1pwtSBTnPU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/57fdc281b90ca05cad69575023b05497/href">https://medium.com/media/57fdc281b90ca05cad69575023b05497/href</a></iframe><p>Clearly self-similarity is omnipresent. The sub-structures occurring on all levels of magnification are also extremely complex.</p><p>Isn’t it surprising that all this complexity gets generated from a very simple rule, the subsequent mapping starting at (0,0) with a function f_c(z)=z²+c and counting how many iterations are needed for divergence?</p><blockquote>Lacking to see exactly where the rich structure comes from, one gets a feeling that it cannot be planned for by the human who defined the generator, and so, ‘is just present in nature itself’. In other words, the generated pattern is a discovery, not an invention.</blockquote><p>Wikipedia gives some history of the Mandelbrot set</p><blockquote>The Mandelbrot set has its origin in <a href="https://en.wikipedia.org/wiki/Complex_dynamics">complex dynamics</a>, a field first investigated by the <a href="https://en.wikipedia.org/wiki/French_mathematicians">French mathematicians</a> <a href="https://en.wikipedia.org/wiki/Pierre_Fatou">Pierre Fatou</a> and <a href="https://en.wikipedia.org/wiki/Gaston_Julia">Gaston Julia</a> at the beginning of the 20th century. This fractal was first defined and drawn in 1978 by <a href="https://en.wikipedia.org/wiki/Robert_W._Brooks">Robert W. Brooks</a> and Peter Matelski as part of a study of <a href="https://en.wikipedia.org/wiki/Kleinian_group">Kleinian groups</a>.<a href="https://en.wikipedia.org/wiki/Mandelbrot_set#cite_note-2">[2]</a> On 1 March 1980, at <a href="https://en.wikipedia.org/wiki/IBM">IBM</a>’s <a href="https://en.wikipedia.org/wiki/Thomas_J._Watson_Research_Center">Thomas J. Watson Research Center</a> in <a href="https://en.wikipedia.org/wiki/Yorktown_Heights,_New_York">Yorktown Heights</a>, <a href="https://en.wikipedia.org/wiki/New_York_(state)">New York</a>, <a href="https://en.wikipedia.org/wiki/Benoit_Mandelbrot">Benoit Mandelbrot</a> first saw a visualization of the set.<a href="https://en.wikipedia.org/wiki/Mandelbrot_set#cite_note-bf-3">[3]</a></blockquote><p>It ends the introduction on the set with:</p><blockquote>The Mandelbrot set has become popular outside <a href="https://en.wikipedia.org/wiki/Mathematics">mathematics</a> both for its aesthetic appeal and as an example of a complex structure arising from the application of simple rules. It is one of the best-known examples of <a href="https://en.wikipedia.org/wiki/Mathematical_visualization">mathematical visualization</a> and <a href="https://en.wikipedia.org/wiki/Mathematical_beauty">mathematical beauty</a>.</blockquote><p>That high complexity can arise from very simple rules is the number one message the book “A New Kind of Science” wants to drive home, using 100s of examples from Wolfram himself. To me the Mandelbrot set is a much better example of generation of complexity from simple rules. It is therefore quite remarkable that Wolfram’s first mention of it is on page 899 in the (foot)note part of the book.³ ⁴</p><h3>2 Nature Shows Complexity and How Can Science Best Describe/Predict it?</h3><p>The chapter 7 of Wolfram’s NKS book, many examples of complexity present in nature are given. The first and a very convincing is about typical forms of growing snowflakes. It’s given in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mr_s9fWRhxfuRZAFdrfZXA.png" /><figcaption>The growth of typical forms of snowflakes.</figcaption></figure><p>This picture directly convinces that complexity in terms of structure, periodicity and self-similarity are all present. It poses some questions.</p><p>Why are snowflakes hexagonally structured?</p><p>Why are they alternating on a very local level between ice and no ice?</p><p>Why are snowflakes so symmetric? In other words, how does one arm of the 6 know to behave in the same way as the others? ⁵</p><p>Hexagonality is due to the crystal structure of ice. Wolfram answers the second question by “the major effect responsible for this is that whenever a piece of ice is added to the snowflake, there is some heat released, which then tends to inhibit the formation of other pieces of ice nearby.” This is a <em>qualitative</em> answer and traditional science would normally take a quantitative approach by for example presenting a (set of coupled) partial differential equation(s) to model this more accurately. Apart from being a more accurate description of a phenomenon, the advantage of using the classical analytical approach is also that computers and software libraries directly allow one to simulate the phenomenon. While differential equations are only <em>descriptive</em> and by themselves they do not contain a recipe to simulate, nowadays a practical <em>constructive </em>recipe directly follows from it<em>.</em></p><p>Wolfram does not mention this. That’s weird because he is the main architect of the Mathematica package which amongst many other things is able to do exactly that: take a differential equation and solve it, which ends up with showing an example simulation of the phenomenon.</p><p>Wolfram does mention that with his approach of cellular automata a <em>visual</em> <em>result</em> close to what is observed in nature can be generated. He shows convincing results of that as in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DyXb4L15slgRhDG6M-5y2Q.png" /></figure><p>One could argue that while the result is ‘close’ by showing similar but not identical structures, it does not prove that the process is the same as taken by nature.</p><p>With the traditional approach to science via differential equations, one only has to take the new step of accurately describing the new studied phenomenon in an equation, based on possibly new but potentially already discovered physics, then the constructive recipe just rolls out via equation solving software libraries.</p><p>As an example of a very condensed and powerful descriptive model in physics, consider the below Maxwell’s equations of magnetism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*AxJlXC3ovb7-kN92Xdy6NA.gif" /><figcaption>Maxwell equations in differential form on electric and magnetic fields.</figcaption></figure><p>With this differential model, the complete field, so the strength and direction of the magnetic force, in each point can be derived. This works with standard calculus. I also happily solved countless exercises in my first engineering education years by integration over surfaces or volumes. These equations are also the basis of numerical software libraries like <a href="https://www.sciencedirect.com/science/article/pii/S2352711020300170"><em>Magpylib</em></a> by which computations of E and B for much larger or more complex settings can be automatically performed.</p><p>On the other hand, with the Wolfram cellular automata approach, one will formulate a certainly new ‘simple rule’, then try out and see if this gives results that are similar. If not, the ‘simple rule’ can just (all too?) quickly be altered. I believe there is a danger there, corresponding to the danger of <a href="https://en.wikipedia.org/wiki/Overfitting"><em>overfitting</em></a> and as such getting results alike to what nature produces without actually catching the essence of the process present in nature. Also, once a certain rule seems to give a nature-like result for a certain setting, will it also give a nature-like result for another setting? How should the rule be changed to adapt to a setting? Or not at all? In other words, does it have predictive power apart from for the possibly overfitted first experiment?</p><p>One may say that this does not matter if the results resemble what nature creates. So it depends if one raises the deeper question of <em>truth</em> (Does nature really behave like this?) versus the more superficial question of <em>utility</em> (Can I just get nature-like pictures?). I think the first question is the one science is supposed to answer. So to me, A New Kind of Science looks like a Lesser Kind of Science.</p><h3>3 Could Simple Programs form the Basis of Complexity found in Nature?</h3><p>Would nature use ‘<em>simple programs</em>’ to come up with the complex structures that we see in plants and animals and also in inanimate objects around us?</p><p>Wolfram does no claim that when he presents an artificial automata generated picture which looks alike some structure in nature that nature actually does the same computation.</p><p>He does formulate a more careful version of this claim, which he calls the ‘<a href="https://www.wolframscience.com/nks/chap-12--the-principle-of-computational-equivalence/"><em>principle of computational equivalence</em></a><em>’</em>. In Wolfram’s words: “What the Principle of Computational Equivalence says is that above an extremely low threshold, all processes correspond to computations of equivalent sophistication.” Even though he spends many pages on this, I still find this a very vague claim, sounding more like a tautology.</p><h3>4. My Conclusion</h3><p>My conclusion about New Kind of Science is this.</p><h4>4.1 Is it New?</h4><p>Yes, it was. The kind and scope of cellular (and other) automata that Wolfram describes were quite new when published in 2002. But quite some earlier or simultaneous discoveries like the Game of Life by Conway and the Mandelbrot set were already known, very relevant and quite downplayed in the book.</p><h4>4.2 Is it Science?</h4><p>In the traditional method of science, one first aims to describe a phenomenon by a compact concise <em>descriptive model</em>, most often as a type of (possibly coupled) equation(s). Then a widely accepted, and by others encoded in software, process follows to perform a simulation with this/these equation(s) as input. This corresponds to the scientific method, where first a <em>hypothesis</em> is formulated, without checking yet what the results would be, and only after careful consideration of the descriptive model, then the outcome with the generative recipe is produced and checked. One typically has one program with the same rules and should be able to predict results from nature by changing only initial conditions.</p><p>In the Wolfram proposed approach with cellular (or other) automata of simple programs, there is just one step essentially, where, for given initial conditions, one can manipulate and tune the rule without constraints to just give the desired results. This corresponds to a less general method than in classical science.</p><p>In both approaches, trial-and-error iterations not forbidden, but I think the split between a <em>descriptive</em> and <em>constructive</em> process of the traditional approach to science gives a higher chance of getting close to the process nature follows than Wolfram’s approach.</p><p>But well, it may just be a matter of taste or habit.</p><blockquote>Is it science? … Kind of. It depends on what one calls science. (see: “Is it Useful” below.)</blockquote><h4>4.3 Is it Wolfram’s?</h4><p><a href="https://en.wikipedia.org/wiki/Stephen_Wolfram"><em>Stephen Wolfram</em></a> is without a doubt a brilliant mathematician and scientist. He also clearly worked extremely hard, with the <a href="https://www.wolfram.com/company/"><em>Wolfram team</em></a> he lead, to first construct the software package “Mathematica” and then, based on that, to produce the monumental volume NKS is. However, at times he downplays contributions of others to the field of cellular automata. In one footnote, on page 849 called “Clarity and Modesty”, he even writes […] “Perhaps I might avoid some criticism by a greater display of modesty, but the cost would be a drastic reduction in clarity.” I don’t think there needs to be a trade-of here, and certainly not a drastic one.</p><h4>4.4 Is it Useful?</h4><p>Did the book ‘New Kind of Science’ have impact from 2002 to 2020?</p><p>It would be most informative to see if Wolfram himself has an opinion on that. And indeed he has written elaborately about this online <a href="https://writings.stephenwolfram.com/2017/05/a-new-kind-of-science-a-15-year-view/">here</a>.</p><p>Summarised, I think we can say that in the last 10 and certainly the last 5 years, genetic algorithms and especially neural networks have been very successful. This is for example demonstrated in the 2016 victory of Deepmind’s <a href="https://en.wikipedia.org/wiki/AlphaGo">alpha-go</a> on the best human players of the game Go and the <a href="https://en.wikipedia.org/wiki/DARPA_Grand_Challenge">DARPA autonomous driving contests (2004–2018)</a>. The latter has by now also given rise to a <a href="https://www.mckinsey.com/features/mckinsey-center-for-future-mobility/overview/autonomous-driving#">whole new industry</a>.</p><p>However, I would attribute the success of that technology to the <em>learning capacity</em> of those systems, which comes from training them on existing input-output sets and then results in predictive capacities of outputs on new similar inputs. This process nor capacity is present in Wolfram’s cellular automata as presented in NKS.</p><p>Wolfram <a href="https://writings.stephenwolfram.com/2017/05/a-new-kind-of-science-a-15-year-view/">claimed</a> in 2015 “But to me the success of today’s neural nets is a <em>spectacular endorsement</em> of the power of the computational universe, and another validation of the ideas of <em>A New Kind of Science</em>. Because it shows that out in the computational universe, away from the constraints of explicitly building systems whose detailed behavior one can foresee, there are immediately all sorts of rich and useful things to be found.”.</p><p>I has become clear that it’s indeed true that we do not need to restrict ourselves to classical science to have <em>useful</em> engineering applications, with the footnote that with the inherent lower understanding about how these models work internally (coming from the training and possible overfitting methods) we have a higher risk at predicting outcomes that do not materialise in nature. To decide whether these predictive methods can be used or not, it depends on the level of <a href="https://arxiv.org/abs/1709.00911">criticality</a> and whether the models are trained on outlier events if these events can occur in practice.</p><p>So George Box’s aphorism comes to mind here.</p><blockquote>All models are wrong but some are useful.</blockquote><h4>4.5 What’s Interesting about the Book?</h4><p>NKS certainly convinces that simple programs can lead to beautiful pictures containing a lot of surprising structure. So it certainly has <em>artistic</em> and some <em>philosophical</em> value. The book can also be seen as a catalogue of programs with some parallels to a naturalist reference, which is a nice idea in itself. I am less convinced it contributes a new method that can be used in theoretical <em>science</em>. For <em>engineering</em> applications recent history has confirmed that the neural networks rather than the cellular automata are most useful because of their ability to <em>learn</em>.</p><h3>Footnotes</h3><ol><li>Interesting side questions here are if the subjective experience of beauty has more to do with the <em>subjective</em> surprise or feeling of discovering something new than with the <em>objective</em> structure in the picture itself. I think it’s about both or even the <em>connection</em> between both. And indeed, from this, one wonders if nature would somehow also ‘<em>computationally work</em>’ like this.</li><li>Note that in information theory, maximum disorder, also called maximum entropy (which, according to the second law of Thermodynamics, is what in nature any closed system ultimately evolves to), is defined as the case where there is the least possible information at all about what is going to happen next. More formally, in terms of exclusive events <em>e</em> out of a set <em>E</em> of N events, where each e will occur with a probability p(e), the missing information H(E) can be defined as:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m0SjFVenfT8oVhmqaKg23g.png" /><figcaption>Missing information formula</figcaption></figure><p>It can be proven via derivation of the Lagrangian (see e.g. <a href="http://pillowlab.princeton.edu/teaching/statneuro2018/slides/notes08_infotheory.pdf">here</a>) that this is maximised when P(e)=P(e’) for all event pairs (e,e’) in ExE. This implies P(e) = 1/N. This proves that all events being equally likely to happen corresponds to maximum randomness.</p><p>3. Unsurprising versus Surprising Structure: It’s Subjective.<br>The distinction between what is surprising and what is not depends on the observer’s knowledge and understanding an so is certainly <em>subjective</em>. Once more knowledge is acquired (e.g. with the Koch curve), something that was surprising may become logical in the sense that one understands what causes it (giving satisfaction by the feeling of having <em>discovered a new relation</em>) and become <em>interesting</em> but stop being surprising.<br>If one looks at the animated zooms of the Mandelbrot set, at least to me, it is still incredible that so much structure keeps coming up from ‘just z²+c’. So one keeps wondering why. The animation keeps surprising me.</p><p>4. At the outset we said that Wolfram claims that simple programs can produce complex patterns. It’s quite clear that all the rules presented here and also in the book are quite simple. The complexity found in the output pictures is of different levels. From <em>blandness</em> (a black pyramid), to <em>periodicity</em> (a chess board pattern pyramid) to <em>self-similarity (</em>pyramids containing sub-pyramids, koch curves and fractals<em>). </em>We have tried to demonstrate that this is only <em>interesting</em> to the degree that it remains <em>surprising</em> even after closer inspection.</p><p>So to me, Wolfram’s main thesis should be understood in the sense that the ratio of complexity in the output over the complexity in the input is surprising and interesting when high. I still find this ratio the highest in fractals like the Mandelbrot sets. It seems to reveal more about ‘nature’ than Wolframs examples. I think this is also why in the 1980s so many people got excited about it when they became part of the popular science press.</p><p>5. Why are snowflakes so highly symmetric? In other words, how does each arm of the 6 <em>know</em> to behave in the same way as the others? ⁵ This <a href="https://www.scientificamerican.com/article/why-are-snowflakes-symmet">Scientific American article</a> gives a qualitative answer, indicating that the symmetry follows from minimisation of energy in the structure, which balances maximisation of attracting forces and minimization of repelling forces. So surely one arm does not actively <em>know</em> about the others, but given certain homogeneous temperature and humidity conditions, then via the forces, it seems that when one arm starts forming in one way, the other arms have no choice anymore but to do the same. The sheer variety of snowflake structures is a consequence of the large variation of these conditions from high to low altitude across different snowflake trajectories through our atmosphere.</p><h3>Appendix: Further Nature vs. Computational Experiment Similarities</h3><p>To show that the scope of the book is not only about snowflakes, here are some more examples from the book. On page 385 of NKS, Wolfram gives beautiful examples of periodic or self-similar structures found in nature at many different scales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fGYsMHdlK2pJ4CZxx_Rngw.png" /></figure><p>He then produces similar structures artificially with his automata like these ones on page 400.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ELqEloxuTMs483L1_lq2w.png" /><figcaption>Growing structures with automata that end up looking like trees.</figcaption></figure><p>The structures are quite alike the ones in row 3, column 3 and 4 of the pictures gotten from nature above and certainly arty. But does it capture anything that would ‘happen’ in nature or is the similarity accidental? Not sure… Is it useful for science? I am not so convinced.</p><p>More examples from chapter 7 concern the breaking of materials, fluid flows, 2D pigment structures and 3D shapes in biology and even financial systems.</p><p>Peter Sels, August 7th 2020. Written for all people curious about the NKS book, but wanting to be efficient in spending their time. :)</p><p>Copyright © 2020 <a href="http://logicallyyours.com/">Logically Yours BV</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=269b185ac6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Magic of Euler’s Formula V-E+F=2. An Eye Opener.]]></title>
            <link>https://henk-celcius.medium.com/the-magic-of-eulers-formula-v-e-f-2-an-eye-opener-ef2fe6dead9b?source=rss-84f80ed927ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef2fe6dead9b</guid>
            <category><![CDATA[graph-theory]]></category>
            <category><![CDATA[topology]]></category>
            <category><![CDATA[3d-polyhedra]]></category>
            <category><![CDATA[euler]]></category>
            <category><![CDATA[mathematics-education]]></category>
            <dc:creator><![CDATA[Peter Sels]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 21:16:52 GMT</pubDate>
            <atom:updated>2020-08-07T15:14:35.279Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Magic of Euler’s Equation: V-E+F=2. An Eye Opener.</h3><p>If you have not yet studied topology before, you are in for some very nice surprises when you read David S. Richeson’s book <a href="https://press.princeton.edu/books/paperback/9780691154572/eulers-gem">“Euler’s Gem, The Polyhedron Formula and the Birth of Topology”</a> . These revelations come not only in the shape of pretty pictures, but you’ll also get deeper insights and see new connections between mathematical disciplines.</p><p>You can of course pick up the book yourself if you want to avoid me spoiling your surprises. If you prefer to ride the fast lane, here follows my personal account of what I discovered while reading the book.</p><h3>1 Regular Polyhedra or Platonic Solids</h3><h4>1.1 What are Regular Polyhedra?</h4><p>From reading some popular maths books back in the mid 1980s, I was happy to discover that there was something called the <em>Platonic solids</em>. Their <a href="https://en.wikipedia.org/wiki/Platonic_solid">definition</a> can be simplified to that they are 3 dimensional structures, consisting of faces that are all identical regular polygons of the same type and size such that all the vertices lie on a perfect sphere.</p><p>The most well known is the cube that consists of 6 equally sized squares. The tetraeder is likely the second-most well known. It consists of 4 regular triangles. The octaeder consists of two equal pyramids with a square base oppositely attached to each other at their bases. It has 8 regular triangular faces.</p><p>In today’s public knowledge there are two lesser known solids that are also platonic; the dodecahedron consisting of 12 regular pentagonal faces and the icosahedron consisting of 20 regular triangles for faces.</p><p>Wolfram has made some very nice visualisations of these solids via their software package Mathematica. They <a href="https://mathworld.wolfram.com/PlatonicSolid.html#:~:text=Entries%20%3E%20Interactive%20Demonstrations%20%3E-,Platonic%20Solid,of%20congruent%20convex%20regular%20polygons.&amp;text=The%20Platonic%20solids%20were%20known,350%20BC.">look</a> like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAWDmgaafiGsNrc9D2CHcA.png" /><figcaption>The 5 Platonic Solids from left to tight: cube, dodecahedron, icosahedron, octahedron and tetrahedron.</figcaption></figure><p>Richeson’s account of their chronological discovery is that according to a reading of Euclid’s Elements, only the cube, tetrahedron and dodecahedron were known to the Pythagoreans (Pythagoras (c. 560-480 BC))</p><p>One tale suggest that <a href="https://en.wikipedia.org/wiki/Hippasus">Hippasus of Metapontum</a> (c. 530 -c. 450 BC), while being a member of the Pythagorean club, discovered the dodecahedron but failed to give credit to Pythagoras. Hippasus also discovered that there are non-rational numbers by studying the length of a diagonal of a unit square (root of 2) or/and the length of an edge of the pentagram star (root of 5 plus 1 over 2, also called the <em>golden ratio</em>) that is inscribed in a regular pentagon with sides of length one. The Pythagoreans, on the contrary, discovered that many numbers occurring in nature were ratios of integer numbers. For example in music, halving or dividing by 3, the length of a string resulting in two tones that went well together. So they attributed some magic to rational numbers and liked to believe that all numbers were rational. The tale continuous saying that both of Hippasus’ discoveries upset Pythagoras so much so that Hippasus got banned from the club. Ironically, the proof of the existence of irrational numbers is one of the most significant and lasting contributions of the Pythagoreans to mathematics.</p><p>Richeson mentions that the octahedron and icosahedron were only later discovered by Theaetetus of Athens (c. 417–369 BC).</p><p>It surprised me that the octahedron, which seems much more easy to construct with sticks or even imagine in ones head than the dodecahedron would not have been discovered before it.</p><p>Thinking about that, I wondered if maybe the Greeks would have thought: “Well we have one with triangles already, so let’s focus on polyhedra with other types of faces, like squares and pentagons.” Likely, right?</p><p>Or maybe there was still an utilitarian bias in that a dodecahedron was a better primitive football than the way too pointy octahedron. Hmm, those long-robe-wearing thinkers were probably not so much into football, so that seems less likely, right?</p><p>Still, it got me thinking …</p><h4>1.2 How Did the Old Greeks Discover the Regular Polyhedra?</h4><p>How would you have done it? In your head?</p><p>I think it’s likely that they may have taken a practical approach by constructing some regular triangles by collecting or chopping some equal length wooden sticks or as I did with toothpicks. Would toothpicks have existed? They would then have fitted the corners of 3 triangles together in one point and then bend the faces so that one edge of the first coincides with one edge the third. That directly ends up in a tetraeder. Imagine the wonder the first person ever to do that may have felt when the fourth triangle appearing at the bottom appeared to have exactly the same shape as the three others.</p><p>When taking 4 triangles together one ends up with a pyramid with a square base. It should have been easy from there to double it and construct the octaeder, right? Or were they at first not convinced that the vertices all lie on a sphere? Maybe because they had the tetraeder already?</p><p>When taking 5 triangles, one ends up with a ‘pyramid with a pentagonal base. Note that one cannot just mirror this pyramid to end up with a 10 triangle ‘platonic solid’, since that would not satisfy the requirement that the vertices all lie on a sphere. So one has to realise that an extra row of 10 triangles (in up- down-up-down…-configuration) has to be put in between those two pentagonal pyramids to make up an icosahedron.</p><p>By fitting 6 regular triangles together, since all triangles have 60 degree angles, we need not bend them for an edge of the first to coincide with the edge of the last, since that already happens when they are all flat on the table in 1 plane. So no regular solid can be made out of it.</p><p>With 3 squares we get the cube and with 3 pentagons we get the dodecahedron.</p><p>There are no other regular solids constructable with squares nor pentagons since 4 of each type put together already make 4*90=360 degrees respectively 4*108=432 degrees which does not satisfy the ≤360 degrees requirement to make a chance on obtaining a solid fitting in a sphere.</p><h4>1.3 Are there only 5 Regular Polyhedra?</h4><p>There is the question if there are more regular polyhedra than these five, and in fact there are not. Did the old Greeks know it?</p><p>We can easily prove that there cannot be Platonic solids constructed out of regular n-gons with n≥6, since the internal angle of a hexagon is 120 degrees (divide the hexagon into 6 triangles to see that) and when you shift 3 hexagons together they will fill the plane without gaps like in a beehive, meaning that you cannot build a sphere-like structure with it.</p><p>Regular n-gons have internal angles of each (n-2)*180/n. So for larger n, also the internal angles get larger, so surely for n&gt;6, there cannot exist regular polyhedra constructed with such n-gons.</p><p>Also for n-gons with 3≤n≤5, from the above practical construction procedure one can get convinced that there are no polyhedra, other than the 5 pictured above.</p><p>Euclid (435 BC.-365 BC) in his final book XIII of <a href="https://en.wikipedia.org/wiki/Platonic_solid">‘The Elements’ </a>gives <a href="https://en.wikipedia.org/wiki/Platonic_solid#Geometric_proof">geometric proof</a> along the lines of the above argument of the conjecture that there are only 5 regular polyhedra. In fact this proof was already known by Theaetetus (c. 417–369 BC). We know this from the books <em>Sophist</em> and <em>Theaetetus</em> written by Plato (427–347 BC).</p><p>Since topology did simply not exist until some time after Euler (1707–1783) came up with his formula, we have to wait about 2000 years longer for a <a href="https://en.wikipedia.org/wiki/Platonic_solid#Topological_proof">topological proof</a> of the same conjecture.</p><p>Topologists say that for example in a cube, in each vertex, the 3*90 degrees angles leads to an <em>angle deficit</em> of 360-(3*90)=90 degrees and in general with 3 n-gons, there is an <em>angle deficit of 360-(3*</em>(n-2)*180/n). For n = 3,4,5,6 and 7 this gives respectively: 180, 90, 36, 0 and -25.7 degrees. The <em>angle excess</em> is defined as minus the angle deficit. One needs an angle deficit larger than 0 to have any chance at constructing a polyhedron.</p><h4>1.3 Mysticism: Some Saw a Little Too Much in Regular Polyhedra</h4><p><em>1.3.1 The Primal Elements: Earth, Air, Fire and Water</em></p><p>Plato learned about the 5 regular polyhedra from Theaetetus and, like some other figures much later, found that there was some <em>cosmic beauty</em> to it. Plato was also familiar with the writings from Empedocles (c. 492–432 BC) stating that all matter was created from four primal elements: earth, air fire and water.</p><p>Nowadays that view seems naive. But imagine you lived back then. Fewer man made things existed. There was no plastic, bubble gum or nuclear plants. When you looked around, the man made things that existed were simpler to guess were they came from. Earthwork can be seen as coming from earth and water and then baking it in an oven with fire. Wine comes from grapes, which grows on grapevines that grow in earth and ‘inhale’ air. Clothes consisted of animal or plant derived material, which in turn come from plants which grow in earth and inhale air. So in fact the view could be considered correct in the sense of tracking back things to their four primitive <em>origins</em>. Of course they do not literally <em>consist</em> of these 4 elements anymore.</p><p>In Timaeus Plato wrote up a fictional account of a discussion between Socrates, Hermocrates, Critias and Timaeus, where he explains his mapping as follows.</p><p>“To earth let us give the cube because of the four kinds of bodies earth is the most immobile and the most pliable”. With arguments of ‘stability or pliability of faces” (which makes little sense to me) he then assigns to fire the tetrahedron, to air the octahedron and to water the icosahedron. As such, there is no element left for the dodecahedron. Timaeus, in Plato’s story, then says “this one the god used for the whole universe, embroidering figures on it”.</p><p>In so doing, one can of course make a mapping from any list to any other list even if the number of items in both lists differ. :)</p><p>Later, Aristotle adopted and expanded the belief with a 5th element, called the <em>aether</em> or the <em>quintessence</em>. The term <a href="https://en.wikipedia.org/wiki/Aether_(classical_element)#:~:text=According%20to%20ancient%20and%20medieval,universe%20above%20the%20terrestrial%20sphere.">aether</a> has been used by medieval alchemists for a medium similar or identical to that thought to make up the heavenly bodies (stars and planets). Later able scientists like <a href="https://en.wikipedia.org/wiki/Aether_(classical_element)#:~:text=According%20to%20ancient%20and%20medieval,universe%20above%20the%20terrestrial%20sphere.">Christiaan Huygens</a> (1629–1695) also <a href="https://en.wikipedia.org/wiki/Aether_(classical_element)#Aether_and_light">felt the need</a> for a substance to exists, so that light could move through a vacuum. Huygens’ theory was replaced by subsequent theories proposed by <a href="https://en.wikipedia.org/wiki/James_Clerk_Maxwell">Maxwell</a> (1831–1879), <a href="https://en.wikipedia.org/wiki/Albert_Einstein">Einstein</a> (1879–1955) and <a href="https://en.wikipedia.org/wiki/Louis-Victor_de_Broglie">de Broglie</a> (1892–1987), which rejected the existence and necessity of aether to explain the various optical phenomena.</p><p>This belief in the existence of an aether to make up for phenomenons one understands yet may seem silly now, but will we not think similarly of <a href="https://en.wikipedia.org/wiki/Dark_matter">dark matter</a> and <a href="https://en.wikipedia.org/wiki/Dark_energy">dark energy</a> in the future when we get more insight into those? After all aren’t they just placeholder-names for what we do not comprehend fully yet today? As an extension of this thought, is/was god such a placeholder name too?</p><p><em>1.3.2 Johannes Kepler and his ‘Cosmic Mystery’</em></p><p>The astronomer Johannes Kepler (1571–1630), very capably, came up with his <a href="https://en.wikipedia.org/wiki/Kepler%27s_laws_of_planetary_motion">three laws of planetary motion</a> that accurately described the trajectories of the planets.</p><p>However, he also obsessed about the Platonic solids and attributed more astrological meaning to them than they had (none). He assigned to each of the 5 then-known planets (Saturn, Jupiter, Mars, Venus and Mercury, so excluding planet Earth) one of the platonic solids. A picture of this pseudo-relation is shown <a href="https://en.wikipedia.org/wiki/Mysterium_Cosmographicum">here</a>. Both ‘revelations’ were written up in the same book called ‘Cosmic Mystery’.</p><p><em>1.3.3 Mystical Mappings</em></p><p>So the old Greeks tried to map 4 concepts to 5 and declare it somehow as ‘natural’ and Kepler tried to defend a 6 to 5 mapping. Nowadays we programmers would call this a ‘one off error’. It seems that even the greatest minds sometimes read more into some construction or discovery than there is to it.</p><p>Yet, as we will see later, sometimes it’s the opposite, that they do not dig into it enough, and that they leave some aspect undiscovered, unknowingly, sometimes for centuries.</p><h3>2 Semiregular Polyhedra or Archimedean Solids</h3><p>Richeson does not dive deeply into it but Archimedes of Syracuse (c. 287-212 BC) discovered that there are a limited set of semi regular polyhedra as well;13 to be exact. They consist of more than one type of regular polygons as faces. Their exact definition is a bit involved but given <a href="https://en.wikipedia.org/wiki/Archimedean_solid">here</a>. <a href="https://mathworld.wolfram.com/ArchimedeanSolid.html">Wolfram Mathworld</a> gives a nice visualisation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mYb3klnRgPHixdYIrG_e8Q.png" /><figcaption>The 13 Archimedean Solids</figcaption></figure><p><a href="https://en.wikipedia.org/wiki/Johannes_Kepler">Johannes Kepler</a> had completed the rediscovery of the 13 polyhedra in 1620.</p><p>Up to this day, the truncated icosahedron is better known as the structure used to knit a leather football from. This is likely because the regular polyhedra are not spherical enough in shape yet and because of the sem-regular ones it is the one where the faces are all of approximately the same size, also giving it shape that deviates the least in different places from the spherical shape. This should make its trajectory more predictable when you kick it.</p><p>To show how advanced Archimedes’ understanding of geometry already was we quote <a href="https://en.wikipedia.org/wiki/Archimedes">Wikipedia</a>. “Archimedes is considered to be the greatest mathematician of <a href="https://en.wikipedia.org/wiki/Ancient_history">ancient history</a>, and one of the greatest of all time. He anticipated modern <a href="https://en.wikipedia.org/wiki/Calculus">calculus</a> and <a href="https://en.wikipedia.org/wiki/Mathematical_analysis">analysis</a> by applying concepts of <a href="https://en.wikipedia.org/wiki/Infinitesimals">infinitesimals</a> and the <a href="https://en.wikipedia.org/wiki/Method_of_exhaustion">method of exhaustion</a> to derive and rigorously prove a range of <a href="https://en.wikipedia.org/wiki/Geometry">geometrical</a> <a href="https://en.wikipedia.org/wiki/Theorem">theorems</a>, including: the <a href="https://en.wikipedia.org/wiki/Area_of_a_circle">area of a circle</a>; the <a href="https://en.wikipedia.org/wiki/Surface_area">surface area</a> and <a href="https://en.wikipedia.org/wiki/Volume">volume</a> of a <a href="https://en.wikipedia.org/wiki/Sphere">sphere</a>; area of an <a href="https://en.wikipedia.org/wiki/Ellipse">ellipse</a>; the area under a <a href="https://en.wikipedia.org/wiki/Parabola">parabola</a>; the volume of a segment of a <a href="https://en.wikipedia.org/wiki/Paraboloid_of_revolution">paraboloid of revolution</a>; the volume of a segment of a <a href="https://en.wikipedia.org/wiki/Hyperboloid_of_revolution">hyperboloid of revolution</a>; and the area of a <a href="https://en.wikipedia.org/wiki/Spiral">spiral</a>.”</p><p>Yet, he missed to remark or publish some simple rule about the Platonic solids, which in fact even applies to ‘his own’ Archimedean solids.</p><h3>3 Euler’s Formula</h3><p>Richeson’s tale is a chronological one in the order of events as mathematical discoveries were becoming public knowledge to the world by publication time. In this sense, Euler’s made the discovery first.</p><h4>3.1 Euler’s Formulation</h4><p>When one tabulates the number of vertices V , edges E and faces F for each of the Platonic solids we get this table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c031040bf5173b29e915d1d50158a6ed/href">https://medium.com/media/c031040bf5173b29e915d1d50158a6ed/href</a></iframe><p>The old Greeks as well as Kepler noticed that some polyhedra are the dual of another in the sense that the number of vertices of the first equals the number of vertices of the second and vice versa. The octahedron is the dual of the cube and the icosahedron is the dual of the dodecahedron. The tetrahedron is the dual of itself. Thanks to that, the vertices of a regular polyhedron fit nicely into the centre of the faces of its dual regular polyhedron.</p><p>Richeson’s book starts with the sentence “They all missed it.”, meaning that when Euler discovered a relation between the number of vertices, edges and faces and wrote it up in 2 papers in 1750 and 1751, but only published in 1758, nobody else had noticed or published this before. Maybe some realised it but thought it was an irrelevant or accidental curiosity and judged it as no material not worthy for publication.</p><p>But indeed, see for yourself, in the table above one can clearly see that V-E+F=2 for each of the 5 solids. Is it meaningful? To know that, we need to see for which other classes of polyhdra it also holds, if any and where it does not hold anymore.</p><p>It turns out that the Euler equality also holds for the Archimedean solids. One can easily check this for each of them from the table mentioning the numbers of V, E and F for each of them <a href="https://en.wikipedia.org/wiki/Archimedean_solid#Classification">here</a>.</p><h4>3.2 Descartes Formulation</h4><p>Later, in 1860 evidence emerged that René Descartes (1596–1650), in 1630, so preceding Euler by 120 years, already discovered a relationship which he wrote down as P=2F+2V-4. As for Euler later, he called F <em>faces</em> and V <em>solid angles</em> instead of vertices. However, Descartes counted P as <em>plane angles </em>where Euler counted E for<em> edges</em>. Plane angles are the interior angles of all the faces, so there are F * n of them for polyhedra consisting of faces that are n-gons. For example, in a cube there are 6*4=24 of them. 2F+2V-4= 2*6+2*8–4 is 24 as well indeed.</p><p>Because in any polyhedron, it is a general truth that an edge connects two face angles, it follows that P=2E. So Descartes formula is equivalent to 2E=2F+2V-4 or to V-E+F=2 which is Euler’s formula. Because of that some argue that this equation should be called Descartes formula or the Descartes-Euler formula.</p><p>Some mathematicians claim that if the notion <em>edge</em> would have existed at Decarte’s time, he would have formulated it the Euler way. It is Euler who came up with the notion edge.</p><p>I find it interesting to note that over the course of history, features that have in some dimensions, a size equal to 0 tend to take more time in history to receive a proper name. An edge, apart from the dimension along the line it is coincident with is in other dimensions of size 0. A vertex, has size 0 in all dimensions and used to be called <em>solid angle</em>. Similarly, the number 0 was only introduced into the decimal system in use in Europe by <a href="https://en.wikipedia.org/wiki/Fibonacci">Fibonacci</a> (c. 1170–1250). He used the term <em>zephyrum. </em>Judging from the given names <em>solid angle</em> and <em>plane angle</em> it seems that the lower dimensional features edge and vertex were mainly seen as resulting from intersections of two and more faces respectively<em>.</em></p><p>This leads us to the realisation that the formula V-E+F=2 relates zero-, one- and two-dimensional properties of polyhedra, in that order. Later generalisations will show that this is quite fundamental for this relation to hold.</p><h3>4 Categories for which Euler’s Equation holds and Proofs</h3><h4>4.3 Euler’s Proof for Convex Polyhedra</h4><p>A year after his publication of the discovery that his formula applies on Platonic solids, so in 1759, Euler gave proof of the fact that V-E+F=2 is applicable to general polyhedra. The proof starts with a general (convex) polyhedron and repeatedly removes vertex at a time, keeping track of V, E, F across different cases and ending up with a triangular pyramid for which V-E+F=2 holds. He then correctly concludes that V-E+F=2 holds for the original polyhedron.</p><p>However (1) he made the only implicit assumption that polyhedra are convex and (2) in his method of reducing polyhedra by subsequent removal of vertices, he ignores some possible cases of ending up with degenerate polyhedra (non-convex ones, disconnected polyhedra, even a combo of two polyhedra joined by an edge or vertex — so non-polyhedra). This proof has later been completed for these cases, but more simple proofs have been given later as well.</p><h4>4.4 Legendre’s Proof for Convex Polyhedra</h4><p>Adrien-Marie Legendre (1752-1833) proved that the Euler equation holds for convex polyhedra, starting from an entirely different angle: by calculating the sum of the areas of all faces of the polyhedra as projected on a unit sphere contained in/around the polyhedron on equating it to 4 Pi, which was already known from the old Greeks.</p><p>The English astronomer, mathematician <a href="https://en.wikipedia.org/wiki/Thomas_Harriot">Thomas Harriot</a> (c. 1560–1621) and the French mathematician <a href="https://en.wikipedia.org/wiki/Albert_Girard">Albert Girard</a> (1595–1632) had proven two useful formula for the area of a geodesic triangle and a general (even non-convex) geodesic polygon on a sphere. In both cases the generalised formula is A = a1+a2+..+an — (2-n)Pi, where A is the area, the a1, a2, ..., an are the polygon interior angles in radians and n is the number of vertices of the polygon.</p><p>So Legendre ‘simply’ noticed that per n-edged face of a polyhedron, we have a contribution of area when projected from a center point, onto the unit sphere with the same center point of a1+a2+..+an -(2-n)Pi. One can visualise this by assigning a contribution of Pi to each of the face edges and one 2 Pi contribution to the face itself. The sum of all geodesic areas for all faces should be 4 Pi r*r with r = 1 so 4 Pi. From the visualisation, this sum clearly is 2 F Pi - 2 E Pi + 2 V Pi. The -2 E Pi results from noting that each edge occurs in two faces. The 2 V Pi results from the fact that we know that at each vertex all geodesic angles add up to 2 Pi on the geodesic sphere. So 2 F Pi-2 E Pi+2 V Pi=4 Pi or after division by 2 pi, this leads to V-E+F=2, which proves Euler’s formula for convex polyhedra. How short, smart and beautiful this proof, isn’t it?</p><p>Does the proof rely on the convexity of the polyhedron? Not explicitly, but in fact, the idea of the projection on the sphere from some not further specified central point to result into non overlapping faces on the sphere, some condition must hold on the polyhedron with start with. Clearly this will not work for all polyhedra. For convex ones, such a point can always be found. For example the central point of the polyhedron always works. Are there non-convex polyhedra for which Legendre’s method of proof will hold, and so Euler’s relation will also hold?</p><h4>4.5 Poinsot’s Discovery of Star-Convex Polyhedra</h4><p>Must the polyhedra be <em>convex</em> to satisfy the Euler equality? In fact it turns out that no, this is <em>not a necessary requirement</em> since some non-convex polyhedra like two of the four <a href="https://en.wikipedia.org/wiki/Kepler%E2%80%93Poinsot_polyhedron">Kepler-Poinsot’s polyhedra</a> also satisfy the Euler equality. There are four Kepler-Poinsot polyhedra, and they <a href="https://mathworld.wolfram.com/Kepler-PoinsotSolid.html">look</a> like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2GnOWjkcj5gCcs7TRJR9Ug.png" /><figcaption>The 4 Kepler-Poinsot Polyhedra, which are all non-convex, from left to right: the great dodecahedron, the great icosahedron, the great stellated dodecahedron and the small stellated dodecahedron.</figcaption></figure><p>The list of V, E, F number for these polyhedra in the same order is as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/826353113fb1736d3896838accfa45b7/href">https://medium.com/media/826353113fb1736d3896838accfa45b7/href</a></iframe><p>From this table, it is clear that the second and third polyhedron satisfy V-E+F=2 while the first and last do not. What is so different between the two categories? Can you see it?</p><p>It turns out that for the first and the last, no point can be found from which to project the polyhedron faces on a sphere such that no two of them overlap each other on the sphere.</p><h4>4.6 Cauchy’s Proof for Flattened/Projected Convex Polyhedra</h4><p>By using the idea of the projection of convex Polyhedra, Cauchy attempted to prove the Euler formula directly on the 2D picture of the projection obtained. He used a method of subsequent removal of first triangulating each face in the 2D picture and then, removing one vertex (and the connected edges and enclosed face) at a time. By keeping track of some different cases, he ends up with a triangle for which V-E+F=2 still holds and can then reason that this must have been the case for the original 2D picture as well. (Note that the exterior face around the triangle counts for a face as well.) This method can be seen as the 2D version of the 3D method of proof from Euler.</p><h4>4.7 Hamilton’s Insight that V-E+F=2 holds for all Planar Graphs</h4><p><a href="https://en.wikipedia.org/wiki/William_Rowan_Hamilton">William Rowan Hamilton</a> (1805–1865) noticed, while Cauchy himself did not, that Cauchy’s proof was in fact applicable to any graph also with non-straight edges as long as it does not have crossing edges.</p><p>Some graphs have crossing edges, but can be redrawn in a way without crossing edges, just by lengthening, shortening or bending edges, and displacing vertices, but still taking care that vertices and edges are not disconnected and edges are not broken up nor removed. We call such a graph a <a href="https://en.wikipedia.org/wiki/Planar_graph#:~:text=In%20graph%20theory%2C%20a%20planar,no%20edges%20cross%20each%20other."><em>planar graph</em></a>. So one must in fact read <em>planar graph</em> a as graph that is <em>planarisable without crossing edges</em>.</p><p>Examples of planar graphs are the ones for the Platonic solids.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*NqM8n55B1J_iG5LdJJGCVw.gif" /><figcaption>All 5 Platonic solids: tetrahedron, octahedron, cube, dodecahedron and icosahedron correspond to planar graphs.</figcaption></figure><p>Note that if you want to count faces of these graphs, you also have to count the single ‘outer face’ that surrounds the graph as one. You will then see that the Euler formula still holds on these planar graphs.</p><p>Again, note that even though a graph is planar, one can still draw the same graph in a way that some edges do cross. For example here are some equivalent graphs of the graph for the dodecahedron where the first two demonstrate planarity, but the next 10 do not, even though they are equivalent graphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*v6JMVkaV8bjcXQeet7-xYg.gif" /><figcaption>12 times the same graph, but only the first two clearly demonstrate planarity, while the next 10 have crossing edges in their representation so hide planarity. But all 12 graphs are essentially the same regarding connectivity or ‘topology’.</figcaption></figure><p>Also the Archimedean polyhedra, necessarily because they satisfy the Euler formula, have planar graph representations, for example as generated by <a href="https://mathworld.wolfram.com/ArchimedeanSolid.html">Mathematica</a> below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*oPRKiLZ6V7e8GkS1s5HZuA.gif" /><figcaption>All 13 Archimedean solids correspond to planar graphs.</figcaption></figure><p>So since Euler’s relation has been proved to hold for convex polyhedra, we know that all convex polyhedra (and some more, like the 2 of the Kepler-Poinsot polyhedra satisfying the Euler formula) are represented in 2D by a planar graph.</p><h3>5 The Connection to Graph Theory</h3><p>Graph theory has become a separate discipline within mathematics and computer science.</p><h4>5.1 Euler Walks on Graphs</h4><p>Euler <a href="https://www.whitman.edu/mathematics/cgt_online/book/section05.02.html">defined</a> a walk as a tracing of a graph starting at one vertex, following edges and ending at another vertex. A walk that has the same begin and end vertex is called a circuit. A walk that visits every edge just one is called an Euler walk. When beginning and ending vertex of the walk are the same we call the walk an Euler circuit. The <em>degree</em> of a vertex is the number of incident edges in that vertex.</p><p>Euler proved that, a graph has an Euler walk precisely when the graph is connected and there are zero or two vertices of odd degree. When there are two, the walk starts at a vertex with odd degree, otherwise the walk may begin anywhere.</p><h4>5.2 Hamilton Walks on Graphs</h4><p>Apart from Euler walks on graphs, there are also Hamilton walks, where all vertices rather than all edges should be visited.</p><p>Applied on the Platonic Solids this gives the following Hamilton cycles in 3D or 2D as pictured by <a href="https://mathworld.wolfram.com/HamiltonianCycle.html">Wolfram</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ya6KvX_d0FVPV7iq4pWCag.png" /><figcaption>Hamiltonian cycles for each of the Platonic Solids: shown in 3D isometric projection or 2D on their respective planar graphs.</figcaption></figure><p>‘The’ necessary and sufficient condition for a graph to possess a Hamilton cycle is not as simple as the condition for a graph to have a Euler cycle. As an example, a <a href="https://www.whitman.edu/mathematics/cgt_online/book/section05.03.html">sufficient condition</a> for a simple graph with n vertices to have a Hamilton cycle is is that<em> </em>n≥3<em>, and </em>d⁡(v1)+d⁡(v2)≥n<em> </em>whenever v1 and v2 are not adjacent, where d(v1), d(v2) are the degrees of vertex v1 and v2.</p><p>So the connection of Euler’s formula to graph theory is that the formula holds for planar graphs, even though Euler did not know that when he discovered his formula holding for some classes of polyhedra and even when he proved it for some (implicitly assumed) convex polyhedra a year later.</p><h4>5.3 Applications</h4><p>Algorithms on computers to efficiently find walks that visit every vertex or edge in large graphs, with or without extra conditions, are still an important research area in computer science today. Applications are for example, how can a travelling salesman most efficiently plan to visit his clients in a day and in what order, and related, if he has 5 days to visit 25 of them, how to subdivide them into the 5 days of the week?</p><h3>6 The Connection to Topology</h3><p>When we look back at how the category of structures for which the Euler formula holds expanded from Platonic solids, Archimedean solids, convex polyhedra, some star-convex polyhedra expanded in 3D and how the category was then ‘projected down to 2D’ and planar graphs in the end, one may realise that there was a centuries long ‘<em>unnecessary detour</em>’ in determining the crux to it all. It would have been better to start with drawing some arbitrary planar graphs on paper and discovering that V-E+F=2 holds for all of these. Imagine in a parallel universe Theaetetus would have gotten up one day and made some simple 2D planar graphs and counted V, E and F. How much earlier would V-E+F=2 have been discovered then? ¹</p><p>Yet, apart from graph theory, there is even more that came out of the V-E+F=2 formula and it’s called topology, another mathematical discipline.</p><p>For all polyhedra we considered up to now, they are imagined on a sphere-like shape. For example consider cutting an apple in 8 parts in three perpendicular cuts (one along each of the 3 axis-planes: xy, xz, yz planes). We then have 8 apples parts and so 8 skin faces, 3 * 4=12 edges and 6 vertices. V-E+F=6–12+8=2. The Euler relation holds! If we consider a division directly on the sphere, for example of the worlds globe in latitude and longitude lines, no matter how many lines we choose, we could also count vertices, edges and faces and it turns out the Euler relation still holds!</p><p>So this makes one realise that maybe, the Euler relation has more to do with the sphere’s nature than with (convex or non-convex) polyhedra or the particular division of a globe itself.</p><p>Say we make such a similar 3-cut or surface division on a torus. What results? V-E+F=8–16+8=0, so 0 instead of 2, so the Euler relation does not hold anymore? It turns out that the Euler relation can be generalised to V-E+F=X(S), where X(S) is the Euler characteristic of the surface S. X(sphere)=2 and X(torus)=0. And an g-holed torus has X(S)=2–2g.</p><p>Topology goes much further with cross caps, mobius bands and klein bottles, but suffice it to say that the Euler formula still holds but can be generalised for surfaces and even in multiple dimensions and that the Euler characteristic is still one of the invariants used to classify topological surfaces.</p><p>Richeson dedicates a chapter to showing in another way how fundamentally different spheres and tori are. If one imagines a continuous vector field, say describing the wind on planet Earth. There will always be at least two places on earth where there will be no wind. Try it. As for a different field, the magnetic field on earth, this is similar. There will be the magnetic north pole and the magnetic south pole. On a torus, imagine putting it as a doughnut, with the hole in front of you and dripping chocolate on it. You will have a ‘north pole’ where — locally — you see the chocolate going downwards, spreading out to all sides (a <em>source point</em>). You will have a ‘south pole’ where — locally — you will see all chocolate coming together (a <em>sink point</em>). But you will also have an upper and a lower point lying on the inner hole where for both, from some sides chocolate glides down into it and to other sides chocolate glides out to. These two are called saddle points.</p><p>When we then defined the (Poincare-Hopf) indices on these different types of points. We will derive a surprising fact. This index for a point in a field is defined as the number of times the incoming field vector turns by -2 Pi when going around clockwise on a small circle around the point in anti-clockwise direction. The figure below shows four cases. For a source and a sink this can be see to be 1. For a saddle point with two incoming chocolate streams and two outgoing ones interleaved, this can be seen to be -1. The fourth case in the figure shows a saddle point that has 3 incoming and 3 outgoing vectors, which leads to an index of -2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*rjmnuXTv254rGsATcTNgpw.jpeg" /><figcaption>Poincare-Hopf index examples, from left to right: a source, a sink and two saddle points.</figcaption></figure><p>When we add the indices for the ‘zero’ points of the field on a sphere, we get (+1)+(+1)=2, while for the torus, we get from top to toe: (+1)+(-1 + -1) +(+1)=0. Both sums are exactly equal to the Euler characteristic of the respective surfaces. So the zeroes of the fields defined over a surface reveal some intrinsic properties of that surface, just like polyhedra defined over surfaces reveal fundamental properties of that surface.</p><p>Richeson describes many more topics like knot theory, the four color problem (it takes at most 4 colors to color any map on a sphere, but it takes at most 7 for a map on a torus (as demonstrated for this map here)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rXcnpmQItpdWLJRJGTxhUg.png" /><figcaption>A map on a torus that needs 7 colors for map coloring.</figcaption></figure><p>and generally <a href="https://en.wikipedia.org/wiki/Four_color_theorem">p=floor((7+sqrt(49–24 X))/2))</a> for a map on any surface with Euler number X, extensions to n dimensions where Poincare defined an Euler number X(M) on a manifold M, and it turns out that in a <a href="https://en.wikipedia.org/wiki/Euler_characteristic#Topological_definition">generalised formula</a> for X(M), you still have the + and -signs alternating as in V-E+F over more and more higher <em>simplices. </em>Amazing how much structure is present! But this would lead us too far here.</p><h3>7 Conclusions</h3><p>In the introduction to this article we mentioned that with the story of Euler’s formula, you were in for some nice surprises. As for me, these surprises were the following.</p><ol><li>how it took about 2000 years until someone discovered that ‘simple formula’ on polyhedra that were out there already for so long,</li><li>how something from one field, <em>geometry</em> (a formula on polyhedra with discrete rigid features) does actually have a connection with <em>topology</em> (the number of holes in smooth surfaces a polyhedron can be imagined to be constructed on),</li><li>how something from one field, <em>geometry</em> (that same formula) does actually have another connection (or manifestation of the same connection) with <em>topology</em> (the sum of the indices of all the ‘zeroes’ in a continuous field constructed on surfaces a polyhedron can be imagined to be constructed on),</li><li>how 2 and 3 can give rise to an entirely new field in Mathematics (topology),</li><li>related to the previous surprise, how only very few people over these centuries know where to look, how to think, what to investigate to find this deeper structure (For all the others, that’s probably called <em>intuition or genius.),</em></li><li>how much beautiful structure there <em>is</em> to discover (by yourself or from reading) in Mathematics and so in nature but at the same time how one has to pay attention not to imagine things that are <em>not really there, </em>called<em> mystic</em> at best,</li><li>how even something that abstract as topology still has <a href="https://en.wikipedia.org/wiki/Topology#Applications">some applications</a> (though Richeson does not focus on that).</li></ol><p>It’s also surprising to me that this fun story of discovery that does not require more than primary school arithmetic to understand, does not make part of the secondary school mathematics education. It was not even part of my full engineering curriculum.</p><p><em>Footnotes</em></p><ol><li>I like the idea of changing one single small thing that would have happened earlier in history and imagining the effect it could have happened on later development. Spoiler alert … For one, McEwan’s novel <a href="https://www.newyorker.com/magazine/2019/04/22/man-woman-and-robot-in-ian-mcewans-new-novel">‘Machines Like Me’</a> is the story of Alan Turing supposedly having proven that <a href="https://en.wikipedia.org/wiki/P_versus_NP_problem">P=NP</a> in the 60s and the subsequent accelerated development of science and technology that (could have) changed history, with the actual story playing in the 80s. So it’s called a <a href="https://en.wikipedia.org/wiki/Retrofuturism">retro-futurist</a> story. It’s a bit like <a href="https://en.wikipedia.org/wiki/Steampunk#:~:text=Steampunk%20is%20a%20retrofuturistic%20subgenre,century%20industrial%20steam%2Dpowered%20machinery.">steampunk</a> or <a href="https://en.wikipedia.org/wiki/Dieselpunk">diesel-punk</a> are based on the idea that steam or diesel would have persisted as general energy source. For another, the series ‘For All Mankind’ available on Apple TV+, makes the assumption that in ’69, the Russians beat the Americans as the first ones to set foot on the Moon. Subsequently everything could indeed have been very different. Would a black sheep have been searched for? Would it have been <a href="https://en.wikipedia.org/wiki/Wernher_von_Braun">Wernher von Braun</a>? Would the US have become more aggressive in its space exploration or rather have given up? Would the space race never have ended/been paused?</li></ol><p>Peter Sels, July 12th 2020. Written for my nephew Edward, to show him that there is a lot of fun in continuing self-discovery in Maths or Science after secondary school. :)</p><p>Copyright © 2020 <a href="http://logicallyyours.com/">Logically Yours BV</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef2fe6dead9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chain Gang on a Fence]]></title>
            <link>https://henk-celcius.medium.com/chain-gang-on-a-fence-f1ffda7597c6?source=rss-84f80ed927ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1ffda7597c6</guid>
            <category><![CDATA[pranks]]></category>
            <category><![CDATA[computational-thinking]]></category>
            <category><![CDATA[electric-circuit]]></category>
            <category><![CDATA[electric-fence]]></category>
            <category><![CDATA[urban-legends]]></category>
            <dc:creator><![CDATA[Peter Sels]]></dc:creator>
            <pubDate>Tue, 23 Jun 2020 08:36:10 GMT</pubDate>
            <atom:updated>2020-07-14T09:33:37.739Z</atom:updated>
            <content:encoded><![CDATA[<h3>“The person furthest from the fence is the only one feeling the electric shock!”… Debunked!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*MLThf3QI33o-qiG8Ey25jA.png" /><figcaption>Who gets hurt the most in a series of people giving hands when the first person touches an electric fence? It’s also quite shocking what some people believe! :)</figcaption></figure><h3>1. The Discussion</h3><p>Dining last night with some neighbours, neighbour X came with the following story. “<em>When we were kids</em>”, he said, “<em>we used to give hands to each other, left to right, in a long chain and then the first one used to touch an electric fence. None of us would feel any electric current or shock, but the last one felt it all!</em>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*kTC2MgTZPYhltgHgxtcqXQ.gif" /><figcaption>This very much sounds like a prank <a href="https://simpsons.fandom.com/wiki/Bart_Simpson">Bart Simpson</a> with his friends would play on a chosen victim. Haahaa!</figcaption></figure><p>I reacted that the last person suffering the most could not be the case, but my neighbour replied: “It is surely the case, since we did it and we all experienced it!” I then asked him how it could be the case ‘scientifically’ because surely, the current the last person felt should come through the arms of the previous people and he replied that this is/must be the case because “any but the last person is ‘just a conductor’.</p><h3>2 Refutation</h3><p>Depending on the amount of science one understands, one may use different techniques to convince people that the conclusion that the last person suffers the most as well as that the other persons would not feel anything is just wrong.</p><h4>2.1 Refutation by Showing an Error in the Story Telling or Reasoning</h4><p>First, surely, the last statement that all but the last person in the row are ‘just conductors’ is wrong or at least inaccurate. The confusion is partly due to natural languages allowing for the all too casual use of the word ‘conductor’, while the word does have <a href="https://en.wikipedia.org/wiki/Electrical_conductor">a particular scientific meaning</a>. In secondary school we all learn about Ohm’s law and that objects (except for some rare superconducting ones that show that behaviour only at very low temperatures close to 0K) all materials have a certain resistance to electric current (whether is be AC or DC current). (There are also <a href="https://en.wikipedia.org/wiki/Semiconductor"><em>semi-conductors</em></a>.)</p><p>Humans do resist electric current so are ‘resistors’. <a href="https://en.wikipedia.org/wiki/Electrical_injury#:~:text=The%20NIOSH%20states%20%22Under%20dry,body&#39;s%20resistance%20to%20500%20ohms%22.">Wikipedia</a> for example states that a human has a resistance between 100000 Ohm and 700 Ohm, depending on how wet/broken the skin is. Wetter and more broken skin has lower resistance, but never 0 Ohm resistance.</p><p>Second, even if humans were ‘just conductors’, meaning they would have 0 Ohm resistance, the last man standing would also have 0 resistance and nothing would be fundamentally different for him, since even then, it would still be true that all the current that goes through him has to pass from the fence through all the intermediate people in the chain and then back through the ground to the battery.</p><p>This second reason should be sufficient proof for anyone who <em>understands</em> or even <em>has a vague feeling</em> of how electricity chooses its way from a fence to the ground, through a network of resistors, which is what a bunch of connected humans are, as far as the electrons and so electricity are concerned.</p><p>At this point, I considered the story sufficiently debunked.</p><p>However, since I experienced this was still unconvincing to some (and I admit this somewhat irritated me), I decided I needed some bigger guns.</p><h4>2.2 Refutation by Googling</h4><p>Nowadays, outside science, the quickest path to convincing people of something is to find an internet link (millenials need a youtube video) that supports your ‘opinion’ and somehow seems more reputable than you are to your listening audience. Essentially, you try to find someone with either more <em>authority</em> than yourself that supports your opinion, or better, also <em>explains</em> why your opinion is in fact a widely acceptable <em>fact or/and can be derived from widely accepted facts.</em></p><p>However, while searching you may find opposite opinions and then you should just give in and openly admit you were wrong of course.</p><p><strong><em>2.2.1 Listening to Glen</em></strong></p><p>But so we found <a href="https://www.quora.com/If-a-line-of-people-hold-hands-and-the-person-at-the-end-touches-an-electric-fence-who-will-get-the-greatest-shock">this exact question </a>on Quora. And the first answer, from Glen Helgeland who signs with “Studied Robotics at Swinbourne University of Technology” says what is right, yet without starting from basic physics but directly stating results.</p><blockquote>“If all the people were insulated from the ground, no one would feel a shock. just as a bird can perch on power-lines.</blockquote><blockquote>If one of the people grounds themselves, every person between them and the fence will experience the same shock, as the current flowing through them would all be the same. All the others beyond this circuit will feel nothing.</blockquote><blockquote>If multiple people ground themselves (or all of them, as the most probable scenario), then each grounding point will lessen the pain for all those to the next node and so on. As the human body is quite resistive, the power will flow most through the first “circuits”. The pain/shock will become progressively weaker after each grounding point. This will continue till the last ground contact, again every one after this point (not grounded) will not be affected.”</blockquote><p>What is helpful and hopefully convincing here is that Glen states experiments from from simple to more complex and as such shows also some consistency in the results.</p><p>It may be unclear to some what <em>being grounded</em> means in the above. One is grounded if on conducts to the ground with a zero or negligible resistance (in Ohms, the unit of resistance). Being bare feet and in very wet grass would be the most conductive situation while wearing rubber soles on very dry ground would be the least conductive — so highest resistance — situation.</p><p>However, who believes Glen? Is he really an engineer? (I have no reason to not believe him.) But he does not build up an argument starting from scientific facts, so some people may not yet buy his claims.</p><p><strong><em>2.2.2 Listening to Pascal</em></strong></p><p>“Who receives the biggest shock?” was the question.</p><p>Pascal Heitz, signing as an engineer, answers this.</p><blockquote>Probably the guy who touches the fence, since electricity will use the shortest path, which is from the fence to the ground through his body.<br>The second person of the chain might feel the shock too, but lowered, since he is only the second choice path for electricity.<br>The third person will feel it too, but again a little less.<br>Etc.</blockquote><p>So contrary to Glen, Pascal uses <em>reasoning from facts</em>, saying the people closer to the fence should experience more current through their bodies <em>since</em> ‘electricity will use the shortest path’.</p><p>This conclusion is correct, but the wording ‘electricity will choose the shortest path’ is somewhat sloppy.</p><p>However, Pascal wrote something else as well:</p><blockquote>There is a belief that says that the last person gets the biggest shock, but from my little electricity knowledge, I don’t see why it would be that way.</blockquote><p>So apparently this is a more wide spread urban legend than just with my neighbour and his chain gang.</p><p>This means that this belief deserves to be more widely refuted, with proper wording and derived from scientific laws.</p><p>Let’s reword to make the argument more accurate.</p><h4>2.3 Refutation Based on Very Simple Physics and No Mathematics</h4><p>Electricity consists of electrons flowing from a cathode of the battery to the (connected to the ground) anode of the battery.</p><blockquote>Every electron going through the arms and body of person N (furthest from the fence) has to flow through both arms of each of the previous persons closer to the electric fence. This means the last person cannot possibly receive more current than going through the arms of the previous people. This refutes the belief.</blockquote><p>Convinced?</p><p>Note that we did not need to calculate anything here, to refute the belief.</p><p>As for the currents through the bodies, we need a little mathematics.</p><h4>2.4 Refutation based on Current Flow Physics and Little Mathematics</h4><p>If one also wants to know by how much every next person receives less electricity, expressed in terms of ‘arm’-resistance r(a) and the arm to feet called ‘body’-resistance r(b), mathematical modelling comes into play.</p><p>The laws of Physics tells us in a very accurate way how current flows through resistor networks.</p><p>In fact, for any given resistor network, series or parallel or any combination of it, for which each resistor value is known, one can also solve that for all currents and voltages.</p><p>As for the physics, only two laws are needed: the Kirchhoff current law and the Kirchhoff voltage law.</p><p>The <a href="https://www.electronics-tutorials.ws/dccircuits/kirchhoffs-current-law.html">Kirchhoff Current Law</a> states that in each <em>node</em>, all the current that comes in equals the current that goes out.</p><p>The <a href="https://www.electronics-tutorials.ws/dccircuits/kirchhoffs-voltage-law.html">Kirchhoff Voltage Law</a> states that in each <em>loop</em>, the summation of all voltage drops along each resistor (and battery) in the loop adds up to zero.</p><p>For our human-chain we have the following network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*gg1A5kiN0RzyHpIxIsKtkA.png" /><figcaption>Resistor network describing the electrical connectivity and resistors from which mathematical equations to calculate currents (and voltages) will be derived.</figcaption></figure><p>In the left of the above figure, a single person is modelled, with a head and two arms. Each arms has a resistance r(i,a), with i the index of the person in the chain gang, from 1 on the left to N on the right. The body and legs will leak current from the center of the two arms to the ground along a resistance we call r(i,b).</p><p>We then chain N people in a row on the right of the above figure. They all face the same direction and left hands join right hands. The = sign in the network on the left of the right part represents the battery and has an upper voltage vu(0). The nodes vu(1), vu(2) etc… towards the right represent the voltage every person will perceive between both shoulders. From experience, an electrical engineer will know that one has a voltage drop from left to right. So the rightmost person will perceive a voltage vu(N) that is lower than voltage vu(N-1), that is lower than … vu(0). We also have voltages at ground/’down’ level ‘vd’ and theorize that they could increase by distance to the battery ground voltage vd(0)=0V.</p><p>The currents going through the arms are i(a,1), i(a,2), etc… towards the right, and are not necessarily equal for each person.</p><p>Each person leaks a current to the ground called i(b,1), i(b,2), … etc towards the right and these are not necessarily equal either.</p><p>At the feet/ground of the people, we assume currents i(g,1) ,i(g,2), … etc flowing from right to left in the ground. We assume that people have equal distance from each other and so the ground resistances from one person to the previous can be assumed equal. The currents however are not necessarily equal.</p><p><em>2.4.1 Currents through Arm: Refutation by inspection of Current Flows</em></p><p>If we just look at the current flow from person 1 to 2, we see that the current i(1,a) in the closest-to-the fence arm of person 1 gets split into a current i2a into the closest-to-the-fence arm of person 2 and a current i1b in person 1 his body to the ground. So i(a,2) = i(a,1) — i(b,1), so i(a,1) ≥ i(a,2), so currents through the arms from person 1 to person N get lower and lower i.o. higher! So i(a,1) ≥ i(a,2)≥ i(a,3)≥ … ≥ i(a,N). So this refutes the belief that person N will feel a higher current in his arm than any previous person! Note that this is true, whatever the resistances r(a,i) and r(b,i) are!</p><p><em>2.4.2 Current through Bodies: Refutation by Primary School Mathematics</em></p><p>As for the body currents, i(b,i), assuming the same r(b,i)for all i, and assuming the same ground level voltages vd for now, note that then i(b,i) = vu(i) / r(b,i) and since, from current i(i,a) direction to the right, the vu(i) decrease to the right, as in vu(b,0) ≥ vu(b,2)≥ vu(b,3)≥ … ≥ vu(b,N), it also holds that i(1,b) ≥ i(2,b)≥ i(3,b)≥ … ≥ i(N,b). So, assuming equal body resistance for all people, this also proves that the belief that body currents are larger towards the end of the chain is false.</p><p>Even if we assume that only the last person is barefoot in wet grass and the rest of them are all wearing insulating rubber soles, then r(b,N) &lt;&lt; r(b,i) for all i and the body current can become larger for person N then for the other people, but even in that case, the full current r(b,N) (and some more!) will still have to go through all the <em>arms</em> of all previous people, again refuting the belief that the last person will get more current through the his whole body than other people experience in their arms.</p><h4>2.5. Refutation by (Repeated) Full Calculation &amp; Secondary School Mathematics &amp; some Engineering</h4><p>Now, by applying Kirchhoff’s (conservation of) current law in every node where currents can merge or split, we get N equations in N variables I(1,a) to i(N,a), first for the top nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*_HHLgKO87wL3jySthWLz8A.png" /><figcaption>Kirchhoff’s Current Law on all Upper Nodes</figcaption></figure><p>and then N equations in N variables i(1,g) to i(N,g), for the bottom nodes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*tZesN3VFdQPdL1HsKFuFow.png" /><figcaption>Kirchhoff’s Current Law on all Lower Nodes</figcaption></figure><p>For the Kirchoff Voltage laws, we have, by going through all lines in the network. For the upper lines, this gives the equations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*xBhGnqVIm3xT2oiqpzF1Dg.png" /><figcaption>Kirchhoff’s Voltage Law on Upper Lines</figcaption></figure><p>For the vertical lines we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*N9OxzxjuDJGq1M096XED1Q.png" /><figcaption>Kirchhoff’s Voltage Law on Vertical Lines</figcaption></figure><p>For the lower lines we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*CzgHx_pf4wHRcntVTMBWbw.png" /><figcaption>Kirchhoff’s Voltage Law on Lower Lines</figcaption></figure><p>This gives a system of 5N linear equations for 3N current variables and 2(N+1) voltage variables, so for 5N+2 variables. However, in addition, we set v(l,0) to 0 and v(u,0) to the battery voltage, so we then have 5N+2 equations as well. That is nicely and easily solvable using some linear algebra.</p><p>Even though, there is only one solution here and we do not have an objective, to solve this, we can still use the Integer Linear Programming (ILP) solver Gurobi. There will be only continuous variables and the problem is a feasibility rather than optimisation problem.</p><p>For a real implementation of this problem, using the Gurobi solver for solving linear algebra systems, have a look at <a href="https://gist.github.com/PeterSels/bfc58a4f9d3b5b45d106bf79549522dd">this gist on github</a> or you can even get the source code from github <a href="https://github.com/PeterSels/OnComputation/tree/master/ChainGangOnAFence">here</a> and then run it on your own machine, assuming you have a Gurobi license.</p><p>The conclusion of the calculation experiments in that notebook is that indeed, in each case the current through the last person’s arm is always lower than the ones through the previous peoples arms. Also the body currents in the last person are always lower than the ones in the previous people, even if the last person is assumed to have (much) lower body resistance than the previous ones, since he is protected by the arm resistance of the chain of people before him.</p><h4>2.6. Refutation by (Repeated) Experimentation</h4><p>People may have no belief in the above scientific method, but it is fundamentally founded in the experimental method, where a law only becomes accepted while all experiments support it. A scientific law will only stand until one properly conducted experiment disproves it.</p><p>If you are still unconvinced, chances are that you want to experiment and find some willing mates to form a chain-gang and find yourself a ‘victim’ too. You may want to measure currents by holding Amere meters between hands rather than trust your possibly subjective sensation of current though.</p><p>I must warn that it is not a safe experiment. So <a href="https://en.wikipedia.org/wiki/Electrical_injury#:~:text=The%20NIOSH%20states%20%22Under%20dry,body&#39;s%20resistance%20to%20500%20ohms%22.">don’t try this at home</a>.</p><h3>3 Epilogue</h3><h4>3.1 Why do People hold Unfounded Beliefs?</h4><p>That this belief that the last person suffers most exists, to the degree that they even start believing they feel no current in their own bodies (e.g. ‘because they are just conductors’ or for whatever reason), or at least believe they will feel less so than the last person is altogether surprising!</p><p>Maybe people unconsciously think that the electrical laws behave like the ones where on an ice rink, people connect hand to hand in series and the first once swings the other ones around him. The centripetal force acts in a way such that the outer Nth person will pick up the highest speed, as such having an amplifying effect from person 1 to N. Of course, this is not the case for electricity.</p><p>But maybe it is just group psychology: “As a group, we will play a prank on a sole individual and make fun of him, bully him, which makes us psychologically strong.” Apparently this can even overrule even physical pain in ones own body!</p><p>Another possibility would be that people are more sensitive to the current through their body from neck through legs into the ground compared with current through their arms. In that case the last person could sense a current i(b,N)=C as higher than the previous people experiencing the same or even than a higher current i(a,i)=C+some in their arms. If that would be true, it would be purely subjective. In addition, the opposite is true: the density of the nervous system is larger in the hands than in the back, so one will be more sensitive to hand-to-hand currents than back-to-leg currents, as confirmed to me by a specialist medical doctor.</p><h4>3.2 A Better way to Play the Prank.</h4><p>A better way to play the prank would be to — as a pranking group — join all left hands together and join all right hands together, as such shunting each individual as a resistor in parallel with all others. The teasers would then each feel roughly 1/(N-1) of the current that the last person N would feel. This is the setup shown in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*-zgAcEGR7dkzWLQPE2qwAw.png" /><figcaption>Chain Gang setting up themselves in Parallel, as such lowering currents through their arms and bodies roughly by a factor N-1. Not so for person N though.</figcaption></figure><p>The left side of the figure shows N-1 people holding hands in parallel and one person (in red) receiving all the current going through the N-1 previous people. The current divides itself equally through the first N-1 people, so the voltages v1 to vN-1 are equal, so can all be joined into one node. Doing that, we get the (grey part in) circuit on the right of the figure, where the N-1 resistances Ra and Rb, combined in parallel, behave as single resistances Ra/(N-1) and Rb/(N-1). So, now, the person N will roughly receive N-1 times as much current as the other N-1 people playing the prank.</p><p>This is clearly the ‘somewhat smarter’ way <a href="https://simpsons.fandom.com/wiki/Martin_Prince">Martin Prince Jr</a> would do it! :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*4barCDWJu49YKCSdpFvmyg.gif" /><figcaption>Martin Prince Jr happy about ‘his’ Parallel Prank</figcaption></figure><p>However, note that person N will still receive somewhat lower currents compared to the case where you tease him into directly touching the fence. So there is no effect of ‘magic current multiplication’ or so happening by insertion of previous people before person N, but just adding extra resistance which lowers the current in person N.</p><h4>3.3 Conclusion</h4><p>The myth of person N suffering the most is totally busted. It’s quite the opposite!</p><p>One can only conclude science should be taught before pranking age. :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*_aNuhIt5FMzKwbZBN_v01Q.jpeg" /><figcaption>Physics for kids</figcaption></figure><p>Peter Sels, June 19th 2020. Written for my neighbour X and his neighbours.</p><p>Copyright © 2020 <a href="http://logicallyyours.com/">Logically Yours BV</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1ffda7597c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>