File: GoalSeekDialog.cpp

package info (click to toggle)
calligra 1%3A2.4.4-3
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 290,028 kB
  • sloc: cpp: 1,105,019; xml: 24,940; ansic: 11,807; python: 8,457; perl: 2,792; sh: 1,507; yacc: 1,307; ruby: 1,248; sql: 903; lex: 455; makefile: 89
file content (325 lines) | stat: -rw-r--r-- 10,992 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
/* This file is part of the KDE project
   Copyright (C) 2002-2003 Norbert Andres <nandres@web.de>
             (C) 2002-2003 Philipp Mueller <philipp.mueller@gmx.de>
             (C) 2002 Laurent Montel <montel@kde.org>
             (C) 2002 John Dailey <dailey@vt.edu>
             (C) 2002 Ariya Hidayat <ariya@kde.org>
             (C) 2002 Werner Trobin <trobin@kde.org>
             (C) 2002 Harri Porten <porten@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library 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
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "GoalSeekDialog.h"

#include <KTextEdit>

#include "CalculationSettings.h"
#include "Cell.h"
#include "ui/RegionSelector.h"
#include "Formula.h"
#include "Map.h"
#include "ui/Selection.h"
#include "Sheet.h"
#include "Util.h"

// commands
#include "commands/DataManipulators.h"

#include "ui_GoalSeekWidget.h"

#include <KMessageBox>

#include <QCloseEvent>

#include <math.h>

using namespace Calligra::Sheets;

class GoalSeekDialog::Private
{
public:
    Selection   * selection;
    Cell          sourceCell;
    Cell          targetCell;
    double        result;
    int           maxIter;
    double        oldSource;
    bool          firstRun;

    Ui::GoalSeekWidget widget;
};


GoalSeekDialog::GoalSeekDialog(QWidget* parent, Selection* selection)
        : KDialog(parent)
        , d(new Private)
{
    d->selection = selection;
    d->result = 0.0;
    d->maxIter = 1000; // TODO make this configurable
    d->oldSource = 0.0;
    d->firstRun = true;

    setButtons(Ok | Cancel);
    enableButtonOk(false);
    setModal(false);

    setObjectName(QLatin1String("GoalSeekDialog"));

    setWindowTitle(i18n("Goal Seek"));

    QWidget* mainWidget = new QWidget(this);
    d->widget.setupUi(mainWidget);
    d->widget.selector1->setDialog(this);
    d->widget.selector1->setSelection(d->selection);
    d->widget.selector1->setSelectionMode(RegionSelector::SingleCell);
    d->widget.selector2->setDialog(this);
    d->widget.selector2->setSelection(d->selection);
    d->widget.selector2->setSelectionMode(RegionSelector::SingleCell);
    d->widget.selector3->setDialog(this);
    d->widget.selector3->setSelection(d->selection);
    d->widget.selector3->setSelectionMode(RegionSelector::SingleCell);
    d->widget.preview->hide();
    setMainWidget(mainWidget);

    // connections
    connect(d->widget.selector1->textEdit(), SIGNAL(textChanged()),
            this, SLOT(textChanged()));
    connect(d->widget.selector2->textEdit(), SIGNAL(textChanged()),
            this, SLOT(textChanged()));
    connect(d->widget.selector3->textEdit(), SIGNAL(textChanged()),
            this, SLOT(textChanged()));

    // Allow the user to select cells on the spreadsheet.
//   d->selection->canvasWidget()->startChoose();
}

GoalSeekDialog::~GoalSeekDialog()
{
    delete d;
}

void GoalSeekDialog::closeEvent(QCloseEvent * e)
{
    d->selection->endReferenceSelection();
    e->accept();
    deleteLater();
}

void GoalSeekDialog::textChanged()
{
    d->widget.preview->hide();
    const bool s1 = !d->widget.selector1->textEdit()->toPlainText().isEmpty();
    const bool s2 = !d->widget.selector2->textEdit()->toPlainText().isEmpty();
    const bool s3 = !d->widget.selector3->textEdit()->toPlainText().isEmpty();
    enableButtonOk(s1 && s2 && s3);
}

void GoalSeekDialog::accept()
{
    if (!d->widget.preview->isVisible()) {
        Sheet * sheet = d->selection->activeSheet();

        const Region source(d->widget.selector3->textEdit()->toPlainText(), sheet->map(), sheet);
        if (!source.isValid() || !source.isSingular()) {
            KMessageBox::error(this, i18n("Cell reference is invalid."));
            d->widget.selector3->textEdit()->selectAll();
            d->widget.selector3->textEdit()->setFocus();

            d->selection->emitModified();
            return;
        }

        const Region target(d->widget.selector1->textEdit()->toPlainText(), sheet->map(), sheet);
        if (!target.isValid() || !target.isSingular()) {
            KMessageBox::error(this, i18n("Cell reference is invalid."));
            d->widget.selector1->textEdit()->selectAll();
            d->widget.selector1->textEdit()->setFocus();

            d->selection->emitModified();
            return;
        }

        bool ok = false;
        double goal = d->selection->activeSheet()->map()->calculationSettings()->locale()->readNumber(d->widget.selector2->textEdit()->toPlainText(), &ok);
        if (!ok) {
            KMessageBox::error(this, i18n("Target value is invalid."));
            d->widget.selector2->textEdit()->selectAll();
            d->widget.selector2->textEdit()->setFocus();

            d->selection->emitModified();
            return;
        }

        d->sourceCell = Cell(source.firstSheet(), source.firstRange().topLeft());
        d->targetCell = Cell(target.firstSheet(), target.firstRange().topLeft());

        if (!d->sourceCell.value().isNumber()) {
            KMessageBox::error(this, i18n("Source cell must contain a numeric value."));
            d->widget.selector3->textEdit()->selectAll();
            d->widget.selector3->textEdit()->setFocus();

            d->selection->emitModified();
            return;
        }

        if (!d->targetCell.isFormula()) {
            KMessageBox::error(this, i18n("Target cell must contain a formula."));
            d->widget.selector1->textEdit()->selectAll();
            d->widget.selector1->textEdit()->setFocus();

            d->selection->emitModified();
            return;
        }

        enableButtonOk(false);
        enableButtonCancel(false);

        d->widget.preview->show();

        startCalc(numToDouble(d->sourceCell.value().asFloat()), goal);
        d->selection->emitModified();
        return;
    }

    // Reset the value for a proper undo value.
    const Value value = d->sourceCell.value();
    d->sourceCell.setValue(Value(d->oldSource));
    Sheet *const sheet = d->selection->activeSheet();
    DataManipulator *const command = new DataManipulator();
    command->setSheet(sheet);
    command->add(Region(d->sourceCell.cellPosition(), sheet));
    command->setValue(value);
    sheet->map()->addCommand(command);

    d->selection->endReferenceSelection();
    d->selection->emitModified();
    deleteLater();
}

void GoalSeekDialog::reject()
{
    if (d->widget.preview->isVisible()) {
        d->sourceCell.setValue(Value(d->oldSource));
    }

    deleteLater();
}

void GoalSeekDialog::startCalc(double _start, double _goal)
{
    d->widget.label4->setText(i18n("Starting..."));
    d->widget.label5->setText(i18n("Iteration:"));

    // lets be optimistic
    bool ok = true;

    // TODO: make this configurable
    double eps = 0.0000001;

    double startA = 0.0, startB;
    double resultA, resultB;

    // save old value
    if (d->firstRun) {
        d->firstRun = false;
        d->oldSource = numToDouble(d->sourceCell.value().asFloat());
    }
    resultA = numToDouble(d->targetCell.value().asFloat()) - _goal;

    // initialize start value
    startB = _start;
    double x = startB + 0.5;

    int iterations = d->maxIter;
    const Formula formula = d->targetCell.formula();

    // while the result is not close enough to zero
    // or while the max number of iterations is not reached...
    while (fabs(resultA) > eps && (iterations >= 0)) {
        startA = startB;
        startB = x;

        d->sourceCell.setValue(Value(startA));
        const double targetValueA = numToDouble(formula.eval().asFloat());
        resultA = targetValueA - _goal;
//         kDebug() << "Target A:" << targetValueA << "," << d->targetCell.userInput() << "Calc:" << resultA;

        d->sourceCell.setValue(Value(startB));
        const double targetValueB = numToDouble(formula.eval().asFloat());
        resultB = targetValueB - _goal;
//         kDebug() << "Target B:" << targetValueB << "," << d->targetCell.userInput() << "Calc:" << resultB;

//         kDebug() <<"Iteration:" << iterations <<", StartA:" << startA
//                  << ", ResultA: " << resultA << " (eps: " << eps << "), StartB: "
//                  << startB << ", ResultB: " << resultB << endl;


        // find zero with secant method (rough implementation was provided by Franz-Xaver Meier):
        // if the function returns the same for two different
        // values we have something like a horizontal line
        // => can't get zero.
        if (resultB == resultA) {
//         kDebug() <<" resultA == resultB";
            if (fabs(resultA) < eps) {
                ok = true;
                break;
            }

            ok = false;
            break;
        }

        // Point of intersection of secant with x-axis
        x = (startA * resultB - startB * resultA) / (resultB - resultA);

        if (fabs(x) > 100000000) {
//             kDebug() <<"fabs(x) > 100000000:" << x;
            ok = false;
            break;
        }

//         kDebug() <<"X:" << x <<", fabs (resultA):" << fabs(resultA) <<", Real start:" << startA <<", Real result:" << resultA <<", Iteration:" << iterations;

        --iterations;
        if (iterations % 20 == 0)
            d->widget.newValue->setText(QString::number(iterations));
    }

    d->widget.label5->setText(i18n("New value:"));
    if (ok) {
        d->sourceCell.setValue(Value(startA));

        d->widget.label4->setText(i18n("Goal seeking with cell %1 found a solution:",
                                       d->widget.selector3->textEdit()->toPlainText()));
        d->widget.newValue->setText(d->selection->activeSheet()->map()->calculationSettings()->locale()->formatNumber(startA));
        d->widget.currentValue->setText(d->selection->activeSheet()->map()->calculationSettings()->locale()->formatNumber(d->oldSource));
    } else {
        // restore the old value
        d->sourceCell.setValue(Value(d->oldSource));
        d->widget.label4->setText(i18n("Goal seeking with cell %1 has found NO solution.",
                                       d->widget.selector3->textEdit()->toPlainText()));
        d->widget.newValue->setText("");
        d->widget.currentValue->setText(d->selection->activeSheet()->map()->calculationSettings()->locale()->formatNumber(d->oldSource));
    }

    enableButtonOk(ok);
    enableButtonCancel(true);
}

#include "GoalSeekDialog.moc"