gnm-solver.c 89.6 KB
Newer Older
1 2 3 4
#include <gnumeric-config.h>
#include "gnumeric.h"
#include "value.h"
#include "cell.h"
5
#include "expr.h"
6
#include "expr-deriv.h"
7 8
#include "sheet.h"
#include "workbook.h"
9
#include "rangefunc.h"
10
#include "ranges.h"
Morten Welinder's avatar
Morten Welinder committed
11
#include "gutils.h"
12
#include "mathfunc.h"
13 14 15
#include "gnm-solver.h"
#include "workbook-view.h"
#include "workbook-control.h"
Morten Welinder's avatar
Morten Welinder committed
16
#include "application.h"
17
#include "gnm-marshalers.h"
18
#include <tools/dao.h>
19
#include "gui-util.h"
20
#include "gnm-i18n.h"
21 22 23 24 25 26 27
#include <gsf/gsf-impl-utils.h>
#include <gsf/gsf-output-stdio.h>
#include <glib/gi18n-lib.h>
#include <glib/gstdio.h>
#include <unistd.h>
#include <signal.h>
#include <string.h>
28
#ifdef HAVE_SYS_WAIT_H
29
#include <sys/wait.h>
30
#endif
31

32 33 34 35 36 37 38 39 40 41
#ifdef G_OS_WIN32
#include <windows.h>
#ifndef WIFEXITED
#define WIFEXITED(x) ((x) != STILL_ACTIVE)
#endif
#ifndef WEXITSTATUS
#define WEXITSTATUS(x) (x)
#endif
#endif

42 43
/* ------------------------------------------------------------------------- */

44 45
gboolean
gnm_solver_debug (void)
46 47 48 49 50 51 52
{
	static int debug = -1;
	if (debug == -1)
		debug = gnm_debug_flag ("solver");
	return debug;
}

Morten Welinder's avatar
Morten Welinder committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
static char *
gnm_solver_cell_name (GnmCell const *cell, Sheet *origin)
{
	GnmConventionsOut out;
	GnmCellRef cr;
	GnmParsePos pp;

	gnm_cellref_init (&cr, cell->base.sheet,
			  cell->pos.col, cell->pos.row,
			  TRUE);
	out.accum = g_string_new (NULL);
	out.pp = parse_pos_init_sheet (&pp, origin);
	out.convs = origin->convs;
	cellref_as_string (&out, &cr, cell->base.sheet == origin);
	return g_string_free (out.accum, FALSE);
}

70 71
/* ------------------------------------------------------------------------- */

72 73 74 75 76 77 78
GType
gnm_solver_status_get_type (void)
{
	static GType etype = 0;
	if (etype == 0) {
		static GEnumValue const values[] = {
			{ GNM_SOLVER_STATUS_READY,
79 80
			  "GNM_SOLVER_STATUS_READY",
			  "ready"
81 82
			},
			{ GNM_SOLVER_STATUS_PREPARING,
83 84
			  "GNM_SOLVER_STATUS_PREPARING",
			  "preparing"
85 86
			},
			{ GNM_SOLVER_STATUS_PREPARED,
87 88
			  "GNM_SOLVER_STATUS_PREPARED",
			  "prepared"
89 90
			},
			{ GNM_SOLVER_STATUS_RUNNING,
91 92
			  "GNM_SOLVER_STATUS_RUNNING",
			  "running"
93 94
			},
			{ GNM_SOLVER_STATUS_DONE,
95 96
			  "GNM_SOLVER_STATUS_DONE",
			  "done"
97 98
			},
			{ GNM_SOLVER_STATUS_ERROR,
99 100
			  "GNM_SOLVER_STATUS_ERROR",
			  "error"
101 102
			},
			{ GNM_SOLVER_STATUS_CANCELLED,
103 104
			  "GNM_SOLVER_STATUS_CANCELLED",
			  "cancelled"
105 106 107
			},
			{ 0, NULL, NULL }
		};
108 109 110 111 112 113 114 115 116 117 118 119
		etype = g_enum_register_static ("GnmSolverStatus", values);
	}
	return etype;
}

GType
gnm_solver_problem_type_get_type (void)
{
	static GType etype = 0;
	if (etype == 0) {
		static GEnumValue const values[] = {
			{ GNM_SOLVER_MINIMIZE,
120 121
			  "GNM_SOLVER_MINIMIZE",
			  "minimize"
122 123
			},
			{ GNM_SOLVER_MAXIMIZE,
124 125
			  "GNM_SOLVER_MAXIMIZE",
			  "maximize"
126 127 128 129
			},
			{ 0, NULL, NULL }
		};
		etype = g_enum_register_static ("GnmSolverProblemType", values);
130 131 132 133 134 135
	}
	return etype;
}

/* ------------------------------------------------------------------------- */

136 137
static GObjectClass *gnm_solver_parent_class;

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
GnmSolverConstraint *
gnm_solver_constraint_new (Sheet *sheet)
{
	GnmSolverConstraint *res = g_new0 (GnmSolverConstraint, 1);
	dependent_managed_init (&res->lhs, sheet);
	dependent_managed_init (&res->rhs, sheet);
	return res;
}

void
gnm_solver_constraint_free (GnmSolverConstraint *c)
{
	gnm_solver_constraint_set_lhs (c, NULL);
	gnm_solver_constraint_set_rhs (c, NULL);
	g_free (c);
}

GnmSolverConstraint *
gnm_solver_constraint_dup (GnmSolverConstraint *c, Sheet *sheet)
{
	GnmSolverConstraint *res = gnm_solver_constraint_new (sheet);
	res->type = c->type;
160 161
	dependent_managed_set_expr (&res->lhs, c->lhs.texpr);
	dependent_managed_set_expr (&res->rhs, c->rhs.texpr);
162 163 164
	return res;
}

Morten Welinder's avatar
Morten Welinder committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
static GnmSolverConstraint *
gnm_solver_constraint_dup1 (GnmSolverConstraint *c)
{
	return gnm_solver_constraint_dup (c, c->lhs.sheet);
}

GType
gnm_solver_constraint_get_type (void)
{
	static GType t = 0;

	if (t == 0)
		t = g_boxed_type_register_static ("GnmSolverConstraint",
			 (GBoxedCopyFunc)gnm_solver_constraint_dup1,
			 (GBoxedFreeFunc)gnm_solver_constraint_free);
	return t;
}

183 184 185 186 187 188 189 190 191 192
gboolean
gnm_solver_constraint_equal (GnmSolverConstraint const *a,
			     GnmSolverConstraint const *b)
{
	return (a->type == b->type &&
		gnm_expr_top_equal (a->lhs.texpr, b->lhs.texpr) &&
		(!gnm_solver_constraint_has_rhs (a) ||
		 gnm_expr_top_equal (a->rhs.texpr, b->rhs.texpr)));
}

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
gboolean
gnm_solver_constraint_has_rhs (GnmSolverConstraint const *c)
{
	g_return_val_if_fail (c != NULL, FALSE);

	switch (c->type) {
	case GNM_SOLVER_LE:
	case GNM_SOLVER_GE:
	case GNM_SOLVER_EQ:
		return TRUE;
	case GNM_SOLVER_INTEGER:
	case GNM_SOLVER_BOOLEAN:
	default:
		return FALSE;
	}
}

