-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathjmat.js
1747 lines (1584 loc) · 57.5 KB
/
jmat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
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
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
console.log('jmat :-)');
jmat = {
abs:function(x){ // absolute value
if (Array.isArray(x)){return x.map(function(xi){return jmat.abs(xi)})}
else{return Math.abs(x)}
},
array2mat:function(x){ // to handle indexed arrays by converting them into two separate numerically indexed arrays
var j = 0, y1=[], y2=[];
for(var i in x){
y1[j]=i;
y2[j]=x[i];
j=j+1;
}
return [y1,y2]
},
array2str:function(x,sp){ // convert array into a sp separated
if (!sp){sp='\n'}
y=x[0];
for (var i=1;i<x.length;i++){
y=y+sp+x[i];
}
return y
},
array2obj:function(A){
var y = {};
A.map(function(x){y[x[0]]=x[1]});
return y;
},
arrayfun:function(x,fun,i){ // apply function to each element of an array
if (Array.isArray(x)){return x.map(function(xi,i){return jmat.arrayfun(xi,fun,i)})}
else{return fun(x,i)}
},
array2table:function(a){ // determines unique entries and builds a table with counts
var t = {columns:jmat.unique(a)};
t.rows = [];
t.rows[0] = t.columns.map(function(u){var c = 0; a.map(function(ai){if(ai==u){c++}});return c});
return t;
},
bin2dec:function(x){
var n=x.length;
return x.split('').map(function(xi,i){return xi*Math.pow(2,n-i-1)}).reduce(function(a,b){return a+b});
},
cat:function(x,y){ // cat will work for matrices and objects
x=this.stringify(x);
y=this.stringify(y);
return this.parse(x.slice(0,x.length-1)+','+y.slice(1,y.length));
},
callback:function(url,fun,success){ // jmat.callback('https://api.github.com/users/jonasalmeida',function(x){console.log(x)})
if(!fun){fun=function(x){console.log(x)}} // default is to dump it on teh console
if(typeof(fun)=='function'){
var funId = this.uid('fun');
this.callback[funId]=function(x){delete jmat.callback[funId];return fun(x)};
this.load(url+'?callback=jmat.callback.'+funId,success);
}
else{this.load(url+'?callback='+fun,success)} // if fun is just the function name
},
catArray:function(A){ // optimized for conCATenation of an array of numerically indexed arrays
// this function was developed to adress memory issues of dealing with large arrays, not performance
var Astr='[',Ai='';
for(var i=0;i<A.length;i++){
Ai=JSON.stringify(A[i]);
Astr+=Ai.slice(1,Ai.length-1)+',';
}
return JSON.parse(Astr.slice(0,Astr.length-1)+']');
},
cEl:function(x,id){
x = document.createElement(x);
if(id){x.id=id}
return x
},
class:function(x){
if(!x.constructor){return null}
else{return x.constructor.name}
},
clone:function(x){ // clone object without functional elements
return JSON.parse(JSON.stringify(x))
},
clone2:function(x){ // clone object that may have functional elements
return jmat.parse(jmat.stringify(x))
},
cloneArray:function(A){
if(Array.isArray(A)){return A.map(function(x){return jmat.cloneArray(x)})}
else{return A}
},
cloneVector:function(V){// fastar than cloneArray if your array only has one dimension
return V.map(function(v){return v})
},
console:function(id){
if(!id){id = 'jmatConsole'};
if(!jmat.gId(id)){
var div = document.createElement('div');
div.id = id;
document.body.appendChild(div);
}
// Now that we have a place to go lets populate it
div.innerHTML="..."; // start with a blank slate
return div;
},
colon:function(x){// equivalent to x(:)
var y=[]; // to have it in the scope
jmat.arrayfun(x,function(x){y[y.length]=x});
return y;
},
compress: function (uncompressed) { // Source: http://rosettacode.org/wiki/LZW_compression#JavaScript
uncompressed = this.stringify(uncompressed); // this is new - such that we are sompressing JS objects, not strings
// Build the dictionary.
var i,
dictionary = {},
c,
wc,
w = "",
result = [],
dictSize = 256;
for (i = 0; i < 256; i += 1) {
dictionary[String.fromCharCode(i)] = i;
}
for (i = 0; i < uncompressed.length; i += 1) {
c = uncompressed.charAt(i);
wc = w + c;
if (dictionary[wc]) {
w = wc;
} else {
result.push(dictionary[w]);
// Add wc to the dictionary.
dictionary[wc] = dictSize++;
w = String(c);
}
}
// Output the code for w.
if (w !== "") {
result.push(dictionary[w]);
}
return result;
},
decompress: function (compressed) {
"use strict";
// Build the dictionary.
var i,
dictionary = [],
w,
result,
k,
entry = "",
dictSize = 256;
for (i = 0; i < 256; i += 1) {
dictionary[i] = String.fromCharCode(i);
}
w = String.fromCharCode(compressed[0]);
result = w;
for (i = 1; i < compressed.length; i += 1) {
k = compressed[i];
if (dictionary[k]) {
entry = dictionary[k];
} else {
if (k === dictSize) {
entry = w + w.charAt(0);
} else {
return null;
}
}
result += entry;
// Add w+entry[0] to the dictionary.
dictionary[dictSize++] = w + entry.charAt(0);
w = entry;
}
return this.parse(result);
},
colormap:function(c){
if(!c){c='default'}
switch(c){
case 'default':
c=[[0,0,0.5625],[0,0,0.625],[0,0,0.6875],[0,0,0.75],[0,0,0.8125],[0,0,0.875],[0,0,0.9375],[0,0,1],[0,0.0625,1],[0,0.125,1],[0,0.1875,1],[0,0.25,1],[0,0.3125,1],[0,0.375,1],[0,0.4375,1],[0,0.5,1],[0,0.5625,1],[0,0.625,1],[0,0.6875,1],[0,0.75,1],[0,0.8125,1],[0,0.875,1],[0,0.9375,1],[0,1,1],[0.0625,1,0.9375],[0.125,1,0.875],[0.1875,1,0.8125],[0.25,1,0.75],[0.3125,1,0.6875],[0.375,1,0.625],[0.4375,1,0.5625],[0.5,1,0.5],[0.5625,1,0.4375],[0.625,1,0.375],[0.6875,1,0.3125],[0.75,1,0.25],[0.8125,1,0.1875],[0.875,1,0.125],[0.9375,1,0.0625],[1,1,0],[1,0.9375,0],[1,0.875,0],[1,0.8125,0],[1,0.75,0],[1,0.6875,0],[1,0.625,0],[1,0.5625,0],[1,0.5,0],[1,0.4375,0],[1,0.375,0],[1,0.3125,0],[1,0.25,0],[1,0.1875,0],[1,0.125,0],[1,0.0625,0],[1,0,0],[0.9375,0,0],[0.875,0,0],[0.8125,0,0],[0.75,0,0],[0.6875,0,0],[0.625,0,0],[0.5625,0,0],[0.5,0,0]];
break;
default:
c = 'not found';
}
return c
},
d3:{
figure:function(id,type){ // create figure by appending d3's svg element to DOM element with specified id
if (typeof(id)==='undefined'){
var fig = d3.select("body").append("div");
fig.id = jmat.uid('fig');
}
else{
if(jmat.gId(id)!=null){var fig = d3.select('#'+id);} // if it exists
else {var fig = this.figure();fig[0][0].id = id} // otherwise create it
}
if (typeof(type)==='string'){
fig.attr('class',type); // possibilities: "chart",
}
this.gcf=fig;
return fig;
},
},
data:{
wappUI:function(id){ // UI for the wApps ecosystem
if(!id){id = jmat.uid()}; // if build target element doesn't exist, then create it
if(!document.getElementById('lala')){$('<div id="'+id+'">').appendTo(document.body);}
// now the target exists for sure
var div = $('#'+id);
var divDataInput = $('<div id="divDataInput">').appendTo(div);
var idTextArea = jmat.uid('inputTextArea');
var inputTextArea = $('<textarea id = "'+idTextArea+'" rows="10"></textarea><button id="inputTextAreaParse">Parse</button><br>').appendTo(divDataInput)
var inputDataFile = $('<input type="file" id="inputDataFile" multiple>').appendTo(divDataInput);
//inputDataFile.idTextArea=idTextArea;
inputDataFile.change(function(){
jmat.loadFiles(this.files,"readAsText",function(x){document.getElementById(idTextArea).value=x.result});});
$('#inputTextAreaParse').click(function(){jmat.data.parse(idTextArea)});
},
wksp:[], // workspace
parse:function(id){ // parsing text tab delimited data into a table (compatible with google fusion tables table template)
jmat.data.wksp.push(jmat.text2table(document.getElementById(id).value));
}
},
data2imData:function(data){ // the reverse of im2data, data is a matlabish set of 4 2d matrices, with the r, g, b and alpha values
var n=data.length, m=data[0].length;
//var imData = {width:m, height:n, data:[]};
var imData = document.createElement('canvas').getContext('2d').createImageData(m,n);
for (var i=0;i<n;i++){ //row
//data.r[i]=[];data.g[i]=[];data.b[i]=[];data.a[i]=[];
for (var j=0;j<m;j++){ // column
ij=(i*m+j)*4;
imData.data[ij]=data[i][j][0];
imData.data[ij+1]=data[i][j][1];
imData.data[ij+2]=data[i][j][2];
imData.data[ij+3]=data[i][j][3];
}
}
return imData;
},
deblank:function(s){ // remove tailing blanks from string
return s.replace(/^\s+/,'').replace(/\s+$/,'');
},
dec2bin:function(x,n){
if(!n){n=Math.ceil(this.log(x,2))+1};
var b='';
for(i=n-1;i>=0;i=i-1){
m=Math.pow(2,i);
if(x>=m){b=b+'1';x=x-m}
else{b=b+'0'}
};
return b
},
disp:function(x){ // by default displays both in the console and in document.body
console.log(x);
document.body.innerHTML+='<br><span style="color:blue">'+x+'</span>';
},
div:function(id,html){
if(!this.gId(id)){
div = this.cEl('div');
div.id=id;
document.body.appendChild(div);
}else{div=this.gId(id)}
if(!!html){div.innerHTML=html};
return div
},
dotFun:function(A,B,fun){ // dot matrix function
4;
},
dimfun:function(){ // first argument is the function, subsequent arguments specify dimensions
if(arguments.length==0){arguments=[function(){return 0}]}
var fun=arguments[0];
if(arguments.length>1){
if(typeof(arguments[1])!='number'){var x = [];for(var i=0;i<arguments[1].length;i++){x[i]=arguments[1][i]}}
else{var x=[];for(var i=1;i<arguments.length;i++){x[i-1]=arguments[i]}} // note first argument is always fun
var z=[];
if(x.length<2){
for(var i=0;i<x[0];i++){
z[i]=fun(i); // fun has access to array index
}
}
else {
var x0=x[0];
x=x.slice(1);
for(var i=0;i<x0;i++){
z[i]=jmat.dimfun(fun,x);
}
}
}
else {z=fun()}
return z
},
edge:function(M){//find edge in bidimensional binary matrix such as what is produced by im2bw
var n = M.length, m = M[0].length;
var E=M.map(function(x,i){return x.map(function(y,j){
if((i>0)&&(i<n-1)&&(j>0)&&(j<m-1)&&(y==1)){
var s = M[i-1][j]+M[i-1][j+1]+M[i][j+1]+M[i+1][j+1]+M[i+1][j]+M[i+1][j-1]+M[i][j-1]+M[i-1][j-1];
if(s<8){return 1} // this is an edge
else{return 0}
}
else {return 0}
})});
return E
},
exist:function(x){ // does it exist? note x is the variable name, not the variable itself
if(eval('typeof('+x+')')=='undefined'){return false}
else{return true}
},
extractSegs:function(bw){ // extracts segmented features from a [0,1] matrix and retruns them as an Array
if(typeof(segFeatures)=='undefined'){var segFeatures=[]} // collect extracted features here
var m = jmat.max2(bw);
var n = jmat.size(bw);
while(m[0]>0){ // extract this feature
var C=[1,0,0]; // always use yellow
//jmat.plot(cvTop,m[1][1],m[1][0],'s',{Color:[1,1,0],MarkerSize:30});
var extractSeg = function(x,y,S){ // bw is passed in the scope of extractSegs
if(typeof(S)=='undefined'){var S=[]} // collect feature's positions
S[S.length]=[x,y];bw[x][y]=0;
// check which neighbors are >0 and take them out too
var xi,yi;
if(x>0){xi=x-1;yi=y;if(bw[xi][yi]>0){S=extractSeg(xi,yi,S)}}
if(x<n[0]-1){xi=x+1;yi=y;if(bw[xi][yi]>0){S=extractSeg(xi,yi,S)}}
if(y>0){xi=x;yi=y-1;if(bw[xi][yi]>0){S=extractSeg(xi,yi,S)}}
if(y<n[1]-1){xi=x;yi=y+1;if(bw[xi][yi]>0){S=extractSeg(xi,yi,S)}}
return S;
}
segFeatures[segFeatures.length]=extractSeg(m[1][0],m[1][1]);//extraction starts with coordiantes ofmaximum value
m = jmat.max2(bw);
}
return segFeatures.map(function(si){return jmat.transpose(si)})
},
fieldnames:function(x){
y=[];i=0;
for(var f in x){
y[i]=f;
i++;
}
return y;
},
find:function(x,patt,modifier){ // find wich elements of an array match a pattern
if(!modifier){modifier='i'}// default is case insensitive
var y = [];
if(Array.isArray(patt)){patt='('+patt.join(')|(')+')'} // allows multiple patterns
patt = new RegExp(patt,modifier);
var M
for(var i in x){
M=x[i].match(patt);
if(!!M){y.push(i)}
}
return y
},
findExact:function(x,patt,modifier){ // find wich elements of an array match a pattern
if(!modifier){modifier='i'}// default is case insensitive
var y = [];
if(Array.isArray(patt)){patt='^('+patt.join(')|(')+')$'} // allows multiple patterns
else{patt='^'+patt+'$'}
patt = new RegExp(patt,modifier);
var M;
for(var i in x){
M=x[i].match(patt);
if(!!M){y.push(i)}
}
return y;
},
fminsearch:function(fun,Parm0,x,y,Opt){// fun = function(x,Parm)
// example
//
// x = [32,37,42,47,52,57,62,67,72,77,82,87,92]
// y=[749,1525,1947,2201,2380,2537,2671,2758,2803,2943,3007,2979,2992]
// fun = function(x,P){return x.map(function(xi){return (P[0]+P[1]*(1-Math.exp(-P[2]*(xi-P[3]))))})}
// Parms=jmat.fminsearch(fun,[100,3000,1,30],x,y)
//
// Opt is an object will all other parameters, from the objective function (cost function), to the
// number of iterations, initial step vector and the display switch, for example
// Parms=jmat.fminsearch(fun,[100,3000,1,30],x,y,{maxIter:5000,display:false})
if(!Opt){Opt={}};
if(!Opt.maxIter){Opt.maxIter=1000};
if(!Opt.step){// initial step is 1/100 of initial value (remember not to use zero in Parm0)
Opt.step=Parm0.map(function(p){return p/100});
Opt.step=Opt.step.map(function(si){if(si==0){return 1}else{ return si}}); // convert null steps into 1's
};
if(typeof(Opt.display)=='undefined'){Opt.display=true};
if(!Opt.objFun){Opt.objFun=function(y,yp){return jmat.sum(y.map(function(yi,i){return Math.pow((yi-yp[i]),2)}))}}
var ya,y0,yb,fP0,fP1;
var P0=jmat.cloneVector(Parm0),P1=jmat.cloneVector(Parm0);
var n = P0.length;
var step=Opt.step;
var funParm=function(P){return Opt.objFun(y,fun(x,P))}//function (of Parameters) to minimize
// silly multi-univariate screening
for(var i=0;i<Opt.maxIter;i++){
for(var j=0;j<n;j++){ // take a step for each parameter
P1=jmat.cloneVector(P0);
P1[j]+=step[j];
if(funParm(P1)<funParm(P0)){ // parm value going in the righ direction
step[j]=1.2*step[j]; // go a little faster
P0=jmat.cloneVector(P1);
}
else{
step[j]=-(0.5*step[j]); // reverse and go slower
}
}
if(Opt.display){if(i>(Opt.maxIter-10)){console.log(i+1,funParm(P0),P0)}}
}
return P0
},
get:function(key,callback,url){ // get content at url or key
if (!callback){callback=function(x){console.log(x)}}
if (!url){url=this.webrwUrl};
var uid = this.uid();
if(!this.get.jobs){this.get.jobs=[]}
this.get.jobs[uid]={'fun':callback};
var url=url+'?get='+key+'&callback=jmat.get.jobs.'+uid+'.fun';
var s=document.createElement('script');
s.id = uid;s.src=url;
document.body.appendChild(s);
setTimeout('document.body.removeChild(document.getElementById("'+uid+'"));delete jmat.get.jobs.'+uid+';',10000); // is the waiting still need ? script onload would be another possibility to delete it
return uid;
},
gId:function(x){ // x is the id of an existing DOM element
return document.getElementById(x)
},
html:function(x){ // convertes stuff (JSON mostly) to html
var y = '';
switch (typeof(x)){
case 'object':
if(Array.isArray(x)){ // x is an array
/*if(typeof(x[0])=='object'){
y = x.map(function(xi){return '<td>'+jmat.html(xi)+'</td>'})
}
else{
y = '<table><tr><td>'+x.join('</td><td>')+'</td></tr></table>';
}
*/
y = '<tr>'+x.map(function(xi){return '<td>'+jmat.html(xi).replace(/^<table>/,'').replace(/<\/table>$/,'')+'</td>'}).join('')+'</tr>';
y = '<table>'+y+'</table>';
}
else{// x is an Object
for(var xi in x){
y+='<li><b>'+xi+'</b>: '+x[xi]+'</li>';
}
}
break;
default:
//throw('jmat.html input type not recognized:',x);
y = ''+x;
}
return y;
//
},
im1to255:function(x){// converts {0-1} matrix into an im data matrix
4
},
imread:function(cv){ // reads image from context into matrix
// find out what type of input
if(typeof(cv)=='string'){ // cv is the id of a canvas element
cv=jmat.gId(cv)
}
var ct=cv.getContext('2d'), n=cv.width, m=cv.height;
var imData=ct.getImageData(0,0,n,m); // pixel values will be stored in imData.data
return this.imData2data(imData)
},
imhalve:function(dt0,PSmax){ // poor man's version of imresize, it halves an image size by averaging two rows/columns
var s = jmat.size(dt0);
if(!PSmax){PSmax = jmat.prod(s.slice(0,2))-1} // if maximum size not defined then just have it once
if(jmat.prod(s.slice(0,2))>PSmax){
if(jmat.length(s)!==3){throw('this should be an image value matrix, size n x m x 4')}
if(s[2]!==4){throw('this should be an image value matrix, size n x m x 4')}
s = jmat.arrayfun(s,function(x){return Math.floor(x/2)}); // half size, with floored integers
s[2]=4; // rgba
var dt = jmat.zeros(s[0],s[1],s[2]);
dt=dt.map(function(x,i){
return x.map(function(y,j){
return y.map(function(z,k){
return (dt0[i*2][j*2][k]+dt0[i*2+1][j*2+1][k]+dt0[i*2][j*2+1][k])/3;
})
})
});
}
else{var dt = dt0};
// if maximum pixel size was set and was exceeded keep halving
if(jmat.prod(jmat.size(dt).slice(0,2))>PSmax){dt = jmat.imhalve(dt,PSmax)}
return dt
},
imwrite:function(cv,im,dx,dy){
if(!dy){dx=0;dy=0} // default location
if(typeof(cv)=='string'){cv=jmat.gId(cv)} //cv can also be the id of a canvas element
if(!im.data){im=jmat.data2imData(im)} // such that im can also be the matrix created by imread
var ct = cv.getContext('2d');
ct.putImageData(im,dx,dy);
return ct;
},
image:function(cv,im,dx,dy){ // for consistency
return this.imwrite(cv,im,dx,dy);
},
imagesc:function(cv,dt,cm,fun,M){ // scales values to use full range of values. cv is the canvas, dt the data, and cm the colormap
if(!cm){cm=jmat.colormap()}
if(!fun){fun=function(){return 1}}; // opaque function
cm = jmat.transpose(cm); // to get one vector per channel
var n = cm[0].length-1; // should be 64-1=63
var I = jmat.dimfun(function(i){return i/(n)},n+1); // 64 numbers evenly spaced between 0 and 1
if(!M){M = jmat.max(jmat.max(dt))};
if(typeof(fun)=='string'){eval('fun='+fun)} // allow eval fun with transparencies
dt = jmat.arrayfun(dt,function(x){return [jmat.interp1(I,cm[0],[x/M])[0],jmat.interp1(I,cm[1],[x/M])[0],jmat.interp1(I,cm[2],[x/M])[0],fun(x)]});
dt = jmat.arrayfun(dt,function(x){return Math.round(255*x)});
if(!!cv){jmat.imwrite(cv,dt)};
return dt
},
imagebw:function(cv,dt,C0,C1){ // imagesc for binary matrices
if(!C0){C0=[0,0,0,0]}
if(!C1){C1=[255,255,255,255]}
var dt01 = jmat.arrayfun(dt,function(x){if(x==1){return C1}else{return C0}})
if(!!cv){jmat.imwrite(cv,dt01)};
return dt01;
},
imData2data:function(imData){ // imData is the data structure returned by canvas.getContext('2d').getImageData(0,0,n,m)
var m=imData.width, n=imData.height, data=[];
for (var i=0;i<n;i++){ //row
data[i]=[];
for (var j=0;j<m;j++){ // column
ij=(i*m+j)*4;
data[i][j]=[imData.data[ij],imData.data[ij+1],imData.data[ij+2],imData.data[ij+3]]
}
}
return data;
},
imMap:function(im,fun){ // applies function to all pixels of an image and returns the 2D map of fun values
if(!fun){fun=function(xy){return 0}} // in no fun return a 2D zero matrix
return im.map(function(x){
return x.map(function(xy){
return fun(xy)
})
})
},
im2bw:function(im,thr){ // segments 2d matrix into 0's and 1's for values below or above a threshold
return jmat.imMap(im,function(xy){
if(xy>=thr){return 1}
else{return 0}
}
)
},
interp1:function(X,Y,XI){ // linear interpolation, remember X is supposed to be sorted
var n = X.length;
var YI = XI.map(function(XIi){
var i=jmat.sum(X.map(function(Xi){if (Xi<XIi){return 1}else{return 0}}));
if (i==0){return Y[0]} // lower bound
else if (i==n){return Y[n-1]} // upper bound
else{return (Y[i-1]+(XIi-X[i-1])*(Y[i]-Y[i-1])/(X[i]-X[i-1]))}
});
return YI
},
ind:function(X,I){ // return vector of values reordered by vector of indexes
return I.map(function(i){return X[i]});
},
innerfun:function(x,y,fun){ // inner operations between two arrays
if(Array.isArray(x)){
return x.map(function(xi,i){return jmat.innerfun(xi,y[i],fun)});
}
else{
return fun(x,y)
}
},
length:function(x){ // js Array.length returns highest index, not always the numerical length
var n=0
for(var i in x){n++};
return n
},
load:function(url,cb,er){ // load script / JSON
var s = document.createElement('script');
s.src=url.replace("module.imagejs.googlecode.com/git","imagejs.org");
s.id = this.uid();
if(!!cb){s.onload=cb}
if(!!er){s.onerror=er}
document.body.appendChild(s);
setTimeout('document.body.removeChild(document.getElementById("'+s.id+'"));',30000); // is the waiting still needed ?
return s.id
},
loadSync:function(url,cb,er){ // Synchronous version of jmat.load
var s = document.createElement('script');
s.async=false; // <-- this is the only difference !
s.src=url;
s.id = this.uid();
if(!!cb){s.onload=cb}
if(!!er){s.onerror=er}
document.body.appendChild(s);
setTimeout('document.body.removeChild(document.getElementById("'+s.id+'"));',3000); // is the waiting still needed ?
return s.id
},
loadScripts:function(urls,cb,er){ // loading multiple scripts sequentially, runn callback after the last one is loaded
console.log('loading script '+urls[0]+' ...');
if (urls.length>1){jmat.load(urls[0],function(){jmat.loadScripts(urls.slice(1))})} // recursion
else {jmat.load(urls[0],cb,er)}
},
loadFiles:function(files,readAs,callback){
//<input type="file" id="files" multiple onchange="jmat.loadFiles(this.files,'readAsText')"></input> //<-- example of button for reading text files
if(!readAs){readAs='readAsDataURL'} // default is to read as dataURL
for(var i=0;i<files.length;i++){
this.readFile(files[i],readAs,callback)
}
return i
},
loadGoogleCoreChart:function(cb){ // load Google corechart visualization
if(!cb){cb=function(){}};
jmat.loadVar('google',function(){google.load('visualization', '1', {'callback':cb, 'packages':['corechart']})});
},
readFile:function(f,readAs,callback){
var that = this;
if(!callback){callback=function(x){ // DEAFAULT CALLBACK - you may want to write your own
console.log('---'+x.file.fileName+'---');console.log(x.result); // comment out if you don't want to track reading in the console
if(!that.work){that.work={}};if(!that.work.files){that.work.files=[]} // results stored in .work.files
that.work.files[x.file.fileName]={file:x.file,result:x.result}; // array indexed to file name
}
}
var reader = new FileReader();
reader.onload=(function(theFile){
return function(ev){
callback({file:theFile,result:ev.target.result})
}
})(f)
reader[readAs](f);
},
require:function(lib,fun){ // jmat's version of requirejs
// if a url then just load it
// if a variable name that doesn't exist then load it with loadVar
// if the variable is found to exist then move on
if(!fun){fun=function(){console.log('no fun required')}} // which is silly as it defaults to loadVar
if(typeof(lib)=='string'){lib=[lib]}
// check if this is a variable
var libfun=function(lib){
jmat.loadVar(lib[0],function(){
if(lib.length>1){
jmat.require(lib.slice(1),fun)
}
else{fun()} // have fun
})
}
if(!lib[0].match(/http[s]{0,1}:/)){ // it is a variable
if(typeof(window[lib[0]])=='undefined'){libfun(lib)} // load it only if it doesn't exist
}
else{libfun(lib)}
},
loadD3:function(callback){ // loads d3.js library
//jmat.load('http://mbostock.github.com/d3/d3.v2.js',callback);
jmat.load('d3.v2.min.js',callback);
},
log:function(x,n){
if (!n){return Math.log(x)}
else{return Math.log(x)/Math.log(n)}
},
loadVarCallBack:{},
loadVar:function(V,cb,er,cbId){ // check that an external library is loaded, V is the name of the variable, for example, "Q"
if(Array.isArray(V)){ // are there more than one?
if(!cbId){cbId=jmat.uid();jmat.loadVarCallBack[cbId]=cb}
//if(V.length==1){jmat.load(V[0],cb,er)}
//else if(V.length>1){jmat.load}
if(V.length>0){
if(V.length>1){jmat.loadVar(V[0],function(){jmat.loadVar(V.slice(1),cb,er,cbId)},er,cbId)}
else{ // V.length=1
jmat.loadVar(V[0],jmat.loadVarCallBack[cbId],er);
}
}
}
else{
var url;
switch(V){
case 'QM':
url = 'https://qmachine.org/q.js';break;
case 'CoffeeScript':
url = 'https://raw.github.com/jashkenas/coffee-script/master/extras/coffee-script.js';break;
case 'jQuery':
url='https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';break;
case 'jQuery.ui':
if(typeof(jQuery)=="undefined"){ // check for jQuery dependency
url="";
jmat.loadVar('jQuery',function(){jmat.loadVar(V,cb,er,cbId)});
}
else{
url='https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js';
// add css to head
lk = document.createElement('link');
lk.rel='stylesheet';
lk.href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/themes/smoothness/jquery-ui.css';
document.head.appendChild(lk);
}
break;
case 'd3':
url='https://cdnjs.cloudflare.com/ajax/libs/d3/3.0.1/d3.v3.min.js';break;
case 'google':
url='https://www.google.com/jsapi';break;
case 'minerva':
url='http://minervajs.org/api';break;
case 'usm':
url='https://raw.github.com/usm/usm.github.com/master/usm.js';break;
case 'crossfilter':
jmat.loadVar('d3'); // dependency
url='http://square.github.com/crossfilter/crossfilter.v1.min.js';break;
case 'S3QLtranslator':
url='http://js.s3db.googlecode.com/hg/translate/s3ql_translator.js';break;
case 'PUBNUB':
url='http://cdn.pubnub.com/pubnub-3.3.min.js';break;
case 'cBio':
url='https://dl.dropbox.com/s/x7yvewsh7xs1xtu/cBio.js?dl=1';break; // dev link
default :
if(!!V.match(/http[s]{0,1}:/)){url=V} // if it is a url
else{throw('No library was found to assemble "'+V+'"')};
}
if(url.length>0){
jmat.loadSync(url,cb,er);
console.log('variable "'+V+'"'+' loaded from '+url);
}
}
return V;
},
lookup:function(tbl,col_in,val_in,col_out){// lookup in table tbl,
// for value in column col_out where the column col_in has the value val_in
var val_out={};// return results as a table
// Find Columns
var col_in_i=this.findExact(tbl.columns,col_in);
if(col_in_i.length==0){throw('input column not found')}
// if output columns not specified then get all
if(!col_out){col_out=tbl.columns;var col_out_i=jmat.range(col_out.length-1)}
else{var col_out_i=this.find(tbl.columns,col_out)}
var rows = this.transpose(tbl.rows) , r=[] , Ind=[];
for(var c in col_in_i){
r=this.find(rows[col_in_i[c]],val_in);
if(r.length>0){for (var i in r){Ind.push(r[i])}}
}
Ind = this.unique(Ind);
val_out.columns=col_out_i.map(function(i){return tbl.columns[i]});
val_out.rows=this.zeros(Ind.length,col_out_i.length);
for(var i=0;i<val_out.columns.length;i++){
for(var j=0;j<Ind.length;j++){
val_out.rows[j][i]=rows[col_out_i[i]][Ind[j]]
}
}
return val_out;
},
lookupExact:function(tbl,col_in,val_in,col_out){// lookup in table tbl,
// for value in column col_out where the column col_in has the value val_in
var val_out={};// return results as a table
// Find Columns
var col_in_i=this.findExact(tbl.columns,col_in);
if(col_in_i.length==0){throw('input column not found')}
// if output columns not specified then get all
if(!col_out){col_out=tbl.columns;var col_out_i=jmat.range(col_out.length-1)}
else{var col_out_i=this.findExact(tbl.columns,col_out)}
var rows = this.transpose(tbl.rows) , r=[] , Ind=[];
for(var c in col_in_i){
r=this.findExact(rows[col_in_i[c]],val_in);
if(r.length>0){for (var i in r){Ind.push(r[i])}}
}
Ind = this.unique(Ind);
val_out.columns=col_out_i.map(function(i){return tbl.columns[i]});
val_out.rows=this.zeros(Ind.length,col_out_i.length);
for(var i=0;i<val_out.columns.length;i++){
for(var j=0;j<Ind.length;j++){
val_out.rows[j][i]=rows[col_out_i[i]][Ind[j]]
}
}
return val_out;
},
max:function(x){ //return maximum value of array
if(Array.isArray(x[0])){return x.map(function(xi){return jmat.max(xi)})}
else{return x.reduce(function(a,b){if(a>b){return a}else{return b}})};
//return x.reduce(function(a,b){if(a>b){return a}else{return b}})
},
max2:function(x){ // returns maximum value of array and its index, i.e. [max,i]
if(Array.isArray(x[0])){ // coded only up to 2 dimensions
var xx = jmat.transpose(x.map(function(xi){return jmat.max2(xi)}))
var y = jmat.max2(xx[0]);
return [y[0],[y[1],xx[1][y[1]]]];
}
else{return x.map(function(xi,i){return [xi,i]}).reduce(function(a,b){if(a[0]>b[0]){return a}else{return b}})};
//return x.map(function(xi,i){return [xi,i]}).reduce(function(a,b){if(a[0]>b[0]){return a}else{return b}})
},
min:function(x){ //return maximum value of array
return x.reduce(function(a,b){if(a<b){return a}else{return b}})
},
min2:function(x){ // returns maximum value of array and its index, i.e. [max,i]
return x.map(function(xi,i){return [xi,i]}).reduce(function(a,b){if(a[0]<b[0]){return a}else{return b}})
},
memb:function(x,dst){ // builds membership function
var n = x.length-1;
if(!dst){
dst = this.sort(x);
Ind=dst[1];
dst[1]=dst[1].map(function(z,i){return i/(n)});
var y = x.map(function(z,i){return dst[1][Ind[i]]});
return dst;
}
else{ // interpolate y from distributions, dst
var y = this.interp1(dst[0],dst[1],x);
return y;
}
},
not:function(x){ // negates Boolean value, or an array thereof
if(Array.isArray(x)){return x.map(function(xi){return jmat.not(xi)})}
else{return !x}
},
ones:function(){
return jmat.dimfun(function(){return 1},arguments)
},
parse:function(x){ // x is a stringified Object
eval('var res='+x);
return res;
},
parseUrl:function(url){ // parsing url and its arguments out
var u = {};u.url=url.match(/[htf]+tp[s]*:\/\/[^?]+/);
if (u.url.length!==1){throw ('something is wrong with the syntax this url: '+url)}
else{
u.url=u.url[0];u.parms={};url.slice(u.url.length+1).split('&').map(function(x){y=x.split('=');u.parms[y[0]]=y[1];return x});
}
return u
},
plot:function(ctx,x,y,s,opt){ // plot
if(this.class(ctx)!="CanvasRenderingContext2D"){ // get context then
switch (this.class(ctx)){
case "String":
ctx=jmat.gId(ctx).getContext('2d');
break;
case "HTMLCanvasElement":
// assume it is a canvas element
ctx=ctx.getContext('2d');
break;
}
}
//default opt
var opt0={
MarkerSize:12,
Color:[0,0,1],
MarkerEdgeColor:'auto',
MarkerFaceColor:'none',
x:x,
y:y
}
if(!opt){opt=opt0};
opt = jmat.cat(opt0,opt);
// inherit colors
if (typeof(opt.MarkerEdgeColor)=='string'){
if(opt.MarkerEdgeColor=='auto'){opt.MarkerEdgeColor=opt.Color}
else{opt.MarkerEdgeColor=[0,0,0,0]}
}
if (typeof(opt.MarkerFaceColor)=='string'){
if(opt.MarkerFaceColor=='auto'){opt.MarkerFaceColor=opt.Color}
else{opt.MarkerFaceColor=[0,0,0,0]} // string is 'none'
}
if(opt.Color.length==3){opt.Color}
var L=opt.MarkerSize;
switch(s){
case 'o': // draw a circle
ctx.beginPath();
ctx.strokeStyle=jmat.rgba(opt.MarkerEdgeColor);
ctx.arc(x,y,L/2,0,2*Math.PI,true);
ctx.closePath();
ctx.stroke();
break;
case 's': // draw a square
ctx.beginPath();
ctx.strokeStyle=jmat.rgba(opt.MarkerEdgeColor);
ctx.strokeRect(x-L/2,y-L/2,L,L);
ctx.closePath();
ctx.stroke();
break;
case '+': // draw a +
ctx.beginPath();
ctx.strokeStyle=jmat.rgba(opt.MarkerEdgeColor);
ctx.moveTo(x-L/2,y);ctx.lineTo(x+L/2,y);
ctx.moveTo(x,y-L/2);ctx.lineTo(x,y+L/2);
ctx.closePath();
ctx.stroke();
break;
case 'x': // draw a x
ctx.beginPath();
ctx.strokeStyle=jmat.rgba(opt.MarkerEdgeColor);
ctx.moveTo(x-L/2,y-L/2);ctx.lineTo(x+L/2,y+L/2);
ctx.moveTo(x-L/2,y+L/2);ctx.lineTo(x+L/2,y-L/2);
ctx.closePath();
ctx.stroke();
break;
case '*': // draw a *
this.plot(ctx,x,y,'+',opt);
opt.MarkerSize=L*Math.cos(Math.PI/4);
this.plot(ctx,x,y,'x',opt);
break;
}
// return handle structure
opt.x=x;
opt.y=y;
opt.radius=opt.MarkerSize;
return opt
},
/*
plot:function(id,x,y,opt){
if(typeof(google)=="undefined"){
jmat.loadGoogleCoreChart(function(){jmat.plot(id,x,y,opt)});
}
else if(typeof(!google.visualization)=="undefined"){
google.load('visualization', '1', {'callback':function(){jmat.plot(id,x,y,opt)}, 'packages':['corechart']})
}
else{
//console.log('plot');
var dt = jmat.transpose([x,y]);
dt.unshift(['x','y']);
var data = google.visualization.arrayToDataTable(dt);
var chart = new google.visualization.ScatterChart(jmat.div(id));
chart.draw(data);
}
},
*/
post:function(x,id){ // post x onto DOM element
if(typeof(jQuery)=='undefined'){jmat.loadVar('jQuery',function(){jmat.post(x,id)})}
else{