<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ibrahim Nauman</title>
    <description>The latest articles on DEV Community by Ibrahim Nauman (@ibrahim_nauman_786).</description>
    <link>https://dev.to/ibrahim_nauman_786</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4196219%2Fb8787811-84ed-4468-bcbb-e2272541dfb9.jpg</url>
      <title>DEV Community: Ibrahim Nauman</title>
      <link>https://dev.to/ibrahim_nauman_786</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ibrahim_nauman_786"/>
    <language>en</language>
    <item>
      <title>Load Bank Testing an Industrial Generator: Planning the Steps and Checking the Log With Python</title>
      <dc:creator>Ibrahim Nauman</dc:creator>
      <pubDate>Tue, 17 Nov 2026 09:51:00 +0000</pubDate>
      <link>https://dev.to/ibrahim_nauman_786/load-bank-testing-an-industrial-generator-planning-the-steps-and-checking-the-log-with-python-2i9k</link>
      <guid>https://dev.to/ibrahim_nauman_786/load-bank-testing-an-industrial-generator-planning-the-steps-and-checking-the-log-with-python-2i9k</guid>
      <description>&lt;p&gt;A standby set that only ever runs its weekly no-load exercise is an untested machine. We at Enpower see this on factory sites across Punjab and Sindh: the set starts every Friday, idles for ten minutes, and nobody knows whether it can carry its rating until the grid drops in the middle of a shift. A load bank test answers that question on your schedule instead of the feeder's. For an industrial generator that protects a production line, it's one of the most useful days in the maintenance year.&lt;/p&gt;

&lt;p&gt;This post is for the engineers and maintenance people who run that test. Choosing the set in the first place is a separate job, and our &lt;a href="https://enpower.com.pk/industrial-generators-in-pakistan/" rel="noopener noreferrer"&gt;guide to industrial brands and capacities&lt;/a&gt; covers it. Here we'll plan the load steps, decide what to record, and use a short pandas script to check the log for the things people miss when they read numbers off a controller screen.&lt;/p&gt;

&lt;h2&gt;Resistive or reactive bank?&lt;/h2&gt;

&lt;p&gt;Most hire load banks are purely resistive, so they load an industrial generator at unity power factor. That's a proper test of the engine, because every kilowatt is real. It's a weaker test of the alternator, which is rated in kVA at a lagging power factor, usually 0.8.&lt;/p&gt;

&lt;p&gt;Take a set rated 500 kVA at 0.8 PF, which makes 400 kW. A resistive bank at 400 kW loads the engine fully, but the alternator only carries 400 kVA worth of current, four fifths of its rating. If alternator heating or voltage regulation under reactive load is what worries you, ask for a resistive-reactive bank. They're less common, so book one early.&lt;/p&gt;

&lt;h2&gt;Planning the load steps&lt;/h2&gt;

&lt;p&gt;Build load in steps and hold each one long enough for temperatures to settle. A common pattern is 25, 50, 75 and 100 percent of the prime kW rating, with a longer hold at full load. Agree the actual steps and hold times with your supplier or the engine manufacturer's guidance, because some engines come with their own recommendations.&lt;/p&gt;

&lt;p&gt;Use the prime rating from the data plate as your 100 percent, not the standby figure. Standby is the emergency ceiling under ISO 8528, and it's not a sensible target for a planned test.&lt;/p&gt;

&lt;h2&gt;What to record when you test an industrial generator&lt;/h2&gt;

&lt;p&gt;Log at short intervals, ideally every few seconds, through the whole test. Most modern controllers can record many of these channels for you, and a power analyser on the output fills in the rest.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;kW, kVA and power factor, plus voltage and current on each phase.&lt;/li&gt;
&lt;li&gt;Frequency.&lt;/li&gt;
&lt;li&gt;Coolant temperature and oil pressure.&lt;/li&gt;
&lt;li&gt;Ambient air temperature at the radiator inlet, not in the office.&lt;/li&gt;
&lt;li&gt;Exhaust temperature, if the set has a sensor or you can fit a probe safely.&lt;/li&gt;
&lt;li&gt;Fuel used at each step, from a flow meter or careful tank dips.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Add a "step" column to the export, either by hand or from the bank's own log, so every row knows which load step it belongs to.&lt;/p&gt;

&lt;h2&gt;Checking the log with pandas&lt;/h2&gt;

&lt;p&gt;The script below takes the last ten minutes of each step as the "settled" window and summarises it. The limits are deliberately empty. Fill them in from the engine and alternator data sheets for your set, not from a blog post, ours included.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import numpy as np
import pandas as pd

# Fill every limit from the engine and alternator data sheets.
LIMITS = {
    "freq_band_hz": None,        # allowed max-minus-min swing in a settled window
    "volt_imbalance_pct": None,  # allowed phase-to-phase spread
    "coolant_alarm_c": None,     # high coolant temperature alarm point
    "settle_c_per_10min": None,  # above this, coolant is still climbing
}
missing = [k for k, v in LIMITS.items() if v is None]
if missing:
    raise SystemExit(f"Set these limits first: {missing}")

log = pd.read_csv("loadbank_log.csv", parse_dates=["timestamp"])
log = log.set_index("timestamp").sort_index()
# columns: step, kw, freq, v_l1, v_l2, v_l3, coolant_c, oil_kpa, ambient_c

rows = []
for step, g in log.groupby("step"):
    settled = g[g.index &amp;gt;= g.index.max() - pd.Timedelta("10min")]
    mins = (settled.index - settled.index[0]).total_seconds() / 60
    slope = np.polyfit(mins, settled["coolant_c"], 1)[0] * 10
    volts = settled[["v_l1", "v_l2", "v_l3"]]
    spread = (volts.max(axis=1) - volts.min(axis=1)) / volts.mean(axis=1)
    rows.append({
        "step": step,
        "kw_mean": settled["kw"].mean(),
        "freq_mean": settled["freq"].mean(),
        "freq_swing": settled["freq"].max() - settled["freq"].min(),
        "volt_imbalance_pct": 100 * spread.max(),
        "coolant_end_c": settled["coolant_c"].iloc[-1],
        "rise_over_ambient_c": (settled["coolant_c"] - settled["ambient_c"]).iloc[-1],
        "coolant_c_per_10min": slope,
        "oil_min_kpa": settled["oil_kpa"].min(),
    })

report = pd.DataFrame(rows).set_index("step")
report["freq_ok"] = report["freq_swing"] &amp;lt;= LIMITS["freq_band_hz"]
report["volts_ok"] = report["volt_imbalance_pct"] &amp;lt;= LIMITS["volt_imbalance_pct"]
report["settled"] = report["coolant_c_per_10min"] &amp;lt;= LIMITS["settle_c_per_10min"]
report["coolant_ok"] = report["coolant_end_c"] &amp;lt; LIMITS["coolant_alarm_c"]
print(report.round(2))
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Reading the results&lt;/h2&gt;

&lt;p&gt;The column people skip is the coolant slope. If the coolant is still climbing at the end of a hold, that step hasn't told you anything about cooling yet, and you should extend the hold before moving up. A radiator half blocked with dust often looks fine at half load and only gives trouble an hour into full load.&lt;/p&gt;

&lt;p&gt;Judge frequency per step, not against a flat 50 Hz. If the governor runs in droop, frequency falls a little as load rises by design. What you're looking for is a steady value inside each settled window, and a swing that stays within the band your supplier commits to.&lt;/p&gt;

&lt;p&gt;Watch the oil pressure column alongside coolant temperature. Some drop as oil warms up is normal, but a pressure that keeps falling through a hold is worth a call to your service engineer.&lt;/p&gt;

&lt;p&gt;Finally, keep the ambient figure next to the coolant rise. A comfortable result on a mild November morning doesn't prove the set will cope with a 45°C afternoon in Sukkur or Multan. Ask your supplier what ambient the cooling package is rated for, and compare that with how much margin your test showed.&lt;/p&gt;

&lt;h2&gt;Running the test on a Pakistani site&lt;/h2&gt;

&lt;p&gt;During the test, the industrial generator is off the plant. If the grid fails halfway through, you have no backup at all. Pick a window when your feeder is normally on, and agree in advance how quickly the team can drop the bank and put the set back on the changeover.&lt;/p&gt;

&lt;p&gt;Place the bank so its hot exhaust air can't blow back into the radiator intake, which is easy to get wrong in a cramped generator yard. Size the temporary cables properly, keep them out of walkways, and have fuel on site for the whole test plus a margin. Sets that spend their lives lightly loaded may smoke for the first few steps as deposits burn off. Note it, and see whether it clears.&lt;/p&gt;

&lt;h2&gt;Keep the summary, not just the certificate&lt;/h2&gt;

&lt;p&gt;File the report table with the date, the ambient and the bank used. Next year's test is only useful if you can compare it with this one, and a slowly rising coolant figure at the same load and ambient is exactly the early warning you're paying for. That record is worth more than any certificate in a drawer, and it's how we'd want every industrial generator on a production site to be looked after.&lt;/p&gt;

