Module:Convert

From Random Island Wiki
Revision as of 20:03, 5 September 2012 by >Johnuniq (default rounding done (not checked!); tweaks)
Jump to navigation Jump to search

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

--[[
TODO Too many items to list, but following are some points:
- Output needs   rather than space in several places.
- Some conversions require two outputs: {{convert|55|nmi|km mi}}.
- Some units have two values: {{convert|3.21|m|ftin}}.
]]--

--[[-----BEGIN DATA TABLE-----
Plan to write a program to generate the conversion tables below.
The input would be a text file in human-friendly format, and
the output would be the following tables.
When a lot of data is added, it might be useful to put this in another module.
Values from http://en.wikipedia.org/wiki/Conversion_of_units
Check with  http://en.wikipedia.org/wiki/Template:Convert/list_of_units
]]--

local units = {
    -- Each value is {converter_table, default_out_unit}.
    lookup = function (self, unit)
        -- If unit is known, return its converter_table, default_out_unit.
        local t = self[unit]
        if t == nil then
            local msg = 'Unit %s not known[[Category:Convert unknown unit]]'
            error(msg:format(unit))
        end
        return t
    end,
    utype = 1,
    scale = 2,
    offset = 3,
    defaultunit = 4,
    ['kg'] =  {'mass',        1,          0,      'lb'},
    ['lb'] =  {'mass',        0.45359237, 0,      'kg'},
    ['m'] =   {'length',      1,          0,      'ft'},
    ['km'] =  {'length',      1000,       0,      'mi'},
    ['mi'] =  {'length',      1609.344,   0,      'km'},
    ['ft'] =  {'length',      0.3048,     0,      'm'},
    ['K'] =   {'temperature', 1,          273.15, 'C'},
    ['C'] =   {'temperature', 1,          0,      'F'},
    ['F'] =   {'temperature', 1.8,        32,     'C'},
    ['°K'] =  {'temperature', 1,          273.15, '°C'},
    ['°C'] =  {'temperature', 1,          0,      '°F'},
    ['°F'] =  {'temperature', 1.8,        32,     '°C'},
}
-------END DATA TABLE-----

local function scaled(value, in_unit, out_unit)
    -- Return scaled value for a simple convert.
    return (value - in_unit[units.offset]) / in_unit[units.scale] * out_unit[units.scale] + out_unit[units.offset]
end

local function require_number(value, missing, invalid)
    -- If value is missing or not a number, throw an error.
    -- Return value as a number if valid.
    if value == nil then error(missing) end
    local number = tonumber(value)
    if number == nil then error(invalid:format(value)) end
    return number
end

local function require_integer(value, missing, invalid)
    -- If value is missing or not an integer, throw an error.
    -- Return value as a number if valid.
    local number = require_number(value, missing, invalid)
    if number ~= math.floor(number) then
        error(invalid:format(value))
    end
    return number
end

local function get_parms(pframe)
    -- Return table with all arguments passed by template converted to
    -- named arguments. The numeric args are used to add named args:
    --   in_text, in_text2 (strings given for value, value2)
    --   value, in_unit, out_unit, value2, range, round_to
    -- (except for range, which is nil or a table, the named args that are
    -- added here could be provided by the user of the template).
    local range_types = {  -- text to separate input, output ranges
        ['and'] = {' and ', ' and '},
        ['by'] = {' by ', ' by '},
        ['to'] = {' to ', ' to '},
        ['-'] = {'–', '–'},
        ['to(-)'] = {' to ', '–'},
        ['x'] = {' by ', ' × '},
        ['+/-'] = {' ± ', ' ± '},
    }
    local args = {}                         -- arguments passed to template
    for k,v in pframe:argumentPairs() do
        args[k] = v
    end
    args.in_text = args[1]
    args.value = require_number(args.in_text, 'Need value', 'Value "%s" must be a number')
    local in_unit = args[2]
    local i = 3
    local range = range_types[in_unit]
    if range ~= nil then
        args.in_text2 = args[3]
        args.value2 = require_number(args.in_text2, 'Need second value', 'Second value "%s" must be a number')
        in_unit = args[4]
        i = 5
    end
    local out_unit = args[i]
    local round_to = args[i+1]
    if in_unit == nil then error('Need input unit') end
    args.in_unit = in_unit
    args.out_unit = out_unit
    args.range = range
    args.round_to = round_to
    return args
end

