expr-deriv.c 19.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * exp-deriv.c : Expression derivation
 *
 * Copyright (C) 2016 Morten Welinder (terra@gnome.org)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
 * USA
 */
#include <gnumeric-config.h>
#include <glib/gi18n-lib.h>
23 24 25 26 27 28 29 30 31
#include <gnumeric.h>
#include <expr-deriv.h>
#include <expr-impl.h>
#include <func.h>
#include <value.h>
#include <sheet.h>
#include <workbook.h>
#include <cell.h>
#include <gutils.h>
32 33 34 35

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

struct GnmExprDeriv_ {
36
	unsigned ref_count;
37 38 39
	GnmEvalPos var;
};

Morten Welinder's avatar
Morten Welinder committed
40
/**
41 42 43
 * gnm_expr_deriv_info_new:
 *
 * Returns: (transfer full): A new #GnmExprDeriv.
Morten Welinder's avatar
Morten Welinder committed
44
 */
45 46 47
GnmExprDeriv *
gnm_expr_deriv_info_new (void)
{
48 49 50
	GnmExprDeriv *res = g_new0 (GnmExprDeriv, 1);
	res->ref_count = 1;
	return res;
51 52
}

Morten Welinder's avatar
Morten Welinder committed
53
/**
54 55
 * gnm_expr_deriv_info_unref:
 * @deriv: (transfer full) (nullable): #GnmExprDeriv
Morten Welinder's avatar
Morten Welinder committed
56
 */
57
void
58
gnm_expr_deriv_info_unref (GnmExprDeriv *deriv)
59
{
60 61
	if (!deriv || deriv->ref_count-- > 1)
		return;
62 63 64
	g_free (deriv);
}

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
/**
 * gnm_expr_deriv_info_ref:
 * @deriv: (transfer none) (nullable): #GnmExprDeriv
 *
 * Returns: (transfer full) (nullable): a new reference to @deriv.
 */
GnmExprDeriv *
gnm_expr_deriv_info_ref (GnmExprDeriv *deriv)
{
	if (deriv)
		deriv->ref_count++;
	return deriv;
}

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

	if (t == 0) {
		t = g_boxed_type_register_static ("GnmExprDeriv",
			 (GBoxedCopyFunc)gnm_expr_deriv_info_ref,
			 (GBoxedFreeFunc)gnm_expr_deriv_info_unref);
	}
	return t;
}

92
void
Morten Welinder's avatar
Morten Welinder committed
93
/**
94 95 96
 * gnm_expr_deriv_info_set_var:
 * @deriv: #GnmExprDeriv
 * @var: (transfer none): location of variable
Morten Welinder's avatar
Morten Welinder committed
97
 */
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
gnm_expr_deriv_info_set_var (GnmExprDeriv *deriv, GnmEvalPos const *var)
{
	deriv->var = *var;
}

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

static GnmExpr const *
gnm_value_deriv (GnmValue const *v)
{
	if (VALUE_IS_NUMBER (v))
		return gnm_expr_new_constant (value_new_float (0));
	else
		return NULL;
}

114 115 116 117 118 119 120 121 122 123
static GnmExpr const *madd (GnmExpr const *l, gboolean copyl, GnmExpr const *r, gboolean copyr);
static GnmExpr const *msub (GnmExpr const *l, gboolean copyl, GnmExpr const *r, gboolean copyr);
static GnmExpr const *mmul (GnmExpr const *l, gboolean copyl, GnmExpr const *r, gboolean copyr);
static GnmExpr const *mdiv (GnmExpr const *l, gboolean copyl, GnmExpr const *r, gboolean copyr);
static GnmExpr const *mneg (GnmExpr const *l, gboolean copyl);
static GnmExpr const *optimize_sum (GnmExpr const *e);




124 125 126 127 128
static gboolean
is_any_const (GnmExpr const *e, gnm_float *c)
{
	GnmValue const *v = gnm_expr_get_constant (e);
	if (v && VALUE_IS_FLOAT (v)) {
129
		if (c) *c = value_get_as_float (v);
130 131 132 133 134
		return TRUE;
	} else
		return FALSE;
}

