nub.ts 45.2 KB
Newer Older
1
import { CalculatorType, ComputeNode } from "./compute-node";
2
import { Dichotomie } from "./dichotomie";
3
4
import { acSection, IParamDefinitionIterator, Pab, ParamDefinition, ParamsEquation,
         ParamsEquationArrayIterator, Session, Structure } from "./index";
5
import { LinkedValue } from "./linked-value";
6
import { ParamCalculability } from "./param/param-definition";
7
import { ParamValueMode } from "./param/param-value-mode";
Mathias Chouet's avatar
Mathias Chouet committed
8
import { ParamValues } from "./param/param-values";
Mathias Chouet's avatar
Mathias Chouet committed
9
import { Props } from "./props";
10
import { IObservable, Observable, Observer } from "./util/observer";
11
import { Result } from "./util/result";
12
import { ResultElement } from "./util/resultelement";
13

14
/**
Mathias Chouet's avatar
Mathias Chouet committed
15
16
 * Classe abstraite de Noeud de calcul dans une session :
 * classe de base pour tous les calculs
17
 */
18
export abstract class Nub extends ComputeNode implements IObservable {
19

Mathias Chouet's avatar
Mathias Chouet committed
20
21
    public get result(): Result {
        return this._result;
22
23
    }

24
25
26
27
28
29
    /**
     * Local setter to set results of Equation() / Solve() / …  as current
     * ResultElement, instead of overwriting the whole Result object
     * (used by CalcSerie with varying parameters)
     */
    protected set currentResult(r: Result) {
30
31
32
33
        // if for ex. Calc() is called outside of CalcSerie(), _result might not be initialized
        if (! this._result) {
            this.initNewResultElement();
        }
34
35
36
37
        this._result.resultElement = r.resultElement;
        this._result.resultElement.log = r.log;
    }

38
    /** Returns Props object (observable set of key-values) associated to this Nub */
39
    public get properties(): Props {
Mathias Chouet's avatar
Mathias Chouet committed
40
41
        // completes props with calcType if not already set
        this._props.setPropValue("calcType", this.calcType);
Mathias Chouet's avatar
Mathias Chouet committed
42
43
44
        return this._props;
    }

45
46
    public set properties(props: Props) {
        this._props = props.clone();
Mathias Chouet's avatar
Mathias Chouet committed
47
48
    }

Dorchies David's avatar
Dorchies David committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
    /**
     * return ParamsEquation of all children recursively
     */
    public get childrenPrms(): ParamsEquation[] {
        const prms: ParamsEquation[] = [];
        if (this._children.length) { // if called within constructor, default class member value is not set yet
            for (const child of this._children) {
                prms.push(child.prms);
                if (child.getChildren()) {
                    if (child.getChildren().length) {
                        Nub.concatPrms(prms, child.childrenPrms);
                    }
                }
            }
        }
        return prms;
    }

Mathias Chouet's avatar
Mathias Chouet committed
67
68
69
70
71
72
73
74
    /**
     * Returns an iterator over :
     *  - own parameters (this._prms)
     *  - children parameters (this._children[*]._prms)
     */
    public get parameterIterator(): IParamDefinitionIterator {
        const prms: ParamsEquation[] = [];
        prms.push(this._prms);
Dorchies David's avatar
Dorchies David committed
75
76
        if (this._children) {
            Nub.concatPrms(prms, this.childrenPrms);
Mathias Chouet's avatar
Mathias Chouet committed
77
78
79
80
        }
        return new ParamsEquationArrayIterator(prms);
    }

81
82
83
84
85
    protected get progress() {
        return this._progress;
    }

    /**
86
87
     * Updates the progress percentage and notifies observers,
     * at most once per 300ms
88
89
90
     */
    protected set progress(v: number) {
        this._progress = v;
91
92
93
94
95
96
97
98
99
        const currentTime = new Date().getTime();
        if (
            (currentTime - this.previousNotificationTimestamp) > 30
            || v === 100
        ) {
            // console.log(">> notifying !");
            this.notifyProgressUpdated();
            this.previousNotificationTimestamp = currentTime;
        }
100
101
    }

102
    public get calcType(): CalculatorType {
Mathias Chouet's avatar
Mathias Chouet committed
103
        return this._calcType;
104
105
    }

Mathias Chouet's avatar
Mathias Chouet committed
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
    public get calculatedParam(): ParamDefinition {
        return this._calculatedParam;
    }

    /**
     * Sets p as the parameter to be computed; sets it to CALC mode
     */
    public set calculatedParam(p: ParamDefinition) {
        this._calculatedParam = p;
        this._calculatedParam.valueMode = ParamValueMode.CALCUL;
    }

    /**
     * Returns a parameter descriptor compatible with Calc() methods,
     * ie. a symbol string for a Nub's main parameter, or an object
     * of the form { uid: , symbol: } for a Nub's sub-Nub parameter
     * (ex: Structure parameter in ParallelStructure)
     */
    public get calculatedParamDescriptor(): string | { uid: string, symbol: string } {
        if (this.uid === this._calculatedParam.nubUid) {
            return this._calculatedParam.symbol;
        } else {
            return {
                uid: this._calculatedParam.nubUid,
                symbol: this._calculatedParam.symbol
            };
        }
    }

135
    protected static concatPrms(p1: ParamsEquation[], p2: ParamsEquation[]): ParamsEquation[] {
Dorchies David's avatar
Dorchies David committed
136
137
138
139
140
141
142
        const p3: ParamsEquation[] = p1;
        for (const p of p2) {
            p3.push(p);
        }
        return p3;
    }

143
144
    private static progressPercentageAccordedToChainCalculation = 50;

Dorchies David's avatar
Dorchies David committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
    /** paramétrage de la dichotomie */
    public dichoStartIntervalMaxSteps: number = 100;

    /** pointer to parent Nub */
    public parent: Nub;

