<rss xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title>Andy Holt</title><link>https://andyholt.github.io/</link><description>Andy Holt's landing page</description><generator>Hugo -- gohugo.io</generator><language>en</language><lastBuildDate>Tue, 07 Oct 2025 00:00:00 +0000</lastBuildDate><atom:link href="https://andyholt.github.io/index.xml" rel="self" type="application/rss+xml"/><item><title>Reconnecting After a Storm</title><link>https://andyholt.github.io/posts/2025/10/reconnecting-after-storm/</link><pubDate>Tue, 07 Oct 2025 00:00:00 +0000</pubDate><author>Andy Holt</author><guid>https://andyholt.github.io/posts/2025/10/reconnecting-after-storm/</guid><description><![CDATA[
<p>
I would never claim that we live at the beating heart of civilisation. But the
outskirts of Dundee are hardly the wilderness. Even so, a recent storm has
knocked out our internet access, and this is how I&#39;ve managed to get us
temporarily back on line. Hopefully it&#39;ll be a short term fix – but I fear it
may grow into one of those short term fixes that become all too permanent.</p>
<p>
I&#39;ve learned enough in trying to solve the problem to seem worth writing up.
It&#39;s not really concrete enough to record a &#34;how to&#34; in my personal notes, so a
blog post seemed like a fitting record.</p>
<div id="outline-container-headline-1" class="outline-2">
<h2 id="headline-1">
Losing connection
</h2>
<div id="outline-text-headline-1" class="outline-text-2">
<p>
Last Friday, a storm blew down a tree which fell on the phone and internet line
into the village. The first I knew of it was the internet connection being down
from our wifi network, though I didn&#39;t realise at first. Occasionally, the
internet connection gets dropped by our router, and resolves after a router
reboot. It&#39;s one of those issues that I should really sort out, but it&#39;s both
easy to fix by power cycling the router, and so intermittent that it would be
difficult to debug and know whether any solution has worked. So I&#39;ve lived with
the occasional dropping of the connection and needing to turn the router off and
on again.</p>
<p>
But this time, when my wife complained the router needed rebooting, it didn&#39;t
work. Then a minute or two later I had a text from our ISP that there was an
openreach problem, our service was down, and they were aiming to fix it by 2am.</p>
<p>
Being a Friday night, and a significant storm, I had my doubts about the 2am
fix. But I was pretty impressed by the observability and notification system
of the ISP.</p>
<p>
Over the weekend, the scale of the problem became clear as neighbours shared
their issues and attempts to get some info from various internet providers, and
photos of the fallen tree appeared on the local whatsapp groups.</p>
<p>
With no live TV in our house, we managed to survive a weekend without screen
time for the kids. But more pressing was whether the internet would be back by
Monday. Since I work remotely as a software engineer on a web platform, no
internet would make things rather difficult.</p>
<p>
While the village – which we live just outside of – isn&#39;t a large village,
it&#39;s also not at all remote, and is surrounded by other villages and
settlements. So I was surprised that a single line would completely knock out
internet for such a large populated area. So it&#39;s interesting to consider more
deeply the infrastructure on which we depend every day, yet never give any
thought to.</p>
</div>
</div>
<div id="outline-container-headline-2" class="outline-2">
<h2 id="headline-2">
Assessing the options
</h2>
<div id="outline-text-headline-2" class="outline-text-2">
<p>Once it became clear that the line wasn&#39;t going to be fixed for the start of the
week, I began to consider the options for getting some work done.</p>
<p>
One option is to relocate to somewhere with an internet connection, and spend a
week or two working out of coffee shops and libraries. There may still be some
of that, but I also didn&#39;t want to limit my access to decent sized monitors and
work off my 13 inch MacBook Air screen for an extended time. The 13 inch M3
MacBook Air is an <em>amazing</em> machine – capable, portable, and completely silent.
But it&#39;s much easier to do serious editing and research when plugged into a
couple of 4K monitors at my desk.</p>
<p>
Relocating also wouldn&#39;t solve the problem of internet access for the rest of
the family. Or outside of coffee shop hours (which working at a start up
involves quite a bit of).</p>
<p>
Another option was to get a 4G dongle – the USB stick that takes a sim card and
plugs into a laptop to provide access via the mobile phone network. My initial
guess was that this was the obvious way to go. But phone signal in our house
isn&#39;t great, and especially in the room I use for a study.</p>
<p>
Some research confirmed that a dongle was unlikely to serve very well, with the
tiny antenna of a compact, portable usb stick giving poor performance in
anything but the strongest coverage areas.</p>
<p>
However, another suggestion was to pay a little more than the cost of a dongle
and get a router which takes a sim card. I wasn&#39;t aware of this product category
at all, but it provides 2 major advantages. First, being somewhat bigger than a
dongle, it can make use of beefier antennae to make the most of whatever signal
there is. And secondly, not needing to plug in directly to the computer, it can
be positioned for best network signal, like next to a window on the other side
of the house.</p>
<p>
An additional benefit of a mobile service router is that, if I could find a way
to connect it to our existing router, all our other devices in the house could
remain on the existing networks, without the need to switch networks for a few
days or weeks until normal service is resumed.</p>
</div>
</div>
<div id="outline-container-headline-3" class="outline-2">
<h2 id="headline-3">
The current temp-fix solution
</h2>
<div id="outline-text-headline-3" class="outline-text-2">
<p>
There were two big unknowns in embarking on this project, which are still
largely unknown as I write. One is how long this temporary solution will be
needed – it may be for just a few days, though probably a couple of weeks.
Hopefully not many weeks or months, though it could be. The other unknown is how
well a 4G or 5G router would perform, whether the stability of connection and
speed would be good enough to make working from home viable, however
temporarily.</p>
<p>
Given these uncertainties, I wasn&#39;t going to fork out hundreds on a state of the
art router. Some online recommendations and a timely Amazon deal led me to the
TP-Link TL-MR100. The specs are not particularly impressive, but it was cheap
enough to try (at least with Amazon&#39;s return policy), and available quickly
enough to give it a go. I was pretty confident the router&#39;s &#34;up to 300Mbps&#34;
wasn&#39;t going to be the rate limiting factor. That would be about 15 times faster
than our usual download speed anyway.</p>
<p>

</p>
<p>
After jumping through what felt like an inordinate number of hoops, I also
managed to order a monthly, unlimited data sim from the provider rated as having
the best service in our area, EE. Neither of our phones are on EE, and the
fairly rubbish reception we get on our network at home usually isn&#39;t an issue as
we&#39;re on the WiFi anyway. They promised 4G speeds capped at 100Mbps, though I
had my doubts we&#39;d be bumping into any such speed restrictions.</p>
<p>
Today, both the sim card and router arrived, so I got them set up this evening,
curious to see how the 4G router would perform, and how difficult it would be to
get our existing router as an access point, served by the new router.</p>
<p>
The answers, not to bury the lede any further, are that the set up was
reasonably simple, and the performance is fairly terrible.</p>
<p>
Initially, I just set up the new router as plug and play. Put in the sim card,
turn it on, and move it around a few different places to test its signal and
performance. The router has 3 LEDs to indicate signal level, and everywhere I
tested had 2 or 3 lit. But speed tests started at around 500–600kbps, and
haven&#39;t gone above 2Mbps.</p>
<p>
I&#39;m not sure what speed I was expecting, but this has been pretty disappointing.
Tethering off my phone, with only a single or couple of bars of signal (out
of 4) tended to give about 3 times better speeds.</p>
<p>
Despite the poor speed test results, I was reasonably impressed that I managed
to stream some &#34;Have I Got News for You&#34; and YouTube. Not at very high quality,
but watchable.</p>
<p>
The speed isn&#39;t great, but the connection stability seems to be an improvement
on my tethering experience over the past couple of days. The connection dropping
every few minutes has been far more annoying than the relatively slow download
speeds.</p>
<p>
As to setting up the router with our existing router (what this was supposed to
be all about), I&#39;ve learned a bit more about networking, so it hasn&#39;t been a
complete waste of time.</p>
<p>
The setup I&#39;ve ended up with is the TP-Link 4G router providing the intenet
connection, and forwarding all traffic to our existing router, operating in the
&#34;DMZ&#34; (demilitarised zone), and our usual router then doing all its normal jobs.</p>
<p>
To do this, I first gave the TP-Link router a new local, static IP address and
set up the DHCP range. Then our normal router is plugged in with its WAN port to
the TP-Link by ethernet cable. Then a new WAN interface is configured for the
existing router. Once the access-point router is assigned an IP by the TP-Link, that address can
be set for NAT forwarding as DMZ.</p>
<p>
My understanding is that the TP-Link router then just passes everything to the
existing router. The existing router acts as normal, but receiving packets from
the 4G router instead of the usual broadband line and modem.</p>
<p>
Time will tell whether the connection is serviceable, but I&#39;ve managed to fix my
hugo config and write up this post using the new connection. And so far, the
stability has been far better than my tethering experience had been.</p>
<p>
Tethering my laptop from my phone was bringing me to the end of mine.</p>
</div>
</div>
]]></description></item><item><title>Solving Leetcode Problem #399, "Evaluate Division"</title><link>https://andyholt.github.io/posts/2023/11/solving-leetcode-399/</link><pubDate>Thu, 02 Nov 2023 00:00:00 +0000</pubDate><author>Andy Holt</author><guid>https://andyholt.github.io/posts/2023/11/solving-leetcode-399/</guid><description><![CDATA[
<p>
Because I studied engineering and not computer science, I never took a specific
class on algorithms and data structures. In an attempt to self-educate and catch
up, I&#39;ve been working through a number of <a href="https://leetcode.com/">Leetcode</a> problems, working with
Python. This has helped me get a better grasp of some of the standard algorithm
and data structure problems and approaches, as well as helping me learn more
about Python&#39;s data structures and their properties, and brushing up my Python
style.</p>
<p>
A nice problem, for which I devised what I think is a fairly nice solution, is
<a href="https://leetcode.com/problems/evaluate-division/">399. Evaluate Division</a>.</p>
<div id="outline-container-headline-1" class="outline-2">
<h2 id="headline-1">
The problem
</h2>
<div id="outline-text-headline-1" class="outline-text-2">
<p>The problem is to use a series of divisor equations to solve another series of
equations. In other words, a set of ratios between a number of variables is
given, and a different set of ratios of variables is required. For example, the
given equations may be:</p>
<p>
<data id="id-1" data-raw></data></p>
<p>
and the required equations to evaluate may be:</p>
<p>
<data id="id-2" data-raw></data></p>
<p>
In the problem definition, unsolvable equations (including those actually
solvable but using undefined variables like $\frac{x}{x}$ here) should receive
the result -1.0, and values are otherwise positive to ensure the insoluble case
is distinguishable. Solving the equations manually is straightforward. But it&#39;s
quite an interesting problem to write a programme to solve a general set of
input and output equations with the added complication that some required
equations can&#39;t be solved.</p>
</div>
</div>
<div id="outline-container-headline-2" class="outline-2">
<h2 id="headline-2">
Working towards a solution
</h2>
<div id="outline-text-headline-2" class="outline-text-2">
<p>After briefly considering whether a matrix-based approach might be useful, and
quickly discovering how rusty my linear algebra is, I turned to a graph based
approach. Each variable from the input equations is represented by a node, and
the relation of one variable to another is represented by a directed and
weighted edge. So the equation:
<data id="id-3" data-raw></data>
can be represented by the graph:
<div class="mermaid" id="id-4">graph LR
   a((a)) -- 2.0 --&gt; b((b))</div>
