Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Uncaught ReferenceError: glpk is not defined" even after local loading #44

Open
lbreal opened this issue Jun 14, 2024 · 3 comments
Open

Comments

@lbreal
Copy link

lbreal commented Jun 14, 2024

Hello,

I am facing a problem with GLPK.js. Even after downloading the glpk.min.js file and including it locally in my project, I keep getting the error "Uncaught ReferenceError: glpk is not defined".

My HTML code is as follows:
<

<script src="glpk.min.js" defer></script> <script> document.addEventListener('DOMContentLoaded', function() { glpk.then(glpk => { // Inicialize o GLPK.js antes de usá-lo console.log("GLPK.js loaded successfully.");
    // Definindo o problema de transporte
    const supply = [20, 30, 25]; // Fornecimento de cada fornecedor
        const demand = [10, 25, 20, 20]; // Demanda de cada consumidor

        // Custos de transporte
        const costs = [
            [8, 6, 10, 9],  // Custos do fornecedor 1
            [9, 12, 13, 7], // Custos do fornecedor 2
            [14, 9, 16, 5]  // Custos do fornecedor 3
        ];

        // Função para resolver o problema de transporte usando GLPK.js
        function solveTransportationProblem(supply, demand, costs) {
            const numSuppliers = supply.length;
            const numConsumers = demand.length;

            // Variáveis de decisão e a função objetivo
            let variables = [];
            let objective = [];
            for (let i = 0; i < numSuppliers; i++) {
                for (let j = 0; j < numConsumers; j++) {
                    let varName = `x_${i}_${j}`;
                    variables.push(varName);
                    objective.push({ name: varName, coef: costs[i][j] });
                }
            }

            // Restrições de fornecimento
            let constraints = [];
            for (let i = 0; i < numSuppliers; i++) {
                let constraint = { name: `supply_${i}`, vars: [], bnds: { type: glpk.GLP_UP, ub: supply[i], lb: supply[i] } };
                for (let j = 0; j < numConsumers; j++) {
                    constraint.vars.push({ name: `x_${i}_${j}`, coef: 1 });
                }
                constraints.push(constraint);
            }

            // Restrições de demanda
            for (let j = 0; j < numConsumers; j++) {
                let constraint = { name: `demand_${j}`, vars: [], bnds: { type: glpk.GLP_UP, ub: demand[j], lb: demand[j] } };
                for (let i = 0; i < numSuppliers; i++) {
                    constraint.vars.push({ name: `x_${i}_${j}`, coef: 1 });
                }
                constraints.push(constraint);
            }

            // Configuração do problema
            let problem = {
                name: 'Transportation Problem',
                objective: {
                    direction: glpk.GLP_MIN,
                    name: 'obj',
                    vars: objective
                },
                subjectTo: constraints
            };

            // Resolver o problema usando GLPK.js
            let solution = glpk.solve(problem);

            // Extrair a matriz de alocação e o custo total
            let allocation = Array.from({ length: numSuppliers }, () => Array(numConsumers).fill(0));
            for (let varName in solution.result.vars) {
                let [_, i, j] = varName.split('_').map(Number);
                allocation[i][j] = solution.result.vars[varName];
            }
            let totalCost = solution.result.z;

            return { allocation, totalCost };
        }

        // Resolvendo o problema de transporte
        const solution = solveTransportationProblem(supply, demand, costs);
        console.log("Solution:", solution);
        alert(`Custo total de transporte: ${solution.totalCost}`);

        // Exibir matriz de alocação
        console.log("Allocation matrix:", solution.allocation);


  }); 
});
</script>
@jvail
Copy link
Owner

jvail commented Jun 15, 2024

Hi,

here is a minimal example: https://github.com/jvail/glpk.js/blob/master/examples/lp.html If you adjust your import/script then it should work out of the box.

@lbreal
Copy link
Author

lbreal commented Jun 17, 2024

Thanks for answering!

