Module:Chord edo approximation: Difference between revisions

From Xenharmonic Wiki
Jump to navigation Jump to search
Pailiaq (talk | contribs)
m Undo revision 230969 by Pailiaq (talk)
Tag: Undo
Pailiaq (talk | contribs)
mNo edit summary
Tag: Manual revert
Line 1: Line 1:
-- Chord EDO Approximations Module
-- EDO Approximations Module
-- Calculates EDO approximations for JI chords like 4:5:6 or 4:5:6:7
-- Calculates EDO approximations for just intervals
-- Usage: {{#invoke:Chord_EDO_Approximation|main|chord=4:5:6|max_total_error=20|min_edo=5|max_edo=60}}
-- Usage: {{#invoke:EDO_Approximations|main|interval=3/2|tolerance=9|min_edo=5|max_edo=60}}
local u = require("Module:Utils")
local u = require("Module:Utils")
local yesno = require("Module:Yesno")
local yesno = require("Module:Yesno")
Line 7: Line 7:


-- ===== CONFIGURATION VARIABLES =====
-- ===== CONFIGURATION VARIABLES =====
local DEFAULT_MAX_TOTAL_ERROR = 25  -- Max summed RELATIVE error in cents
local DEFAULT_TOLERANCE = 9.0  -- Relative error tolerance in percent
local DEFAULT_MIN_EDO = 5
local DEFAULT_MIN_EDO = 5     -- Minimum EDO to check
local DEFAULT_MAX_EDO = 60
local DEFAULT_MAX_EDO = 60     -- Maximum EDO to check
-- ====================================
-- ====================================


-- Convert a frequency ratio to cents
local function cents(ratio)
local function cents(ratio)
     return 1200 * u.log2(ratio)
     return 1200 * u.log2(ratio)
end
end


-- Python-compatible round (banker's rounding) — matches your existing module
-- Python-compatible rounding function (banker's rounding)
local function round(x)
local function round(x)
     local floor_x = math.floor(x)
     local floor_x = math.floor(x)
     local frac = x - floor_x
     local frac = x - floor_x
     if frac < 0.5 then
     if frac < 0.5 then
         return floor_x
         return floor_x
Line 25: Line 27:
         return floor_x + 1
         return floor_x + 1
     else
     else
         if floor_x % 2 == 0 then return floor_x else return floor_x + 1 end
         if floor_x % 2 == 0 then
            return floor_x
        else
            return floor_x + 1
        end
     end
     end
end
end


local function gcd(a, b)
-- Find the best approximation of an interval in a given EDO
     while b ~= 0 do a, b = b, a % b end
local function find_best_approximation(ratio_cents, edo)
     return a
    local edostep = 1200 / edo
    local best_step = round(ratio_cents / edostep)
     local approximation_cents = best_step * edostep
    local absolute_error = approximation_cents - ratio_cents
    local relative_error = (absolute_error / edostep) * 100
 
     return best_step, absolute_error, relative_error
end
end


-- Parse "4:5:6" or "4:5:6:7" into a list of positive integers
-- Calculate all EDO approximations within tolerance for a given ratio
local function parse_chord(chord_str)
local function calculate_edo_approximations(ratio, tolerance, min_edo, max_edo)
     local notes = {}
     local ratio_cents = cents(ratio)
    for n in string.gmatch(chord_str, "([^:%s]+)") do
    local results = {}
        local num = tonumber(n)
        if not num or num <= 0 then return nil end
        table.insert(notes, num)
    end
    if #notes < 2 then return nil end
    return notes
end


-- For a given EDO and a list of interval-cents (from root), compute the chord approximation
    for edo = min_edo, max_edo do
local function calculate_chord_approximation(interval_cents_list, edo)
        local steps, abs_error, rel_error = find_best_approximation(ratio_cents, edo)
    local edostep = 1200 / edo
    local steps = {}
    local abs_errors = {}
    local rel_errors = {}
    local total_abs = 0
    local total_rel = 0


    for _, ic in ipairs(interval_cents_list) do
         if math.abs(rel_error) <= tolerance then
         local step = round(ic / edostep)
            table.insert(results, {
        local approx = step * edostep
                edo = edo,
        local abs_err = approx - ic
                steps = steps,
        local rel_err = (abs_err / edostep) * 100
                abs_error = abs_error,
        table.insert(steps, step)
                rel_error = rel_error
        table.insert(abs_errors, abs_err)
            })
        table.insert(rel_errors, rel_err)
         end
        total_abs = total_abs + math.abs(abs_err)
         total_rel = total_rel + math.abs(rel_err)
     end
     end


     return {
     return results
        steps = steps,
        abs_errors = abs_errors,
        rel_errors = rel_errors,
        total_abs = total_abs,
        total_rel = total_rel,
    }
end
end


-- Format a number with sign and 2 decimal places
local function format_error(value)
local function format_error(value)
     if value >= 0 then
     if value >= 0 then
Line 84: Line 76:
end
end


-- Main function to generate the wikitable
function p.main(frame)
function p.main(frame)
     local args = frame.args
     local args = frame.args
     local chord_str = args.chord or args[1]
     local interval_str = args.interval or args[1]
     local chord_name = args.chord_name
     local interval_name = args.interval_name
     local max_total_error = tonumber(args.max_total_error) or DEFAULT_MAX_TOTAL_ERROR
     local tolerance = tonumber(args.tolerance) or DEFAULT_TOLERANCE
     local min_edo = tonumber(args.min_edo) or DEFAULT_MIN_EDO
     local min_edo = tonumber(args.min_edo) or DEFAULT_MIN_EDO
     local max_edo = tonumber(args.max_edo) or DEFAULT_MAX_EDO
     local max_edo = tonumber(args.max_edo) or DEFAULT_MAX_EDO


     if not chord_str then
     if not interval_str then
         return "Error: No chord specified"
         return "Error: No interval specified"
    end
 
    local notes = parse_chord(chord_str)
    if not notes then
        return "Error: Invalid chord format (use 'a:b:c' with positive integers, e.g. '4:5:6')"
     end
     end


    -- Build intervals from root → each upper note
     local ratio = u.eval_num_arg(interval_str)
     local root = notes[1]
    if not ratio then
    local intervals_cents = {}
         return "Error: Invalid interval format (use format like '3/2')"
    local interval_strs = {}
    for i = 2, #notes do
        local n, d = notes[i], root
        local g = gcd(n, d)
        local rn, rd = n / g, d / g
         table.insert(intervals_cents, cents(n / d))
        table.insert(interval_strs, string.format("%d/%d", rn, rd))
     end
     end


    -- Scan EDOs in range (inclusive)
     local results = calculate_edo_approximations(ratio, tolerance, min_edo, max_edo)
     local results = {}
    for edo = min_edo, max_edo do
        local data = calculate_chord_approximation(intervals_cents, edo)
        if data.total_rel <= max_total_error then
            data.edo = edo
            table.insert(results, data)
        end
    end


     if #results == 0 then
     if #results == 0 then
         return "No edos found within total absolute error tolerance of " .. max_total_error .. "¢"
         return "No edos found within tolerance of " .. tolerance .. "%"
     end
     end


    -- Build wikitable
     local output = {}
     local output = {}
     table.insert(output, '{| class="wikitable center-all mw-collapsible sortable"')
     table.insert(output, '{| class="wikitable center-all mw-collapsible sortable"')


     local display_name = (chord_name and chord_name ~= "") and chord_name or chord_str
     local ratio_cents = cents(ratio)
     local intervals_display = table.concat(interval_strs, ",&nbsp;")
     local display_name = (interval_name and interval_name ~= "") and interval_name or interval_str
 
    -- Caption
    local caption_main
    if display_name ~= chord_str then
        caption_main = string.format("Edo&nbsp;approximations&nbsp;for&nbsp;%s&nbsp;(%s)", display_name, chord_str)
    else
        caption_main = string.format("Edo&nbsp;approximations&nbsp;for&nbsp;%s", display_name)
    end
 
    table.insert(output, '|+ style="font-size: 105%;" | ' .. caption_main
        .. string.format('<br /><span style="font-size: 0.75em;">\'\'intervals:&nbsp;%s&nbsp;·&nbsp;&le;&nbsp;%dedo,&nbsp;total&nbsp;abs&nbsp;error&nbsp;&le;&nbsp;%g{{c}}\'\'</span>',
            intervals_display, max_edo, max_total_error))


    table.insert(output, '|+ style="font-size: 105%;" | '
        .. string.format('Edo&nbsp;approximations&nbsp;for&nbsp;%s&nbsp;(%.2f{{c}})<br /><span style="font-size: 0.75em;">\'\'&le;&nbsp;%dedo,&nbsp;relative&nbsp;error&nbsp;&le;&nbsp;%g%%\'\'</span>',
            display_name, ratio_cents, max_edo, tolerance))
     table.insert(output, '|-')
     table.insert(output, '|-')
     table.insert(output, '! Edo'
     table.insert(output, '! class="unsortable" | &nbsp;'
        .. ' !! class="unsortable" | Steps'
                        .. ' !! Edo'
        .. ' !! class="unsortable" | Cents ([[cent|¢]])'
                        .. ' !! class="unsortable" | Step size'
        .. ' !! class="unsortable" | Absolute errors ([[cent|¢]])'
                        .. ' !! Cents ([[cent|¢]])'
        .. ' !! Total abs. error ([[cent|¢]])'
                        .. ' !! Absolute error ([[cent|¢]])'
        .. ' !! Total [[Relative interval error|relative error]] ([[relative cent|%]])')
                        .. ' !! [[Relative interval error|Relative error]] ([[relative cent|%]])')


     for _, r in ipairs(results) do
     for _, result in ipairs(results) do
         local edo_link = string.format("[[%dedo|%d]]", r.edo, r.edo)
         local edo_link = string.format("[[%dedo|%d]]", result.edo, result.edo)
 
         local step_size = string.format("%d\\%d", result.steps, result.edo)
         -- Steps column, e.g. "0 4 7\12"
         local approximation_cents = result.steps * (1200 / result.edo)
        local step_parts = {"0"}
         local approx_str = string.format("%.2f", approximation_cents)
        for _, s in ipairs(r.steps) do
         local abs_err = format_error(result.abs_error)
            table.insert(step_parts, tostring(s))
         local rel_err = format_error(result.rel_error)
        end
         local steps_str = table.concat(step_parts, " ")
 
        -- Cents approximation column
        local edostep = 1200 / r.edo
         local cents_parts = {"0.00"}
        for _, s in ipairs(r.steps) do
            table.insert(cents_parts, string.format("%.2f", s * edostep))
        end
         local cents_str = table.concat(cents_parts, " ")
 
        -- Per-interval absolute errors (signed)
         local err_parts = {}
        for _, e in ipairs(r.abs_errors) do
            table.insert(err_parts, format_error(e))
        end
        local err_str = table.concat(err_parts, " ")


         local total_abs_str = string.format("%.2f", r.total_abs)
        -- Play button: dyad of root (0) + the interval's step in this edo
         local total_rel_str = string.format("%.2f", r.total_rel)
         local steps_data = "0," .. tostring(result.steps)
         local play_btn = string.format(
            '<span class="edo-chord-play" data-edo="%d" data-steps="%s" title="Play %s in %dedo" role="button" tabindex="0">▶</span>',
            result.edo, steps_data, interval_str, result.edo)


         table.insert(output, '|-')
         table.insert(output, '|-')
         table.insert(output, string.format('| %s || %s || %s || %s || %s || %s',
         table.insert(output, string.format('| %s || %s || %s || %s || %s || %s',
             edo_link, steps_str, cents_str, err_str, total_abs_str, total_rel_str))
             play_btn, edo_link, step_size, approx_str, abs_err, rel_err))
     end
     end



Revision as of 01:31, 26 May 2026

Documentation for this module may be created at Module:Chord edo approximation/doc

-- EDO Approximations Module
-- Calculates EDO approximations for just intervals
-- Usage: {{#invoke:EDO_Approximations|main|interval=3/2|tolerance=9|min_edo=5|max_edo=60}}
local u = require("Module:Utils")
local yesno = require("Module:Yesno")
local p = {}

-- ===== CONFIGURATION VARIABLES =====
local DEFAULT_TOLERANCE = 9.0  -- Relative error tolerance in percent
local DEFAULT_MIN_EDO = 5      -- Minimum EDO to check
local DEFAULT_MAX_EDO = 60     -- Maximum EDO to check
-- ====================================

-- Convert a frequency ratio to cents
local function cents(ratio)
    return 1200 * u.log2(ratio)
end

-- Python-compatible rounding function (banker's rounding)
local function round(x)
    local floor_x = math.floor(x)
    local frac = x - floor_x

    if frac < 0.5 then
        return floor_x
    elseif frac > 0.5 then
        return floor_x + 1
    else
        if floor_x % 2 == 0 then
            return floor_x
        else
            return floor_x + 1
        end
    end
end

-- Find the best approximation of an interval in a given EDO
local function find_best_approximation(ratio_cents, edo)
    local edostep = 1200 / edo
    local best_step = round(ratio_cents / edostep)
    local approximation_cents = best_step * edostep
    local absolute_error = approximation_cents - ratio_cents
    local relative_error = (absolute_error / edostep) * 100

    return best_step, absolute_error, relative_error
end

-- Calculate all EDO approximations within tolerance for a given ratio
local function calculate_edo_approximations(ratio, tolerance, min_edo, max_edo)
    local ratio_cents = cents(ratio)
    local results = {}

    for edo = min_edo, max_edo do
        local steps, abs_error, rel_error = find_best_approximation(ratio_cents, edo)

        if math.abs(rel_error) <= tolerance then
            table.insert(results, {
                edo = edo,
                steps = steps,
                abs_error = abs_error,
                rel_error = rel_error
            })
        end
    end

    return results
end

-- Format a number with sign and 2 decimal places
local function format_error(value)
    if value >= 0 then
        return string.format("+%.2f", value)
    else
        return string.format("%.2f", value)
    end
end

-- Main function to generate the wikitable
function p.main(frame)
    local args = frame.args
    local interval_str = args.interval or args[1]
    local interval_name = args.interval_name
    local tolerance = tonumber(args.tolerance) or DEFAULT_TOLERANCE
    local min_edo = tonumber(args.min_edo) or DEFAULT_MIN_EDO
    local max_edo = tonumber(args.max_edo) or DEFAULT_MAX_EDO

    if not interval_str then
        return "Error: No interval specified"
    end

    local ratio = u.eval_num_arg(interval_str)
    if not ratio then
        return "Error: Invalid interval format (use format like '3/2')"
    end

    local results = calculate_edo_approximations(ratio, tolerance, min_edo, max_edo)

    if #results == 0 then
        return "No edos found within tolerance of " .. tolerance .. "%"
    end

    local output = {}
    table.insert(output, '{| class="wikitable center-all mw-collapsible sortable"')

    local ratio_cents = cents(ratio)
    local display_name = (interval_name and interval_name ~= "") and interval_name or interval_str

    table.insert(output, '|+ style="font-size: 105%;" | '
        .. string.format('Edo&nbsp;approximations&nbsp;for&nbsp;%s&nbsp;(%.2f{{c}})<br /><span style="font-size: 0.75em;">\'\'&le;&nbsp;%dedo,&nbsp;relative&nbsp;error&nbsp;&le;&nbsp;%g%%\'\'</span>',
            display_name, ratio_cents, max_edo, tolerance))
    table.insert(output, '|-')
    table.insert(output, '! class="unsortable" | &nbsp;'
                        .. ' !! Edo'
                        .. ' !! class="unsortable" | Step size'
                        .. ' !! Cents ([[cent|¢]])'
                        .. ' !! Absolute error ([[cent|¢]])'
                        .. ' !! [[Relative interval error|Relative error]] ([[relative cent|%]])')

    for _, result in ipairs(results) do
        local edo_link = string.format("[[%dedo|%d]]", result.edo, result.edo)
        local step_size = string.format("%d\\%d", result.steps, result.edo)
        local approximation_cents = result.steps * (1200 / result.edo)
        local approx_str = string.format("%.2f", approximation_cents)
        local abs_err = format_error(result.abs_error)
        local rel_err = format_error(result.rel_error)

        -- Play button: dyad of root (0) + the interval's step in this edo
        local steps_data = "0," .. tostring(result.steps)
        local play_btn = string.format(
            '<span class="edo-chord-play" data-edo="%d" data-steps="%s" title="Play %s in %dedo" role="button" tabindex="0">▶</span>',
            result.edo, steps_data, interval_str, result.edo)

        table.insert(output, '|-')
        table.insert(output, string.format('| %s || %s || %s || %s || %s || %s',
            play_btn, edo_link, step_size, approx_str, abs_err, rel_err))
    end

    table.insert(output, '|}')

    local result = table.concat(output, '\n')
    if yesno(frame.args["debug"]) == true then
        result = '<syntaxhighlight lang="wikitext">' .. result .. '</syntaxhighlight>'
    end

    return frame:preprocess(result)
end

return p