135 136 137 138 139 140 141
static gboolean
is_const (GnmExpr const *e, gnm_float c)
{
	GnmValue const *v = gnm_expr_get_constant (e);
	return v && VALUE_IS_FLOAT (v) && value_get_as_float (v) == c;
}

142 143 144 145 146 147 148 149 150 151 152 153 154 155
static gboolean
is_neg (GnmExpr const *e)
{
	return (GNM_EXPR_GET_OPER (e) == GNM_EXPR_OP_UNARY_NEG);
}

static gboolean
is_lcmul (GnmExpr const *e, gnm_float *c)
{
	return (GNM_EXPR_GET_OPER (e) == GNM_EXPR_OP_MULT &&
		is_any_const (e->binary.value_a, c));
}


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
// Optimizing constructor for "+".  Takes ownership of "l" and "r"
// if the corresponding "copy" argument is false.
//
// Note, that this plays fast-and-loose with semantics when errors are
// involved.
static GnmExpr const *
madd (GnmExpr const *l, gboolean copyl, GnmExpr const *r, gboolean copyr)
{
	if (is_const (l, 0)) {
		if (!copyl) gnm_expr_free (l);
		if (copyr) r = gnm_expr_copy (r);
		return r;
	}

	if (is_const (r, 0)) {
		if (!copyr) gnm_expr_free (r);
		if (copyl) l = gnm_expr_copy (l);
		return l;
	}

	if (copyl) l = gnm_expr_copy (l);
	if (copyr) r = gnm_expr_copy (r);
	return gnm_expr_new_binary (l, GNM_EXPR_OP_ADD, r);
}

// Optimizing constructor for unary "-".  Takes ownership of "l"
// if the corresponding "copy" argument is false.
//
// Note, that this plays fast-and-loose with semantics when errors are
// involved.
static GnmExpr const *
mneg (GnmExpr const *l, gboolean copyl)
{
189 190 191 192 193 194
	gnm_float x;
	if (is_any_const (l, &x)) {
		if (!copyl) gnm_expr_free (l);
		return gnm_expr_new_constant (value_new_float (-x));
	}

195 196 197 198 199 200 201
	if (is_lcmul (l, &x)) {
		GnmExpr const *res = mmul (gnm_expr_new_constant (value_new_float (-x)), 0,
					   l->binary.value_b, 1);
		if (!copyl) gnm_expr_free (l);
		return res;
	}

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
	if (copyl) l = gnm_expr_copy (l);
	return gnm_expr_new_unary (GNM_EXPR_OP_UNARY_NEG, l);
}

// Optimizing constructor for "-".  Takes ownership of "l" and "r"
// if the corresponding "copy" argument is false.
//
// Note, that this plays fast-and-loose with semantics when errors are
// involved.
static GnmExpr const *
msub (GnmExpr const *l, gboolean copyl, GnmExpr const *r, gboolean copyr)
{
	if (is_const (r, 0)) {
		if (!copyr) gnm_expr_free (r);
		if (copyl) l = gnm_expr_copy (l);
		return l;
	}

	if (is_const (l, 0)) {
		if (!copyl) gnm_expr_free (l);
		return mneg (r, copyr);
	}

	if (copyl) l = gnm_expr_copy (l);
	if (copyr) r = gnm_expr_copy (r);
	return gnm_expr_new_binary (l, GNM_EXPR_OP_SUB, r);
}

