File: gnm-lpsolve.c

package info (click to toggle)
gnumeric 1.12.57-1.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 111,496 kB
  • sloc: ansic: 296,601; xml: 56,363; perl: 6,615; sh: 5,288; makefile: 2,981; yacc: 1,341; python: 389
file content (507 lines) | stat: -rw-r--r-- 11,798 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#include <gnumeric-config.h>
#include <gnumeric.h>
#include "boot.h"
#include <cell.h>
#include <sheet.h>
#include <value.h>
#include <ranges.h>
#include <gnumeric-conf.h>
#include <gsf/gsf-impl-utils.h>
#include <glib/gi18n-lib.h>
#include <string.h>

#define SOLVER_PROGRAM "lp_solve"
#define SOLVER_URL "http://sourceforge.net/projects/lpsolve/"
#define PRIVATE_KEY "::lpsolve::"
#define SOLVER_INF GNM_const(1e30)

typedef struct {
	GnmSubSolver *parent;
	GnmSolverResult *result;
	GnmSolverSensitivity *sensitivity;
	enum { SEC_UNKNOWN, SEC_VALUES,
	       SEC_LIMITS, SEC_DUAL_LIMITS } section;
} GnmLPSolve;

static void
gnm_lpsolve_cleanup (GnmLPSolve *lp)
{
	gnm_sub_solver_clear (lp->parent);

	if (lp->result) {
		g_object_unref (lp->result);
		lp->result = NULL;
	}

	if (lp->sensitivity) {
		g_object_unref (lp->sensitivity);
		lp->sensitivity = NULL;
	}
}

static void
gnm_lpsolve_final (GnmLPSolve *lp)
{
	gnm_lpsolve_cleanup (lp);
	g_free (lp);
}

static gboolean
write_program (GnmSolver *sol, WorkbookControl *wbc, GError **err)
{
	GnmSubSolver *subsol = GNM_SUB_SOLVER (sol);
	GOFileSaver *fs;

	fs = go_file_saver_for_mime_type ("application/lpsolve");
	if (!fs) {
		g_set_error (err, G_FILE_ERROR, 0,
			     _("The LPSolve exporter is not available."));
		return FALSE;
	}

	return gnm_solver_saveas (sol, wbc, fs,
				  "program-XXXXXX.lp",
				  &subsol->program_filename,
				  err);
}

static GnmSolverResult *
gnm_lpsolve_start_solution (GnmLPSolve *lp)
{
	int n;
	GnmSolver *sol;

	g_return_val_if_fail (lp->result == NULL, NULL);

	sol = GNM_SOLVER (lp->parent);
	n = sol->input_cells->len;

	lp->result = g_object_new (GNM_SOLVER_RESULT_TYPE, NULL);
	lp->result->solution = g_new0 (gnm_float, n);

	lp->sensitivity = gnm_solver_sensitivity_new (sol);

	return lp->result;
}

static void
gnm_lpsolve_flush_solution (GnmLPSolve *lp)
{
	if (lp->result) {
		g_object_set (lp->parent, "result", lp->result, NULL);
		g_object_unref (lp->result);
		lp->result = NULL;
	}
	g_clear_object (&lp->sensitivity);
}


static char **
my_strsplit (const char *line)
{
	GPtrArray *res = g_ptr_array_new ();

	while (1) {
		const char *end;

		while (g_ascii_isspace (*line))
			line++;

		if (!*line)
			break;

		end = line;
		while (*end && !g_ascii_isspace (*end))
			end++;

		g_ptr_array_add (res, g_strndup (line, end - line));
		line = end;
	}
	g_ptr_array_add (res, NULL);

	return (char **)g_ptr_array_free (res, FALSE);
}

static gnm_float
fixup_inf (gnm_float v)
{
	if (v <= -SOLVER_INF)
		return go_ninf;
	if (v >= +SOLVER_INF)
		return go_pinf;
	return v;
}


