Module:BassaridEmployment: Difference between revisions

From MicrasWiki
Jump to navigationJump to search
NewZimiaGov (talk | contribs)
No edit summary
NewZimiaGov (talk | contribs)
No edit summary
 
(12 intermediate revisions by the same user not shown)
Line 1: Line 1:
-- Module:BassaridEmployment
local p = {}
-- Employment report for the General Port of Lake Morovia.
 
--
local market = require("Module:BassaridMarketActivity")
-- Key changes:
 
--  • Includes ALL companies listed on [[General Port of Lake Morovia]] Company Table (auto-parsed).
local CITY_POP = {
--  • Factors in: costs (Ag/Manf/Serv price modules), weather (BassaridiaForecast),
["Vaeringheim"] = 20887650.86,
--   War League activity (WarLeagueDivisionOpsBVR), Temple Bank activity (MissionaryDailyOpsBVR),
["Lunalis Sancta"] = 7832869.07,
--    market sentiment (BassaridMarketActivity), and (optionally) Hatch Ministry ops.
["Luminaria"] = 6382335.99,
--
["Serena"] = 6672442.61,
-- Usage:
["Symphonara"] = 4351592.87,
--  {{#invoke:BassaridEmployment|generateTable}}
["Aurelia"] = 3771379.63,
--  {{#invoke:BassaridEmployment|generateTable|city=Vaeringheim}}
["Sylvapolis"] = 3481276.21,
--  {{#invoke:BassaridEmployment|generateTable|limit=80}}
["Delphica"] = 2030743.12,
--  {{#invoke:BassaridEmployment|generateTable|sector=Agricultural}}
["Catonis Atrium"] = 1682617.10,
--  {{#invoke:BassaridEmployment|generateTable|dashboard=no}}
["Ferrum Citadel"] = 928339.26,
--
["Pyralis"] = 12965917.88,
-- Notes:
["Nexa"] = 7979025.10,
-- • This module is designed to be deterministic per day (stable output on the same day).
["Saluria"] = 7729680.74,
--  • If the port page format changes, parsing may need a small adjustment.
["Acheron"] = 4238856.91,
["Koinonía"] = 5485581.50,
["Aureum"] = 4488201.27,
["Aetherium"] = 3740168.19,
["Erythros"] = 3241479.47,
["Somniumpolis"] = 16035032.55,
["Hafaan"] = 3568579.65,
["Jeseri"] = 2430778.52,
["Skýrophos"] = 5132630.96,
["Bjornopolis"] = 4016840.25,
["Aegerheim"] = 3347368.98,
["Norsolyra"] = 2901052.70,
["Thorsalon"] = 2454736.41,
["Myrene"] = 1338945.70,
["Ephyra"] = 1115790.71,
["Thyrea"] = 892632.57,
["Pelagia"] = 669474.43,
["Halicarn"] = 446316.28,
["Keybir-Aviv"] = 4592562.31,
["Tel-Amin"] = 4155174.90,
["Jogi"] = 3936483.03,
["Lewisburg"] = 3280401.91,
["Diamandis"] = 2843014.50,
["Thermosalem"] = 1312160.40,
["Akróstadium"] = 1093466.69,
["Lykopolis"] = 437387.41,
["Sufriya"] = 218693.71,
["Riddersborg"] = 11757190.77,
["Ardclach"] = 5426395.09,
["Ourid"] = 31826487.08,
["Bashkim"] = 23046766.50
}
 
-- Default sector shares of the employed population.
-- These should sum to 1.00.
local SECTOR_EMPLOYMENT_SHARE = {
agriculture = 0.27,
industry = 0.31,
services = 0.42
}


local p = {}
local MOD = 2147483647
local A  = 1103515245
local C  = 12345


--------------------------------------------------------------------------------
local function hashString(s)
-- 0) BASIC UTILS
--------------------------------------------------------------------------------
local function trim(s)
s = tostring(s or "")
s = tostring(s or "")
return (s:gsub("^%s+", ""):gsub("%s+$", ""))
local h = 0
for i = 1, #s do
h = (h * 31 + s:byte(i)) % MOD
end
return h
end
end


local function stripWiki(s)
local function lcg(seed)
s = tostring(s or "")
seed = seed % MOD
s = s:gsub("%{%b{}%}", "")                                -- templates
return function()
s = s:gsub("%[%[[^%]|]+|([^%]]+)%]%]", "%1")               -- piped links
seed = (A * seed + C) % MOD
s = s:gsub("%[%[([^%]]+)%]%]", "%1")                      -- plain links
return seed
s = s:gsub("'''''", ""):gsub("'''", ""):gsub("''", "")    -- ital/bold
end
s = s:gsub(" ", " ")
return trim(s)
end
end


local function safeNumber(x)
local function randUnit(nextInt)
local n = tonumber(x)
return (nextInt() % 100000) / 100000
if not n then return nil end
return n
end
end


Line 51: Line 89:
end
end


local function hashFrac(s)
local function round(num)
-- stable 0..1 from md5 hex
return math.floor(num + 0.5)
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
end


--------------------------------------------------------------------------------
local function getCurrentDate()
-- 1) DATE (PSSC) – keep same base logic as your other modules
local startDate = os.time({ year = 1999, month = 8, day = 6 })
--------------------------------------------------------------------------------
local DAYS_IN_YEAR = 183
local function getCurrentDateInfo()
local startDate = os.time({year = 1999, month = 8, day = 6})
local secondsInDay = 86400
local secondsInDay = 86400
local now = os.time()
local daysPerYear = 183
local totalDays = math.floor((now - startDate) / secondsInDay)
local currentDate = os.time()
local yearFraction = totalDays / DAYS_IN_YEAR
local totalDaysElapsed = math.floor((currentDate - startDate) / secondsInDay)
local yearFraction = totalDaysElapsed / daysPerYear
local psscYear = math.floor(yearFraction)
local psscYear = math.floor(yearFraction)
local dayOfYear = math.floor((yearFraction - psscYear) * DAYS_IN_YEAR) + 1
local dayOfYear = math.floor((yearFraction - psscYear) * daysPerYear) + 1
 
local month, dayOfMonth
local month, dayOfMonth
if dayOfYear <= 61 then month, dayOfMonth = 1, dayOfYear
if dayOfYear <= 61 then
elseif dayOfYear <= 122 then month, dayOfMonth = 2, dayOfYear - 61
month = 1; dayOfMonth = dayOfYear
else month, dayOfMonth = 3, dayOfYear - 122 end
elseif dayOfYear <= 122 then
 
month = 2; dayOfMonth = dayOfYear - 61
return {
else
dateString = string.format("%d/%d/%d [[PSSC]]", dayOfMonth, month, psscYear),
month = 3; dayOfMonth = dayOfYear - 122
year = psscYear,
dayOfYear = dayOfYear
}
end
 
--------------------------------------------------------------------------------
-- 2) PULL ALL PORT COMPANIES (auto-parse from the General Port page)
--------------------------------------------------------------------------------
local PORT_PAGE = "General Port of Lake Morovia"
 
local function parsePortCompanies()
local title = mw.title.new(PORT_PAGE)
if not title then return {} end
local content = title:getContent() or ""
if content == "" then return {} end
 
-- We track sector based on headers.
-- Your page uses a Company Table split into Agricultural / Mining/Manufacturing / Services.
local sector = nil
local companies = {}
local seen = {}
 
local function push(name, sec)
name = stripWiki(name)
if name == "" then return end
if not seen[name] then
seen[name] = true
table.insert(companies, { name = name, sector = sec or "Unknown" })
end
end
end
 
return string.format("%d/%d/%d [[PSSC]]", dayOfMonth, month, psscYear)
for line in content:gmatch("[^\n]+") do
local l = trim(line)
 
-- sector headers (tolerant patterns)
if l:match("^=+%s*Agricultural%s*=+") then
sector = "Agricultural"
elseif l:match("^=+%s*Mining/Manufacturing%s*=+") or l:match("^=+%s*Mining%s*/%s*Manufacturing%s*=+") then
sector = "Mining/Manufacturing"
elseif l:match("^=+%s*Services%s*=+") then
sector = "Services"
end
 
-- Company cell style you use: | **Company Name**
local boldName = l:match("%|%s*%*%*([^%*]+)%*%*")
if boldName then
push(boldName, sector)
end
end
 
return companies
end
end


--------------------------------------------------------------------------------
local function normalizeSectorKey(sector)
-- 3) COST INDICES FROM PRICE MODULES (avg adjusted vs avg base)
sector = tostring(sector or "agriculture"):lower()
--------------------------------------------------------------------------------
if sector == "agriculture" or sector == "ag" then
local function getCostIndex(moduleName, mode)
return "agriculture"
local ok, m = pcall(require, moduleName)
elseif sector == "industry" or sector == "manufacturing" or sector == "manf" then
if not ok or not m or type(m.generateTable) ~= "function" then
return "industry"
return { ratio = 1.0, avgNew = nil, avgBase = nil }
elseif sector == "services" or sector == "serv" then
end
return "services"
 
-- call generateTable in summary mode (your modules accept frame tables)
local out = m.generateTable({ args = { mode = mode or "summary" } }) or ""
-- parse: "Average adjusted (X) vs base (Y)"
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
end
return { ratio = aNew / aBase, avgNew = aNew, avgBase = aBase }
return nil
end
end


--------------------------------------------------------------------------------
local function getSectorModule(sector)
-- 4) MARKET ACTIVITY (investor sentiment proxy)
local key = normalizeSectorKey(sector)
--------------------------------------------------------------------------------
if key == "agriculture" then
local function getMarketSentiment()
return require("Module:AutoUpdateAgPrices"), "Agriculture", key
local ok, m = pcall(require, "Module:BassaridMarketActivity")
elseif key == "industry" then
if not ok or not m or type(m.generateTable) ~= "function" then
return require("Module:AutoUpdateManfPrices"), "Mining / Manufacturing / Energy", key
return { avgPct = 0.0, bias = 0.0 }
elseif key == "services" then
return require("Module:AutoUpdateServPrices"), "Services", key
end
end
 
return nil, nil, nil
local out = m.generateTable({ args = {} }) or ""
-- Extract pct values like " -1.23%" or " 2.50%"
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
end


--------------------------------------------------------------------------------
local function getEmploymentSignal(city, cache)
-- 5) WEATHER / OPS IMPACT (default city Vaeringheim)
city = city or "Vaeringheim"
--------------------------------------------------------------------------------
if cache[city] then
local function getWeatherSignal(city, year, dayOfYear)
return cache[city]
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
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 sig
-- Base by alert level
if market.getEmploymentSignals then
local lvl = tonumber(wx.level or 0) or 0
sig = market.getEmploymentSignals(city)
local m = 1.0
else
if lvl == 1 then m = 0.98
sig = { marketScore = 0, volatility = 0 }
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 "")
 
-- Sector-sensitive penalties
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
end


return clamp(m, 0.65, 1.10)
cache[city] = sig
return sig
end
end


--------------------------------------------------------------------------------
local function computeWeights(companies)
-- 6) WAR LEAGUE TEMPO (table-derived)
local total = 0
--------------------------------------------------------------------------------
for _, co in ipairs(companies) do
local function getWarTempo(di)
local cityPop = CITY_POP[co.city] or 1000000
local ok, wl = pcall(require, "Module:WarLeagueDivisionOpsBVR")
local cityFactor = math.max(0.60, math.min(1.50, cityPop / 5000000))
if not ok or not wl or type(wl.makeTable) ~= "function" then
local weight = (co.count or 1) * math.max(0.01, co.avgBase or 0.01) * cityFactor
return { score = 0, redRate = 0 }
co.weight = weight
total = total + weight
end
end


local out = wl.makeTable({ args = { rows = 36, showlegend = "no", seed = (di.year * 1000 + di.dayOfYear) } }) or ""
if total <= 0 then
local rows = 0
local evenWeight = 1 / math.max(1, #companies)
local high, critical = 0, 0
for _, co in ipairs(companies) do
 
co.weight = evenWeight
-- Count urgency tokens
end
for urg in out:gmatch("||%s*([A-Z]+)%s*||%s*%d") do
-- not reliable; fall back below
end
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)
-- War tempo raises security/logistics employment, can mildly depress agriculture (labor diversion).
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
 
--------------------------------------------------------------------------------
-- 7) TEMPLE BANK / MISSIONARY ACTIVITY (table-derived)
--------------------------------------------------------------------------------
local function getTempleTempo(di)
local ok, tb = pcall(require, "Module:MissionaryDailyOpsBVR")
if not ok or not tb or type(tb.makeTable) ~= "function" then
return { redRate = 0 }
end
 
-- Keep it light: Core only, limited rows, no econ scan
local out = tb.makeTable({ args = { region = "Core", includeThreat = "no", showEcon = "no", limit = 40, showlegend = "no" } }) or ""
local red, n = 0, 0
 
-- Severity column is last; values like Green/Yellow/Red (and sometimes richer labels)
for sev in out:gmatch("||%s*([^|\n]+)%s*$") do
-- too broad; instead count explicit "Red" tokens in the table rows
end
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)
-- Temple activity tends to lift services/admin and stabilize labor participation.
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
 