    /** parameter that is to be computed by default - to be overloaded by child classes */
    protected _defaultCalculatedParam: ParamDefinition;

    /** parameter that is to be computed */
    protected _calculatedParam: ParamDefinition;

    /**
     * List of children Nubs; browsed by parameters iterator.
     *  - for ParallelStructures: contains 0 or more Structures
     *  - for SectionNub : contains exactly 1 acSection
     */
    protected _children: Nub[];

    /** properties describing the Nub type */
    protected _props: Props = new Props();

167
    /** résultat de Calc()/CalcSerie() */
168
    protected _result: Result;
169

Dorchies David's avatar
Dorchies David committed
170
171
172
173
174
175
176
177
178
    /** implémentation par délégation de IObservable */
    private _observable: Observable;

    /** a rough indication of calculation progress, between 0 and 100 */
    private _progress: number = 0;

    /** allows notifying of progress every X milliseconds only */
    private previousNotificationTimestamp = 0;

179
180
    private _firstAnalyticalPrmSymbol: string;

Dorchies David's avatar
Dorchies David committed
181
182
183
184
185
186
187
188
    public constructor(prms: ParamsEquation, dbg: boolean = false) {
        super(prms, dbg);
        this._children = [];
        this._observable = new Observable();
        this._defaultCalculatedParam = this.getFirstAnalyticalParameter();
        this.resetDefaultCalculatedParam();
    }

Mathias Chouet's avatar
Mathias Chouet committed
189
    /**
190
191
192
193
     * Finds the previous calculated parameter and sets its mode to SINGLE
     */
    public unsetCalculatedParam(except: ParamDefinition) {
        for (const p of this.parameterIterator) {
194
195
196
197
            if (
                p.valueMode === ParamValueMode.CALCUL
                && p !== except
            ) {
198
199
200
201
202
203
204
205
206
207
                p.setValueMode(ParamValueMode.SINGLE, false);
            }
        }
    }

    /**
     * Tries to reset the calculated parameter, successively, to :
     *  - the default one if it is in SINGLE mode
     *  - the first SINGLE calculable parameter other than requirer
     *  - the first MINMAX/LISTE calculable parameter other than requirer
Dorchies David's avatar
Dorchies David committed
208
     *
Mathias Chouet's avatar
Mathias Chouet committed
209
210
211
212
213
214
215
     * If no default calculated parameter is defined, does nothing.
     */
    public resetDefaultCalculatedParam(requirer?: ParamDefinition) {
        if (this._defaultCalculatedParam) {
            // if default calculated param is not eligible to CALC mode
            if (
                requirer === this._defaultCalculatedParam
216
217
218
219
220
221
                || ! [
                        ParamValueMode.SINGLE,
                        ParamValueMode.MINMAX,
                        ParamValueMode.LISTE
                    ].includes(this._defaultCalculatedParam.valueMode
                )
Mathias Chouet's avatar
Mathias Chouet committed
222
            ) {
Mathias Chouet's avatar
Mathias Chouet committed
223
                // first SINGLE calculable parameter if any
224
                const newCalculatedParam = this.findFirstCalculableParameter(requirer);
Mathias Chouet's avatar
Mathias Chouet committed
225
226
227
                if (newCalculatedParam) {
                    this.calculatedParam = newCalculatedParam;
                } else {
228
                    // @TODO throws when a new linkable nub is added, and all parameters are already linked !
229
                    throw Error("resetDefaultCalculatedParam : could not find any SINGLE/MINMAX/LISTE parameter");
Mathias Chouet's avatar
Mathias Chouet committed
230
231
232
233
234
235
236
237
238
239
240
241
                }
            } else {
                // default one
                this.calculatedParam = this._defaultCalculatedParam;
            }
        } else {
            // do nothing (ex: Section Paramétrée)
        }
    }

    /**
     * Returns the first visible calculable parameter other than "Pr",
242
243
     * and other than otherThan, that is set to SINGLE, MINMAX or LISTE
     * mode (there might be none)
Mathias Chouet's avatar
Mathias Chouet committed
244
     */
245
    public findFirstCalculableParameter(otherThan?: ParamDefinition) {
Mathias Chouet's avatar
Mathias Chouet committed
246
247
        for (const p of this.parameterIterator) {
            if (
248
249
250
251
252
                [ ParamCalculability.EQUATION, ParamCalculability.DICHO ].includes(p.calculability)
                && p.symbol !== "Pr"
                && p.visible
                && p !== otherThan
                && [ ParamValueMode.SINGLE, ParamValueMode.MINMAX, ParamValueMode.LISTE ].includes(p.valueMode)
Mathias Chouet's avatar
Mathias Chouet committed
253
            ) {
254
                return p;
Mathias Chouet's avatar
Mathias Chouet committed
255
256
            }
        }
257
        return undefined;
Mathias Chouet's avatar
Mathias Chouet committed
258
259
    }

260
    /**
261
262
     * Formule utilisée pour le calcul analytique (solution directe ou méthode de résolution spécifique)
     */
263
    public abstract Equation(sVarCalc: string): Result;
264

265
    /**
266
     * Calculate and put in cache the symbol of first parameter calculable analytically
267
     */
268
    get firstAnalyticalPrmSymbol(): string {
269
270
271
        if (this._firstAnalyticalPrmSymbol === undefined) {
            this._firstAnalyticalPrmSymbol = this.getFirstAnalyticalParameter().symbol;
        }
272
273
274
275
276
277
278
279
280
        return this._firstAnalyticalPrmSymbol;
    }