gboolean
gnm_solver_constraint_valid (GnmSolverConstraint const *c,
			     GnmSolverParameters const *sp)
{
	GnmValue const *lhs;

	g_return_val_if_fail (c != NULL, FALSE);

	lhs = gnm_solver_constraint_get_lhs (c);
219
	if (lhs == NULL || !VALUE_IS_CELLRANGE (lhs))
220 221 222
		return FALSE;

	if (gnm_solver_constraint_has_rhs (c)) {
223
		GnmValue const *rhs = gnm_solver_constraint_get_rhs (c);
224 225
		if (rhs == NULL)
			return FALSE;
226
		if (VALUE_IS_CELLRANGE (rhs)) {
Morten Welinder's avatar
Morten Welinder committed
227
			GnmSheetRange srl, srr;
228

Morten Welinder's avatar
Morten Welinder committed
229 230
			gnm_sheet_range_from_value (&srl, lhs);
			gnm_sheet_range_from_value (&srr, rhs);
231

Morten Welinder's avatar
Morten Welinder committed
232 233
			if (range_width (&srl.range) != range_width (&srr.range) ||
			    range_height (&srl.range) != range_height (&srr.range))
234 235 236 237 238 239 240 241 242 243 244 245 246 247
				return FALSE;
		} else if (VALUE_IS_FLOAT (rhs)) {
			/* Nothing */
		} else
			return FALSE;
	}

	switch (c->type) {
	case GNM_SOLVER_INTEGER:
	case GNM_SOLVER_BOOLEAN: {
		GnmValue const *vinput = gnm_solver_param_get_input (sp);
		GnmSheetRange sr_input, sr_c;

		if (!vinput)
Morten Welinder's avatar
Morten Welinder committed
248
			break; /* No need to blame constraint.  */
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

		gnm_sheet_range_from_value (&sr_input, vinput);
		gnm_sheet_range_from_value (&sr_c, lhs);

		if (eval_sheet (sr_input.sheet, sp->sheet) !=
		    eval_sheet (sr_c.sheet, sp->sheet) ||
		    !range_contained (&sr_c.range, &sr_input.range))
			return FALSE;
		break;
	}

	default:
		break;
	}

	return TRUE;
}

Morten Welinder's avatar
Morten Welinder committed
267 268 269 270 271 272
/**
 * gnm_solver_constraint_get_lhs:
 * @c: GnmSolverConstraint
 *
 * Returns: (transfer none) (nullable): Get left-hand side of constraint @c.
 */
273 274 275 276 277 278 279
GnmValue const *
gnm_solver_constraint_get_lhs (GnmSolverConstraint const *c)
{
	GnmExprTop const *texpr = c->lhs.texpr;
	return texpr ? gnm_expr_top_get_constant (texpr) : NULL;
}

Morten Welinder's avatar
Morten Welinder committed
280 281 282 283 284
/**
 * gnm_solver_constraint_set_lhs:
 * @c: GnmSolverConstraint
 * @v: (transfer full) (nullable): new left-hand side
 */
285 286 287 288 289 290 291 292
void
gnm_solver_constraint_set_lhs (GnmSolverConstraint *c, GnmValue *v)
{
	GnmExprTop const *texpr = v ? gnm_expr_top_new_constant (v) : NULL;
	dependent_managed_set_expr (&c->lhs, texpr);
	if (texpr) gnm_expr_top_unref (texpr);
}

Morten Welinder's avatar
Morten Welinder committed
293 294 295 296 297 298
/**
 * gnm_solver_constraint_get_rhs:
 * @c: GnmSolverConstraint
 *
 * Returns: (transfer none) (nullable): Get right-hand side of constraint @c.
 */
299 300 301 302 303 304 305
GnmValue const *
gnm_solver_constraint_get_rhs (GnmSolverConstraint const *c)
{
	GnmExprTop const *texpr = c->rhs.texpr;
	return texpr ? gnm_expr_top_get_constant (texpr) : NULL;
}

Morten Welinder's avatar
Morten Welinder committed
306 307 308 309 310
/**
 * gnm_solver_constraint_set_rhs:
 * @c: GnmSolverConstraint
 * @v: (transfer full) (nullable): new right-hand side
 */
311 312 313 314 315 316 317 318
void
gnm_solver_constraint_set_rhs (GnmSolverConstraint *c, GnmValue *v)
{
	GnmExprTop const *texpr = v ? gnm_expr_top_new_constant (v) : NULL;
	dependent_managed_set_expr (&c->rhs, texpr);
	if (texpr) gnm_expr_top_unref (texpr);
}

Morten Welinder's avatar
Morten Welinder committed
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
/**
 * gnm_solver_constraint_get_part:
 * @c: GnmSolverConstraint
 * @sp: GnmSolverParameters
 * @i: part index
 * @lhs: (optional) (out): #GnmCell of left-hand side
 * @cl: (optional) (out): constant value of left-hand side
 * @rhs: (optional) (out): #GnmCell of right-hand side
 * @cr: (optional) (out): constant value of left-hand side
 *
 * This splits @c into parts and returns information about the @i'th part.
 * There will be multiple parts when the left-hand side is a cell range.
 *
 * Returns: %TRUE if the @i'th part exists.
 */
334 335 336 337 338 339
gboolean
gnm_solver_constraint_get_part (GnmSolverConstraint const *c,
				GnmSolverParameters const *sp, int i,
				GnmCell **lhs, gnm_float *cl,
				GnmCell **rhs, gnm_float *cr)
{
Morten Welinder's avatar
Morten Welinder committed
340
	GnmSheetRange sr;
341 342 343 344 345 346 347 348 349 350 351 352 353 354
	int h, w, dx, dy;
	GnmValue const *vl, *vr;

	if (cl)	*cl = 0;
	if (cr)	*cr = 0;
	if (lhs) *lhs = NULL;
	if (rhs) *rhs = NULL;

	if (!gnm_solver_constraint_valid (c, sp))
		return FALSE;

	vl = gnm_solver_constraint_get_lhs (c);
	vr = gnm_solver_constraint_get_rhs (c);

Morten Welinder's avatar
Morten Welinder committed
355 356 357
	gnm_sheet_range_from_value (&sr, vl);
	w = range_width (&sr.range);
	h = range_height (&sr.range);
358 359 360 361 362 363 364

	dy = i / w;
	dx = i % w;
	if (dy >= h)
		return FALSE;

	if (lhs)
Morten Welinder's avatar
Morten Welinder committed
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
		*lhs = sheet_cell_get (eval_sheet (sr.sheet, sp->sheet),
				       sr.range.start.col + dx,
				       sr.range.start.row + dy);

	if (!gnm_solver_constraint_has_rhs (c)) {
		/* Nothing */
	} else if (VALUE_IS_FLOAT (vr)) {
		if (cr)
			*cr = value_get_as_float (vr);
	} else {
		gnm_sheet_range_from_value (&sr, vr);
		if (rhs)
			*rhs = sheet_cell_get (eval_sheet (sr.sheet, sp->sheet),
					       sr.range.start.col + dx,
					       sr.range.start.row + dy);
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
	}

	return TRUE;
}

void
gnm_solver_constraint_set_old (GnmSolverConstraint *c,
			       GnmSolverConstraintType type,
			       int lhs_col, int lhs_row,
			       int rhs_col, int rhs_row,
			       int cols, int rows)
{
	GnmRange r;

	c->type = type;

	range_init (&r,
		    lhs_col, lhs_row,
		    lhs_col + (cols - 1), lhs_row + (rows - 1));
	gnm_solver_constraint_set_lhs
		(c, value_new_cellrange_r (NULL, &r));

	if (gnm_solver_constraint_has_rhs (c)) {
		range_init (&r,
			    rhs_col, rhs_row,
			    rhs_col + (cols - 1), rhs_row + (rows - 1));
		gnm_solver_constraint_set_rhs
			(c, value_new_cellrange_r (NULL, &r));
	} else
		gnm_solver_constraint_set_rhs (c, NULL);
}

void
gnm_solver_constraint_side_as_str (GnmSolverConstraint const *c,
				   Sheet const *sheet,
				   GString *buf, gboolean lhs)
{
	GnmExprTop const *texpr;

	texpr = lhs ? c->lhs.texpr : c->rhs.texpr;
	if (texpr) {
		GnmConventionsOut out;
		GnmParsePos pp;

		out.accum = buf;
		out.pp = parse_pos_init_sheet (&pp, sheet);
		out.convs = sheet->convs;
		gnm_expr_top_as_gstring (texpr, &out);
	} else
		g_string_append (buf,
				 value_error_name (GNM_ERROR_REF,
						   sheet->convs->output.translated));
}