// Optimizing constructor for "*".  Takes ownership of "l" and "r"
// if the corresponding "copy" argument is false.
//
// Note, that this plays fast-and-loose with semantics when errors are
// involved.
static GnmExpr const *
mmul (GnmExpr const *l, gboolean copyl, GnmExpr const *r, gboolean copyr)
{
	if (is_const (l, 1) || is_const (r, 0)) {
		if (!copyl) gnm_expr_free (l);
		if (copyr) r = gnm_expr_copy (r);
		return r;
	}

	if (is_const (l, 0) || is_const (r, 1)) {
		if (!copyr) gnm_expr_free (r);
		if (copyl) l = gnm_expr_copy (l);
		return l;
	}

250 251 252 253 254
	if (is_const (l, -1)) {
		if (!copyl) gnm_expr_free (l);
		return mneg (r, copyr);
	}

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
	if (is_neg (l)) {
		GnmExpr const *res = mneg (mmul (l->unary.value, 1, r, copyr), 0);
		if (!copyl) gnm_expr_free (l);
		return res;
	}

	if (is_neg (r)) {
		GnmExpr const *res = mneg (mmul (l, copyl, r->unary.value, 1), 0);
		if (!copyr) gnm_expr_free (r);
		return res;
	}

	if (is_lcmul (l, NULL)) {
		GnmExpr const *res = mmul (l->binary.value_a, 1,
					   mmul (l->binary.value_b, 1,
						 r, copyr), 0);
		if (!copyl) gnm_expr_free (l);
		return res;
	}

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
	if (copyl) l = gnm_expr_copy (l);
	if (copyr) r = gnm_expr_copy (r);
	return gnm_expr_new_binary (l, GNM_EXPR_OP_MULT, r);
}

// Optimizing constructor for "/".  Takes ownership of "l" and "r"
// if the corresponding "copy" argument is false.
//
// Note, that this plays fast-and-loose with semantics when errors are
// involved.
static GnmExpr const *
mdiv (GnmExpr const *l, gboolean copyl, GnmExpr const *r, gboolean copyr)
{
	if (is_const (l, 0) || is_const (r, 1)) {
		if (!copyr) gnm_expr_free (r);
		if (copyl) l = gnm_expr_copy (l);
		return l;
	}

	if (copyl) l = gnm_expr_copy (l);
	if (copyr) r = gnm_expr_copy (r);
	return gnm_expr_new_binary (l, GNM_EXPR_OP_DIV, r);
}

// Optimizing constructor for "^".  Takes ownership of "l" and "r"
// if the corresponding "copy" argument is false.
//
// Note, that this plays fast-and-loose with semantics when errors are
// involved.
static GnmExpr const *
mexp (GnmExpr const *l, gboolean copyl, GnmExpr const *r, gboolean copyr)
{
	if (is_const (r, 1)) {
		if (!copyr) gnm_expr_free (r);
		if (copyl) l = gnm_expr_copy (l);
		return l;
	}

	if (copyl) l = gnm_expr_copy (l);
	if (copyr) r = gnm_expr_copy (r);
	return gnm_expr_new_binary (l, GNM_EXPR_OP_EXP, r);
}

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
static GnmExpr const *
msum (GnmExprList *as)
{
	GnmFunc *fsum = gnm_func_lookup_or_add_placeholder ("SUM");
	GnmExpr const *res = gnm_expr_new_funcall (fsum, as);
	GnmExpr const *opt = optimize_sum (res);

	if (opt) {
		gnm_expr_free (res);
		res = opt;
	}

	return res;
}

static GnmExpr const *
optimize_sum (GnmExpr const *e)
{
	int argc = e->func.argc;
	GnmExprConstPtr *argv = e->func.argv;
	gboolean all_neg = (argc > 0);
	gboolean all_lcmul = (argc > 0);
	gnm_float cl = 0;
	int i;

	for (i = 0; i < argc; i++) {
		GnmExpr const *a = argv[i];
		gnm_float x;

		all_neg = all_neg && is_neg (a);

		all_lcmul = all_lcmul &&
350 351
			is_lcmul (a, i ? &x : &cl) &&
			(i == 0 || cl == x);
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
	}

	if (all_neg) {
		GnmExprList *as = NULL;
		for (i = argc; i-- > 0;) {
			GnmExpr const *a = argv[i];
			as = g_slist_prepend (as, (gpointer)gnm_expr_copy (a->unary.value));
		}
		return mneg (msum (as), 0);
	}

	if (all_lcmul) {
		GnmExprList *as = NULL;
		for (i = argc; i-- > 0;) {
			GnmExpr const *a = argv[i];
			as = g_slist_prepend (as, (gpointer)gnm_expr_copy (a->binary.value_b));
		}
		return mmul (gnm_expr_new_constant (value_new_float (cl)), 0,
			     msum (as), 0);
	}

	return NULL;
}