    /**
     * Run Equation with first analytical parameter to compute
     * Returns the result in number form
     */
    public EquationFirstAnalyticalParameter(): number {
        return this.Equation(this.firstAnalyticalPrmSymbol).vCalc;
281
282
    }

283
    /**
284
285
     * Calcul d'une équation quelle que soit l'inconnue à calculer; déclenche le calcul en
     * chaîne des modules en amont si nécessaire
286
287
288
     * @param sVarCalc nom de la variable à calculer
     * @param rInit valeur initiale de la variable à calculer dans le cas de la dichotomie
     */
Mathias Chouet's avatar
Mathias Chouet committed
289
290
291
292
293
294
295
296
    public Calc(sVarCalc?: string, rInit?: number): Result {
        let computedVar;
        // overload calculated param at execution time ?
        if (sVarCalc) {
            computedVar = this.getParameter(sVarCalc);
        } else {
            computedVar = this.calculatedParam;
        }
297

298
        if (rInit === undefined) {
299
            rInit = computedVar.v;
300
        }
301
        if (computedVar.isAnalytical()) {
302
            this.currentResult = this.Equation(sVarCalc);
303
            this._result.name = sVarCalc;
304
            return this._result;
305
        }
306

307
        const resSolve: Result = this.Solve(sVarCalc, rInit);
308
        if (!resSolve.ok) {
309
            this.currentResult = resSolve;
310
            this._result.name = sVarCalc;
311
            return this._result;
312
313
        }
        const sAnalyticalPrm: string = this.getFirstAnalyticalParameter().symbol;
314
        computedVar.v = resSolve.vCalc;
315
316
        const res: Result = this.Equation(sAnalyticalPrm);
        res.vCalc = resSolve.vCalc;
317
        this.currentResult = res;
318
        this._result.name = sVarCalc;
319
320
321

        this.notifyResultUpdated();

322
        return this._result;
323
324
    }

325
    /**
326
327
     * Calculates required Nubs so that all input data is available;
     * uses 50% of the progress
328
     */
Mathias Chouet's avatar
Mathias Chouet committed
329
330
    public triggerChainCalculation() {
        const requiredNubs1stLevel = this.getRequiredNubs();
331
332
333
334
335
336
337
338
        if (requiredNubs1stLevel.length > 0) {
            const progressStep = Nub.progressPercentageAccordedToChainCalculation / requiredNubs1stLevel.length;
            for (const rn of requiredNubs1stLevel) {
                rn.CalcSerie();
                this.progress += progressStep;
            }
            // round progress to accorded percentage
            this.progress = Nub.progressPercentageAccordedToChainCalculation;
339
340
341
        }
    }

342
    /**
343
344
     * Effectue une série de calculs sur un paramètre; déclenche le calcul en chaîne
     * des modules en amont si nécessaire
345
     * @param rInit solution approximative du paramètre
346
     * @param sDonnee éventuel symbole / paire symbole-uid du paramètre à calculer
347
     */
348
    public CalcSerie(rInit?: number, sDonnee?: any): Result {
349
        // variated parameters caracteristics
350
        const variated: Array<{ param: ParamDefinition, values: ParamValues }> = [];
351

352
        // prepare calculation
353
        this.progress = 0;
Mathias Chouet's avatar
Mathias Chouet committed
354
        this.triggerChainCalculation();
355
        this.copySingleValuesToSandboxValues();
356
357

        // check which values are variating, if any
358
        for (const p of this.parameterIterator) {
359
360
361
362
363
364
365
366
367
368
369
370
371
            if (
                p.valueMode === ParamValueMode.LISTE
                || p.valueMode === ParamValueMode.MINMAX
                || (
                    p.valueMode === ParamValueMode.LINK
                    && p.isReferenceDefined()
                    && p.referencedValue.hasMultipleValues()
                )
            ) {
                variated.push({
                    param: p,
                    // extract variated values from variated Parameters
                    // (in LINK mode, proxies to target data)
372
                    values: p.paramValues
373
                });
374
375
376
            }
        }

377
        // find calculated parameter
378
        const computedSymbol = this.findCalculatedParameter(sDonnee);
379

380
        if (rInit === undefined && this.calculatedParam) {
Mathias Chouet's avatar
Mathias Chouet committed
381
            rInit = this.calculatedParam.v;
382
        }
383

384
385
386
        // reinit Result and children Results
        this.reinitResult();

387
        if (variated.length === 0) { // no parameter is varying
388
389
390
            // prepare a new slot to store results
            this.initNewResultElement();
            this.doCalc(computedSymbol, rInit); // résultat dans this.currentResult (resultElement le plus récent)
391
392
            this.progress = 100;

393
394
395
396
397
398
399
400
401
        } else { // at least one parameter is varying
            // find longest series
            let longest = 0;
            for (let i = 0; i < variated.length; i++) {
                if (variated[i].values.valuesIterator.count() > variated[longest].values.valuesIterator.count()) {
                    longest = i;
                }
            }
            const size = variated[longest].values.valuesIterator.count();
Mathias Chouet's avatar
Mathias Chouet committed
402

403
404
405
406
            // grant the remaining percentage of the progressbar to local calculation
            // (should be 50% if any chain calculation occurred, 100% otherwise)
            let progressStep;
            const remainingProgress = 100 - this.progress;
407
            progressStep = remainingProgress / size;
408

409
            // const res = new Result(undefined, this);
410

411
412
413
414
415
416
417
418
419
420
            // (re)init all iterators
            for (const v of variated) {
                if (v === variated[longest]) {
                    v.values.initValuesIterator(false);
                } else {
                    v.values.initValuesIterator(false, size);
                }
            }

            // iterate over longest series (in fact any series would do)
421
422
423
            while (variated[longest].values.hasNext) {
                // get next value for all variating parameters
                for (const v of variated) {
424
425
                    const currentIteratorValue = v.values.next();
                    v.param.v = currentIteratorValue.value;
426
                }
427
428
                // prepare a new slot to store results
                this.initNewResultElement();
429
                // calculate
430
431
                this.doCalc(computedSymbol, rInit); // résultat dans this.currentResult (resultElement le plus récent)
                if (this._result.resultElement.ok) {
432
                    rInit = this._result.resultElement.vCalc;
433
                }
434
435
                // update progress
                this.progress += progressStep;
436
            }
437
            // this._result = res;
438
439
            // round progress to 100%
            this.progress = 100;
440
441
        }

442
443
444
445
        if (computedSymbol !== undefined) {
            const realSymbol = (typeof computedSymbol === "string") ? computedSymbol : computedSymbol.symbol;
            this._result.name = realSymbol;
        }
446

447
448
        this.notifyResultUpdated();

449
        return this._result;
450
451
    }

452
453
454
455
456
457
458
    /**
     * Renvoie la valeur actuelle d'un paramètre (valeur utilisateur ou résultat)
     * @param p Paramètre
     */
    public V(p: ParamDefinition): number {
        if (p.valueMode === ParamValueMode.CALCUL) {
            if (this.result !== undefined) {
459
                if (this.result.resultElement.ok) {
460
461
462
463
                    return this.result.vCalc;
                }
            }
        }
464
        return p.currentValue;
465
466
    }

Mathias Chouet's avatar
Mathias Chouet committed
467
468
469
470
471
472
473
474
475
476
    public addChild(child: Nub, after?: number) {
        if (after !== undefined) {
            this._children.splice(after + 1, 0, child);
        } else {
            this._children.push(child);
        }
        // add reference to parent collection (this)
        child.parent = this;
        // propagate precision
        child.prms.Pr.setValue(this.prms.Pr.v); // does not write to .v to bypass calculability control
Mathias Chouet's avatar
Fix #86    
Mathias Chouet committed
477
478
        // postprocessing
        this.adjustChildParameters(child);
Mathias Chouet's avatar
Mathias Chouet committed
479
    }
480
481