char *
gnm_solver_constraint_as_str (GnmSolverConstraint const *c, Sheet *sheet)
{
	const char * const type_str[] =	{
		"\xe2\x89\xa4" /* "<=" */,
		"\xe2\x89\xa5" /* ">=" */,
Morten Welinder's avatar
Morten Welinder committed
440 441 442
		"=",
		N_("Int"),
		N_("Bool")
443
	};
Morten Welinder's avatar
Morten Welinder committed
444 445
	const char *type = type_str[c->type];
	gboolean translate = (c->type >= GNM_SOLVER_INTEGER);
446 447 448 449
	GString *buf = g_string_new (NULL);

	gnm_solver_constraint_side_as_str (c, sheet, buf, TRUE);
	g_string_append_c (buf, ' ');
Morten Welinder's avatar
Morten Welinder committed
450
	g_string_append (buf, translate ? _(type) : type);
451 452 453 454 455 456 457 458
	if (gnm_solver_constraint_has_rhs (c)) {
		g_string_append_c (buf, ' ');
		gnm_solver_constraint_side_as_str (c, sheet, buf, FALSE);
	}

	return g_string_free (buf, FALSE);
}

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
char *
gnm_solver_constraint_part_as_str (GnmSolverConstraint const *c, int i,
				   GnmSolverParameters *sp)
{
	const char * const type_str[] =	{
		"\xe2\x89\xa4" /* "<=" */,
		"\xe2\x89\xa5" /* ">=" */,
		"=",
		N_("Int"),
		N_("Bool")
	};
	const char *type = type_str[c->type];
	gboolean translate = (c->type >= GNM_SOLVER_INTEGER);
	GString *buf;
	gnm_float cl, cr;
	GnmCell *lhs, *rhs;

	if (!gnm_solver_constraint_get_part (c, sp, i, &lhs, &cl, &rhs, &cr))
		return NULL;

	buf = g_string_new (NULL);

	g_string_append (buf, cell_name (lhs));
	g_string_append_c (buf, ' ');
	g_string_append (buf, translate ? _(type) : type);
	if (gnm_solver_constraint_has_rhs (c)) {
		g_string_append_c (buf, ' ');
		g_string_append (buf, cell_name (rhs));
	}

	return g_string_free (buf, FALSE);
}

492 493
/* ------------------------------------------------------------------------- */

494 495 496 497 498
enum {
	SOLP_PROP_0,
	SOLP_PROP_SHEET,
	SOLP_PROP_PROBLEM_TYPE
};
499

500
static GObjectClass *gnm_solver_param_parent_class;
501

502 503
GnmSolverParameters *
gnm_solver_param_new (Sheet *sheet)
504
{
505 506 507
	return g_object_new (GNM_SOLVER_PARAMETERS_TYPE,
			     "sheet", sheet,
			     NULL);
508 509
}

Morten Welinder's avatar
Morten Welinder committed
510 511 512 513 514 515 516
/**
 * gnm_solver_param_dup:
 * @src: #GnmSolverParameters
 * @new_sheet: #Sheet
 *
 * Returns: (transfer full): duplicate @src, but for @new_sheet.
 */
517
GnmSolverParameters *
518
gnm_solver_param_dup (GnmSolverParameters *src, Sheet *new_sheet)
519
{
520 521
	GnmSolverParameters *dst = gnm_solver_param_new (new_sheet);
	GSList *l;
522

523 524 525
	dst->problem_type = src->problem_type;
	dependent_managed_set_expr (&dst->target, src->target.texpr);
	dependent_managed_set_expr (&dst->input, src->input.texpr);
526

527
	g_free (dst->options.scenario_name);
528 529
	dst->options = src->options;
	dst->options.algorithm = NULL;
Morten Welinder's avatar
Morten Welinder committed
530
	dst->options.scenario_name = g_strdup (src->options.scenario_name);
531
	gnm_solver_param_set_algorithm (dst, src->options.algorithm);
532 533

	/* Copy the constraints */
534 535 536 537
	for (l = src->constraints; l; l = l->next) {
		GnmSolverConstraint *old = l->data;
		GnmSolverConstraint *new =
			gnm_solver_constraint_dup (old, new_sheet);
538

539
		dst->constraints = g_slist_prepend (dst->constraints, new);
540
	}
541
	dst->constraints = g_slist_reverse (dst->constraints);
542

543
	return dst;
544 545
}

546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
gboolean
gnm_solver_param_equal (GnmSolverParameters const *a,
			GnmSolverParameters const *b)
{
	GSList *la, *lb;

	if (a->sheet != b->sheet ||
	    a->problem_type != b->problem_type ||
	    !gnm_expr_top_equal (a->target.texpr, b->target.texpr) ||
	    !gnm_expr_top_equal (a->input.texpr, b->input.texpr) ||
	    a->options.max_time_sec != b->options.max_time_sec ||
	    a->options.max_iter != b->options.max_iter ||
	    a->options.algorithm != b->options.algorithm ||
	    a->options.model_type != b->options.model_type ||
            a->options.assume_non_negative != b->options.assume_non_negative ||
            a->options.assume_discrete != b->options.assume_discrete ||
            a->options.automatic_scaling != b->options.automatic_scaling ||
            a->options.program_report != b->options.program_report ||
564
            a->options.sensitivity_report != b->options.sensitivity_report ||
565
            a->options.add_scenario != b->options.add_scenario ||
566 567
	    strcmp (a->options.scenario_name, b->options.scenario_name) ||
	    a->options.gradient_order != b->options.gradient_order)
568 569 570 571 572 573 574 575 576 577 578 579 580
		return FALSE;

	for (la = a->constraints, lb = b->constraints;
	     la && lb;
	     la = la->next, lb = lb->next) {
		GnmSolverConstraint *ca = la->data;
		GnmSolverConstraint *cb = lb->data;
		if (!gnm_solver_constraint_equal (ca, cb))
			return FALSE;
	}
	return la == lb;
}

Morten Welinder's avatar
Morten Welinder committed
581 582 583 584 585 586
/**
 * gnm_solver_param_get_input:
 * @sp: #GnmSolverParameters
 *
 * Returns: (transfer none) (nullable): the input cell area.
 */
587 588 589 590 591 592 593 594
GnmValue const *
gnm_solver_param_get_input (GnmSolverParameters const *sp)
{
	return sp->input.texpr
		? gnm_expr_top_get_constant (sp->input.texpr)
		: NULL;
}

Morten Welinder's avatar
Morten Welinder committed
595 596 597 598 599
/**
 * gnm_solver_param_set_input:
 * @sp: #GnmSolverParameters
 * @v: (transfer full) (nullable): new input area
 */
600 601 602 603 604 605 606 607 608 609 610
void
gnm_solver_param_set_input (GnmSolverParameters *sp, GnmValue *v)
{
	GnmExprTop const *texpr = v ? gnm_expr_top_new_constant (v) : NULL;
	dependent_managed_set_expr (&sp->input, texpr);
	if (texpr) gnm_expr_top_unref (texpr);
}

static GnmValue *
cb_grab_cells (GnmCellIter const *iter, gpointer user)
{
Morten Welinder's avatar
Morten Welinder committed
611
	GPtrArray *input_cells = user;
612 613 614 615 616
	GnmCell *cell;

	if (NULL == (cell = iter->cell))
		cell = sheet_cell_create (iter->pp.sheet,
			iter->pp.eval.col, iter->pp.eval.row);
Morten Welinder's avatar
Morten Welinder committed
617
	g_ptr_array_add (input_cells, cell);
618 619 620
	return NULL;
}

Morten Welinder's avatar
Morten Welinder committed
621 622 623 624 625 626
/**
 * gnm_solver_param_get_input_cells:
 * @sp: #GnmSolverParameters
 *
 * Returns: (element-type GnmCell) (transfer container):
 */
