manager.ts 34.9 KB
Newer Older
Lukas Pravda's avatar
Lukas Pravda committed
1
class Visualization {
Lukas Pravda's avatar
Lukas Pravda committed
2 3
    // component related
    private parent: HTMLElement;
Lukas Pravda's avatar
Lukas Pravda committed
4

Lukas Pravda's avatar
Lukas Pravda committed
5
    // #region svg properties
Lukas Pravda's avatar
Lukas Pravda committed
6 7
    private simulation: d3.Simulation<d3.SimulationNodeDatum, undefined>;
    private svg: d3.Selection<any, {}, HTMLElement, any>;
Lukas Pravda's avatar
Lukas Pravda committed
8
    private canvas: d3.Selection<SVGGElement, {}, HTMLElement, any>;
Lukas Pravda's avatar
Lukas Pravda committed
9

Lukas Pravda's avatar
Lukas Pravda committed
10 11 12 13 14
    private depictionRoot: d3.Selection<SVGGElement, {}, HTMLElement, any>;
    private nodesRoot: d3.Selection<SVGGElement, {}, HTMLElement, any>;
    private linksRoot: d3.Selection<SVGGElement, {}, HTMLElement, any>;

    private zoomHandler: d3.ZoomBehavior<Element, unknown>
Lukas Pravda's avatar
Lukas Pravda committed
15 16

    private nodes: any;
Lukas Pravda's avatar
Lukas Pravda committed
17
    private links: any;
Lukas Pravda's avatar
Lukas Pravda committed
18
    // #endregion
Lukas Pravda's avatar
Lukas Pravda committed
19

Lukas Pravda's avatar
Lukas Pravda committed
20
    // #region data properties    
Lukas Pravda's avatar
Lukas Pravda committed
21
    private environment: Model.Environment;
Lukas Pravda's avatar
Lukas Pravda committed
22
    private pdbId: string;
23 24
    private bindingSites: Model.BindingSite[];
    private presentBindingSite: Model.BindingSite;
Lukas Pravda's avatar
Lukas Pravda committed
25
    private depiction: Depiction;
Lukas Pravda's avatar
Lukas Pravda committed
26

Lukas Pravda's avatar
Lukas Pravda committed
27
    private visualsMapper: VisualsMapper;
Lukas Pravda's avatar
Lukas Pravda committed
28
    private interactionsData: any;
Lukas Pravda's avatar
Lukas Pravda committed
29
    private selectedResidueHash: string;
30 31

    private rProvider: ResidueProvider;
Lukas Pravda's avatar
Lukas Pravda committed
32

33
    public fullScreen: boolean;
Lukas Pravda's avatar
Lukas Pravda committed
34
    // #endregion
Lukas Pravda's avatar
Lukas Pravda committed
35

Lukas Pravda's avatar
Lukas Pravda committed
36
    constructor(element: HTMLElement, uiParameters: Config.UIParameters = undefined, env: string = "production") {
Lukas Pravda's avatar
Lukas Pravda committed
37
        this.parent = element;
Lukas Pravda's avatar
Lukas Pravda committed
38
        this.environment = this.parseEnvironment(env);
Lukas Pravda's avatar
Lukas Pravda committed
39 40
        this.parent.style.cssText += "display: block; height: 100%; width: 100%; position: relative;";

41 42
        this.visualsMapper = new VisualsMapper(this.environment);
        this.rProvider = ResidueProvider.getInstance(this.environment);
Lukas Pravda's avatar
Lukas Pravda committed
43
        this.fullScreen = false;
44
        this.bindingSites = new Array<Model.BindingSite>();
Lukas Pravda's avatar
Lukas Pravda committed
45

Lukas Pravda's avatar
Lukas Pravda committed
46
        if (uiParameters === undefined) uiParameters = new Config.UIParameters();
Lukas Pravda's avatar
Lukas Pravda committed
47

Lukas Pravda's avatar
Lukas Pravda committed
48
        new UI(this.parent, this).register(uiParameters);
Lukas Pravda's avatar
Lukas Pravda committed
49

Lukas Pravda's avatar
Lukas Pravda committed
50 51
        this.svg = d3.select(this.parent)
            .append('div')
52
            .attr('id', 'pdb-lig-env-root')
Lukas Pravda's avatar
Lukas Pravda committed
53
            .append('svg')
Lukas Pravda's avatar
Lukas Pravda committed
54
            .style('background-color', 'white')
Lukas Pravda's avatar
Lukas Pravda committed
55
            .attr('xmlns', 'http://www.w3.org/2000/svg')
Lukas Pravda's avatar
Lukas Pravda committed
56
            .attr('width', '100%')
Lukas Pravda's avatar
Lukas Pravda committed
57 58 59 60 61 62 63
            .attr('height', '100%');

        this.canvas = this.svg.append('g').attr('id', 'vis-root');
        this.linksRoot = this.canvas.append('g').attr('id', 'links');
        this.depictionRoot = this.canvas.append('g').attr('id', 'depiction');
        this.nodesRoot = this.canvas.append('g').attr('id', 'nodes');

Lukas Pravda's avatar
Lukas Pravda committed
64
        if (uiParameters.zoom) this.zoomHandler = this.getZoomHandler();
Lukas Pravda's avatar
Lukas Pravda committed
65

Lukas Pravda's avatar
Lukas Pravda committed
66 67 68
        document.addEventListener(Config.molstarClickEvent, e => this.nodeMouseEnterEventHandler(e));
        document.addEventListener(Config.molstarMouseoverEvent, e => this.nodeMouseEnterEventHandler(e));
        document.addEventListener(Config.molstarMouseoutEvent, () => this.nodeMouseLeaveEventHandler());
Lukas Pravda's avatar
Lukas Pravda committed
69

Lukas Pravda's avatar
Lukas Pravda committed
70 71
        d3.select(this.parent).on('resize', () => this.resize());
        this.addMarkers();
Lukas Pravda's avatar
Lukas Pravda committed
72 73
    }

Lukas Pravda's avatar
Lukas Pravda committed
74
    // #region even handlers
75 76 77 78 79 80
    private getZoomHandler() {
        return d3.zoom()
            .scaleExtent([1 / 10, 10])
            .on('zoom', () => this.canvas
                .attr('transform', d3.event.transform));
    }
Lukas Pravda's avatar
Lukas Pravda committed
81

82

Lukas Pravda's avatar
Lukas Pravda committed
83
    private nodeMouseEnterEventHandler(e: any) {
84 85
        if (this.fullScreen) return;

Lukas Pravda's avatar
Lukas Pravda committed
86
        let hash = `${e.eventData.auth_asym_id}${e.eventData.auth_seq_id}${e.eventData.ins_code}`;
Lukas Pravda's avatar
Lukas Pravda committed
87

Lukas Pravda's avatar
Lukas Pravda committed
88
        this.nodes?.each((node: Model.InteractionNode, index: number, group: any) => {
89 90
            this.nodeDim(node, index, group);
            
Lukas Pravda's avatar
Lukas Pravda committed
91 92 93 94 95 96 97 98 99 100
            if (node.id === hash) {
                this.selectedResidueHash = hash;
                this.nodeHighlight(node, index, group);
                return;
            }
        });

    }


Lukas Pravda's avatar
Lukas Pravda committed
101
    private nodeMouseLeaveEventHandler() {
102 103
        if (this.fullScreen) return;

Lukas Pravda's avatar
Lukas Pravda committed
104 105 106 107 108 109
        this.nodes?.each((node: Model.InteractionNode, index: number, group: any) => {
            if (node.id == this.selectedResidueHash) {
                this.nodeDim(node, index, group);
                return;
            }
        });
Lukas Pravda's avatar
Lukas Pravda committed
110 111 112
    }

