# All files / src utilities.ts

4.58% Statements 12/262
1.87% Branches 3/160
5.26% Functions 2/38
4.41% Lines 11/249

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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

    18x
    180x
    180x

    18x

    6x
    6x
    6x
    6x
    196560x

    6x

    18x

     //a collection of miscellaneous utility functions

    import { Gradient } from "./Gradient";
    import { VolumeData } from "./VolumeData";

    declare var $;

    //simplified version of $.extend
    export function extend(obj1, src1) {
        for (var key in src1) {
            if (src1.hasOwnProperty(key) && src1[key] !== undefined) {
                obj1[key] = src1[key];
            }
        }
        return obj1;
    };

    //deep copy, cannot deal with circular refs; undefined input becomes an empty object
    //https://medium.com/javascript-in-plain-english/how-to-deep-copy-objects-and-arrays-in-javascript-7c911359b089
    export function deepCopy(inObject) {
        let outObject, value, key;

        Iif (inObject == undefined) {
            return {};
        }
        Iif (typeof inObject !== "object" || inObject === null) {
            return inObject; // Return the value if inObject is not an object
        }

        // Create an array or object to hold the values
        outObject = Array.isArray(inObject) ? [] : {};

        for (key in inObject) {
            value = inObject[key];
            // Recursively (deep) copy for nested objects, including arrays
            outObject[key] = deepCopy(value);
        }

        return outObject;
    };

    export function isNumeric(obj) {

        var type = typeof (obj);
        return (type === "number" || type === "string") &&
            !isNaN(obj - parseFloat(obj));
    };

    export function isEmptyObject(obj) {
        var name;
        for (name in obj) {
            return false;
        }
        return true;
    };

    export function makeFunction(callback) {
        //for py3dmol let users provide callback as string
        Iif (callback && typeof callback === "string") {
            /* jshint ignore:start */
            callback = eval("(" + callback + ")");
            /* jshint ignore:end */
        }
        // report to console if callback is not a valid function
        Iif (callback && typeof callback != "function") {
            return null;
        }
        return callback;
    };

    //standardize voldata/volscheme in style
    export function adjustVolumeStyle(style) {
        Iif (style) {
            Iif (style.volformat && !(style.voldata instanceof VolumeData)) {
                style.voldata = new VolumeData(style.voldata, style.volformat);
            }
            Iif (style.volscheme) {
                style.volscheme = Gradient.getGradient(style.volscheme);
            }
        }
    };

    /**
     * computes the bounding box around the provided atoms
     * @param {AtomSpec[]} atomlist
     * @return {Array}
     */
    export function getExtent(atomlist, ignoreSymmetries?) {
        var xmin, ymin, zmin, xmax, ymax, zmax, xsum, ysum, zsum, cnt;
        var includeSym = !ignoreSymmetries;

        xmin = ymin = zmin = 9999;
        xmax = ymax = zmax = -9999;
        xsum = ysum = zsum = cnt = 0;

        Iif (atomlist.length === 0)
            return [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
        for (var i = 0; i < atomlist.length; i++) {
            var atom = atomlist[i];
            Iif (typeof atom === 'undefined' || !isFinite(atom.x) ||
                !isFinite(atom.y) || !isFinite(atom.z))
                continue;
            cnt++;
            xsum += atom.x;
            ysum += atom.y;
            zsum += atom.z;

            xmin = (xmin < atom.x) ? xmin : atom.x;
            ymin = (ymin < atom.y) ? ymin : atom.y;
            zmin = (zmin < atom.z) ? zmin : atom.z;
            xmax = (xmax > atom.x) ? xmax : atom.x;
            ymax = (ymax > atom.y) ? ymax : atom.y;
            zmax = (zmax > atom.z) ? zmax : atom.z;

            Iif (atom.symmetries && includeSym) {
                for (var n = 0; n < atom.symmetries.length; n++) {
                    cnt++;
                    xsum += atom.symmetries[n].x;
                    ysum += atom.symmetries[n].y;
                    zsum += atom.symmetries[n].z;
                    xmin = (xmin < atom.symmetries[n].x) ? xmin : atom.symmetries[n].x;
                    ymin = (ymin < atom.symmetries[n].y) ? ymin : atom.symmetries[n].y;
                    zmin = (zmin < atom.symmetries[n].z) ? zmin : atom.symmetries[n].z;
                    xmax = (xmax > atom.symmetries[n].x) ? xmax : atom.symmetries[n].x;
                    ymax = (ymax > atom.symmetries[n].y) ? ymax : atom.symmetries[n].y;
                    zmax = (zmax > atom.symmetries[n].z) ? zmax : atom.symmetries[n].z;
                }
            }
        }

        return [[xmin, ymin, zmin], [xmax, ymax, zmax],
        [xsum / cnt, ysum / cnt, zsum / cnt]];
    };

    /* get the min and max values of the specified property in the provided
    * @function $3Dmol.getPropertyRange
    * @param {AtomSpec[]} atomlist - list of atoms to evaluate
    * @param {string} prop - name of property
    * @return {Array} - [min, max] values
    */
    export function getPropertyRange(atomlist, prop) {
        var min = Number.POSITIVE_INFINITY;
        var max = Number.NEGATIVE_INFINITY;

        for (var i = 0, n = atomlist.length; i < n; i++) {
            var atom = atomlist[i];
            var val = getAtomProperty(atom, prop);

            Iif (val != null) {
                Iif (val < min)
                    min = val;
                Iif (val > max)
                    max = val;
            }
        }

        if (!isFinite(min) && !isFinite(max))
            min = max = 0;
        else if (!isFinite(min))
            min = max;
        else Iif (!isFinite(max))
            max = min;

        return [min, max];
    };

    //adapted from https://stackoverflow.com/questions/3969475/javascript-pause-settimeout
    export class PausableTimer {
        ident: any;
        total_time_run = 0;
        start_time: number;
        countdown: number;
        fn: any;
        arg: any;

        constructor(fn, countdown, arg?) {
            this.fn = fn;
            this.arg = arg;
            this.countdown = countdown;
            this.start_time = new Date().getTime();
            this.ident = setTimeout(fn, countdown, arg);
        }

        cancel() {
            clearTimeout(this.ident);
        }

        pause() {
            clearTimeout(this.ident);
            this.total_time_run = new Date().getTime() - this.start_time;
        }

        resume() {
            this.ident = setTimeout(this.fn, Math.max(0, this.countdown - this.total_time_run), this.arg);
        }

    };

    /**
     * Convert a base64 encoded string to a Uint8Array
     * @function $3Dmol.base64ToArray
     * @param {string} base64 encoded string
     */
    export function base64ToArray(base64) {
        var binary_string = window.atob(base64);
        var len = binary_string.length;
        var bytes = new Uint8Array(len);
        for (var i = 0; i < len; i++) {
            bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes;
    };

    //return the value of an atom property prop, or null if non existent
    // looks first in properties, then in the atom itself
    export function getAtomProperty(atom, prop) {
        var val = null;
        if (atom.properties &&
            typeof (atom.properties[prop]) != "undefined") {
            val = atom.properties[prop];
        } else Iif (typeof (atom[prop]) != 'undefined') {
            val = atom[prop];
        }
        return val;
    };

    //Miscellaneous functions and classes - to be incorporated into $3Dmol proper
    /**
     *
     * @param {$3Dmol.Geometry} geometry
     * @param {$3Dmol.Mesh} mesh
     * @returns {undefined}
     */
    export function mergeGeos(geometry, mesh) {

        var meshGeo = mesh.geometry;

        Iif (meshGeo === undefined)
            return;

        geometry.geometryGroups.push(meshGeo.geometryGroups[0]);

    };

    /**
     * Parse a string that represents a style or atom selection and convert it
     * into an object.  The goal is to make it easier to write out these specifications
     * without resorting to json. Objects cannot be defined recursively.
     * ; - delineates fields of the object
     * : - if the field has a value other than an empty object, it comes after a colon
     * , - delineates key/value pairs of a value object
     *     If the value object consists of ONLY keys (no = present) the keys are
     *     converted to a list.  Otherwise a object of key/value pairs is created with
     *     any missing values set to null
     * = OR ~ - separates key/value pairs of a value object, if not provided value is null
     *     twiddle is supported since = has special meaning in URLs
     * @param (String) str
     * @returns {Object}
     */
    export function specStringToObject(str) {
        if (typeof (str) === "object") {
            return str; //not string, assume was converted already
        }
        else Iif (typeof (str) === "undefined" || str == null) {
            return str;
        }

        str = str.replace(/%7E/, '~'); //copy/pasting urls sometimes does this
        //convert things that look like numbers into numbers
        var massage = function (val) {
            if (isNumeric(val)) {
                //hexadecimal does not parse as float
                if (Math.floor(parseFloat(val)) == parseInt(val)) {
                    return parseFloat(val);
                }
                else if (val.indexOf('.') >= 0) {
                    return parseFloat(val); // ".7" for example, does not parseInt
                }
                else {
                    return parseInt(val);
                }
            }
            //boolean conversions
            else if (val === 'true') {
                return true;
            }
            else Iif (val === 'false') {
                return false;
            }
            return val;
        };

        var ret = {};
        Iif (str === 'all') return ret;
        var fields = str.split(';');
        for (var i = 0; i < fields.length; i++) {
            var fv = fields[i].split(':');
            var f = fv[0];
            var val = {};
            var vstr = fv[1];
            Iif (vstr) {
                vstr = vstr.replace(/~/g, "=");
                if (vstr.indexOf('=') !== -1) {
                    //has key=value pairs, must be object
                    var kvs = vstr.split(',');
                    for (var j = 0; j < kvs.length; j++) {
                        var kv = kvs[j].split('=', 2);
                        val[kv[0]] = massage(kv[1]);
                    }
                }
                else if (vstr.indexOf(',') !== -1) {
                    //has multiple values, must list
                    val = vstr.split(',');
                }
                else {
                    val = massage(vstr); //value itself
                }
            }
            ret[f] = val;
        }

        return ret;
    };

    /**
    *
    * jquery.binarytransport.js
    *
    * @description. jQuery ajax transport for making binary data type requests.
    * @version 1.0
    * @author Henry Algus <henryalgus@gmail.com>
    *
    */

    // use this transport for "binary" data type
    $.ajaxTransport(
        "+binary",
        function (options, originalOptions, jqXHR) {
            // check for conditions and support for blob / arraybuffer response type
            Iif (window.FormData && ((options.dataType && (options.dataType == 'binary')) ||
                (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) ||
                    (window.Blob && options.data instanceof Blob))))) {
                return {
                    // create new XMLHttpRequest
                    send: function (headers, callback) {
                        // setup all variables
                        var xhr = new XMLHttpRequest(), url = options.url, type = options.type, async = options.async || true,
                            // blob or arraybuffer. Default is blob
                            dataType = options.responseType || "blob",
                            data = options.data || null,
                            username = options.username || null,
                            password = options.password || null;

                        var xhrret = function () {
                            var data = {};
                            data[options.dataType] = xhr.response;
                            // make callback and send data
                            callback(xhr.status, xhr.statusText,
                                data,
                                xhr.getAllResponseHeaders());
                        };

                        xhr.addEventListener('load', xhrret);
                        xhr.addEventListener('error', xhrret);
                        xhr.addEventListener('abort', xhrret);

                        xhr.open(type, url, async, username,
                            password);

                        // setup custom headers
                        for (var i in headers) {
                            xhr.setRequestHeader(i, headers[i]);
                        }

                        xhr.responseType = dataType;
                        xhr.send(data);
                    },
                    abort: function () {
                        jqXHR.abort();
                    }
                };
            }
        });

    /**
     * Download binary data (e.g. a gzipped file) into an array buffer and provide
     * arraybuffer to callback.
     * @function $3Dmol.getbin
     * @param {string} uri - location of data
     * @param {Function} [callback] - Function to call with arraybuffer as argument.
     * @param {string} [request] - type of request
     * @param {string} [postdata] - data for POST request
     * @return {Promise}
     */
    export function getbin(uri, callback?, request?, postdata?) {
        var promise = new Promise<ArrayBufferLike>(function (resolve, reject) {

            request = (request == undefined) ? "GET" : request;
            $.ajax({
                url: uri,
                dataType: "binary",
                method: request,
                data: postdata,
                responseType: "arraybuffer",
                processData: false
            })
                .done(function (ret) {
                    resolve(ret);
                })
                .fail(function (e, txt) {
                    console.log(txt);
                    reject();
                });
        });
        if (callback) return promise.then(callback);
        else return promise;
    };

    /**
     * Load a PDB/PubChem structure into existing viewer. Automatically calls 'zoomTo' and 'render' on viewer after loading model
     * @function $3Dmol.download
     * @param {string} query - String specifying pdb or pubchem id; must be prefaced with "pdb: " or "cid: ", respectively
     * @param {$3Dmol.GLViewer} viewer - Add new model to existing viewer
     * @param {Object} options - Specify additional options
     *                           format: file format to download, if multiple are available, default format is pdb
     *                           pdbUri: URI to retrieve PDB files, default URI is http://www.rcsb.org/pdb/files/
     * @param {Function} [callback] - Function to call with model as argument after data is loaded.

     * @return {$3Dmol.GLModel} GLModel, Promise if callback is not provided
     * @example
     viewer.setBackgroundColor(0xffffffff);
           $3Dmol.download('pdb:2nbd',viewer,{onemol: true,multimodel: true},function(m) {
            m.setStyle({'cartoon':{colorscheme:{prop:'ss',map:$3Dmol.ssColors.Jmol}}});
           viewer.zoomTo();
           viewer.render(callback);
        });
     */
    export function download(query, viewer, options, callback?) {
        var type = "";
        var pdbUri = "";
        var mmtfUri = "";
        var uri = "";
        var promise = null;
        var m = viewer.addModel();

        Iif (query.indexOf(':') < 0) {
            //no type specifier, guess
            if (query.length == 4) {
                query = 'pdb:' + query;
            } else if (!isNaN(query)) {
                query = 'cid:' + query;
            } else {
                query = 'url:' + query;
            }
        }
        if (query.substr(0, 5) === 'mmtf:') {
            pdbUri = options && options.pdbUri ? options.pdbUri : "https://mmtf.rcsb.org/v1.0/full/";
            query = query.substr(5).toUpperCase();
            uri = pdbUri + query;
            Iif (options && typeof options.noComputeSecondaryStructure === 'undefined') {
                //when fetch directly from pdb, trust structure annotations
                options.noComputeSecondaryStructure = true;
            }
            promise = new Promise(function (resolve) {
                getbin(uri)
                    .then(function (ret) {
                        m.addMolData(ret, 'mmtf', options);
                        viewer.zoomTo();
                        viewer.render();
                        resolve(m);
                    }, function () { console.log("fetch of " + uri + " failed."); });
            });
        }
        else {
            if (query.substr(0, 4) === 'pdb:') {
                type = 'mmtf';
                Iif (options && options.format) {
                    type = options.format; //can override and require pdb
                }

                Iif (options && typeof options.noComputeSecondaryStructure === 'undefined') {
                    //when fetch directly from pdb, trust structure annotations
                    options.noComputeSecondaryStructure = true;
                }
                query = query.substr(4).toUpperCase();
                Iif (!query.match(/^[1-9][A-Za-z0-9]{3}$/)) {
                    alert("Wrong PDB ID");
                    return;
                }
                if (type == 'mmtf') {
                    mmtfUri = options && options.mmtfUri ? options.mmtfUri : 'https://mmtf.rcsb.org/v1.0/full/';
                    uri = mmtfUri + query.toUpperCase();
                }
                else {
                    pdbUri = options && options.pdbUri ? options.pdbUri : "https://files.rcsb.org/view/";
                    uri = pdbUri + query + "." + type;
                }

            } else if (query.substr(0, 4) == 'cid:') {
                type = "sdf";
                query = query.substr(4);
                Iif (!query.match(/^[0-9]+$/)) {
                    alert("Wrong Compound ID"); return;
                }
                uri = "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/" + query +
                    "/SDF?record_type=3d";
            } else Iif (query.substr(0, 4) == 'url:') {
                uri = query.substr(4);
                type = uri;
            }

            var handler = function (ret) {
                m.addMolData(ret, type, options);
                viewer.zoomTo();
                viewer.render();
            };
            promise = new Promise(function (resolve) {
                if (type == 'mmtf') { //binary data
                    getbin(uri)
                        .then(function (ret) {
                            handler(ret);
                            resolve(m);
                        }).catch(function () {
                            //if mmtf server is being annoying, fallback to text
                            pdbUri = options && options.pdbUri ? options.pdbUri : "https://files.rcsb.org/view/";
                            uri = pdbUri + query + ".pdb";
                            type = "pdb";
                            console.log("falling back to pdb format");
                            $.get(uri, function (ret) {
                                handler(ret);
                                resolve(m);
                            }).fail(function (e) {
                                handler("");
                                resolve(m);
                                console.log("fetch of " + uri + " failed: " + e.statusText);
                            });
                        }); //an error msg has already been printed
                }
                else {
                    $.get(uri, function (ret) {
                        handler(ret);
                        resolve(m);
                    }).fail(function (e) {
                        handler("");
                        resolve(m);
                        console.log("fetch of " + uri + " failed: " + e.statusText);
                    });
                }
            });
        }
        if (callback) {
            promise.then(function (m) {
                callback(m);
            });
            return m;
        }
        else return promise;
    };