Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@cosmograph/cosmos

Package Overview
Dependencies
Maintainers
1
Versions
74
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cosmograph/cosmos

GPU-based force graph layout and rendering

  • 1.1.4-beta.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
742
increased by35.9%
Maintainers
1
Weekly downloads
 
Created
Source

🌌 Cosmos

GPU-accelerated Force Graph

Cosmos is a WebGL Force Graph layout algorithm and rendering engine. All the computations and drawing are happening on the GPU in fragment and vertex shaders avoiding expensive memory operations.

It enables real-time simulation of network graphs consisting of hundreds of thousands of nodes and edges on modern hardware.

https://user-images.githubusercontent.com/755708/173392407-9b05cbb6-d39e-4c2c-ab41-50900cfda823.mp4

📺 Comparison with other libraries

🎮 Try Cosmos on CodeSandbox

Quick Start

Install the package:

npm install @cosmograph/cosmos

Get the data, configure the graph and run the simulation:

import { Graph } from '@cosmograph/cosmos'
import { nodes, links } from './data'

const canvas = document.querySelector('canvas')
const config = {
  simulation: {
    repulsion: 0.5,
  },
  renderLinks: true,
  linkColor: link => link.color,
  nodeColor: node => node.color,
  events: {
    onClick: node => { console.log('Clicked node: ', node) },
  },
  /* ... */
}

const graph = new Graph(canvas, config)

graph.setData(nodes, links)

Note If your canvas element has no width and height styles (either CSS or inline) Cosmos will automatically set them to 100%.

Examples

# Cosmos configuration

PropertyDescriptionDefault
backgroundColorCanvas background color#222222
spaceSizeSimulation space size (max 8192)4096
nodeColorNode color accessor function or hex value#b3b3b3
nodeGreyoutOpacityGreyed out node opacity value when the selection is active0.1
nodeSizeNode size accessor function or value in pixels4
nodeSizeScaleScale factor for the node size1
renderLinksTurns link rendering on / offtrue
linkColorLink color accessor function or hex value#666666
linkGreyoutOpacityGreyed out link opacity value when the selection is active0.1
linkWidthLink width accessor function or value in pixels1
linkWidthScaleScale factor for the link width1
linkArrowsTurns link arrow rendering on / offtrue
linkArrowsSizeScaleScale factor for the link arrows size1
linkVisibilityDistanceRangeThe range defines the minimum and maximum link visibility distance in pixels.

The link will be fully opaque when its length is less than the first number in the array, and will have linkVisibilityMinTransparency transparency when its length is greater than the second number in the array.

This distance is defined in screen space coordinates and will change as you zoom in and out (e.g. links become longer when you zoom in, and shorter when you zoom out).
[50, 150]
linkVisibilityMinTransparencyThe transparency value that the link will have when its length reaches the maximum link distance value from linkVisibilityDistanceRange.0.25
useQuadtreeUse the classic quadtree algorithm for the Many-Body force. This property will be applied only on component initialization and it can't be changed using the setConfig method.

⚠ The algorithm might not work on some GPUs (e.g. Nvidia) and on Windows (unless you disable ANGLE in the browser settings).
false
simulationSimulation parameters and event listenersSee Simulation configuration table for more details
events.onClickCallback function that will be called on every canvas click. If clicked on a node, its data will be passed as a first argument, index as a second argument, position as a third argument and the corresponding mouse event as a forth argument: (node: Node | undefined, index: number | undefined, nodePosition: [number, number] | undefined, event: MouseEvent) => voidundefined
events.onZoomStartCallback function that will be called when zooming or panning starts. First argument is a D3 Zoom Event and second indicates whether the event has been initiated by a user interaction (e.g. a mouse event): (event: D3ZoomEvent, userDriven: boolean) => voidundefined
events.onZoomCallback function that will be called continuously during zooming or panning. First argument is a D3 Zoom Event and second indicates whether the event has been initiated by a user interaction (e.g. a mouse event): (event: D3ZoomEvent, userDriven: boolean) => voidundefined
events.onZoomEndCallback function that will be called when zooming or panning ends. First argument is a D3 Zoom Event and second indicates whether the event has been initiated by a user interaction (e.g. a mouse event): (event: D3ZoomEvent, userDriven: boolean) => voidundefined
showFPSMonitorShow WebGL performance monitorfalse
pixelRatioCanvas pixel ratio2
scaleNodesOnZoomScale the nodes when zooming in or outtrue

# Simulation configuration

Cosmos layout algorithm was inspired by the d3-force simulation forces: Link, Many-Body, Gravitation, and Centering. It provides several simulation settings to adjust the layout. Each of them can be changed in real time, while the simulation is in progress.

PropertyDescriptionRecommended rangeDefault
repulsionRepulsion force coefficient0.0 – 2.00.1
repulsionThetaDecreases / increases the detalization of the Many-Body force calculations.