    private linkMouseClickEventHandler(x: Model.Link) {
Lukas Pravda's avatar
Lukas Pravda committed
113
        this.fireExternalLinkEvent(x, Config.interactionClickEvent);
Lukas Pravda's avatar
Lukas Pravda committed
114 115
    }

Lukas Pravda's avatar
Lukas Pravda committed
116 117 118 119
    private linkMouseOverEventHandler(x: Model.Link, index: number, group: any) {
        let parent = d3.select(group[index]).node().parentNode;
        d3.select(parent).classed('pdb-lig-env-svg-bond-highlighted', true);

Lukas Pravda's avatar
Lukas Pravda committed
120
        this.fireExternalLinkEvent(x, Config.interactionMouseoverEvent);
Lukas Pravda's avatar
Lukas Pravda committed
121 122
    }

Lukas Pravda's avatar
Lukas Pravda committed
123 124 125 126
    private linkMouseOutEventHandler(index: number, group: any) {
        let parent = d3.select(group[index]).node().parentNode;
        d3.select(parent).classed('pdb-lig-env-svg-bond-highlighted', false);

127
        this.fireExternalLinkLeaveEvent();
Lukas Pravda's avatar
Lukas Pravda committed
128
    }
Lukas Pravda's avatar
Lukas Pravda committed
129

Lukas Pravda's avatar
Lukas Pravda committed
130
    private dragHandler = d3.drag()
131
        .filter((x: Model.InteractionNode) => !x.static)
Lukas Pravda's avatar
Lukas Pravda committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
        .on('start', (x: Model.InteractionNode) => {
            if (!d3.event.active) this.simulation.alphaTarget(0.3).restart();

            x.fx = x.x;
            x.fy = x.y;
        })
        .on('drag', (x: Model.InteractionNode) => {
            x.fx = d3.event.x;
            x.fy = d3.event.y;
        })
        .on('end', (x: Model.InteractionNode) => {
            if (!d3.event.active) this.simulation.alphaTarget(0);
            x.fx = d3.event.x;
            x.fy = d3.event.y;
        });

    // #endregion event handlers

150
    // #region public methods
Lukas Pravda's avatar
Lukas Pravda committed
151 152 153 154 155 156 157 158 159 160 161 162
    /**
     * Download bound molecule interactions data from PDBe Graph API end point
     * /pdb/bound_molecule_interactions
     * 
     * Correct parameters can be obtained using API call:
     * /pdb/bound_molecules
     *
     * @param {string} pdbid
     * @param {string} bmId bound molecule identifier: e.g. bm1, bm2, ...
     * @memberof Visualization
     */
    public initBoundMoleculeInteractions(pdbid: string, bmId: string) {
Lukas Pravda's avatar
Lukas Pravda committed
163
        this.pdbId = pdbid;
Lukas Pravda's avatar
Lukas Pravda committed
164
        let url = Resources.boundMoleculeAPI(pdbid, bmId, this.environment);
Lukas Pravda's avatar
Lukas Pravda committed
165

Lukas Pravda's avatar
Lukas Pravda committed
166
        d3.json(url)
Lukas Pravda's avatar
Lukas Pravda committed
167
            .catch(e => this.processError(e, 'No interactions data are available.'))
168 169 170
            .then((data: any) => this.addBoundMoleculeInteractions(data, bmId))
            .then(() => new Promise(resolve => setTimeout(resolve, 1500)))
            .then(() => this.centerScene());
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    }

