Giter Site home page Giter Site logo

cytoscape.js-elk's Introduction

cytoscape-elk

Description

The elk layout algorithm adapter for Cytoscape.js

ELK is a set of layout algorithms implemented by the Eclipse Foundation in Java. The source code is compiled to JS by the ELK.js project using GWT. This Cytoscape extension adds support for the ELK layout aglorithms in Cytoscape.

Dependencies

  • Cytoscape.js >= 3.2.0
  • elkjs >= 0.8.1

Usage instructions

Download the library:

  • via npm or yarn: npm install cytoscape-elk or yarn add cytoscape-elk,
  • via direct download in the repository (probably from a tag).

Import the library as appropriate for your project:

ES import:

import cytoscape from 'cytoscape';
import elk from 'cytoscape-elk';

cytoscape.use( elk );

CommonJS require:

let cytoscape = require('cytoscape');
let elk = require('cytoscape-elk');

cytoscape.use( elk ); // register extension

AMD:

require(['cytoscape', 'cytoscape-elk'], function( cytoscape, elk ){
  elk( cytoscape ); // register extension
});

Plain HTML/JS has the extension registered for you automatically, because no require() is needed.

API

var options = {
  nodeDimensionsIncludeLabels: false, // Boolean which changes whether label dimensions are included when calculating node dimensions
  fit: true, // Whether to fit
  padding: 20, // Padding on fit
  animate: false, // Whether to transition the node positions
  animateFilter: function( node, i ){ return true; }, // Whether to animate specific nodes when animation is on; non-animated nodes immediately go to their final positions
  animationDuration: 500, // Duration of animation in ms if enabled
  animationEasing: undefined, // Easing of animation if enabled
  transform: function( node, pos ){ return pos; }, // A function that applies a transform to the final node position
  ready: undefined, // Callback on layoutready
  stop: undefined, // Callback on layoutstop
  nodeLayoutOptions: undefined, // Per-node options function
  elk: {
    // All options are available at http://www.eclipse.org/elk/reference.html
    //
    // 'org.eclipse.' can be dropped from the identifier. The subsequent identifier has to be used as property key in quotes.
    // E.g. for 'org.eclipse.elk.direction' use:
    // 'elk.direction'
    //
    // Enums use the name of the enum as string e.g. instead of Direction.DOWN use:
    // 'elk.direction': 'DOWN'
    //
    // The main field to set is `algorithm`, which controls which particular layout algorithm is used.
    // Example (downwards layered layout):
    'algorithm': 'layered',
    'elk.direction': 'DOWN',
  },
  priority: function( edge ){ return null; }, // Edges with a non-nil value are skipped when geedy edge cycle breaking is enabled
};

cy.layout( options ).run();

You can set layout options per node by defining a nodeLayoutOptions function which is called on a per-node basis. This is useful for tweaking the layout of a particular node, like for setting its partition for the layered layout. For instance, if you want to store these options within the node's scratch object, you can do something like this:

nodeLayoutOptions: node => n.scratch('layoutOptions')