static gboolean
cb_read_stdout (GIOChannel *channel, GIOCondition cond, GnmLPSolve *lp)
{
	GnmSolver *sol = GNM_SOLVER (lp->parent);
	const char obj_line_prefix[] = "Value of objective function:";
	size_t obj_line_len = sizeof (obj_line_prefix) - 1;
	const char val_header_line[] = "Actual values of the variables:";
	size_t val_header_len = sizeof (val_header_line) - 1;
	const char limit_header_line[] = "Objective function limits:";
	size_t limit_header_len = sizeof (limit_header_line) - 1;
	const char dual_limit_header_line[] = "Dual values with from - till limits:";
	size_t dual_limit_header_len = sizeof (dual_limit_header_line) - 1;
	gchar *line = NULL;

	do {
		GIOStatus status;
		gsize tpos;

		g_free (line);
		line = NULL;

		status = g_io_channel_read_line (channel,
						 &line, NULL, &tpos,
						 NULL);
		if (status != G_IO_STATUS_NORMAL)
			break;

		line[tpos] = 0;

		if (line[0] == 0)
			lp->section = SEC_UNKNOWN;
		else if (lp->section == SEC_UNKNOWN &&
			 !strncmp (line, obj_line_prefix, obj_line_len)) {
			GnmSolverResult *r;
			gnm_lpsolve_flush_solution (lp);
			r = gnm_lpsolve_start_solution (lp);
			r->quality = GNM_SOLVER_RESULT_FEASIBLE;
			r->value = gnm_ascii_strto (line + obj_line_len, NULL);
		} else if (lp->section == SEC_UNKNOWN &&
			   !strncmp (line, val_header_line, val_header_len)) {
			lp->section = SEC_VALUES;
		} else if (lp->section == SEC_UNKNOWN &&
			   !strncmp (line, limit_header_line, limit_header_len)) {
			lp->section = SEC_LIMITS;
		} else if (lp->section == SEC_UNKNOWN &&
			   !strncmp (line, dual_limit_header_line, dual_limit_header_len)) {
			lp->section = SEC_DUAL_LIMITS;
		} else if (lp->section == SEC_VALUES && lp->result) {
			GnmSolverResult *r = lp->result;
			gnm_float v;
			char *space = strchr (line, ' ');
			GnmCell *cell;
			int idx;

			if (!space) {
				lp->section = SEC_UNKNOWN;
				continue;
			}
			*space = 0;
			cell = gnm_sub_solver_find_cell (lp->parent, line);
			idx = gnm_solver_cell_index (sol, cell);
			if (idx < 0) {
				g_printerr ("Strange cell %s in output\n",
					    line);
				lp->section = SEC_UNKNOWN;
				continue;
			}

			v = gnm_ascii_strto (space + 1, NULL);
			r->solution[idx] = v;
		} else if (lp->section == SEC_LIMITS) {
			gnm_float low, high;
			GnmCell *cell;
			int idx;
			gchar **items;

			if (g_ascii_isspace (line[0]))
				continue;

			items = my_strsplit (line);

			if (g_strv_length (items) != 4)
				goto bad_limit;

			cell = gnm_sub_solver_find_cell (lp->parent, items[0]);
			idx = gnm_solver_cell_index (sol, cell);
			if (idx < 0)
				goto bad_limit;

			low = fixup_inf (gnm_ascii_strto (items[1], NULL));
			high = fixup_inf (gnm_ascii_strto (items[2], NULL));

			lp->sensitivity->vars[idx].low = low;
			lp->sensitivity->vars[idx].high = high;

			g_strfreev (items);

			continue;

		bad_limit:
			g_printerr ("Strange limit line in output: %s\n",
				    line);
			lp->section = SEC_UNKNOWN;
			g_strfreev (items);
		} else if (lp->section == SEC_DUAL_LIMITS) {
			gnm_float dual, low, high;
			GnmCell *cell;
			int idx, cidx;
			gchar **items;

			if (g_ascii_isspace (line[0]))
				continue;

			items = my_strsplit (line);

			if (g_strv_length (items) != 4)
				goto bad_dual;

			cell = gnm_sub_solver_find_cell (lp->parent, items[0]);
			idx = gnm_solver_cell_index (sol, cell);

			cidx = (idx == -1)
				? gnm_sub_solver_find_constraint (lp->parent, items[0])
				: -1;

			dual = fixup_inf (gnm_ascii_strto (items[1], NULL));
			low = fixup_inf (gnm_ascii_strto (items[2], NULL));
			high = fixup_inf (gnm_ascii_strto (items[3], NULL));

			if (idx >= 0) {
				lp->sensitivity->vars[idx].reduced_cost = dual;
			} else if (cidx >= 0) {
				lp->sensitivity->constraints[cidx].low = low;
				lp->sensitivity->constraints[cidx].high = high;
				lp->sensitivity->constraints[cidx].shadow_price = dual;
			} else {
				// Ignore
			}

			g_strfreev (items);
			continue;

		bad_dual:
			g_printerr ("Strange dual limit line in output: %s\n",
				    line);
			lp->section = SEC_UNKNOWN;
			g_strfreev (items);
		}
	} while (1);

	g_free (line);

	return TRUE;
}