    public getChildren(): Nub[] {
Mathias Chouet's avatar
Mathias Chouet committed
482
        return this._children;
483
484
485
    }

    public getParent(): Nub {
Mathias Chouet's avatar
Mathias Chouet committed
486
        return this.parent;
487
488
    }

489
490
491
492
493
494
495
496
497
498
499
500
    /**
     * Returns true if all parameters are valid; used to check validity of
     * parameters linked to Nub results
     */
    public isComputable() {
        let valid = true;
        for (const p of this.prms) {
            valid = valid && p.isValid;
        }
        return valid;
    }

501
502
503
504
505
    /**
     * Liste des valeurs (paramètre, résultat, résultat complémentaire) liables à un paramètre
     * @param src paramètre auquel lier d'autres valeurs
     */
    public getLinkableValues(src: ParamDefinition): LinkedValue[] {
506
        let res: LinkedValue[] = [];
507
508
        const symbol = src.symbol;

509
510
511
512
        // If parameter comes from the same Nub, its parent or any of its children,
        // no linking is possible at all.
        // Different Structures in the same parent can get linked to each other.
        if (! this.isParentOrChildOf(src.nubUid)) {
513

Mathias Chouet's avatar
Mathias Chouet committed
514
            // 1. own parameters
515
516
517
518
519
520
            for (const p of this._prms) {
                // if symbol and Nub type are identical, or if family is identical
                if (
                    (p.symbol === symbol && this.calcType === src.nubCalcType)
                    || (p.family !== undefined && (p.family === src.family))
                ) {
521
522
                    // if it is safe to link p's value to src
                    if (p.isLinkableTo(src)) {
Mathias Chouet's avatar
Mathias Chouet committed
523
                        // if p is a CALC param of a Structure other than "Q"
524
                        // (structures always have Q as CALC param and cannot have another)
Mathias Chouet's avatar
Mathias Chouet committed
525
526
                        // or a CALC param of a Section, that is not sibling of the target
                        // (to prevent circular dependencies among ParallelStructures),
Mathias Chouet's avatar
Mathias Chouet committed
527
                        // expose its parent
528
                        if (
Mathias Chouet's avatar
Mathias Chouet committed
529
                            (
Mathias Chouet's avatar
Mathias Chouet committed
530
                              (this instanceof Structure && p.symbol !== "Q" && ! this.isSiblingOf(src.nubUid))
Mathias Chouet's avatar
Mathias Chouet committed
531
532
                              || this instanceof acSection
                            )
533
534
                            && (p.valueMode === ParamValueMode.CALCUL)
                        ) {
Mathias Chouet's avatar
Mathias Chouet committed
535
                            // trick to expose p as a result of the parent Nub
536
537
                            res.push(new LinkedValue(this.parent, p, p.symbol));
                        } else {
538
539
540
541
                            // do not suggest parameters that are already linked to another one
                            if (p.valueMode !== ParamValueMode.LINK) {
                                res.push(new LinkedValue(this, p, p.symbol));
                            }
542
                        }
543
544
545
                    }
                }
            }
546

547
548
            // 2. extra results
            if (this._extraResultsFamilies) {
549
                // if I don't depend on your result, you may depend on mine !
Mathias Chouet's avatar
Mathias Chouet committed
550
                if (! this.dependsOnNubResult(src.parentNub)) {
551
                    const erk = Object.keys(this._extraResultsFamilies);
552
                    // browse extra results
553
554
555
556
557
558
559
560
                    for (const erSymbol of erk) {
                        const erFamily = this._extraResultsFamilies[erSymbol];
                        // if family is identical
                        if (erFamily === src.family) {
                            res.push(new LinkedValue(this, undefined, erSymbol));
                        }
                    }
                }
561
562
            }
        }
563

564
565
566
567
568
        // 3. children Nubs, except for PAB
        if (! (this instanceof Pab)) {
            for (const cn of this.getChildren()) {
                res = res.concat(cn.getLinkableValues(src));
            }
569
570
        }

571
        return res;
572
    }
573

574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
    /**
     * Returns true if the given Nub UID is either of :
     *  - the current Nub UID
     *  - the current Nub's parent Nub UID
     *  - the UID of any of the current Nub's children
     */
    public isParentOrChildOf(uid: string): boolean {
        if (this.uid === uid) {
            return true;
        }
        const parent = this.getParent();
        if (parent && parent.uid === uid) {
            return true;
        }
        for (const c of this.getChildren()) {
            if (c.uid === uid) {
                return true;
            }
        }
        return false;
    }

Mathias Chouet's avatar
Mathias Chouet committed
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
    /**
     * Returns true if the given Nub UID :
     *  - is the current Nub UID
     *  - is the UID of any of the current Nub's siblings (children of the same parent)
     */
    public isSiblingOf(uid: string): boolean {
        if (this.uid === uid) {
            return true;
        }
        const parent = this.getParent();
        if (parent) {
            for (const c of parent.getChildren()) {
                if (c.uid === uid) {
                    return true;
                }
            }
            return true;
        }
        return false;
    }

Mathias Chouet's avatar
Mathias Chouet committed
617
618
619
620
621
622
    /**
     * Returns all Nubs whose results are required by the given one,
     * without following links (stops when it finds a Nub that has to
     * be calculated). Used to trigger chain calculation.
     */
    public getRequiredNubs(visited: string[] = []) {
Mathias Chouet's avatar
Mathias Chouet committed
623
        const requiredNubs: Nub[] = [];
Mathias Chouet's avatar
Mathias Chouet committed
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
        // prevent loops
        if (! visited.includes(this.uid)) {
            visited.push(this.uid);

            // inspect all target Nubs
            for (const p of this.parameterIterator) {
                if (p.valueMode === ParamValueMode.LINK && p.isReferenceDefined()) {
                    const nub = p.referencedValue.nub;

                    // a Nub is required if I depend on its result
                    if (this.dependsOnNubResult(nub, false)) {
                        requiredNubs.push(nub);
                    }
                }
            }
        }
        return requiredNubs;
    }

643
    /**
644
     * Returns all Nubs whose parameters or results are targetted
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
     * by the given one.
     * (used for dependencies checking at session saving time)
     */
    public getTargettedNubs(visited: string[] = []) {
        const targettedNubs: Nub[] = [];
        // prevent loops
        if (! visited.includes(this.uid)) {
            visited.push(this.uid);

            // inspect all target Nubs
            for (const p of this.parameterIterator) {
                if (p.valueMode === ParamValueMode.LINK && p.isReferenceDefined()) {
                    targettedNubs.push(p.referencedValue.nub);
                }
            }
        }
        return targettedNubs;
    }

664
    /**
665
666
667
668
669
670
671
672
673
674
     * Returns true if
     *  - this Nub
     *  - any of this Nub's children
     *  - this Nub's parent
     * depends on
     *  - the result of the given Nub
     *  - the result of any of the given Nub's children
     *  - the result of the given Nub's parent
     *
     * (ie. "my family depends on the result of your family")
Mathias Chouet's avatar
Mathias Chouet committed
675
676
     *
     * If followLinksChain is false, will limit the exploration to the first target level only
677
     */
Mathias Chouet's avatar
Mathias Chouet committed
678
    public dependsOnNubResult(nub: Nub, followLinksChain: boolean = true): boolean {
679
680
681
682
683
684
685
        let thisFamily: Nub[] = [this];
        const tp = this.getParent();
        if (tp) {
            thisFamily = thisFamily.concat(tp);
        }
        thisFamily = thisFamily.concat(this.getChildren());

686
        let yourFamily: Nub[] = [];
Mathias Chouet's avatar
Mathias Chouet committed
687
        const you = nub;
688
689
690
691
692
693
694
        if (you) {
            yourFamily = [you];
            const yp = you.getParent();
            if (yp) {
                yourFamily = yourFamily.concat(yp);
            }
            yourFamily = yourFamily.concat(you.getChildren());
695
696
697
698
699
700
701
702
703
        }

        let depends = false;

        outerloop:
        for (const t of thisFamily) {
            // look for a parameter linked to the result of any Nub of yourFamily
            for (const p of t.prms) {
                if (p.valueMode === ParamValueMode.LINK) {
Mathias Chouet's avatar
Mathias Chouet committed
704
                    if (p.isLinkedToResultOfNubs(yourFamily, followLinksChain)) {
705
706
707
708
709
710
711
712
713
714
715
                        // dependence found !
                        depends = true;
                        break outerloop;
                    }
                }
            }
        }

        return depends;
    }

716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
    /**
     * Returns true if this nub (parent and children included)
     * directly requires (1st level only) @TODO follow links ?
     * the given parameter
     */
    public dependsOnParameter(src: ParamDefinition) {
        let thisFamily: Nub[] = [this];
        const tp = this.getParent();
        if (tp) {
            thisFamily = thisFamily.concat(tp);
        }
        thisFamily = thisFamily.concat(this.getChildren());

        let depends = false;

        outerloop:
        for (const t of thisFamily) {
            // look for a parameter of thisFamily that is directly linked to src
            for (const p of t.prms) {
                if (
                    p.valueMode === ParamValueMode.LINK
                    && p.isReferenceDefined()
                    && p.referencedValue.isParameter()
                ) {
                    if (
                        p.referencedValue.nub.uid === src.nubUid
                        && p.referencedValue.symbol === src.symbol
                    ) {
                        // dependence found !
                        depends = true;
                        break outerloop;
                    }
                }
            }
        }

        return depends;
    }

755
756
757
758
    /**
     * Returns true if the computation of the current Nub (parent and children
     * included) directly requires (1st level only), anything (parameter or result)
     * from the given Nub UID "uid", its parent or any of its children
759
     * @param uid
760
761
762
763
     * @param symbol symbol of the target parameter whose value change triggered this method;
     *      if current Nub targets this symbol, it will be considered dependent
     * @param includeValuesLinks if true, even if this Nub targets only non-calculated non-modified
     *      parameters, it will be considered dependent @see jalhyd#98
764
     */
765
766
767
768
769
770
    public resultDependsOnNub(
        uid: string,
        visited: string[] = [],
        symbol?: string,
        includeValuesLinks: boolean = false
    ): boolean {
771
772
773
774
775
776
        if (uid !== this.uid && ! visited.includes(this.uid)) {
            visited.push(this.uid);

            // does any of our parameters depend on the target Nub ?
            for (const p of this._prms) {
                if (p.valueMode === ParamValueMode.LINK) {
777
                    if (p.dependsOnNubFamily(uid, symbol, includeValuesLinks)) {
778
779
780
781
782
783
784
                        return true;
                    }
                }
            }
            // does any of our parent's parameters depend on the target Nub ?
            const parent = this.getParent();
            if (parent) {
785
                if (parent.resultDependsOnNub(uid, visited, symbol, includeValuesLinks)) {
786
787
788
789
790
                    return true;
                }
            }
            // does any of our children' parameters depend on the target Nub ?
            for (const c of this.getChildren()) {
791
                if (c.resultDependsOnNub(uid, visited, symbol, includeValuesLinks)) {
792
                    return true;
793
                }
794
            }
795
        }
796
797
        return false;
    }
798

799
800
801
802
803
804
    /**
     * Returns true if the computation of the current Nub has multiple values
     * (whether it is already computed or not), by detecting if any parameter,
     * linked or not, is variated
     */
    public resultHasMultipleValues(): boolean {
805
        let hmv = false;
Mathias Chouet's avatar
Mathias Chouet committed
806
        for (const p of this.parameterIterator) {
807
            if (p.valueMode === ParamValueMode.MINMAX || p.valueMode === ParamValueMode.LISTE) {
808
                hmv = true;
Mathias Chouet's avatar
Mathias Chouet committed
809
            } else if (p.valueMode === ParamValueMode.LINK && p.isReferenceDefined()) {
810
                // indirect recursivity
811
                hmv = hmv || p.referencedValue.hasMultipleValues();
812
            }
813
        }
814
        return hmv;
815
    }
816

817
818
    /**
     * Sets the current result to undefined, as well as the results
Mathias Chouet's avatar
Mathias Chouet committed
819
820
     * of all depending Nubs; also invalidates all fake ParamValues
     * held by LinkedValues pointing to this result
821
     */
822
    public resetResult(visited: string[] = []) {
823
        this._result = undefined;
824
        visited.push(this.uid);
825
826
        const dependingNubs = Session.getInstance().getDependingNubs(this.uid);
        for (const dn of dependingNubs) {
827
828
829
            if (! visited.includes(dn.uid)) {
                dn.resetResult(visited);
            }
Mathias Chouet's avatar
Mathias Chouet committed
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
            dn.resetLinkedParamValues(this);
        }
    }