--------------------------------------------------------------------------------
-- 8) OPTIONAL: HATCH MINISTRY OPS (if you add a module later)
--------------------------------------------------------------------------------
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
 
local function hatchMultiplier(hatch, sector)
if not hatch.present then return 1.0 end
local x = tonumber(hatch.intensity or 0) or 0
-- More ops -> more services + compliance work; mild drag on throughput-heavy sectors
if sector == "Services" then
return clamp(1.0 + (x * 0.002), 1.0, 1.12)
else
else
return clamp(1.0 - (x * 0.001), 0.90, 1.02)
for _, co in ipairs(companies) do
end
co.weight = co.weight / total
end
 
--------------------------------------------------------------------------------
-- 9) BUILD BASE EMPLOYMENT SHARES ACROSS ALL PORT COMPANIES
--------------------------------------------------------------------------------
local function buildBaseShares(allCompanies)
-- Sector shares (can be tuned later)
local sectorTarget = {
["Agricultural"] = 0.34,
["Mining/Manufacturing"] = 0.33,
["Services"] = 0.33,
["Unknown"] = 0.00
}
 
-- Collect by sector
local bySector = { Agricultural = {}, ["Mining/Manufacturing"] = {}, Services = {}, Unknown = {} }
for _, c in ipairs(allCompanies) do
local sec = c.sector or "Unknown"
if not bySector[sec] then sec = "Unknown" end
table.insert(bySector[sec], c)
end
 