    /**
     * Download carbohydrate interactions data from PDBe Graph API end point
     * /pdb/carbohydrate_polymer_interactions
     * 
     * Correct parameters can be obtained using API call:
     * /pdb/bound_molecules
     *
     * @param {string} pdbid
     * @param {string} bmId bound molecule identifier: e.g. bm1, bm2, ...
     * @param {string} entityId
     * @memberof Visualization
     */
    public initCarbohydratePolymerInteractions(pdbid: string, bmId: string, entityId: string) {
        this.pdbId = pdbid;
Lukas Pravda's avatar
Lukas Pravda committed
187
        let url = Resources.carbohydratePolymerAPI(pdbid, bmId, entityId, this.environment);
188 189 190 191

        d3.json(url)
            .catch(e => this.processError(e, 'No interactions to display'))
            .then((data: any) => this.addBoundMoleculeInteractions(data, bmId))
192 193
            .then(() => new Promise(resolve => setTimeout(resolve, 1500)))
            .then(() => this.centerScene());
Lukas Pravda's avatar
Lukas Pravda committed
194
    }
Lukas Pravda's avatar
Lukas Pravda committed
195

Lukas Pravda's avatar
Lukas Pravda committed
196 197 198 199 200 201 202 203 204 205 206 207 208 209
    /**
     * Download ligand interactions data from PDBe Graph API end point
     * /pdb/bound_ligand_interactions.
     * 
     * Correct parameters can be obtained using API call:
     * /pdb/bound_molecules
     * 
     * @param {string} pdbId pdb id
     * @param {number} resId residue number aka: auth_seq_id
     * @param {string} chainId chain id aka: auth_asym_id
     * @memberof Visualization
     */
    public initLigandInteractions(pdbId: string, resId: number, chainId: string) {
        this.pdbId = pdbId;
Lukas Pravda's avatar
Lukas Pravda committed
210
        let url = Resources.ligandInteractionsAPI(pdbId, chainId, resId, this.environment);
Lukas Pravda's avatar
Lukas Pravda committed
211

Lukas Pravda's avatar
Lukas Pravda committed
212
        d3.json(url)
Lukas Pravda's avatar
Lukas Pravda committed
213
            .catch(e => this.processError(e, 'No interactions data are available.'))
214 215 216
            .then((data: any) => this.addLigandInteractions(data))
            .then(() => new Promise(resolve => setTimeout(resolve, 1500)))
            .then(() => this.centerScene());
Lukas Pravda's avatar
Lukas Pravda committed
217 218
    }

Lukas Pravda's avatar
Lukas Pravda committed
219 220 221 222 223 224 225 226 227
    /**
     * Download ligand structure given the anotation generated by the 
     * PDBeChem process.
     *
     * @param {string} ligandId
     * @returns
     * @memberof Visualization
     */
    public async initLigandDisplay(ligandId: string) {
228
        const ligandUrl = Resources.ligandAnnotationAPI(ligandId, this.environment);
229

Lukas Pravda's avatar
Lukas Pravda committed
230
        return d3.json(ligandUrl)
Lukas Pravda's avatar
Lukas Pravda committed
231
            .catch(e => this.processError(e, `Component ${ligandId} was not found.`))
232
            .then((d: any) => this.addDepiction(d))
Lukas Pravda's avatar
Lukas Pravda committed
233
            .then(() => this.centerScene());
Lukas Pravda's avatar
Lukas Pravda committed
234 235
    }

Lukas Pravda's avatar
Lukas Pravda committed
236

Lukas Pravda's avatar
Lukas Pravda committed
237 238 239 240 241 242 243
    /**
     * Add depiction to the canvas from external resource.
     *
     * @param {*} depiction Content of annotation.json file generated by
     * the PDBeChem process.
     * @memberof Visualization
     */
244
    public addDepiction(depiction: any) {
Lukas Pravda's avatar
Lukas Pravda committed
245
        this.depiction = new Depiction(this.depictionRoot, depiction);
246
        this.depiction.draw();
Lukas Pravda's avatar
Lukas Pravda committed
247 248 249 250
    }