    /**
     * For all parameters pointing to the result of the given Nub,
     * invalidates fake ParamValues held by pointed LinkedValue
     */
    public resetLinkedParamValues(nub: Nub) {
        for (const p of this.parameterIterator) {
            if (p.valueMode === ParamValueMode.LINK && p.isReferenceDefined()) {
                if (
                    (p.referencedValue.isResult() || p.referencedValue.isExtraResult())
                    && p.referencedValue.nub.uid === nub.uid
                ) {
                    p.referencedValue.invalidateParamValues();
                }
            }
848
849
850
        }
    }

851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
    /**
     * Returns a JSON representation of the Nub's current state
     * @param extra extra key-value pairs, for ex. calculator title in GUI
     */
    public serialise(extra?: object) {
        return JSON.stringify(this.objectRepresentation(extra));
    }

    /**
     * Returns an object representation of the Nub's current state
     * @param extra extra key-value pairs, for ex. calculator title in GUI
     */
    public objectRepresentation(extra?: object) {
        let ret: any = {
            uid: this.uid,
866
            props: Session.invertEnumKeysAndValuesInProperties(this.properties.props),
867
        };
Mathias Chouet's avatar
Mathias Chouet committed
868

869
870
871
        if (extra) {
            ret =  {...ret, ...{ meta: extra } }; // merge properties
        }
Mathias Chouet's avatar
Mathias Chouet committed
872
        ret = {...ret, ...{  children: [], parameters: [] } }; // extend here to make "parameters" the down-most key
873

Mathias Chouet's avatar
Mathias Chouet committed
874
875
876
        // iterate over local parameters
        const localParametersIterator =  new ParamsEquationArrayIterator([this._prms]);
        for (const p of localParametersIterator) {
877
878
            if (p.visible) {
                ret.parameters.push(p.objectRepresentation());
879
880
881
            }
        }

Mathias Chouet's avatar
Mathias Chouet committed
882
883
884
885
886
        // iterate over children Nubs
        for (const child of this._children) {
            ret.children.push(child.objectRepresentation());
        }

887
888
889
        return ret;
    }

890
891
892
    /**
     * Fills the current Nub with parameter values, provided an object representation
     * @param obj object representation of a Nub content (parameters)
Mathias Chouet's avatar
Mathias Chouet committed
893
894
     * @returns the calculated parameter found, if any - used by child Nub to notify
     *          its parent of the calculated parameter to set
895
     */
896
897
898
899
900
901
    public loadObjectRepresentation(obj: any): { p: ParamDefinition, hasErrors: boolean } {
        // return value
        const ret: { p: ParamDefinition, hasErrors: boolean } = {
            p: undefined,
            hasErrors: false
        };
902
903
904
905
        // set parameter modes and values
        if (obj.parameters && Array.isArray(obj.parameters)) {
            for (const p of obj.parameters) {
                const param = this.getParameter(p.symbol);
906
907
908
909
910
911
912
913
914
915
916
917
918
                if (param) {
                    // load parameter
                    const pRet = param.loadObjectRepresentation(p, false);
                    if (pRet.calculated) {
                        ret.p = param;
                    }
                    // forward errors
                    if (pRet.hasErrors) {
                        ret.hasErrors = true;
                    }
                } else {
                    console.error(`session file : cannot find parameter ${p.symbol} in target Nub`);
                    ret.hasErrors = true;
919
920
                }
            }
Mathias Chouet's avatar
Mathias Chouet committed
921
            // define calculated param at Nub level
922
            // @TODO except if we are a Section / Structure / Cloisons ?
923
924
            if (ret.p) {
                this.calculatedParam = ret.p;
Mathias Chouet's avatar
Mathias Chouet committed
925
            }
926
        }
Mathias Chouet's avatar
Mathias Chouet committed
927
928
929
930

        // iterate over children if any
        if (obj.children && Array.isArray(obj.children)) {
            for (const s of obj.children) {
931
932
                // decode properties
                const props = Session.invertEnumKeysAndValuesInProperties(s.props, true);
Mathias Chouet's avatar
Mathias Chouet committed
933
                // create the Nub
934
                const subNub = Session.getInstance().createNub(new Props(props), this);
Mathias Chouet's avatar
Mathias Chouet committed
935
936
937
938
                // try to keep the original ID
                if (! Session.getInstance().uidAlreadyUsed(s.uid)) {
                    subNub.setUid(s.uid);
                }
939
                const childRet = subNub.loadObjectRepresentation(s);
Mathias Chouet's avatar
Mathias Chouet committed
940
                // add Structure to parent
941
                this.addChild(subNub);
Mathias Chouet's avatar
Mathias Chouet committed
942
                // set calculated parameter for child ?
943
944
945
946
947
948
                if (childRet.p) {
                    this.calculatedParam = childRet.p;
                }
                // forward errors
                if (childRet.hasErrors) {
                    ret.hasErrors = true;
Mathias Chouet's avatar
Mathias Chouet committed
949
950
951
952
                }
            }
        }

953
        return ret;
954
955
    }

956
957
958
959
    /**
     * Once session is loaded, run a second pass on all linked parameters to
     * reset their target if needed
     */
960
961
962
963
964
    public fixLinks(obj: any): { hasErrors: boolean } {
        // return value
        const ret = {
            hasErrors: false
        };
965
966
967
968
969
970
971
972
        if (obj.parameters && Array.isArray(obj.parameters)) {
            for (const p of obj.parameters) {
                const mode: ParamValueMode = (ParamValueMode as any)[p.mode]; // get enum index for string value
                if (mode === ParamValueMode.LINK) {
                    const param = this.getParameter(p.symbol);
                    // formulaire dont le Nub est la cible du lien
                    const destNub = Session.getInstance().findNubByUid(p.targetNub);
                    if (destNub) {
Mathias Chouet's avatar
Fix #89    
Mathias Chouet committed
973
974
975
                        try {
                            param.defineReference(destNub, p.targetParam);
                        } catch (err) {
976
                            // tslint:disable-next-line:no-console
Mathias Chouet's avatar
Fix #95    
Mathias Chouet committed
977
978
                            console.error(`fixLinks: defineReference error`
                                + ` (${this.uid}.${param.symbol} => ${destNub.uid}.${p.targetParam})`);
979
980
                            // forward error
                            ret.hasErrors = true;
Mathias Chouet's avatar
Fix #89    
Mathias Chouet committed
981
                        }
982
                    } else {
983
                        // tslint:disable-next-line:no-console
984
                        console.error("fixLinks : cannot find target Nub");
985
986
                        // forward error
                        ret.hasErrors = true;
987
988
989
990
                    }
                }
            }
        }
991
        return ret;
992
993
    }

Mathias Chouet's avatar
Mathias Chouet committed
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
    /**
     * Replaces a child Nub
     * @param index index of child in _children array
     * @param child new child
     * @param resetCalcParam if true, resets default calculated parameter after replacing child
     * @param keepParametersState if true, mode and value of parameters will be kept between old and new section
     */
    public replaceChild(index: number, child: Nub, resetCalcParam: boolean = false,
                        keepParametersState: boolean = true
    ) {
        if (index > -1 && index < this._children.length) {
            const hasOldChild = (this._children[index] !== undefined);
            const parametersState: any = {};

            // store old parameters state
            if (keepParametersState && hasOldChild) {
                for (const p of this._children[index].parameterIterator) {
                    parametersState[p.symbol] = p.objectRepresentation();
                }
            }

            // replace child
            this._children[index] = child;

            // reapply parameters state
            if (keepParametersState && hasOldChild) {
                for (const p of this._children[index].parameterIterator) {
                    if (p.symbol in parametersState) {
                        p.loadObjectRepresentation(parametersState[p.symbol]);
                    }
                }
            }
        } else {
            throw new Error(`${this.constructor.name}.replaceChild invalid index ${index}`
                          + ` (children length: ${this._children.length})`);
        }
1030
1031
1032
        // postprocessing
        this.adjustChildParameters(child);
        // ensure one parameter is calculated
Mathias Chouet's avatar
Mathias Chouet committed
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
        if (resetCalcParam) {
            this.resetDefaultCalculatedParam();
        }
        // add reference to parent collection (this)
        child.parent = this;
    }