Morten Welinder's avatar
Morten Welinder committed
627
GPtrArray *
628 629 630
gnm_solver_param_get_input_cells (GnmSolverParameters const *sp)
{
	GnmValue const *vr = gnm_solver_param_get_input (sp);
Morten Welinder's avatar
Morten Welinder committed
631
	GPtrArray *input_cells = g_ptr_array_new ();
632

Morten Welinder's avatar
Morten Welinder committed
633 634 635 636 637 638 639
	if (vr) {
		GnmEvalPos ep;
		eval_pos_init_sheet (&ep, sp->sheet);
		workbook_foreach_cell_in_range (&ep, vr, CELL_ITER_ALL,
						cb_grab_cells,
						input_cells);
	}
640

Morten Welinder's avatar
Morten Welinder committed
641
	return input_cells;
642 643 644 645 646
}

void
gnm_solver_param_set_target (GnmSolverParameters *sp, GnmCellRef const *cr)
{
647 648 649 650 651 652 653 654 655 656 657 658 659
	if (cr) {
		GnmExprTop const *texpr;
		GnmCellRef cr2 = *cr;
		/* Make reference absolute to avoid tracking problems on row/col
		   insert.  */
		cr2.row_relative = FALSE;
		cr2.col_relative = FALSE;

		texpr = gnm_expr_top_new (gnm_expr_new_cellref (&cr2));
		dependent_managed_set_expr (&sp->target, texpr);
		gnm_expr_top_unref (texpr);
	} else
		dependent_managed_set_expr (&sp->target, NULL);
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
}

const GnmCellRef *
gnm_solver_param_get_target (GnmSolverParameters const *sp)
{
	return sp->target.texpr
		? gnm_expr_top_get_cellref (sp->target.texpr)
		: NULL;
}

GnmCell *
gnm_solver_param_get_target_cell (GnmSolverParameters const *sp)
{
	const GnmCellRef *cr = gnm_solver_param_get_target (sp);
	if (!cr)
		return NULL;

        return sheet_cell_get (eval_sheet (cr->sheet, sp->sheet),
			       cr->col, cr->row);
}

681 682 683 684 685 686 687
void
gnm_solver_param_set_algorithm (GnmSolverParameters *sp,
				GnmSolverFactory *algo)
{
	sp->options.algorithm = algo;
}

688 689 690 691 692 693
gboolean
gnm_solver_param_valid (GnmSolverParameters const *sp, GError **err)
{
	GSList *l;
	int i;
	GnmCell *target_cell;
Morten Welinder's avatar
Morten Welinder committed
694 695
	GPtrArray *input_cells;
	unsigned ui;
696 697 698 699 700 701 702 703 704

	target_cell = gnm_solver_param_get_target_cell (sp);
	if (!target_cell) {
		g_set_error (err,
			     go_error_invalid (),
			     0,
			     _("Invalid solver target"));
		return FALSE;
	}
705
	gnm_cell_eval (target_cell);
706 707 708 709

	if (!gnm_cell_has_expr (target_cell) ||
	    target_cell->value == NULL ||
	    !VALUE_IS_FLOAT (target_cell->value)) {
Morten Welinder's avatar
Morten Welinder committed
710
		char *tcname = gnm_solver_cell_name (target_cell, sp->sheet);
711 712 713 714
		g_set_error (err,
			     go_error_invalid (),
			     0,
			     _("Target cell, %s, must contain a formula that evaluates to a number"),
Morten Welinder's avatar
Morten Welinder committed
715 716
			     tcname);
		g_free (tcname);
717 718 719 720 721 722 723 724 725 726 727
		return FALSE;
	}

	if (!gnm_solver_param_get_input (sp)) {
		g_set_error (err,
			     go_error_invalid (),
			     0,
			     _("Invalid solver input range"));
		return FALSE;
	}
	input_cells = gnm_solver_param_get_input_cells (sp);
Morten Welinder's avatar
Morten Welinder committed
728 729
	for (ui = 0; ui < input_cells->len; ui++) {
		GnmCell *cell = g_ptr_array_index (input_cells, ui);
730
		if (gnm_cell_has_expr (cell)) {
Morten Welinder's avatar
Morten Welinder committed
731
			char *cname = gnm_solver_cell_name (cell, sp->sheet);
732 733 734 735
			g_set_error (err,
				     go_error_invalid (),
				     0,
				     _("Input cell %s contains a formula"),
Morten Welinder's avatar
Morten Welinder committed
736 737
				     cname);
			g_free (cname);
Morten Welinder's avatar
Morten Welinder committed
738
			g_ptr_array_free (input_cells, TRUE);
739 740 741
			return FALSE;
		}
	}
Morten Welinder's avatar
Morten Welinder committed
742
	g_ptr_array_free (input_cells, TRUE);
743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758

	for (i = 1, l = sp->constraints; l; i++, l = l->next) {
		GnmSolverConstraint *c = l->data;
		if (!gnm_solver_constraint_valid (c, sp)) {
			g_set_error (err,
				     go_error_invalid (),
				     0,
				     _("Solver constraint #%d is invalid"),
				     i);
			return FALSE;
		}
	}

	return TRUE;
}

759 760 761 762 763 764 765 766 767 768 769 770 771 772 773
static GObject *
gnm_solver_param_constructor (GType type,
			      guint n_construct_properties,
			      GObjectConstructParam *construct_params)
{
	GObject *obj;
	GnmSolverParameters *sp;

	obj = gnm_solver_param_parent_class->constructor
		(type, n_construct_properties, construct_params);
	sp = GNM_SOLVER_PARAMETERS (obj);

	dependent_managed_init (&sp->target, sp->sheet);
	dependent_managed_init (&sp->input, sp->sheet);

774
	sp->options.model_type = GNM_SOLVER_LP;
775 776
	sp->options.max_iter = 1000;
	sp->options.max_time_sec = 60;
777 778
	sp->options.assume_non_negative = TRUE;
	sp->options.scenario_name = g_strdup ("Optimal");
779
	sp->options.gradient_order = 10;
780 781 782 783 784 785 786 787 788 789 790

	return obj;
}

static void
gnm_solver_param_finalize (GObject *obj)
{
	GnmSolverParameters *sp = GNM_SOLVER_PARAMETERS (obj);

	dependent_managed_set_expr (&sp->target, NULL);
	dependent_managed_set_expr (&sp->input, NULL);
791
	g_slist_free_full (sp->constraints,
792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
			      (GFreeFunc)gnm_solver_constraint_free);
	g_free (sp->options.scenario_name);

	gnm_solver_param_parent_class->finalize (obj);
}

static void
gnm_solver_param_get_property (GObject *object, guint property_id,
			       GValue *value, GParamSpec *pspec)
{
	GnmSolverParameters *sp = (GnmSolverParameters *)object;

	switch (property_id) {
	case SOLP_PROP_SHEET:
		g_value_set_object (value, sp->sheet);
		break;

	case SOLP_PROP_PROBLEM_TYPE:
		g_value_set_enum (value, sp->problem_type);
		break;

	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
		break;
	}
}

static void
gnm_solver_param_set_property (GObject *object, guint property_id,
			       GValue const *value, GParamSpec *pspec)
{
	GnmSolverParameters *sp = (GnmSolverParameters *)object;

	switch (property_id) {
	case SOLP_PROP_SHEET:
		/* We hold no ref.  */
		sp->sheet = g_value_get_object (value);
		break;

	case SOLP_PROP_PROBLEM_TYPE:
		sp->problem_type = g_value_get_enum (value);
		break;

	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
		break;
	}
}