    /**
251 252
     * Add atom highlight to the ligand structure. The previous highlight
     * is going to be removed.
Lukas Pravda's avatar
Lukas Pravda committed
253
     *
254 255
     * @param {string[]} highlight List of atom names to be highlighted.
     * @param {string} [color=undefined] Color in #HEXHEX format.
Lukas Pravda's avatar
Lukas Pravda committed
256 257 258 259 260 261
     * @memberof Visualization
     */
    public addLigandHighlight(highlight: string[], color: string = undefined) {
        this.depiction.highlightSubgraph(highlight, color);
    }

262 263 264 265 266 267 268 269 270 271 272 273
    /**
     * Add contours to the ligand structure. The previous contours are
     * going to be removed.
     *
     * @param {*} data
     * @memberof Visualization
     */
    public addContours(data: any) {
        this.depiction.addContour(data);
    }


Lukas Pravda's avatar
Lukas Pravda committed
274 275 276 277 278 279 280 281
    public toogleZoom(active: boolean) {
        if (active) {
            this.zoomHandler = this.getZoomHandler();
        } else {
            this.zoomHandler = undefined;
        }
    }

282

Lukas Pravda's avatar
Lukas Pravda committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296
    /**
     * Add ligand interactions to the canvas
     *
     * @param {*} data Data content of the API end point 
     * /pdb/bound_ligand_interactions
     * @memberof Visualization
     */
    public addLigandInteractions(data: any) {
        let key = Object.keys(data)[0];
        let body = data[key][0];
        this.interactionsData = data;

        if (this.depiction === undefined || this.depiction.ccdId !== body.ligand.chem_comp_id) {
            this.initLigandDisplay(body.ligand.chem_comp_id).then(() => {
297 298
                this.presentBindingSite = new Model.BindingSite().fromLigand(key, body, this.depiction);
                this.bindingSites.push(this.presentBindingSite);
Lukas Pravda's avatar
Lukas Pravda committed
299
                this.setupLigandScene();
Lukas Pravda's avatar
Lukas Pravda committed
300
            });
Lukas Pravda's avatar
Lukas Pravda committed
301
        } else {
302 303
            this.presentBindingSite = new Model.BindingSite().fromLigand(key, body, this.depiction);
            this.bindingSites.push(this.presentBindingSite);
Lukas Pravda's avatar
Lukas Pravda committed
304 305 306 307
            this.setupLigandScene();
        }
    }

308

Lukas Pravda's avatar
Lukas Pravda committed
309 310 311 312 313 314 315 316 317 318 319
    /**
     * Add bound molecule interactions to the canvas.
     *
     * @param {*} data Data content of the API end point 
     * /pdb/bound_molecule_interactions
     * @param {string} bmId Bound molecule id
     * @memberof Visualization
     */
    public addBoundMoleculeInteractions(data: any, bmId: string) {
        let key = Object.keys(data)[0];
        this.interactionsData = data;
320
        this.presentBindingSite = new Model.BindingSite().fromBoundMolecule(key, data[key][0]);
Lukas Pravda's avatar
Lukas Pravda committed
321

322 323 324
        this.bindingSites.push(this.presentBindingSite);
        this.presentBindingSite.bmId = bmId;
        let ligands = this.presentBindingSite.residues.filter(x => x.isLigand);
Lukas Pravda's avatar
Lukas Pravda committed
325 326 327

        if (ligands.length === 1) this.initLigandInteractions(this.pdbId, ligands[0].authorResidueNumber, ligands[0].chainId);
        else this.setupScene();
Lukas Pravda's avatar
Lukas Pravda committed
328 329
    }

330

Lukas Pravda's avatar
Lukas Pravda committed
331
    // #region menu functions
Lukas Pravda's avatar
Lukas Pravda committed
332
    public saveSvg() {
333
        d3.text(Resources.ligEnvCSSAPI(this.environment))
Lukas Pravda's avatar
Lukas Pravda committed
334
            .then(x => {
335
                let svgData = `
Lukas Pravda's avatar
Lukas Pravda committed
336 337 338 339 340 341
                <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" style="background-color: white;">
                ${this.svg.html()}
                <style>
                /* <![CDATA[ */ \n ${x} \n /* ]]> */
                </style>
                </svg>`;
Lukas Pravda's avatar
Lukas Pravda committed
342

343 344 345
                let svgBlob = new Blob([svgData], { type: 'image/svg;charset=utf-8' });
                let svgUrl = URL.createObjectURL(svgBlob);
                let downloadLink = document.createElement('a');
Lukas Pravda's avatar
Lukas Pravda committed
346

347 348
                downloadLink.href = svgUrl;
                downloadLink.download = this.getSVGName();
349

350 351 352 353
                document.body.appendChild(downloadLink);
                downloadLink.click();
                document.body.removeChild(downloadLink);
            });
Lukas Pravda's avatar
Lukas Pravda committed
354 355
    }

Lukas Pravda's avatar
Lukas Pravda committed
356

357 358 359 360 361
    /**
     * Download interactions data in the JSON format.
     *
     * @memberof Visualization
     */
Lukas Pravda's avatar
Lukas Pravda committed
362
    public downloadInteractionsData(): void {
Lukas Pravda's avatar
Lukas Pravda committed
363
        let downloadLink = document.createElement('a');
Lukas Pravda's avatar
Lukas Pravda committed
364
        let dataBlob = new Blob([JSON.stringify(this.interactionsData, null, 4)], { type: 'application/json' });
Lukas Pravda's avatar
Lukas Pravda committed
365

Lukas Pravda's avatar
sync  
Lukas Pravda committed
366
        downloadLink.href = URL.createObjectURL(dataBlob);
367
        downloadLink.download = this.interactionsData === undefined ? 'no name.json' : `${this.pdbId}_${this.presentBindingSite.bmId}_interactions.json`;
Lukas Pravda's avatar
Lukas Pravda committed
368 369 370 371 372 373
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
    }


374 375 376 377 378
    /**
     * Reinitialize the scene (basicaly rerun the simulation to place interaction partners)
     *
     * @memberof Visualization
     */
Lukas Pravda's avatar
Lukas Pravda committed
379
    public reinitialize() {
380
        
381 382 383 384 385 386 387
        if (this.bindingSites.length > 1 && this.depiction !== undefined) {
            this.presentBindingSite = this.bindingSites[0];
            this.bindingSites.pop();
            
            this.depictionRoot.selectAll('*').remove();
            this.depiction = undefined;
            
Lukas Pravda's avatar
Lukas Pravda committed
388
            this.nullNodesPositions();
389 390 391
            this.setupScene().then(() => this.centerScene());
        }
        else if (this.depiction === undefined) { 
Lukas Pravda's avatar
Lukas Pravda committed
392
            this.nullNodesPositions();
393 394 395
            this.setupScene().then(() => this.centerScene());
        }
        else {
Lukas Pravda's avatar
Lukas Pravda committed
396
            this.nullNodesPositions();
397 398
            this.setupLigandScene().then(() => this.centerScene());
        }
Lukas Pravda's avatar
Lukas Pravda committed
399

Lukas Pravda's avatar
Lukas Pravda committed
400
        this.hideLigandLabel();
Lukas Pravda's avatar
Lukas Pravda committed
401
    }
Lukas Pravda's avatar
Lukas Pravda committed
402

Lukas Pravda's avatar
Lukas Pravda committed
403

Lukas Pravda's avatar
Lukas Pravda committed
404

Lukas Pravda's avatar
Lukas Pravda committed
405
    /**
406
     * Center scene to the viewbox
Lukas Pravda's avatar
Lukas Pravda committed
407 408 409
     *
     * @memberof Visualization
     */
Lukas Pravda's avatar
Lukas Pravda committed
410
    public centerScene() {
Lukas Pravda's avatar
Lukas Pravda committed
411
        // Get the bounding box
Lukas Pravda's avatar
Lukas Pravda committed
412 413 414
        if (this.nodes !== undefined) {
            let minX: any = d3.min(this.nodes.data().map((x) => x.x));
            let minY: any = d3.min(this.nodes.data().map((x) => x.y));
Lukas Pravda's avatar
Lukas Pravda committed
415

Lukas Pravda's avatar
Lukas Pravda committed
416 417
            let maxX: any = d3.max(this.nodes.data().map((x) => x.x));
            let maxY: any = d3.max(this.nodes.data().map((x) => x.y));
Lukas Pravda's avatar
Lukas Pravda committed
418

Lukas Pravda's avatar
Lukas Pravda committed
419
            this.computeBoundingBox(minX, maxX, minY, maxY);
Lukas Pravda's avatar
Lukas Pravda committed
420

Lukas Pravda's avatar
Lukas Pravda committed
421 422 423 424 425 426 427 428 429 430 431 432
        } else if (this.depiction !== undefined) {
            let minX: any = d3.min(this.depiction.atoms.map((x: Atom) => x.position.x));
            let minY: any = d3.min(this.depiction.atoms.map((x: Atom) => x.position.y));

            let maxX: any = d3.max(this.depiction.atoms.map((x: Atom) => x.position.x));
            let maxY: any = d3.max(this.depiction.atoms.map((x: Atom) => x.position.y));

            this.computeBoundingBox(minX, maxX, minY, maxY);
        }
    }

