graph2D.component.ts 32.9 KB
Newer Older
1
import { Component, ViewChild, ElementRef } from '@angular/core';
Diego Rey's avatar
Diego Rey committed
2
3
import { GHCIService } from '../../../shared/services/ghci.service';
import functionPlot from 'function-plot';
4
import { Animation, Setting, toJSON, triggerDownload } from './graph2D.helper';
5
import { TranslateService } from '@ngx-translate/core';
Diego Rey's avatar
Diego Rey committed
6

7
8
@Component({
    moduleId: module.id,
Diego Rey's avatar
Diego Rey committed
9
10
    selector: 'graph2D-component',
    templateUrl: './graph2D.component.html',
11
    styleUrls: ['./graph2D.component.scss'],
12
    host: {
13
        '(window:resize)': 'onResize($event)'
14
15
    }
})
Diego Rey's avatar
Diego Rey committed
16
export class Graph2DComponent {
Diego Rey's avatar
Diego Rey committed
17

18
    // Ghci Service
19
20
    private ghciServiceSub: any;

21
22
23
24
25
26
27
28
29
30
31
32
33
    // Chart Container - DOM Element
    @ViewChild('graph2DContainer')
    private graph2DRef: ElementRef;

    // Chart Instance
    private instance: any;

    // Settings
    settings: Setting = {
        axis: true,
        grid: true,
        tip: true
    }
34

35
36
37
38
39
40
    private funciones= [];

    private id = 0;

    private conjunto= [];

41
    // Animation state
42
    animation: Animation = {
43
        data: [],
44
        init: false,
45
        currentFrame: 0,
46
        fps: 10,
47
        playing: false,
48
49
50
        timeout: null,
        animationFrame: null,
        speedX: 10,
51
52
        boton: true,
        zoo: 2000
53
    };
54
55
    //Nuevo

56
57
58
59
60
61
62
    public easeInOutCubic = function(fps) {
        var t = fps < 6 ? 6 : fps;
        var k = t/60;
        var animation = k<.5 ? 60*(4*k*k*k) : 60*((k-1)*(2*k-2)*(2*k-2)+1);
        console.log(animation);
        return animation;
    }
Diego Rey's avatar
Diego Rey committed
63

64
    public setZoom = () => {
65
        this.animation.zoo = this.animation.zoo ;  
66
67
68
69
    }
    public multiGraf = () => { 
        this.animation.boton = !this.animation.boton;
    }
70
    public constructor(private ghciService: GHCIService, public translate: TranslateService) {
71
        this.ghciServiceSub = ghciService.messages.subscribe(
Diego Rey's avatar
Diego Rey committed
72
            canvas => {
73
74
75
76
                // Stop Animation
                if (this.animation.init) {
                    this.stopAnimation();
                }
77
78
79
80
81
                switch(canvas.tipo) { 
                    case 'graph': {
                        var jsonCanvas = JSON.parse(canvas.resultado);
                        var conjs = this.obtenerConjunto(jsonCanvas.funs[0]);
    
82
                        var d = conjs + "}"; //Leo
83
84
85
86
87
    
                        var obj = JSON.parse(d);
                        //Para las funciones 
                        if (obj.conj.sets.fdom == "function(x)") {
                            var nom = jsonCanvas.funs[0].dom;
88
89
                            var elemento1 = this.recursionfuncion(jsonCanvas.funs[0].sets, nom);
                            obj.conj.sets.fdom = function (x) { return eval(elemento1) }
90
                        }
91
92
                        if (obj.conj.sets.fcod == "function(x)") {
                            var nom = jsonCanvas.funs[0].cod;
93
94
                            var elemento2 = this.recursionfuncion(jsonCanvas.funs[0].sets, nom);
                            obj.conj.sets.fcod = function (x) { return (eval(elemento2)) }
95
                        }
96
97
98
99

                        var funcionGenerada = this.generarFuncion(jsonCanvas);
                        console.log(obj)

100
101
102
                        //para Enumerados
                        if (obj.conj.dom == 'Numer') {
                            var j = 0;
103
104
105
106
                            for (var f of obj.conj.sets.fdom) {
                                var expresionDom = new RegExp('( '+f+' )', 'g'); 
                                funcionGenerada = funcionGenerada.replace(expresionDom, j.toString()); 
                                j += 1;
107
108
109
                            }
                        }
                        if (obj.conj.cod == 'Numer') {
110
111
112
113
114
                            var j2 = 0;
                            for (var f2 of obj.conj.sets.fcod) {
                                var expresionCod = new RegExp(f2, 'g'); 
                                funcionGenerada = funcionGenerada.replace(expresionCod, j2.toString()); 
                                j2 += 1;
115
                            }
116

117
                        }
118
119
120

                        let fun = eval(funcionGenerada);

121
122
123
124
125
126
127
128
129
130
                        var colores = ['pink', 'red', 'blue', 'orange', 'green']
                        var num = this.getRandomArbitrary(0, 4);
                        var color = colores[num];
    
                        var tipoGraf;
                        if (obj.conj.baseDom != 'R'){
                            tipoGraf = 'scatter';
                        }else{
                            tipoGraf = 'polyline';
                        }
131
132

                        if(this.animation.boton && obj.conj.cod != 'Numer' && obj.conj.dom != 'Numer'){
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
                            if(this.conjunto.length == 1 && (this.conjunto[0].cod == 'Numer' || this.conjunto[0].dom == 'Numer')){
                                this.conjunto = [];
                                this.conjunto.push(obj.conj);
                                this.id = 0;
                                this.funciones = [];
                                this.funciones.push({
                                    id: this.funciones.length,
                                    sampler: 'builtIn',
                                    fn: function(scope) {
                                      return fun(scope.x)
                                    },
                                    graphType: tipoGraf,
                                    color: color
                                })
                            }else{
                                if(this.conjunto.length == 1){
                                    this.id = 1;
                                    this.conjunto.unshift({radio: 2, dom:this.conjunto[0].baseDom, cod:this.conjunto[0].baseCod, baseCod:this.conjunto[0].baseCod, baseDom:this.conjunto[0].baseDom, sets:{fdom:this.conjunto[0].baseDom,fcod:this.conjunto[0].baseCod}});
                                    this.funciones[0].id = this.id;
                                    
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
                                if (this.conjunto.length != 0){ 
                                    if (obj.conj.baseDom == 'R'){
                                        this.conjunto[0].baseDom = 'R';
                                        this.conjunto[0].dom = 'R';
                                        this.conjunto[0].sets.fdom = 'R';
                                    }
                                    if (obj.conj.baseCod == 'R'){
                                        this.conjunto[0].baseCod = 'R';
                                        this.conjunto[0].cod = 'R';
                                        this.conjunto[0].sets.fcod = 'R';
                                    }
                                }    
                                this.conjunto.push(obj.conj);

                                this.funciones.push({
                                    id: this.funciones.length + this.id,
                                    sampler: 'builtIn',
                                    fn: function(scope) {
                                    return fun(scope.x)
                                    },
                                    graphType: tipoGraf,
                                    color: color
                                });
                            }        
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
                        }else{ 
                            this.conjunto = [];
                            this.conjunto.push(obj.conj);
                            this.id = 0;
                            this.funciones = [];
                            this.funciones.push({
                                id: this.funciones.length,
                                sampler: 'builtIn',
                                fn: function(scope) {
                                  return fun(scope.x)
                                },
                                graphType: tipoGraf,
                                color: color
                            });
                        }
193
                        let bounding = this.getBounding();
194
195
                        this.instance = functionPlot({
                            target: '#graph2D-container',
196
197
                            width: bounding.width,
                            height: bounding.height,
Diego Rey's avatar
Diego Rey committed
198
199
200
201
                            tip: { 
                                color: 'green'
                            },
                            xAxis: {
202
203
204
205
206
207
208
209
                                scale: 'linear',
                                domain: { initial: [-4, 4],
                                        type: 'discrete' },
                                yAxis: { domain: [-4, 4] }
                            },
                            conj:this.conjunto,
                            data: this.funciones,
                            zoom:this.animation.zoo,
210
211
212
213
214
                            plugins: [
                                functionPlot.plugins.zoomBox()
                            ]
                        })
                        break; 
215
                    }
216
                    case 'canvas': {
217
                        var shapesData = JSON.parse(canvas.resultado);
218
                        var shapesDataNormalized = this.normalizeShapesData(shapesData);
219
220
                        let bounding = this.getBounding();
                        this.cleanPlot();
221
222
                        this.instance = functionPlot({
                            target: '#graph2D-container',
223
224
225
                            width: bounding.width,
                            height: bounding.height,
                            grid: true,
226
227
228
229
230
231
232
233
234
235
236
237
238
                            xAxis: {
                                scale: 'linear',
                                domain: {
                                    initial: [-10, 10],
                                    type: 'discrete'
                                }
                            },
                            data: shapesDataNormalized,
                            plugins: [
                                functionPlot.plugins.zoomBox()
                            ]
                        })
                        break; 
239
                    }
240
241
                    case 'animacion': {
                        this.cleanPlot();                  
242
243
244
                        var animationData = canvas.resultado.map(res => JSON.parse(res));
                        for (var frame of animationData) {
                            this.animation.data.push(this.normalizeShapesData(frame));
245
                        }
246
247
                        this.runAnimation();
                        this.animation.init = true;
248
249
                        break; 
                    }
250
                }
Diego Rey's avatar
Diego Rey committed
251
252
            },
            error => {
253
254
255
            }
        )
    }
Diego Rey's avatar
Diego Rey committed
256

257
258
259
260
261
262
    /**
     * Angular lifecycle hook.
     * called after Angular has fully initialized a component's view.
     */
    ngAfterViewInit() {
        if (!this.instance) {
263
            let bounding = this.getBounding();
264
265
            this.instance = functionPlot({
                target: '#graph2D-container',
266
267
268
                width: bounding.width,
                height: bounding.height,
                grid: true,
269
270
271
272
273
274
275
                xAxis: {
                    scale: 'linear',
                    domain: {
                        initial: [-10, 10],
                        type: 'discrete'
                    }
                },
276
                data: []
277
278
279
280
281
282
283
284
285
286
287
288
289
290
            })
        }
    }

    /**
     * Angular lifecycle hook.
     * called when a directive, pipe, or service is destroyed.
     */
    ngOnDestroy() {
        if (this.ghciServiceSub) {
          this.ghciServiceSub.unsubscribe();
        }
    }

291
292
293
294
295
296
    /**
     * On Resize Event.
     */
    onResize(event){
        let instance = this.instance;
        let bounding = this.getBounding();
297
        if (bounding.width > 0) {
298
299
300
            instance.options.width = bounding.width;
            instance.options.height = bounding.height;
            instance.build();
301
        }
302
303
304
305
306
307
308
    }

    /**
     * @name getBounding
     * @desc get the measures of the container of the graph
     */
    private getBounding = function() {
Diego Rey's avatar
Diego Rey committed
309
310
311
312
313
        var {width, height} = this.graph2DRef.nativeElement.getBoundingClientRect();
        if (width === 0) {
            width = document.getElementById('graph2D-container').querySelector('svg').width.baseVal.value;
            height = document.getElementById('graph2D-container').querySelector('svg').height.baseVal.value;
        }
314
315
316
        return {width, height}
    }

317
318
319
320
    /**
     * @name updateFrame
     * @desc update data for Function Plot and redraw the graph
     */
321
322
323
324
325
326
    public updateFrame = function() {
        var $this = this;
        var $data = $this.animation.data[$this.animation.currentFrame];
        if ($this.instance) {
            $this.instance.options.data = $data;
            $this.instance.draw();
327
        } else {
328
329
            let bounding = $this.getBounding();
            $this.instance = functionPlot({
330
                target: '#graph2D-container',
331
332
                width: bounding.width,
                height: bounding.height,
333
334
335
336
337
338
339
340
                xAxis: {
                    label: 'x - axis',
                    scale: 'linear',
                    domain: {
                        initial: [-10, 10],
                        type: 'discrete'
                    }
                },
341
                data: $data
Diego Rey's avatar
Diego Rey committed
342
            })
343
        }
344
        // Update Frame
345
346
347
348
        $this.animation.timeout = setTimeout(function() {
            $this.animation.currentFrame = ($this.animation.currentFrame + 1) % $this.animation.data.length;
            $this.animation.animationFrame = requestAnimationFrame($this.updateFrame.bind($this));
        }, 1000/ this.easeInOutCubic($this.animation.fps));
349
    }
350

351
352
353
354
355
    /**
     * @name runAnimation
     * @desc Run Shapes Animation
     */
    public runAnimation = function() {
356
        if (this.animation.playing) return;
357
358
        var $this = this;
        $this.animation.playing = true;
359
        $this.updateFrame();
360
    }
361

362
363
364
365
366
367
    /**
     * @name pauseAnimation
     * @desc Pause Shapes Animation
     */
    public pauseAnimation = function() {
        var $this = this;
368
369
370
        cancelAnimationFrame($this.animation.animationFrame);
        clearTimeout($this.animation.timeout);
        $this.animation.timeout = null;
371
        $this.animation.playing = false;
Diego Rey's avatar
Diego Rey committed
372
    }
373

374
375
376
377
378
379
    /**
     * @name stopAnimation
     * @desc Stop Shapes Animation
     */
    public stopAnimation = function() {
        var $this = this;
380
        $this.pauseAnimation();
381
382
        $this.animation.data = [];
        $this.animation.currentFrame = 0;
Diego Rey's avatar
Diego Rey committed
383
        $this.animation.init = false;
384
385
        this.instance.removeAllGraphs();
    }
Diego Rey's avatar
Diego Rey committed
386

Diego Rey's avatar
Diego Rey committed
387
388
389
390
391
    /**
     * @name decreaseSpeed
     * @desc Decrease Speed Animation
     */
    public decreaseSpeed = function() {
392
393
394
395
396
397
398
399
400
401
402
403
        var decrease = false;
        if (this.animation.fps > 6) {
            decrease = true;
        }
        if (decrease) {
            if (this.animation.fps > 10) {
                this.animation.fps -= 1;
                this.animation.speedX = this.animation.fps / 10;
            } else {
                this.animation.fps -= 1;
                this.animation.speedX = this.animation.fps / 10;
            }
Diego Rey's avatar
Diego Rey committed
404
405
406
407
408
409
410
411
412
413
            this.pauseAnimation();
            this.runAnimation();
        }
    }
    
    /**
     * @name restoreSpeed
     * @desc Increase Speed Animation
     */
    public restoreSpeed = function() {
414
        this.animation.fps = 10;
Diego Rey's avatar
Diego Rey committed
415
416
417
418
419
        this.animation.speedX = 1;
        this.pauseAnimation();
        this.runAnimation();
    }

420
    /**
421
422
423
424
     * @name increaseSpeed
     * @desc Increase Speed Animation
     */
    public increaseSpeed = function() {
425
426
427
428
429
430
431
432
433
434
435
436
        var increase = false;
        if (this.animation.fps < 60) {
            increase = true;
        }
        if (increase) {
            if (this.animation.fps >= 10) {
                this.animation.fps += 1;
                this.animation.speedX = this.animation.fps / 10;
            } else {
                this.animation.fps += 1;
                this.animation.speedX = this.animation.fps / 10;
            }
Diego Rey's avatar
Diego Rey committed
437
438
439
            this.pauseAnimation();
            this.runAnimation();
        }
440
441
442
443
444
445
446
447
    }


    /**
     * @name toggleGrid
     * @desc Show and Hide Grid
     */
    public toggleGrid = function () {
448
        this.instance.toggleGrid();
Diego Rey's avatar
Diego Rey committed
449
        this.settings.grid = !this.settings.grid;
450
451
452
453
454
455
456
    }

    /**
     * @name toggleAxis
     * @desc Show and Hide Axis
     */
    public toggleAxis = function () {
457
        this.instance.toggleAxis();
Diego Rey's avatar
Diego Rey committed
458
        this.settings.axis = !this.settings.axis;
459
460
461
462
463
464
465
    }

    /**
     * @name toggleTip
     * @desc Show and Hide Tip
     */
    public toggleTip = function () {
466
        this.instance.toggleTip();
Diego Rey's avatar
Diego Rey committed
467
        this.settings.tip = !this.settings.tip;
468
469
470
    }

    /**
471
472
473
474
     * @name zoomOut
     * @desc Zoom Out Button Control
     */
    public zoomOut = function () {
Diego Rey's avatar
Diego Rey committed
475
        this.instance.zoomOut();
476
    }
477
478
479
480
481
    /**
     * @name zoomIn
     * @desc Zoom In Button Control 
     */
    public zoomIn = function () {
Diego Rey's avatar
Diego Rey committed
482
483
        this.instance.zoomIn();
    }
484
485
486
487
488
489
490
491
492
493
494
495
    /**
     * @name recenterPlot
     * @desc center the plot and it returns to the initial state.
     */
    public recenterPlot = function () {
        this.instance.recenter();
    }
    /**
     * @name cleanPlot
     * @desc remove all the graph from the instance.
     */
    public cleanPlot = function () {
496
497
498
        if (this.animation.playing) {
            this.stopAnimation();
        } else {
499
500
501
            this.funciones = [];
            this.conjunto = [];
            this.id = 0;
502
503
            this.instance.removeAllGraphs();
        }
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
    }

    /**
     * @name exportPlot
     * @desc Download Plot as an SVG image.
     */
    public exportPlot = function() {
        // Objects
        var svg = document.querySelector('svg');
        var canvas = document.createElement("canvas");

        // Set dimensions of the image
        var svgSize = svg.getBoundingClientRect();
        canvas.width = svgSize.width;
        canvas.height = svgSize.height;

        // Convert SVG DOM structure to xml
        var ctx = canvas.getContext('2d');
        var data = new XMLSerializer().serializeToString(svg);

        // URL Object used to parse, construct, normalise, and encode URLs.
        var DOMURL = window.URL || (<any>window).webkitURL || window;

        var img = new Image();
        var svgBlob = new Blob([data], { type: 'image/svg+xml;charset=utf-8' });
        var url = DOMURL.createObjectURL(svgBlob);

        img.onload = function () {
            ctx.drawImage(img, 0, 0);
            DOMURL.revokeObjectURL(url);

            var imgURI = canvas
                .toDataURL('image/png')
                .replace('image/png', 'image/octet-stream');

            triggerDownload(imgURI);
        };
        img.src = url;
    }

544

545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
    /**
     * @name normalizeRectData
     * @desc Normalize Rectangle data for Function Plot Library 
     * @param {Object} rectData Data of Rectangle to be normalized
     * @returns {Object}
     */
    public normalizeRectData = function ($rectData) {
        var $rectNormalized:any = {};
        var $shape:any = {};
        $shape.w = $rectData.w;
        $shape.h = $rectData.h;
        $shape.x = $rectData.x;
        $shape.y = $rectData.y;
        $rectData.color && ($shape.fill = $rectData.color);
        $rectData.rot !== 'undefined' && ($shape.rotation = $rectData.rot);

        $rectNormalized.shape = $shape;
        $rectNormalized.graphType = 'shape';
        $rectNormalized.shapeType = 'rect';
    
        return $rectNormalized;
    }
    /**
     * @name normalizeCircleData
     * @desc Normalize Circle data for Function Plot Library 
     * @param {Object} circleData Data of Circle to be normalized
     * @returns {Object}
     */
    public normalizeCircleData = function ($circleData) {
        var $circleNormalized:any = {};
        var $shape:any = {};
        $shape.r = $circleData.r;
        $shape.x = $circleData.x;
        $shape.y = $circleData.y;
        $circleData.color && ($shape.fill = $circleData.color);
        $circleData.rot !== 'undefined' && ($shape.rotation = $circleData.rot);

        $circleNormalized.shape = $shape;
        $circleNormalized.graphType = 'shape';
        $circleNormalized.shapeType = 'circle';
    
        return $circleNormalized;
    }
588
    /**
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
     * @name normalizeTextData
     * @desc Normalize Text data for Function Plot Library 
     * @param {Object} textData Data of Text to be normalized
     * @returns {Object}
     */
    public normalizeTextData = function ($textData) {
        var $textNormalized:any = {};
        var $shape:any = {};
        $shape.text = $textData.text;
        $shape.size = $textData.size;
        $shape.x = $textData.x;
        $shape.y = $textData.y;
        $textData.color && ($shape.fill = $textData.color);
        $textData.rot !== 'undefined' && ($shape.rotation = $textData.rot);

        $textNormalized.shape = $shape;
        $textNormalized.graphType = 'shape';
        $textNormalized.shapeType = 'text';
    
        return $textNormalized;
    }
610
611
612
613
    /**
     * @name normalizeLineData
     * @desc Normalize Line data for Function Plot Library 
     * @param {Object} lineData Data of Line to be normalized
614
615
     * @returns {Object}
     */
Diego Rey's avatar
Diego Rey committed
616
617
618
619
620
621
622
623
624
625
626
627
    public normalizeLineData = function ($lineData) {
        var $lineNormalized:any = {};
        var $points = []
        for (var p of $lineData.pts) {
            $points.push([p[0],p[1]]);
        }
        $lineNormalized.points = $points;
        $lineNormalized.stroke = $lineData.color;
        $lineNormalized.rotation = $lineData.rot;
        $lineNormalized.fnType = 'points';
        $lineNormalized.polylineType = 'line';
        $lineNormalized.graphType = 'polyline';
628
    
Diego Rey's avatar
Diego Rey committed
629
630
        return $lineNormalized;
    }
631
632
633
634
    /**
     * @name normalizePolygonData
     * @desc Normalize Polygon data for Function Plot Library 
     * @param {Object} textData Data of Polygon to be normalized
635
636
     * @returns {Object}
     */
Diego Rey's avatar
Diego Rey committed
637
638
639
640
641
642
643
644
645
646
647
648
    public normalizePolygonData = function ($polygonData) {
        var $polygonNormalized:any = {};
        var $points = []
        for (var p of $polygonData.pts) {
            $points.push([p[0],p[1]]);
        }
        $polygonNormalized.points = $points;
        $polygonNormalized.fill = $polygonData.color;
        $polygonNormalized.rotation = $polygonData.rot;
        $polygonNormalized.fnType = 'points';
        $polygonNormalized.polylineType = 'polygon';
        $polygonNormalized.graphType = 'polyline';
649
    
Diego Rey's avatar
Diego Rey committed
650
651
        return $polygonNormalized;
    }
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673

    /**
     * @name normalizeShapesData
     * @desc Normalize Shapes data for Function Plot Library 
     * @param {Array} shapesData Data of Shapes to be normalized 
     * @returns {Array}
     */
    public normalizeShapesData = function (shapesData) {
        var normalized:Array<Object> = [];
        for (var shape of shapesData) {
            switch(shape.kind) { 
                case 'rect': { 
                    normalized.push(this.normalizeRectData(shape)); 
                    break; 
                } 
                case 'circle': { 
                    normalized.push(this.normalizeCircleData(shape)); 
                    break; 
                } 
                case 'text': { 
                    normalized.push(this.normalizeTextData(shape)); 
                    break; 
674
                }
Diego Rey's avatar
Diego Rey committed
675
676
677
678
679
680
681
682
                case 'line': { 
                    normalized.push(this.normalizeLineData(shape)); 
                    break; 
                }
                case 'poly': { 
                    normalized.push(this.normalizePolygonData(shape)); 
                    break; 
                } 
683
684
685
686
687
            } 
        }
        return normalized;
    }

688
689


Diego Rey's avatar
Diego Rey committed
690
    getRandomArbitrary = function (min, max) {
691
692
        return Math.round(Math.random() * (max - min) + min);
    }
Diego Rey's avatar
Diego Rey committed
693
694
695
696
697
698
699
700
701
702

    generarFuncion = function (graph) {
        var funcionString = '';
        var grafica;
        for (var fun of graph.funs) {
            funcionString = 'var ' + fun.fun + ' = function(' + fun.args.join() + '){\n return ' + this.generarExpresion(fun.bdy) + '}\n' + funcionString;

            if (fun.fun == graph.graph) {
                funcionString += 'return ' + fun.fun + '(' + fun.args.join() + ');\n'
                grafica = fun;
703
704
            }
        }
705
        funcionString = '(' + grafica.args.join() + ')=>{\n' + funcionString + '}';
Diego Rey's avatar
Diego Rey committed
706
707
708

        return funcionString;
    }
709

Diego Rey's avatar
Diego Rey committed
710
    generarExpresion = function (exp) {
711
712
        var expresion = '';
        if (exp.kind == 'cnd') {
Diego Rey's avatar
Diego Rey committed
713
            expresion = ' (' + this.generarExpresion(exp.cond) + '?' + this.generarExpresion(exp.exp1) + ':' + this.generarExpresion(exp.exp2) + ') ';
714
        } else if (exp.kind == 'bop') {
Diego Rey's avatar
Diego Rey committed
715
            if (exp.op == '==') {
716
                expresion = ' Math.abs((' + this.generarExpresion(exp.exp1) + ') - (' + this.generarExpresion(exp.exp2) + ')) == 0 ';
Diego Rey's avatar
Diego Rey committed
717
            } else if (exp.op == '/=') {
718
                expresion = ' Math.abs((' + this.generarExpresion(exp.exp1) + ') - (' + this.generarExpresion(exp.exp2) + ')) == 0 ||  Math.abs((' + this.generarExpresion(exp.exp1) + ') - (' + this.generarExpresion(exp.exp2) + ')) == 0  ';
Diego Rey's avatar
Diego Rey committed
719
720
721
722
723
            } else if (exp.op == '^') {
                expresion = ' Math.pow(' + this.generarExpresion(exp.exp1) + ',' + this.generarExpresion(exp.exp2) + ') ';
            } else {
                expresion = ' (' + this.generarExpresion(exp.exp1) + ')' + exp.op + '(' + this.generarExpresion(exp.exp2) + ') ';
            }
724
        } else if (exp.kind == 'uop') {
Diego Rey's avatar
Diego Rey committed
725
            expresion = ' ' + exp.op + ' ' + this.generarExpresion(exp.exp) + ' ';
726
        } else if (exp.kind == 'app') {
727
728
729
730
731
732
733
734
735
736
			
			if (exp.fun == 'cos') {
				exp.fun = 'Math.cos'
			} else if (exp.fun == 'sin') {
				exp.fun = 'Math.sin'
			} else if (exp.fun == 'round') {
				exp.fun = 'Math.round'
			}
			expresion = ' ' + exp.fun + '(' + exp.args.map(e => this.generarExpresion(e)).join() + ') ';

737
        } else if (exp.kind == 'tup') {
Diego Rey's avatar
Diego Rey committed
738
            expresion = ' (' + exp.exps.map(e => this.generarExpresion(e)).join() + ') ';
739
        } else if (exp.kind == 'lit') {
Diego Rey's avatar
Diego Rey committed
740
            expresion = ' ' + exp.val + ' ';
741
        } else if (exp.kind == 'var') {
Diego Rey's avatar
Diego Rey committed
742
            expresion = ' ' + exp.var + ' ';
743
        } else {
Diego Rey's avatar
Diego Rey committed
744
            expresion = ' undefined ';
745
        }
Diego Rey's avatar
Diego Rey committed
746

747
748
        return expresion;
    }
749

Diego Rey's avatar
Diego Rey committed
750
    //Nuevo 20-07-2018
751
752


Diego Rey's avatar
Diego Rey committed
753
    obtenerConjunto = function (grf) {
754
755

        var setf = '\"sets\": {';
Diego Rey's avatar
Diego Rey committed
756
757
        var dominio = '{\"conj\": {';
        if (grf.dom == 'R') {
758
759
            dominio += "\"radio\": 0.3, \"baseDom\": \"R\", \"dom\": \"R\"";
            setf += "\"fdom\": \"R\",";
Diego Rey's avatar
Diego Rey committed
760
        } else if (grf.dom == 'Z') {
761
762
            dominio += "\"radio\": 2, \"baseDom\": \"Z\", \"dom\": \"Z\"";
            setf += "\"fdom\": \"Z\",";
763
        }/* else if (grf.dom == 'N') {
764
765
            dominio += "\"radio\":2, \"baseDom\": \"N\", \"dom\": \"N\"";
            setf += "\"fdom\": \"N\",";
766
        }*/ else {
767
            var nom = grf.dom;
Diego Rey's avatar
Diego Rey committed
768
            if (Array.isArray(grf.sets[0][nom])) {
769
770
                var arreglo = grf.sets[0][nom];
                var arreglo2 = [];
Diego Rey's avatar
Diego Rey committed
771
772
                for (var item of arreglo) {
                    arreglo2.push("\"" + item + "\"");
773
774
775
                }
                dominio += "\"radio\":2, \"baseDom\": \"N\", \"dom\": \"Numer\"";
                setf += "\"fdom\": [" + arreglo2 + "], ";
Diego Rey's avatar
Diego Rey committed
776
777
778
            } else {

                dominio += this.recursivoDom(grf.sets, nom);
779
                setf += "\"fdom\":\"function(x)\",";
Diego Rey's avatar
Diego Rey committed
780
            }
781
        }
Diego Rey's avatar
Diego Rey committed
782
783
        dominio += ", ";
        if (grf.cod == 'R') {
784
785
            dominio += "\"baseCod\": \"R\", \"cod\": \"R\" ,";
            setf += "\"fcod\": \"R\"";
Diego Rey's avatar
Diego Rey committed
786
        } else if (grf.cod == 'Z') {
787
788
            dominio += "\"baseCod\": \"Z\", \"cod\": \"Z\" ,";
            setf += "\"fcod\": \"Z\"";
Diego Rey's avatar
Diego Rey committed
789
        } else if (grf.cod == 'N') {
790
791
            dominio += "\"baseCod\": \"N\", \"cod\": \"N\" ,";
            setf += "\"fcod\": \"N\"";
Diego Rey's avatar
Diego Rey committed
792
        } else {
793
            var nom = grf.cod;
Diego Rey's avatar
Diego Rey committed
794
            if (Array.isArray(grf.sets[0][nom])) {
795
796
                var arreglo = grf.sets[0][nom];
                var arreglo2 = [];
Diego Rey's avatar
Diego Rey committed
797
798
                for (var item of arreglo) {
                    arreglo2.push("\"" + item + "\"");
799
800
                }
                dominio += "\"baseCod\": \"N\", \"cod\": \"Numer\" ,";
Diego Rey's avatar
Diego Rey committed
801
802
803
                setf += '\"fcod\":[' + arreglo2 + ']';
            } else {
                dominio += this.recursivoCod(grf.sets, nom);
804
                setf += "\"fcod\": \"function(x)\"";
Diego Rey's avatar
Diego Rey committed
805
            }
806
807
808
809
        }
        return dominio + setf + "}}";
    }

Diego Rey's avatar
Diego Rey committed
810
    recursionfuncion = function (func, nombre) {
811
812
        var fun = func[0][nombre].set;
        var resul = "";
Diego Rey's avatar
Diego Rey committed
813
814
815
816
817
        if (fun == 'R' || fun == 'Z' || fun == 'N') {
            resul += this.generarF(func[0][nombre].cond);
        } else {
            resul += this.generarF(func[0][nombre].cond) + " && " + this.recursionfuncion(func, fun);

818
819
820
821
        }
        return resul;
    }

Diego Rey's avatar
Diego Rey committed
822
    recursivoDom = function (sets, nom) {
823
        var domin = "";
Diego Rey's avatar
Diego Rey committed
824
        if (sets[0][nom].set == 'R') {
825
            domin += "\"radio\": 0.3, \"baseDom\": \"R\", \"dom\": \"Func\"";
Diego Rey's avatar
Diego Rey committed
826
        } else if (sets[0][nom].set == 'Z') {
827
            domin += "\"radio\": 2, \"baseDom\": \"Z\", \"dom\": \"Func\"";
Diego Rey's avatar
Diego Rey committed
828
        } else if (sets[0][nom].set == 'N') {
829
            domin += "\"radio\": 2, \"baseDom\": \"N\", \"dom\": \"Func\"";
Diego Rey's avatar
Diego Rey committed
830
        } else {
831
            var nombre = sets[0][nom].set;
Diego Rey's avatar
Diego Rey committed
832
            domin = this.recursivoDom(sets, nombre);
833
834
835
836
        }
        return domin;
    }

Diego Rey's avatar
Diego Rey committed
837
838

    recursivoCod = function (sets, nom) {
839
        var coodo = "";
Diego Rey's avatar
Diego Rey committed
840
        if (sets[0][nom].set == 'R') {
841
            coodo += "\"baseCod\": \"R\", \"cod\": \"Func\",";
Diego Rey's avatar
Diego Rey committed
842
        } else if (sets[0][nom].set == 'Z') {
843
            coodo += "\"baseCod\": \"Z\", \"cod\": \"Func\",";
Diego Rey's avatar
Diego Rey committed
844
        } else if (sets[0][nom].set == 'N') {
845
            coodo += "\"baseCod\": \"N\", \"cod\": \"Func\",";
Diego Rey's avatar
Diego Rey committed
846
        } else {
847
            var nombre = sets[0][nom].set;
Diego Rey's avatar
Diego Rey committed
848
            coodo += this.recursivoDom(sets, nombre);
849
850
851
        }
        return coodo;
    }
Diego Rey's avatar
Diego Rey committed
852
853

    generarF = function (exp) {
854
855
        var expresion = '';
        if (exp.kind == 'cond') {
Diego Rey's avatar
Diego Rey committed
856
            expresion = ' (' + this.generarF(exp.cond) + '?' + this.generarF(exp.exp1) + ':' + this.generarF(exp.exp2) + ') ';
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
        } else if (exp.kind == 'bop') {
            if (exp.op == '==') {
                expresion = ' Math.abs((' + this.generarF(exp.exp1) + ') - (' + this.generarF(exp.exp2) + ')) == 0 ';
            } else if (exp.op == '/=') {
                expresion = ' Math.abs((' + this.generarF(exp.exp1) + ') - (' + this.generarF(exp.exp2) + ')) == 0 ||  Math.abs((' + this.generarF(exp.exp1) + ') - (' + this.generarF(exp.exp2) + ')) == 0  ';
            } else if (exp.op == '^') {
                expresion = ' Math.pow(' + this.generarF(exp.exp1) + ',' + this.generarF(exp.exp2) + ') ';
            } else {
                expresion = ' (' + this.generarF(exp.exp1) + ')' + exp.op + '(' + this.generarF(exp.exp2) + ') ';
            }
        } else if (exp.kind == 'uop') {
            expresion = ' ' + exp.op + ' ' + this.generarF(exp.exp) + ' ';
        } else if (exp.kind == 'app') {
            if (exp.fun == 'cos') {
                exp.fun = 'Math.cos'
872
            } else if (exp.fun == 'sin') {
873
874
875
876
877
878
879
880
881
882
                exp.fun = 'Math.sin'
            } else if (exp.fun == 'round') {
                exp.fun = 'Math.round'
            }
            expresion = ' ' + exp.fun + '(' + exp.args.map(e => this.generarF(e)).join() + ') ';
        } else if (exp.kind == 'tup') {
            expresion = ' (' + exp.exps.map(e => this.generarF(e)).join() + ') ';
        } else if (exp.kind == 'lit') {
            expresion = ' ' + exp.val + ' ';
        } else if (exp.kind == 'var') {
Diego Rey's avatar
Diego Rey committed
883
            expresion = ' ' + exp.var + ' ';
884
        } else {
Diego Rey's avatar
Diego Rey committed
885
            expresion = ' undefined ';
886
        }
Diego Rey's avatar
Diego Rey committed
887

888
889
890
        return expresion;
    }

Diego Rey's avatar
Diego Rey committed
891
    generarFun = function (graph) {
892
893
894
895
896
897
898
899
900
901
        var funcionString = '';
        var grafica;
        for (var fun of graph.funs) {
            funcionString = 'var ' + fun.fun + ' = function(' + fun.args.join() + '){\n return ' + this.generarF(fun.bdy) + '}\n' + funcionString;

            if (fun.fun == graph.graph) {
                funcionString += 'return ' + fun.fun + '(' + fun.args.join() + ');\n'
                grafica = fun;
            }
        }
Diego Rey's avatar
Diego Rey committed
902
        funcionString = '(' + grafica.args.join() + ')=>{\n' + funcionString + '}';
903
904
905

        return funcionString;
    }
Diego Rey's avatar
Diego Rey committed
906

907

908

909
910
}