A more complex set of equations from one of the problem test cases is:
<data id="id-5" data-raw></data>
This can be represented in the graph:
<div class="mermaid" id="id-6">graph TB
   a((a)) -- 2.0 --&gt; b((b))
   c((c)) -- 3.0 --&gt; b
   d((d)) -- 4.0 --&gt; b
   w((w)) -- 5.0 --&gt; x((x))
   y((y)) -- 6.0 --&gt; x
   z((z)) -- 7.0 --&gt; x
   w -- 8.0 --&gt; d</div></p>
<p>
To solve the required equations, one simply traverses the graph, starting at the
numerator node and ending at the denominator node, and taking the product of the
edges over the route. For example, if a required equation is $\frac{w}{b}$, we
can solve this by the substitutions:
<data id="id-7" data-raw></data></p>
<p>
From this procedure, it is clear that the product of edges traversed is
equivalent to the substitutions required to get the numerator in terms of the
denominator, and therefore the product of edges gives the result. We move from
node $w$ to node $d$, with edge weight 8, then from node $d$ to node $b$ with
edge weight 4, and the product gives 32.</p>
<p>
Initially, I thought the task would be best approached by using a single
direction of edge to represent each input equation. While the equation
<data id="id-8" data-raw></data>
defines two relations:
<data id="id-9" data-raw></data>
the difficulty of encoding both relations in the graph is that it introduces
cycles into the graph.
<div class="mermaid" id="id-10">graph LR
    a((a)) -- 2.0 --&gt; b((b))
    b -- 0.5 --&gt; a</div></p>
