30 Commits

Autor SHA1 Mensagem Data
Alex Castillo c1ad1e0476 ng2-charts fixes
TODO: clean-up, test, optimize and submit as a PR
2016-09-09 15:32:52 +02:00
Alex Castillo 70332ca560 buffer size and scale update 2016-09-09 14:32:01 +02:00
Alex Castillo 12fbbdd06b clean-up 2016-09-09 14:31:29 +02:00
Alex Castillo 723eb8c533 chart scale adjustment 2016-06-13 21:14:54 -04:00
Alex Castillo aa7a5c78f2 time series improvements 2016-06-12 16:12:14 -04:00
Alex Castillo ff0b0192bb signals improvements 2016-06-12 16:09:13 -04:00
Alex Castillo 2803c3b829 upgrade to ng2-charts/chart.js v2
Closes #34
2016-06-05 20:13:39 -04:00
Alex Castillo 6e1fc861e7 Merge branch 'motion' 2016-06-03 12:46:52 -04:00
Alex Castillo d96fbabef8 motion progress 2016-06-03 12:46:07 -04:00
Alex Castillo ed260da6ee add motion component
Closes 31
2016-06-03 07:42:25 -04:00
Alex Castillo 4cd9a641ce dynamic global scale
Closes #27
2016-06-01 22:43:51 -04:00
Alex Castillo 9601ff89a1 add constants to back-end
Closes #24
2016-06-01 22:09:42 -04:00
Alex Castillo 2942d8a3d0 refactor time series server code for filters
Closes #14
2016-05-31 22:30:01 -04:00
Alex Castillo b3f41b00de create connector class
Closes #25
2016-05-31 21:59:54 -04:00
Alex Castillo 8b7e60ca35 upgrade to node.js v6
Closes #22
2016-05-31 21:59:54 -04:00
Alex Castillo 7661dad72e refactor back-end
Closes #23
2016-05-31 21:59:54 -04:00
Alex Castillo cc3eaf834b add too assets 2016-05-31 21:59:54 -04:00
Alex Castillo 8351474fbc update readme 2016-05-19 16:56:09 -04:00
Alex Castillo 005950b173 package.json add email 2016-05-18 22:08:36 -04:00
Alex Castillo 847c1ff511 update package.json 2016-05-18 22:07:18 -04:00
Alex Castillo 44ed5c8fa5 update readme 2016-05-18 22:04:06 -04:00
Alex Castillo 44f7a035c8 make time series default route 2016-05-18 21:59:59 -04:00
Alex Castillo ef761dd32b update readme 2016-05-17 19:56:44 -04:00
Alex Castillo c2bad61f92 mask topo plot
includes clean-up
2016-05-17 19:56:05 -04:00
Alex Castillo 74c8fb1a68 update contour plot 2016-05-17 18:44:46 -04:00
Alex Castillo 36986b66a6 style fixes 2016-05-15 19:56:39 -04:00
Alex Castillo 98ebbd83fd add filters component
includes notch filter
2016-05-15 18:52:09 -04:00
Alex Castillo 118b480690 topo experiment 2016-05-15 11:08:08 -04:00
Alex Castillo e3e9974888 topo via plotly 2016-05-14 19:21:25 -04:00
Alex Castillo 0c237e0116 add assets for readme 2016-05-14 19:01:54 -04:00
62 arquivos alterados com 247530 adições e 666 exclusões
+13 -1
Ver Arquivo
@@ -2,7 +2,7 @@
![alt text](/assets/preview3.gif "OpenBCI Dashboard Preview")
A fullstack javascript app for capturing and visualizing OpenBCI EEG data
A fullstack JavaScript app for reading and visualizing OpenBCI EEG data.
This project is under development, this is just a first draft.
@@ -12,6 +12,7 @@ This project is under development, this is just a first draft.
* Turn on OpenBCI board
```bash
npm install -g angular-cli concurrently
npm install
npm run visualize
```
@@ -24,6 +25,17 @@ npm run visualize
npm run simulate
```
## Technologies
* Node.js
* Angular 2
* Socket.io
* Data Visualization
- Plotly.js
- Chart.js
- Smoothie
## Support
Pull requests are welcomed!
+3 -1
Ver Arquivo
@@ -7,9 +7,11 @@ module.exports = function(defaults) {
vendorNpmFiles: [
'socket.io-client/socket.io.js',
'smoothie/smoothie.js',
'chart.js/Chart.js',
'chart.js/dist/Chart.bundle.js',
'ng2-charts/bundles/ng2-charts.js',
'chroma-js/chroma.js',
'plotly.js/dist/plotly.js',
'brainbrowser/build/brainbrowser-2.3.0/**/*.js',
'systemjs/dist/system-polyfills.js',
'systemjs/dist/system.src.js',
'zone.js/dist/*.js',
Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 356 KiB

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 3.6 MiB

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 1.9 MiB

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 3.6 MiB

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 120 KiB

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 123 KiB

Arquivo binário não exibido.

Depois

Largura:  |  Altura:  |  Tamanho: 76 KiB

+28 -7
Ver Arquivo
@@ -1,19 +1,38 @@
{
"name": "clitest",
"version": "0.0.0",
"name": "openbci-dashboard",
"description": "A fullstack javascript app for capturing and visualizing OpenBCI EEG data",
"main": "visualizer.js",
"version": "0.1.0",
"author": "Alex Castillo <alex@castillo.io>",
"license": "MIT",
"private": false,
"angular-cli": {},
"engines": {
"node": ">= 6.2.0 < 7"
},
"scripts": {
"start": "ng server",
"postinstall": "typings install",
"lint": "tslint \"src/**/*.ts\"",
"format": "clang-format -i -style=file --glob=src/**/*.ts",
"visualize": "concurrently \"ng serve\" \"node visualizer\" ",
"simulate": "concurrently \"ng serve\" \"node visualizer simulate\" ",
"visualize": "concurrently \"ng serve\" \"node src/server/app\" ",
"simulate": "concurrently \"ng serve\" \"node src/server/app simulate\" ",
"pree2e": "webdriver-manager update",
"e2e": "protractor"
},
"private": true,
"keywords": [
"openbci",
"eeg",
"neurojs",
"dashboard"
],
"repository": {
"type": "git",
"url": "git@github.com:NeuroJS/openbci-dashboard.git"
},
"bugs": {
"url": "https://github.com/NeuroJS/openbci-dashboard/issues"
},
"dependencies": {
"@angular/common": "2.0.0-rc.1",
"@angular/compiler": "2.0.0-rc.1",
@@ -21,16 +40,18 @@
"@angular/platform-browser": "2.0.0-rc.1",
"@angular/platform-browser-dynamic": "2.0.0-rc.1",
"@angular/router": "2.0.0-rc.1",
"chart.js": "^1.0.2",
"brainbrowser": "^2.3.0",
"chart.js": "^2.1.4",
"chroma-js": "^1.1.1",
"dsp.js": "neurojs/dsp.js",
"es6-shim": "^0.35.0",
"express": "^4.13.4",
"fili": "^1.2.1",
"jstat": "^1.5.2",
"ng2-charts": "^1.0.3",
"ng2-charts": "^1.1.0",
"nodemon": "^1.9.1",
"openbci-sdk": "^0.3.4",
"plotly.js": "^1.10.2",
"reflect-metadata": "0.1.3",
"rxjs": "5.0.0-beta.6",
"smoothie": "^1.27.0",
+8
Ver Arquivo
@@ -10,6 +10,14 @@
margin: 0;
}
main {
display: flex;
}
.content {
width: 100%;
}
h1 {
padding: 20px;
font-weight: 300;
+13 -9
Ver Arquivo
@@ -1,11 +1,15 @@
<main>
<h1>{{title}}</h1>
<nav>
<a [routerLink]="['/time-series']">Time Series</a>
<a [routerLink]="['/frequency/line', { type: 'Line' }]">Frequency Line</a>
<a [routerLink]="['/frequency/radar', { type: 'Radar' }]">Frequency Radar</a>
<a [routerLink]="['/frequency/bands']">Frequency Bands</a>
<a [routerLink]="['/topo']">Topo</a>
</nav>
<router-outlet></router-outlet>
<bci-filters></bci-filters>
<section class="content">
<h1>{{ title }}</h1>
<nav>
<a [routerLink]="['/time-series']">Time Series</a>
<a [routerLink]="['/frequency/line', { type: 'line' }]">Frequency Line</a>
<a [routerLink]="['/frequency/radar', { type: 'radar' }]">Frequency Radar</a>
<a [routerLink]="['/frequency/bands']">Frequency Bands</a>
<a [routerLink]="['/motion']">Motion</a>
<a [routerLink]="['/topo']">Topo</a>
</nav>
<router-outlet></router-outlet>
</section>
</main>
+4 -1
Ver Arquivo
@@ -1,8 +1,10 @@
import { Component, OnInit } from '@angular/core';
import { FiltersComponent } from './filters';
import { TimeSeriesComponent } from './time-series';
import { FrequencyComponent } from './frequency';
import { FrequencyBandsComponent } from './frequency-bands';
import { TopoComponent } from './topo';
import { MotionComponent } from './motion';
import { Routes, Router, ROUTER_PROVIDERS, ROUTER_DIRECTIVES } from '@angular/router';
@Component({
@@ -10,7 +12,7 @@ import { Routes, Router, ROUTER_PROVIDERS, ROUTER_DIRECTIVES } from '@angular/ro
selector: 'bci-dashboard',
templateUrl: 'dashboard.component.html',
styleUrls: ['dashboard.component.css'],
directives: [ROUTER_DIRECTIVES],
directives: [ROUTER_DIRECTIVES, FiltersComponent],
providers: [ROUTER_PROVIDERS]
})
@@ -20,6 +22,7 @@ import { Routes, Router, ROUTER_PROVIDERS, ROUTER_DIRECTIVES } from '@angular/ro
{ path: '/frequency/line', component: FrequencyComponent },
{ path: '/frequency/radar', component: FrequencyComponent },
{ path: '/frequency/bands', component: FrequencyBandsComponent },
{ path: '/motion', component: MotionComponent },
{ path: '/topo', component: TopoComponent }
])
+66
Ver Arquivo
@@ -0,0 +1,66 @@
:host {
display: block;
}
.filters {
width: 120px;
height: 100vh;
padding: 14px;
background-color: #333;
}
.filters h3 {
font-weight: 500;
margin-top: 10px;
}
.filters article {
display: flex;
flex-direction: column;
margin-bottom: 14px;
}
.filters nav {
display: flex;
flex-direction: column;
}
.filters label {
margin-bottom: 8px;
font-size: 14px;
}
.filters .select {
position: relative;
border: 2px solid rgba(255,255,255, 0.6);
border-radius: 4px;
}
.filters .select:after {
content: "▼";
position: absolute;
top: 0;
right: 0;
bottom: 0;
font-size: 6px;
line-height: 27px;
padding: 0 8px;
color: rgba(255,255,255,0.2);
pointer-events: none;
}
.filters select {
width: 100%;
-webkit-appearance: none;
color: rgba(255,255,255,0.4);
font-weight: 300;
letter-spacing: 1px;
background: transparent;
padding: 6px;
outline: none;
border: 0;
}
.filters .disabled {
opacity: 0.2;
}
+20
Ver Arquivo
@@ -0,0 +1,20 @@
<aside class="filters">
<h3>Filters</h3>
<nav>
<article *ngFor="let filter of filters"
[ngClass]="{ disabled: !filter.enabled }">
<label>{{ filter.label }}</label>
<div class="select">
<select
[multiple]="filter.type === 'multiple'"
[disabled]="!filter.enabled"
(change)="applyFilter($event.target.value)">
<option *ngFor="let option of filter.options"
[value]="option.id">
{{ option.label }}
</option>
</select>
</div>
</article>
</nav>
</aside>
+46
Ver Arquivo
@@ -0,0 +1,46 @@
import {
beforeEach,
beforeEachProviders,
describe,
expect,
it,
inject,
} from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '@angular/compiler/testing';
import { Component } from '@angular/core';
import { By } from '@angular/platform-browser';
import { FiltersComponent } from './filters.component';
describe('Component: Filters', () => {
let builder: TestComponentBuilder;
beforeEachProviders(() => [FiltersComponent]);
beforeEach(inject([TestComponentBuilder], function (tcb: TestComponentBuilder) {
builder = tcb;
}));
it('should inject the component', inject([FiltersComponent],
(component: FiltersComponent) => {
expect(component).toBeTruthy();
}));
it('should create the component', inject([], () => {
return builder.createAsync(FiltersComponentTestController)
.then((fixture: ComponentFixture<any>) => {
let query = fixture.debugElement.query(By.directive(FiltersComponent));
expect(query).toBeTruthy();
expect(query.componentInstance).toBeTruthy();
});
}));
});
@Component({
selector: 'test',
template: `
<bci-filters></bci-filters>
`,
directives: [FiltersComponent]
})
class FiltersComponentTestController {
}
+30
Ver Arquivo
@@ -0,0 +1,30 @@
import { Component, OnInit } from '@angular/core';
import * as io from 'socket.io-client';
import { Constants } from '../shared';
@Component({
moduleId: module.id,
selector: 'bci-filters',
templateUrl: 'filters.component.html',
styleUrls: ['filters.component.css'],
providers: [Constants]
})
export class FiltersComponent {
socket: any;
constructor(private constants: Constants) {
this.socket = io(this.constants.socket.url);
}
private filters: Array<any> = this.constants.filters;
applyFilter (filter) {
this.socket.emit(
this.constants.socket.events.filter,
filter
);
}
}
+1
Ver Arquivo
@@ -0,0 +1 @@
export { FiltersComponent } from './filters.component';
@@ -1,14 +1,21 @@
.chart {
display: block;
width: 100%;
height: 100%;
}
:host {
display: inline-block;
margin: 20px;
margin: 0 0 20px 20px;
padding: 20px;
box-shadow: 0 0 5px rgba(0,0,0,0.3);
background-color: #333333;
position: relative;
height: 100%;
width: 27%;
width: 47%;
overflow: hidden;
box-sizing: border-box;
}
h2 {
@@ -21,4 +28,9 @@ h2 {
.capitalize {
text-transform: capitalize;
}
.frequency-band {
height: 100%;
padding-top: 40px;
}
@@ -1,10 +1,11 @@
<section class="frequency-band" [ngClass]="{ 'loading': !data }">
<h2 class="capitalize">{{ band }} {{ type }}</h2>
<base-chart class="chart"
[data]="data"
[datasets]="data"
[labels]="channels"
[options]="options"
[colours]="colors"
[colors]="colors"
[legend]="false"
[series]="channels"
[chartType]="type">
</base-chart>
+19 -16
Ver Arquivo
@@ -1,8 +1,7 @@
import { Component, ElementRef, OnInit, OnDestroy, Input } from '@angular/core';
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import * as io from 'socket.io-client';
import { ChartService } from '../shared';
import { ChartService, Constants } from '../shared';
import { CHART_DIRECTIVES } from '../shared/ng2-charts';
import { Constants } from '../shared/constants';
@Component({
moduleId: module.id,
@@ -13,13 +12,12 @@ import { Constants } from '../shared/constants';
providers: [ChartService, Constants]
})
export class FrequencyBandComponent implements OnInit {
export class FrequencyBandComponent implements OnInit, OnDestroy {
socket: any;
constructor(private view: ElementRef,
private chartService: ChartService,
constructor(private chartService: ChartService,
private constants: Constants) {
this.view = view;
this.socket = io(constants.socket.url);
}
@@ -27,22 +25,27 @@ export class FrequencyBandComponent implements OnInit {
@Input() public band:string;
@Input() public color:number;
private data:Array<any> = [[]];
private colors:Array<any>;
private channels:Array<string> = this.chartService.getChannels();
private options:any = this.chartService.getChartJSDefaults({
responsive: false
});
private data:Array<any> = [{ data: [], label: [] }];
private colors = this.chartService.getColorByIndex(this.color);
private channels = this.chartService.getChannels();
private options = this.chartService.getChartJSBarDefaults();
ngOnInit() {
ngOnInit() {
this.colors = this.chartService.getColorByIndex(this.color);
this.socket.on(this.constants.socket.events.fft, (data) => {
this.data = data[this.band || 'data'];
this.data = [];
data[this.band || 'data'].forEach((dataset, index) => {
this.data.push({
data: dataset
});
});
});
}
ngOnDestroy () {
this.socket.removeListener(this.constants.socket.events.fft);
this.socket.removeListener(
this.constants.socket.events.fft
);
}
}
@@ -1,9 +1,9 @@
<section>
<bci-frequency-band [type]="'Bar'" [band]="'delta'" [color]="1"></bci-frequency-band>
<bci-frequency-band [type]="'Bar'" [band]="'theta'" [color]="2"></bci-frequency-band>
<bci-frequency-band type="bar" band="delta" [color]="1"></bci-frequency-band>
<bci-frequency-band type="bar" band="theta" [color]="2"></bci-frequency-band>
</section>
<section>
<bci-frequency-band [type]="'Bar'" [band]="'alpha'" [color]="3"></bci-frequency-band>
<bci-frequency-band [type]="'Bar'" [band]="'beta'" [color]="4"></bci-frequency-band>
<bci-frequency-band [type]="'Bar'" [band]="'gamma'" [color]="5"></bci-frequency-band>
<bci-frequency-band type="bar" band="alpha" [color]="3"></bci-frequency-band>
<bci-frequency-band type="bar" band="beta" [color]="4"></bci-frequency-band>
<bci-frequency-band type="bar" band="gamma" [color]="5"></bci-frequency-band>
</section>
+8 -1
Ver Arquivo
@@ -1,6 +1,8 @@
.chart {
display: block;
width: 100%;
height: 100%;
}
:host {
@@ -10,7 +12,7 @@
box-shadow: 0 0 5px rgba(0,0,0,0.3);
background-color: #333333;
position: relative;
height: 100%;
height: 600px;
overflow: hidden;
}
@@ -20,4 +22,9 @@ h2 {
top: 10px;
right: 20px;
font-weight: 300;
}
.frequency {
height: 100%;
padding-top: 40px;
}
+2 -2
Ver Arquivo
@@ -1,10 +1,10 @@
<section class="frequency" [ngClass]="{ 'loading': !data }">
<h2>Frequency {{ type }}</h2>
<base-chart class="chart"
[data]="data"
[datasets]="data"
[labels]="labels"
[options]="options"
[colours]="colors"
[colors]="colors"
[series]="channels"
[chartType]="type">
</base-chart>
+30 -10
Ver Arquivo
@@ -1,9 +1,8 @@
import { Component, ElementRef, OnInit, OnDestroy, Input } from '@angular/core';
import { RouteSegment, ROUTER_PROVIDERS } from '@angular/router';
import * as io from 'socket.io-client';
import { ChartService } from '../shared';
import { ChartService, Constants } from '../shared';
import { CHART_DIRECTIVES } from '../shared/ng2-charts';
import { Constants } from '../shared/constants';
@Component({
moduleId: module.id,
@@ -17,32 +16,53 @@ import { Constants } from '../shared/constants';
export class FrequencyComponent implements OnInit {
socket: any;
constructor(private view: ElementRef,
private chartService: ChartService,
constructor(private chartService: ChartService,
private segment: RouteSegment,
private constants: Constants) {
this.view = view;
this.socket = io(constants.socket.url);
this.type = segment.getParam('type') || 'Line';
this.type = segment.getParam('type') || 'line';
this.setOptions(this.type);
}
@Input() type:string;
private data:Array<any> = [[]];
private data:Array<any> = Array(8).fill(0).map(() => { return { data: [], label: [] } });
private labels:Array<any> = [];
private colors:Array<any> = this.chartService.getColors();
private channels:Array<string> = this.chartService.getChannels();
private options:any = this.chartService.getChartJSDefaults();
private options:any;
setOptions (type) {
if (type === 'line') {
this.options = this.chartService.getChartJSLineDefaults();
}
if (type === 'radar') {
this.options = this.chartService.getChartJSRadarDefaults();
}
}
ngOnInit() {
this.socket.on(this.constants.socket.events.fft, (data) => {
this.data = data.data;
this.data = [];
data.data.forEach((dataset, index) => {
this.data.push({
data: dataset,
label: this.channels[index],
borderWidth: 1,
pointRadius: 0,
fill: false
});
});
this.labels = data.labels;
});
}
ngOnDestroy () {
this.socket.removeListener(this.constants.socket.events.fft);
this.socket.removeListener(
this.constants.socket.events.fft
);
}
}
Ver Arquivo
+1
Ver Arquivo
@@ -0,0 +1 @@
export { MotionComponent } from './motion.component';
Diferenças do arquivo suprimidas por serem muito extensas Carregar Diff
Arquivo binário não exibido.
+25
Ver Arquivo
@@ -0,0 +1,25 @@
:host {
display: block;
margin: 20px;
padding: 20px;
box-shadow: 0 0 5px rgba(0,0,0,0.3);
background-color: #333333;
position: relative;
height: 100%;
width: 768px;
overflow: hidden;
}
h2 {
position: absolute;
margin: 0;
top: 10px;
right: 20px;
font-weight: 300;
}
#brainbrowser {
width: 100%;
height: 500px;
}
+4
Ver Arquivo
@@ -0,0 +1,4 @@
<section class="motion" [ngClass]="{ 'loading': !model }">
<h2>Motion</h2>
<article id="brainbrowser"></article>
</section>
+46
Ver Arquivo
@@ -0,0 +1,46 @@
import {
beforeEach,
beforeEachProviders,
describe,
expect,
it,
inject,
} from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '@angular/compiler/testing';
import { Component } from '@angular/core';
import { By } from '@angular/platform-browser';
import { MotionComponent } from './motion.component';
describe('Component: Motion', () => {
let builder: TestComponentBuilder;
beforeEachProviders(() => [MotionComponent]);
beforeEach(inject([TestComponentBuilder], function (tcb: TestComponentBuilder) {
builder = tcb;
}));
it('should inject the component', inject([MotionComponent],
(component: MotionComponent) => {
expect(component).toBeTruthy();
}));
it('should create the component', inject([], () => {
return builder.createAsync(MotionComponentTestController)
.then((fixture: ComponentFixture<any>) => {
let query = fixture.debugElement.query(By.directive(MotionComponent));
expect(query).toBeTruthy();
expect(query.componentInstance).toBeTruthy();
});
}));
});
@Component({
selector: 'test',
template: `
<bci-motion></bci-motion>
`,
directives: [MotionComponent]
})
class MotionComponentTestController {
}
+55
Ver Arquivo
@@ -0,0 +1,55 @@
import { Component, OnInit, ElementRef } from '@angular/core';
import * as io from 'socket.io-client';
import { Constants } from '../shared/constants';
declare var BrainBrowser;
@Component({
moduleId: module.id,
selector: 'bci-motion',
templateUrl: 'motion.component.html',
styleUrls: ['motion.component.css'],
providers: [Constants]
})
export class MotionComponent implements OnInit {
socket: any;
viewer: any;
model: any;
constructor(private view: ElementRef,
private constants: Constants) {
this.socket = io(constants.socket.url);
}
private rotation = [];
ngOnInit() {
BrainBrowser.config.set('worker_dir', 'vendor/brainbrowser/build/brainbrowser-2.3.0/workers');
this.socket.on(this.constants.socket.events.motion, (data) => {
this.rotation = data.data;
if (this.model) {
this.viewer.resetView();
this.viewer.model.rotation.set(...this.rotation);
}
});
}
ngAfterViewInit () {
this.viewer = BrainBrowser.SurfaceViewer.start('brainbrowser', (viewer) => {
this.viewer = viewer;
this.viewer.render();
this.viewer.setWireframe(true);
this.viewer.loadModelFromURL('app/motion/models/brain-surface.obj');
this.viewer.setClearColor(0x333333);
this.viewer.addEventListener('displaymodel', (data) => {
this.model = data.model;
});
});
}
}
+128 -23
Ver Arquivo
@@ -5,26 +5,131 @@ export class ChartService {
constructor() {}
getChartJSDefaults (overrides: any = {}): any {
getPlotlyContourLayout (overrides: any = {}): any {
return Object.assign({
bargap: 0,
autosize: true,
paper_bgcolor: 'rgba(0,0,0,0)',
plot_bgcolor: 'rgba(0,0,0,0)',
margin: { l: 0, r: 0, b: 0, t: 0 },
xaxis: {
autorange: true,
showgrid: false,
zeroline: false,
showline: false,
autotick: true,
ticks: '',
showticklabels: false
},
yaxis: {
autorange: true,
showgrid: false,
zeroline: false,
showline: false,
autotick: true,
ticks: '',
showticklabels: false
}
}, overrides);
}
getPlotlyContourData (overrides: any = {}): any {
return Object.assign({
z: [],
x: [],
y: [],
type: 'contour',
colorscale: 'Jet',
showscale: false
}, overrides);
}
getChartJSGlobalDefaults (overrides: any = {}): any {
return Object.assign({
responsive: true,
animation: false,
animationSteps: 15,
datasetStrokeWidth: 1,
pointDot: false,
pointDotRadius: 1,
pointDotStrokeWidth: 0,
datasetFill: false,
scaleOverride: true,
scaleStartValue: -2,
scaleStepWidth: 1,
scaleSteps: 6,
barShowStroke: false,
barValueSpacing: 1,
barStrokeWidth: 1
legend: {
display: true,
position: 'bottom'
},
}, overrides);
}
getChartJSLineDefaults (overrides: any = {}): any {
return Object.assign({
scales: {
xAxes: [{
gridLines: {
display: true
},
ticks: {
max: 4,
min: -2,
stepSize: 0.5
}
}],
yAxes: [{
gridLines: {
display: true
},
ticks: {
max: 4,
min: -2,
stepSize: 0.5
}
}]
}
}, this.getChartJSGlobalDefaults());
}
getChartJSBarDefaults (overrides: any = {}): any {
return Object.assign({
scales: {
xAxes: [{
gridLines: {
display: false
},
ticks: {
max: 4,
min: 0,
stepSize: 0.5
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
max: 4,
min: 0,
stepSize: 0.5
}
}]
}
}, this.getChartJSGlobalDefaults({
legend: {
display: false
}
}));
}
getChartJSRadarDefaults (overrides: any = {}): any {
return Object.assign({
scale: {
lineArc: false,
angleLines: {
display: true
},
ticks: {
max: 4,
min: -2,
stepSize: 0.5,
showLabelBackdrop: false
}
}
}, this.getChartJSGlobalDefaults());
}
getChartSmoothieDefaults (overrides: any = {}): any {
return Object.assign({
millisPerLine: 3000,
@@ -49,18 +154,18 @@ export class ChartService {
getColors (): Array<any> {
return [
{ strokeColor: 'rgba(112,185,252,1)', fillColor: 'rgba(112,185,252,1)' },
{ strokeColor: 'rgba(116,150,161,1)', fillColor: 'rgba(116,150,161,1)' },
{ strokeColor: 'rgba(162,86,178,1)', fillColor: 'rgba(162,86,178,1)' },
{ strokeColor: 'rgba(144,132,246,1)', fillColor: 'rgba(144,132,246,1)' },
{ strokeColor: 'rgba(138,219,229,1)', fillColor: 'rgba(138,219,229,1)' },
{ strokeColor: 'rgba(232,223,133,1)', fillColor: 'rgba(232,223,133,1)' },
{ strokeColor: 'rgba(148,159,177,1)', fillColor: 'rgba(148,159,177,1)' },
{ strokeColor: 'rgba(77,83,96,1)', fillColor: 'rgba(77,83,96,1)' }
{ borderColor: 'rgba(112,185,252,1)', backgroundColor: 'rgba(112,185,252,1)' },
{ borderColor: 'rgba(116,150,161,1)', backgroundColor: 'rgba(116,150,161,1)' },
{ borderColor: 'rgba(162,86,178,1)', backgroundColor: 'rgba(162,86,178,1)' },
{ borderColor: 'rgba(144,132,246,1)', backgroundColor: 'rgba(144,132,246,1)' },
{ borderColor: 'rgba(138,219,229,1)', backgroundColor: 'rgba(138,219,229,1)' },
{ borderColor: 'rgba(232,223,133,1)', backgroundColor: 'rgba(232,223,133,1)' },
{ borderColor: 'rgba(148,159,177,1)', backgroundColor: 'rgba(148,159,177,1)' },
{ borderColor: 'rgba(77,83,96,1)', backgroundColor: 'rgba(77,83,96,1)' }
];
}
getColorByIndex (index:number): Array<any> {
getColorByIndex (index: number): Array<any> {
return this.getColors().filter((c, i) => index === i);
}
+185 -10
Ver Arquivo
@@ -2,16 +2,191 @@ import { Injectable } from '@angular/core';
@Injectable()
export class Constants {
socket: any;
constructor(){
this.socket = {
url: 'http://localhost:8080',
events: {
fft: 'bci:fft',
time: 'bci:time',
topo: 'bci:topo'
socket: any = {
url: 'http://localhost:8080',
events: {
fft: 'bci:fft',
time: 'bci:time',
topo: 'bci:topo',
filter: 'bci:filter',
motion: 'bci:motion'
}
};
filters: Array<any> = [
{
id: 'NOTCH',
label: 'Notch',
type: 'single',
enabled: true,
options: [
{
id: 'NOTCH:60',
label: '60 Hz'
},
{
id: 'NOTCH:50',
label: '50 Hz'
},
{
id: 'NOTCH:NONE',
label: 'None'
}
]
},
{
id: 'BANDPASS',
label: 'Band Pass',
type: 'single',
enabled: false,
options: [
{
id: 'BANDPASS:1-50',
label: '1-50 Hz'
},
{
id: 'BANDPASS:7-13',
label: '7-13 Hz'
},
{
id: 'BANDPASS:15-50',
label: '15-50 Hz'
},
{
id: 'BANDPASS:5-50',
label: '5-50 Hz'
},
{
id: 'BANDPASS:NONE',
label: 'None'
}
};
}
]
},
{
id: 'VERTSCALE',
label: 'Vert Scale',
type: 'single',
enabled: false,
options: [
{
id: 'VERTSCALE:50',
label: '50uV'
},
{
id: 'VERTSCALE:100',
label: '100uV'
},
{
id: 'VERTSCALE:200',
label: '200uV'
},
{
id: 'VERTSCALE:400',
label: '400uV'
},
{
id: 'VERTSCALE:1000',
label: '1000uV'
},
{
id: 'VERTSCALE:10000',
label: '10,000uV'
},
{
id: 'VERTSCALE:NONE',
label: 'None'
}
]
},
{
id: 'VERTALGO',
label: 'Vert Algo',
type: 'single',
enabled: false,
options: [
{
id: 'VERTALGO:50',
label: 'Log'
},
{
id: 'VERTALGO:Linear',
label: 'Linear'
}
]
},
{
id: 'SMOOTH',
label: 'Smooth',
type: 'single',
enabled: false,
options: [
{
id: 'SMOOTH:0-75',
label: '0 75'
},
{
id: 'SMOOTH:0-9',
label: '0 9'
},
{
id: 'SMOOTH:0-95',
label: '0 95'
},
{
id: 'SMOOTH:0-98',
label: '0 98'
},
{
id: 'SMOOTH:0-0',
label: '0 0'
},
{
id: 'SMOOTH:0-5',
label: '0 5'
},
]
},
{
id: 'POLARITY',
label: 'Polarity',
type: 'single',
enabled: false,
options: [
{
id: 'POLARITY:Yes',
label: 'Yes'
},
{
id: 'POLARITY:NO',
label: 'No'
}
]
},
{
id: 'MAXFREQUENCY',
label: 'Max Frequency',
type: 'single',
enabled: false,
options: [
{
id: 'MAXFREQUENCY:60',
label: '60 Hz'
},
{
id: 'MAXFREQUENCY:120',
label: '120 Hz'
},
{
id: 'MAXFREQUENCY:20',
label: '20 Hz'
},
{
id: 'MAXFREQUENCY:40',
label: '40 Hz'
}
]
}
];
}
+1
Ver Arquivo
@@ -1,2 +1,3 @@
export * from './chart.service';
export * from './ng2-charts';
export * from './constants';
+229 -208
Ver Arquivo
@@ -1,119 +1,51 @@
import {
Component, OnDestroy, OnInit, OnChanges,
EventEmitter, ElementRef, Input
Component, OnDestroy, OnInit, OnChanges, EventEmitter, ElementRef, Input,
Output
} from '@angular/core';
import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass} from '@angular/common';
declare var Chart:any;
@Component({
selector: 'chart',
template: `<canvas></canvas>`,
directives: [CORE_DIRECTIVES, NgClass]
})
export class ChartsComponent {}
@Component({
selector: 'base-chart',
properties: [
'data',
'labels',
'series',
'colours',
'chartType',
'legend',
'options'
],
events: ['chartClick', 'chartHover'],
template: `
<canvas style="width: 100%; height: 100%;" (click)="click($event)" (mousemove)="hover($event)"></canvas>
`,
template: `<canvas style="width: 100%; height: 100%;"></canvas>`,
directives: [CORE_DIRECTIVES, FORM_DIRECTIVES, NgClass]
})
export class BaseChartComponent implements OnInit, OnDestroy, OnChanges {
@Input() public data:Array<any> = [];
export class BaseChartComponent implements OnDestroy, OnChanges, OnInit {
public static defaultColors:Array<number[]> = [
[255, 99, 132],
[54, 162, 235],
[255, 206, 86],
[231, 233, 237],
[75, 192, 192],
[151, 187, 205],
[220, 220, 220],
[247, 70, 74],
[70, 191, 189],
[253, 180, 92],
[148, 159, 177],
[77, 83, 96]
];
@Input() public data:number[] | Array<number[]>;
@Input() public datasets:any[];
@Input() public labels:Array<any> = [];
@Input() public options:any = {responsive: true};
@Input() public chartType:string;
@Input() public series:Array<any> = [];
@Input() public colours:Array<any> = [];
@Input() public colors:Array<any>;
@Input() public legend:boolean;
@Output() public chartClick:EventEmitter<any> = new EventEmitter();
@Output() public chartHover:EventEmitter<any> = new EventEmitter();
private ctx:any;
private cvs:any;
private parent:any;
private chart:any;
private legendTemplate:any;
private initFlag:boolean = false;
private chartClick:EventEmitter<any> = new EventEmitter();
private chartHover:EventEmitter<any> = new EventEmitter();
private defaultsColours:Array<any> = [
{
fillColor: 'rgba(151,187,205,0.2)',
strokeColor: 'rgba(151,187,205,1)',
pointColor: 'rgba(151,187,205,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(151,187,205,0.8)',
color: 'rgba(151,187,205,1)',
highlight: 'rgba(151,187,205,0.8)'
}, {
fillColor: 'rgba(220,220,220,0.2)',
strokeColor: 'rgba(220,220,220,1)',
pointColor: 'rgba(220,220,220,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(220,220,220,0.8)',
color: 'rgba(220,220,220,1)',
highlight: 'rgba(220,220,220,0.8)'
}, {
fillColor: 'rgba(247,70,74,0.2)',
strokeColor: 'rgba(247,70,74,1)',
pointColor: 'rgba(247,70,74,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(247,70,74,0.8)',
color: 'rgba(247,70,74,1)',
highlight: 'rgba(247,70,74,0.8)'
}, {
fillColor: 'rgba(70,191,189,0.2)',
strokeColor: 'rgba(70,191,189,1)',
pointColor: 'rgba(70,191,189,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(70,191,189,0.8)',
color: 'rgba(70,191,189,1)',
highlight: 'rgba(70,191,189,0.8)'
}, {
fillColor: 'rgba(253,180,92,0.2)',
strokeColor: 'rgba(253,180,92,1)',
pointColor: 'rgba(253,180,92,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(253,180,92,0.8)',
color: 'rgba(253,180,92,1)',
highlight: 'rgba(253,180,92,0.8)'
}, {
fillColor: 'rgba(148,159,177,0.2)',
strokeColor: 'rgba(148,159,177,1)',
pointColor: 'rgba(148,159,177,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(148,159,177,0.8)',
color: 'rgba(148,159,177,1)',
highlight: 'rgba(148,159,177,0.8)'
}, {
fillColor: 'rgba(77,83,96,0.2)',
strokeColor: 'rgba(77,83,96,1)',
pointColor: 'rgba(77,83,96,1)',
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: 'rgba(77,83,96,0.8)',
color: 'rgba(77,83,96,1)',
highlight: 'rgba(77,83,96,0.8)'
}];
private element:ElementRef;
public constructor(element:ElementRef) {
this.element = element;
}
@@ -122,8 +54,10 @@ export class BaseChartComponent implements OnInit, OnDestroy, OnChanges {
this.ctx = this.element.nativeElement.children[0].getContext('2d');
this.cvs = this.element.nativeElement.children[0];
this.parent = this.element.nativeElement;
this.refresh();
this.initFlag = true;
if (this.data || this.datasets) {
this.create(this.ctx);
}
}
public ngOnChanges():any {
@@ -137,129 +71,216 @@ export class BaseChartComponent implements OnInit, OnDestroy, OnChanges {
this.chart.destroy();
this.chart = void 0;
}
if (this.legendTemplate) {
this.legendTemplate.destroy();
this.legendTemplate = void 0;
}
}
public setLegend():void {
let list = this.parent.getElementsByTagName('ul');
if (list.length) {
list[0].remove();
this.parent.insertAdjacentHTML('beforeend', this.chart.generateLegend());
} else {
this.parent.insertAdjacentHTML('beforeend', this.chart.generateLegend());
}
}
public create(ctx:any):any {
let datasets:any = void 0;
public getColour(colour:Array<number>):any {
return {
fillColor: this.rgba(colour, 0.2),
strokeColor: this.rgba(colour, 1),
pointColor: this.rgba(colour, 1),
pointStrokeColor: '#fff',
pointHighlightFill: '#fff',
pointHighlightStroke: this.rgba(colour, 0.8),
color: this.rgba(colour, 1),
highlight: this.rgba(colour, 0.8)
// in case if datasets is not provided, but data is present
if (!this.datasets || !this.datasets.length && (this.data && this.data.length)) {
if (Array.isArray(this.data[0])) {
datasets = (this.data as Array<number[]>).map((data:number[], index:number) => {
return {data, label: this.labels[index] || `Label ${index}`};
});
} else {
datasets = [{data: this.data, label: `Label 0`}];
}
}
if (this.datasets && this.datasets.length ||
(datasets && datasets.length)) {
datasets = (this.datasets || datasets)
.map((elm:number, index:number) => {
let newElm:any = Object.assign({}, elm);
if (this.colors && this.colors.length) {
Object.assign(newElm, this.colors[index]);
} else {
Object.assign(newElm, getColors(this.chartType, index, newElm.data.length));
}
return newElm;
});
}
if (!datasets) {
throw new Error(`ng-charts configuration error,
data or datasets field are required to render char ${this.chartType}`);
}
const options:any = Object.assign({}, this.options);
// hock for onHover and onClick events
options.hover = options.hover || {};
if (!options.hover.onHover) {
options.hover.onHover = (active:Array<any>) => {
if (active && !active.length) {
return;
}
this.chartHover.emit({active});
};
}
if (!options.onClick) {
options.onClick = (event:any, active:Array<any>) => {
this.chartClick.emit({event, active});
};
}
const opts = {
type: this.chartType,
data: {
labels: this.labels,
datasets: datasets
},
options: options
};
}
public getRandomInt(min:number, max:number):number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
public rgba(colour:Array<number>, alpha:number):string {
return 'rgba(' + colour.concat(alpha).join(',') + ')';
}
public click(evt:any):void {
let atEvent = this.chart.getPointsAtEvent || this.chart.getBarsAtEvent || this.chart.getSegmentsAtEvent;
let activePoints = atEvent.call(this.chart, evt);
if (activePoints.length > 0) {
let activeLabel = activePoints[0].label;
this.chartClick.emit({activePoints: activePoints, activeLabel: activeLabel});
}
}
public hover(evt:any):void {
let atEvent = this.chart.getPointsAtEvent || this.chart.getBarsAtEvent || this.chart.getSegmentsAtEvent;
let activePoints = atEvent.call(this.chart, evt);
if (activePoints.length > 0) {
let activeLabel = activePoints[0].label;
let activePoint = activePoints[0].value;
this.chartHover.emit({activePoints: activePoints, activePoint: activePoint, activeLabel: activeLabel});
}
}
public getChartBuilder(ctx:any, data:Array<any>, options:any):any {
return new Chart(ctx)[this.chartType](data, options);
}
public getDataObject(label:string, value:any):any {
if (this.chartType === 'Line'
|| this.chartType === 'Bar'
|| this.chartType === 'Radar') {
return {
label: label,
data: value
};
if (typeof Chart === 'undefined') {
throw new Error('ng2-charts configuration issue: Embedding Chart.js lib is mandatory');
}
if (this.chartType === 'Pie'
|| this.chartType === 'Doughnut'
|| this.chartType === 'PolarArea') {
return {
label: label,
value: value
};
}
return void 0;
}
public getChartData(labels:any, dataObject:any):any {
if (this.chartType === 'Line'
|| this.chartType === 'Bar'
|| this.chartType === 'Radar') {
return {
labels: labels,
datasets: dataObject
};
}
if (this.chartType === 'Pie'
|| this.chartType === 'Doughnut'
|| this.chartType === 'PolarArea') {
return dataObject;
}
this.chart = new Chart(ctx, opts);
}
private refresh():any {
if (this.options.responsive && this.parent.clientHeight === 0) {
return setTimeout(() => this.refresh(), 50);
}
this.ngOnDestroy();
let dataset:Array<any> = [];
for (let i = 0; i < this.data.length; i++) {
let colourDesc:Array<number> = [this.getRandomInt(0, 255), this.getRandomInt(0, 255), this.getRandomInt(0, 255)];
let colour = i < this.colours.length ? this.colours[i] : this.defaultsColours[i] || this.getColour(colourDesc);
let data:any = Object.assign(colour,
this.getDataObject(this.series[i] || this.labels[i], this.data[i]));
dataset.push(data);
}
let data:any = this.getChartData(this.labels, dataset);
this.chart = this.getChartBuilder(this.ctx, data, this.options);
if (this.legend) {
this.setLegend();
}
this.chart.data.labels = [...this.labels];
this.chart.data.datasets = [...this.chart.data.datasets.map((set, index) => {
return Object.assign(set, this.datasets[index]);
})];
this.chart.update();
}
}
export const CHART_DIRECTIVES:Array<any> = [ChartsComponent, BaseChartComponent];
// private helper functions
export interface Color {
backgroundColor?:string | string[];
borderWidth?:number | number[];
borderColor?:string | string[];
borderCapStyle?:string;
borderDash?:number[];
borderDashOffset?:number;
borderJoinStyle?:string;
pointBorderColor?:string | string[];
pointBackgroundColor?:string | string[];
pointBorderWidth?:number | number[];
pointRadius?:number | number[];
pointHoverRadius?:number | number[];
pointHitRadius?:number | number[];
pointHoverBackgroundColor?:string | string[];
pointHoverBorderColor?:string | string[];
pointHoverBorderWidth?:number | number[];
pointStyle?:string | string[];
hoverBackgroundColor?:string | string[];
hoverBorderColor?:string | string[];
hoverBorderWidth?:number;
}
// pie | doughnut
export interface Colors extends Color {
data?:number[];
label?:string;
}
function rgba(colour:Array<number>, alpha:number):string {
return 'rgba(' + colour.concat(alpha).join(',') + ')';
}
function getRandomInt(min:number, max:number):number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function formatLineColor(colors:Array<number>):Color {
return {
backgroundColor: rgba(colors, 0.4),
borderColor: rgba(colors, 1),
pointBackgroundColor: rgba(colors, 1),
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: rgba(colors, 0.8)
};
}
function formatBarColor(colors:Array<number>):Color {
return {
backgroundColor: rgba(colors, 0.6),
borderColor: rgba(colors, 1),
hoverBackgroundColor: rgba(colors, 0.8),
hoverBorderColor: rgba(colors, 1)
};
}
function formatPieColors(colors:Array<number[]>):Colors {
return {
backgroundColor: colors.map((color:number[]) => rgba(color, 0.6)),
borderColor: colors.map(() => '#fff'),
pointBackgroundColor: colors.map((color:number[]) => rgba(color, 1)),
pointBorderColor: colors.map(() => '#fff'),
pointHoverBackgroundColor: colors.map((color:number[]) => rgba(color, 1)),
pointHoverBorderColor: colors.map((color:number[]) => rgba(color, 1))
};
}
function formatPolarAreaColors(colors:Array<number[]>):Color {
return {
backgroundColor: colors.map((color:number[]) => rgba(color, 0.6)),
borderColor: colors.map((color:number[]) => rgba(color, 1)),
hoverBackgroundColor: colors.map((color:number[]) => rgba(color, 0.8)),
hoverBorderColor: colors.map((color:number[]) => rgba(color, 1))
};
}
function getRandomColor():number[] {
return [getRandomInt(0, 255), getRandomInt(0, 255), getRandomInt(0, 255)];
}
/**
* Generate colors for line|bar charts
* @param index
* @returns {number[]|Color}
*/
function generateColor(index:number):number[] {
return BaseChartComponent.defaultColors[index] || getRandomColor();
}
/**
* Generate colors for pie|doughnut charts
* @param count
* @returns {Colors}
*/
function generateColors(count:number):Array<number[]> {
let colorsArr:Array<number[]> = new Array(count);
for (let i = 0; i < count; i++) {
colorsArr[i] = BaseChartComponent.defaultColors[i] || getRandomColor();
}
return colorsArr;
}
/**
* Generate colors by chart type
* @param chartType
* @param index
* @param count
* @returns {Color}
*/
function getColors(chartType:string, index:number, count:number):Color {
if (chartType === 'pie' || chartType === 'doughnut') {
return formatPieColors(generateColors(count));
}
if (chartType === 'polarArea') {
return formatPolarAreaColors(generateColors(count));
}
if (chartType === 'line' || chartType === 'radar') {
return formatLineColor(generateColor(index));
}
if (chartType === 'bar') {
return formatBarColor(generateColor(index));
}
return generateColor(index);
}
export const CHART_DIRECTIVES:Array<any> = [BaseChartComponent];
@@ -6,7 +6,6 @@
box-shadow: 0 0 5px rgba(0,0,0,0.3);
background-color: #333333;
position: relative;
height: 100%;
width: 1060px;
overflow: hidden;
}
+2 -2
Ver Arquivo
@@ -3,7 +3,7 @@
<aside class="time-series-channels">
<ul>
<li *ngFor="let channel of channels, let i = index"
[ngStyle]="{ 'color': colors[i].strokeColor }">
[ngStyle]="{ 'color': colors[i].borderColor }">
{{ channel }}
</li>
</ul>
@@ -12,7 +12,7 @@
<aside class="time-series-amplitudes">
<ul>
<li *ngFor="let amplitude of amplitudes, let i = index"
[ngStyle]="{ 'color': colors[i].strokeColor }">
[ngStyle]="{ 'color': colors[i].borderColor }">
{{ amplitude }}
</li>
</ul>
+13 -11
Ver Arquivo
@@ -1,8 +1,8 @@
import { Component, ElementRef, OnInit, OnDestroy } from '@angular/core';
import { Component, ElementRef } from '@angular/core';
import { OnInit, OnDestroy } from '@angular/core';
import { SmoothieChart, TimeSeries } from 'smoothie';
import { ChartService } from '../shared';
import { ChartService, Constants } from '../shared';
import * as io from 'socket.io-client';
import { Constants } from '../shared/constants';
@Component({
moduleId: module.id,
@@ -12,25 +12,23 @@ import { Constants } from '../shared/constants';
providers: [ChartService, Constants]
})
export class TimeSeriesComponent implements OnInit {
export class TimeSeriesComponent implements OnInit, OnDestroy {
socket: any;
constructor(private view: ElementRef,
private chartService: ChartService,
private constants: Constants) {
this.view = view;
this.socket = io(constants.socket.url);
this.chartService = chartService;
}
private options = this.chartService.getChartSmoothieDefaults();
private channels = this.chartService.getChannels();
private colors = this.chartService.getColors();
private timeSeries = new SmoothieChart(this.options);
private amplitudes = [];
private timeline = [];
private lines = Array(8).fill(0).map(() => new TimeSeries());
private channels = this.chartService.getChannels();
private colors = this.chartService.getColors();
ngOnInit() {
this.addTimeSeriesLines();
@@ -43,17 +41,21 @@ export class TimeSeriesComponent implements OnInit {
}
ngOnDestroy () {
this.socket.removeListener(this.constants.socket.events.time);
this.socket.removeListener(
this.constants.socket.events.time
);
}
ngAfterViewInit () {
this.timeSeries.streamTo(this.view.nativeElement.querySelector('canvas'), 40);
this.timeSeries.streamTo(
this.view.nativeElement.querySelector('#timeSeries')
);
}
addTimeSeriesLines () {
this.lines.forEach((line, index) => {
this.timeSeries.addTimeSeries(line, {
strokeStyle: this.colors[index].strokeColor
strokeStyle: this.colors[index].borderColor
});
});
}
+7 -6
Ver Arquivo
@@ -9,8 +9,8 @@
box-shadow: 0 0 5px rgba(0,0,0,0.3);
background-color: #333333;
position: relative;
height: 100%;
width: 50%;
height: 40vw;
width: 40vw;
}
h2 {
@@ -19,14 +19,15 @@ h2 {
top: 10px;
right: 20px;
font-weight: 300;
z-index: 1;
}
.topoplot-wrapper {
width: 300px;
height: 300px;
border: 3px solid black;
.topoplot {
-webkit-clip-path: circle(50%);
border-radius: 50%;
position: relative;
width: 100%;
height: 100%;
}
[class*='topoplot-c'] {
+3 -19
Ver Arquivo
@@ -1,22 +1,6 @@
<section [ngClass]="{ loading: !grid }">
<section [ngClass]="{ loading: !data }">
<h2>Topo</h2>
<section class="topoplot-wrapper">
<article class="topoplot-c1 top left"></article>
<article class="topoplot-c2 top right"></article>
<article class="topoplot-c3 middle left"></article>
<article class="topoplot-c4 middle right"></article>
<article class="topoplot-c5 third left"></article>
<article class="topoplot-c6 third right"></article>
<article class="topoplot-c7 bottom left"></article>
<article class="topoplot-c8 bottom right"></article>
<aside class="topoplot-grid">
<div *ngFor="let pixel of grid, let i = index"
[ngStyle]="getColor(i, pixel, grid)"
[ngClass]="getClass(i)">
</div>
</aside>
<section class="topoplot">
<div id="topo"></div>
</section>
</section>
+36 -24
Ver Arquivo
@@ -1,47 +1,59 @@
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Component, OnInit, OnDestroy, ElementRef } from '@angular/core';
import * as io from 'socket.io-client';
import { Constants } from '../shared/constants';
import { ChartService, Constants } from '../shared';
declare var chroma;
declare var chroma: any;
declare var Plotly: any;
@Component({
moduleId: module.id,
selector: 'bci-topo',
templateUrl: 'topo.component.html',
styleUrls: ['topo.component.css'],
providers: [Constants]
providers: [Constants, ChartService]
})
export class TopoComponent implements OnInit {
socket: any;
constructor(private constants: Constants) {
plotElement: any;
constructor(private view: ElementRef,
private chartService: ChartService,
private constants: Constants) {
this.socket = io(constants.socket.url);
}
private data: any = this.chartService.getPlotlyContourData({
x: this.getGrid(11),
y: this.getGrid(11)
});
private grid:Array<any> = [];
private layout: any = this.chartService.getPlotlyContourLayout();
ngOnInit() {
private options: any = {
staticPlot: true
};
ngOnInit(): void {
this.plotElement = this.view.nativeElement.querySelector('#topo');
Plotly.newPlot(this.plotElement.id, [this.data], this.layout, this.options);
this.socket.on(this.constants.socket.events.topo, (data) => {
this.grid = data.data;
this.data.z = data.data;
Plotly.redraw(this.plotElement);
Plotly.Plots.resize(this.plotElement);
});
}
ngOnDestroy () {
this.socket.removeListener(this.constants.socket.events.topo);
}
ngOnDestroy (): void {
this.socket.removeListener(
this.constants.socket.events.topo
);
}
getClass (index) {
return 'topoplot-u' + index;
getGrid (n) {
return Array(n).fill(0).map((v, i) => i).reverse();
}
getColor (index, pixel, grid) {
var min = Math.min.apply(Math, grid);
var max = Math.max.apply(Math, grid);
var f = chroma.scale('Spectral').domain([min, max]);
return {
'background-color': f(pixel)
}
}
}
+4 -2
Ver Arquivo
@@ -13,7 +13,7 @@
font-family: 'Roboto', sans-serif;
font-weight: 300;
color: #ffffff;
background-color: #222222;
background-color: rgba(30, 30, 30, 1);
margin: 0;
}
</style>
@@ -33,8 +33,10 @@
<body>
<bci-dashboard>Loading...</bci-dashboard>
<script src="vendor/chart.js/Chart.js"></script>
<script src="vendor/chart.js/dist/Chart.bundle.js"></script>
<script src="vendor/chroma-js/chroma.js"></script>
<script src="vendor/plotly.js/dist/plotly.js"></script>
<script src="vendor/brainbrowser/build/brainbrowser-2.3.0/brainbrowser.surface-viewer.min.js"></script>
<script src="vendor/es6-shim/es6-shim.js"></script>
<script src="vendor/reflect-metadata/Reflect.js"></script>
<script src="vendor/systemjs/dist/system.src.js"></script>
+28
Ver Arquivo
@@ -0,0 +1,28 @@
'use strict';
const constants = require('./constants');
const io = require('socket.io')(process.env.app_port || constants.sockets.port);
const Connectors = require('./connectors');
const Providers = require('./providers');
const Modules = require('./modules');
const Connector = new Connectors.Serialport({
verbose: true
});
const Signal = new Providers.Signal({ io });
const Motion = new Providers.Motion({ io });
Connector.start().then(() => {
const FFT = new Modules.FFT({ Signal });
const Topo = new Modules.Topo({ Signal });
const TimeSeries = new Modules.TimeSeries({ Signal });
});
Connector.stream((data) => {
Signal.buffer(data);
Motion.capture(data);
});
process.on(constants.events.terminate, Connector.stop);
@@ -0,0 +1,6 @@
module.exports = class Bluetooth {
/**
* The future!
*/
}
+9
Ver Arquivo
@@ -0,0 +1,9 @@
'use strict';
const Serialport = require('./serialport.connector');
const Bluetooth = require('./bluetooth.connector');
module.exports = {
Serialport,
Bluetooth
}
@@ -0,0 +1,55 @@
'use strict';
const Utils = require('../utils');
const OpenBCI = require('openbci-sdk');
const OpenBCIBoard = OpenBCI.OpenBCIBoard;
const constants = require('../constants');
module.exports = class Serialport extends OpenBCIBoard {
constructor (options) {
super(options);
}
start () {
return new Promise((resolve, reject) => {
var onConnect = () => {
this.on(constants.connector.readyEvent, () => {
this.streamStart();
resolve();
});
};
this.autoFindOpenBCIBoard()
.then((portName) => {
if (portName) {
this.connect(portName).then(onConnect);
}
})
.catch((error) => {
console.log(error);
if (Utils.signal.isSimulated()) {
this.connect(OpenBCI.OpenBCIConstants.OBCISimulatorPortName)
.then(onConnect);
} else {
reject(error);
}
});
});
}
stop () {
this.streamStop().then(() => {
this.disconnect().then(() => {
process.exit();
});
});
}
stream (callback) {
this.on(constants.connector.sampleEvent, callback);
}
}
+57
Ver Arquivo
@@ -0,0 +1,57 @@
'use strict';
module.exports = {
connector: {
channels: 8,
simulateFlag: 'simulate',
readyEvent: 'ready',
sampleEvent: 'sample'
},
signal: {
bufferSize: 256,
sampleRate: 250,
windowSize: 32 // data has a moving window of 32 samples = 128 milliseconds (250Hz)
},
fft: {
bins: 256
},
scale: {
global: 1,
simulated: 4,
skipLabels: 4
},
units: {
hertz: 'Hz',
microvolts: 'uV',
seconds: 's'
},
bands: { // frequency
delta: [1, 3],
theta: [4, 8],
alpha: [8, 12],
beta: [13, 30],
gamma: [30, 100]
},
time: {
windowSize: 5, // seconds
timeline: 20, // seconds
skip: 2 //
},
events: {
fft: 'bci:fft',
topo: 'bci:topo',
time: 'bci:time',
signal: 'bci:signal',
filter: 'bci:filter',
motion: 'bci:motion',
terminate: 'SIGINT'
},
topo: {
params: [0,10,11],
x: [3,7,2,8,0,10,3,7],
y: [0,0,3,3,8,8,10,10]
},
sockets: {
port: 8080
}
};
+76
Ver Arquivo
@@ -0,0 +1,76 @@
'use strict';
const dsp = require('dsp.js');
const Utils = require('../utils');
const constants = require('../constants');
module.exports = class FFT {
constructor ({ Signal }) {
this.signal = Signal;
this.bins = constants.fft.bins;
this.bufferSize = constants.signal.bufferSize;
this.sampleRate = constants.signal.sampleRate;
this.bands = constants.bands;
this.spectrums = [[],[],[],[],[],[],[],[]];
this.byBand = [];
this.labels = [];
this.subscribe();
}
subscribe () {
this.signal.emitter.on(constants.events.signal, (signals) => {
this.signalsToFFT(signals);
this.scaleLabels();
this.filterBands();
this.filterLabels();
this.emit();
});
}
signalsToFFT (signals) {
signals.forEach((signal, index) => {
signal = Utils.filter.process(signal);
let fft = new dsp.FFT(this.bufferSize, this.sampleRate);
fft.forward(signal);
this.spectrums[index] = Utils.data.parseObjectAsArray(fft.spectrum);
this.spectrums[index] = Utils.signal.voltsToMicrovolts(this.spectrums[index], true);
});
}
scaleLabels () {
this.labels = new Array(this.bins / 2).fill()
.map((label, index) => {
return Math.ceil(index * (this.sampleRate / this.bins));
});
}
filterBands () {
for (let band in this.bands) {
this.byBand[band] = Utils.filter.filterBand(this.spectrums, this.labels, this.bands[band]);
}
}
filterLabels () {
// Skip every 8, add uni (too many labels issue)
this.labels = this.labels.map((label, index, labels) => {
let eighth = index % constants.scale.skipLabels === 0;
let last = index === (labels.length - 1);
return eighth || last ? `${label} ${constants.units.hertz}` : ``;
});
}
emit () {
this.signal.io.emit(constants.events.fft, {
data: this.spectrums,
labels: this.labels,
theta: this.byBand.theta.spectrums,
delta: this.byBand.delta.spectrums,
alpha: this.byBand.alpha.spectrums,
beta: this.byBand.beta.spectrums,
gamma: this.byBand.gamma.spectrums
});
}
}
+11
Ver Arquivo
@@ -0,0 +1,11 @@
'use strict';
const FFT = require('./fft.module');
const TimeSeries = require('./time-series.module');
const Topo = require('./topo.module');
module.exports = {
FFT,
TimeSeries,
Topo
}
+67
Ver Arquivo
@@ -0,0 +1,67 @@
'use strict';
const Utils = require('../utils');
const constants = require('../constants');
module.exports = class TimeSeries {
constructor ({ Signal }) {
this.signal = Signal;
this.sampleRate = constants.signal.sampleRate;
this.bufferSize = constants.signal.bufferSize;
this.windowSize = constants.signal.windowSize;
this.timeline = Utils.data.generateTimeline(constants.time.timeline, constants.time.skip, constants.units.seconds);
this.timeSeries = [];
this.amplitudes = [];
this.subscribe();
}
subscribe () {
this.signal.emitter.on(constants.events.signal, (signal) => {
this.timeSeries = signal;
this.filter();
this.offset();
this.trim();
this.signalToAmplitudes(signal);
this.emit();
});
}
offset () {
this.timeSeries = this.timeSeries.map((channel, channelIndex) => {
return channel.map((amplitude) => {
return Utils.signal.offsetForGrid(amplitude, channelIndex, constants.connector.channels, this.signal.scale);
});
});
}
filter () {
this.timeSeries.forEach((signal) => {
signal = Utils.filter.highpass(signal);
});
}
trim () {
this.timeSeries.forEach((channel) => {
channel = channel.splice(0, this.bufferSize - this.windowSize);
});
}
signalToAmplitudes (signal) {
this.amplitudes = signal.map((channel) => {
let microvolts = Utils.signal.voltsToMicrovolts(channel[channel.length - 1])[0];
return `${Math.round(microvolts)} ${constants.units.microvolts}`;
});
}
emit () {
this.signal.io.emit(constants.events.time, {
data: this.timeSeries,
amplitudes: this.amplitudes,
timeline: this.timeline
});
}
}
+52
Ver Arquivo
@@ -0,0 +1,52 @@
'use strict';
const topogrid = require('topogrid');
const Utils = require('../utils');
const constants = require('../constants');
module.exports = class Topo {
constructor ({ Signal }) {
this.signal = Signal;
this.sampleRate = constants.signal.sampleRate;
this.grid = [];
this.subscribe();
}
subscribe () {
this.signal.emitter.on(constants.events.signal, (signal) => {
this.signalToGrid(signal);
this.emit();
});
}
signalToGrid (signal) {
let grid = [];
signal.forEach((channel) => {
grid.push(channel[channel.length - 1]);
});
/**
* params: Parameters for the grid [x,y,z] where x is the min
* of the grid, y is the Max of the grid and z is the number of points
* x: coordinates of the data
* y: coordinates of the data
* grid: data = [10,0,0,0,0,0,-10,30,25]; // the data values
*/
this.grid = topogrid.create(
constants.topo.x,
constants.topo.y,
grid,
constants.topo.params
);
}
emit () {
this.signal.io.emit(constants.events.topo, {
data: this.grid
});
}
}
+9
Ver Arquivo
@@ -0,0 +1,9 @@
'use strict';
const Signal = require('./signal.provider');
const Motion = require('./motion.provider');
module.exports = {
Signal,
Motion
}
+57
Ver Arquivo
@@ -0,0 +1,57 @@
'use strict';
const constants = require('../constants');
const Utils = require('../utils');
module.exports = class Motion {
constructor ({ io }) {
this.io = io;
this.auxData = [];
this.count = 0;
}
capture ({ auxData }) {
if (Utils.signal.isSimulated()) {
this.simulate();
} else {
if (this.hasMotion(auxData)) {
this.auxData = this.amplify(auxData);
this.emit();
}
}
}
hasMotion (auxData) {
return auxData.reduce((a, b) => a + b, 0);
}
amplify (auxData) {
return auxData.map(axis => Math.round(axis));
}
simulate () {
this.count++;
if (this.count === 10) {
this.auxData = [
Math.round(Math.random() * 180),
Math.round(Math.random() * 180),
Math.round(Math.random() * 180)
];
this.count = 0;
this.emit();
}
}
emit () {
this.io.emit(constants.events.motion, {
data: this.auxData
});
}
}
+66
Ver Arquivo
@@ -0,0 +1,66 @@
'use strict';
const EventEmitter = require('events');
const Utils = require('../utils');
const constants = require('../constants');
class SignalEmitter extends EventEmitter {}
module.exports = class Signal {
constructor ({ io }) {
this.io = io;
this.emitter = new SignalEmitter();
this.bufferSize = constants.signal.bufferSize;
this.windowSize = constants.signal.windowSize;
this.sampleRate = constants.signal.sampleRate;
this.signals = [[],[],[],[],[],[],[],[]];
this.sampleNumber = 0;
this.init();
}
init () {
this.io.on('connection', (socket) => {
socket.on(constants.events.filter, (filter) => {
Utils.filter.apply(filter);
});
});
this.setScale();
}
buffer (sample) {
this.sampleNumber++;
this.add(sample);
if (this.sampleNumber === this.bufferSize) {
this.emitter.emit(constants.events.signal, [...this.signals]);
this.window();
}
}
add (sample) {
console.log('sample', sample);
Object.keys(sample.channelData).forEach((channel, i) => {
this.signals[i].push(sample.channelData[channel]);
});
}
window () {
this.signals = this.signals.map((channel) => {
return channel.filter((signal, index) => {
return index > (this.windowSize - 1);
});
});
this.sampleNumber = this.bufferSize - this.windowSize;
}
setScale () {
if (Utils.signal.isSimulated()) {
this.scale = constants.scale.simulated;
} else {
this.scale = constants.scale.global;
}
}
}
+29
Ver Arquivo
@@ -0,0 +1,29 @@
'use strict';
module.exports = {
parseObjectAsArray (obj) {
var array = [];
Object.keys(obj).forEach((key) => {
array.push(obj[key]);
});
return array;
},
/**
* generateTimeline
* @param size
* @param skip
* @param suffix
* @returns {Array.<T>}
*/
generateTimeline (size, skip, suffix) {
return new Array(size)
.fill()
.map((value, index) => index)
.filter((value, index) => index % skip === 0)
.map((value) => (value ? '-' : '') + value + suffix)
.reverse();
}
}
+136
Ver Arquivo
@@ -0,0 +1,136 @@
'use strict';
var Fili = require('fili');
module.exports = {
state: {
BANDPASS: '1-50',
NOTCH: '60',
VERTSCALE: '50',
VERTALGO: 'LOG',
SMOOTH: '0-75',
POLARITY: 'YES',
MAXFREQUENCY: '60'
},
apply (filter) {
if (!filter) return;
let [id, value] = filter.split(':');
this.state[id] = value;
},
process (signal) {
Object.keys(this.state).forEach((key) => {
let filter = key.toLowerCase();
if (filter in this && typeof this[filter] === 'function') {
// @TODO: apply all filters dynamically
//signal = this[filter](signal);
}
});
signal = this.notch(signal);
return signal;
},
highpass (signal) {
var iirCalculator = new Fili.CalcCascades();
var hpFilterCoeffs = iirCalculator.highpass({
order: 4, // cascade 4 biquad filters (max: 12)
characteristic: 'butterworth',
Fs: 250, // sampling frequency
Fc: 1,
gain: 0, // gain for peak, lowshelf and highshelf
preGain: false // adds one constant multiplication for highpass and lowpass
// k = (1 + cos(omega)) * 0.5 / k = 1 with preGain == false
});
var hpFilter = new Fili.IirFilter(hpFilterCoeffs);
return hpFilter.multiStep(signal);
},
notch (signal) {
if (this.state.NOTCH === 'NONE') return signal;
var notchValue = parseInt(this.state.NOTCH);
var iirCalculator = new Fili.CalcCascades();
var notchFilterCoeffs = iirCalculator.bandstop({
order: 2, // cascade 3 biquad filters (max: 12)
characteristic: 'butterworth',
Fs: 250, // sampling frequency
Fc: notchValue,
F1: notchValue - 1,
F2: notchValue + 1,
gain: 0, // gain for peak, lowshelf and highshelf
preGain: false // adds one constant multiplication for highpass and lowpass
// k = (1 + cos(omega)) * 0.5 / k = 1 with preGain == false
});
var notchFilter = new Fili.IirFilter(notchFilterCoeffs);
return notchFilter.multiStep(signal);
},
bandpass (signal) {
// @TODO: Finish bandpass filter
return filter;
var iirCalculator = new Fili.CalcCascades();
var hpFilterCoeffs = iirCalculator.highpass({
order: 3, // cascade 3 biquad filters (max: 12)
characteristic: 'butterworth',
Fs: sampleRate, // sampling frequency
Fc: 1,
gain: 0, // gain for peak, lowshelf and highshelf
preGain: false // adds one constant multiplication for highpass and lowpass
// k = (1 + cos(omega)) * 0.5 / k = 1 with preGain == false
});
var hpFilter = new Fili.IirFilter(hpFilterCoeffs);
var lpFilterCoeffs = iirCalculator.lowpass({
order: 3, // cascade 3 biquad filters (max: 12)
characteristic: 'butterworth',
Fs: sampleRate, // sampling frequency
Fc: 50,
gain: 0, // gain for peak, lowshelf and highshelf
preGain: false // adds one constant multiplication for highpass and lowpass
// k = (1 + cos(omega)) * 0.5 / k = 1 with preGain == false
});
var lpFilter = new Fili.IirFilter(lpFilterCoeffs);
// @TODO: get from state which filter to use, then return it based on state settings
},
filterBand (spectrums, labels, range) {
if (!spectrums ) return console.log('Please provide spectrums');
spectrums = spectrums.map(function (channel) {
return channel.filter(function (spectrum, index) {
return labels[index] >= range[0] && labels[index] <= range[1];
});
});
spectrums = [spectrums.map(function (channel) {
if (channel.length) {
return channel.reduce(function (a, b) {
return a + b;
}) / channel.length;
} else return channel;
})];
return {
spectrums: spectrums,
labels: labels
}
}
}
+11
Ver Arquivo
@@ -0,0 +1,11 @@
'use strict';
const data = require('./data.util');
const filter = require('./filter.util');
const signal = require('./signal.util');
module.exports = {
data,
filter,
signal
}
+27
Ver Arquivo
@@ -0,0 +1,27 @@
'use strict';
var argv = require('yargs').argv;
const constants = require('../constants');
module.exports = {
voltsToMicrovolts (volts, log) {
if (!Array.isArray(volts)) {
volts = [volts];
}
return volts.map((volt) => {
return log ? Math.log10(Math.pow(10, 6) * volt) : Math.pow(10, 6) * volt;
});
},
offsetForGrid (amplitude, channelNumber, channelAmount = 8, scale = 1.5) {
let scaledAmplitude = amplitude * Math.pow(10, scale);
let offset = 2 * (channelAmount - channelNumber) - 1;
return parseFloat(scaledAmplitude + offset);
},
isSimulated () {
return !!(argv._[0] && argv._[0] === constants.connector.simulateFlag);
}
}
+6 -1
Ver Arquivo
@@ -4,9 +4,12 @@
/** Map relative paths to URLs. */
const map: any = {
'smoothie': 'vendor/smoothie/smoothie.js',
'chartjs': 'vendor/chart.js/dist/Chart.bundle.js',
'ng2-charts': 'vendor/ng2-charts/bundles/ng2-charts.js',
'socket.io-client': 'vendor/socket.io-client/socket.io.js',
'chroma-js': 'vendor/chroma-js/chroma.js'
'chroma-js': 'vendor/chroma-js/chroma.js',
'plotly': 'vendor/plotly.js/dist/plotly.js',
'brainbrowser': 'vendor/brainbrowser/build/brainbrowser-2.3.0/brainbrowser.surface-viewer.min.js'
};
/** User packages configuration. */
@@ -40,6 +43,8 @@ const barrels: string[] = [
'app/frequency-bands',
'app/frequency-band',
'app/topo',
'app/filters',
'app/motion',
/** @cli-barrel */
];
-302
Ver Arquivo
@@ -1,302 +0,0 @@
var path = require('path');
var argv = require('yargs').argv;
var OpenBCIBoard = require('openbci-sdk');
var dsp = require('dsp.js');
var io = require('socket.io')(process.env.app_port || 8080);
var topogrid = require('topogrid');
var jStat = require('jstat').jStat;
var Fili = require('fili');
var globalScale = 1.5;
// Sockets
io.on('connection', function(socket){
console.log('A user connected');
});
// OpenBCI
var board = new OpenBCIBoard.OpenBCIBoard({
verbose: true
});
board.autoFindOpenBCIBoard()
.then(onBoardFind)
.catch(function () {
if (!!(argv._[0] && argv._[0] === 'simulate')) {
globalScale = 4;
board.connect(OpenBCIBoard.OpenBCIConstants.OBCISimulatorPortName)
.then(onBoardConnect);
}
});
// Board find handler
function onBoardFind (portName) {if (portName) {
console.log('board found', portName);
board.connect(portName)
.then(onBoardConnect);
}
}
// Board connect handler
function onBoardConnect () {
board.on('ready', onBoardReady);
}
// Board ready handler
function onBoardReady () {
board.streamStart();
board.on('sample', onSample);
}
var bins = 128; // Approx .5 second
var bufferSize = 128;
var windowRefreshRate = 8;
var windowSize = bins / windowRefreshRate;
var sampleRate = board.sampleRate();
var sampleInterval = (1 / sampleRate) * 1000; // in milliseconds (4)
var sampleNumber = 0;
var signals = [[],[],[],[],[],[],[],[]];
var timeSeriesWindow = 5; // in seconds
var timeSeriesRate = 10; // emits time series every 10 samples (adds 40 ms delay because this * sampleInterval = 40
var seriesNumber = 0;
var timeline = generateTimeline(20, 2, 's');
var timeSeries = new Array(8).fill([]); // 8 channels
timeSeries = timeSeries.map(function () {
return new Array((sampleRate * timeSeriesWindow)).fill(0).map(function (amplitude, channelNumber) {
return offsetForGrid(amplitude, channelNumber);
}); // / timeSeriesRate
});
// the parameters for the grid [x,y,z] where x is the min of the grid, y is the
// max of the grid and z is the number of points
var grid_params = [0,10,11];
var pos_x = [3,7,2,8,0,10,3,7]; // x coordinates of the data
var pos_y = [0,0,3,3,8,8,10,10]; // y coordinates of the data
// var data = [10,0,0,0,0,0,-10,30,25]; // the data values
// Instance of a filter coefficient calculator
var iirCalculator = new Fili.CalcCascades();
// calculate filter coefficients
var notchFilterCoeffs = iirCalculator.bandstop({
order: 2, // cascade 3 biquad filters (max: 12)
characteristic: 'butterworth',
Fs: sampleRate, // sampling frequency
Fc: 60,
F1: 59,
F2: 61,
gain: 0, // gain for peak, lowshelf and highshelf
preGain: false // adds one constant multiplication for highpass and lowpass
// k = (1 + cos(omega)) * 0.5 / k = 1 with preGain == false
});
// create a filter instance from the calculated coeffs
var notchFilter = new Fili.IirFilter(notchFilterCoeffs);
var hpFilterCoeffs = iirCalculator.highpass({
order: 3, // cascade 3 biquad filters (max: 12)
characteristic: 'butterworth',
Fs: sampleRate, // sampling frequency
Fc: 1,
gain: 0, // gain for peak, lowshelf and highshelf
preGain: false // adds one constant multiplication for highpass and lowpass
// k = (1 + cos(omega)) * 0.5 / k = 1 with preGain == false
});
var hpFilter = new Fili.IirFilter(hpFilterCoeffs);
var lpFilterCoeffs = iirCalculator.lowpass({
order: 3, // cascade 3 biquad filters (max: 12)
characteristic: 'butterworth',
Fs: sampleRate, // sampling frequency
Fc: 50,
gain: 0, // gain for peak, lowshelf and highshelf
preGain: false // adds one constant multiplication for highpass and lowpass
// k = (1 + cos(omega)) * 0.5 / k = 1 with preGain == false
});
var lpFilter = new Fili.IirFilter(lpFilterCoeffs);
function onSample (sample) {
sampleNumber++;
console.log('sample', sample);
Object.keys(sample.channelData).forEach(function (channel, i) {
signals[i].push(sample.channelData[channel]);
});
if (sampleNumber === bins) {
var spectrums = [[],[],[],[],[],[],[],[]];
signals.forEach(function (signal, index) {
signal = notchFilter.multiStep(signal);
var fft = new dsp.FFT(bufferSize, sampleRate);
fft.forward(signal);
spectrums[index] = parseObjectAsArray(fft.spectrum);
spectrums[index] = voltsToMicrovolts(spectrums[index], true);
});
var labels = new Array(bins / 2).fill()
// Apply scaler
.map(function (label, index) {
return Math.ceil(index * (sampleRate / bins));
});
var spectrumsByBand = [];
var bands = {
delta: [1, 3],
theta: [4, 8],
alpha: [8, 12],
beta: [13, 30],
gamma: [30, 100]
};
for (band in bands) {
spectrumsByBand[band] = filterBand(spectrums, labels, bands[band])
}
// Skip every 4, add unit
labels = labels.map(function (label, index, labels) {
return (index % 4 === 0 || index === (labels.length - 1)) ? label + ' Hz' : '';
});
io.emit('bci:fft', {
data: spectrums,
theta: spectrumsByBand.theta.spectrums,
delta: spectrumsByBand.delta.spectrums,
alpha: spectrumsByBand.alpha.spectrums,
beta: spectrumsByBand.beta.spectrums,
gamma: spectrumsByBand.gamma.spectrums,
labels: labels
});
signals = signals.map(function (channel) {
return channel.filter(function (signal, index) {
return index > (windowSize - 1);
});
});
var meanSpectrum = spectrums.map(function(channel){
return jStat.mean(channel);
});
sampleNumber = bins - windowSize;
}
// Time Series
seriesNumber++;
timeSeries.forEach(function (channel, index) {
channel.push(
offsetForGrid(sample.channelData[index], index)
);
channel.shift();
});
if (seriesNumber === timeSeriesRate) {
var amplitudes = signals.map(function (channel) {
return (Math.round(voltsToMicrovolts(channel[channel.length - 1])[0])) + ' uV';
});
io.emit('bci:time', {
data: timeSeries,
amplitudes: amplitudes,
timeline: timeline
});
seriesNumber = 0;
grid = topogrid.create(pos_x,pos_y,sample.channelData,grid_params);
var grid_flat = [].concat.apply([], grid);
io.emit('bci:topo', {
data: grid_flat
});
}
}
// @TODO: initial dataset is returning messed up values
function offsetForGrid (amplitude, channelNumber) {
var scaledAmplitude = amplitude * Math.pow(10, globalScale);
var offset = 2 * (timeSeries.length - channelNumber) - 1;
return parseFloat(scaledAmplitude + offset);
}
function voltsToMicrovolts (volts, log) {
if (!Array.isArray(volts)) volts = [volts];
return volts.map(function (volt) {
return log ? Math.log10(Math.pow(10, 6) * volt) : Math.pow(10, 6) * volt;
});
}
function parseObjectAsArray (obj) {
var array = [];
Object.keys(obj).forEach(function (key) {
array.push(obj[key]);
});
return array;
}
function filterBand(spectrums, labels, range) {
if (!spectrums ) return console.log('Please provide spectrums');
spectrums = spectrums.map(function (channel) {
return channel.filter(function (spectrum, index) {
return labels[index] >= range[0] && labels[index] <= range[1];
});
});
spectrums = [spectrums.map(function (channel) {
if (channel.length) {
return channel.reduce(function (a, b) {
return a + b;
}) / channel.length;
} else return channel;
})];
return {
spectrums: spectrums,
labels: labels
}
}
/**
* generateTimeline
* @param size
* @param skip
* @param suffix
* @returns {Array.<T>}
*/
function generateTimeline (size, skip, suffix) {
return new Array(size)
.fill()
.map(function (value, index) {
return index;
})
.filter(function (value, index) {
return index % skip === 0;
})
.map(function (value) {
return (value ? '-' : '') + value + suffix;
})
.reverse();
}
/**
* disconnectBoard
*/
function disconnectBoard () {
board.streamStop()
.then(function () {
board.disconnect().then(function () {
console.log('board disconnected');
process.exit();
});
});
}
process.on('SIGINT', disconnectBoard);