&lt;p&gt;If you'd like help planning a load bank test or reading the results, talk to the engineering team at &lt;a href="https://enpower.com.pk/" rel="noopener noreferrer"&gt;Enpower&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>automation</category>
      <category>hardware</category>
      <category>python</category>
      <category>testing</category>
    </item>
    <item>
      <title>When Will an LED Bulb Light Actually Fail? Modelling Rated Hours and Load-Shedding in Python</title>
      <dc:creator>Ibrahim Nauman</dc:creator>
      <pubDate>Wed, 11 Nov 2026 12:10:49 +0000</pubDate>
      <link>https://dev.to/ibrahim_nauman_786/when-will-an-led-bulb-light-actually-fail-modelling-rated-hours-and-load-shedding-in-python-g1l</link>
      <guid>https://dev.to/ibrahim_nauman_786/when-will-an-led-bulb-light-actually-fail-modelling-rated-hours-and-load-shedding-in-python-g1l</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F12q59p4r2hjowdqqpkb5.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F12q59p4r2hjowdqqpkb5.jpg" alt=" " width="800" height="336"&gt;&lt;/a&gt;&lt;br&gt;
`&lt;/p&gt;
&lt;p&gt;Almost every LED bulb light box sold in Pakistan prints a big number of hours. Facility managers read it as "these will last for years", and procurement reads it as "we don't need spares". Then a three-shift factory in Faisalabad finds a corridor full of dead bulbs in year three, and everyone is surprised.&lt;/p&gt;


&lt;p&gt;The hours were never the problem. The calendar is. Most of our &lt;a href="https://hyundailedlights.com.pk/indoor-lighting-bulb-light/" rel="noopener noreferrer"&gt;bulb range, from the 7W up to the 50W HLBL50N&lt;/a&gt;, lists a 25,000-hour life, and most models carry an 18-month warranty. This post builds a small Python model that turns those two numbers into dates for each zone of a building, and estimates how many failures to expect each year, including inside the warranty window.&lt;/p&gt;

&lt;p&gt;It's standard library only. Use it for planning spares and maintenance budgets, not for arguing with a datasheet.&lt;/p&gt;

&lt;h2&gt;Reading the hours on an LED bulb light listing&lt;/h2&gt;

&lt;p&gt;A lifespan figure is a statement about a population of lamps, not a promise about the one in your hand. Datasheets usually mean one of two things. Either it's a lumen-maintenance figure, the hours until output drops to a set share of the original (often written L70), or it's a survival figure, the hours by which a set share of lamps have failed (written B50 or similar). Plenty of retail listings, ours included, just say "lifespan".&lt;/p&gt;

&lt;p&gt;For this model we treat 25,000 hours as the point where half the bulbs in a batch have failed. That's an assumption. If your supplier can tell you what their figure actually means, get it in writing and change the code, because it moves the answer.&lt;/p&gt;

&lt;h2&gt;Burn hours, not switch hours&lt;/h2&gt;

&lt;p&gt;The second input is how long each zone actually runs per day. In a factory, corridors, stairwells and the guard post often run around the clock. A canteen might cover two shifts. A godown is lit while someone's working in it.&lt;/p&gt;

&lt;p&gt;Here's the part that's specific to Pakistan. Load-shedding takes hours off the clock for any circuit that isn't on the generator or UPS. A zone switched on for 16 hours with 4 hours of outage only burns 12. The backed-up corridors never get that break, which is part of why they age first.&lt;/p&gt;

&lt;p&gt;Heat would go here too if we had a number for it. An LED bulb light inside a closed glass dome on a top floor in Multan in June runs hotter than the same bulb in an open holder in an air-conditioned office, and heat shortens LED life. The bulb listings don't give a temperature derating curve, so the model leaves heat out rather than guessing.&lt;/p&gt;

&lt;h2&gt;The model&lt;/h2&gt;

&lt;p&gt;Failures across a batch of LED bulb lights are modelled with a Weibull distribution, which is the usual choice for lifetime data. Its shape parameter, k, controls how bunched the failures are. A high k means most bulbs die close together around rated life. A low k spreads them out, with more early failures. We don't have a datasheet value for k, so the script runs two placeholder shapes to show the range.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import math
from dataclasses import dataclass

RATED_HOURS = 25_000   # lifespan printed on the bulb listing
WARRANTY_MONTHS = 18   # check the listing for the model you buy


@dataclass
class Zone:
    name: str
    bulbs: int
    hours_on: float        # hours per day the switch is on
    outage: float = 0.0    # load-shedding hours per day with no backup
    backed_up: bool = False


def burn_hours_per_day(z):
    """Hours the bulbs actually run. Off-backup zones go dark in outages."""
    if z.backed_up:
        return z.hours_on
    return max(z.hours_on - z.outage, 0)


def frac_failed(hours, k, rated=RATED_HOURS):
    """Weibull CDF, treating the rated life as the point where half have failed."""
    eta = rated / math.log(2) ** (1 / k)
    return 1 - math.exp(-((hours / eta) ** k))


def report(zones, k, years=6):
    print(f"shape k = {k}")
    print(f"{'zone':&amp;lt;13}{'h/day':&amp;gt;6}{'yrs to rated':&amp;gt;13}{'in warranty':&amp;gt;12}"
          + "".join(f"{'y' + str(y):&amp;gt;6}" for y in range(1, years + 1)))
    for z in zones:
        h = burn_hours_per_day(z)
        to_rated = RATED_HOURS / (h * 365) if h else float("inf")
        w = frac_failed(h * 30.4 * WARRANTY_MONTHS, k) * z.bulbs
        yearly = [(frac_failed(h * 365 * y, k) - frac_failed(h * 365 * (y - 1), k)) * z.bulbs
                  for y in range(1, years + 1)]
        print(f"{z.name:&amp;lt;13}{h:&amp;gt;6.0f}{to_rated:&amp;gt;13.1f}{w:&amp;gt;12.1f}"
              + "".join(f"{n:&amp;gt;6.1f}" for n in yearly))
    print()


if __name__ == "__main__":
    shed = 4  # hours a day, change to match your feeder
    site = [
        Zone("corridors", 40, 24, shed, backed_up=True),
        Zone("canteen", 16, 16, shed),
        Zone("godown", 30, 12, shed),
        Zone("admin block", 24, 10, shed),
    ]
    for k in (3.0, 1.5):   # placeholder shapes, not datasheet values
        report(site, k)
&lt;/code&gt;&lt;/pre&gt;

&lt;h2&gt;Four zones, two shapes&lt;/h2&gt;

&lt;p&gt;Here's the output for a site with 40 bulbs in backed-up corridors, 16 in the canteen, 30 in the godown and 24 in the admin block, with 4 hours of load-shedding a day:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;shape k = 3.0
zone          h/day yrs to rated in warranty    y1    y2    y3    y4    y5    y6
corridors        24          2.9         3.8   1.2   7.3  13.6  11.9   5.0   0.9
canteen          12          5.7         0.2   0.1   0.4   1.1   1.9   2.6   2.9
godown            8          8.6         0.1   0.0   0.2   0.6   1.2   1.8   2.5
admin block       6         11.4         0.0   0.0   0.1   0.2   0.4   0.7   0.9

shape k = 1.5
zone          h/day yrs to rated in warranty    y1    y2    y3    y4    y5    y6
corridors        24          2.9         9.3   5.4   8.0   7.7   6.3   4.6   3.2
canteen          12          5.7         1.4   0.8   1.3   1.6   1.6   1.6   1.5
godown            8          8.6         1.5   0.8   1.4   1.8   1.9   2.0   2.0
admin block       6         11.4         0.8   0.4   0.8   1.0   1.1   1.2   1.2
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Read the corridor row first. Forty bulbs on 24 hours with backup reach 25,000 hours in under three years. With k at 3.0, expect about four failures inside the 18-month warranty, then a wave of around 14 in year three and 12 in year four. With k at 1.5 the failures come earlier and flatter: about nine inside warranty, then somewhere between three and eight a year.&lt;/p&gt;

&lt;p&gt;The admin block is the opposite case. Six burn hours a day puts rated life more than 11 years out, and either shape gives about one failure a year at most. A small box of spares covers it.&lt;/p&gt;

&lt;p&gt;Notice what the shape does and doesn't change. Over six years, the corridor total is close to the full 40 either way. What k really moves is the warranty column, and that's the number you need when you're deciding how many spares to hold and how firmly to track warranty claims.&lt;/p&gt;

&lt;h2&gt;Group re-lamping or replacing as they fail&lt;/h2&gt;

&lt;p&gt;The corridor row is the classic case for group re-lamping. If most failures bunch into years three and four, it can be cheaper in labour to change every bulb in the zone on a planned Sunday than to send someone up a ladder every few days. That's even more true where a high stairwell needs a scaffold every time.&lt;/p&gt;

&lt;p&gt;The godown and admin rows aren't worth it. Replace those as they go.&lt;/p&gt;

&lt;p&gt;Bulbs pulled out in a group re-lamp aren't all dead, either. Working ones can go into a low-hours store room, as long as you keep colour temperatures matched within each room.&lt;/p&gt;

&lt;h2&gt;Where the numbers can mislead you&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Replacements restart the clock.&lt;/strong&gt; The script only follows the original batch. After the first wave, a replaced bulb has its own life, so read the later years as "original bulbs still failing", not total call-outs.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Supply problems kill bulbs in clusters.&lt;/strong&gt; Surges, a loose neutral or a feeder that swings badly at night can take out drivers far faster than any lifetime curve. If one zone burns through bulbs much faster than the model says, check the supply before blaming the bulbs.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The rated-life definition.&lt;/strong&gt; If the 25,000 hours turns out to be a lumen-maintenance figure rather than a failure figure, bulbs will mostly still be working at that point, just dimmer.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;Plugging in your own building&lt;/h2&gt;

&lt;p&gt;Swap in your zones, your feeder's typical outage hours, and the rated life and warranty of whatever LED bulb light you're quoting. The real upgrade is a failure log. Note the date and zone every time someone changes a bulb, and after a year you can fit k from your own data instead of guessing it.&lt;/p&gt;

&lt;p&gt;If you'd like help setting the inputs for a real site, &lt;a href="https://hyundailedlights.com.pk/" rel="noopener noreferrer"&gt;Hyundai LED's technical sales team&lt;/a&gt; can share the datasheet details we have for each model.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>python</category>
      <category>science</category>
    </item>
    <item>
      <title>Sizing a Diesel Generator for Industries From Power Logger Data: A pandas Walkthrough</title>
      <dc:creator>Ibrahim Nauman</dc:creator>
      <pubDate>Tue, 10 Nov 2026 11:29:29 +0000</pubDate>
      <link>https://dev.to/ibrahim_nauman_786/sizing-a-diesel-generator-for-industries-from-power-logger-data-a-pandas-walkthrough-hl2</link>
      <guid>https://dev.to/ibrahim_nauman_786/sizing-a-diesel-generator-for-industries-from-power-logger-data-a-pandas-walkthrough-hl2</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fq9nkm8d8gywz1yxdzu6n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fq9nkm8d8gywz1yxdzu6n.png" alt=" " width="800" height="336"&gt;&lt;/a&gt;&lt;br&gt;
Ask a factory how big its backup set should be and you'll usually get a number someone added up from motor nameplates. We at Enpower see those sums on most enquiries for a diesel generator for industries, and they tend to be wrong twice over. They're too high on running load, because no plant runs every motor flat out at once. And they're too low on what happens in the first few seconds after a restart.&lt;/p&gt;

&lt;p&gt;If someone at the plant can write a bit of Python, there's a better route. Clip a power logger onto the incoming supply for a week, export the readings and let the data settle the argument. Picking the engine brand is the easier half, and our comparison of the four engine brands we supply for factory loads covers that part. This post is about getting the size right first.&lt;/p&gt;

&lt;p&gt;What to log, and for how long&lt;br&gt;
Use a three-phase power quality analyser or energy logger on the main incomer, downstream of the point where the generator will connect. You want kW, kVA, power factor and current on each phase. One-minute intervals are fine for demand. For motor starts you need one-second data, or an analyser that captures inrush events separately.&lt;/p&gt;

&lt;p&gt;Log for at least a full production week. That should include a shift change, a weekend wind-down and, if you can catch one, a restart after a load-shedding trip. Season matters too. In a Faisalabad weaving unit or a Lahore food plant, the June afternoon with every AC and chiller running is the load that decides things. A January log will undersize the set.&lt;/p&gt;

&lt;p&gt;If you can log individual feeders as well as the incomer, do it. You'll need that split later.&lt;/p&gt;

&lt;p&gt;Loading the export&lt;br&gt;
Every logger exports a slightly different CSV, so rename the columns first. The script below assumes one-second readings with a timestamp, kW, kVA, power factor and three phase currents.&lt;/p&gt;

&lt;p&gt;import pandas as pd&lt;/p&gt;

&lt;p&gt;df = pd.read_csv("incomer_log.csv", parse_dates=["timestamp"])&lt;br&gt;
df = df.set_index("timestamp").sort_index()&lt;/p&gt;

&lt;h1&gt;
  
  
  expected columns: kw, kva, pf, i_l1, i_l2, i_l3
&lt;/h1&gt;

&lt;p&gt;per_min = df.resample("1min").mean(numeric_only=True)&lt;br&gt;
running = per_min[per_min["kw"] &amp;gt; 1]  # ignore the plant-off hours&lt;/p&gt;

&lt;p&gt;summary = {&lt;br&gt;
    "peak_1min_kw": per_min["kw"].max(),&lt;br&gt;
    "peak_15min_kw": per_min["kw"].rolling("15min").mean().max(),&lt;br&gt;
    "p99_kw": per_min["kw"].quantile(0.99),&lt;br&gt;
    "min_running_kw": running["kw"].min(),&lt;br&gt;
    "worst_pf": running["pf"].min(),&lt;br&gt;
    "largest_step_kw": df["kw"].diff().max(),  # needs 1-second data&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;phases = running[["i_l1", "i_l2", "i_l3"]]&lt;br&gt;
spread = (phases.max(axis=1) - phases.min(axis=1)) / phases.mean(axis=1)&lt;br&gt;
summary["worst_imbalance_pct"] = 100 * spread.max()&lt;/p&gt;

&lt;p&gt;for name, value in summary.items():&lt;br&gt;
    print(f"{name:22s} {value:10.1f}")&lt;br&gt;
Run it on the whole week, then on the worst day on its own. The two summaries are rarely the same.&lt;/p&gt;

&lt;p&gt;Five numbers that matter more than the peak&lt;br&gt;
Sustained demand. The highest 15-minute average is what the engine actually has to carry. A one-minute peak above it is usually a start or a short burst.&lt;br&gt;
The 99th percentile against the absolute peak. If they're far apart, find the timestamp of the peak and ask what happened. It might have been a test, a fault or a one-off that nobody wants on backup.&lt;br&gt;
Largest step. This is what the generator feels when loads come back. A set handles a sudden step much worse than the grid does. ISO 8528-5 sets the frequency and voltage dip limits for each performance class, and the engine maker states what load step its set can accept.&lt;br&gt;
Minimum running load. Long hours at very light load lead to wet stacking. If your nights are much lighter than your days, that's a design question, maybe a smaller set or two sets.&lt;br&gt;
Worst power factor and imbalance. A generator is limited by current. Poor power factor eats into its kVA, and the most loaded phase decides how far you can go.&lt;br&gt;
Strip out what won't run on backup&lt;br&gt;
Very few plants put everything on a diesel generator for industries, and yours probably shouldn't either. A spare compressor, the admin block's ACs or a non-critical line can usually wait for the grid. If you logged those feeders separately, subtract their series from the incomer and run the summary again. If you didn't, log them for a day or two now.&lt;/p&gt;

&lt;p&gt;Then model the restart. After a FESCO or LESCO trip, everything with a contactor tries to come back at once unless someone has set delays. Group your large loads into restart steps, sum the starting demand of each group from your one-second data, and the biggest group becomes your step figure. That number is often more useful than the peak.&lt;/p&gt;

&lt;p&gt;Turning the numbers into a diesel generator for industries rating&lt;br&gt;
Divide the sustained kW by the worst realistic power factor to get kVA. Then decide which rating you're sizing against. Under ISO 8528-1, standby and prime ratings mean different things, and a set that runs several hours a day through load-shedding should be chosen on its prime rating.&lt;/p&gt;

&lt;p&gt;Next comes site derating. Datasheet output assumes a reference ambient temperature and altitude, and a 45°C plant room in Multan or Sukkur isn't that. The manufacturer's derating table tells you what's left at your site. Add the machines production expects to install over the next couple of years, then check your step figure against the load acceptance of each set on your shortlist.&lt;/p&gt;

&lt;p&gt;Where logger data misleads you&lt;br&gt;
One-minute averages hide motor starts completely, so never take a step figure from them. Check the scaling too. A wrong CT ratio in the logger setup gives you numbers that look sensible and aren't. A quick sanity check is to compare your peak against the MDI on the plant's electricity bill.&lt;/p&gt;

&lt;p&gt;If the plant has a lot of VFDs or UPS systems, log harmonic distortion as well. Those loads affect how an alternator behaves, and the engineer sizing the set will want to see that data.&lt;/p&gt;

&lt;p&gt;Hand over the data, not a guess&lt;br&gt;
When you send an enquiry, attach the summary, the worst-day plot and your restart groups. An engineer can do far more with a week of measurements than with a list of nameplates, and the quotes you get back will be much easier to compare. That's how we'd want any diesel generator for industries to be specified, whoever ends up supplying it.&lt;/p&gt;

&lt;p&gt;If you'd like a second pair of eyes on your logger export before you go out for quotes, the engineering team at Enpower is happy to look through it with you.&lt;/p&gt;

</description>
      <category>data</category>
      <category>python</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Exhaust Back Pressure on Diesel Generators in Pakistan: Working It Out Before the Pipe Goes Up</title>
      <dc:creator>Ibrahim Nauman</dc:creator>
      <pubDate>Mon, 09 Nov 2026 12:15:40 +0000</pubDate>
      <link>https://dev.to/ibrahim_nauman_786/exhaust-back-pressure-on-diesel-generators-in-pakistan-working-it-out-before-the-pipe-goes-up-4pg6</link>
      <guid>https://dev.to/ibrahim_nauman_786/exhaust-back-pressure-on-diesel-generators-in-pakistan-working-it-out-before-the-pipe-goes-up-4pg6</guid>
      <description>&lt;p&gt;Every diesel engine has to push its exhaust out through whatever pipe you give it. The harder it has to push, the less of its power reaches the alternator. That resistance is called back pressure, and it's one of the few installation numbers that can quietly cost a perfectly good engine a chunk of its output.&lt;/p&gt;

&lt;p&gt;We at Enpower check exhaust systems on a lot of diesel generators in Pakistan, and back pressure problems almost never show up on the drawing. They show up a year later as black smoke at full load, high exhaust temperatures, or a set that won't quite carry what it carried on the test bed. The good news is that it's a calculation you can do on paper, and a measurement you can take on site. Here's how we approach both.&lt;/p&gt;

&lt;p&gt;Why the engine cares&lt;br&gt;
A turbocharged engine uses exhaust energy to drive the turbo, which pushes air into the cylinders. Raise the pressure downstream of the turbo and it does less useful work. Less air means a richer burn, higher exhaust temperatures and more soot. Over time that shows up in valves, the turbo and fuel economy.&lt;/p&gt;

&lt;p&gt;Engine makers publish a maximum allowable exhaust back pressure in the engine data sheet, usually as a pressure at rated load. That figure is your budget. Everything between the turbo outlet and the open air spends some of it.&lt;/p&gt;

&lt;p&gt;Where the budget goes&lt;br&gt;
An exhaust system is a chain of resistances in series. The usual items:&lt;/p&gt;

&lt;p&gt;Straight pipe. Loss grows with length, and it grows sharply as the diameter shrinks.&lt;br&gt;
Bends. Each elbow behaves like a length of extra straight pipe. A tight or mitred bend costs much more than a long-radius one.&lt;br&gt;
The silencer. Often the biggest single item. Its maker should state the pressure drop at a given gas flow.&lt;br&gt;
Flexible bellows, rain caps and spark arrestors. Small individually, but they add up.&lt;br&gt;
The diameter point deserves emphasis. For turbulent flow at a fixed gas flow, friction loss in a straight pipe rises roughly with the fifth power of the inverse of the diameter. Going one size down to fit through a slab opening can multiply the loss in that section several times over. That's the single most common mistake we see.&lt;/p&gt;

&lt;p&gt;Doing the calculation&lt;br&gt;
You don't need special software. A spreadsheet with one row per component works well, and if you prefer a short script that's fine too. The inputs come from three places:&lt;/p&gt;

&lt;p&gt;Engine data sheet: exhaust gas flow and exhaust temperature at rated load, plus the maximum allowable back pressure.&lt;br&gt;
Installation drawing: pipe diameter, the length of each straight run, and the count and type of bends.&lt;br&gt;
Component data: the silencer's pressure drop curve and any figures for caps, bellows or arrestors.&lt;br&gt;
Convert bends to equivalent straight length using the pipe supplier's or engine maker's tables, add them to the real length, and work out the loss for that total using the gas flow at exhaust temperature. Then add the fixed component losses. Hot gas takes up much more volume than cold air, so always use the hot flow figure, not the intake air flow.&lt;/p&gt;

&lt;p&gt;Compare the total against the engine limit and keep a sensible margin. Soot builds up, silencers age and someone always adds a bend during installation. If you're near the limit on paper, you'll be over it in real life.&lt;/p&gt;

&lt;p&gt;Pakistani buildings make this harder&lt;br&gt;
Long exhaust runs are common on diesel generators in Pakistan's city buildings. A set in a Lahore or Karachi basement may need its exhaust carried up several floors to the roof. A set squeezed into a back lane may need a run that dodges a neighbour's windows. Each detour adds bends and length.&lt;/p&gt;

&lt;p&gt;Retrofits are the other trap. When a set is moved or replaced, the old exhaust is often reused because it's already there. A pipe sized for a smaller engine can be a real restriction on a bigger one.&lt;/p&gt;

&lt;p&gt;Weather plays a part too. Before the monsoon, sites fit rain caps to keep water out, and some caps restrict flow more than you'd expect. After an andhi, dust settles into vertical sections that don't have a proper cap at all. And on a 45°C afternoon in Multan, the engine is already working hard to stay cool, so extra back pressure is the last thing it needs.&lt;/p&gt;

&lt;p&gt;Measuring it on diesel generators in Pakistan's real installations&lt;br&gt;
A calculation is a prediction. At commissioning, measure it. Ask for a pressure tapping in the exhaust close to the turbo outlet, connect a suitable gauge or manometer, and read it with the set at full load. A load bank is the easiest way to get that load without disturbing the building.&lt;/p&gt;

&lt;p&gt;Record the reading on the commissioning sheet alongside load and exhaust temperature. That number becomes your baseline. If performance drops later, take the same reading again. A rise points at soot build-up, a damaged silencer or something lodged in the pipe.&lt;/p&gt;

&lt;p&gt;Symptoms that point back at the exhaust&lt;br&gt;
Black smoke at heavy load that clears at light load, exhaust temperatures creeping higher than they used to, and a set that struggles to reach rated output can all have other causes. Air filters and injectors come first on our list. But if those check out and the exhaust was changed recently, measure the back pressure before you start replacing engine parts.&lt;/p&gt;

&lt;p&gt;A few layouts we'd always question: two sets sharing one flue, a long horizontal run with no condensate drain, and any section where the pipe has been necked down to fit a gap. Each of them tends to cause trouble sooner or later.&lt;/p&gt;

&lt;p&gt;Ask for the numbers before installation&lt;br&gt;
Whoever installs diesel generators in Pakistan for you should be able to show you the back pressure calculation and the engine limit it was checked against. If they can't, ask for it before the pipe goes up. We do this as part of the job on the Baudouin generator sets we size and install, and on every other make we handle, because the exhaust is part of the generator's performance.&lt;/p&gt;

&lt;p&gt;If you have an existing installation that smokes or underperforms and you suspect the exhaust, the engineering team at Enpower can look over your drawings and readings with you.&lt;/p&gt;

</description>
      <category>hardware</category>
      <category>infrastructure</category>
      <category>systems</category>
    </item>
    <item>
      <title>Logging Diesel Generators Over Modbus RTU With Python: A Hands-On Build</title>
      <dc:creator>Ibrahim Nauman</dc:creator>
      <pubDate>Mon, 02 Nov 2026 10:00:53 +0000</pubDate>
      <link>https://dev.to/ibrahim_nauman_786/logging-diesel-generators-over-modbus-rtu-with-python-a-hands-on-build-651</link>
      <guid>https://dev.to/ibrahim_nauman_786/logging-diesel-generators-over-modbus-rtu-with-python-a-hands-on-build-651</guid>
      <description>&lt;p&gt;Generators, in this post, means the diesel kind that keep factories running when the grid drops. Not the Python kind, although one does turn up in the code below.&lt;/p&gt;

&lt;p&gt;We at Enpower supply and commission diesel sets across Pakistan, where load-shedding means a backup set can run for hours a day. More of our customers now have someone in-house who writes code, and they ask the same thing: how do we get the data out of our generators and into something we can query? This is the hands-on version of our answer. You'll wire an RS-485 link, poll the controller with Python, store readings in SQLite and write a few rules that flag real problems.&lt;/p&gt;

&lt;p&gt;What you need on the bench&lt;br&gt;
A generator controller with a Modbus RTU port on RS-485, or a Modbus TCP gateway&lt;br&gt;
A USB to RS-485 adapter, preferably an isolated one&lt;br&gt;
A Raspberry Pi or any small Linux box that can live in the panel room&lt;br&gt;
Python 3 with pymodbus installed&lt;br&gt;
The controller's Modbus register map, from its manufacturer&lt;br&gt;
That last item matters more than the hardware. Controller makers such as Deep Sea Electronics and ComAp publish register maps, and each one is laid out differently.&lt;/p&gt;

&lt;p&gt;Read the register map before you write code&lt;br&gt;
The register map tells you which address holds which value, whether it's a holding or an input register, how it's scaled and whether it's signed. Oil pressure might be stored in kPa, coolant temperature in whole degrees, battery voltage in tenths of a volt. Values like run hours or kWh usually span two 16-bit registers, and you need to know which word comes first.&lt;/p&gt;

&lt;p&gt;Check whether the map's addresses are zero-based or one-based, too. Some documents list registers in the old 40001-style notation that you have to convert, and an off-by-one error will happily return a plausible but wrong value.&lt;/p&gt;

&lt;p&gt;Make a table of the handful of values you actually want before touching Python. Keep it short. Fuel level, battery voltage, coolant temperature, oil pressure, frequency, run hours and the alarm status registers cover most of what a maintenance team needs.&lt;/p&gt;

&lt;p&gt;Wiring RS-485 without the usual headaches&lt;br&gt;
Most failed first attempts are wiring, not code. Use twisted pair, connect A to A and B to B, and if nothing answers, swap them, because manufacturers don't agree on labelling. Terminate both ends of a long bus with 120-ohm resistors. Match the controller's baud rate, parity and stop bits exactly, and note its Modbus unit ID.&lt;/p&gt;

&lt;p&gt;A generator room is electrically noisy. Keep the RS-485 cable away from power cables, ground the shield at one end only, and use an isolated adapter so a fault on the set doesn't travel back into your Pi.&lt;/p&gt;

&lt;p&gt;Polling the controller in Python&lt;br&gt;
Here's a minimal poller. The register addresses are placeholders, so replace them with the ones from your controller's map, along with the correct scale factors and signedness.&lt;/p&gt;

&lt;p&gt;import sqlite3&lt;br&gt;
import time&lt;br&gt;
from datetime import datetime, timezone&lt;/p&gt;

&lt;p&gt;from pymodbus.client import ModbusSerialClient&lt;br&gt;
from pymodbus.exceptions import ModbusException&lt;/p&gt;

&lt;h1&gt;
  
  
  Placeholder addresses: copy the real ones, and their scaling,
&lt;/h1&gt;

&lt;h1&gt;
  
  
  from your controller's Modbus register map.
&lt;/h1&gt;

&lt;p&gt;REGISTERS = {&lt;br&gt;
    "fuel_level_pct":   (100, 1.0, False),&lt;br&gt;
    "battery_v":        (101, 0.1, False),&lt;br&gt;
    "coolant_temp_c":   (102, 1.0, True),&lt;br&gt;
    "oil_pressure_kpa": (103, 1.0, False),&lt;br&gt;
    "gen_freq_hz":      (104, 0.1, False),&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;def to_signed(raw):&lt;br&gt;
    return raw - 0x10000 if raw &amp;amp; 0x8000 else raw&lt;/p&gt;

&lt;p&gt;def poll(client, unit_id=1):&lt;br&gt;
    """Yield (name, value) pairs: a Python generator reading a diesel one."""&lt;br&gt;
    for name, (addr, scale, signed) in REGISTERS.items():&lt;br&gt;
        try:&lt;br&gt;
            rr = client.read_holding_registers(addr, count=1, device_id=unit_id)&lt;br&gt;
        except ModbusException as exc:&lt;br&gt;
            print(f"{name}: {exc}")&lt;br&gt;
            continue&lt;br&gt;
        if rr.isError():&lt;br&gt;
            print(f"{name}: controller returned an error")&lt;br&gt;
            continue&lt;br&gt;
        raw = rr.registers[0]&lt;br&gt;
        yield name, (to_signed(raw) if signed else raw) * scale&lt;/p&gt;

&lt;p&gt;def main():&lt;br&gt;
    db = sqlite3.connect("genset.db")&lt;br&gt;
    db.execute("CREATE TABLE IF NOT EXISTS readings (ts TEXT, name TEXT, value REAL)")&lt;br&gt;
    client = ModbusSerialClient(port="/dev/ttyUSB0", baudrate=9600,&lt;br&gt;
                                parity="N", stopbits=1, bytesize=8, timeout=1)&lt;br&gt;
    if not client.connect():&lt;br&gt;
        raise SystemExit("Could not open the serial port")&lt;br&gt;
    while True:&lt;br&gt;
        ts = datetime.now(timezone.utc).isoformat()&lt;br&gt;
        rows = [(ts, name, value) for name, value in poll(client)]&lt;br&gt;
        db.executemany("INSERT INTO readings VALUES (?, ?, ?)", rows)&lt;br&gt;
        db.commit()&lt;br&gt;
        time.sleep(30)&lt;/p&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    main()&lt;br&gt;
A few notes. Recent pymodbus 3.x releases call the unit-ID argument device_id, while older ones used slave, so match the version you've installed. Reading each register on its own is slow but easy to debug. Once it works, read contiguous blocks with a larger count and slice the result.&lt;/p&gt;

&lt;p&gt;Turning readings into useful alerts&lt;br&gt;
Data is only useful if someone acts on it. These are the rules we find most valuable, and each one is a short SQL query or a few lines of Python:&lt;/p&gt;

&lt;p&gt;Battery voltage sliding over several days while the set is stopped, which usually means a failing charger or battery&lt;br&gt;
Fuel level dropping while run hours stay flat, which points to a leak or theft&lt;br&gt;
Coolant temperature trending higher at similar loads, often dust-packed radiator fins in a Pakistani summer&lt;br&gt;
Run hours approaching the next service interval&lt;br&gt;
Send alerts through whatever the team already reads. In most offices here that means WhatsApp or email, not a dashboard nobody opens. Keep the raw readings for at least a year. Summer and winter behave very differently here, and last June's coolant trend is the baseline you'll want this June.&lt;/p&gt;

&lt;p&gt;Lessons from running this on real generators&lt;br&gt;
Poll gently. Every 30 to 60 seconds is plenty for trend data, and hammering a controller with requests can slow its own processing. Only read. Many controllers accept write commands that start, stop or change settings, and a bug in a write loop is the last thing you want near a running engine.&lt;/p&gt;

&lt;p&gt;Expect gaps. Mobile signal drops, a Pi reboots after an outage, SD cards wear out. Log timestamps in UTC, buffer readings locally, and let systemd restart the script. And talk to whoever services the set before connecting anything, because some service contracts have rules about third-party equipment on the controller.&lt;/p&gt;

&lt;p&gt;Where this goes next&lt;br&gt;
Once readings are in SQLite, a Grafana dashboard or a small Flask page is an afternoon's work. If your site is also choosing its next set, ask which controller comes fitted and whether its register map is available before you sign. That question applies to the Baudouin diesel sets we supply and commission as much as to any other make.&lt;/p&gt;

&lt;p&gt;For questions about controller options on a new set, or about connecting a logger like this to sets you already run, contact Enpower.&lt;/p&gt;

</description>
      <category>database</category>
      <category>iot</category>
      <category>python</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Laying Out LED Panel Lights on a 600 mm Ceiling Grid With Python</title>
      <dc:creator>Ibrahim Nauman</dc:creator>
      <pubDate>Fri, 30 Oct 2026 10:49:37 +0000</pubDate>
      <link>https://dev.to/ibrahim_nauman_786/laying-out-led-panel-lights-on-a-600-mm-ceiling-grid-with-python-2h5a</link>
      <guid>https://dev.to/ibrahim_nauman_786/laying-out-led-panel-lights-on-a-600-mm-ceiling-grid-with-python-2h5a</guid>
      <description>&lt;p&gt;We supply lighting to office fit-outs across Lahore and Karachi, and the drawings that reach us often have the same gap. Someone has worked out how many LED panel lights the room needs, and then the false-ceiling contractor turns up and finds that half the positions land on a T-bar, or right where the AC diffuser has to go. The panels get shuffled on site, by eye, and the rows end up crooked.&lt;/p&gt;

&lt;p&gt;The count is the easy part. Putting that count onto a 600 mm grid so the rows look straight and the light stays even is where the time goes. So this post builds a small Python script that works out the count with the lumen method, searches the row and column layouts that actually fit the tiles, and prints an ASCII ceiling plan you can drop into the WhatsApp group with the contractor.&lt;/p&gt;

&lt;p&gt;Treat it as a planning aid. For anything a client signs off, run the manufacturer's photometric file through DIALux or similar.&lt;/p&gt;

&lt;p&gt;Four inputs and one formula&lt;br&gt;
The lumen method says the number of fittings is N = (E × A) / (Φ × UF × MF), rounded up. E is the target illuminance in lux, A is the floor area, Φ is the rated output of one panel in lumens, and UF and MF are the utilisation and maintenance factors.&lt;/p&gt;

&lt;p&gt;For desk-based office work, most specs we see here use 500 lux, which is the figure EN 12464-1 gives for writing, typing and reading. Agree it with the client in writing anyway. For Φ, take the bottom of the datasheet range, not the top. Our 36 W backlit LED panel light is listed at 3,240 to 3,888 lumens, so the script uses 3,240.&lt;/p&gt;

&lt;p&gt;UF and MF are where the judgement sits. We default to 0.6 and 0.8 as placeholders. A pale room with a white ceiling earns a better UF than one lined with dark wood, and the MF should reflect real cleaning habits. Offices on a main road in Faisalabad or Multan collect a film of dust on the diffusers within weeks of an andhi, and nobody climbs up to wipe them.&lt;/p&gt;

&lt;p&gt;Why a 600 mm grid turns this into a search&lt;br&gt;
In an ideal layout, panels sit at equal spacing with half a spacing between the outer rows and the walls. On paper that's trivial. On a T-bar ceiling, every LED panel light centre has to fall on the centre of a tile, and tiles come in fixed 600 mm steps.&lt;/p&gt;

&lt;p&gt;Take a room that's 7.2 by 4.8 metres, which is 12 tiles by 8. Four columns along the 12-tile side means one panel every three tiles, and the centres land exactly on tile centres. Three rows across the 8-tile side can't do that. Eight doesn't split into three equal whole-tile gaps, so at least one row ends up off its ideal position.&lt;/p&gt;

&lt;p&gt;So the script tries every rows-by-columns combination for the required count and a few above it. It drops anything where the spacing is too wide for the ceiling height, snaps the rest to the grid and ranks them by how far the panels had to move. For the spacing limit we use 1.5 times the height from desk to ceiling as a placeholder. The real spacing-to-height ratio comes from the panel's photometric data.&lt;/p&gt;

&lt;p&gt;The layout script&lt;br&gt;
Standard library only, so it runs on any Python 3.7 or later.&lt;/p&gt;

&lt;p&gt;import math&lt;br&gt;
from dataclasses import dataclass&lt;/p&gt;

&lt;p&gt;TILE = 0.6  # metres, nominal 600 x 600 mm T-bar grid&lt;/p&gt;

&lt;p&gt;@dataclass&lt;br&gt;
class Room:&lt;br&gt;
    length: float          # metres, along the long wall&lt;br&gt;
    width: float           # metres&lt;br&gt;
    ceiling: float         # false ceiling height&lt;br&gt;
    workplane: float = 0.75&lt;/p&gt;

&lt;p&gt;@dataclass&lt;br&gt;
class Panel:&lt;br&gt;
    name: str&lt;br&gt;
    lumens: float          # low end of the datasheet range&lt;/p&gt;

&lt;p&gt;def panels_needed(room, panel, lux, uf=0.6, mf=0.8):&lt;br&gt;
    """Lumen method, rounded up to whole panels."""&lt;br&gt;
    area = room.length * room.width&lt;br&gt;
    return math.ceil(lux * area / (panel.lumens * uf * mf))&lt;/p&gt;

&lt;p&gt;def snap_axis(n, span):&lt;br&gt;
    """Spread n panels evenly along one axis, snap each to a tile centre.&lt;br&gt;
    Returns (tile indices, offset of each from its ideal spot in mm)."""&lt;br&gt;
    picks, offsets = [], []&lt;br&gt;
    for i in range(n):&lt;br&gt;
        ideal = (i + 0.5) * span / n&lt;br&gt;
        idx = int(ideal // TILE)&lt;br&gt;
        picks.append(idx)&lt;br&gt;
        offsets.append(round(abs((idx + 0.5) * TILE - ideal) * 1000))&lt;br&gt;
    return picks, offsets&lt;/p&gt;

&lt;p&gt;def candidates(room, count, shr=1.5, extra=4):&lt;br&gt;
    """Try every rows x cols grid holding count..count+extra panels."""&lt;br&gt;
    h = room.ceiling - room.workplane&lt;br&gt;
    out = []&lt;br&gt;
    for total in range(count, count + extra + 1):&lt;br&gt;
        for rows in range(1, total + 1):&lt;br&gt;
            if total % rows:&lt;br&gt;
                continue&lt;br&gt;
            cols = total // rows&lt;br&gt;
            sx, sy = room.length / cols, room.width / rows&lt;br&gt;
            if max(sx, sy) &amp;gt; shr * h:&lt;br&gt;
                continue   # too far apart for this mounting height&lt;br&gt;
            _, ox = snap_axis(cols, room.length)&lt;br&gt;
            _, oy = snap_axis(rows, room.width)&lt;br&gt;
            avg = round(sum(ox + oy) / len(ox + oy))&lt;br&gt;
            out.append((total, avg, rows, cols, sx, sy))&lt;br&gt;
    return sorted(out)[:5]&lt;/p&gt;

&lt;p&gt;def plan(room, rows, cols, blocked=()):&lt;br&gt;
    """ASCII ceiling plan. P = panel, A = AC diffuser, . = plain tile."""&lt;br&gt;
    nx, ny = round(room.length / TILE), round(room.width / TILE)&lt;br&gt;
    xs, _ = snap_axis(cols, room.length)&lt;br&gt;
    ys, _ = snap_axis(rows, room.width)&lt;br&gt;
    spots = {(x, y) for x in xs for y in ys}&lt;br&gt;
    for (x, y) in list(spots):&lt;br&gt;
        if (x, y) in blocked:          # nudge one tile along the row&lt;br&gt;
            spots.discard((x, y))&lt;br&gt;
            spots.add((x + 1, y) if (x + 1, y) not in blocked else (x - 1, y))&lt;br&gt;
    for y in range(ny):&lt;br&gt;
        row = ""&lt;br&gt;
        for x in range(nx):&lt;br&gt;
            row += "A" if (x, y) in blocked else "P" if (x, y) in spots else "."&lt;br&gt;
        print(" ".join(row))&lt;/p&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    room = Room(length=7.2, width=4.8, ceiling=2.7)&lt;br&gt;
    panel = Panel("36 W backlit, 595 mm", lumens=3240)&lt;br&gt;
    target = 500&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;n = panels_needed(room, panel, target)
print(f"{room.length} x {room.width} m at {target} lux: {n} panels minimum\n")
print("total  avg-offset  rows x cols  spacing (long / short)")
for total, err, rows, cols, sx, sy in candidates(room, n):
    print(f"{total:&amp;gt;5}  {err:&amp;gt;7} mm  {rows:&amp;gt;4} x {cols:&amp;lt;4}  {sx:.2f} m / {sy:.2f} m")

print()
plan(room, rows=3, cols=4, blocked={(4, 1), (7, 6)})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Where the LED panel lights land in a 7.2 by 4.8 metre office&lt;br&gt;
With a 2.7 m false ceiling, a 500 lux target and the 3,240-lumen figure, the script prints this:&lt;/p&gt;

&lt;p&gt;7.2 x 4.8 m at 500 lux: 12 panels minimum&lt;/p&gt;

&lt;p&gt;total  avg-offset  rows x cols  spacing (long / short)&lt;br&gt;
   12       71 mm     3 x 4     1.80 m / 1.60 m&lt;br&gt;
   12      300 mm     2 x 6     1.20 m / 2.40 m&lt;br&gt;
   12      300 mm     4 x 3     2.40 m / 1.20 m&lt;br&gt;
   14      186 mm     2 x 7     1.03 m / 2.40 m&lt;br&gt;
   15      160 mm     3 x 5     1.44 m / 1.60 m&lt;/p&gt;

&lt;p&gt;. . . . . . . . . . . .&lt;br&gt;
. P . . A P . P . . P .&lt;br&gt;
. . . . . . . . . . . .&lt;br&gt;
. . . . . . . . . . . .&lt;br&gt;
. P . . P . . P . . P .&lt;br&gt;
. . . . . . . . . . . .&lt;br&gt;
. P . . P . . A P . P .&lt;br&gt;
. . . . . . . . . . . .&lt;br&gt;
Twelve panels is the minimum, and twelve gives an average of about 540 lux, so there's a little headroom. The ranking shows why the search matters. The 2 x 6 and 4 x 3 layouts hold the same twelve panels, but every one of them sits a full 300 mm from its ideal spot. On this grid that means the ideal position is on a T-bar. The 3 x 4 layout averages only 71 mm.&lt;/p&gt;

&lt;p&gt;It still isn't perfect. Look at the plan: the rows sit on tiles 1, 4 and 6, so the gap between the first two rows is 1.8 m and between the last two it's 1.2 m. That's the 8-tile problem from earlier.&lt;/p&gt;

&lt;p&gt;Most clients accept it once they see it on paper. What they don't accept is discovering it after the tiles are up.&lt;/p&gt;

&lt;p&gt;Dodging AC diffusers&lt;br&gt;
In a lot of offices here, a ducted split unit feeds square supply diffusers and return grilles into the same grid, and the HVAC contractor fixes those positions first. The blocked argument takes their tile coordinates. Where an LED panel light collides with one, the script slides it one tile along the row, which is the A sitting next to a P in the second and seventh rows of the plan.&lt;/p&gt;

&lt;p&gt;It's a crude rule, and on a busy ceiling it can push a panel right up against its neighbour. Read the plan rather than trusting it. If two diffusers sit in the same row, it's usually cleaner to shift that whole row by one tile than to nudge single panels.&lt;/p&gt;

&lt;p&gt;What the script doesn't model&lt;br&gt;
Load-shedding is the big one. Most offices put part of the lighting on a UPS or inverter, and the lazy way is one circuit for the panels nearest the board. That leaves one bright corner and a dark office when the supply drops. Use the plan to put every other LED panel light in each row on the backed-up circuit instead, so the room dims evenly. In this example six panels on backup give roughly 270 lux, which is enough to keep working through an outage.&lt;/p&gt;

&lt;p&gt;Daylight is the other. A west-facing window wall in a Lahore summer floods that side of the room until late afternoon, so the row nearest the glass is often worth its own switch.&lt;/p&gt;

&lt;p&gt;Getting real numbers in&lt;br&gt;
Swap in your own room, ceiling height and the lumen figure from the datasheet of whatever panel you're quoting. If you're still choosing, our LED panel lights with the lumen figure on every model are a reasonable place to start.&lt;/p&gt;

&lt;p&gt;And if you'd like a second pair of eyes on a layout before it goes to the contractor, Hyundai LED's lighting engineers are happy to go over the numbers with you.&lt;/p&gt;

</description>
      <category>python</category>
      <category>programming</category>
      <category>tutorial</category>
      <category>automation</category>
    </item>
    <item>
      <title>Switching Outdoor LED Lights at Sunset With Python, and Surviving Load-Shedding</title>
      <dc:creator>Ibrahim Nauman</dc:creator>
      <pubDate>Wed, 28 Oct 2026 12:05:29 +0000</pubDate>
      <link>https://dev.to/ibrahim_nauman_786/switching-outdoor-led-lights-at-sunset-with-python-and-surviving-load-shedding-1i7b</link>
      <guid>https://dev.to/ibrahim_nauman_786/switching-outdoor-led-lights-at-sunset-with-python-and-surviving-load-shedding-1i7b</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdjw3xruhncfrrjvctny9.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdjw3xruhncfrrjvctny9.jpg" alt=" " width="799" height="339"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We sell LED lighting in Pakistan, and a surprising number of the questions we get from customers who write software for a living aren't about the fittings at all. They're about switching. Someone has put a smart relay behind the gate light or the shop signboard, set a fixed 6 pm timer, and is now annoyed that the LED lights come on in broad daylight in June and well after dark in December.&lt;/p&gt;

&lt;p&gt;This post is the small Python service we'd suggest instead. It switches outdoor LED lights relative to the actual sunset for your city, recovers from load-shedding without any special handling, and writes a log you can turn into a rough figure for what the lights cost to run.&lt;/p&gt;

&lt;p&gt;Why a fixed timer drifts&lt;br&gt;
Pakistan doesn't use daylight saving time, so the clock stays put while sunset moves. In Lahore, sunset falls a little after 5 pm in late December and after 7 pm in late June. That's a swing of around two hours. A fixed timer is wrong for most of the year, either burning power in daylight or leaving the gate's LED lights off for the first part of the evening.&lt;/p&gt;

&lt;p&gt;Cities differ as well. Karachi sits further west and further south than Lahore, and in winter its sunset comes roughly three quarters of an hour later. A timer copied from a Lahore setup will be visibly off in Karachi.&lt;/p&gt;

&lt;p&gt;Compute the state, don't schedule the event&lt;br&gt;
The obvious design is an event scheduler: at sunset, send "on". The trouble is what happens when the event is missed. If the electricity is off at sunset, the Raspberry Pi running your script is off too, the event never fires, and the lights stay dark after power returns.&lt;/p&gt;

&lt;p&gt;The fix is to make the code stateless about time. Every minute, ask one question: given the current time and today's sun times, should this relay be on? Then send that state, whether or not it has changed. A missed minute doesn't matter. A reboot doesn't matter. An outage at exactly sunset fixes itself one loop after the supply comes back.&lt;/p&gt;

&lt;p&gt;The script&lt;br&gt;
It needs two packages: astral for the sun calculations, and tzdata so that zoneinfo works on Windows machines too.&lt;/p&gt;

&lt;p&gt;pip install astral tzdata&lt;br&gt;
Here's the whole service. Change the coordinates to your own site and the IP addresses to your relays.&lt;/p&gt;

&lt;p&gt;import csv&lt;br&gt;
import datetime as dt&lt;br&gt;
import time&lt;br&gt;
import urllib.request&lt;br&gt;
from zoneinfo import ZoneInfo&lt;/p&gt;

&lt;p&gt;from astral import LocationInfo&lt;br&gt;
from astral.sun import sun&lt;/p&gt;

&lt;p&gt;PKT = ZoneInfo("Asia/Karachi")&lt;br&gt;
SITE = LocationInfo("Lahore", "Pakistan", "Asia/Karachi", 31.52, 74.36)&lt;br&gt;
ON_OFFSET = dt.timedelta(minutes=-10)  # switch on a little before sunset&lt;/p&gt;

&lt;p&gt;RELAYS = {&lt;br&gt;
    "gate": {"ip": "192.168.1.50", "off_at": None},                 # dusk to dawn&lt;br&gt;
    "signboard": {"ip": "192.168.1.51", "off_at": dt.time(23, 0)},  # off at 11 pm&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;def desired_state(now, off_at):&lt;br&gt;
    """True if the relay should be on at this moment."""&lt;br&gt;
    s = sun(SITE.observer, date=now.date(), tzinfo=PKT)&lt;br&gt;
    on_time = s["sunset"] + ON_OFFSET&lt;br&gt;
    if off_at is None:&lt;br&gt;
        return now &amp;gt;= on_time or now &amp;lt; s["sunrise"]&lt;br&gt;
    off_time = dt.datetime.combine(now.date(), off_at, tzinfo=PKT)&lt;br&gt;
    return on_time &amp;lt;= now &amp;lt; off_time&lt;/p&gt;

&lt;p&gt;def set_relay(ip, on):&lt;br&gt;
    """Send the state to a Tasmota relay over HTTP. Safe to repeat."""&lt;br&gt;
    cmd = "Power%20On" if on else "Power%20Off"&lt;br&gt;
    with urllib.request.urlopen(f"http://{ip}/cm?cmnd={cmd}", timeout=5) as r:&lt;br&gt;
        return r.status == 200&lt;/p&gt;

&lt;p&gt;def log(name, on, ok):&lt;br&gt;
    stamp = dt.datetime.now(PKT).isoformat(timespec="seconds")&lt;br&gt;
    with open("lights_log.csv", "a", newline="") as f:&lt;br&gt;
        csv.writer(f).writerow([stamp, name, int(on), int(ok)])&lt;/p&gt;

&lt;p&gt;def main():&lt;br&gt;
    last = {}&lt;br&gt;
    while True:&lt;br&gt;
        now = dt.datetime.now(PKT)&lt;br&gt;
        for name, cfg in RELAYS.items():&lt;br&gt;
            want = desired_state(now, cfg["off_at"])&lt;br&gt;
            try:&lt;br&gt;
                ok = set_relay(cfg["ip"], want)&lt;br&gt;
            except OSError:&lt;br&gt;
                ok = False&lt;br&gt;
            if last.get(name) != (want, ok):&lt;br&gt;
                log(name, want, ok)&lt;br&gt;
                last[name] = (want, ok)&lt;br&gt;
        time.sleep(60)&lt;/p&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    main()&lt;br&gt;
The relays in this example run Tasmota firmware, which accepts commands over plain HTTP, so the standard library is enough. If your devices sit on MQTT instead, swap set_relay for a paho-mqtt publish and leave the rest alone.&lt;/p&gt;

&lt;p&gt;Two rules are built in. The gate light runs dusk to dawn. The signboard comes on ten minutes before sunset and goes off at 11 pm, after the market has closed. Adding a third relay is one more line in the dictionary.&lt;/p&gt;

&lt;p&gt;What happens during load-shedding&lt;br&gt;
Walk through a typical winter evening. Power goes at 6:30 pm, after sunset. The relays, the router and the Pi all go dark. At 7:30 pm the supply returns. The Pi boots, the loop runs, desired_state says the gate should be on, and the command goes out. Within a minute or two of the router reconnecting, everything is back where it should be. No catch-up logic, no missed-event queue.&lt;/p&gt;

&lt;p&gt;Two settings still matter. The first is the relay's own behaviour at power-up. Tasmota's PowerOnState setting decides whether a relay comes back on, off or in its last saved state. For a security light, coming back on is the safer default in case the Pi is slow to recover. The second is the split between UPS and mains. If the Pi is on the house UPS and the relays aren't, the script keeps running through the outage and its commands fail, which is why the log records whether each command succeeded and not just what it asked for.&lt;/p&gt;

&lt;p&gt;Turning the log into an estimate for your LED lights&lt;br&gt;
The CSV gets one row whenever a relay's wanted state or its success flag changes. Pair each successful "on" with the next "off" for the same relay and you have hours on. Multiply by the rated wattage of the fittings on that relay and you get kWh, which you can hold up against the units on your WAPDA or K-Electric bill.&lt;/p&gt;

&lt;p&gt;import csv&lt;br&gt;
import datetime as dt&lt;br&gt;
from collections import defaultdict&lt;/p&gt;

&lt;p&gt;WATTS = {"gate": 50, "signboard": 100}  # rated watts on each relay&lt;/p&gt;

&lt;p&gt;on_since, hours = {}, defaultdict(float)&lt;br&gt;
with open("lights_log.csv", newline="") as f:&lt;br&gt;
    for stamp, name, on, ok in csv.reader(f):&lt;br&gt;
        t = dt.datetime.fromisoformat(stamp)&lt;br&gt;
        if on == "1" and ok == "1":&lt;br&gt;
            on_since.setdefault(name, t)&lt;br&gt;
        elif on == "0" and name in on_since:&lt;br&gt;
            hours[name] += (t - on_since.pop(name)).total_seconds() / 3600&lt;/p&gt;

&lt;p&gt;for name, h in hours.items():&lt;br&gt;
    print(f"{name}: {h:.1f} h on, about {h * WATTS[name] / 1000:.2f} kWh")&lt;br&gt;
Treat the output as an estimate. It assumes the fittings draw their rated wattage, and it counts time when a relay was meant to be on but the supply itself was out. For a real figure, put an energy meter on the circuit for a week and compare the two numbers.&lt;/p&gt;

&lt;p&gt;Hardware notes before you wire anything&lt;br&gt;
Check the relay's contact rating against the load. LED drivers draw a brief surge at switch-on, and several outdoor LED lights on one small smart relay can weld its contacts. For more than a light or two, let the relay drive a contactor.&lt;br&gt;
Mains wiring is a job for a qualified electrician. The code is the easy part.&lt;br&gt;
Put outdoor relays in a sealed enclosure. Dust gets into everything during the May andhi season, and the monsoon finds any gap that's left.&lt;br&gt;
Tasmota has its own sunrise and sunset timers if you only have one device. The Python version earns its place once you have several relays, want one log, or need different rules per light.&lt;br&gt;
If you're choosing fittings for a setup like this, our product listings, each named with its rated wattage give you the numbers the WATTS table needs.&lt;/p&gt;

&lt;p&gt;And if you build something along these lines, we'd like to hear how it went. You can reach the engineering team through Hyundai LED.&lt;/p&gt;

</description>
      <category>automation</category>
      <category>iot</category>
      <category>python</category>
    </item>
    <item>
      <title>Sizing a 50 W Flood Light Layout With Python: Lux, Lumens and Mounting Height</title>
      <dc:creator>Ibrahim Nauman</dc:creator>
      <pubDate>Tue, 27 Oct 2026 12:55:31 +0000</pubDate>
      <link>https://dev.to/ibrahim_nauman_786/sizing-a-50-w-flood-light-layout-with-python-lux-lumens-and-mounting-height-473d</link>
      <guid>https://dev.to/ibrahim_nauman_786/sizing-a-50-w-flood-light-layout-with-python-lux-lumens-and-mounting-height-473d</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ft09e4saperlbac0nhhxm.webp" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Ft09e4saperlbac0nhhxm.webp" alt=" " width="800" height="450"&gt;&lt;/a&gt;We sell outdoor LED lighting in Pakistan, and the question we get most from site engineers is a numbers question. How many fittings does this yard need, and how high do they go? Very often someone has already decided on a 50 W flood light because it's the familiar size, and what they actually want to know is whether six of them is enough or whether they need twelve.&lt;/p&gt;

&lt;p&gt;This post walks through the method we use for a first estimate, written up as a small Python script you can run and adapt. It's the lumen method, which gives you an average illuminance over an area. It's a sanity check and a starting point, not a substitute for a proper photometric calculation in DIALux or similar using the manufacturer's IES file, which you should still do for anything safety-critical.&lt;/p&gt;

&lt;p&gt;The inputs you need before writing any code&lt;br&gt;
Five numbers drive the whole calculation. Get these right and the arithmetic is trivial. Get them wrong and no script will save you.&lt;/p&gt;

&lt;p&gt;Target illuminance (E), in lux. This comes from the client's requirement or the standard they work to. For outdoor workplaces, EN 12464-2 is the usual reference. Agree the figure in writing before you start.&lt;br&gt;
Area (A), in square metres. The area that actually needs lighting, not the whole plot.&lt;br&gt;
Luminous flux per fitting, in lumens. Take this from the datasheet. Never estimate it from wattage, because two fittings with the same wattage can differ a lot.&lt;br&gt;
Utilisation factor (UF). The fraction of the fitting's lumens that actually lands on the target area. Flood lights aimed at a yard spill a good share of their light past the edges, onto walls and into the sky.&lt;br&gt;
Maintenance factor (MF). Allowance for dirt on the glass and the gradual drop in LED output over time.&lt;br&gt;
UF and MF are where judgement comes in. In the script we default to 0.5 and 0.8 as placeholder assumptions. A real photometric file replaces the UF guess, and the MF should reflect how often the glass actually gets cleaned. On a site in Faisalabad or Multan that gets a couple of dust storms every summer and is cleaned once a year, be more pessimistic than you would for a sealed canopy in a clean area.&lt;/p&gt;

&lt;p&gt;The lumen method in one line&lt;br&gt;
The number of fittings is:&lt;/p&gt;

&lt;p&gt;N = (E × A) / (Φ × UF × MF)&lt;/p&gt;

&lt;p&gt;where Φ is the rated flux of one fitting. You need E × A lumens on the ground. Each fitting contributes Φ × UF × MF of useful, maintained lumens. Divide, then round up, because you can't install 4.5 fittings.&lt;/p&gt;

&lt;p&gt;Run it backwards and you get the average lux a given number of fittings will deliver, which is handy for checking a layout someone else has already drawn.&lt;/p&gt;

&lt;p&gt;A small calculator&lt;br&gt;
Here's the whole thing. It uses only the standard library, so it runs anywhere Python 3.7 or later is installed.&lt;/p&gt;

&lt;p&gt;import math&lt;br&gt;
from dataclasses import dataclass&lt;/p&gt;

&lt;p&gt;@dataclass&lt;br&gt;
class Fitting:&lt;br&gt;
    name: str&lt;br&gt;
    lumens: float    # rated luminous flux from the datasheet&lt;br&gt;
    beam_deg: float  # full beam angle in degrees&lt;/p&gt;

&lt;p&gt;def fittings_needed(target_lux, area_m2, fitting, uf=0.5, mf=0.8):&lt;br&gt;
    """Lumen method: N = (E x A) / (flux x UF x MF), rounded up."""&lt;br&gt;
    n = (target_lux * area_m2) / (fitting.lumens * uf * mf)&lt;br&gt;
    return math.ceil(n)&lt;/p&gt;

&lt;p&gt;def average_lux(n, area_m2, fitting, uf=0.5, mf=0.8):&lt;br&gt;
    """Average maintained illuminance that n fittings give over the area."""&lt;br&gt;
    return n * fitting.lumens * uf * mf / area_m2&lt;/p&gt;

&lt;p&gt;def footprint_m(height_m, beam_deg):&lt;br&gt;
    """Beam diameter on the ground for a fitting aimed straight down."""&lt;br&gt;
    return 2 * height_m * math.tan(math.radians(beam_deg / 2))&lt;/p&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    yard_l, yard_w = 30, 20   # metres&lt;br&gt;
    area = yard_l * yard_w&lt;br&gt;
    target = 20               # lux, the figure agreed with the client&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;options = [
    Fitting("50 W, 90 deg beam", lumens=5000, beam_deg=90),
    Fitting("50 W, 120 deg beam", lumens=5500, beam_deg=120),
]

print(f"Yard {yard_l} x {yard_w} m = {area} m2, target {target} lux")
for f in options:
    n = fittings_needed(target, area, f)
    lux = average_lux(n, area, f)
    print(f"\n{f.name}: {n} fittings, about {lux:.1f} lux average")
    for h in (5, 6, 8):
        print(f"  at {h} m the beam is about {footprint_m(h, f.beam_deg):.1f} m across")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Running it for a 50 W flood light on a factory yard&lt;br&gt;
The example is a 30 by 20 metre loading yard behind a factory, with an assumed target of 20 lux for this walkthrough. Treat that figure as an example only, not a recommendation for your site. The two fittings are a 50 W flood light with a 90° beam rated at 5,000 lumens, and a 50 W model with a 120° beam at 5,500 lumens, which are the kind of figures you'll find on real datasheets in this class.&lt;/p&gt;

&lt;p&gt;The script prints:&lt;/p&gt;

&lt;p&gt;Yard 30 x 20 m = 600 m2, target 20 lux&lt;/p&gt;

&lt;p&gt;50 W, 90 deg beam: 6 fittings, about 20.0 lux average&lt;br&gt;
  at 5 m the beam is about 10.0 m across&lt;br&gt;
  at 6 m the beam is about 12.0 m across&lt;br&gt;
  at 8 m the beam is about 16.0 m across&lt;/p&gt;

&lt;p&gt;50 W, 120 deg beam: 6 fittings, about 22.0 lux average&lt;br&gt;
  at 5 m the beam is about 17.3 m across&lt;br&gt;
  at 6 m the beam is about 20.8 m across&lt;br&gt;
  at 8 m the beam is about 27.7 m across&lt;br&gt;
Both options land on six fittings. That's where the second function earns its place.&lt;/p&gt;

&lt;p&gt;Checking the beam footprint against mounting height&lt;br&gt;
An average can hide a lot. Six fittings giving 20 lux on average might mean a bright patch under each pole and dark bands between them. The footprint function is a crude check for that: for a fitting aimed straight down, the lit circle on the ground has a diameter of 2 × h × tan(beam / 2).&lt;/p&gt;

&lt;p&gt;A 50 W flood light with a 90° beam at 6 metres lights a circle roughly 12 metres across. Spread six of them over a 30 by 20 metre yard and the circles barely touch, so expect visible gaps. The 120° fitting at the same height covers about 21 metres, so the pools overlap and the yard looks far more even. The catch is that a wider beam also throws more light past the yard edges, so its real UF is probably lower than the 0.5 we assumed. Change the uf argument per fitting and rerun to see how sensitive your answer is.&lt;/p&gt;

&lt;p&gt;Flood lights are rarely aimed straight down in practice, so treat the footprint as an approximation. Tilting a fitting stretches its pool into an ellipse and pushes more light toward the far side.&lt;/p&gt;

&lt;p&gt;What the script doesn't know&lt;br&gt;
A few things matter on Pakistani sites that no lumen calculation captures. Glare toward a road or a neighbour's house depends on aiming, not on the maths. Heat matters too: a 50 W flood light on a south-facing wall in a Lahore June runs hotter than one under a shade, and that affects how long it lasts. And dust is constant, which is why we'd rather be pessimistic on MF than promise a client 20 lux that turns into 14 after one andhi season.&lt;/p&gt;

&lt;p&gt;If you're filling in the lumen and beam inputs, our &lt;a&gt;flood light&lt;/a&gt; models with published lumen and beam figures give you real numbers from 50W upward to plug straight into the script.&lt;/p&gt;

&lt;p&gt;Questions about a specific yard or layout can go to our engineering team at &lt;a href="https://hyundailedlights.com.pk" rel="noopener noreferrer"&gt;Hyundai LED&lt;/a&gt;, and we're happy to sanity-check your numbers.&lt;/p&gt;

</description>
      <category>code</category>
      <category>programming</category>
      <category>python</category>
    </item>
  </channel>
</rss>