static void
gnm_solver_param_class_init (GObjectClass *object_class)
{
	gnm_solver_param_parent_class = g_type_class_peek_parent (object_class);

	object_class->constructor = gnm_solver_param_constructor;
847
	object_class->finalize = gnm_solver_param_finalize;
848 849 850 851
	object_class->set_property = gnm_solver_param_set_property;
	object_class->get_property = gnm_solver_param_get_property;

	g_object_class_install_property (object_class, SOLP_PROP_SHEET,
852 853 854
		g_param_spec_object ("sheet",
				      P_("Sheet"),
				      P_("Sheet"),
855 856 857 858 859 860
				      GNM_SHEET_TYPE,
				      GSF_PARAM_STATIC |
				      G_PARAM_CONSTRUCT_ONLY |
				      G_PARAM_READWRITE));

	g_object_class_install_property (object_class, SOLP_PROP_PROBLEM_TYPE,
861 862 863
		g_param_spec_enum ("problem-type",
				    P_("Problem Type"),
				    P_("Problem Type"),
864 865 866 867 868 869 870 871 872
				    GNM_SOLVER_PROBLEM_TYPE_TYPE,
				    GNM_SOLVER_MAXIMIZE,
				    GSF_PARAM_STATIC |
				    G_PARAM_READWRITE));
}

GSF_CLASS (GnmSolverParameters, gnm_solver_param,
	   gnm_solver_param_class_init, NULL, G_TYPE_OBJECT)

873 874
/* ------------------------------------------------------------------------- */

875 876 877 878 879 880 881 882 883 884 885 886
enum {
	SOL_SIG_PREPARE,
	SOL_SIG_START,
	SOL_SIG_STOP,
	SOL_SIG_LAST
};

static guint solver_signals[SOL_SIG_LAST] = { 0 };

enum {
	SOL_PROP_0,
	SOL_PROP_STATUS,
887
	SOL_PROP_REASON,
888
	SOL_PROP_PARAMS,
889
	SOL_PROP_RESULT,
890
	SOL_PROP_SENSITIVITY,
891
	SOL_PROP_STARTTIME,
892 893
	SOL_PROP_ENDTIME,
	SOL_PROP_FLIP_SIGN
894 895 896 897
};

static GObjectClass *gnm_solver_parent_class;

898
static void gnm_solver_update_derived (GnmSolver *sol);
899

900 901 902 903 904 905 906 907 908 909 910 911
static void
gnm_solver_dispose (GObject *obj)
{
	GnmSolver *sol = GNM_SOLVER (obj);

	if (sol->status == GNM_SOLVER_STATUS_RUNNING) {
		gboolean ok = gnm_solver_stop (sol, NULL);
		if (ok) {
			g_warning ("Failed to stop solver -- now what?");
		}
	}

912 913
	g_free (sol->reason);
	sol->reason = NULL;
914

915 916 917 918 919
	if (sol->result) {
		g_object_unref (sol->result);
		sol->result = NULL;
	}

Morten Welinder's avatar
Morten Welinder committed
920 921 922 923 924
	if (sol->sensitivity) {
		g_object_unref (sol->sensitivity);
		sol->sensitivity = NULL;
	}

925 926 927
	if (sol->params) {
		g_object_unref (sol->params);
		sol->params = NULL;
928
		gnm_solver_update_derived (sol);
929 930
	}

931 932 933 934 935 936
	if (sol->gradient) {
		sol->gradient_status = 0;
		g_ptr_array_unref (sol->gradient);
		sol->gradient = NULL;
	}

937 938 939 940 941 942
	if (sol->hessian) {
		sol->hessian_status = 0;
		g_ptr_array_unref (sol->hessian);
		sol->hessian = NULL;
	}

943 944 945 946 947 948 949 950 951 952 953 954 955 956
	gnm_solver_parent_class->dispose (obj);
}

static void
gnm_solver_get_property (GObject *object, guint property_id,
			 GValue *value, GParamSpec *pspec)
{
	GnmSolver *sol = (GnmSolver *)object;

	switch (property_id) {
	case SOL_PROP_STATUS:
		g_value_set_enum (value, sol->status);
		break;

957 958 959 960
	case SOL_PROP_REASON:
		g_value_set_string (value, sol->reason);
		break;

961
	case SOL_PROP_PARAMS:
962
		g_value_set_object (value, sol->params);
963 964 965 966 967 968
		break;

	case SOL_PROP_RESULT:
		g_value_set_object (value, sol->result);
		break;

969 970 971 972
	case SOL_PROP_SENSITIVITY:
		g_value_set_object (value, sol->sensitivity);
		break;

973 974 975 976 977 978 979 980
	case SOL_PROP_STARTTIME:
		g_value_set_double (value, sol->starttime);
		break;

	case SOL_PROP_ENDTIME:
		g_value_set_double (value, sol->endtime);
		break;

981 982 983 984
	case SOL_PROP_FLIP_SIGN:
		g_value_set_boolean (value, sol->flip_sign);
		break;

985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
		break;
	}
}

static void
gnm_solver_set_property (GObject *object, guint property_id,
			 GValue const *value, GParamSpec *pspec)
{
	GnmSolver *sol = (GnmSolver *)object;

	switch (property_id) {
	case SOL_PROP_STATUS:
		gnm_solver_set_status (sol, g_value_get_enum (value));
		break;

1002 1003 1004 1005
	case SOL_PROP_REASON:
		gnm_solver_set_reason (sol, g_value_get_string (value));
		break;

1006 1007
	case SOL_PROP_PARAMS: {
		GnmSolverParameters *p = g_value_dup_object (value);
1008
		if (sol->params) g_object_unref (sol->params);
1009 1010
		sol->params = p;
		gnm_solver_update_derived (sol);
1011
		break;
1012
	}
1013

1014 1015
	case SOL_PROP_RESULT: {
		GnmSolverResult *r = g_value_dup_object (value);
1016
		if (sol->result) g_object_unref (sol->result);
1017
		sol->result = r;
1018
		break;
1019
	}
1020

1021 1022 1023 1024 1025 1026 1027
	case SOL_PROP_SENSITIVITY: {
		GnmSolverSensitivity *s = g_value_dup_object (value);
		if (sol->sensitivity) g_object_unref (sol->sensitivity);
		sol->sensitivity = s;
		break;
	}

1028 1029 1030 1031 1032 1033 1034 1035
	case SOL_PROP_STARTTIME:
		sol->starttime = g_value_get_double (value);
		break;

	case SOL_PROP_ENDTIME:
		sol->endtime = g_value_get_double (value);
		break;

1036 1037 1038 1039
	case SOL_PROP_FLIP_SIGN:
		sol->flip_sign = g_value_get_boolean (value);
		break;

1040 1041 1042 1043 1044 1045
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
		break;
	}
}

1046
/**
Morten Welinder's avatar
Morten Welinder committed
1047
 * gnm_solver_prepare: (virtual prepare)
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
 * @sol: solver
 * @wbc: control for user interaction
 * @err: location to store error
 *
 * Prepare for solving.  Preparation need not do anything, but may include
 * such tasks as checking that the model is valid for the solver and
 * locating necessary external programs.
 *
 * Returns: %TRUE ok success, %FALSE on error.
 */
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
gboolean
gnm_solver_prepare (GnmSolver *sol, WorkbookControl *wbc, GError **err)
{
	gboolean res;

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

	g_signal_emit (sol, solver_signals[SOL_SIG_PREPARE], 0, wbc, err, &res);
	return res;
}

1070
/**
Morten Welinder's avatar
Morten Welinder committed
1071
 * gnm_solver_start: (virtual start)
1072 1073 1074 1075 1076 1077 1078 1079
 * @sol: solver
 * @wbc: control for user interaction
 * @err: location to store error
 *
 * Start the solving process.  If needed, the solver will be prepared first.
 *
 * Returns: %TRUE ok success, %FALSE on error.
 */
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
gboolean
gnm_solver_start (GnmSolver *sol, WorkbookControl *wbc, GError **err)
{
	gboolean res;

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

	if (sol->status == GNM_SOLVER_STATUS_READY) {
		res = gnm_solver_prepare (sol, wbc, err);
		if (!res)
			return FALSE;
	}

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

	g_signal_emit (sol, solver_signals[SOL_SIG_START], 0, wbc, err, &res);
	return res;
}