<p>
Using only a single edge will result in a non-cyclic graph for a well determined
set of input equations, and this makes traversing the graph simple.</p>
<p>
A single direction of graph makes traversal simple, but brings a challenge.
Undefined equations (which receive the answer -1.0) are those for which no path
exists from numerator to denominator. But if the equation demanded in the
example above were not $\frac{w}{b}$ but instead $\frac{b}{w}$, this would
result in a wrong answer.</p>
<p>
My solution to overcome this was to first try to traverse the graph from
numerator to denominator. But if this failed, then try traversing from
denominator to numerator, then return the inverse of the edge products. Thus
while the traversal $b \rightarrow w$ will result in failure and a wrong returned
value of -1.0, when we try $w \rightarrow b$, we have success, and can invert
the product to get the reverse journey.</p>
<p>
Two further cases require attention. Using the information encoded in the graph,
both $\frac{a}{c}$ and $\frac{d}{x}$ are solvable, using substitution of values.
In the case of $\frac{a}{c}$, the common child node $b$ gives a common term to
solve, while in the case of $\frac{d}{x}$, the parent of both nodes $w$ provides
a common term. I therefore added further logic to check if nodes had either a
common child or a common parent, and use these to get the correct result.</p>
<p>
However, the nature of the connected graph is that any pair of nodes in the
graph will yield a valid solution, by enough steps of substitution, and using
direct common parents and children is not enough. For example, the relation
$\frac{z}{c}$ can be obtained by substitution through $x, w, d, b$.<sup class="footnote-reference"><a id="footnote-reference-1" href="#footnote-1">1</a></sup> This
could be resolved by recursively searching for common children and parents of
the intermediate nodes at every point until an exhaustive search has been
carried out between the two nodes. But at this point, it was clear that the
single edge, non-cyclic graph was actually becoming a liability rather than a
help.</p>
</div>
</div>
<div id="outline-container-headline-3" class="outline-2">
<h2 id="headline-3">
Simplifying by adding complexity
</h2>
<div id="outline-text-headline-3" class="outline-text-2">
<p>The path from any node within a connected graph to any other could be easily
found if we make the graph more complex: by adding both relations represented by
an equation. While the cycles this introduces between every pair of directly
connected nodes must be carefully navigated in traversing the graph (so as to
avoid falling into infinite loops), the additional complexity of traversal pays
for itself in being able to follow a straightforward path between any two nodes
in the graph.</p>
<p>
Adding both relations for the example we have been following results in the
following graph:
<div class="mermaid" id="id-11">graph LR
   a((a)) -- 2.0 --&gt; b((b))
   b -- 0.5 --&gt; a
   c((c)) -- 3.0 --&gt; b
   b -- 0.333 --&gt; c
   d((d)) -- 4.0 --&gt; b
   b -- 0.25 --&gt; d
   w((w)) -- 5.0 --&gt; x((x))
   x -- 0.2 --&gt; w
   y((y)) -- 6.0 --&gt; x
   x -- 0.1667 --&gt; y
   z((z)) -- 7.0 --&gt; x
   x -- 0.143 --&gt; z
   w -- 8.0 --&gt; d
   d -- 0.125 --&gt; w</div></p>