The set of options.elk.algorithm values that are supported by ELK.js follows:

  • box : (Demo) (Docs) Pack the nodes like boxes.
  • disco : (Demo) (Docs) Pack the (disconnected) components. A secondary layout may be applied to each component via options.elk.componentLayoutAlgorithm.
  • force : (Demo) (Docs) Apply a basic force-directed layout.
  • layered : (Demo) (Docs) Apply a hierarchical layout, appropriate for DAGs and trees.
  • mrtree : (Demo (Docs) Apply a traditional, hierarchical tree layout.
  • random : (Demo) (Docs) Apply random positions to the nodes.
  • stress : (Demo) (Docs) Apply a force-directed layout.

See the ELK.js documentation and the ELK algorithm options documentation for more information.

Build targets

  • npm run test : Run Mocha tests in ./test
  • npm run build : Build ./src/** into cytoscape.js-elk
  • npm run watch : Automatically build on changes with live reloading (N.b. you must already have an HTTP server running)
  • npm run dev : Automatically build on changes with live reloading with webpack dev server
  • npm run lint : Run eslint on the source

N.b. all builds use babel, so modern ES features can be used in the src.

Publishing instructions

This project is set up to automatically be published to npm. To publish:

  1. Build the extension : npm run build
  2. Commit the build : git commit -am "Build for release"
  3. Bump the version number and tag: npm version major|minor|patch
  4. Push to origin: git push && git push --tags
  5. Publish to npm: npm publish .

cytoscape.js-elk's People

Contributors

akx avatar alexcli avatar d2fong avatar itf avatar jfstephe avatar lorenz-n avatar marshallchen avatar maxkfranz avatar petertsmith avatar saulshanabrook avatar simonwarchol avatar yuan0728a avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cytoscape.js-elk's Issues

Module not found: Error: Can't resolve 'fs'

After running npm install cytoscape-elk, importing it with import elk from 'cytoscape-elk' and using it with cytoscape.use(elk); I get the following error within node:

ERROR in ./node_modules/bindings/bindings.js
Module not found: Error: Can't resolve 'fs' in './node_modules/bindings'

Installing 'fs' (npm install --save fs) does not solve the issue.

Any ideas?

node: v10.16.0
npm: 6.9.0

Cannot resolve `web-worker` issue in create-react-app

this is what I am doing:

import Cytoscape from 'react-cytoscapejs';
const Elk = require('cytoscape-elk');
Cytoscape.use(Elk);

this throws the error in compiling,

./node_modules/elkjs/lib/main.js
Module not found: Can't resolve 'web-worker' in '/node_modules/elkjs/lib'

Can anyone resolve this issue?

Options not mapped to props as expected

From the given samples, I would expect that options from http://www.eclipse.org/elk/reference.html get mapped to the elk props, e.g.:

layout: {
  elk: {
    direction: 'DOWN',
  },
},

instead, it seems that the props have to be named by the subsequent identifier as property key in quotes, after the org.eclipse. part (which was also misleading in the current sample - saying org.eclipse.elk. can be dropped from the Identifier). So currently it seems to be only working with:

layout: {
  elk: {
    'elk.direction': 'DOWN',
  },
},

algorithm and noLayout seems to be the only exceptions (not requiring the elk. prefix and property key in quotes) from what I've figured out so far.

elk mrtree hierarchical layout

The following does not give me mrtree layout shown here
https://cytoscape.org/cytoscape.js-elk/?demo=mrtree

import CytoscapeComponent from "react-cytoscapejs";
import Cytoscape from "cytoscape";
import elk from "cytoscape-elk";
Cytoscape.use(elk);

const layout = {
name: "elk",
fit: true,
// circle: true,
directed: true,
padding: 50,
// spacingFactor: 1.5,
//animate: false,
//animationDuration: 1000,
avoidOverlap: true,
nodeDimensionsIncludeLabels: true,
elk: {
// All options are available at http://www.eclipse.org/elk/reference.html
"elk.direction": "DOWN",
"algorithm": "mrtree",
},
};

Layered algorithm in cytoscape overlaps edges and nodes

Hi there!

Looking at the image for "Layered" in the ELK docs, it seems that edges should not overlap each other, and also avoid overlapping nodes:
image

However, it seems it is not possible to achieve the same behavior in cytoscape? There is a similar question in Stack Overflow here that seems to suggest it is not possible either?

Layouts do not ignore parent nodes from calculating nodes positions

Quote from cytoscape compound nodes documentation:

A compound parent node does not have independent dimensions (position and size), as those values are automatically inferred by the positions and dimensions of the descendant nodes.

When applying layered layout on a plain tree, everything goes perfectly, but when I add in the parent nodes the layout is all messed up. Any suggestions?

Uncaught TypeError: Cannot read properties of null (reading 'je')

I installed the latest version of this package with npm install, and then tried to use the node REPL to lay out a simple network.

However, this failed with the error Uncaught TypeError: Cannot read properties of null (reading 'je').

$ node
Welcome to Node.js v16.13.0.
Type ".help" for more information.
> const cytoscape = require('cytoscape')
undefined
> const elk = require('cytoscape-elk')
undefined
> 
> 
> const nodes = [
...       {"id": "Alice"},
...       {"id": "Bob"},
...       {"id": "Carol"}
...   ];
undefined
> 
> const links = [
...     {"source": "Alice", "target": "Bob"}, // Alice → Bob
...     {"source": "Bob", "target": "Carol"} // Bob → Carol
... ];
undefined
> 
> const elements = [
...     ...nodes.map(n => ({data: n})),
...     ...links.map(n => ({data: n}))
... ];
undefined
> 
> cytoscape.use(elk);
[Function: cytoscape] {
  use: [Function (anonymous)],
  warnings: [Function (anonymous)],
  version: '3.20.0',
  Stylesheet: [Function: Stylesheet],
  stylesheet: [Function: Stylesheet]
}
> 
> let cy = cytoscape({ elements });
undefined
> cy.layout({name: 'elk', animate: false}).run();
<ref *1> Layout {
  options: {
    nodeDimensionsIncludeLabels: false,
    fit: true,
    padding: 20,
    animate: false,
    animateFilter: [Function: animateFilter],
    animationDuration: 500,
    animationEasing: undefined,
    transform: [Function: transform],
    ready: undefined,
    stop: undefined,
    elk: { aspectRatio: 1, algorithm: undefined },
    priority: [Function: priority],
    name: 'elk',
    cy: Core { _private: [Object] },
    eles: Array {
      '0': [Array],
      '1': [Array],
      '2': [Array],
      '3': [Array],
      '4': [Array],
      length: 5,
      _private: [Object]
    }
  },
  _private: {
    cy: Core { _private: [Object] },
    listeners: [],
    emitter: Emitter {
      qualifierCompare: [Function: qualifierCompare],
      eventMatches: [Function: eventMatches],
      addEventFields: [Function: addEventFields],
      callbackContext: [Function: callbackContext],
      beforeEmit: [Function: beforeEmit],
      afterEmit: [Function: afterEmit],
      bubble: [Function: bubble],
      parent: [Function: parent],
      context: [Circular *1],
      listeners: [],
      emitting: 0
    }
  }
}
> Uncaught TypeError: Cannot read properties of null (reading 'je')
    at Jqd (/home/jsb/code/grammar-of-networks/node_modules/elkjs/lib/elk-worker.min.js:5706:225)
    at Iqd (/home/jsb/code/grammar-of-networks/node_modules/elkjs/lib/elk-worker.min.js:5685:188)
    at h.dispatch (/home/jsb/code/grammar-of-networks/node_modules/elkjs/lib/elk-worker.min.js:5984:473)
    at h.saveDispatch (/home/jsb/code/grammar-of-networks/node_modules/elkjs/lib/elk-worker.min.js:5984:603)
> 

Showing just the code:

const cytoscape = require('cytoscape')
const elk = require('cytoscape-elk')

const nodes = [
      {"id": "Alice"},
      {"id": "Bob"},
      {"id": "Carol"}
  ];

const links = [
    {"source": "Alice", "target": "Bob"}, // Alice → Bob
    {"source": "Bob", "target": "Carol"} // Bob → Carol
];

const elements = [
    ...nodes.map(n => ({data: n})),
    ...links.map(n => ({data: n}))
];

cytoscape.use(elk);

let cy = cytoscape({ elements });
cy.layout({name: 'elk', animate: false}).run();

I have also tried to use the library with import, but encountered the same error.

I think this is a duplicate of #3, which was marked as stale and closed without resolution.

using algorithms

Is it possible to use algorithms that have longer name spaces? for example for using : org.eclipse.elk.graphviz.circo , I tried "circo" and also full name as well as "graphviz.circo" but none worked. Would you please let me know if it's possible? Thanks

cytoscape.js-elk / web worker dependency

In the elkjs documentation it is said :

A warning is raised if one requests a web worker without having installed the package. elkjs falls back to the non-Web Worker version in that case.

But when I try to do so, using cytoscape.js-elk, I get an error :

Failed to compile. <path>/node_modules/elkjs/lib/main.js Module not found: Can't resolve 'webworker-threads' in '<path>\node_modules\elkjs\lib'

ReferenceError: g is not defined

Problem
When opening the page it throws the error:

ERROR Error: Uncaught (in promise): ReferenceError: g is not defined
ReferenceError: g is not defined
    at Emd (elk-worker.min.js:5037)
    at Iqd (elk-worker.min.js:5685)
    at h.dispatch (elk-worker.min.js:5984)
    at h.saveDispatch (elk-worker.min.js:5984)
    at elk-worker.min.js:5985

Steps to reproduce

import { Component, OnInit } from '@angular/core';
import cytoscape from 'cytoscape';
import elk from 'cytoscape-elk';

In the ngOnInit() function:

      cytoscape.use(elk);
        var cy = cytoscape({
            container: document.getElementById('cy')
         });

        var nodes = cy.add([
            { group: 'nodes', data: { id: 'n1', name: 'N1' } },
            { group: 'nodes', data: { id: 'n2', name: 'N2' } },
        ])

        var edges = cy.add([
            { group: 'edges', data: { id: 'e1', source: 'n1', target: 'n2' } },
        ]);

       var options = {
            name: "elk",
            nodeDimensionsIncludeLabels: false, // Boolean which changes whether label dimensions are included when calculating node dimensions
            fit: true, // Whether to fit
            padding: 20, // Padding on fit
            animate: false, // Whether to transition the node positions
            animateFilter: function (node, i) { return true; }, // Whether to animate specific nodes when animation is on; non-animated nodes immediately go to their final positions
            animationDuration: 500, // Duration of animation in ms if enabled
            animationEasing: undefined, // Easing of animation if enabled
            transform: function (node, pos) { return pos; }, // A function that applies a transform to the final node position
            ready: undefined, // Callback on layoutready
            stop: undefined, // Callback on layoutstop
            elk: {
                algorithm: 'layered',
                // All options are available at http://www.eclipse.org/elk/reference.html
                // 'org.eclipse.elk.' can be dropped from the Identifier
                // Or look at demo-demo.js for an example.
                // Enums use the name of the enum e.g.
                // 'searchOrder': 'DFS'
                //
                // The main field to set is `algorithm`, which controls which particular
                // layout algorithm is used.
            },
            priority: function (edge) { return null; }, // Edges with a non-nil value are skipped when geedy edge cycle breaking is enabled
        };

        cy.layout(options).run();

Reported on environment
Browser: Chrome and Safari
OS: Windows 10 Pro, macOS 11
Nodejs: 10.24 (LTS)

Missing port functionality

Is this functional with ports ? as I have tried setting the edges with a targets to a port and it returns an error

Priority example?

Hi, I'm having trouble having my layout recognize priority; some nodes are pointing left when I'd prefer them to point to the default direction (right).

I've tried this:

    priority: function( edge ) {
        let ed = edge.data();
        if (ed.target === "r113" || ed.target ==="r112" || ed.target === "r76" || ed.target === "r77") {
            console.log("attempting to set priority for edge...");
            return 100;
        }
        return null;
    }

And in the source data I've already tried this:

                data: {
                    source: ed.source,
                    target: ed.target,
                    label: ed.label,
                    layoutOptions: {
                        'elk.layered.priority.direction': ((ed.target === "r113" || ed.target === "r77") ? 10 : 0)
                    }
                }

But neither are having an effect. I'm using GREEDY, and NETWORK_SIMPLEX on the layered algorithm. Is there some other syntax I should be using?

getPos while loop uses incorrect scratch namespace

I have updated to version 1.2.2 but I'm finding that I'm encountering an error in the getPos function of layout.js.

I believe the issue stems from this PR: https://github.com/cytoscape/cytoscape.js-elk/pull/22/files which was changed to use a non-existent "klay" scratch namespace. Trying to get the scratch of "klay" returns undefined which causes getPos to error out.

It doesn't seem like the "klay" scratch is set anywhere either, so I believe this to be a defect.

I would fix it myself but I don't have write access to the repo.

Why depending on webworker-threads

In your package.json, you have the "webworker-threads": "^0.7.16" dependency, but I did not find any place where you used the provided features.
Is this just included because the elkjs package could use this.
If this is the case, would it not be more convenient to handle it as the elkjs package handles it:

The package is not installed automatically to avoid the unnecessary dependency for everyone who is not interested in using a web worker. A warning is raised if one requests a web worker without having installed the package. elkjs falls back to the non-Web Worker version in that case.
https://www.npmjs.com/package/elkjs

Thanks for the help.

"self is not defined" exception in nodejs

Affected versions: 2.0.0, 2.0.1, 1.2.2 is not affected

Problem
When executed by nodejs, it throws uncaught exception: self is not defined at cytoscape-elk/dist/cytoscape-elk.js:10:4 (as reported by the 2.0.1), but the same uncaught exception is raised also by the 2.0.0

Steps to reproduce

  1. create test.js file with the following content:
    const cytoscape = require('cytoscape');
    const elk = require('cytoscape-elk');
    cytoscape.use(elk);
  2. execute the file by nodejs: node ./test.js

Reported on environment
OS: Windows 10 Pro, Linux Debian 4.9
Nodejs: 12.18.1, 12.16.1, 14.15.5

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.