-- Assign raw weights per company (stable)
local weights = {}
for sec, list in pairs(bySector) do
local sum = 0
for _, c in ipairs(list) do
local w = 0.6 + (hashFrac("w:" .. c.name) * 1.4)  -- 0.6..2.0
weights[c.name] = { raw = w, sector = sec }
sum = sum + w
end
-- normalize to sector target
local target = sectorTarget[sec] or 0
for _, c in ipairs(list) do
local raw = weights[c.name].raw
local share = (sum > 0) and (raw / sum) * target or 0
weights[c.name].share = share
end
end
end
end
return weights
end
end


--------------------------------------------------------------------------------
-- 10) MAIN TABLE
--------------------------------------------------------------------------------
function p.generateTable(frame)
function p.generateTable(frame)
local args = (frame and frame.args) or {}
frame = frame or {}
local di = getCurrentDateInfo()
local args = (frame.getParent and frame:getParent() and frame:getParent().args) or {}
local fargs = frame.args or {}


local city = tostring(args.city or "Vaeringheim")
local sectorArg = fargs.sector or args.sector or "agriculture"
local sectorFilter = trim(tostring(args.sector or "")) -- Agricultural | Mining/Manufacturing | Services
local population = tonumber(fargs.population or args.population) or 293833483.50
local limit = tonumber(args.limit or "")              -- optional row cap
local unemploymentRate = tonumber(fargs.unemployment or args.unemployment) or 0.04
local showDashboard = tostring(args.dashboard or "yes"):lower() ~= "no"


-- Seed (stable per day)
local sectorModule, sectorLabel, sectorKey = getSectorModule(sectorArg)
math.randomseed(di.year * 1000 + di.dayOfYear)
if not sectorModule then
 
return "Invalid sector. Use agriculture, industry, or services."
-- Pull all companies from the port page
end
local companies = parsePortCompanies()
if not sectorModule.getCompanyEmploymentInputs then
 
return "This sector module does not expose getCompanyEmploymentInputs() yet."
-- Fallback to legacy list if parsing fails
if #companies == 0 then
companies = {
{ name = "Gladeseed Farmers' Union", sector = "Agricultural" },
{ name = "Atterian Cattle Drivers", sector = "Agricultural" },
{ name = "Noctic Fleet", sector = "Agricultural" },
{ name = "Baratar Corporation", sector = "Mining/Manufacturing" },
{ name = "Hatch Ministry", sector = "Services" },
}
end
end


local shares = buildBaseShares(companies)
-- Optional per-sector overrides
local agShare  = tonumber(fargs.ag_share or args.ag_share) or SECTOR_EMPLOYMENT_SHARE.agriculture
local indShare  = tonumber(fargs.ind_share or args.ind_share) or SECTOR_EMPLOYMENT_SHARE.industry
local servShare = tonumber(fargs.serv_share or args.serv_share) or SECTOR_EMPLOYMENT_SHARE.services


-- Cost indices by sector from your three pricing modules
local sectorShareMap = {
local costAg  = getCostIndex("Module:AutoUpdateAgPrices", "summary")
agriculture = agShare,
local costManf = getCostIndex("Module:AutoUpdateManfPrices", "summary")
industry = indShare,
local costServ = getCostIndex("Module:AutoUpdateServPrices", "summary")
services = servShare
}


-- Market sentiment
local sectorShare = sectorShareMap[sectorKey] or 0.33
local market = getMarketSentiment()
sectorShare = clamp(sectorShare, 0, 1)


-- Weather / ops
local employedPopulation = math.floor(population * (1 - unemploymentRate))
local wx = getWeatherSignal(city, di.year, di.dayOfYear)
local sectorEmploymentPool = math.floor(employedPopulation * sectorShare)


-- War / Temple / Hatch
local dateString = getCurrentDate()
local war = getWarTempo(di)
local localTime = os.date("*t")
local temple = getTempleTempo(di)
local dailySeed = localTime.year * 1000 + localTime.yday
local hatch = getHatchTempo(di)


-- Macro unemployment baseline (tune here)
local companies = sectorModule.getCompanyEmploymentInputs()
-- Using national population referenced on the Port page; keep unemployment modest.
computeWeights(companies)
local population = 94160000
local unemploymentRate = 0.04


-- Small macro adjustment:
table.sort(companies, function(a, b) return a.name < b.name end)
-- • positive market bias reduces unemployment slightly
-- • severe weather increases it slightly
local u = unemploymentRate
u = u - clamp(market.bias * 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 signalCache = {}
 
local function sectorCostMultiplier(sec)
-- In your price modules, "Low" corresponds to higher adjusted price (better voucher yield).
-- So ratio > 1 => affordability/availability tailwind.
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)
-- Small demand signal; services most responsive.
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
 
-- Build one combined multiplier by sector
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
 