    /**
     * Finds oldChild in the list, and replaces it at the same index with newChild;
     * if the current calculated parameter belonged to the old child, resets a default one
     * @param oldChild child to get the index for
     * @param newChild child to set at this index
     */
    public replaceChildInplace(oldChild: Nub, newChild: Nub) {
        const calcParamLost = (
            typeof this.calculatedParamDescriptor !== "string"
            && this.calculatedParamDescriptor.uid === oldChild.uid
        );
        const index = this.getIndexForChild(oldChild);
        if (index === -1) {
            throw new Error("old child not found");
        }
        this.replaceChild(index, newChild, calcParamLost);
1056
    }
Mathias Chouet's avatar
Mathias Chouet committed
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089

    /**
     * Returns the current index of the given child if any,
     * or else returns -1
     * @param child child or child UID to look for
     */
    public getIndexForChild(child: Nub | string): number {
        let index: number = -1;
        const uid = (child instanceof Nub) ? child.uid : child;
        for (let i = 0; i < this._children.length; i++) {
            if (this._children[i].uid === uid) {
                index = i;
            }
        }
        return index;
    }

    /**
     * @return true if given Nub id a child of current Nub
     */
    public hasChild(child: Nub): boolean {
        return this.hasChildUid(child.uid);
    }

    /**
     * @return true if given Nub uid id a child of current Nub
     */
    public hasChildUid(childUid: string): boolean {
        for (const s of this._children) {
            if (s.uid === childUid) {
                return true;
            }
        }
1090
1091
1092
        return false;
    }

1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
    /**
     * @return child having the given UID
     */
    public getChild(uid: string): Nub {
        for (const s of this._children) {
            if (s.uid === uid) {
                return s;
            }
        }
        return undefined;
    }

Mathias Chouet's avatar
Mathias Chouet committed
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
    /**
     * Moves a child to first position
     */
    public moveChildUp(child: Nub) {
        let i = 0;
        for (const s of this._children) {
            if (s.uid === child.uid && i > 0) {
                const t = this._children[i - 1];
                this._children[i - 1] = this._children[i];
                this._children[i] = t;
                return;
            }
            i++;
        }
    }

