local mWikidata = require('Modulo:Wikidata')
local mChart = require('Modulo:Graph/sandbox')
local p = {}
end
local function max_pop(data)
-- =============================================================
-- Funzioni copiate da Modulo:Wikidata
-- =============================================================
-- Messaggi di errore
local i18n = {
["errors"] = {
["entityid-param-not-provided"] = "Parametro ''entityid'' non fornito",
["property-param-not-provided"] = "Parametro ''property'' non fornito",
["qualifier-param-not-provided"] = "Parametro ''qualifier'' non fornito",
["value-param-not-provided"] = "Parametro ''valore'' da ricercare non fornito",
["entity-not-found"] = "Entità non trovata",
["unknown-claim-type"] = "Tipo asserzione sconosciuta",
["unknown-snak-type"] = "Tipo di snak sconosciuto",
["unknown-datavalue-type"] = "Tipo di dato sconosciuto",
["unknown-entity-type"] = "Tipo di entità sconosciuta"
},
["somevalue"] = "''valore sconosciuto''",
["novalue"] = "''nessun valore''"
}
-------------------------------------------------------------------------------
-- Formatters
-------------------------------------------------------------------------------
local function errhandler(msg)
local cat = mw.title.getCurrentTitle().namespace == 0 and errorCategory or ''
return string.format('<span class="error">%s</span>%s', msg, cat)
end
local function formatExtLink(url)
local protocols = { ftp = true, http = true, https = true }
local success, uri = pcall(function() return mw.uri.new(url) end)
if success and uri.protocol and protocols[uri.protocol] then
local dest = tostring(uri)
return string.format('[%s %s]', dest, dest:gsub(uri.protocol .. '://', ''))
else
return url
end
end
local function formatEntityId(entityId)
local label = mw.wikibase.label(entityId)
local link = mw.wikibase.sitelink(entityId)
if link then
if label then
return '[[' .. link .. '|' .. label .. ']]'
else
return '[[' .. link .. ']]'
end
else
return label or ''
end
end
local function formatTime(value, args)
local year, month, day
local ret = ''
year, month, day = value.time:match('(%d+)%-(%d%d)%-(%d%d).+')
if value.precision == 9 then
ret = tonumber(year)
elseif value.precision == 10 then
ret = mw.getLanguage('it'):formatDate('F Y', tonumber(year) .. '-' .. month)
elseif value.precision == 11 then
ret = mw.getLanguage('it'):formatDate('j F Y', tonumber(year) .. '-' .. month .. '-' .. day)
ret = ret:gsub('^1%s', '1º ')
end
if value.precision >= 9 and value.precision <= 11 then
ret = ret .. (value.time:sub(1, 1) == '-' and ' a.C.' or '')
end
return ret
end
local function formatGlobecoordinate(value, args)
local ret
if args.formatting == 'latitude' then
ret = value.latitude
elseif args.formatting == 'longitude' then
ret = value.longitude
else
ret = value.latitude .. ', ' .. value.longitude
end
return ret
end
local function formatFromPattern(str, args)
local pattern = args.pattern
pattern = mw.ustring.gsub(pattern, '\\{', '{')
pattern = mw.ustring.gsub(pattern, '\\}', '}')
return mw.getCurrentFrame():preprocess(mw.message.newRawMessage(pattern, str):plain())
end
local function getEntityIdFromValue(value)
local prefix = ''
if value['entity-type'] == 'item' then
prefix = 'Q'
elseif value['entity-type'] == 'property' then
prefix = 'P'
else
error(i18n.errors['unknown-entity-type'])
end
return prefix .. value['numeric-id']
end
local function formatDatavalue(datavalue, args)
local ret
--Default formatters
if datavalue.type == 'wikibase-entityid' then
if args.formatting == 'raw' then
ret = getEntityIdFromValue(datavalue.value)
else
ret = formatEntityId(getEntityIdFromValue(datavalue.value))
end
elseif datavalue.type == 'string' then
ret = datavalue.value
if args.formatting == 'extlink' then
ret = formatExtLink(ret)
end
elseif datavalue.type == 'monolingualtext' then
ret = datavalue.value.text
elseif datavalue.type == 'time' then
if args.formatting == 'raw' then
ret = datavalue.value.time
else
ret = formatTime(datavalue.value, args)
end
elseif datavalue.type == 'globecoordinate' then
ret = formatGlobecoordinate(datavalue.value, args)
elseif datavalue.type == 'quantity' then
ret = tonumber(datavalue.value.amount)
else
error(i18n.errors['unknown-datavalue-type'])
end
return ret
end
local function formatSnak(snak, args)
if snak.snaktype == 'somevalue' then
return i18n['somevalue']
elseif snak.snaktype == 'novalue' then
return i18n['novalue']
elseif snak.snaktype == 'value' then
return formatDatavalue(snak.datavalue, args)
else
error(i18n.errors['unknown-snak-type'])
end
end
-- =============================================================
-- Fine Funzioni copiate da Modulo:Wikidata
-- =============================================================
local function max_array(array)
local max = 0
for _,pd in ipairs(arraydata) do
if pd.population > max then max = pd.population end
end
return max
-- Eventuali valori non numerici sono ignorati
local function read_array(args)
local yearsraw_data = {}
if args.anni and args.popolazione then
local populations = {}
if local years = mw.text.split(args.anni, then",")
local listpopulations = mw.text.split(string.gsub(args.annipopolazione, "%s", ""), ",")
forif _,s#years in== ipairs(list)#populations dothen
years[#years+1]for i = tonumber(s)1, or#years 0do
raw_data[i] = {year=string.gsub(years[i], "%s", "") , population = tonumber(populations[i]) or 0 }
end
if args.popolazione then
local list = mw.text.split(string.gsub(args.popolazione, "%s", ""), ",")
for _,s in ipairs(list) do
populations[#populations+1] = tonumber(s) or 0
end
end
end
else -- vecchio metodo di inserimento
if #raw_data == 0 then -- vecchio metodo di inserimento
for i=1,20 do
local index = tonumber(i)
local year = tonumber(args['a' .. index])
if year then
yearsraw_data[#yearsraw_data+1] = { year = year, population = tonumber(args['p' .. index]) or 0 }
populations[#populations+1] = tonumber(args['p' .. index]) or 0
end
end
end
return years, populationsraw_data
end
local function comp_year(a1d1, a2d2)
return a1[1]d1.year < a2[1]d2.year
end
local function get_wikidata(from)
local P585claims = 'P585'
local P1082 = 'P1082'
local entity = mw.wikibase.getEntityObject(from)
local claims
if entity.claims and entity.claims.P1082 and #entity.claims.P1082 > 0 then
claims = entity.claims.P1082
else
return nil
end
--if true then return mw.text.jsonEncode(claims[1],mw.text.JSON_PRETTY) end
local raw_data = {}
for _,claim in ipairs(claims) do
claims = if claimmWikidata.qualifiers_getClaims('P1082', and{ claim.qualifiers.P585 and (claim.rankfrom == 'preferred'from, or claim.rank == 'normal' }) thenor {}
for _, claim in ipairs(claims) do
--if true then return claim end
raw_data[#raw_data + 1] = { formatSnak(claim.qualifiers.P585[1] , {}), formatSnak(claim.mainsnak, {}) }
population = tonumber(mWikidata._formatStatement(claim)) or 0,
end
year = mWikidata._formatQualifiers(claim, 'P585')
}
end
table.sort(raw_data, comp_year)
local years = {}
return raw_data
local populations = {}
for i,data in ipairs(raw_data) do
years[i], populations[i] = data[1], data[2]
end
return years, populations
end
local function default_table(popmax, n)
end
local function p._demografiadraw_graph(raw_data, args, default)
local years,populations = read_array(args){}
local from_wikidatayears = false{}
iffor #yearsi,d ==in 0ipairs(raw_data) thendo
years[i], populations[i] = get_wikidata(argsd.year, d.from)population
from_wikidata = true
end
local graph = {
--if true then return mw.text.jsonEncode(years) end
graphwidth = tonumber(args.dimx) or default.dimx,
if #years == 0 then return '' end
graphheight = tonumber(args.dimy) or 280,
local popmax = max_array(populations)
local is_thousand ygrid = falsetrue,
ymax = args.popmax or tostring(default.popmax),
if from_wikidata and popmax >= 900000 then
popmaxxtitle = popmax / 1000'anni',
ytitle = 'popolazione',
for index,population in ipairs(populations) do
y = { populations[index] = population / 1000},
x = is_thousand = trueyears,
endgraph_type = 'rect',
seriesTitles = {'Popolazione'},
end
colors = {'#4682B4'},
-- calcolo default per la popolazione
showValue = true
local default = default_table(popmax, #populations)
}
-- generazione del grafico
local graph_json = mChart.chart_json(graph)
if args.raw then return graph_json end
return mw.getCurrentFrame():extensionTag('graph', graph_json)
end
local function draw_timeline(raw_data, args, default)
local graph = {}
dump(graph, 'Colors=\n id:lightgrey value:gray(0.9)\n id:darkgrey value:gray(0.7)\n id:sfondo value:rgb(1,1,1)\n id:barra value:rgb(0.6,0.7,0.8)\n\n')
dump(graph, 'ImageSize = width:', args.dimx or tostring(default.dimx), ' height:', args.dmydimy or '373', '\n')
dump(graph, 'PlotArea = left:50 bottom:50 top:30 right:30\nDateFormat = x.y\n')
dump(graph, 'Period = from:0 till:', args.popmax or tostring(default.popmax), '\n')
dump(graph, 'BackgroundColors = canvas:sfondo\n')
dump(graph, 'BarData=\n')
for _,yeardata in ipairs(yearsraw_data) do
dump(graph, string.format(' bar: %ds text:%ds\n', data.year, data.year))
end
dump(graph, '\n')
dump(graph, 'PlotData=\n color:barra width:20 align:left\n\n')
for i =1_,#yearsdata in ipairs(raw_data) do
dump(graph, string.format(' bar:%ds from:0 till:%d\n', years[i]data.year, populations[i]data.population))
end
dump(graph, '\n')
local lang = mw.language.new('it')
dump(graph, 'PlotData=\n')
for i=1_,#yearsdata in ipairs(raw_data) do
local p_formatted = lang:formatNum(math.floor(tonumber(populations[i])data.population + 0,5) )
dump(graph, string.format(' bar: %ds at: %d fontsize:S text: %s shift:(-10,5)|n.d. shift:(-8,5)\n',
years[i]data.year, populations[i]data.population, p_formatted))
end
dump(graph, '\n')
draw_graph = mw.getCurrentFrame():extensionTag('timeline', table.concat(graph))
end
return draw_graph
local titolo = "''Abitanti censiti''\n"
end
function p._demografia(args)
local graph
local raw_data = read_array(args)
local from_wikidata = false
if #raw_data == 0 then
raw_data = get_wikidata(args.from)
from_wikidata = true
-- if true then return mw.text.jsonEncode(raw_data, mw.text.JSON_PRETTY) end
end
if #raw_data == 0 then return '' end
local popmax = max_pop(raw_data)
local is_thousand = false
if from_wikidata and popmax >= 900000 then
popmax = popmax / 1000
for i,data in ipairs(raw_data) do
raw_data[i].population = raw_data[i].population / 1000
is_thousand = true
end
end
-- calcolo default per la popolazione
local default = default_table(popmax, #raw_data)
-- generazione del grafico
local titolo = "''Abitanti censiti''<br />"
if is_thousand then
titolo = "''Abitanti censiti (migliaia)''\n<br />"
end
if args.titolo then
titolo = "''" .. args.titolo .. "''\n<br />"
end
if args.graph then
graph = draw_graph(raw_data, args, default)
else
graph = draw_timeline(raw_data, args, default)
end
return titolo .. draw_graphgraph
end
|