static void
gnm_lpsolve_child_exit (GnmSubSolver *subsol, gboolean normal, int code,
			GnmLPSolve *lp)
{
	GnmSolver *sol = GNM_SOLVER (subsol);
	GnmSolverStatus new_status = GNM_SOLVER_STATUS_DONE;

	if (sol->status != GNM_SOLVER_STATUS_RUNNING)
		return;

	if (normal) {
		GnmSolverResult *r;

		switch (code) {
		case 0: /* Optimal */
			gnm_sub_solver_flush (subsol);
			if (lp->result)
				lp->result->quality = GNM_SOLVER_RESULT_OPTIMAL;
			g_object_set (lp->parent,
				      "sensitivity", lp->sensitivity,
				      NULL);
			gnm_lpsolve_flush_solution (lp);
			break;

		case 2: /* Infeasible */
			r = gnm_lpsolve_start_solution (lp);
			r->quality = GNM_SOLVER_RESULT_INFEASIBLE;
			gnm_lpsolve_flush_solution (lp);
			break;

		case 3: /* Unbounded */
			r = gnm_lpsolve_start_solution (lp);
			r->quality = GNM_SOLVER_RESULT_UNBOUNDED;
			gnm_lpsolve_flush_solution (lp);
			break;

		case 1: /* Suboptimal */
		case 4: /* Degenerate */
			gnm_sub_solver_flush (subsol);
			gnm_lpsolve_flush_solution (lp);
			break;

		default:
		case 5: /* Numfailure */
		case 6: /* Userabort */
		case 7: /* Timeout */
		case 8: /* Running (eh?) */
		case 9: /* Presolved (eh?) */
			new_status = GNM_SOLVER_STATUS_ERROR;
			break;
		}
	} else {
		/* Something bad.  */
		new_status = GNM_SOLVER_STATUS_ERROR;
	}

	gnm_solver_set_status (sol, new_status);
}

static void
cb_child_setup (gpointer user)
{
	const char *lcvars[] = {
		"LC_ALL",
		"LC_MESSAGES",
		"LC_CTYPE",
		"LC_NUMERIC"
	};
	unsigned ui;

	g_unsetenv ("LANG");
	for (ui = 0; ui < G_N_ELEMENTS (lcvars); ui++) {
		const char *v = lcvars[ui];
		if (g_getenv (v))
			g_setenv (v, "C", TRUE);
	}
}

static gboolean
gnm_lpsolve_prepare (GnmSolver *sol, WorkbookControl *wbc, GError **err,
		     GnmLPSolve *lp)
{
	gboolean ok;

	g_return_val_if_fail (sol->status == GNM_SOLVER_STATUS_READY, FALSE);

	gnm_solver_set_status (sol, GNM_SOLVER_STATUS_PREPARING);
	ok = write_program (sol, wbc, err);
	if (ok)
		gnm_solver_set_status (sol, GNM_SOLVER_STATUS_PREPARED);
	else {
		gnm_lpsolve_cleanup (lp);
		gnm_solver_set_status (sol, GNM_SOLVER_STATUS_ERROR);
	}

	return ok;
}

