Module:Quantity

From MaRDI portal

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

-- Required modules for SPARQL queries and HTML table generation
-- Module for executing SPARQL queries
local sparql = require('SPARQL')
-- MediaWiki library for logging and utilities
local mw = require('mw')
local json = require("mw.text") 
-- load MathModDBHelperMethods module
local mathHelpers = require("Module:MathModDBHelperMethods")

-- Main table to hold all functions
local p = {}


-- Function to get defining formulation with Quantities 
function p.extractDefiningFormulationWithQuantities(frame)
	
	local equation = mw.wikibase.getEntity()
	local equationID = entity and entity.id or nil
	
	-- Table to store formulations
    local formulations = {}
    -- Table to store quantity symbol and name id 
    local quantitySymbolNameIdPairs = {}
    
  
	-- P989 refers to property defining formula 
	local definingFormula = equation:getBestStatements('P989')
	if definingFormula and #definingFormula > 0 then
    	local value = definingFormula[1].mainsnak.datavalue.value
    	mathTag = frame:extensionTag{
	    	name = "math",
	        content = value
        }
	   table.insert(formulations, "| Defining Formula: " .. mathTag)
	end
   
    
    quantitySymbolNameIdPairs = p.extractQuantities(equationID)
    if type(quantitySymbolNameIdPairs) == "table" then
    	-- Accessing the stored pairs
		for i, pair in ipairs(quantitySymbolNameIdPairs) do
			local pairFirstValue = pair[1]
			local pairFirstValue = mw.text.decode(pairFirstValue or "")
			local quantitySymbolMathTag = frame:extensionTag{
				  name = "math",
            	  content = pairFirstValue
        		  }
        	-- Construct the Portal URL
        	local quantityId = pair[3]
        	local urlRendered = mathHelpers.canonicalLink(quantityId)
        	local labelWithUrl = string.format('[%s %s]', tostring(urlRendered), tostring(pair[2]))
        	
            table.insert(formulations, "| " .. quantitySymbolMathTag   ..  " symbol represents "  .. labelWithUrl)
		end
		table.insert(formulations, "| " .. " " )
	else
		-- Error: extractQuantities did not return a table"
	end

		-- Construct the Wikitext table
    	local wikitextTable = [[
{| class="wikitable" style="table-layout: fixed; width: 1000px;"
]] .. table.concat(formulations, "\n|-\n") .. "\n|}"
    	return wikitextTable
  end

function p.extractQuantities(qid)
	-- Property ID for in defining formula 
    local pidInDefiningFormula  = "P983"
    -- Property ID for the (qualifier) symbol represents
    local pidSymbolRepresents = "P984"   

    -- Attempt to retrieve entity data
    local entity = mw.wikibase.getEntity(qid)
    if not entity or not entity.claims[pidInDefiningFormula] then
        return "No formulation found"
    end
    
    
    local inDefiningFormulaClaims = entity.claims[pidInDefiningFormula]
    local count = 0
    -- Table to store pairs of quantity symbol and quantity name
    local quantitySymbolNameIdPairs = {}
	for _ in pairs(inDefiningFormulaClaims or {}) do
    	count = count + 1
    	-- Get the quantity symbol
    	local quantitySymbol = inDefiningFormulaClaims[count].mainsnak.datavalue.value
    	if not quantitySymbol then
        	return "No valid symbol found"
    	end

    	local claim = inDefiningFormulaClaims[count]
		if claim
		and claim.qualifiers
		and claim.qualifiers[pidSymbolRepresents]
		and claim.qualifiers[pidSymbolRepresents][1]
		and claim.qualifiers[pidSymbolRepresents][1].datavalue
		and claim.qualifiers[pidSymbolRepresents][1].datavalue.value
		and claim.qualifiers[pidSymbolRepresents][1].datavalue.value.text
		then
    		quantity = claim.qualifiers[pidSymbolRepresents][1].datavalue.value.text
		end

        if claim
		and claim.qualifiers
		and claim.qualifiers[pidSymbolRepresents]
		and claim.qualifiers[pidSymbolRepresents][1]
		and claim.qualifiers[pidSymbolRepresents][1].datavalue
		and claim.qualifiers[pidSymbolRepresents][1].datavalue.value
		and claim.qualifiers[pidSymbolRepresents][1].datavalue.value.id
		then
	    	quantityId = claim.qualifiers[pidSymbolRepresents][1].datavalue.value.id
	    end
	    local quantityName = mw.wikibase.label(quantityId)
	    -- Insert pair into the table
	    table.insert(quantitySymbolNameIdPairs, {quantitySymbol, quantityName, quantityId})
    end
    return quantitySymbolNameIdPairs
end


-- Function to get get contained entities 
function p.getContainedEntities(frame)
	local entityId = frame.args[1]
    
    -- Validate input parameter
    if not entityId or entityId == '' then
        return ""
    end
    
    -- Constructing the SPARQL query with dynamic entity entityId
    local sparqlQuery = [[
PREFIX entityId: <https://portal.mardi4nfdi.de/entity/]] .. entityId .. [[>
	SELECT ?URL ?Label  
	WHERE {
		  entityId: wdt:P1560  ?URL.
		  ?URL rdfs:label ?Label
		  FILTER(LANG(?Label) = "en")
	}
	ORDER BY ?Label
	]]

	-- Executing the SPARQL query and retrieving results in JSON format
	local jsonResults = sparql.runQuery(sparqlQuery)
	-- Validate results
	if not jsonResults or not jsonResults.results or not jsonResults.results.bindings then
       	return "No specialized academic discipline found"
    end
	
	local listContainedItems = {}
    -- Get the number of specialized academic disciplines
	local totalContainedItems = #jsonResults.results.bindings
	-- Loop through the bindings
	for index = 0, totalContainedItems  do
    	local item = jsonResults.results.bindings[index]
    	if not item then
        		return ""
    	end
    	if not item.Label.value then
        	return ""
    	elseif not item.URL.value then
        	return ""
    	else
    		local label = item.Label.value
        	local url = item.URL.value
        	local qid = url:match("(Q%d+)")
        	local urlRendered = mathHelpers.canonicalLink(qid)
        	local labelWithUrl = string.format('[%s %s]', tostring(urlRendered), tostring(label))
        	table.insert(listContainedItems, "| " .. labelWithUrl)
    	end
	end

	-- Construct the Wikitext table
	local wikitextTable = "{| class='wikitable'\n" .. table.concat(listContainedItems, "\n|-\n") .. "\n|}"
	return wikitextTable
end	


-- Function to get nondimensionalized by quantities
function p.getNondimensionalized(frame)
	local entityId = frame.args[1]
    
    -- Validate input parameter
    if not entityId or entityId == '' then
        return " "
    end
    
    -- Constructing the SPARQL query with dynamic entity entityId
    -- P1658: nondimensionalizeded by property id
    local sparqlQuery = [[
PREFIX entityId: <https://portal.mardi4nfdi.de/entity/]] .. entityId .. [[>
	SELECT ?NonDimensionalizedURL ?NonDimensionalizedLabel
	WHERE {
		entityId: p:P1658 ?statement.
		?statement ps:P1658 ?NonDimensionalizedURL.
		?NonDimensionalizedURL rdfs:label ?NonDimensionalizedLabel.
		FILTER(LANG(?NonDimensionalizedLabel) = "en")
	}
	ORDER BY ?NonDimensionalizedLabel
	]]


	-- Executing the SPARQL query and retrieving results in JSON format
	local jsonResults = sparql.runQuery(sparqlQuery)
	-- Validate results
	if not jsonResults or not jsonResults.results or not jsonResults.results.bindings then
       	return " "
    end
	
	local nonDimensionalized = {}
    -- Get the number of similar expressions
	local totalNonDimensionalized = #jsonResults.results.bindings
	-- Loop through the bindings
	for index = 0, totalNonDimensionalized  do
    	local item = jsonResults.results.bindings[index]
    	if not item.NonDimensionalizedLabel.value then
        	return "Error: Missing item.Label.value"
    	elseif not item.NonDimensionalizedURL.value then
        	return "Error: Missing item.URL.value"
    	else
        	local label = item.NonDimensionalizedLabel.value
        	local url = item.NonDimensionalizedURL.value
        	local qid = url:match("(Q%d+)")
        	local urlRendered = mathHelpers.canonicalLink(qid)
        	local labelWithUrl = string.format('[%s %s]', tostring(urlRendered), tostring(label))
			table.insert(nonDimensionalized, "| "  .. labelWithUrl)
    	end
	end

	-- Construct the Wikitext table
	local wikitextTable = "{| class='wikitable'\n" .. table.concat(nonDimensionalized, "\n|-\n") .. "\n|}"
	return wikitextTable
	
end
return p