    private computeBoundingBox(minX: number, maxX: number, minY: number, maxY: number) {
Lukas Pravda's avatar
Lukas Pravda committed
433 434 435 436 437
        // The width and the height of the graph
        let molWidth = maxX - minX;
        let molHeight = maxY - minY;

        // how much larger the drawing area is than the width and the height
Lukas Pravda's avatar
Lukas Pravda committed
438 439
        let widthRatio = this.parent.offsetWidth / molWidth;
        let heightRatio = this.parent.offsetHeight / molHeight;
Lukas Pravda's avatar
Lukas Pravda committed
440 441 442

        // we need to fit it in both directions, so we scale according to
        // the direction in which we need to shrink the most
Lukas Pravda's avatar
Lukas Pravda committed
443
        let minRatio = Math.min(widthRatio, heightRatio) * 0.85;
Lukas Pravda's avatar
Lukas Pravda committed
444 445 446 447 448 449

        // the new dimensions of the molecule
        let newMolWidth = molWidth * minRatio;
        let newMolHeight = molHeight * minRatio;

        // translate so that it's in the center of the window
Lukas Pravda's avatar
Lukas Pravda committed
450 451
        let xTrans = -(minX) * minRatio + (this.parent.offsetWidth - newMolWidth) / 2;
        let yTrans = -(minY) * minRatio + (this.parent.offsetHeight - newMolHeight) / 2;
Lukas Pravda's avatar
Lukas Pravda committed
452 453

        // do the actual moving
Lukas Pravda's avatar
Lukas Pravda committed
454
        this.canvas.attr('transform', `translate(${xTrans}, ${yTrans}) scale(${minRatio})`);
Lukas Pravda's avatar
Lukas Pravda committed
455 456 457 458

        // tell the zoomer what we did so that next we zoom, it uses the
        // transformation we entered here        

Lukas Pravda's avatar
Lukas Pravda committed
459
        let translation = d3.zoomIdentity.translate(xTrans, yTrans).scale(minRatio);
Lukas Pravda's avatar
Lukas Pravda committed
460 461
        this.zoomHandler?.transform(this.svg, translation);

Lukas Pravda's avatar
Lukas Pravda committed
462
    };
463

Lukas Pravda's avatar
Lukas Pravda committed
464 465
    // #endregion menu functions

466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
    // #endregion public methods

    private resize() {
        this.svg
            .attr('width', this.parent.offsetWidth)
            .attr('height', this.parent.offsetHeight);

        if (this.depiction === undefined) {
            this.simulation
                .force('center', d3.forceCenter(this.parent.offsetWidth / 2, this.parent.offsetHeight / 2))
                .restart();
        } else this.simulation.restart();

        if (this.zoomHandler !== undefined) this.zoomHandler(this.svg);
    }

    private getSVGName(): string {
483
        if (this.presentBindingSite !== undefined) return `${this.presentBindingSite.bmId}.svg`;
484 485
        if (this.depiction !== undefined) return `${this.depiction.ccdId}.svg`;

486
        return 'blank.svg';
487 488
    }

Lukas Pravda's avatar
Lukas Pravda committed
489 490 491 492 493 494 495 496 497 498
    private nullNodesPositions() { 
        this.presentBindingSite.interactionNodes.forEach((x: Model.InteractionNode) => {
            if (!x.static) {
                x.fx = null;
                x.fy = null;
            }
        });

    }

Lukas Pravda's avatar
Lukas Pravda committed
499
    // #region fire events
500

Lukas Pravda's avatar
Lukas Pravda committed
501
    //https://stackoverflow.com/questions/40722344/understanding-d3-with-an-example-mouseover-mouseup-with-multiple-arguments
502
    private fireExternalNodeMouseEnterEvent(x: Model.InteractionNode, i: number, g: any) {
Lukas Pravda's avatar
Lukas Pravda committed
503
        this.nodeHighlight(x, i, g);
Lukas Pravda's avatar
Lukas Pravda committed
504
        this.fireExternalNodeEvent(x, Config.interactionMouseoverEvent);
Lukas Pravda's avatar
Lukas Pravda committed
505 506
    }

507
    private fireExternalNodeMouseLeaveEvent(x: Model.InteractionNode, i: number, g: any) {
Lukas Pravda's avatar
Lukas Pravda committed
508
        this.nodeDim(x, i, g);
Lukas Pravda's avatar
Lukas Pravda committed
509

Lukas Pravda's avatar
Lukas Pravda committed
510
        const e = new CustomEvent(Config.interactionMouseoutEvent, {
Lukas Pravda's avatar
Lukas Pravda committed
511 512 513 514
            bubbles: true,
            detail: {}
        });
        this.parent.dispatchEvent(e);
Lukas Pravda's avatar
Lukas Pravda committed
515
    }
Lukas Pravda's avatar
sync  
Lukas Pravda committed
516

517
    private fireExternalLinkEvent(link: Model.Link, eventName: string) {
Lukas Pravda's avatar
Lukas Pravda committed
518 519
        let atomsSource = [];
        let atomsTarget = [];
Lukas Pravda's avatar
Lukas Pravda committed
520 521

        if (link instanceof Model.LigandResidueLink) {
Lukas Pravda's avatar
Lukas Pravda committed
522
            let tmpSrc = [].concat.apply([], link.interaction.map(x => x.sourceAtoms));
Lukas Pravda's avatar
Lukas Pravda committed
523
            atomsSource = [].concat.apply([], tmpSrc).filter((v, i, a) => a.indexOf(v) === i);
Lukas Pravda's avatar
Lukas Pravda committed
524

Lukas Pravda's avatar
Lukas Pravda committed
525
            let tmpTar = [].concat.apply([], link.interaction.map(x => x.targetAtoms));
Lukas Pravda's avatar
Lukas Pravda committed
526
            atomsTarget = [].concat.apply([], tmpTar).filter((v, i, a) => a.indexOf(v) === i);
Lukas Pravda's avatar
Lukas Pravda committed
527
        }
Lukas Pravda's avatar
Lukas Pravda committed
528

Lukas Pravda's avatar
Lukas Pravda committed
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
        const e = new CustomEvent(eventName, {
            bubbles: true,
            detail: {
                interacting_nodes: [
                    {
                        pdb_res_id: this.pdbId,
                        auth_asym_id: link.source.residue.chainId,
                        auth_seq_id: link.source.residue.authorResidueNumber,
                        auth_ins_code_id: link.source.residue.authorInsertionCode,
                        atoms: atomsSource
                    },
                    {
                        pdb_res_id: this.pdbId,
                        auth_asym_id: link.target.residue.chainId,
                        auth_seq_id: link.target.residue.authorResidueNumber,
                        auth_ins_code_id: link.target.residue.authorInsertionCode,
                        atoms: atomsTarget
                    }
547 548
                ],
                tooltip: link.toTooltip()
Lukas Pravda's avatar
Lukas Pravda committed
549 550 551 552
            }
        });
        this.parent.dispatchEvent(e);
    }
Lukas Pravda's avatar
Lukas Pravda committed
553

554
    private fireExternalNodeEvent(node: Model.InteractionNode, eventName: string) {
Lukas Pravda's avatar
Lukas Pravda committed
555
        const e = new CustomEvent(eventName, {
Lukas Pravda's avatar
Lukas Pravda committed
556 557
            bubbles: true,
            detail: {
Lukas Pravda's avatar
Lukas Pravda committed
558 559 560 561 562
                selected_node: {
                    pdb_res_id: this.pdbId,
                    auth_asym_id: node.residue.chainId,
                    auth_seq_id: node.residue.authorResidueNumber,
                    auth_ins_code_id: node.residue.authorInsertionCode
563 564
                },
                tooltip: node.toTooltip()
Lukas Pravda's avatar
Lukas Pravda committed
565 566
            }
        });
Lukas Pravda's avatar
Lukas Pravda committed
567

Lukas Pravda's avatar
Lukas Pravda committed
568
        this.parent.dispatchEvent(e);
Lukas Pravda's avatar
Lukas Pravda committed
569 570
    }

571
    private fireExternalLinkLeaveEvent() {
Lukas Pravda's avatar
Lukas Pravda committed
572
        const e = new CustomEvent(Config.interactionMouseoutEvent, {
Lukas Pravda's avatar
Lukas Pravda committed
573 574 575
            bubbles: true,
            detail: {}
        });
Lukas Pravda's avatar
Lukas Pravda committed
576

Lukas Pravda's avatar
Lukas Pravda committed
577
        this.parent.dispatchEvent(e);
Lukas Pravda's avatar
Lukas Pravda committed
578
    }
Lukas Pravda's avatar
Lukas Pravda committed
579

Lukas Pravda's avatar
Lukas Pravda committed
580
    // #endregion fire events
Lukas Pravda's avatar
Lukas Pravda committed
581 582


Lukas Pravda's avatar
Lukas Pravda committed
583 584 585 586 587 588 589 590 591
    //#region setup scene micromethods
    private wipeOutVisuals() {
        this.nodesRoot.selectAll('*').remove();
        this.linksRoot.selectAll('*').remove();
    }