local function default_roundto(intext, factor)
    -- Return a default value for round_to (an integer like 2, 0, -2).
    -- prec = (precision implied in intext)
    --      = (#digits after dot, or negative of #zeroes before dot)
    -- If conversion is multiplication by a factor, and
    -- if factor >= 0.02, compensate prec by adding N where:
    --     N    factor is in range
    --     1     0.02 :     2  =   .1/5 :   .1*2
    --     0     0.2  :    20  =   1/5  :   1*2
    --    -1     2    :   200  =  10/5  :  10*2
    --    -2    20    :  2000  = 100/5  : 100*2  etc.
    -- Which is achieved with calculation below (log10(5) = 0.69897).
    -- TODO Exception required for temperature.
    prec = 0
    dot = intext:find('.', 1, true)
    if dot ~= nil then
        prec = intext:sub(dot+1):len()
        if prec == 0 then
            intext = intext:sub(1, -2)
        end
    end
    if prec == 0 then
        prec = -intext:match('0*$'):len()
    end
    if factor ~= nil and factor >= 0.02 then
        prec = prec - math.floor(factor + 0.69897)
    end
    return prec
end

local function cvtround(invalue, intext, parms)
    -- Convert given invalue using parms (return '' if invalue == nil).
    -- Return rounded, formatted string for result, using rounding
    -- specified in parms.
    -- This code combines convert/round because some rounding requires
    -- knowledge of what we are converting.
    -- TODO Lots of checking required. Will need tweaks for special cases
    -- handled by old Template:Convert.
    local text = ''
    if invalue == nil then return text end
    local outvalue = scaled(invalue, parms.in_unit_table, parms.out_unit_table)
    local round_to = parms.round_to
    local sigfig = parms.sigfig
    local disp = parms.disp
    local auto = false
    if round_to then
        -- Ignore sigfig, disp.
        round_to = require_integer(round_to, 'Need value', 'round_to "%s" must be an integer')
    elseif sigfig then
        -- Ignore disp.
        sigfig = require_integer(sigfig, 'Need value', 'sigfig "%s" must be an integer')
        if sigfig <= 0 then
            msg = 'sigfig "%s" must be positive'
            error(msg:format(parms.sigfig))
        end
        local fmt = '%.' .. string.format('%.0f', sigfig) .. 'g'
        text = string.format(fmt, outvalue)
    elseif disp == '5' then
        local negative = false
        if outvalue < 0 then
            negative = true
            outvalue = -outvalue
        end
        outvalue = math.floor((outvalue / 5) + 0.5) * 5
        if negative then
            outvalue = -outvalue
        end
        text = string.format('%.0f', outvalue)
    else
        auto = true  -- using default rounding
        -- TODO If conversion is not multiplication by a number, need factor = nil.
        local factor = outvalue / invalue
        round_to = default_roundto(intext, factor)
    end
    if round_to then
        if auto then
            -- TODO: No less than two significant figures.
        end
        if round_to >= 0 then
            local fmt = '%.' .. string.format('%.0f', round_to) .. 'f'
            text = string.format(fmt, outvalue)
        else
            local factor = 10^(-round_to)
            local zeroes = string.sub(tostring(factor), 2)
            text = string.format('%.0f', outvalue/factor) .. zeroes
        end
    end
    return text
end

local disp_single = {
    ['or'] = '%s %s or %s %s',
    ['sqbr'] = '%s %s [%s %s]',
    ['comma'] = '%s %s, %s %s',
    ['b'] = '%s %s (%s %s)',
}

local disp_double = {
    ['or'] = '%s%s%s %s or %s%s%s %s',
    ['sqbr'] = '%s%s%s %s [%s%s%s %s]',
    ['comma'] = '%s%s%s %s, %s%s%s %s',
    ['b'] = '%s%s%s %s (%s%s%s %s)',
}

local function process(parms)
    -- If we can convert from given in to out unit, return the table values for the two given unit types.
    parms.in_unit_table = units:lookup(parms.in_unit)
    if parms.out_unit == nil then           -- need to catch empty string also?
        parms.out_unit = parms.in_unit_table[units.defaultunit]
    end
    parms.out_unit_table = units:lookup(parms.out_unit)
    if parms.in_unit_table[units.utype] ~= parms.out_unit_table[units.utype] then
        local msg = 'Cannot convert %s to %s'
        error(msg:format(parms.in_unit_table[units.utype], parms.out_unit_table[units.utype]))
    end
    local intext = parms.in_text
    local intext2 = parms.in_text2
    local outext = cvtround(parms.value, intext, parms)
    local outext2 = cvtround(parms.value2, intext2, parms)
    local range = parms.range
    local disp = parms.disp
    local wikitext
    if range == nil then
        wikitext = disp_single[disp] or disp_single['b']
        wikitext = wikitext:format(intext, parms.in_unit, outext, parms.out_unit)
    else
        wikitext = disp_double[disp] or disp_double['b']
        wikitext = wikitext:format(intext, range[1], intext2, parms.in_unit, outext, range[2], outext2, parms.out_unit)
    end
    return wikitext
end

-- Used by template {{convert2}}.
-- We will have to keep old {{convert}} for a long time, and run
-- {{convert2}} in parallel with {{convert}} while testing/developing.
local p = {}
local bodge = require "Module:mw" -- This fixes up mw.text.tag for us.

function p.convert(frame)
    local pframe = frame:getParent()
    local parms = get_parms(pframe)
    local state,text = pcall(process, parms)
    if not state then
        local params = {style="color:black; background-color:orange;"}
        text=mw.text.tag({name="span", contents="[[Module talk:Convert|Conversion error]]: " .. text, params=params})
    end
    return text
end

return p