Module:BassaridEmployment: Difference between revisions
From MicrasWiki
Jump to navigationJump to search
NewZimiaGov (talk | contribs) No edit summary |
NewZimiaGov (talk | contribs) No edit summary |
||
| Line 1: | Line 1: | ||
-- Module:BassaridEmployment | -- Module:BassaridEmployment | ||
-- Employment report | -- Employment report derived from the company rosters inside: | ||
-- Module:AutoUpdateAgPrices | |||
-- Module:AutoUpdateManfPrices | |||
-- Module:AutoUpdateServPrices | |||
-- | -- | ||
-- | -- It models daily employment movement using: | ||
-- | -- costs (price-module ratios), weather (BassaridiaForecast), market (BassaridMarketActivity), | ||
-- War League tempo (WarLeagueDivisionOpsBVR), Temple tempo (MissionaryDailyOpsBVR), | |||
-- | -- and optionally Hatch Ministry tempo (HatchMinistryDailyOpsBVR if present). | ||
-- | |||
-- | -- | ||
-- Usage: | -- Usage: | ||
-- {{#invoke:BassaridEmployment|generateTable}} | -- {{#invoke:BassaridEmployment|generateTable}} | ||
-- {{#invoke:BassaridEmployment|generateTable|city=Vaeringheim}} | -- {{#invoke:BassaridEmployment|generateTable|city=Vaeringheim}} | ||
-- {{#invoke:BassaridEmployment|generateTable|sector=Services}} | |||
-- {{#invoke:BassaridEmployment|generateTable|limit=80}} | -- {{#invoke:BassaridEmployment|generateTable|limit=80}} | ||
-- {{#invoke:BassaridEmployment|generateTable|dashboard=no}} | -- {{#invoke:BassaridEmployment|generateTable|dashboard=no}} | ||
local p = {} | local p = {} | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
-- | -- UTIL | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
local function trim(s) | local function trim(s) | ||
| Line 40: | Line 38: | ||
local function safeNumber(x) | local function safeNumber(x) | ||
return tonumber(x) | |||
end | end | ||
| Line 52: | Line 48: | ||
local function hashFrac(s) | local function hashFrac(s) | ||
local ok, h = pcall(function() return mw.hash.hashValue("md5", tostring(s or "")) end) | local ok, h = pcall(function() return mw.hash.hashValue("md5", tostring(s or "")) end) | ||
if not ok or not h or #h < 8 then return 0.5 end | if not ok or not h or #h < 8 then return 0.5 end | ||
| Line 60: | Line 55: | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
-- | -- DATE (PSSC) | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
local DAYS_IN_YEAR = 183 | local DAYS_IN_YEAR = 183 | ||
| Line 85: | Line 80: | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
-- | -- READ COMPANY ROSTERS FROM PRICE MODULE OUTPUT (breakdown table) | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
local | local function splitCells(line) | ||
-- expects something like: | |||
-- | 4/3/52 [[PSSC]] || Product || Company || 1.23 || ... | |||
-- We return an array of cell strings. | |||
line = trim(line) | |||
if not line:match("^|%s*[^%-!}]") then | |||
return nil | |||
end | |||
line = line:gsub("^|%s*", "") | |||
local cells = {} | |||
for part in line:gmatch("([^|]+)") do | |||
-- this would also split single |, so we use a safer approach below. | |||
end | |||
-- safer: split on "||" | |||
for cell in line:gmatch("([^|][^|]-)%s*||") do | |||
table.insert(cells, trim(cell)) | |||
end | |||
-- add final cell (after last ||) | |||
local last = line:match("||%s*([^|].-)%s*$") | |||
if last then table.insert(cells, trim(last)) end | |||
return cells | |||
end | |||
local function extractCompaniesFromModule(modName, sectorLabel) | |||
local ok, m = pcall(require, modName) | |||
if not ok or not m or type(m.generateTable) ~= "function" then | |||
return {} | |||
end | |||
-- force breakdown expanded so the output is deterministic & complete | |||
local | local out = m.generateTable({ args = { mode = "breakdown", collapse = "no" } }) or "" | ||
local companies = {} | local companies = {} | ||
local seen = {} | local seen = {} | ||
local productCounts = {} | |||
for line in out:gmatch("[^\n]+") do | |||
line = trim(line) | |||
if | -- data line is the one starting with "| <date> || <product> || <company> || ..." | ||
if line:match("^|%s*%d+/%d+/%d+%s*%[%[PSSC%]%]%s*||") then | |||
local cells = {} | |||
-- split on "||" | |||
for cell in line:gmatch("([^|]-)%s*||%s*") do | |||
if trim(cell) ~= "" then table.insert(cells, trim(cell)) end | |||
end | |||
-- add tail | |||
local tail = line:match("||%s*([^|].-)%s*$") | |||
if tail and trim(tail) ~= "" then table.insert(cells, trim(tail)) end | |||
-- expected: 1=date, 2=product, 3=company | |||
local company = cells[3] | |||
if company then | |||
company = stripWiki(company) | |||
if company ~= "" then | |||
if not seen[company] then | |||
seen[company] = true | |||
companies[#companies + 1] = { name = company, sector = sectorLabel } | |||
end | |||
productCounts[company] = (productCounts[company] or 0) + 1 | |||
end | |||
end | |||
end | end | ||
end | end | ||
return companies, productCounts | |||
end | |||
local function buildCompanyRoster() | |||
local roster = {} | |||
local counts = {} | |||
local agCompanies, agCounts = extractCompaniesFromModule("Module:AutoUpdateAgPrices", "Agricultural") | |||
local mfCompanies, mfCounts = extractCompaniesFromModule("Module:AutoUpdateManfPrices", "Mining/Manufacturing") | |||
local svCompanies, svCounts = extractCompaniesFromModule("Module:AutoUpdateServPrices", "Services") | |||
local seen = {} | |||
local function addAll(list, cts) | |||
for _, c in ipairs(list or {}) do | |||
if not seen[c.name] then | |||
seen[c.name] = true | |||
table.insert(roster, c) | |||
end | |||
counts[c.name] = (counts[c.name] or 0) + (cts[c.name] or 0) | |||
end | end | ||
end | end | ||
return | addAll(agCompanies, agCounts or {}) | ||
addAll(mfCompanies, mfCounts or {}) | |||
addAll(svCompanies, svCounts or {}) | |||
return roster, counts | |||
end | end | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
-- | -- COST INDEX (avg adjusted vs base) from price modules | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
local function getCostIndex(moduleName | local function getCostIndex(moduleName) | ||
local ok, m = pcall(require, moduleName) | local ok, m = pcall(require, moduleName) | ||
if not ok or not m or type(m.generateTable) ~= "function" then | if not ok or not m or type(m.generateTable) ~= "function" then | ||
return { ratio = 1.0, avgNew = nil, avgBase = nil } | return { ratio = 1.0, avgNew = nil, avgBase = nil } | ||
end | end | ||
local out = m.generateTable({ args = { mode = "summary" } }) or "" | |||
local out = m.generateTable({ args = { mode = | |||
local aNew, aBase = out:match("Average adjusted %(([%d%.]+)%) vs base %(([%d%.]+)%)") | local aNew, aBase = out:match("Average adjusted %(([%d%.]+)%) vs base %(([%d%.]+)%)") | ||
aNew, aBase = safeNumber(aNew), safeNumber(aBase) | aNew, aBase = safeNumber(aNew), safeNumber(aBase) | ||
| Line 153: | Line 196: | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
-- | -- MARKET | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
local function getMarketSentiment() | local function getMarketSentiment() | ||
| Line 162: | Line 205: | ||
local out = m.generateTable({ args = {} }) or "" | local out = m.generateTable({ args = {} }) or "" | ||
local sum, n, pos, neg = 0, 0, 0, 0 | local sum, n, pos, neg = 0, 0, 0, 0 | ||
for pct in out:gmatch("([%+%-]?%d+%.?%d*)%%") do | for pct in out:gmatch("([%+%-]?%d+%.?%d*)%%") do | ||
| Line 178: | Line 220: | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
-- | -- WEATHER (BassaridiaForecast.getOpsData) | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
local function getWeatherSignal(city, year, dayOfYear) | local function getWeatherSignal(city, year, dayOfYear) | ||
| Line 198: | Line 240: | ||
local function weatherMultiplier(wx, sector) | local function weatherMultiplier(wx, sector) | ||
local lvl = tonumber(wx.level or 0) or 0 | local lvl = tonumber(wx.level or 0) or 0 | ||
local m = 1.0 | local m = 1.0 | ||
| Line 210: | Line 251: | ||
local a = tostring(imp.air or "") | local a = tostring(imp.air or "") | ||
if sector == "Agricultural" then | if sector == "Agricultural" then | ||
if g == "No-Go" then m = m * 0.75 | if g == "No-Go" then m = m * 0.75 | ||
| Line 227: | Line 267: | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
-- | -- WAR LEAGUE TEMPO | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
local function getWarTempo(di) | local function getWarTempo(di) | ||
| Line 236: | Line 276: | ||
local out = wl.makeTable({ args = { rows = 36, showlegend = "no", seed = (di.year * 1000 + di.dayOfYear) } }) or "" | local out = wl.makeTable({ args = { rows = 36, showlegend = "no", seed = (di.year * 1000 + di.dayOfYear) } }) or "" | ||
local rows | local rows, high, critical = 0, 0, 0 | ||
for u in out:gmatch("||%s*(LOW|MEDIUM|HIGH|CRITICAL)%s*||") do | for u in out:gmatch("||%s*(LOW|MEDIUM|HIGH|CRITICAL)%s*||") do | ||
rows = rows + 1 | rows = rows + 1 | ||
| Line 248: | Line 282: | ||
if u == "CRITICAL" then critical = critical + 1 end | if u == "CRITICAL" then critical = critical + 1 end | ||
end | end | ||
if rows == 0 then rows = 36 end | if rows == 0 then rows = 36 end | ||
local severity = (high * 1.0 + critical * 2.0) / rows | local severity = (high * 1.0 + critical * 2.0) / rows | ||
| Line 255: | Line 288: | ||
local function warMultiplier(war, sector) | local function warMultiplier(war, sector) | ||
local s = tonumber(war.score or 0) or 0 | local s = tonumber(war.score or 0) or 0 | ||
if sector == "Services" then | if sector == "Services" then | ||
| Line 268: | Line 300: | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
-- | -- TEMPLE / MISSIONARY TEMPO | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
local function getTempleTempo( | local function getTempleTempo() | ||
local ok, tb = pcall(require, "Module:MissionaryDailyOpsBVR") | local ok, tb = pcall(require, "Module:MissionaryDailyOpsBVR") | ||
if not ok or not tb or type(tb.makeTable) ~= "function" then | if not ok or not tb or type(tb.makeTable) ~= "function" then | ||
return { redRate = 0 } | return { redRate = 0 } | ||
end | end | ||
local out = tb.makeTable({ args = { region = "Core", includeThreat = "no", showEcon = "no", limit = 40, showlegend = "no" } }) or "" | local out = tb.makeTable({ args = { region = "Core", includeThreat = "no", showEcon = "no", limit = 40, showlegend = "no" } }) or "" | ||
local red, n = 0, 0 | local red, n = 0, 0 | ||
for sev in out:gmatch("||%s*(Green|Yellow|Red)%s*$") do | for sev in out:gmatch("||%s*(Green|Yellow|Red)%s*$") do | ||
n = n + 1 | n = n + 1 | ||
if sev == "Red" then red = red + 1 end | if sev == "Red" then red = red + 1 end | ||
end | end | ||
if n == 0 then n = 40 end | if n == 0 then n = 40 end | ||
return { redRate = red / n } | return { redRate = red / n } | ||
| Line 294: | Line 318: | ||
local function templeMultiplier(temple, sector) | local function templeMultiplier(temple, sector) | ||
local r = tonumber(temple.redRate or 0) or 0 | local r = tonumber(temple.redRate or 0) or 0 | ||
if sector == "Services" then | if sector == "Services" then | ||
| Line 303: | Line 326: | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
-- | -- OPTIONAL HATCH MINISTRY TEMPO | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
local function getHatchTempo(di) | local function getHatchTempo(di) | ||
local ok, hm = pcall(require, "Module:HatchMinistryDailyOpsBVR") | |||
if not ok or not hm or type(hm.makeTable) ~= "function" then | |||
return { present = false, intensity = 0 } | |||
end | |||
local out = hm.makeTable({ args = { rows = 30, seed = (di.year * 1000 + di.dayOfYear) } }) or "" | |||
-- naive proxy: count "Interdiction" / "Inspection" / "Seizure" | |||
local c = 0 | |||
for _ in out:gmatch("[Ii]nterdict") do c = c + 1 end | |||
for _ in out:gmatch("[Ii]nspect") do c = c + 1 end | |||
end | for _ in out:gmatch("[Ss]eiz") do c = c + 1 end | ||
return { present = true, intensity = c } | |||
end | end | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
-- | -- BUILD BASE SHARES FROM PRODUCT-COUNTS (all companies from price modules) | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
local function buildBaseShares( | local function buildBaseShares(roster, productCounts) | ||
-- | -- Baseline sector targets (tweak if you want) | ||
local sectorTarget = { | local sectorTarget = { | ||
["Agricultural"] = 0.34, | ["Agricultural"] = 0.34, | ||
["Mining/Manufacturing"] = 0.33, | ["Mining/Manufacturing"] = 0.33, | ||
["Services"] = 0.33 | ["Services"] = 0.33 | ||
} | } | ||
local bySector = { Agricultural = {}, ["Mining/Manufacturing"] = {}, Services = {} } | |||
local bySector = { Agricultural = {}, ["Mining/Manufacturing"] = {}, Services | for _, c in ipairs(roster) do | ||
for _, c in ipairs( | table.insert(bySector[c.sector], c) | ||
table.insert(bySector[ | |||
end | end | ||
local shares = {} | |||
local | |||
for sec, list in pairs(bySector) do | for sec, list in pairs(bySector) do | ||
local | local rawSum = 0 | ||
for _, c in ipairs(list) do | for _, c in ipairs(list) do | ||
local w = 0. | local nprod = productCounts[c.name] or 1 | ||
-- weight: sqrt(products) * (0.7..1.9) | |||
local w = (math.sqrt(nprod)) * (0.7 + hashFrac("w:" .. c.name) * 1.2) | |||
shares[c.name] = { sector = sec, raw = w, share = 0, nprod = nprod } | |||
rawSum = rawSum + w | |||
end | end | ||
local target = sectorTarget[sec] or 0 | local target = sectorTarget[sec] or 0 | ||
for _, c in ipairs(list) do | for _, c in ipairs(list) do | ||
local | local rec = shares[c.name] | ||
rec.share = (rawSum > 0) and (rec.raw / rawSum) * target or 0 | |||
end | end | ||
end | end | ||
return | return shares | ||
end | end | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
-- | -- MAIN | ||
-------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ||
function p.generateTable(frame) | function p.generateTable(frame) | ||
| Line 380: | Line 390: | ||
local city = tostring(args.city or "Vaeringheim") | local city = tostring(args.city or "Vaeringheim") | ||
local sectorFilter = trim(tostring(args.sector or "")) -- Agricultural | Mining/Manufacturing | Services | local sectorFilter = trim(tostring(args.sector or "")) -- Agricultural | Mining/Manufacturing | Services | ||
local limit = tonumber(args.limit or "") | local limit = tonumber(args.limit or "") | ||
local showDashboard = tostring(args.dashboard or "yes"):lower() ~= "no" | local showDashboard = tostring(args.dashboard or "yes"):lower() ~= "no" | ||
-- | -- stable per day | ||
math.randomseed(di.year * 1000 + di.dayOfYear) | math.randomseed(di.year * 1000 + di.dayOfYear) | ||
-- | -- roster from the three price modules | ||
local | local roster, productCounts = buildCompanyRoster() | ||
if #roster == 0 then | |||
return "''BassaridEmployment error: could not read company rosters from price modules.''" | |||
if # | |||
end | end | ||
local shares = buildBaseShares( | local shares = buildBaseShares(roster, productCounts) | ||
-- | -- Costs (ratios) | ||
local costAg = getCostIndex("Module:AutoUpdateAgPrices | local costAg = getCostIndex("Module:AutoUpdateAgPrices") | ||
local costManf = getCostIndex("Module:AutoUpdateManfPrices | local costManf = getCostIndex("Module:AutoUpdateManfPrices") | ||
local costServ = getCostIndex("Module:AutoUpdateServPrices | local costServ = getCostIndex("Module:AutoUpdateServPrices") | ||
-- Market | -- Market / Weather / Ops | ||
local market = getMarketSentiment() | local market = getMarketSentiment() | ||
local wx = getWeatherSignal(city, di.year, di.dayOfYear) | local wx = getWeatherSignal(city, di.year, di.dayOfYear) | ||
local war = getWarTempo(di) | local war = getWarTempo(di) | ||
local temple = getTempleTempo( | local temple = getTempleTempo() | ||
local hatch = getHatchTempo(di) | local hatch = getHatchTempo(di) | ||
-- Macro | -- Macro base | ||
local population = 94160000 | local population = 94160000 | ||
local unemploymentRate = 0.04 | local unemploymentRate = 0.04 | ||
-- | -- Macro adjustments | ||
local u = unemploymentRate | local u = unemploymentRate | ||
u = u - clamp(market.bias * 0.01, -0.01, 0.01) | u = u - clamp((market.bias or 0) * 0.01, -0.01, 0.01) | ||
u = u + clamp((wx.level or 0) * 0.005, 0, 0.02) | u = u + clamp((wx.level or 0) * 0.005, 0, 0.02) | ||
u = clamp(u, 0.02, 0.08) | u = clamp(u, 0.02, 0.08) | ||
| Line 434: | Line 429: | ||
local function sectorCostMultiplier(sec) | local function sectorCostMultiplier(sec) | ||
local r = 1.0 | local r = 1.0 | ||
if sec == "Agricultural" then r = costAg.ratio or 1.0 | if sec == "Agricultural" then r = costAg.ratio or 1.0 | ||
| Line 444: | Line 437: | ||
local function marketMultiplier(sec) | local function marketMultiplier(sec) | ||
local b = clamp(market.bias or 0, -1, 1) | local b = clamp(market.bias or 0, -1, 1) | ||
if sec == "Services" then | if sec == "Services" then | ||
| Line 455: | Line 447: | ||
end | end | ||
local function combinedMultiplier(sec) | local function combinedMultiplier(sec) | ||
local m = 1.0 | local m = 1.0 | ||
| Line 467: | Line 458: | ||
end | end | ||
local out = {} | local out = {} | ||
if showDashboard then | if showDashboard then | ||
table.insert(out, "{| class=\"wikitable\" style=\"width:100%;\"") | table.insert(out, "{| class=\"wikitable\" style=\"width:100%;\"") | ||
| Line 486: | Line 477: | ||
end | end | ||
table.insert(out, '<div style="overflow-x:auto;">') | table.insert(out, '<div style="overflow-x:auto;">') | ||
table.insert(out, "{| class=\"wikitable sortable\"") | table.insert(out, "{| class=\"wikitable sortable\"") | ||
table.insert(out, "! Date !! Sector !! Company !! Base Share % !! | table.insert(out, "! Date !! Sector !! Company !! Products !! Base Share % !! Prev Emp. !! Curr Emp. !! Δ !! Drivers") | ||
local | local n = 0 | ||
for _, c in ipairs( | for _, c in ipairs(roster) do | ||
local sec = c.sector | local sec = c.sector | ||
if sectorFilter == "" or sec == sectorFilter then | if sectorFilter == "" or sec == sectorFilter then | ||
local | local rec = shares[c.name] | ||
local share = (rec and rec.share) or 0 | |||
local nprod = (rec and rec.nprod) or (productCounts[c.name] or 1) | |||
local prev = math.max(1, math.floor(employedPopulation * share)) | local prev = math.max(1, math.floor(employedPopulation * share)) | ||
-- | -- company/day jitter ±9% | ||
local jitter = (hashFrac(string.format("jit:%s:%d:%d", c.name, di.year, di.dayOfYear)) - 0.5) * 0.18 | local jitter = (hashFrac(string.format("jit:%s:%d:%d", c.name, di.year, di.dayOfYear)) - 0.5) * 0.18 | ||
local mult = combinedMultiplier(sec) * (1.0 + jitter) | local mult = combinedMultiplier(sec) * (1.0 + jitter) | ||
local curr = math.max(1, math.floor(prev * mult)) | local curr = math.max(1, math.floor(prev * mult)) | ||
| Line 509: | Line 500: | ||
elseif curr < prev then deltaSym = "↓" end | elseif curr < prev then deltaSym = "↓" end | ||
local rowStyle = "" | local rowStyle = "" | ||
if curr > prev then rowStyle = ' style="background-color:lightblue;"' | if curr > prev then rowStyle = ' style="background-color:lightblue;"' | ||
| Line 526: | Line 516: | ||
table.insert(out, string.format( | table.insert(out, string.format( | ||
"|-%s\n| %s || %s || %s || %.3f%% || %d || %d || %s || %s", | "|-%s\n| %s || %s || %s || %d || %.3f%% || %d || %d || %s || %s", | ||
rowStyle, | rowStyle, | ||
di.dateString, | di.dateString, | ||
sec, | sec, | ||
c.name, | c.name, | ||
nprod, | |||
share * 100, | share * 100, | ||
prev, | prev, | ||
| Line 538: | Line 529: | ||
)) | )) | ||
n = n + 1 | |||
if limit and | if limit and n >= limit then break end | ||
end | end | ||
end | end | ||
Revision as of 18:56, 19 January 2026
Documentation for this module may be created at Module:BassaridEmployment/doc
-- Module:BassaridEmployment
-- Employment report derived from the company rosters inside:
-- Module:AutoUpdateAgPrices
-- Module:AutoUpdateManfPrices
-- Module:AutoUpdateServPrices
--
-- It models daily employment movement using:
-- costs (price-module ratios), weather (BassaridiaForecast), market (BassaridMarketActivity),
-- War League tempo (WarLeagueDivisionOpsBVR), Temple tempo (MissionaryDailyOpsBVR),
-- and optionally Hatch Ministry tempo (HatchMinistryDailyOpsBVR if present).
--
-- Usage:
-- {{#invoke:BassaridEmployment|generateTable}}
-- {{#invoke:BassaridEmployment|generateTable|city=Vaeringheim}}
-- {{#invoke:BassaridEmployment|generateTable|sector=Services}}
-- {{#invoke:BassaridEmployment|generateTable|limit=80}}
-- {{#invoke:BassaridEmployment|generateTable|dashboard=no}}
local p = {}
--------------------------------------------------------------------------------
-- UTIL
--------------------------------------------------------------------------------
local function trim(s)
s = tostring(s or "")
return (s:gsub("^%s+", ""):gsub("%s+$", ""))
end
local function stripWiki(s)
s = tostring(s or "")
s = s:gsub("%{%b{}%}", "") -- templates
s = s:gsub("%[%[[^%]|]+|([^%]]+)%]%]", "%1") -- piped links
s = s:gsub("%[%[([^%]]+)%]%]", "%1") -- plain links
s = s:gsub("'''''", ""):gsub("'''", ""):gsub("''", "") -- ital/bold
s = s:gsub(" ", " ")
return trim(s)
end
local function safeNumber(x)
return tonumber(x)
end
local function clamp(x, lo, hi)
if x < lo then return lo end
if x > hi then return hi end
return x
end
local function hashFrac(s)
local ok, h = pcall(function() return mw.hash.hashValue("md5", tostring(s or "")) end)
if not ok or not h or #h < 8 then return 0.5 end
local n = tonumber(h:sub(1, 8), 16) or 0
return (n % 1000000) / 1000000
end
--------------------------------------------------------------------------------
-- DATE (PSSC)
--------------------------------------------------------------------------------
local DAYS_IN_YEAR = 183
local function getCurrentDateInfo()
local startDate = os.time({year = 1999, month = 8, day = 6})
local secondsInDay = 86400
local now = os.time()
local totalDays = math.floor((now - startDate) / secondsInDay)
local yearFraction = totalDays / DAYS_IN_YEAR
local psscYear = math.floor(yearFraction)
local dayOfYear = math.floor((yearFraction - psscYear) * DAYS_IN_YEAR) + 1
local month, dayOfMonth
if dayOfYear <= 61 then month, dayOfMonth = 1, dayOfYear
elseif dayOfYear <= 122 then month, dayOfMonth = 2, dayOfYear - 61
else month, dayOfMonth = 3, dayOfYear - 122 end
return {
dateString = string.format("%d/%d/%d [[PSSC]]", dayOfMonth, month, psscYear),
year = psscYear,
dayOfYear = dayOfYear
}
end
--------------------------------------------------------------------------------
-- READ COMPANY ROSTERS FROM PRICE MODULE OUTPUT (breakdown table)
--------------------------------------------------------------------------------
local function splitCells(line)
-- expects something like:
-- | 4/3/52 [[PSSC]] || Product || Company || 1.23 || ...
-- We return an array of cell strings.
line = trim(line)
if not line:match("^|%s*[^%-!}]") then
return nil
end
line = line:gsub("^|%s*", "")
local cells = {}
for part in line:gmatch("([^|]+)") do
-- this would also split single |, so we use a safer approach below.
end
-- safer: split on "||"
for cell in line:gmatch("([^|][^|]-)%s*||") do
table.insert(cells, trim(cell))
end
-- add final cell (after last ||)
local last = line:match("||%s*([^|].-)%s*$")
if last then table.insert(cells, trim(last)) end
return cells
end
local function extractCompaniesFromModule(modName, sectorLabel)
local ok, m = pcall(require, modName)
if not ok or not m or type(m.generateTable) ~= "function" then
return {}
end
-- force breakdown expanded so the output is deterministic & complete
local out = m.generateTable({ args = { mode = "breakdown", collapse = "no" } }) or ""
local companies = {}
local seen = {}
local productCounts = {}
for line in out:gmatch("[^\n]+") do
line = trim(line)
-- data line is the one starting with "| <date> || <product> || <company> || ..."
if line:match("^|%s*%d+/%d+/%d+%s*%[%[PSSC%]%]%s*||") then
local cells = {}
-- split on "||"
for cell in line:gmatch("([^|]-)%s*||%s*") do
if trim(cell) ~= "" then table.insert(cells, trim(cell)) end
end
-- add tail
local tail = line:match("||%s*([^|].-)%s*$")
if tail and trim(tail) ~= "" then table.insert(cells, trim(tail)) end
-- expected: 1=date, 2=product, 3=company
local company = cells[3]
if company then
company = stripWiki(company)
if company ~= "" then
if not seen[company] then
seen[company] = true
companies[#companies + 1] = { name = company, sector = sectorLabel }
end
productCounts[company] = (productCounts[company] or 0) + 1
end
end
end
end
return companies, productCounts
end
local function buildCompanyRoster()
local roster = {}
local counts = {}
local agCompanies, agCounts = extractCompaniesFromModule("Module:AutoUpdateAgPrices", "Agricultural")
local mfCompanies, mfCounts = extractCompaniesFromModule("Module:AutoUpdateManfPrices", "Mining/Manufacturing")
local svCompanies, svCounts = extractCompaniesFromModule("Module:AutoUpdateServPrices", "Services")
local seen = {}
local function addAll(list, cts)
for _, c in ipairs(list or {}) do
if not seen[c.name] then
seen[c.name] = true
table.insert(roster, c)
end
counts[c.name] = (counts[c.name] or 0) + (cts[c.name] or 0)
end
end
addAll(agCompanies, agCounts or {})
addAll(mfCompanies, mfCounts or {})
addAll(svCompanies, svCounts or {})
return roster, counts
end
--------------------------------------------------------------------------------
-- COST INDEX (avg adjusted vs base) from price modules
--------------------------------------------------------------------------------
local function getCostIndex(moduleName)
local ok, m = pcall(require, moduleName)
if not ok or not m or type(m.generateTable) ~= "function" then
return { ratio = 1.0, avgNew = nil, avgBase = nil }
end
local out = m.generateTable({ args = { mode = "summary" } }) or ""
local aNew, aBase = out:match("Average adjusted %(([%d%.]+)%) vs base %(([%d%.]+)%)")
aNew, aBase = safeNumber(aNew), safeNumber(aBase)
if not aNew or not aBase or aBase == 0 then
return { ratio = 1.0, avgNew = aNew, avgBase = aBase }
end
return { ratio = aNew / aBase, avgNew = aNew, avgBase = aBase }
end
--------------------------------------------------------------------------------
-- MARKET
--------------------------------------------------------------------------------
local function getMarketSentiment()
local ok, m = pcall(require, "Module:BassaridMarketActivity")
if not ok or not m or type(m.generateTable) ~= "function" then
return { avgPct = 0.0, bias = 0.0 }
end
local out = m.generateTable({ args = {} }) or ""
local sum, n, pos, neg = 0, 0, 0, 0
for pct in out:gmatch("([%+%-]?%d+%.?%d*)%%") do
local v = tonumber(pct)
if v then
sum = sum + v
n = n + 1
if v > 0 then pos = pos + 1 elseif v < 0 then neg = neg + 1 end
end
end
local avg = (n > 0) and (sum / n) or 0.0
local bias = (n > 0) and ((pos - neg) / n) or 0.0
return { avgPct = avg, bias = bias }
end
--------------------------------------------------------------------------------
-- WEATHER (BassaridiaForecast.getOpsData)
--------------------------------------------------------------------------------
local function getWeatherSignal(city, year, dayOfYear)
local ok, wx = pcall(require, "Module:BassaridiaForecast")
if not ok or not wx or type(wx.getOpsData) ~= "function" then
return { level = 0, label = "Green", impacts = {}, condition = "" }
end
local op = wx.getOpsData(city, year, dayOfYear)
if not op or not op.alert then
return { level = 0, label = "Green", impacts = {}, condition = "" }
end
return {
level = tonumber(op.alert.level) or 0,
label = tostring(op.alert.label or "Green"),
condition = tostring(op.condition or ""),
impacts = op.impacts or {}
}
end
local function weatherMultiplier(wx, sector)
local lvl = tonumber(wx.level or 0) or 0
local m = 1.0
if lvl == 1 then m = 0.98
elseif lvl == 2 then m = 0.93
elseif lvl >= 3 then m = 0.85 end
local imp = wx.impacts or {}
local g = tostring(imp.ground or "")
local s = tostring(imp.sea or "")
local a = tostring(imp.air or "")
if sector == "Agricultural" then
if g == "No-Go" then m = m * 0.75
elseif g == "Degraded" then m = m * 0.90 end
elseif sector == "Mining/Manufacturing" then
if g == "No-Go" then m = m * 0.78
elseif g == "Degraded" then m = m * 0.92 end
elseif sector == "Services" then
if s == "Closed" then m = m * 0.85
elseif s == "Degraded" then m = m * 0.93 end
if a == "No-Go" then m = m * 0.92 end
end
return clamp(m, 0.65, 1.10)
end
--------------------------------------------------------------------------------
-- WAR LEAGUE TEMPO
--------------------------------------------------------------------------------
local function getWarTempo(di)
local ok, wl = pcall(require, "Module:WarLeagueDivisionOpsBVR")
if not ok or not wl or type(wl.makeTable) ~= "function" then
return { score = 0, redRate = 0 }
end
local out = wl.makeTable({ args = { rows = 36, showlegend = "no", seed = (di.year * 1000 + di.dayOfYear) } }) or ""
local rows, high, critical = 0, 0, 0
for u in out:gmatch("||%s*(LOW|MEDIUM|HIGH|CRITICAL)%s*||") do
rows = rows + 1
if u == "HIGH" then high = high + 1 end
if u == "CRITICAL" then critical = critical + 1 end
end
if rows == 0 then rows = 36 end
local severity = (high * 1.0 + critical * 2.0) / rows
return { score = severity, redRate = (high + critical) / rows }
end
local function warMultiplier(war, sector)
local s = tonumber(war.score or 0) or 0
if sector == "Services" then
return clamp(1.0 + (s * 0.08), 0.95, 1.18)
elseif sector == "Mining/Manufacturing" then
return clamp(1.0 + (s * 0.06), 0.95, 1.15)
elseif sector == "Agricultural" then
return clamp(1.0 - (s * 0.03), 0.88, 1.05)
end
return 1.0
end
--------------------------------------------------------------------------------
-- TEMPLE / MISSIONARY TEMPO
--------------------------------------------------------------------------------
local function getTempleTempo()
local ok, tb = pcall(require, "Module:MissionaryDailyOpsBVR")
if not ok or not tb or type(tb.makeTable) ~= "function" then
return { redRate = 0 }
end
local out = tb.makeTable({ args = { region = "Core", includeThreat = "no", showEcon = "no", limit = 40, showlegend = "no" } }) or ""
local red, n = 0, 0
for sev in out:gmatch("||%s*(Green|Yellow|Red)%s*$") do
n = n + 1
if sev == "Red" then red = red + 1 end
end
if n == 0 then n = 40 end
return { redRate = red / n }
end
local function templeMultiplier(temple, sector)
local r = tonumber(temple.redRate or 0) or 0
if sector == "Services" then
return clamp(1.0 + (r * 0.06), 0.98, 1.10)
end
return clamp(1.0 + (r * 0.02), 0.98, 1.06)
end
--------------------------------------------------------------------------------
-- OPTIONAL HATCH MINISTRY TEMPO
--------------------------------------------------------------------------------
local function getHatchTempo(di)
local ok, hm = pcall(require, "Module:HatchMinistryDailyOpsBVR")
if not ok or not hm or type(hm.makeTable) ~= "function" then
return { present = false, intensity = 0 }
end
local out = hm.makeTable({ args = { rows = 30, seed = (di.year * 1000 + di.dayOfYear) } }) or ""
-- naive proxy: count "Interdiction" / "Inspection" / "Seizure"
local c = 0
for _ in out:gmatch("[Ii]nterdict") do c = c + 1 end
for _ in out:gmatch("[Ii]nspect") do c = c + 1 end
for _ in out:gmatch("[Ss]eiz") do c = c + 1 end
return { present = true, intensity = c }
end
--------------------------------------------------------------------------------
-- BUILD BASE SHARES FROM PRODUCT-COUNTS (all companies from price modules)
--------------------------------------------------------------------------------
local function buildBaseShares(roster, productCounts)
-- Baseline sector targets (tweak if you want)
local sectorTarget = {
["Agricultural"] = 0.34,
["Mining/Manufacturing"] = 0.33,
["Services"] = 0.33
}
local bySector = { Agricultural = {}, ["Mining/Manufacturing"] = {}, Services = {} }
for _, c in ipairs(roster) do
table.insert(bySector[c.sector], c)
end
local shares = {}
for sec, list in pairs(bySector) do
local rawSum = 0
for _, c in ipairs(list) do
local nprod = productCounts[c.name] or 1
-- weight: sqrt(products) * (0.7..1.9)
local w = (math.sqrt(nprod)) * (0.7 + hashFrac("w:" .. c.name) * 1.2)
shares[c.name] = { sector = sec, raw = w, share = 0, nprod = nprod }
rawSum = rawSum + w
end
local target = sectorTarget[sec] or 0
for _, c in ipairs(list) do
local rec = shares[c.name]
rec.share = (rawSum > 0) and (rec.raw / rawSum) * target or 0
end
end
return shares
end
--------------------------------------------------------------------------------
-- MAIN
--------------------------------------------------------------------------------
function p.generateTable(frame)
local args = (frame and frame.args) or {}
local di = getCurrentDateInfo()
local city = tostring(args.city or "Vaeringheim")
local sectorFilter = trim(tostring(args.sector or "")) -- Agricultural | Mining/Manufacturing | Services
local limit = tonumber(args.limit or "")
local showDashboard = tostring(args.dashboard or "yes"):lower() ~= "no"
-- stable per day
math.randomseed(di.year * 1000 + di.dayOfYear)
-- roster from the three price modules
local roster, productCounts = buildCompanyRoster()
if #roster == 0 then
return "''BassaridEmployment error: could not read company rosters from price modules.''"
end
local shares = buildBaseShares(roster, productCounts)
-- Costs (ratios)
local costAg = getCostIndex("Module:AutoUpdateAgPrices")
local costManf = getCostIndex("Module:AutoUpdateManfPrices")
local costServ = getCostIndex("Module:AutoUpdateServPrices")
-- Market / Weather / Ops
local market = getMarketSentiment()
local wx = getWeatherSignal(city, di.year, di.dayOfYear)
local war = getWarTempo(di)
local temple = getTempleTempo()
local hatch = getHatchTempo(di)
-- Macro base
local population = 94160000
local unemploymentRate = 0.04
-- Macro adjustments
local u = unemploymentRate
u = u - clamp((market.bias or 0) * 0.01, -0.01, 0.01)
u = u + clamp((wx.level or 0) * 0.005, 0, 0.02)
u = clamp(u, 0.02, 0.08)
local employedPopulation = math.floor(population * (1 - u))
local function sectorCostMultiplier(sec)
local r = 1.0
if sec == "Agricultural" then r = costAg.ratio or 1.0
elseif sec == "Mining/Manufacturing" then r = costManf.ratio or 1.0
elseif sec == "Services" then r = costServ.ratio or 1.0 end
return clamp(0.92 + (r - 1.0) * 0.20, 0.85, 1.12)
end
local function marketMultiplier(sec)
local b = clamp(market.bias or 0, -1, 1)
if sec == "Services" then
return clamp(1.0 + b * 0.03, 0.95, 1.05)
elseif sec == "Mining/Manufacturing" then
return clamp(1.0 + b * 0.02, 0.96, 1.04)
else
return clamp(1.0 + b * 0.01, 0.97, 1.03)
end
end
local function combinedMultiplier(sec)
local m = 1.0
m = m * sectorCostMultiplier(sec)
m = m * weatherMultiplier(wx, sec)
m = m * warMultiplier(war, sec)
m = m * templeMultiplier(temple, sec)
m = m * hatchMultiplier(hatch, sec)
m = m * marketMultiplier(sec)
return clamp(m, 0.65, 1.25)
end
local out = {}
if showDashboard then
table.insert(out, "{| class=\"wikitable\" style=\"width:100%;\"")
table.insert(out, "! colspan=\"4\" | General Port Employment Signals — " .. di.dateString)
table.insert(out, "|-")
table.insert(out, string.format("| '''Weather''' || %s (%s) || '''Market bias''' || %.2f",
(wx.label or "Green"), (wx.condition or ""), (market.bias or 0)))
table.insert(out, "|-")
table.insert(out, string.format("| '''Cost ratio (Ag/Manf/Serv)''' || %.3f / %.3f / %.3f || '''War tempo (red-rate)''' || %.2f",
(costAg.ratio or 1.0), (costManf.ratio or 1.0), (costServ.ratio or 1.0),
(war.redRate or 0)))
table.insert(out, "|-")
table.insert(out, string.format("| '''Temple tempo (red-rate)''' || %.2f || '''Unemployment (modeled)''' || %.2f%%",
(temple.redRate or 0), u * 100))
table.insert(out, "|}")
table.insert(out, "")
end
table.insert(out, '<div style="overflow-x:auto;">')
table.insert(out, "{| class=\"wikitable sortable\"")
table.insert(out, "! Date !! Sector !! Company !! Products !! Base Share % !! Prev Emp. !! Curr Emp. !! Δ !! Drivers")
local n = 0
for _, c in ipairs(roster) do
local sec = c.sector
if sectorFilter == "" or sec == sectorFilter then
local rec = shares[c.name]
local share = (rec and rec.share) or 0
local nprod = (rec and rec.nprod) or (productCounts[c.name] or 1)
local prev = math.max(1, math.floor(employedPopulation * share))
-- company/day jitter ±9%
local jitter = (hashFrac(string.format("jit:%s:%d:%d", c.name, di.year, di.dayOfYear)) - 0.5) * 0.18
local mult = combinedMultiplier(sec) * (1.0 + jitter)
local curr = math.max(1, math.floor(prev * mult))
local deltaSym = "•"
if curr > prev then deltaSym = "↑"
elseif curr < prev then deltaSym = "↓" end
local rowStyle = ""
if curr > prev then rowStyle = ' style="background-color:lightblue;"'
elseif curr == prev then rowStyle = ' style="background-color:lightgreen;"'
else rowStyle = ' style="background-color:#ffcccb;"' end
local drivers = string.format(
"cost×%.2f; wx×%.2f; war×%.2f; temple×%.2f; hatch×%.2f; mkt×%.2f",
sectorCostMultiplier(sec),
weatherMultiplier(wx, sec),
warMultiplier(war, sec),
templeMultiplier(temple, sec),
hatchMultiplier(hatch, sec),
marketMultiplier(sec)
)
table.insert(out, string.format(
"|-%s\n| %s || %s || %s || %d || %.3f%% || %d || %d || %s || %s",
rowStyle,
di.dateString,
sec,
c.name,
nprod,
share * 100,
prev,
curr,
deltaSym,
drivers
))
n = n + 1
if limit and n >= limit then break end
end
end
table.insert(out, "|}")
table.insert(out, "</div>")
return table.concat(out, "\n")
end
return p