1101
/**
Morten Welinder's avatar
Morten Welinder committed
1102
 * gnm_solver_stop: (virtual stop)
1103 1104 1105 1106 1107 1108 1109
 * @sol: solver
 * @err: location to store error
 *
 * Terminate the currently-running solver.
 *
 * Returns: %TRUE ok success, %FALSE on error.
 */
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
gboolean
gnm_solver_stop (GnmSolver *sol, GError **err)
{
	gboolean res;

	g_return_val_if_fail (GNM_IS_SOLVER (sol), FALSE);

	g_signal_emit (sol, solver_signals[SOL_SIG_STOP], 0, err, &res);
	return res;
}

1121 1122 1123 1124 1125 1126 1127 1128 1129
static double
current_time (void)
{
	GTimeVal now;
	g_get_current_time (&now);
	return now.tv_sec + (now.tv_usec / 1e6);
}


1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
double
gnm_solver_elapsed (GnmSolver *solver)
{
	double endtime;

	g_return_val_if_fail (GNM_IS_SOLVER (solver), 0);

	if (solver->starttime < 0)
		return 0;

	endtime = (solver->endtime < 0)
1141
		? current_time ()
1142 1143 1144 1145 1146
		: solver->endtime;

	return endtime - solver->starttime;
}

1147
gboolean
1148
gnm_solver_check_timeout (GnmSolver *solver)
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
{
	GnmSolverParameters *sp;

	g_return_val_if_fail (GNM_IS_SOLVER (solver), FALSE);

	sp = solver->params;

	if (solver->status != GNM_SOLVER_STATUS_RUNNING)
		return FALSE;

	if (gnm_solver_elapsed (solver) <= sp->options.max_time_sec)
		return FALSE;

1162 1163
	gnm_solver_stop (solver, NULL);
	gnm_solver_set_reason (solver, _("Timeout"));
1164 1165 1166 1167

	return TRUE;
}

1168 1169 1170
void
gnm_solver_store_result (GnmSolver *sol)
{
1171
	gnm_float const *solution;
Morten Welinder's avatar
Morten Welinder committed
1172
	unsigned ui, n = sol->input_cells->len;
1173 1174 1175 1176 1177

	g_return_if_fail (GNM_IS_SOLVER (sol));
	g_return_if_fail (sol->result != NULL);
	g_return_if_fail (sol->result->solution);

Morten Welinder's avatar
Morten Welinder committed
1178 1179 1180
	solution = gnm_solver_has_solution (sol)
		? sol->result->solution
		: NULL;
1181

Morten Welinder's avatar
Morten Welinder committed
1182 1183
	for (ui = 0; ui < n; ui++) {
		GnmCell *cell = g_ptr_array_index (sol->input_cells, ui);
1184
		GnmValue *v = solution ? value_new_float (solution[ui])	: value_new_error_NA (NULL);
Morten Welinder's avatar
Morten Welinder committed
1185 1186
		gnm_cell_set_value (cell, v);
		cell_queue_recalc (cell);
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
	}
}

gboolean
gnm_solver_finished (GnmSolver *sol)
{
	g_return_val_if_fail (GNM_IS_SOLVER (sol), TRUE);

	switch (sol->status) {

	case GNM_SOLVER_STATUS_READY:
	case GNM_SOLVER_STATUS_PREPARING:
	case GNM_SOLVER_STATUS_PREPARED:
	case GNM_SOLVER_STATUS_RUNNING:
		return FALSE;
	case GNM_SOLVER_STATUS_DONE:
	default:
	case GNM_SOLVER_STATUS_ERROR:
	case GNM_SOLVER_STATUS_CANCELLED:
		return TRUE;
	}
}

void
gnm_solver_set_status (GnmSolver *solver, GnmSolverStatus status)
{
1213 1214 1215 1216
	GnmSolverStatus old_status;

	g_return_if_fail (GNM_IS_SOLVER (solver));

1217 1218 1219
	if (status == solver->status)
		return;

1220 1221
	gnm_solver_set_reason (solver, NULL);

1222
	old_status = solver->status;
1223 1224
	solver->status = status;
	g_object_notify (G_OBJECT (solver), "status");
1225 1226 1227

	if (status == GNM_SOLVER_STATUS_RUNNING)
		g_object_set (G_OBJECT (solver),
1228
			      "starttime", current_time (),
1229 1230 1231 1232
			      "endtime", (double)-1,
			      NULL);
	else if (old_status == GNM_SOLVER_STATUS_RUNNING)
		g_object_set (G_OBJECT (solver),
1233
			      "endtime", current_time (),
1234
			      NULL);
1235 1236
}

1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
void
gnm_solver_set_reason (GnmSolver *solver, const char *reason)
{
	g_return_if_fail (GNM_IS_SOLVER (solver));

	if (g_strcmp0 (reason, solver->reason) == 0)
		return;

	g_free (solver->reason);
	solver->reason = g_strdup (reason);
1247 1248

	g_object_notify (G_OBJECT (solver), "reason");
1249 1250 1251
}


Morten Welinder's avatar
Morten Welinder committed
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
gboolean
gnm_solver_has_solution (GnmSolver *solver)
{
	if (solver->result == NULL)
		return FALSE;

	switch (solver->result->quality) {
	case GNM_SOLVER_RESULT_NONE:
	case GNM_SOLVER_RESULT_INFEASIBLE:
	case GNM_SOLVER_RESULT_UNBOUNDED:
	default:
		return FALSE;
	case GNM_SOLVER_RESULT_FEASIBLE:
	case GNM_SOLVER_RESULT_OPTIMAL:
		return TRUE;
	}
}

gboolean
gnm_solver_check_constraints (GnmSolver *solver)
{
	GSList *l;
	GnmSolverParameters *sp = solver->params;
1275
	GnmCell *target_cell;
Morten Welinder's avatar
Morten Welinder committed
1276

1277 1278
	if (sp->options.assume_non_negative ||
	    sp->options.assume_discrete) {
Morten Welinder's avatar
Morten Welinder committed
1279
		unsigned ui;
1280
		gboolean bad;
1281

1282 1283
		for (ui = 0; ui < solver->input_cells->len; ui++) {
			GnmCell *cell = g_ptr_array_index (solver->input_cells, ui);
1284 1285 1286 1287
			gnm_float val;

			gnm_cell_eval (cell);
			val = value_get_as_float (cell->value);
1288 1289 1290 1291 1292 1293
			if (sp->options.assume_non_negative && val < 0)
				break;
			if (sp->options.assume_discrete &&
			    val != gnm_floor (val))
				break;
		}
1294
		bad = (ui < solver->input_cells->len);
Morten Welinder's avatar
Morten Welinder committed
1295

1296
		if (bad)
1297
			return FALSE;
Morten Welinder's avatar
Morten Welinder committed
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
	}

	for (l = sp->constraints; l; l = l->next) {
		GnmSolverConstraint *c = l->data;
		int i;
		gnm_float cl, cr;
		GnmCell *lhs, *rhs;

		for (i = 0;
		     gnm_solver_constraint_get_part (c, sp, i,
						     &lhs, &cl,
						     &rhs, &cr);
		     i++) {
1311 1312
			if (lhs) {
				gnm_cell_eval (lhs);
Morten Welinder's avatar
Morten Welinder committed
1313
				cl = value_get_as_float (lhs->value);
1314 1315 1316
			}
			if (rhs) {
				gnm_cell_eval (rhs);
Morten Welinder's avatar
Morten Welinder committed
1317
				cr = value_get_as_float (rhs->value);
1318
			}
Morten Welinder's avatar
Morten Welinder committed
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347

			switch (c->type) {
			case GNM_SOLVER_INTEGER:
				if (cl == gnm_floor (cl))
					continue;
				return FALSE;
			case GNM_SOLVER_BOOLEAN:
				if (cl == 0 || cl == 1)
					continue;
				return FALSE;
			case GNM_SOLVER_LE:
				if (cl <= cr)
					continue;
				return FALSE;
			case GNM_SOLVER_GE:
				if (cl >= cr)
					continue;
				return FALSE;
			case GNM_SOLVER_EQ:
				if (cl == cr)
					continue;
				return FALSE;
			default:
				g_assert_not_reached ();
				return FALSE;
			}
		}
	}

1348 1349 1350 1351 1352
	target_cell = gnm_solver_param_get_target_cell (sp);
	gnm_cell_eval (target_cell);
	if (!target_cell || !VALUE_IS_NUMBER (target_cell->value))
		return FALSE;

Morten Welinder's avatar
Morten Welinder committed
1353 1354 1355
	return TRUE;
}