static gboolean
gnm_lpsolve_start (GnmSolver *sol, WorkbookControl *wbc, GError **err,
		   GnmLPSolve *lp)
{
	GnmSubSolver *subsol = GNM_SUB_SOLVER (sol);
	gboolean ok;
	gchar *argv[6];
	int argc = 0;
	GnmSolverParameters *param = sol->params;
	const char *binary;

	g_return_val_if_fail (sol->status == GNM_SOLVER_STATUS_PREPARED, FALSE);

	binary = gnm_conf_get_plugin_lpsolve_lpsolve_path ();
	if (binary == NULL || *binary == 0)
		binary = SOLVER_PROGRAM;

	argv[argc++] = (gchar *)binary;
	argv[argc++] = (gchar *)"-i";
	argv[argc++] = (gchar *)(param->options.automatic_scaling
				 ? "-s1"
				 : "-s0");
	argv[argc++] = (gchar *)"-S6";
	argv[argc++] = subsol->program_filename;
	argv[argc] = NULL;
	g_assert (argc < (int)G_N_ELEMENTS (argv));

	ok = gnm_sub_solver_spawn (subsol, argv,
				   cb_child_setup, NULL,
				   (GIOFunc)cb_read_stdout, lp,
				   NULL, NULL,
				   err);

	if (!ok && err &&
	    g_error_matches (*err, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT)) {
		g_clear_error (err);
		g_set_error (err, G_SPAWN_ERROR, G_SPAWN_ERROR_NOENT,
			     _("The %s program was not found.  You can either "
			       "install it or use another solver. "
			       "For more information see %s"),
			     SOLVER_PROGRAM,
			     SOLVER_URL);
	}

	return ok;
}

static gboolean
gnm_lpsolve_stop (GnmSolver *sol, GError *err, GnmLPSolve *lp)
{
	g_return_val_if_fail (sol->status == GNM_SOLVER_STATUS_RUNNING, FALSE);

	gnm_lpsolve_cleanup (lp);

	gnm_solver_set_status (sol, GNM_SOLVER_STATUS_CANCELLED);

	return TRUE;
}

GnmSolver *
lpsolve_solver_create (GnmSolverParameters *params)
{
	GnmSolver *res = g_object_new (GNM_SUB_SOLVER_TYPE,
				       "params", params,
				       NULL);
	GnmLPSolve *lp = g_new0 (GnmLPSolve, 1);

	lp->parent = GNM_SUB_SOLVER (res);

	g_signal_connect (res, "prepare", G_CALLBACK (gnm_lpsolve_prepare), lp);
	g_signal_connect (res, "start", G_CALLBACK (gnm_lpsolve_start), lp);
	g_signal_connect (res, "stop", G_CALLBACK (gnm_lpsolve_stop), lp);
	g_signal_connect (res, "child-exit", G_CALLBACK (gnm_lpsolve_child_exit), lp);

	g_object_set_data_full (G_OBJECT (res), PRIVATE_KEY, lp,
				(GDestroyNotify)gnm_lpsolve_final);

	return res;
}


gboolean
lpsolve_solver_factory_functional (GnmSolverFactory *factory,
				   WBCGtk *wbcg)
{
	const char *full_path = gnm_conf_get_plugin_lpsolve_lpsolve_path ();
	char *path;

	if (full_path && *full_path)
		return g_file_test (full_path, G_FILE_TEST_IS_EXECUTABLE);

	path = g_find_program_in_path (SOLVER_PROGRAM);
	if (path) {
		g_free (path);
		return TRUE;
	}

	if (!wbcg)
		return FALSE;

	path = gnm_sub_solver_locate_binary (SOLVER_PROGRAM,
					     "LP Solve",
					     SOLVER_URL,
					     wbcg);
	if (path) {
		gnm_conf_set_plugin_lpsolve_lpsolve_path (path);
		g_free (path);
		return TRUE;
	}

	return FALSE;
}

GnmSolver *
lpsolve_solver_factory (GnmSolverFactory *factory, GnmSolverParameters *params)
{
	return lpsolve_solver_create (params);
}