    private setupLinks() {
        this.links = this.linksRoot
            .selectAll()
592
            .data(this.presentBindingSite.links)
Lukas Pravda's avatar
Lukas Pravda committed
593 594 595 596
            .enter().append('g');

        this.links
            .append('line')
597
            .classed('pdb-lig-env-svg-shadow-bond', (x: Model.Link) => x.getLinkClass() !== 'hydrophobic')
Lukas Pravda's avatar
Lukas Pravda committed
598
            .on('click', (x: Model.Link) => this.linkMouseClickEventHandler(x))
Lukas Pravda's avatar
Lukas Pravda committed
599 600
            .on('mouseenter', (x: Model.Link, index: number, group: any) => this.linkMouseOverEventHandler(x, index, group))
            .on('mouseleave', (_, index: number, group: any) => this.linkMouseOutEventHandler(index, group));
Lukas Pravda's avatar
Lukas Pravda committed
601 602 603

        this.links
            .append('line')
604
            .attr('class', (e: Model.Link) => `pdb-lig-env-svg-bond pdb-lig-env-svg-bond-${e.getLinkClass()}`)
605
            .attr('marker-mid', (e: Model.Link) => e.hasClash() ? 'url(#clash)' : '')
Lukas Pravda's avatar
Lukas Pravda committed
606 607
            .on('mouseenter', (x: Model.Link, y: any, z: any) => this.linkMouseOverEventHandler(x, y, z))
            .on('mouseleave', (_, index: number, group: any) => this.linkMouseOutEventHandler(index, group));
Lukas Pravda's avatar
Lukas Pravda committed
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
    }