static GnmExpr const *
optimize (GnmExpr const *e)
{
	GnmExprOp op = GNM_EXPR_GET_OPER (e);

	switch (op) {
	case GNM_EXPR_OP_FUNCALL: {
		GnmFunc *f = gnm_expr_get_func_def (e);
		GnmFunc *fsum = gnm_func_lookup_or_add_placeholder ("SUM");

		if (f == fsum)
			return optimize_sum (e);
		return NULL;
	}
	default:
		return NULL;
	}
}

395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
/* ------------------------------------------------------------------------- */

struct cb_arg_collect {
	GnmExprList *args;
	GnmCellRef const *cr0;
	GnmEvalPos const *ep;
};

static GnmValue *
cb_arg_collect (GnmCellIter const *iter, gpointer user_)
{
	struct cb_arg_collect *user = user_;
	GnmCell const *cell = iter->cell;
	GnmCellRef cr;
	GnmParsePos pp;
	gnm_cellref_init (&cr, user->cr0->sheet,
			  cell->pos.col, cell->pos.row,
			  FALSE);
	parse_pos_init_evalpos (&pp, user->ep);
414 415
	gnm_cellref_set_col_ar (&cr, &pp, user->cr0->col_relative);
	gnm_cellref_set_row_ar (&cr, &pp, user->cr0->row_relative);
416 417 418 419 420 421
	user->args = gnm_expr_list_prepend
		(user->args,
		 (gpointer)gnm_expr_new_cellref (&cr));
	return NULL;
}

Morten Welinder's avatar
Morten Welinder committed
422 423 424 425 426 427
/**
 * gnm_expr_deriv_collect:
 * @expr: expression
 * @ep: evaluation position
 * @info: extra information, not currently used
 *
428 429
 * Returns: (type GSList) (transfer full) (element-type GnmExpr): list of
 * expressions expanded from @expr
Morten Welinder's avatar
Morten Welinder committed
430
 */
431
GnmExprList *
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
gnm_expr_deriv_collect (GnmExpr const *expr,
			GnmEvalPos const *ep,
			GnmExprDeriv *info)
{
	struct cb_arg_collect user;
	int i;

	user.args = NULL;
	user.ep = ep;
	for (i = 0; i < expr->func.argc; i++) {
		GnmExpr const *e = expr->func.argv[i];
		GnmValue const *v = gnm_expr_get_constant (e);

		if (!v || !VALUE_IS_CELLRANGE (v)) {
			user.args = gnm_expr_list_prepend
				(user.args, (gpointer)gnm_expr_copy (e));
			continue;
		}

		user.cr0 = &value_get_rangeref (v)->a;
		workbook_foreach_cell_in_range (ep, v,
						CELL_ITER_IGNORE_BLANK,
						cb_arg_collect,
						&user);
	}

458
	return g_slist_reverse (user.args);
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
}

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

#define MAYBE_FREE(e) do { if (e) gnm_expr_free (e); } while (0)