<p>
With this new, more complex graph, solving any determinate equation becomes as
simple as following the edges and taking their product. However, the traversal
becomes slightly more complicated in that we need to avoid following infinite
cycles in the graph.</p>
<p>
I used a depth first search (DFS) approach to traversal, using a recursive
function to follow to any connected nodes from each node visited. To avoid
infinite loops, it becomes necessary to keep track of nodes which have been
already visited, and avoid trying them at each new level of recursion. This is
quite straightforward, simply maintaining a list of visited nodes and adding the
current node to the list before calling the recursive function on child nodes.
So here we find our paradoxical result: by making the graph more complex, we
have greatly simplified the problem as a whole. And probably if I had been aware
of this from the beginning, I would have solved the problem quicker, and
wouldn&#39;t think of it as being quite so nice a problem as it seems having started
with an overly complex strategy. There are upsides in taking the scenic route.</p>
</div>
</div>
<div id="outline-container-headline-4" class="outline-2">
<h2 id="headline-4">
Code and walk-through
</h2>
<div id="outline-text-headline-4" class="outline-text-2">
<p>So now that the strategy is clear, here is the code I submitted to solve the
Leetcode problem.</p>
<div class="src src-python">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Node</span>:
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">__init__</span>(self, name<span style="color:#f92672">=</span><span style="color:#e6db74">&#34;&#34;</span>, edgeNodes<span style="color:#f92672">=</span>[], edgeWeights<span style="color:#f92672">=</span>[]):
</span></span><span style="display:flex;"><span>        self<span style="color:#f92672">.</span>name <span style="color:#f92672">=</span> name
</span></span><span style="display:flex;"><span>        self<span style="color:#f92672">.</span>edgeNodes <span style="color:#f92672">=</span> edgeNodes
</span></span><span style="display:flex;"><span>        self<span style="color:#f92672">.</span>edgeWeights <span style="color:#f92672">=</span> edgeWeights
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span><span style="color:#66d9ef">class</span> <span style="color:#a6e22e">Solution</span>:
</span></span><span style="display:flex;"><span>    nodeDict <span style="color:#f92672">=</span> {}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">traversalCost</span>(
</span></span><span style="display:flex;"><span>        self, start: Optional[<span style="color:#e6db74">&#34;Node&#34;</span>], end: <span style="color:#e6db74">&#34;Node&#34;</span>, visited: List[<span style="color:#e6db74">&#34;Node&#34;</span>], weight: float
</span></span><span style="display:flex;"><span>    ) <span style="color:#f92672">-&gt;</span> float:
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">if</span> start <span style="color:#f92672">is</span> <span style="color:#66d9ef">None</span>:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#f92672">-</span><span style="color:#ae81ff">1</span> <span style="color:#f92672">*</span> weight
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">elif</span> end <span style="color:#f92672">==</span> start:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> weight
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">else</span>:
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">for</span> idx, n <span style="color:#f92672">in</span> enumerate(start<span style="color:#f92672">.</span>edgeNodes):
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">if</span> n <span style="color:#f92672">in</span> visited:
</span></span><span style="display:flex;"><span>                    <span style="color:#66d9ef">continue</span>
</span></span><span style="display:flex;"><span>                res <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>traversalCost(
</span></span><span style="display:flex;"><span>                    n, end, visited <span style="color:#f92672">+</span> [n], weight <span style="color:#f92672">*</span> start<span style="color:#f92672">.</span>edgeWeights[idx]
</span></span><span style="display:flex;"><span>                )
</span></span><span style="display:flex;"><span>                <span style="color:#66d9ef">if</span> res <span style="color:#f92672">&gt;=</span> <span style="color:#ae81ff">0</span>:
</span></span><span style="display:flex;"><span>                    <span style="color:#66d9ef">return</span> res
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">return</span> <span style="color:#f92672">-</span><span style="color:#ae81ff">1.0</span>
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">def</span> <span style="color:#a6e22e">calcEquation</span>(
</span></span><span style="display:flex;"><span>        self, equations: List[List[str]], values: List[float], queries: List[List[str]]
</span></span><span style="display:flex;"><span>    ) <span style="color:#f92672">-&gt;</span> List[float]:
</span></span><span style="display:flex;"><span>        self<span style="color:#f92672">.</span>nodeDict <span style="color:#f92672">=</span> {}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">for</span> i <span style="color:#f92672">in</span> range(len(equations)):
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">if</span> equations[i][<span style="color:#ae81ff">0</span>] <span style="color:#f92672">not</span> <span style="color:#f92672">in</span> self<span style="color:#f92672">.</span>nodeDict:
</span></span><span style="display:flex;"><span>                self<span style="color:#f92672">.</span>nodeDict[equations[i][<span style="color:#ae81ff">0</span>]] <span style="color:#f92672">=</span> Node(equations[i][<span style="color:#ae81ff">0</span>], [], [])
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">if</span> equations[i][<span style="color:#ae81ff">1</span>] <span style="color:#f92672">not</span> <span style="color:#f92672">in</span> self<span style="color:#f92672">.</span>nodeDict:
</span></span><span style="display:flex;"><span>                self<span style="color:#f92672">.</span>nodeDict[equations[i][<span style="color:#ae81ff">1</span>]] <span style="color:#f92672">=</span> Node(equations[i][<span style="color:#ae81ff">1</span>], [], [])
</span></span><span style="display:flex;"><span>            self<span style="color:#f92672">.</span>nodeDict[equations[i][<span style="color:#ae81ff">0</span>]]<span style="color:#f92672">.</span>edgeNodes<span style="color:#f92672">.</span>append(
</span></span><span style="display:flex;"><span>                self<span style="color:#f92672">.</span>nodeDict[equations[i][<span style="color:#ae81ff">1</span>]]
</span></span><span style="display:flex;"><span>            )
</span></span><span style="display:flex;"><span>            self<span style="color:#f92672">.</span>nodeDict[equations[i][<span style="color:#ae81ff">0</span>]]<span style="color:#f92672">.</span>edgeWeights<span style="color:#f92672">.</span>append(values[i])
</span></span><span style="display:flex;"><span>            self<span style="color:#f92672">.</span>nodeDict[equations[i][<span style="color:#ae81ff">1</span>]]<span style="color:#f92672">.</span>edgeNodes<span style="color:#f92672">.</span>append(
</span></span><span style="display:flex;"><span>                self<span style="color:#f92672">.</span>nodeDict[equations[i][<span style="color:#ae81ff">0</span>]]
</span></span><span style="display:flex;"><span>            )
</span></span><span style="display:flex;"><span>            self<span style="color:#f92672">.</span>nodeDict[equations[i][<span style="color:#ae81ff">1</span>]]<span style="color:#f92672">.</span>edgeWeights<span style="color:#f92672">.</span>append(<span style="color:#ae81ff">1.0</span> <span style="color:#f92672">/</span> values[i])
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        res <span style="color:#f92672">=</span> [<span style="color:#ae81ff">0</span>] <span style="color:#f92672">*</span> len(queries)
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">for</span> idx, q <span style="color:#f92672">in</span> enumerate(queries):
</span></span><span style="display:flex;"><span>            print(<span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;Handling query </span><span style="color:#e6db74">{</span>idx<span style="color:#e6db74">}</span><span style="color:#e6db74">, which is </span><span style="color:#e6db74">{</span>q<span style="color:#e6db74">}</span><span style="color:#e6db74">&#34;</span>)
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">if</span> q[<span style="color:#ae81ff">0</span>] <span style="color:#f92672">not</span> <span style="color:#f92672">in</span> self<span style="color:#f92672">.</span>nodeDict <span style="color:#f92672">or</span> q[<span style="color:#ae81ff">1</span>] <span style="color:#f92672">not</span> <span style="color:#f92672">in</span> self<span style="color:#f92672">.</span>nodeDict:
</span></span><span style="display:flex;"><span>                print(<span style="color:#e6db74">f</span><span style="color:#e6db74">&#34;One of </span><span style="color:#e6db74">{</span>q[<span style="color:#ae81ff">0</span>]<span style="color:#e6db74">}</span><span style="color:#e6db74"> or </span><span style="color:#e6db74">{</span>q[<span style="color:#ae81ff">1</span>]<span style="color:#e6db74">}</span><span style="color:#e6db74"> not known, give -1.0&#34;</span>)
</span></span><span style="display:flex;"><span>                res[idx] <span style="color:#f92672">=</span> <span style="color:#f92672">-</span><span style="color:#ae81ff">1.0</span>
</span></span><span style="display:flex;"><span>            <span style="color:#66d9ef">else</span>:
</span></span><span style="display:flex;"><span>                res[idx] <span style="color:#f92672">=</span> self<span style="color:#f92672">.</span>traversalCost(
</span></span><span style="display:flex;"><span>                    self<span style="color:#f92672">.</span>nodeDict[q[<span style="color:#ae81ff">0</span>]], self<span style="color:#f92672">.</span>nodeDict[q[<span style="color:#ae81ff">1</span>]], [], <span style="color:#ae81ff">1.0</span>
</span></span><span style="display:flex;"><span>                )
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">return</span> res</span></span></code></pre></div>
</div>
<p>
Lines 1–5 define the <code>Node</code> class which is used to represented the graph. Edges
between nodes are defined as attributes of the parent node from which they come,
with a reference to the child node. This is useful for traversing the graph,
since everything needed to operate from a given node is contained within that
object.</p>
<p>
In the <code>Solution</code> class, a class attribute <code>nodeDict</code> is make which can be accessed
by all class methods. This provides a lookup map from a node&#39;s name, which is
the variable it represents, to the object which defines that node.</p>
<p>
The method <code>traversalCost</code> performs the traversal using a DFS approach, and
returns the cost of the product of edges for traversing from a starting node to
an end node. If the returned value is negative, the end node is not reachable
from the starting node, and the value returned is unimportant. If the start node
is <code>None</code>, no nodes can be reached, so a negative result is returned. If we have
reached the end node, there is no additional cost, since the end has already
been reached, and we return the current cost, that is <code>weight</code>. Otherwise, we loop
through the child nodes from the current node. In order to avoid infinite loops,
if a node appears in the <code>visited</code> list, it is skipped. Otherwise, we perform the
recursion with the child node. <code>traversalCost</code> is called again, now using the
child node as the starting node, keeping the same target node, <code>end</code>. The parent
node is added to the list of visited nodes passed to the next level of
recursion, and the weight of the edge from parent to child is multiplied by the
weight from the original start to the present node. If any child node returns
with a positive value, it means the end node was reached, with a cost from the
current node of <code>res</code>, so return this value to the calling function. If none of
the children return a positive value, <code>traversalCost</code> will return with value -1.0.</p>
<p>
The main function is <code>calcEquation</code>. This first initialises the empty <code>nodeDict</code> to
makes sure the graph is empty when beginning a new test case. The arguments
<code>equations</code> and <code>values</code> together define the input equations, and these are used to
build the graph in the first for loop, lines 35–47.</p>
<p>
Once the graph is built, it can be used to get the result for each of the
<code>queries</code>, the required equations. For each query, the two variables which define
the equation are first checked to be known in the graph, and if they are not,
the result of -1.0 is used. If they are both known, <code>traversalCost</code> is called from
the numerator to the denominator. If the returned value is negative, -1.0 is the
defined value as required in the problem statement, or otherwise, the product of
edges is returned. Once all queries have been evaluated, <code>calcEquation</code> returns
the list of results.</p>
<p>
The exact performance of my approach is somewhat hard to measure, since Leetcode
gives a huge variance of run times and percentiles for different runs of the
same code. I tend to find that even if I use the same code as one of the very
fastest solutions, my best runs are a bit slower – perhaps recent Python
versions have bigger imports and slower runtimes? So I was pleased with a result
of this one of 31ms and beating 94.90% of all Python solutions for the problem.
While I don&#39;t read too much into Leetcode&#39;s figures, and my purpose here is to
learn about algorithms, data structures, and idiomatic Python – I&#39;m not trying
to score the very best times – these results seem pretty solid to me.</p>
<p>
If you can think of a better way of approaching this problem, or a better way of
implementing it in Python, let me know <a href="https://mas.to/@andyholt">on Mastodon</a>.</p>
</div>
</div>
<div id="outline-container-headline-5" class="outline-2">
<h2 id="headline-5">
Footnotes
</h2>
</div>
<div class="footnotes">
<hr class="footnotes-separatator"/>
<div class="footnote-definitions">
<div class="footnote-definition">
<sup id="footnote-1"><a href="#footnote-reference-1">1</a></sup>
<div class="footnote-body">
<p>Left as an exercise for the reader.</p>
</div>
</div>
</div>
</div>
]]></description></item><item><title>Building The Blanding Consultant</title><link>https://andyholt.github.io/posts/2023/08/building-blanding-consultant/</link><pubDate>Thu, 31 Aug 2023 00:00:00 +0000</pubDate><author>Andy Holt</author><guid>https://andyholt.github.io/posts/2023/08/building-blanding-consultant/</guid><description><![CDATA[
<p>
<a href="https://blanding-consultant.nw.r.appspot.com">The Blanding Consultant</a> is an AI<sup class="footnote-reference"><a id="footnote-reference-1" href="#footnote-1">1</a></sup> character name generator,
producing P. G. Wodehouse style character names. These generated character names
can be used just for fun, or as a prompt for creative writing or improvisation.</p>
<p>
<a href="https://en.wikipedia.org/wiki/P._G._Wodehouse">P. G. Wodehouse</a><sup class="footnote-reference"><a id="footnote-reference-2" href="#footnote-2">2</a></sup> (1881–1975) was an English humourist and writer, known for his
stories set among the upper classes of early 20th century English society. He is
the master of the gentle but hilarious story, with delightfully interwoven plot
lines, unforgettable characters, and arresting turns of phrase: &#34;He looked like
a sheep with a secret sorrow.&#34; Probably his two best known series are <em>Jeeves
and Wooster</em> and <em>Blandings</em>. The name of my character name generator is a
reference to <em>Blandings</em>, the castle home of Lord Emsworth and his prize pig,
Empress. Its also a play on being a branding consultant – very clever, but
perhaps not quite Wodehousian.</p>
<p>
In this post, I will detail the process of building The Blanding Consultant.</p>
<div id="outline-container-headline-1" class="outline-2">
<h2 id="headline-1">
Generating the names
</h2>
<div id="outline-text-headline-1" class="outline-text-2">
<p>New character names are generated by a recurrent neural network, using
<a href="https://github.com/tensorflow/tensorflow">TensorFlow</a> in Python. To train the network, I first needed a list of the
character names in Wodehouse stories. Thankfully Wikipedia has a <a href="https://en.wikipedia.org/wiki/List_of_P._G._Wodehouse_characters">page</a> dedicated
to just such a list, which needed just a little tidying up and normalising to
provide a training data set:</p>
<pre class="example">
&#34;Battling&#34; Billson
&#34;Gazeka&#34; Firby-Smith
&#34;Puffy&#34; Benger
&#34;Smooth&#34; Sam Fisher
&#34;Spennie&#34;, Earl of Dreever
Adair
Admiral George J. &#34;Fruity&#34; Biffen
Agatha Gregson, Lady Worplesdon
Agnes Flack
...
</pre>
<p>
Unfortunately, though Wodehouse was prolific as an author, the number of
characters across all his stories is rather limited: I got 415 in my training
set. Generally we need at least tens of thousands, ideally hundreds of thousands
of examples to train a good machine learning model, so a few hundred character
names is clearly insufficient. A workaround is to start with a neutral network
which has been trained on general English language data, and tune this with a
final stage of training on the limited data set we want to emulate. The
<a href="https://github.com/minimaxir/textgenrnn">textgenrnn</a> project provides exactly such a model, which can be easily retuned to
the Wodehouse character name training set. The project hasn&#39;t been updated for a
few years, so it took a little bit of debugging to get it running with the
latest versions of TensorFlow and Keras, but once running, it performed
remarkably well.</p>
<p>
The next issue was to get the level of tuning to the character name data right:
too little, and the model would simply produce general English, not
distinctively Wodehousian names. But too much, and the model would become
overfitted, and simply reproduce actual characters, being unable to produce
similar, but distinctive, character names. I found that ten epochs got the right
balance, and was reliability producing original, but recognisably Wodehousian,
characters.</p>
<div class="src src-python">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span>  <span style="color:#f92672">from</span> textgenrnn <span style="color:#f92672">import</span> textgenrnn
</span></span><span style="display:flex;"><span>  textgen <span style="color:#f92672">=</span> textgenrnn()
</span></span><span style="display:flex;"><span>  textgen<span style="color:#f92672">.</span>train_from_file(<span style="color:#e6db74">&#39;wodehouse-characters-su.txt&#39;</span>, num_epochs<span style="color:#f92672">=</span><span style="color:#ae81ff">10</span>)</span></span></code></pre></div>
</div>
<p>
One the model was trained, the next stage was to turn this model into a web app,
with an API to return a character name when requested. I built this using Flask,
since the machine learning was being done in Python anyway. This is one of the
joys of using Python as a programming language: its easy to cross from one field
into another, using specialised and mature packages.</p>
<p>
I added some extended functionality to the name generator, to allow the user to
adjust the &#34;absurdity&#34; of the names given. This absurdity measure translates
into the &#34;<a href="http://karpathy.github.io/2015/05/21/rnn-effectiveness/">temperature</a>&#34; of the neural network generation. A low value means more
safer samples generated, at the cost of being more likely to replicate actual
character names instead of generating new ones. A higher absurdity means more
risky character name generation: more original, but at the cost of being more
likely to be nonsense.</p>
<p>
Another extended feature is the ability to provide a &#34;prefix&#34; for the generator,
a letter, title, name which becomes the start of the generated name. This allows
a user to generate a particular kind of name, should they need a more specific
character. For example, one can provide a male or female name to produce a
specifically gendered character, or a title to create a Lord, a Lady, or some
other appropriate aristocrat.</p>
</div>
</div>
<div id="outline-container-headline-2" class="outline-2">
<h2 id="headline-2">
Building the frontend
</h2>
<div id="outline-text-headline-2" class="outline-text-2">
<p>With the backend working, my attention turned to the frontend. It was all very
well to have a flask app running well, responding to URL requests with JSON
data. But that&#39;s not very user friendly. It also gave me the opportunity to
learn <a href="https://react.dev/">React</a>. Other than the initial learning curve of learning React, and
frontend development in general, I found building in React straightforward and
an enjoyable process.</p>
<p>
The biggest hurdle in developing The Blanding Consultant app was how to hook up
the frontend React app to the backend api provided by Flask. Many forum and blog
posts suggested that this would require the <code>useEffect</code> hook. However, the nature
of the app is that the API data only updates when requested by clicking the
&#34;Create Name&#34; button. Instead, the app can simply make a request using <code>fetch()</code> as
part of handling the button click, and use this to update state, in a <code>.then</code>
handler.</p>
<p>
The final stage of building the frontend was the aesthetic. The Blandings
novels, like most of Wodehouse, are set in an English stately home of the early
20th century, so an art deco theme seemed appropriate, but I also wanted it to
be clean and simple – after all, Lord Emsworth is no Gatsby.</p>
<p>

</p>
</div>
</div>
<div id="outline-container-headline-3" class="outline-2">
<h2 id="headline-3">
Deployment
</h2>
<div id="outline-text-headline-3" class="outline-text-2">
<p>Once the frontend was running locally and interacting with the backend API, the
final step was deployment, so as to be a real life web app. I chose to use
Google Cloud for deployment, mainly because I wanted to learn how to use Google
Cloud, and it offers very flexible hosting options.</p>
<p>
I decided to run the backend and the frontend as two separate web apps, running
each as an independent service, providing maximum modularity, and allowing
moving of either part to a different service or hosting arrangement if desired.</p>
<p>
Getting the backend running on Google Cloud App Engine was more difficult than
anticipated. The gunicorn server would start up and begin initialising, but then
the process would be killed before a request could receive a response. Debugging
in GCloud was challenging, as there did not seem to be a straightforward way to
get debugging information from the server. After several hours of fruitless
debugging, I managed to access enough of an error message (by copy-pasting an
error message from the GCloud dashboard into a text editor) to find that the
process was being killed by the supervisor because of high memory usage.</p>
<p>
Since the app was taking up too much memory, this led me to look closely at the
memory usage, and I discovered a memory leak. This was difficult to diagnose,
because it appeared not to be a single object taking up lots of memory
(<code>tracemalloc</code> therefore did not help), but many, many small objects each using a
small amount of memory, building up. The solution was to use keras to clean up
in between each name generation:</p>
<div class="src src-python">
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;"><code class="language-python" data-lang="python"><span style="display:flex;"><span>  tf<span style="color:#f92672">.</span>keras<span style="color:#f92672">.</span>backend<span style="color:#f92672">.</span>clear_session()
</span></span><span style="display:flex;"><span>  gc<span style="color:#f92672">.</span>collect()</span></span></code></pre></div>
</div>
<p>Even with this memory leak fixed, the memory usage was still too high to run in
GCloud&#39;s base F1 instance. Deploying to an F2 instance gave enough memory
overhead to run the app without problems. The warm up time of the RNN is
significant, so I have tried to configure GCloud to have a process running and
ready to respond, even when things have been quiet for some time.</p>
<p>
Deploying the frontend was much simpler by comparison, no doubt in part because
I had learned to use GCloud and the appropriate tools and services while dealing
with the backend deployment.</p>
<p>
The most useful next step of development would probably be to try to get the
name generating neural network to run with a smaller memory footprint. This
would not be simple, however, as this would require jettisoning the <code>textgenrnn</code>
package. It would be a good exercise to use TensorFlow directly for the neural
net, but this will reintroduce the problem of having an intrinsically small
training data set.</p>
<p>
This was an interesting project, giving me the opportunity to develop my
full-stack web development skills. The Blanding Consultant is available online
<a href="https://blanding-consultant.nw.r.appspot.com/">here</a>.</p>
</div>
</div>
<div class="footnotes">
<hr class="footnotes-separatator"/>
<div class="footnote-definitions">
<div class="footnote-definition">
<sup id="footnote-1"><a href="#footnote-reference-1">1</a></sup>
<div class="footnote-body">
<p>I prefer the term &#34;machine learning&#34;. This is not <em>just</em> pedantry and
personal choice. The term machine learning is more precise and, I would argue,
more accurate. While AI has a specific definition within the CS field (as a
superset of ML), this is generally not understood when AI is spoken of
colloquially and within political and media discussions. So I use the term for
its attention grabbing value here, but will use &#34;machine learning&#34; from now on.</p>
</div>
</div>
<div class="footnote-definition">
<sup id="footnote-2"><a href="#footnote-reference-2">2</a></sup>
<div class="footnote-body">
<p>Pronounced <em>Wood-house</em>. I don&#39;t know why its spelt that way
either.</p>
</div>
</div>
</div>
</div>
]]></description></item></channel></rss>