    private addNodeLabels(selection: any) {
        selection
            .append('text')
            .style('text-anchor', 'middle')
            .style('dominant-baseline', 'central')
            .each(function (e: Model.InteractionNode) {
                let labels = [e.residue.chemCompId, `${e.residue.chainId} ${e.residue.authorResidueNumber}`];
                for (var i = 0; i < labels.length; i++) {
                    d3.select(this)
                        .append('tspan')
                        .attr('dy', (i * 20) - 4)
                        .attr('x', 0)
                        .text(labels[i]);
                }
            });
    }
    //#endregion

630 631 632 633 634 635 636 637 638 639
    /**
     * Initialize scene after user selected a part of bound molecule.
     *
     * @private
     * @param {Model.InteractionNode} n Interaction node user clicked to
     * @param {number} i index o the interaction node
     * @param {*} g group of interaction nodes
     * @returns
     * @memberof Visualization
     */
Lukas Pravda's avatar
Lukas Pravda committed
640
    private selectLigand(n: Model.InteractionNode, i: number, g: any) {
Lukas Pravda's avatar
Lukas Pravda committed
641
        this.fireExternalNodeEvent(n, Config.interactionClickEvent);
Lukas Pravda's avatar
Lukas Pravda committed
642

Lukas Pravda's avatar
Lukas Pravda committed
643
        if (!n.residue.isLigand) return;
Lukas Pravda's avatar
Lukas Pravda committed
644

645
        this.nodeDim(n, i, g);
646
        this.fireExternalNodeMouseLeaveEvent(n, i, g);
Lukas Pravda's avatar
Lukas Pravda committed
647
        this.showLigandLabel(n);
Lukas Pravda's avatar
sync  
Lukas Pravda committed
648

Lukas Pravda's avatar
Lukas Pravda committed
649
        this.initLigandInteractions(this.pdbId, n.residue.authorResidueNumber, n.residue.chainId);
Lukas Pravda's avatar
Lukas Pravda committed
650
    }
Lukas Pravda's avatar
Lukas Pravda committed
651

652 653 654 655 656 657 658 659 660 661 662
    /**
     * Display error message on the SVG canvas if any of the resources
     * are not available.
     *
     * @private
     * @param {*} e error object
     * @param {string} msg Error message to display
     * @memberof Visualization
     */
    private processError(e: any, msg: string) {
        this.canvas.append('text')
663
            .classed('pdb-lig-env-svg-node', true)
Lukas Pravda's avatar
Lukas Pravda committed
664 665 666
            .attr('dominant-baseline', 'center')
            .attr('text-anchor', 'middle')
            .attr('x', this.parent.clientWidth / 2)
667 668
            .attr('y', this.parent.clientHeight / 2)
            .text(msg)
Lukas Pravda's avatar
Lukas Pravda committed
669

670 671
        throw e;

Lukas Pravda's avatar
Lukas Pravda committed
672
    }
673

Lukas Pravda's avatar
Lukas Pravda committed
674

675 676 677 678 679 680 681 682 683
    /**
     * Setup ligand scene for display of ligand and interactions.
     * This includes: setup of links, nodes, simulation and subscribing to relevant events.
     *
     * Depiction is expected to be downloaded already.
     *
     * @private
     * @memberof Visualization
     */
Lukas Pravda's avatar
Lukas Pravda committed
684
    private async setupLigandScene() {
Lukas Pravda's avatar
Lukas Pravda committed
685 686
        this.wipeOutVisuals();
        this.setupLinks();
Lukas Pravda's avatar
Lukas Pravda committed
687

688
        this.presentBindingSite.interactionNodes
Lukas Pravda's avatar
Lukas Pravda committed
689 690
            .filter((x: Model.InteractionNode) => !x.residue.isLigand)
            .forEach((x: Model.InteractionNode) => {
Lukas Pravda's avatar
Lukas Pravda committed
691 692 693 694
                let links = this.presentBindingSite.links.filter((y: Model.LigandResidueLink) => y.containsNode(x) && y.getLinkClass() !== 'hydrophobic');
                
                links = links.length == 0 ? this.presentBindingSite.links.filter((y: Model.LigandResidueLink) => y.containsNode(x)) : links;
                let atom_names = links
695
                    .map((y: Model.LigandResidueLink) => [].concat.apply([], y.interaction.map(z => z.sourceAtoms)));
Lukas Pravda's avatar
Lukas Pravda committed
696 697
                
                let concated = [].concat.apply([], atom_names);
Lukas Pravda's avatar
Lukas Pravda committed
698
                let position: Vector2D = this.depiction.getInitalNodePosition(concated);
699

Lukas Pravda's avatar
Lukas Pravda committed
700 701
                x.x = position.x + Math.random() * 55;
                x.y = position.y + Math.random() * 55;
Lukas Pravda's avatar
Lukas Pravda committed
702 703
            });

Lukas Pravda's avatar
Lukas Pravda committed
704

Lukas Pravda's avatar
Lukas Pravda committed
705
        // setup nodes; wait for resources to be ready
706
        this.presentBindingSite.interactionNodes.forEach(x => this.rProvider.downloadAnnotation(x.residue));
Lukas Pravda's avatar
Lukas Pravda committed
707 708
        await Promise.all(this.rProvider.downloadPromises);
        await Promise.all([this.visualsMapper.graphicsPromise, this.visualsMapper.mappingPromise]);
709

Lukas Pravda's avatar
Lukas Pravda committed
710
        this.nodes = this.nodesRoot.append('g')
Lukas Pravda's avatar
Lukas Pravda committed
711
            .selectAll()
712
            .data(this.presentBindingSite.interactionNodes)
Lukas Pravda's avatar
Lukas Pravda committed
713 714
            .enter().append('g');

715

Lukas Pravda's avatar
Lukas Pravda committed
716
        this.nodes.filter((x: Model.InteractionNode) => !x.residue.isLigand)
Lukas Pravda's avatar
Lukas Pravda committed
717
            .on('click', (x: Model.InteractionNode) => this.fireExternalNodeEvent(x, Config.interactionClickEvent))
718
            .attr('class', (x: Model.InteractionNode) => `pdb-lig-env-svg-node pdb-lig-env-svg-${x.residue.getResidueType()}-res`)
719 720
            .on('mouseenter', (x: Model.InteractionNode, i: number, g: any) => this.fireExternalNodeMouseEnterEvent(x, i, g))
            .on('mouseleave', (x: Model.InteractionNode, i: number, g: any) => this.fireExternalNodeMouseLeaveEvent(x, i, g));
Lukas Pravda's avatar
Lukas Pravda committed
721 722 723 724 725

        this.nodes.filter((x: Model.InteractionNode) => !x.residue.isLigand && this.visualsMapper.glycanMapping.has(x.residue.chemCompId))
            .html((e: Model.InteractionNode) => this.visualsMapper.getGlycanImage(e.residue.chemCompId));

        // draw rest
Lukas Pravda's avatar
Lukas Pravda committed
726
        this.nodes.filter((x: Model.InteractionNode) => !this.visualsMapper.glycanMapping.has(x.residue.chemCompId))
Lukas Pravda's avatar
Lukas Pravda committed
727
            .append('circle')
Lukas Pravda's avatar
Lukas Pravda committed
728
            .attr('r', (x: Model.InteractionNode) => x.scale * Config.nodeSize);
Lukas Pravda's avatar
Lukas Pravda committed
729

Lukas Pravda's avatar
Lukas Pravda committed
730 731
        let nodesWithText = this.nodes.filter((x: Model.InteractionNode) => !x.residue.isLigand);
        this.addNodeLabels(nodesWithText);
Lukas Pravda's avatar
Lukas Pravda committed
732

733 734
        let forceLink = d3.forceLink()
            .links(this.links.filter((x: Model.LigandResidueLink) => x.getLinkClass() !== 'hydrophobic'))
Lukas Pravda's avatar
Lukas Pravda committed
735
            .distance(5);
Lukas Pravda's avatar
Lukas Pravda committed
736

Lukas Pravda's avatar
Lukas Pravda committed
737 738
        let charge = d3.forceManyBody().strength(-80).distanceMin(10).distanceMax(20);
        let collision = d3.forceCollide(50).iterations(10).strength(0.5);
Lukas Pravda's avatar
Lukas Pravda committed
739

740
        this.simulation = d3.forceSimulation(this.presentBindingSite.interactionNodes)
741 742
            .force('link', forceLink)
            .force('charge', charge) //strength 
Lukas Pravda's avatar
Lukas Pravda committed
743
            .force('collision', collision)
744
            .on('tick', () => this.simulationStep());
Lukas Pravda's avatar
Lukas Pravda committed
745

Lukas Pravda's avatar
Lukas Pravda committed
746 747
        this.dragHandler(this.nodes);
        if (this.zoomHandler !== undefined) this.zoomHandler(this.svg, d3.zoomIdentity);
Lukas Pravda's avatar
Lukas Pravda committed
748 749
    }

Lukas Pravda's avatar
Lukas Pravda committed
750

751 752 753 754 755 756 757 758
    /**
     * Setup display of interactions for bound molecule. 
     * * This includes: setup of links, nodes, simulation and subscribing to relevant events.
     * No depiction is required for this step.
     *
     * @private
     * @memberof Visualization
     */
Lukas Pravda's avatar
Lukas Pravda committed
759
    private async setupScene() {
Lukas Pravda's avatar
Lukas Pravda committed
760 761
        this.wipeOutVisuals();
        this.setupLinks();
762

Lukas Pravda's avatar
Lukas Pravda committed
763
        // setup nodes; wait for resources to be ready
764
        this.presentBindingSite.interactionNodes.forEach(x => ResidueProvider.getInstance(this.environment).downloadAnnotation(x.residue));
Lukas Pravda's avatar
Lukas Pravda committed
765 766
        await Promise.all(this.rProvider.downloadPromises);
        await Promise.all([this.visualsMapper.graphicsPromise, this.visualsMapper.mappingPromise]);
767

Lukas Pravda's avatar
Lukas Pravda committed
768
        this.nodes = this.nodesRoot
Lukas Pravda's avatar
Lukas Pravda committed
769
            .selectAll()
770
            .data(this.presentBindingSite.interactionNodes)
Lukas Pravda's avatar
Lukas Pravda committed
771
            .enter().append('g')
772
            .attr('class', (e: Model.InteractionNode) => `pdb-lig-env-svg-node pdb-lig-env-svg-${e.residue.getResidueType()}-res`)
Lukas Pravda's avatar
Lukas Pravda committed
773
            .on('click', (x: Model.InteractionNode, i: number, g: any) => this.selectLigand(x, i, g))
774 775
            .on('mouseover', (x: Model.InteractionNode, i: number, g: any) => this.fireExternalNodeMouseEnterEvent(x, i, g))
            .on('mouseout', (x: Model.InteractionNode, i: number, g: any) => this.fireExternalNodeMouseLeaveEvent(x, i, g));
Lukas Pravda's avatar
Lukas Pravda committed
776

Lukas Pravda's avatar
Lukas Pravda committed
777

Lukas Pravda's avatar
Lukas Pravda committed
778
        this.nodes.filter((n: Model.InteractionNode) =>
Lukas Pravda's avatar
Lukas Pravda committed
779
            this.visualsMapper.glycanMapping.has(n.residue.chemCompId))
Lukas Pravda's avatar
Lukas Pravda committed
780
            .html((e: Model.InteractionNode) => this.visualsMapper.getGlycanImage(e.residue.chemCompId));
Lukas Pravda's avatar
Lukas Pravda committed
781

Lukas Pravda's avatar
Lukas Pravda committed
782
        this.nodes.filter((e: Model.InteractionNode) => !this.visualsMapper.glycanMapping.has(e.residue.chemCompId))
Lukas Pravda's avatar
Lukas Pravda committed
783
            .append('circle')
Lukas Pravda's avatar
Lukas Pravda committed
784
            .attr('r', Config.nodeSize);
Lukas Pravda's avatar
Lukas Pravda committed
785

Lukas Pravda's avatar
Lukas Pravda committed
786
        this.addNodeLabels(this.nodes);
Lukas Pravda's avatar
Lukas Pravda committed
787 788

        let forceLink = d3.forceLink()
789
            .links(this.presentBindingSite.links)
790
            .distance((x: Model.Link) => (<Model.InteractionNode>x.source).residue.isLigand && (<Model.InteractionNode>x.target).residue.isLigand ? 55 : 150)
Lukas Pravda's avatar
Lukas Pravda committed
791 792 793 794
            .strength(0.5);

        let charge = d3.forceManyBody().strength(-1000).distanceMin(55).distanceMax(250);
        let collision = d3.forceCollide(45);
Lukas Pravda's avatar
Lukas Pravda committed
795
        let center = d3.forceCenter(this.parent.offsetWidth / 2, this.parent.offsetHeight / 2);
Lukas Pravda's avatar
Lukas Pravda committed
796

797
        this.simulation = d3.forceSimulation(this.presentBindingSite.interactionNodes)
Lukas Pravda's avatar
Lukas Pravda committed
798 799 800 801
            .force('link', forceLink)
            .force('charge', charge) //strength 
            .force('collision', collision)
            .force('center', center)
802
            .on('tick', () => this.simulationStep());
Lukas Pravda's avatar
Lukas Pravda committed
803

Lukas Pravda's avatar
Lukas Pravda committed
804 805 806
        this.dragHandler(this.nodes);

        if (this.zoomHandler) this.zoomHandler(this.svg);
Lukas Pravda's avatar
Lukas Pravda committed
807
    }
Lukas Pravda's avatar
Lukas Pravda committed
808

Lukas Pravda's avatar
Lukas Pravda committed
809

810 811 812 813 814 815 816
    /**
     * This is a tick in a simulation that updates position of nodes and links
     * Depiction does not change its conformation.
     *
     * @private
     * @memberof Visualization
     */
Lukas Pravda's avatar
Lukas Pravda committed
817
    private simulationStep() {
Lukas Pravda's avatar
Lukas Pravda committed
818
        this.nodes.attr('transform', (n: Model.InteractionNode) => `translate(${n.x},${n.y}) scale(${n.scale})`);
Lukas Pravda's avatar