#define COMMON_BINARY_START						\
	GnmExpr const *a = expr->binary.value_a; /* Not owned */	\
	GnmExpr const *da = gnm_expr_deriv (a, ep, info);		\
	GnmExpr const *b = expr->binary.value_b; /* Not owned */	\
	GnmExpr const *db = gnm_expr_deriv (b, ep, info);		\
	if (!da || !db) {						\
		MAYBE_FREE (da);					\
		MAYBE_FREE (db);					\
		return NULL;						\
	} else {

#define COMMON_BINARY_END }

478 479 480 481 482 483 484 485 486
/**
 * gnm_expr_deriv:
 * @expr: #GnmExpr
 * @ep: position for @expr
 * @info: Derivative information
 *
 * Returns: (transfer full) (nullable): the derivative of @expr with respect
 * to @info.
 */
487
GnmExpr const *
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
gnm_expr_deriv (GnmExpr const *expr,
		GnmEvalPos const *ep,
		GnmExprDeriv *info)
{
	GnmExprOp op = GNM_EXPR_GET_OPER (expr);

	switch (op) {
	case GNM_EXPR_OP_RANGE_CTOR:
	case GNM_EXPR_OP_INTERSECT:
	case GNM_EXPR_OP_NAME:
	case GNM_EXPR_OP_ARRAY_CORNER:
	case GNM_EXPR_OP_ARRAY_ELEM:
	case GNM_EXPR_OP_SET:

	case GNM_EXPR_OP_EQUAL:
	case GNM_EXPR_OP_GT:
	case GNM_EXPR_OP_LT:
	case GNM_EXPR_OP_GTE:
	case GNM_EXPR_OP_LTE:
	case GNM_EXPR_OP_NOT_EQUAL:
	case GNM_EXPR_OP_CAT:
509
	case GNM_EXPR_OP_PERCENTAGE:
510 511 512 513 514 515 516
		// Bail
		return NULL;

	case GNM_EXPR_OP_PAREN:
	case GNM_EXPR_OP_UNARY_PLUS:
		return gnm_expr_deriv (expr->unary.value, ep, info);

517
	case GNM_EXPR_OP_UNARY_NEG: {
518
		GnmExpr const *d = gnm_expr_deriv (expr->unary.value, ep, info);
519
		return d ? mneg (d, 0) : NULL;
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
	}

	case GNM_EXPR_OP_ADD: {
		COMMON_BINARY_START
		return madd (da, 0, db, 0);
		COMMON_BINARY_END
	}

	case GNM_EXPR_OP_SUB: {
		COMMON_BINARY_START
		return msub (da, 0, db, 0);
		COMMON_BINARY_END
	}

	case GNM_EXPR_OP_MULT: {
		COMMON_BINARY_START
		GnmExpr const *t1 = mmul (da, 0, b, 1);
		GnmExpr const *t2 = mmul (a, 1, db, 0);
		return madd (t1, 0, t2, 0);
		COMMON_BINARY_END
	}

	case GNM_EXPR_OP_DIV: {
		COMMON_BINARY_START
		GnmExpr const *t1 = mmul (da, 0, b, 1);
		GnmExpr const *t2 = mmul (a, 1, db, 0);
		GnmExpr const *d = msub (t1, 0, t2, 0);
		GnmExpr const *n = mmul (b, 1, b, 1);
		return mdiv (d, 0, n, 0);
		COMMON_BINARY_END
	}

	case GNM_EXPR_OP_EXP: {
		COMMON_BINARY_START
554
		GnmFunc *fln = gnm_func_lookup ("ln", NULL);
555 556 557 558 559 560
		GnmValue const *vb = gnm_expr_get_constant (b);
		if (vb && VALUE_IS_FLOAT (vb)) {
			GnmExpr const *bm1 = gnm_expr_new_constant (value_new_float (value_get_as_float (vb) - 1));
			GnmExpr const *t1 = mexp (a, 1, bm1, 0);
			gnm_expr_free (db);
			return mmul (mmul (b, 1, t1, 0), 0, da, 0);
561
		} else if (fln) {
562 563 564 565 566 567 568 569
			// a^b = exp(b*log(a))
			// (a^b)' = a^b * (a'*b/a + b'*ln(a))
			GnmExpr const *t1 = mdiv (mmul (da, 0, b, 1), 0, a, 1);
			GnmExpr const *t2 = mmul
				(db, 0,
				 gnm_expr_new_funcall1 (fln, gnm_expr_copy (a)), 0);
			GnmExpr const *s = madd (t1, 0, t2, 0);
			return mmul (expr, 1, s, 0);
570 571
		} else
			return NULL;
572 573 574 575 576
		COMMON_BINARY_END
	}

	case GNM_EXPR_OP_FUNCALL: {
		GnmFunc *f = gnm_expr_get_func_def (expr);
577 578 579 580 581
		GnmExpr const *res = gnm_func_derivative (f, expr, ep, info);
		GnmExpr const *opt = optimize (res);
		if (opt) {
			gnm_expr_free (res);
			res = opt;
582 583
		}
		return res;
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
	}

	case GNM_EXPR_OP_CONSTANT:
		return gnm_value_deriv (expr->constant.value);

	case GNM_EXPR_OP_CELLREF: {
		GnmCellRef r;
		Sheet *sheet;
		GnmCell *cell;
		GnmEvalPos ep2;
		GnmExpr const *res;
		GnmExprTop const *texpr;
		GnmExprTop const *texpr2;
		GnmExprRelocateInfo rinfo;

		gnm_cellref_make_abs (&r, &expr->cellref.ref, ep);
		sheet = eval_sheet (r.sheet, ep->sheet);

		if (sheet == info->var.sheet &&
		    r.col == info->var.eval.col &&
		    r.row == info->var.eval.row)
			return gnm_expr_new_constant (value_new_float (1));

		cell = sheet_cell_get (sheet, r.col, r.row);
		if (!cell)
609
			return gnm_expr_new_constant (value_new_float (0));
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
		if (!gnm_cell_has_expr (cell))
			return gnm_value_deriv (cell->value);

		eval_pos_init_cell (&ep2, cell);
		res = gnm_expr_deriv (cell->base.texpr->expr, &ep2, info);
		if (!res)
			return NULL;

		// The just-computed derivative is relative to the wrong
		// position.

		texpr = gnm_expr_top_new (res);
		parse_pos_init_evalpos (&rinfo.pos, &ep2);
		rinfo.reloc_type = GNM_EXPR_RELOCATE_MOVE_RANGE;
		rinfo.origin.start = rinfo.origin.end = ep2.eval;
		rinfo.origin_sheet = ep2.sheet;
		rinfo.target_sheet = ep->sheet;
		rinfo.col_offset = ep->eval.col - ep2.eval.col;
		rinfo.row_offset = ep->eval.row - ep2.eval.row;
		texpr2 = gnm_expr_top_relocate (texpr, &rinfo, FALSE);

		if (texpr2) {
			res = gnm_expr_copy (texpr2->expr);
			gnm_expr_top_unref (texpr2);
		} else {
			res = gnm_expr_copy (texpr->expr);
		}
		gnm_expr_top_unref (texpr);

		return res;
	}

#ifndef DEBUG_SWITCH_ENUM
	default:
		g_assert_not_reached ();
		break;
#endif
	}
}

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

652 653 654 655 656 657 658 659 660
/**
 * gnm_expr_top_deriv:
 * @texpr: Expression
 * @ep: Evaluation position
 * @info: Derivative information
 *
 * Returns: (transfer full) (nullable): The derivative of @texpr with
 * respect to @info.
 */
661 662 663 664 665 666 667
GnmExprTop const *
gnm_expr_top_deriv (GnmExprTop const *texpr,
		    GnmEvalPos const *ep,
		    GnmExprDeriv *info)
{
	GnmExpr const *expr;

668 669 670 671
	g_return_val_if_fail (GNM_IS_EXPR_TOP (texpr), NULL);
	g_return_val_if_fail (ep != NULL, NULL);
	g_return_val_if_fail (info != NULL, NULL);

672 673
	expr = gnm_expr_deriv (texpr->expr, ep, info);
	if (gnm_debug_flag ("deriv")) {
674
		GnmParsePos pp, ppvar;
675 676 677 678
		char *s;
		Sheet *sheet = ep->sheet;
		GnmConventions const *convs = sheet_get_conventions (sheet);

679
		parse_pos_init_evalpos (&ppvar, &info->var);
680
		parse_pos_init_evalpos (&pp, ep);
681

682 683
		s = gnm_expr_top_as_string (texpr, &pp, convs);
		g_printerr ("Derivative of %s with respect to %s:%s",
684
			    s, parsepos_as_string (&ppvar),
685 686 687 688 689 690 691 692
			    expr ? "\n" : " cannot compute.\n");
		g_free (s);
		if (expr) {
			s = gnm_expr_as_string (expr, &pp, convs);
			g_printerr ("%s\n\n", s);
			g_free (s);
		}
	}
693

694 695 696
	return gnm_expr_top_new (expr);
}

697 698 699 700 701 702 703 704
/**
 * gnm_expr_cell_deriv:
 * @y: Result cell
 * @x: Variable cell
 *
 * Returns: (transfer full) (nullable): The derivative of cell @y with
 * respect to cell @x.
 */
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
GnmExprTop const *
gnm_expr_cell_deriv (GnmCell *y, GnmCell *x)
{
	GnmExprTop const *res;
	GnmEvalPos ep, var;
	GnmExprDeriv *info;

	g_return_val_if_fail (y != NULL, NULL);
	g_return_val_if_fail (gnm_cell_has_expr (y), NULL);
	g_return_val_if_fail (x != NULL, NULL);

	eval_pos_init_cell (&ep, y);

	info = gnm_expr_deriv_info_new ();
	eval_pos_init_cell (&var, x);
	gnm_expr_deriv_info_set_var (info, &var);

	res = gnm_expr_top_deriv (y->base.texpr, &ep, info);

724
	gnm_expr_deriv_info_unref (info);
725 726 727 728

	return res;
}

729 730 731 732 733 734 735 736
/**
 * gnm_expr_cell_deriv_value:
 * @y: Result cell
 * @x: Variable cell
 *
 * Returns: The derivative of cell @y with respect to cell @x at the
 * current value of @x.  Returns NaN on error.
 */
737 738 739
gnm_float
gnm_expr_cell_deriv_value (GnmCell *y, GnmCell *x)
{
740
	GnmExprTop const *dydx;
741 742 743 744
	GnmValue *v;
	gnm_float res;
	GnmEvalPos ep;

745 746 747 748
	g_return_val_if_fail (y != NULL, gnm_nan);
	g_return_val_if_fail (x != NULL, gnm_nan);

	dydx = gnm_expr_cell_deriv (y, x);
749 750 751 752 753 754 755 756 757 758
	if (!dydx)
		return gnm_nan;

	eval_pos_init_cell (&ep, y);
	v = gnm_expr_top_eval (dydx, &ep, GNM_EXPR_EVAL_SCALAR_NON_EMPTY);
	res = VALUE_IS_NUMBER (v) ? value_get_as_float (v) : gnm_nan;

	value_release (v);
	gnm_expr_top_unref (dydx);

759
	return res;
760 761
}

762 763
/* ------------------------------------------------------------------------- */

Morten Welinder's avatar
Morten Welinder committed
764
/**
765 766 767 768 769 770 771 772 773 774
 * gnm_expr_deriv_chain:
 * @expr: #GnmExpr for a function call with one argument
 * @deriv: (transfer full) (nullable): Derivative of @expr's function.
 * @ep: position for @expr
 * @info: Derivative information
 *
 * Applies the chain rule to @expr.
 *
 * Returns: (transfer full) (nullable): the derivative of @expr with respect
 * to @info.
Morten Welinder's avatar
Morten Welinder committed
775
 */
776 777 778 779 780
GnmExpr const *
gnm_expr_deriv_chain (GnmExpr const *expr,
		      GnmExpr const *deriv,
		      GnmEvalPos const *ep,
		      GnmExprDeriv *info)
781
{
782
	GnmExpr const *deriv2;
783

784 785
	if (!deriv)
		return NULL;
786

787 788 789 790 791
	deriv2 = gnm_expr_deriv (gnm_expr_get_func_arg (expr, 0), ep, info);
	if (!deriv2) {
		gnm_expr_free (deriv);
		return NULL;
	}
792

793
	return mmul (deriv, 0, deriv2, 0);
794 795 796 797 798 799 800 801
}

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

void
_gnm_expr_deriv_shutdown (void)
{
}
802 803

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