    /**
     * Moves a child to last position
     */
    public moveChildDown(child: Nub) {
        let i = 0;
        for (const s of this._children) {
            if (s.uid === child.uid && i < this._children.length - 1) {
                const t = this._children[i];
                this._children[i] = this._children[i + 1];
                this._children[i + 1] = t;
                return;
            }
            i++;
        }
    }

    /**
     * Removes a child
     * @param index
     */
    public deleteChild(index: number) {
        if (index > -1) {
            this._children.splice(index, 1);
        } else {
            throw new Error(`${this.constructor.name}.deleteChild invalid index=${index}`);
        }
    }

    /**
     * Returns the position or the current structure (starting at 0)
     * in the parent Nub
     */
    public findPositionInParent(): number {
        if (this.parent) {
            return this.parent.getIndexForChild(this);
        }
        throw new Error(`Nub of class ${this.constructor.name} has no parent`);
    }

1160
    /**
1161
     * Adds a new empty ResultElement to the current Result object, so that
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
     * computation result is stored into it, via set currentResult(); does
     * the same for all children
     */
    public initNewResultElement() {
        if (! this._result) {
            this._result = new Result(undefined, this);
        }
        // push empty result element for further affectation va set currentResult()
        this._result.addResultElement(new ResultElement());
        // do the same for children
        for (const c of this._children) {
            c.initNewResultElement();
        }
    }

1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
    /**
     * Sets this._result to a new empty Result, before starting a new CalcSerie();
     * does the same for all children
     */
    public reinitResult() {
        this._result = new Result(undefined, this);
        for (const c of this._children) {
            c.reinitResult();
        }
    }

1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
    // interface IObservable

    /**
     * ajoute un observateur à la liste
     */
    public addObserver(o: Observer) {
        this._observable.addObserver(o);
    }

    /**
     * supprime un observateur de la liste
     */
    public removeObserver(o: Observer) {
        this._observable.removeObserver(o);
    }

    /**
     * notifie un événement aux observateurs
     */
    public notifyObservers(data: any, sender?: any) {
        this._observable.notifyObservers(data, sender);
    }

1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
    protected findCalculatedParameter(sDonnee: any): any {
        let computedSymbol: any;
        if (sDonnee) {
            computedSymbol = sDonnee;
        } else {
            if (this.calculatedParam === undefined) {
                throw new Error(`CalcSerie() : aucun paramètre à calculer`);
            }
            computedSymbol = this.calculatedParamDescriptor;
        }
        return computedSymbol;
    }

1224
1225
1226
1227
    protected doCalc(computedSymbol?: any, rInit?: number) {
        return this.Calc(computedSymbol, rInit);
    }

Mathias Chouet's avatar
lint    
Mathias Chouet committed
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
    /**
     * Returns values of parameters and the result of the calculation for the calculated parameter
     * @param sVarCalc Symbol of the calculated param
     * @param result Result object of the calculation
     */
    protected getParamValuesAfterCalc(sVarCalc: string, result: Result): { [key: string]: number } {
        const cPrms: { [key: string]: number } = {};
        for (const p of this.parameterIterator) {
            if (p.symbol === sVarCalc) {
                cPrms[p.symbol] = result.vCalc;
            } else {
                cPrms[p.symbol] = p.v;
            }
        }
        return cPrms;
    }

1245
1246
    /**
     * For all SINGLE, LINK and CALC parameters, copies singleValue to
1247
     * sandbox value (.v) before calculation
1248
     */
1249
    protected copySingleValuesToSandboxValues() {
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
        for (const p of this.parameterIterator) {
            switch (p.valueMode) {
                case ParamValueMode.SINGLE:
                case ParamValueMode.CALCUL:
                    p.v = p.singleValue;
                    break;
                case ParamValueMode.LINK:
                    if (p.referencedValue) {
                        p.v = p.referencedValue.getValue();
                    } else {
                        throw Error("Nub.CalcSerie() : linked value not defined");
                    }
                    break;
                default:
                    // variable mode, let iterator do the job
                    p.v = undefined;
            }
        }
    }

Mathias Chouet's avatar
Fix #73    
Mathias Chouet committed
1270
1271
1272
1273
1274
1275
1276
    /**
     * To call Nub.calc(…) from indirect child
     */
    protected nubCalc(sVarCalc: string, rInit?: number): Result {
        return Nub.prototype.Calc.call(this, sVarCalc, rInit);
    }

1277
1278
1279
    /**
     * Used by GUI to update results display
     */
1280
    protected notifyResultUpdated() {
1281
1282
1283
1284
        this.notifyObservers({
            action: "resultUpdated"
        }, this);
    }
1285