-- Dashboard (top)
local out = {}
local out = {}
if showDashboard then
out[#out + 1] = '{| class="wikitable sortable"\n'
table.insert(out, "{| class=\"wikitable\" style=\"width:100%;\"")
out[#out + 1] = '! Date !! Sector !! Company !! City !! Price Change !! Sector Share !! Previous Employees !! Current Employees !! Change\n'
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


-- Main table (sortable); can be huge, so keep it scrollable
local totalEmployed = 0
table.insert(out, '<div style="overflow-x:auto;">')
table.insert(out, "{| class=\"wikitable sortable\"")
table.insert(out, "! Date !! Sector !! Company !! Base Share % !! Previous Employees !! Current Employees !! Δ !! Drivers")


local count = 0
for _, co in ipairs(companies) do
for _, c in ipairs(companies) do
local baseEmployees = round(sectorEmploymentPool * co.weight)
local sec = c.sector or "Unknown"
if sectorFilter == "" or sec == sectorFilter then
local share = (shares[c.name] and shares[c.name].share) or 0


-- baseline
local sig = getEmploymentSignal(co.city, signalCache)
local prev = math.max(1, math.floor(employedPopulation * share))
local nextInt = lcg(dailySeed + hashString((co.name or "") .. "|" .. (co.city or "")))
local jitter = (randUnit(nextInt) - 0.5) * 0.04
local priceEffect = (tonumber(co.pctChange) or 0) * 0.18 / 100
local marketEffect = (sig.marketScore or 0) * 0.60
local volDrag = (sig.volatility or 0) * 0.02


-- daily company-level jitter (stable per company/day)
local netEffect = clamp(priceEffect + marketEffect + jitter - volDrag, -0.10, 0.10)
local jitter = (hashFrac(string.format("jit:%s:%d:%d", c.name, di.year, di.dayOfYear)) - 0.5) * 0.18 -- ±9%
local currEmployees = round(baseEmployees * (1 + netEffect))
local mult = combinedMultiplier(sec) * (1.0 + jitter)
if currEmployees < 1 then currEmployees = 1 end
local curr = math.max(1, math.floor(prev * mult))


local deltaSym = "•"
local changeText = "Same"
if curr > prev then deltaSym = "↑"
local rowStyle = ' style="background-color:#f3f3f3;"'
elseif curr < prev then deltaSym = "↓" end
if currEmployees > baseEmployees then
changeText = "Increased"
rowStyle = ' style="background-color:#d8f0d2;"'
elseif currEmployees < baseEmployees then
changeText = "Decreased"
rowStyle = ' style="background-color:#f8d7d7;"'
end


-- row color
totalEmployed = totalEmployed + currEmployees
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(
out[#out + 1] = string.format(
"cost×%.2f; wx×%.2f; war×%.2f; temple×%.2f; hatch×%.2f; mkt×%.2f",
'|-%s\n| %s || %s || %s || %s || %+0.2f%% || %.1f%% || %d || %d || %s\n',
sectorCostMultiplier(sec),
rowStyle,
weatherMultiplier(wx, sec),
dateString,
warMultiplier(war, sec),
sectorLabel,
templeMultiplier(temple, sec),
co.name,
hatchMultiplier(hatch, sec),
co.city or "",
marketMultiplier(sec)
co.pctChange or 0,
)
(co.weight * 100),
 
baseEmployees,
table.insert(out, string.format(
currEmployees,
"|-%s\n| %s || %s || %s || %.3f%% || %d || %d || %s || %s",
changeText
rowStyle,
)
di.dateString,
sec,
c.name,
share * 100,
prev,
curr,
deltaSym,
drivers
))
 
count = count + 1
if limit and count >= limit then break end
end
end
end


table.insert(out, "|}")
local totalUnemployed = math.max(0, math.floor(population - totalEmployed))
table.insert(out, "</div>")
out[#out + 1] = string.format('|-\n! colspan="7" | Sector Employment Pool || %d || \n', sectorEmploymentPool)
out[#out + 1] = string.format('|-\n! colspan="7" | Total Employed (this sector) || %d || \n', totalEmployed)
out[#out + 1] = string.format('|-\n! colspan="7" | Total Unemployed (whole population reference) || %d || \n', totalUnemployed)
out[#out + 1] = '|}'


return table.concat(out, "\n")
return table.concat(out)
end
end


return p
return p

Latest revision as of 18:33, 20 March 2026

Documentation for this module may be created at Module:BassaridEmployment/doc

local p = {}

local market = require("Module:BassaridMarketActivity")

local CITY_POP = {
	["Vaeringheim"] = 20887650.86,
	["Lunalis Sancta"] = 7832869.07,
	["Luminaria"] = 6382335.99,
	["Serena"] = 6672442.61,
	["Symphonara"] = 4351592.87,
	["Aurelia"] = 3771379.63,
	["Sylvapolis"] = 3481276.21,
	["Delphica"] = 2030743.12,
	["Catonis Atrium"] = 1682617.10,
	["Ferrum Citadel"] = 928339.26,
	["Pyralis"] = 12965917.88,
	["Nexa"] = 7979025.10,
	["Saluria"] = 7729680.74,
	["Acheron"] = 4238856.91,
	["Koinonía"] = 5485581.50,
	["Aureum"] = 4488201.27,
	["Aetherium"] = 3740168.19,
	["Erythros"] = 3241479.47,
	["Somniumpolis"] = 16035032.55,
	["Hafaan"] = 3568579.65,
	["Jeseri"] = 2430778.52,
	["Skýrophos"] = 5132630.96,
	["Bjornopolis"] = 4016840.25,
	["Aegerheim"] = 3347368.98,
	["Norsolyra"] = 2901052.70,
	["Thorsalon"] = 2454736.41,
	["Myrene"] = 1338945.70,
	["Ephyra"] = 1115790.71,
	["Thyrea"] = 892632.57,
	["Pelagia"] = 669474.43,
	["Halicarn"] = 446316.28,
	["Keybir-Aviv"] = 4592562.31,
	["Tel-Amin"] = 4155174.90,
	["Jogi"] = 3936483.03,
	["Lewisburg"] = 3280401.91,
	["Diamandis"] = 2843014.50,
	["Thermosalem"] = 1312160.40,
	["Akróstadium"] = 1093466.69,
	["Lykopolis"] = 437387.41,
	["Sufriya"] = 218693.71,
	["Riddersborg"] = 11757190.77,
	["Ardclach"] = 5426395.09,
	["Ourid"] = 31826487.08,
	["Bashkim"] = 23046766.50
}

-- Default sector shares of the employed population.
-- These should sum to 1.00.
local SECTOR_EMPLOYMENT_SHARE = {
	agriculture = 0.27,
	industry = 0.31,
	services = 0.42
}

local MOD = 2147483647
local A   = 1103515245
local C   = 12345

local function hashString(s)
	s = tostring(s or "")
	local h = 0
	for i = 1, #s do
		h = (h * 31 + s:byte(i)) % MOD
	end
	return h
end

local function lcg(seed)
	seed = seed % MOD
	return function()
		seed = (A * seed + C) % MOD
		return seed
	end
end

local function randUnit(nextInt)
	return (nextInt() % 100000) / 100000
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 round(num)
	return math.floor(num + 0.5)
end

local function getCurrentDate()
	local startDate = os.time({ year = 1999, month = 8, day = 6 })
	local secondsInDay = 86400
	local daysPerYear = 183
	local currentDate = os.time()
	local totalDaysElapsed = math.floor((currentDate - startDate) / secondsInDay)
	local yearFraction = totalDaysElapsed / daysPerYear
	local psscYear = math.floor(yearFraction)
	local dayOfYear = math.floor((yearFraction - psscYear) * daysPerYear) + 1
	local month, dayOfMonth
	if dayOfYear <= 61 then
		month = 1; dayOfMonth = dayOfYear
	elseif dayOfYear <= 122 then
		month = 2; dayOfMonth = dayOfYear - 61
	else
		month = 3; dayOfMonth = dayOfYear - 122
	end
	return string.format("%d/%d/%d [[PSSC]]", dayOfMonth, month, psscYear)
end

local function normalizeSectorKey(sector)
	sector = tostring(sector or "agriculture"):lower()
	if sector == "agriculture" or sector == "ag" then
		return "agriculture"
	elseif sector == "industry" or sector == "manufacturing" or sector == "manf" then
		return "industry"
	elseif sector == "services" or sector == "serv" then
		return "services"
	end
	return nil
end

local function getSectorModule(sector)
	local key = normalizeSectorKey(sector)
	if key == "agriculture" then
		return require("Module:AutoUpdateAgPrices"), "Agriculture", key
	elseif key == "industry" then
		return require("Module:AutoUpdateManfPrices"), "Mining / Manufacturing / Energy", key
	elseif key == "services" then
		return require("Module:AutoUpdateServPrices"), "Services", key
	end
	return nil, nil, nil
end

local function getEmploymentSignal(city, cache)
	city = city or "Vaeringheim"
	if cache[city] then
		return cache[city]
	end

	local sig
	if market.getEmploymentSignals then
		sig = market.getEmploymentSignals(city)
	else
		sig = { marketScore = 0, volatility = 0 }
	end

	cache[city] = sig
	return sig
end

local function computeWeights(companies)
	local total = 0
	for _, co in ipairs(companies) do
		local cityPop = CITY_POP[co.city] or 1000000
		local cityFactor = math.max(0.60, math.min(1.50, cityPop / 5000000))
		local weight = (co.count or 1) * math.max(0.01, co.avgBase or 0.01) * cityFactor
		co.weight = weight
		total = total + weight
	end

	if total <= 0 then
		local evenWeight = 1 / math.max(1, #companies)
		for _, co in ipairs(companies) do
			co.weight = evenWeight
		end
	else
		for _, co in ipairs(companies) do
			co.weight = co.weight / total
		end
	end
end

function p.generateTable(frame)
	frame = frame or {}
	local args = (frame.getParent and frame:getParent() and frame:getParent().args) or {}
	local fargs = frame.args or {}

	local sectorArg = fargs.sector or args.sector or "agriculture"
	local population = tonumber(fargs.population or args.population) or 293833483.50
	local unemploymentRate = tonumber(fargs.unemployment or args.unemployment) or 0.04

	local sectorModule, sectorLabel, sectorKey = getSectorModule(sectorArg)
	if not sectorModule then
		return "Invalid sector. Use agriculture, industry, or services."
	end
	if not sectorModule.getCompanyEmploymentInputs then
		return "This sector module does not expose getCompanyEmploymentInputs() yet."
	end

	-- Optional per-sector overrides
	local agShare   = tonumber(fargs.ag_share or args.ag_share) or SECTOR_EMPLOYMENT_SHARE.agriculture
	local indShare  = tonumber(fargs.ind_share or args.ind_share) or SECTOR_EMPLOYMENT_SHARE.industry
	local servShare = tonumber(fargs.serv_share or args.serv_share) or SECTOR_EMPLOYMENT_SHARE.services

	local sectorShareMap = {
		agriculture = agShare,
		industry = indShare,
		services = servShare
	}

	local sectorShare = sectorShareMap[sectorKey] or 0.33
	sectorShare = clamp(sectorShare, 0, 1)

	local employedPopulation = math.floor(population * (1 - unemploymentRate))
	local sectorEmploymentPool = math.floor(employedPopulation * sectorShare)

	local dateString = getCurrentDate()
	local localTime = os.date("*t")
	local dailySeed = localTime.year * 1000 + localTime.yday

	local companies = sectorModule.getCompanyEmploymentInputs()
	computeWeights(companies)

	table.sort(companies, function(a, b) return a.name < b.name end)

	local signalCache = {}
	local out = {}
	out[#out + 1] = '{| class="wikitable sortable"\n'
	out[#out + 1] = '! Date !! Sector !! Company !! City !! Price Change !! Sector Share !! Previous Employees !! Current Employees !! Change\n'

	local totalEmployed = 0

	for _, co in ipairs(companies) do
		local baseEmployees = round(sectorEmploymentPool * co.weight)

		local sig = getEmploymentSignal(co.city, signalCache)
		local nextInt = lcg(dailySeed + hashString((co.name or "") .. "|" .. (co.city or "")))
		local jitter = (randUnit(nextInt) - 0.5) * 0.04
		local priceEffect = (tonumber(co.pctChange) or 0) * 0.18 / 100
		local marketEffect = (sig.marketScore or 0) * 0.60
		local volDrag = (sig.volatility or 0) * 0.02

		local netEffect = clamp(priceEffect + marketEffect + jitter - volDrag, -0.10, 0.10)
		local currEmployees = round(baseEmployees * (1 + netEffect))
		if currEmployees < 1 then currEmployees = 1 end

		local changeText = "Same"
		local rowStyle = ' style="background-color:#f3f3f3;"'
		if currEmployees > baseEmployees then
			changeText = "Increased"
			rowStyle = ' style="background-color:#d8f0d2;"'
		elseif currEmployees < baseEmployees then
			changeText = "Decreased"
			rowStyle = ' style="background-color:#f8d7d7;"'
		end

		totalEmployed = totalEmployed + currEmployees

		out[#out + 1] = string.format(
			'|-%s\n| %s || %s || %s || %s || %+0.2f%% || %.1f%% || %d || %d || %s\n',
			rowStyle,
			dateString,
			sectorLabel,
			co.name,
			co.city or "",
			co.pctChange or 0,
			(co.weight * 100),
			baseEmployees,
			currEmployees,
			changeText
		)
	end

	local totalUnemployed = math.max(0, math.floor(population - totalEmployed))
	out[#out + 1] = string.format('|-\n! colspan="7" | Sector Employment Pool || %d || \n', sectorEmploymentPool)
	out[#out + 1] = string.format('|-\n! colspan="7" | Total Employed (this sector) || %d || \n', totalEmployed)
	out[#out + 1] = string.format('|-\n! colspan="7" | Total Unemployed (whole population reference) || %d || \n', totalUnemployed)
	out[#out + 1] = '|}'

	return table.concat(out)
end

return p