1356 1357 1358
gboolean
gnm_solver_saveas (GnmSolver *solver, WorkbookControl *wbc,
		   GOFileSaver *fs,
1359
		   const char *templ, char **filename,
1360 1361 1362 1363 1364 1365 1366 1367 1368
		   GError **err)
{
	int fd;
	GsfOutput *output;
	FILE *file;
	GOIOContext *io_context;
	gboolean ok;
	WorkbookView *wbv = wb_control_view (wbc);

1369
	fd = g_file_open_tmp (templ, filename, err);
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
	if (fd == -1) {
		g_set_error (err, G_FILE_ERROR, 0,
			     _("Failed to create file for linear program"));
		return FALSE;
	}

	file = fdopen (fd, "wb");
	if (!file) {
		/* This shouldn't really happen.  */
		close (fd);
		g_set_error (err, G_FILE_ERROR, 0,
			     _("Failed to create linear program file"));
		return FALSE;
	}

1385 1386 1387 1388 1389
	/* Give the saver a way to talk to the solver.  */
	g_object_set_data_full (G_OBJECT (fs),
				"solver", g_object_ref (solver),
				(GDestroyNotify)g_object_unref);

1390 1391
	output = gsf_output_stdio_new_FILE (*filename, file, TRUE);
	io_context = go_io_context_new (GO_CMD_CONTEXT (wbc));
1392
	workbook_view_save_to_output (wbv, fs, output, io_context);
1393 1394 1395 1396
	ok = !go_io_error_occurred (io_context);
	g_object_unref (io_context);
	g_object_unref (output);

1397 1398
	g_object_set_data (G_OBJECT (fs), "solver", NULL);

1399 1400 1401 1402 1403 1404 1405 1406 1407
	if (!ok) {
		g_set_error (err, G_FILE_ERROR, 0,
			     _("Failed to save linear program"));
		return FALSE;
	}

	return TRUE;
}

1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
int
gnm_solver_cell_index (GnmSolver *solver, GnmCell const *cell)
{
	gpointer idx;

	if (g_hash_table_lookup_extended (solver->index_from_cell,
					  (gpointer)cell,
					  NULL, &idx))
		return GPOINTER_TO_INT (idx);
	else
		return -1;
}

static int
cell_in_cr (GnmSolver *sol, GnmCell const *cell, gboolean follow)
1423
{
1424 1425
	int idx;

1426
	if (!cell)
1427
		return -1;
1428

1429 1430
	idx = gnm_solver_cell_index (sol, cell);
	if (idx < 0 && follow) {
Morten Welinder's avatar
Morten Welinder committed
1431
		/* If the expression is just =X42 then look at X42 instead.
1432 1433 1434 1435 1436 1437 1438 1439
		   This is because the mps loader uses such a level of
		   indirection.  Note: we follow only one such step.  */
		GnmCellRef const *cr = gnm_expr_top_get_cellref (cell->base.texpr);
		GnmCellRef cr2;
		GnmCell const *new_cell;
		GnmEvalPos ep;

		if (!cr)
1440
			return -1;
1441 1442 1443 1444 1445

		eval_pos_init_cell (&ep, cell);
		gnm_cellref_make_abs (&cr2, cr, &ep);
		new_cell = sheet_cell_get (eval_sheet (cr2.sheet, cell->base.sheet),
					   cr2.col, cr2.row);
1446
		return cell_in_cr (sol, new_cell, FALSE);
1447 1448
	}

1449
	return idx;
1450 1451 1452
}

static gboolean
1453
cell_is_constant (GnmCell *cell, gnm_float *pc)
1454 1455 1456 1457 1458 1459 1460
{
	if (!cell)
		return TRUE;

	if (cell->base.texpr)
		return FALSE;

1461
	gnm_cell_eval (cell);
1462 1463 1464 1465 1466
	*pc = value_get_as_float (cell->value);
	return TRUE;
}

#define SET_LOWER(l_)						\
1467
	do {							\
1468
		sol->min[idx] = MAX (sol->min[idx], (l_));	\
1469
	} while (0)
1470 1471

#define SET_UPPER(l_)						\
1472
	do {							\
1473
		sol->max[idx] = MIN (sol->max[idx], (l_));	\
1474
	} while (0)
1475 1476 1477 1478



static void
1479
gnm_solver_update_derived (GnmSolver *sol)
1480
{
1481
	GnmSolverParameters *params = sol->params;
1482

1483 1484 1485 1486
	if (sol->input_cells) {
		g_ptr_array_free (sol->input_cells, TRUE);
		sol->input_cells = NULL;
	}
1487

1488 1489 1490
	if (sol->index_from_cell) {
		g_hash_table_destroy (sol->index_from_cell);
		sol->index_from_cell = NULL;
1491
	}
1492
	sol->target = NULL;
1493

1494 1495
	g_free (sol->min);
	sol->min = NULL;
1496

1497 1498
	g_free (sol->max);
	sol->max = NULL;
1499

1500 1501
	g_free (sol->discrete);
	sol->discrete = NULL;
1502

1503 1504 1505
	if (params) {
		unsigned ui, n;
		GSList *l;
1506

1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
		sol->target = gnm_solver_param_get_target_cell (params);

		sol->input_cells = gnm_solver_param_get_input_cells (params);

		n = sol->input_cells->len;
		sol->index_from_cell = g_hash_table_new (g_direct_hash, g_direct_equal);
		for (ui = 0; ui < n; ui++) {
			GnmCell *cell = g_ptr_array_index (sol->input_cells, ui);
			g_hash_table_insert (sol->index_from_cell, cell, GUINT_TO_POINTER (ui));
		}

		sol->min = g_new (gnm_float, n);
		sol->max = g_new (gnm_float, n);
		sol->discrete = g_new (guint8, n);
		for (ui = 0; ui < n; ui++) {
			sol->min[ui] = params->options.assume_non_negative ? 0 : gnm_ninf;
			sol->max[ui] = gnm_pinf;
			sol->discrete[ui] = params->options.assume_discrete;
		}

		for (l = params->constraints; l; l = l->next) {
			GnmSolverConstraint *c = l->data;
			int i;
			gnm_float cl, cr;
			GnmCell *lhs, *rhs;

			for (i = 0;
			     gnm_solver_constraint_get_part (c, params, i,
							     &lhs, &cl,
							     &rhs, &cr);
			     i++) {
				int idx = cell_in_cr (sol, lhs, TRUE);

				if (idx < 0)
					continue;
				if (!cell_is_constant (rhs, &cr))
					continue;

				switch (c->type) {
				case GNM_SOLVER_INTEGER:
					sol->discrete[idx] = TRUE;
					break;
				case GNM_SOLVER_BOOLEAN:
					sol->discrete[idx] = TRUE;
					SET_LOWER (0.0);
					SET_UPPER (1.0);
					break;
				case GNM_SOLVER_LE:
					SET_UPPER (cr);
					break;
				case GNM_SOLVER_GE:
					SET_LOWER (cr);
					break;
				case GNM_SOLVER_EQ:
					SET_LOWER (cr);
					SET_UPPER (cr);
					break;

				default:
					g_assert_not_reached ();
					break;
				}
1569 1570
			}
		}
1571

1572 1573 1574 1575 1576 1577 1578 1579 1580
		/*
		 * If parameters are discrete, narrow the range by eliminating
		 * the fractional part of the limits.
		 */
		for (ui = 0; ui < n; ui++) {
			if (sol->discrete[ui]) {
				sol->min[ui] = gnm_ceil (sol->min[ui]);
				sol->max[ui] = gnm_floor (sol->max[ui]);
			}
1581 1582
		}
	}
1583 1584 1585 1586 1587
}