When useQuadtree is set to true, this property corresponds to the Barnes–Hut approximation criterion.
0.3 – 2.01.7
repulsionQuadtreeLevelsBarnes–Hut approximation depth.

Can only be used when useQuadtree is set true.
5 – 1212
linkSpringLink spring force coefficient0.0 – 2.01.0
linkDistanceMinimum link distance1 – 202
linkDistRandomVariationRangeLink distance randomness multiplier range[0.8 – 1.2,
1.2 – 2.0]
[1.0, 1.2]
gravityGravity force coefficient0.0 – 1.00.0
centerCentering force coefficient0.0 – 1.00.0
frictionFriction coefficient0.8 – 1.00.85
decayForce simulation decay coefficient.

Use smaller values if you want the simulation to "cool down" slower.
100 – 10 0001000
repulsionFromMouseRepulsion from the mouse pointer force coefficient0.0 – 5.02.0
simulation.onStartCallback function that will be called when the simulation startsundefined
simulation.onTickCallback function that will be called on every simulation tick.

The value of the argument alpha will decrease over time as the simulation "cools down": (alpha: number) => void
undefined
simulation.onEndCallback function that will be called when the simulation stopsundefined
simulation.onPauseCallback function that will be called when the simulation gets pausedundefined
simulation.onRestartCallback function that will be called when the simulation is restartedundefined

# API Reference

# graph.setConfig(config)

Set Cosmos configuration. The changes will be applied in real time.

# graph.setData(nodes, links, [runSimulation])

Pass data to Cosmos: an array of nodes and an array of links. When runSimulation is set to false, the simulation won't be started automatically (true by default).

# graph.zoomToNodeById(id, [duration])

Center the view on a node and zoom in; by node id with given animation duration. The default duration is 700.

# graph.zoomToNodeByIndex(index, [duration])

Center the view on a node and zoom in; by node index with given animation duration. The default duration is 700.

# graph.setZoomLevel(value, [duration])

Zoom the view in or out to the specified zoom level value with given animation duration. The default duration is 0.

# graph.fitView(duration)

Center and zoom in/out the view to fit all nodes in the scene with given animation duration. The default duration is 500 ms.

# graph.selectNodesInRange(selection)

Select nodes inside a rectangular area defined by two corner points [[left, top], [right, bottom]]. The left and right values should be from 0 to the width of the canvas in pixels.

The top and bottom values should be from 0 to the height of the canvas in pixels.

# graph.selectNodeById(id, [selectAdjacentNodes])

Select a node by id. If you want the adjacent nodes to get selected too, provide true as the second argument.

# graph.selectNodeByIndex(index, [selectAdjacentNodes])

Select a node by index. If you want the adjacent nodes to get selected too, provide true as the second argument.

# graph.selectNodesByIds(ids)

Select multiple nodes by an array of their ids.

# graph.selectNodesByIndices(indices)

Select multiple nodes by an array of their indices.

# graph.unselectNodes()

Unselect all nodes.

# graph.getSelectedNodes()

Get an array of currently selected nodes.

# graph.getAdjacentNodes(id)

Get nodes that are adjacent to a specific node by its id.

# graph.start([alpha])

Start the simulation. The alpha value can be from 0 to 1 (1 by default). The higher the value, the more initial energy the simulation will get.

# graph.pause()

Pause the simulation.

# graph.restart()

Restart the simulation.

# graph.step()

Render only one frame of the simulation. The simulation will be paused if it was active.

# graph.destroy()

Destroy this Cosmos instance.

# graph.getZoomLevel()

Get current zoom level of the view.

# graph.getNodePositions()

Get an object with node coordinates, where keys are the ids of the nodes and values are their X and Y coordinates in the { x: number; y: number } format.

# graph.getNodePositionsMap()

Get a Map object with node coordinates, where keys are the ids of the nodes and the values are their X and Y coordinates in the [number, number] format.

# graph.getNodePositionsArray()

Get an array of [number, number] arrays corresponding to the X and Y coordinates of the nodes.

# graph.isSimulationRunning

A boolean value showing whether the simulation is active or not.

# graph.maxPointSize

The maximum point size the user's hardware can render. This value is a limitation of the gl.POINTS primitive of WebGL and differs from GPU to GPU.

Known Issues

Starting from version 15.4, iOS has stopped supporting the key WebGL extension powering our Many-Body force implementation (EXT_float_blend). We're trying to figure out why that happened and hope to find a way to solve the problem in the future.

License

CC-BY-NC-4.0

Cosmos is free non-commercial usage. If you're a scientist, artist, educator, journalist, student, ..., we would love to hear about your project and how you use Cosmos! If you want to use it in a commercial project, please reach out to us.

Contact

Write us!

📩 hi@cosmograph.app

Keywords

FAQs

Package last updated on 12 Nov 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc