-
Notifications
You must be signed in to change notification settings - Fork 0
/
st.js
4500 lines (4213 loc) · 165 KB
/
st.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
!function(){
var st = {version: "0.0.3"};
/**
* util stub.
*
* @author Stephan Beisken <[email protected]>
* @constructor
*/
st.util = {};
/**
* Simple hash-based object cache.
*
* Adapted from:
* http://markdaggett.com/blog/2012/03/28/
* client-side-request-caching-with-javascript/
*
* @author Stephan Beisken <[email protected]>
* @returns {object} object literal with a add, get, getKey, and exists property
*
* @example
* var cache = st.util.cache();
* var cacheKey = cache.getKey(myObject);
* if (cache.exists(cacheKey)) {
* var cachedObject = cache.get(cacheKey);
* } else {
* var cachedObject = myObject;
* cache.add(cacheKey, cachedObject);
* }
*/
st.util.cache = function () {
var cache = {},
keys = [],
/**
* Returns an element's index in an array or -1.
*
* @param {object[]} arr An element array
* @param {object} obj An element
* @returns {number} the element's index or -1
*/
indexOf = function (arr, obj) {
var len = arr.length;
for (var i = 0; i < len; i++) {
if (arr[i] === obj) {
return i;
}
}
return -1;
},
/**
* Returns a string representation of any input.
*
* @param {object} opts An input to stringify
* @returns {string} the stringified input object
*/
serialize = function (opts) {
if ((opts).toString() === "[object Object]") {
return $.param(opts);
} else {
return (opts).toString();
}
},
/**
* Removes an element from the cache via its key.
*
* @param {string} key The element's key
*/
remove = function (key) {
var t;
if ((t = indexOf(keys, key)) > -1) {
keys.splice(t, 1);
delete cache[key];
}
},
/**
* Removes all elements from the cache.
*/
removeAll = function () {
cache = {};
keys = [];
},
/**
* Adds an element to the cache.
*
* @param {string} key The element's key
* @param {object} obj The element to be added
*/
add = function (key, obj) {
if (keys.indexOf(key) === -1) {
keys.push(key);
}
cache[key] = obj;
},
/**
* Checks whether a key has already been added to the cache.
*
* @param {string} key The element's key
* @returns {boolean} whether the key exists in the cache
*/
exists = function (key) {
return cache.hasOwnProperty(key);
},
/**
* Removes a selected or all elements from the cache.
*
* @returns {object[]} the purged cache array
*/
purge = function () {
if (arguments.length > 0) {
remove(arguments[0]);
} else {
removeAll();
}
return $.extend(true, {}, cache);
},
/**
* Returns matching keys from the cache in an array.
*
* @param {string} str The query key (string)
* @returns {string[]} the array of matching keys
*/
searchKeys = function (str) {
var keys = [];
var rStr;
rStr = new RegExp('\\b' + str + '\\b', 'i');
$.each(keys, function (i, e) {
if (e.match(rStr)) {
keys.push(e);
}
});
return keys;
},
/**
* Returns the element for a given key.
*
* @param {string} key The element's key
* @returns {object} the key's cached object
*/
get = function (key) {
var val;
if (cache[key] !== undefined) {
if ((cache[key]).toString() === "[object Object]") {
val = $.extend(true, {}, cache[key]);
} else {
val = cache[key];
}
}
return val;
},
/**
* Returns the string representation of the element.
*
* @param {object} opts The element to be stringified
* @returns {string} the string representation fo the element
*/
getKey = function (opts) {
return serialize(opts);
},
/**
* Returns all keys stored in the cache.
*
* @returns {string[]} the array of keys
*/
getKeys = function () {
return keys;
};
// reference visible (public) functions as properties
return {
add: add,
get: get,
getKey: getKey,
exists: exists,
};
};
/**
* Color object that consistently returns one of six different colors
* for a given identifier.
*
* @author Stephan Beisken <[email protected]>
* @constructor
* @returns {object} object literal with a get and remove property
*/
st.util.colors = function () {
var colors = {
0: "red",
1: "blue",
2: "green",
3: "orange",
4: "yellow",
5: "black"
},
mapping = {}; // stores the id - color mappings
mapping.size = function() {
var size = -1, key;
for (key in this) {
if (this.hasOwnProperty(key)) {
size++;
}
}
return size;
};
/**
* Gets the color for the identifier or - if id is unassigned - returns
* a new color from the color hash.
*
* @param {int} id A series identifier
* @returns {string} the color string for the identifier
*/
var get = function (id) {
if (mapping[id]) {
return mapping[id];
}
var col = next();
mapping[id] = col;
return mapping[id];
},
/**
* Removes the color for the identifier from the mapping.
*
* @param {int} id An series identifier
*/
remove = function (id) {
if (mapping[id]) {
delete mapping[id];
}
},
/**
* Returns the color string based on the running index. Resets the
* index if it exceeds the color hash.
*
* @returns {string} the color string
*/
next = function () {
var ncolors = Object.keys(colors).length;
var nmappings = mapping.size();
var index = nmappings % ncolors;
return colors[index];
};
// reference visible (public) functions as properties
return {
get: get,
remove: remove
};
};
/**
* Simple hash code generator for strings.
*
* @author Stephan Beisken <[email protected]>
* @param {string} str A string to be hashed
* @returns {number} the hashed string
*/
st.util.hashcode = function (str) {
var hash = 0, i, chr, len;
if (str.length == 0) return hash;
for (i = 0, len = str.length; i < len; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // convert to 32bit integer
}
return hash;
};
/**
* Helper function to resolve the order of domain extrema based on the
* direction of the scale, e.g. for inverted axes the min and max values
* need to be inverted.
*
* @author Stephan Beisken <[email protected]>
* @param {object} scale A d3 scale
* @param {number[]} array An array of length two with a min/max pair
* @returns {number[]} the sorted array
*/
st.util.domain = function (scale, array) {
var domain = scale.domain();
if (domain[0] > domain[1]) {
return [
array[1],
array[0]
];
}
return [
array[0],
array[1]
];
};
/**
* SVG molecule renderer for MDL Molfiles. The header block and
* connection table are loosely parsed according to Elsevier MDL's V2000
* format.
*
* The molecule title is taken from the header block.
*
* The two dimensional coordinates, symbol, charge, and mass difference
* information is extracted from the atom block.
*
* Connectivity and stereo information is extracted from the bond block.
* Single, double, and triple bonds as well as symbols for wedge, hash,
* and wiggly bonds are supported.
*
* The renderer uses the CPK coloring convention.
*
* Initializes the renderer setting the width and height of
* the viewport. The width and height should include a margin
* of 10 px, which is applied all around by default.
*
* @author Stephan Beisken <[email protected]>
* @constructor
* @param {number} width A width of the viewport
* @param {number} height A height of the viewport
* @returns {object} object literal with a draw property
*/
st.util.mol2svg = function (width, height) {
var w = width || 200, // width of the panel
h = height || 200, // height of the panel
x = null, // linear d3 x scale function
y = null, // linear d3 y scale function
avgL = 0, // scaled average bond length (for font size scaling)
cache = st.util.cache();
/**
* Loads the molfile data asynchronously, parses the file and
* creates the SVG. The SVG is appended to the element of the
* given identifier.
*
* @param {string} molfile A URL of the MDL molfile (REST web service)
* @param {string} id An identifier of the element
* @returns {object} a XHR promise
*/
var draw = function (molfile, id) {
var jqxhr;
var el = d3.select(id);
var cacheKey = cache.getKey(molfile);
if (cache.exists(cacheKey)) {
var text = cache.get(cacheKey);
parse(text, el);
} else {
jqxhr = $.when(
$.get(molfile)
)
.fail(function() {
console.log('Request failed for: ' + molfile);
})
.then(function(text) {
cache.add(cacheKey, text);
try {
parse(text, el);
} catch (err) {
console.log('Mol2Svg Error:' + err);
el.html('');
}
});
}
return jqxhr;
};
/**
* Parses the molfile, extracting the molecule title from the
* header block, two dimensional coordinates, symbol, charge,
* and mass difference information extracted from the atom block,
* connectivity and stereo information from the bond block.
*
* @param {string} molfile A URL to the MDL molfile (REST web service)
* @param {string} id An element identifier
*/
var parse = function (molfile, el) {
var lines = molfile.split(/\r\n|\n/),
// title = lines[1],
counter = lines[3].match(/\d+/g),
nAtoms = parseFloat(counter[0]),
nBonds = parseFloat(counter[1]);
var atoms = atomBlock(lines, nAtoms), // get all atoms
bonds = bondBlock(lines, nAtoms, nBonds); // get all bonds
propsBlock(lines, atoms, nAtoms + nBonds); // get properties
var graph = initSvg(atoms, el); // layout SVG
drawBonds(atoms, bonds, graph);
drawAtoms(atoms, avgL, graph);
};
/**
* Parses the atom block line by line.
*
* @param {string[]} lines A molfile line array
* @param {number} nAtoms The total number of atoms
* @returns {object[]} associative array of atom objects
*/
var atomBlock = function (lines, nAtoms) {
var atoms = [];
var offset = 4; // the first three lines belong to the header block
for (var i = offset; i < nAtoms + offset; i++) {
var atom = lines[i].match(/-*\d+\.\d+|\w+/g);
atoms.push({
x: parseFloat(atom[0]),
y: parseFloat(atom[1]),
symbol: atom[3],
mass: 0, // deprecated
charge: 0 // deprecated
});
}
return atoms;
};
/**
* Parses the bond block line by line.
*
* @param {string[]} lines A molfile line array
* @param {number} nAtoms The total number of atoms
* @param {number} nBonds The total number of bonds
* @returns {object[]} associative array of bond objects
*/
var bondBlock = function (lines, nAtoms, nBonds) {
var bonds = [];
var offset = 4; // the first three lines belong to the header block
for (var j = nAtoms + offset; j < nAtoms + nBonds + offset; j++) {
var bond = lines[j].match(/\d+/g);
bonds.push({
// adjust to '0', atom counter starts at '1'
a1: parseInt(bond[0]) - 1,
a2: parseInt(bond[1]) - 1,
// values 1, 2, 3
order: parseInt(bond[2]),
// values 0 (plain),1 (wedge),4 (wiggly),6 (hash)
stereo: parseInt(bond[3])
});
}
return bonds;
};
/**
* Parses the properties block line by line.
*
* @param {string[]} lines A molfile line array
* @param {object[]} atoms An array of atom objects
* @param {number} nAtomsBonds The total number of atoms and bonds
*/
var propsBlock = function (lines, atoms, nAtomsBonds) {
var offset = 4; // the first three lines belong to the header block
for (var k = nAtomsBonds + offset; k < lines.length; k++) {
if (lines[k].indexOf('M ISO') !== -1) {
var props = lines[k].match(/-*\d+/g);
for (var l = 0, m = 1; l < props[0]; l++, m += 2) {
atoms[props[m] - 1].mass = parseInt(props[m + 1], 10);
}
} else if (lines[k].indexOf('M CHG') !== -1) {
var props = lines[k].match(/-*\d+/g);
for (var l = 0, m = 1; l < props[0]; l++, m += 2) {
atoms[props[m] - 1].charge = parseInt(props[m + 1], 10);
}
}
}
};
/**
* Initializes the viewport and appends it to the element identified
* by the given identifier. The linear d3 x- and y-scales are set
* to translate from the viewport coordinates to the mol coordinates.
*
* @param {object[]} atoms An array of atom objects
* @param {string} id An element identifier
* @returns {object} the initialized SVG element
*/
var initSvg = function (atoms, el) {
// x minimum and maximum
var xExtrema = d3.extent(atoms, function (atom) {
return atom.x;
});
// y minimum and maximum
var yExtrema = d3.extent(atoms, function (atom) {
return atom.y;
});
// dimensions of molecule graph
var m = [20, 20, 20, 20]; // margins
var wp = w - m[1] - m[3]; // width
var hp = h - m[0] - m[2]; // height
// maintain aspect ratio: divide/multiply height/width by the ratio (r)
var r = (xExtrema[1] - xExtrema[0]) / (yExtrema[1] - yExtrema[0]);
if (r > 1) {
hp /= r;
} else {
wp *= r;
}
// X scale will fit all values within pixels 0-w
x = d3.scale.linear().domain([xExtrema[0], xExtrema[1]]).range([0, wp]);
// Y scale will fit all values within pixels h-0
y = d3.scale.linear().domain([yExtrema[0], yExtrema[1]]).range([hp, 0]);
// add an SVG element with the desired dimensions
// and margin and center the drawing area
var graph = el.append('svg:svg')
.attr('width', wp + m[1] + m[3])
.attr('height', hp + m[0] + m[2])
.append('svg:g')
.attr('transform', 'translate(' + m[3] + ',' + m[0] + ')');
return graph;
};
/**
* Draws the bonds onto the SVG element. Note that the bonds are drawn
* first before anything else is added.
*
* @param {object[]} atoms An array of atom objects
* @param {object[]} bonds An array of bond objects
* @param {object} graph A SVG element
*/
var drawBonds = function (atoms, bonds, graph) {
for (var i = 0; i < bonds.length; i++) {
var a1 = atoms[bonds[i].a1],
a2 = atoms[bonds[i].a2];
// apply backing by calculating the unit vector and
// subsequent scaling: shortens the drawn bond
var dox = a2.x - a1.x,
doy = a2.y - a1.y,
l = Math.sqrt(dox * dox + doy * doy),
dx = (dox / l) * (0.2),
dy = (doy / l) * (0.2);
// get adjusted x and y coordinates
var x1 = a1.x + dx,
y1 = a1.y + dy,
x2 = a2.x - dx,
y2 = a2.y - dy;
// update average bond length for font scaling
avgL += distance(x(x1), y(y1), x(x2), y(y2));
var off, // offset factor for stereo bonds
xOff, // total offset in x
yOff, // total offset in y
xyData = []; // two dimensional data array
if (bonds[i].order === 1) { // single bond
if (bonds[i].stereo === 1) { // single wedge bond
var length = distance(x1, y1, x2, y2);
off = 0.1;
xOff = off * (y2 - y1) / length;
yOff = off * (x1 - x2) / length;
xyData = [
[x1, y1],
[x2 + xOff, y2 + yOff],
[x2 - xOff, y2 - yOff]
];
graph.append('svg:path')
.style('fill', 'black')
.style('stroke-width', 1)
.attr('d', wedgeBond(xyData));
} else if (bonds[i].stereo === 6) { // single hash bond
off = 0.2;
xOff = off * (y2 - y1) / l;
yOff = off * (x1 - x2) / l;
var dxx1 = x2 + xOff - x1,
dyy1 = y2 + yOff - y1,
dxx2 = x2 - xOff - x1,
dyy2 = y2 - yOff - y1;
for (var j = 0.05; j <= 1; j += 0.15) {
xyData.push(
[x1 + dxx1 * j, y1 + dyy1 * j],
[x1 + dxx2 * j, y1 + dyy2 * j]
);
}
graph.append('svg:path')
.style('fill', 'none')
.style('stroke-width', 1)
.attr('d', hashBond(xyData))
.attr('stroke', 'black');
} else if (bonds[i].stereo === 4) { // single wiggly bond
off = 0.2;
xOff = off * (y2 - y1) / l;
yOff = off * (x1 - x2) / l;
var dxx1 = x2 + xOff - x1,
dyy1 = y2 + yOff - y1,
dxx2 = x2 - xOff - x1,
dyy2 = y2 - yOff - y1;
for (var j = 0.05; j <= 1; j += 0.1) {
if (xyData.length % 2 === 0) {
xyData.push(
[x1 + dxx1 * j, y1 + dyy1 * j]
);
} else {
xyData.push(
[x1 + dxx2 * j, y1 + dyy2 * j]
);
}
}
graph.append('svg:path')
.attr('d', wigglyBond(xyData))
.attr('fill', 'none')
.style('stroke-width', 1)
.attr('stroke', 'black');
} else { // single plain bond
xyData = [
[x1, y1], [x2, y2]
];
graph.append('svg:path')
.attr('d', plainBond(xyData))
.attr('stroke-width', '1')
.attr('stroke-linecap', 'round')
.attr('stroke-linejoin', 'round')
.attr('stroke', 'black');
}
} else if (bonds[i].order === 2) { // double bond
off = 0.1;
xOff = off * (y2 - y1) / l;
yOff = off * (x1 - x2) / l;
xyData = [
[x1 + xOff, y1 + yOff], [x2 + xOff, y2 + yOff],
[x1 - xOff, y1 - yOff], [x2 - xOff, y2 - yOff]
];
graph.append('svg:path').attr('d', plainBond(xyData))
.attr('stroke-width', '1')
.style('fill', 'none')
.attr('stroke-linecap', 'round')
.attr('stroke-linejoin', 'round')
.attr('stroke', 'black');
} else if (bonds[i].order === 3) { // triple bond
off = 0.15;
xOff = off * (y2 - y1) / l;
yOff = off * (x1 - x2) / l;
xyData = [
[x1, y1], [x2, y2],
[x1 + xOff, y1 + yOff], [x2 + xOff, y2 + yOff],
[x1 - xOff, y1 - yOff], [x2 - xOff, y2 - yOff]
];
graph.append('svg:path')
.attr('d', plainBond(xyData))
.attr('stroke-width', '1')
.attr('stroke-linecap', 'round')
.attr('stroke-linejoin', 'round')
.attr('stroke', 'black');
}
}
avgL /= bonds.length; // get average bond length
};
/**
* Draws the atoms onto the SVG element. Note that the atoms are drawn
* on top of the bonds.
*
* @param {object[]} atoms An array of atom objects
* @param {number} avgL An average bond length
* @param {object} graph A SVG element
*/
var drawAtoms = function (atoms, avgL, graph) {
for (var i = 0; i < atoms.length; i++) {
var atom = atoms[i];
var atomCol = d3.rgb(atomColor[atom.symbol]);
var g = graph.append('svg:g')
.attr('transform', 'translate(' +
x(atom.x) + ',' + y(atom.y) + ')');
// draw a circle underneath the text
g.append('svg:circle')
// hack: magic number for scaling
.attr('r', Math.ceil(avgL / 3))
.attr('fill', 'white')
.attr('opacity', '1');
// draw the text string
g.append('text')
// hack: magic number for scaling
.attr('dy', Math.ceil(avgL / 4.5))
.attr('text-anchor', 'middle')
.attr('font-family', 'sans-serif')
// hack: magic number for scaling
.attr('font-size', Math.ceil(avgL / 1.5))
.attr('fill', atomCol)
.text(atom.symbol);
if (atom.charge !== 0) {
var c = atom.charge;
if (c < 0) {
c = (c === -1) ? '-' : (c + '-');
} else {
c = (c === +1) ? '+' : (c + '+');
}
g.append('text')
.attr('dx', +1 * Math.ceil(avgL / 3))
.attr('dy', -1 * Math.ceil(avgL / 4.5))
.attr('text-anchor', 'left')
.attr('font-family', 'sans-serif')
// hack: magic number for scaling (half of symbol size)
.attr('fill', atomCol)
.attr('font-size', Math.ceil(avgL / 3))
.text(c);
}
if (atom.mass !== 0) {
g.append('text')
.attr('dx', -2 * Math.ceil(avgL / 3))
.attr('dy', -1 * Math.ceil(avgL / 4.5))
.attr('text-anchor', 'left')
.attr('font-family', 'sans-serif')
// hack: magic number for scaling (half of symbol size)
.attr('font-size', Math.ceil(avgL / 3))
.attr('fill', atomCol)
.text(atom.mass);
}
}
};
/**
* Calculates the Euclidean distance between two points.
*
* @param {number} x1 A x value of first point
* @param {number} y1 A y value of first point
* @param {number} x2 A x value of second point
* @param {number} y2 A y value of second point
* @returns {number} the Euclidean distance
*/
var distance = function (x1, y1, x2, y2) {
return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
};
/**
* d3 line function using the SVG path mini language to draw a plain bond.
*/
var plainBond = d3.svg.line()
.interpolate(function (points) {
var path = points[0][0] + ',' + points[0][1];
for (var i = 1; i < points.length; i++) {
if (i % 2 === 0) {
path += 'M' + points[i][0] + ',' + points[i][1];
} else {
path += 'L' + points[i][0] + ',' + points[i][1];
}
}
return path;
})
.x(function (d) {
return x(d[0]);
})
.y(function (d) {
return y(d[1]);
});
/**
* d3 line function using the SVG path mini language to draw a wedge bond.
*/
var wedgeBond = d3.svg.line()
.x(function (d) {
return x(d[0]);
})
.y(function (d) {
return y(d[1]);
});
/**
* d3 line function using the SVG path mini language to draw a hash bond.
*/
var hashBond = d3.svg.line()
.interpolate(function (points) {
var path = points[0][0] + ',' + points[0][1];
for (var i = 1; i < points.length; i++) {
if (i % 2 === 0) {
path += 'M' + points[i][0] + ',' + points[i][1];
} else {
path += 'L' + points[i][0] + ',' + points[i][1];
}
}
return path;
})
.x(function (d) {
return x(d[0]);
})
.y(function (d) {
return y(d[1]);
});
/**
* d3 line function using the SVG path mini language to draw a wiggly bond.
*/
var wigglyBond = d3.svg.line()
.interpolate('cardinal')
.x(function (d) {
return x(d[0]);
})
.y(function (d) {
return y(d[1]);
});
/*
* Atom properties containing the CPK color values.
*/
var atomColor = {
H: '#000000',
He: '#FFC0CB',
Li: '#B22222',
B: '#00FF00',
C: '#000000',
N: '#8F8FFF',
O: '#F00000',
F: '#DAA520',
Na: '#0000FF',
Mg: '#228B22',
Al: '#808090',
Si: '#DAA520',
P: '#FFA500',
S: '#FFC832',
Cl: '#00FF00',
Ca: '#808090',
Ti: '#808090',
Cr: '#808090',
Mn: '#808090',
Fe: '#FFA500',
Ni: '#A52A2A',
Cu: '#A52A2A',
Zn: '#A52A2A',
Br: '#A52A2A',
Ag: '#808090',
I: '#A020F0',
Ba: '#FFA500',
Au: '#DAA520'
};
// reference visible (public) functions as properties
return {
draw: draw
};
};
/**
* Helper function to create divs for the spinner animation (defined in css).
*
* @author Stephan Beisken <[email protected]>
* @constructor
* @param {string} el An element identifier to append the spinner to
* @return {object} the spinner element
*/
st.util.spinner = function (el) {
if ($('.st-spinner').length) { // singleton
return $('.st-spinner');
}
// append the sub-divs to the spinner element
$(el).append('<div class="st-spinner">' +
'<div class="st-bounce1"></div>' +
'<div class="st-bounce2"></div>' +
'<div class="st-bounce3"></div>' +
'</div>');
return $('.st-spinner');
};
/**
* Builds a compare function to sort an array of objects.
*
* @author Stephan Beisken <[email protected]>
* @constructor
* @param {string} xacc An x value accessor
* @return {object} the compare function
*/
st.util.compare = function (xacc) {
var compare = function (a, b) {
if (a[xacc] < b[xacc]) {
return -1;
}
if (a[xacc] > b[xacc]) {
return 1;
}
return 0;
};
return compare;
};
/**
* Enum for annotation types.
*
* @author Stephan Beisken <[email protected]>
* @enum {string}
*/
st.annotation = {
TOOLTIP: 'tooltip', // tooltip text, plain text key value pairs
TOOLTIP_MOL: 'tooltip_mol', // tooltip molecule, resolves URLs to SDfiles
ANNOTATION: 'annotation', // canvas annotation, drawn onto the canvas
ANNOTATION_COLOR: 'annotation_color' // canvas annotation color
};
/**
* parser stub.
*
* Parsers for input data should extend this stub.
*
* @author Stephan Beisken <[email protected]>
* @constructor
*/
st.parser = {};
/**
* Incomplete rudimentary JCAMP-DX parser for PAC compressed files and
* arrays of type ##XYDATA= (X++(Y..Y)).
*
* @author Stephan Beisken <[email protected]>
* @constructor
* @deprecated
* @param {string} url A url to the JCAMP-DX file
* @param {function} callback A callback function
*/
st.parser.jdx = function (url, callback) {
// d3 AJAX request to resolve the URL
d3.text(url, function (jdx) {
// essential key definitions
var LABEL = '##',
END = 'END',
XYDATA = 'XYDATA',
YTABLE = '(X++(Y..Y))',
//XFACTOR = 'XFACTOR',
YFACTOR = 'YFACTOR',
FIRSTX = 'FIRSTX',
LASTX = 'LASTX';
//NPOINTS = 'NPOINTS';
// the data store
var objs = [];
// tmp helper objects
var obj = {},
data = false,
points = [];
// tmp helper objects
var pair,
key,
pkey,
value;
// split input text into separate lines
var lines = jdx.split(/\r\n|\r|\n/g);
// iterate over all lines
for (var i in lines) {
var line = lines[i];
if (line.indexOf(LABEL) === 0) {
pair = line.split(/=\s(.*)/); // split key-value pair
if (pair.length < 2) { // sanity check
continue;
}
key = pair[0].slice(2); // parse key
value = pair[1].split(/\$\$(.*)/)[0].trim();// parse value
if (key === XYDATA && value === YTABLE) {
data = true; // boolean flag whether this is a data table
} else if (key === END) {
if (data) { // clean up after a data table has been parsed
if (parseFloat(obj[FIRSTX]) >
parseFloat(obj[LASTX])) {
points.reverse();
}
obj[pkey] = points;
objs.push(obj);
// reset
obj = {};
data = false;
points = [];
}
data = false;
} else {
obj[key] = value;
}
pkey = key;
} else if (data) {
//var deltax = (obj[LASTX] - obj[FIRSTX]) / (obj[NPOINTS] - 1);
var entries = line.match(/(\+|-)*\d+\.*\d*/g);
//var x = obj[XFACTOR] * entries[0];
for (var j = 1; j < entries.length; j++) {
//x += (j - 1) * deltax;
var y = obj[YFACTOR] * entries[j];
points.push(y);
}
}
}
callback(objs);
});
};
/**
* Default data object. Custom data objects should extend this data stub.
*
* @author Stephan Beisken <[email protected]>
* @constructor
* @returns {object} the default data object
*/
st.data = {};