#undef SET_LOWER
#undef SET_UPPER

1588

1589 1590
#define ADD_HEADER(txt_) do {			\
	dao_set_bold (dao, 0, R, 0, R);		\
1591
	dao_set_cell (dao, 0, R, (txt_));	\
1592 1593 1594 1595 1596 1597
	R++;					\
} while (0)

#define AT_LIMIT(s_,l_) \
  (gnm_finite (l_) ? gnm_abs ((s_) - (l_)) <= (gnm_abs ((s_)) + gnm_abs ((l_))) / 1e10 : (s_) == (l_))

1598 1599 1600 1601
#define MARK_BAD(col_)						\
  do {								\
	  int c = (col_);					\
	  dao_set_colors (dao, c, R, c, R,			\
1602
			  gnm_color_new_rgb8 (255, 0, 0),	\
1603 1604 1605 1606
			  NULL);				\
  } while (0)


1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
static void
add_value_or_special (data_analysis_output_t *dao, int col, int row,
		      gnm_float x)
{
	if (gnm_finite (x))
		dao_set_cell_float (dao, col, row, x);
	else {
		dao_set_cell (dao, col, row, "-");
		dao_set_align (dao, col, row, col, row,
			       GNM_HALIGN_CENTER, GNM_VALIGN_TOP);
	}
}

1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
static void
print_vector (const char *name, const gnm_float *v, int n)
{
	int i;

	if (name)
		g_printerr ("%s:\n", name);
	for (i = 0; i < n; i++)
		g_printerr ("%15.8" GNM_FORMAT_f " ", v[i]);
	g_printerr ("\n");
}

1632 1633
static void
gnm_solver_create_program_report (GnmSolver *solver, const char *name)
1634 1635 1636 1637
{
	GnmSolverParameters *params = solver->params;
	int R = 0;
	data_analysis_output_t *dao;
1638
	GSList *l;
1639 1640 1641 1642 1643 1644 1645

	dao = dao_init_new_sheet (NULL);
	dao->sheet = params->sheet;
	dao_prepare_output (NULL, dao, name);

	/* ---------------------------------------- */

1646 1647 1648 1649
	{
		char *tmp;

		ADD_HEADER (_("Target"));
1650 1651 1652 1653 1654 1655
		dao_set_cell (dao, 1, R, _("Cell"));
		dao_set_cell (dao, 2, R, _("Value"));
		dao_set_cell (dao, 3, R, _("Type"));
		dao_set_cell (dao, 4, R, _("Status"));
		R++;

Morten Welinder's avatar
Morten Welinder committed
1656 1657 1658
		tmp = gnm_solver_cell_name
			(gnm_solver_param_get_target_cell (params),
			 params->sheet);
1659 1660
		dao_set_cell (dao, 1, R, tmp);
		g_free (tmp);
1661

1662 1663
		dao_set_cell_float (dao, 2, R, solver->result->value);

1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
		switch (params->problem_type) {
		case GNM_SOLVER_MINIMIZE:
			dao_set_cell (dao, 3, R, _("Minimize"));
			break;
		case GNM_SOLVER_MAXIMIZE:
			dao_set_cell (dao, 3, R, _("Maximize"));
			break;
		}

		switch (solver->result->quality) {
		default:
			break;
		case GNM_SOLVER_RESULT_FEASIBLE:
			dao_set_cell (dao, 4, R, _("Feasible"));
			break;
		case GNM_SOLVER_RESULT_OPTIMAL:
			dao_set_cell (dao, 4, R, _("Optimal"));
			break;
		}

		R++;
1685 1686
		R++;
	}
1687 1688 1689

	/* ---------------------------------------- */

1690
	if (solver->input_cells->len > 0) {
1691
		unsigned ui;
1692 1693 1694

		ADD_HEADER (_("Variables"));

1695 1696 1697 1698 1699 1700 1701
		dao_set_cell (dao, 1, R, _("Cell"));
		dao_set_cell (dao, 2, R, _("Value"));
		dao_set_cell (dao, 3, R, _("Lower"));
		dao_set_cell (dao, 4, R, _("Upper"));
		dao_set_cell (dao, 5, R, _("Slack"));
		R++;

1702 1703
		for (ui = 0; ui < solver->input_cells->len; ui++) {
			GnmCell *cell = g_ptr_array_index (solver->input_cells, ui);
1704 1705
			gnm_float L = solver->min[ui];
			gnm_float H = solver->max[ui];
1706
			gnm_float s = solver->result->solution[ui];
1707
			gnm_float slack = MIN (s - L, H - s);
1708

1709 1710 1711 1712
			char *cname = gnm_solver_cell_name (cell, params->sheet);
			dao_set_cell (dao, 1, R, cname);
			g_free (cname);
			dao_set_cell_value (dao, 2, R, value_new_float (s));
1713 1714
			add_value_or_special (dao, 3, R, L);
			add_value_or_special (dao, 4, R, H);
1715 1716 1717 1718 1719

			add_value_or_special (dao, 5, R, slack);
			if (slack < 0)
				MARK_BAD (5);

1720
			if (AT_LIMIT (s, L) || AT_LIMIT (s, H))
1721 1722
				dao_set_cell (dao, 6, R, _("At limit"));

1723
			if (s < L || s > H) {
1724 1725
				dao_set_cell (dao, 7, R, _("Outside bounds"));
				MARK_BAD (7);
1726
			}
1727 1728

			R++;
1729 1730 1731 1732 1733 1734 1735
		}

		R++;
	}

	/* ---------------------------------------- */

1736 1737
	ADD_HEADER (_("Constraints"));

1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
	if (params->constraints) {
		dao_set_cell (dao, 1, R, _("Condition"));
		dao_set_cell (dao, 2, R, _("Value"));
		dao_set_cell (dao, 3, R, _("Limit"));
		dao_set_cell (dao, 4, R, _("Slack"));
	} else {
		dao_set_cell (dao, 1, R, _("No constraints"));
	}
	R++;

1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
	for (l = params->constraints; l; l = l->next) {
		GnmSolverConstraint *c = l->data;
		int i;
		gnm_float cl, cr;
		GnmCell *lhs, *rhs;

		for (i = 0;
		     gnm_solver_constraint_get_part (c, params, i,
						     &lhs, &cl,
						     &rhs, &cr);
		     i++) {
			gnm_float slack = 0;
1760
			char *ctxt = gnm_solver_constraint_part_as_str (c, i, params);
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
			dao_set_cell (dao, 1, R, ctxt);
			g_free (ctxt);

			if (lhs) {
				gnm_cell_eval (lhs);
				cl = value_get_as_float (lhs->value);
			}
			if (rhs) {
				gnm_cell_eval (rhs);
				cr = value_get_as_float (rhs->value);
			}

			switch (c->type) {
			case GNM_SOLVER_INTEGER: {
				gnm_float c = gnm_fake_round (cl);
				slack = 0 - gnm_abs (c - cl);
				break;
			}
			case GNM_SOLVER_BOOLEAN: {
				gnm_float c = (cl > 0.5 ? 1 : 0);
				slack = 0 - gnm_abs (c - cl);
				break;
			}
			case GNM_SOLVER_LE:
				slack = cr - cl;
				break;
			case GNM_SOLVER_GE:
				slack = cl - cr;
				break;
			case GNM_SOLVER_EQ:
				slack = 0 - gnm_abs (cl - cr);
				break;
			default:
				g_assert_not_reached ();
			}

			add_value_or_special (dao, 2, R, cl);
			if (rhs)
				add_value_or_special (dao, 3, R, cr);

			add_value_or_special (dao, 4, R, slack);
			if (slack < 0)
1803
				MARK_BAD (4);
1804 1805 1806 1807 1808 1809 1810

			R++;
		}
	}

	/* ---------------------------------------- */

1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833