I'm still encountering difficulties using GLPK.js in my local development environment, even after trying different approaches. Here are the issues I'm facing:

Approach 1: Local File Import ( import GLPK from '../dist/index.js';)
I'm unable to import GLPK.js as a module from a local file.

The error in console is:
Access to script at 'file:///C:/Users/luiza/Documents/Documentos/PO/jogos/meu_jogo/glpk.min.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

Approach 2: CDN Import ( import GLPK from 'https://cdn.jsdelivr.net/npm/[email protected]/dist/glpk.min.js';)

When I try to import GLPK.js as a module from a CDN, I get a different error:
Uncaught SyntaxError: The requested module 'https://cdn.jsdelivr.net/npm/[email protected]/dist/glpk.min.js' does not provide an export named 'default' (at teste.html:6:16)

The code used is the following:

<title>Optimal Transportation Problem with GLPK.js</title> <script type="module"> import GLPK from '../dist/index.js'; (async () => {
        const glpk = await GLPK();

        function print(res) {
            const el = window.document.getElementById('out');
            el.innerHTML = `Solution: Transportation Problem\n\n ${JSON.stringify(res, null, 2)}`;
        };

        // Definindo o problema de transporte
        const supply = [20, 30, 25]; // Fornecimento de cada fornecedor
        const demand = [10, 25, 20, 20]; // Demanda de cada consumidor

        // Custos de transporte
        const costs = [
            [8, 6, 10, 9],  // Custos do fornecedor 1
            [9, 12, 13, 7], // Custos do fornecedor 2
            [14, 9, 16, 5]  // Custos do fornecedor 3
        ];

        const numSuppliers = supply.length;
        const numConsumers = demand.length;

        // Variáveis de decisão e a função objetivo
        let variables = [];
        for (let i = 0; i < numSuppliers; i++) {
            for (let j = 0; j < numConsumers; j++) {
                variables.push({ name: `x_${i}_${j}`, coef: costs[i][j] });
            }
        }

        // Restrições de fornecimento
        let constraints = [];
        for (let i = 0; i < numSuppliers; i++) {
            let vars = [];
            for (let j = 0; j < numConsumers; j++) {
                vars.push({ name: `x_${i}_${j}`, coef: 1 });
            }
            constraints.push({ name: `supply_${i}`, vars: vars, bnds: { type: glpk.GLP_FX, ub: supply[i], lb: supply[i] } });
        }

        // Restrições de demanda
        for (let j = 0; j < numConsumers; j++) {
            let vars = [];
            for (let i = 0; i < numSuppliers; i++) {
                vars.push({ name: `x_${i}_${j}`, coef: 1 });
            }
            constraints.push({ name: `demand_${j}`, vars: vars, bnds: { type: glpk.GLP_FX, ub: demand[j], lb: demand[j] } });
        }

        // Configuração do problema
        const lp = {
            name: 'Transportation Problem',
            objective: {
                direction: glpk.GLP_MIN,
                name: 'obj',
                vars: variables
            },
            subjectTo: constraints
        };

        const opt = {
            msglev: glpk.GLP_MSG_OFF
        };

        // Resolver o problema usando GLPK.js
        const solution = await glpk.solve(lp, opt);
        print(solution);

        console.log(await glpk.solve(lp, glpk.GLP_MSG_DBG));

        window.document.getElementById('cplex').innerHTML = await glpk.write(lp);

    })();
</script>

Optimal Transportation Problem with GLPK.js


    



      

@jvail
Copy link
Owner

jvail commented Jun 18, 2024

The error in console is:
Access to script at 'file:///C:/Users/luiza/Documents/Documentos/PO/jogos/meu_jogo/glpk.min.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.

Yes, that is normal. If you want to develop locally I propose to use serve. That is what I do as well:

  1. Clone this repo
  2. Create your html/js files somewhere in the repo folder
  3. Run npx serve
  4. Navigate to your file in the browser e.g. http://localhost:3000/examples/lp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants