Commit e599771c authored by Daria Zenkova's avatar Daria Zenkova

fixing support of colour and size as options for ggplot

parent 13d4dca9
......@@ -67,7 +67,8 @@ module.exports = function (grunt) {
'js/jquery.event.drag-2.2.js',
'js/clipboard.min.js', 'js/slick.min.js',
'js/js.cookie.js', 'js/d3.layout.cloud.js',
'js/long.js', 'js/bytebuffer.js', 'js/protobuf.js']
'js/long.js', 'js/bytebuffer.js', 'js/protobuf.js',
'js/opencpu-0.5.js', 'js/FileSaver.min.js']
},
morpheus: {
nonull: true,
......
......@@ -10,6 +10,10 @@
<title>Morpheus</title>
<link rel="stylesheet" href="css/morpheus-latest.min.css">
<script type="text/javascript" src="js/morpheus-external-latest.min.js"></script>
<script>
ocpu.seturl("http://localhost:7963/ocpu/library/morpheusR/R");
</script>
<script src="js/morpheus-latest.min.js"></script>
<script src="js/jsme/jsme.nocache.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto"
......
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs=saveAs||function(view){"use strict";if(typeof navigator!=="undefined"&&/MSIE [1-9]\./.test(navigator.userAgent)){return}var doc=view.document,get_URL=function(){return view.URL||view.webkitURL||view},save_link=doc.createElementNS("http://www.w3.org/1999/xhtml","a"),can_use_save_link="download"in save_link,click=function(node){var event=new MouseEvent("click");node.dispatchEvent(event)},is_safari=/Version\/[\d\.]+.*Safari/.test(navigator.userAgent),webkit_req_fs=view.webkitRequestFileSystem,req_fs=view.requestFileSystem||webkit_req_fs||view.mozRequestFileSystem,throw_outside=function(ex){(view.setImmediate||view.setTimeout)(function(){throw ex},0)},force_saveable_type="application/octet-stream",fs_min_size=0,arbitrary_revoke_timeout=500,revoke=function(file){var revoker=function(){if(typeof file==="string"){get_URL().revokeObjectURL(file)}else{file.remove()}};if(view.chrome){revoker()}else{setTimeout(revoker,arbitrary_revoke_timeout)}},dispatch=function(filesaver,event_types,event){event_types=[].concat(event_types);var i=event_types.length;while(i--){var listener=filesaver["on"+event_types[i]];if(typeof listener==="function"){try{listener.call(filesaver,event||filesaver)}catch(ex){throw_outside(ex)}}}},auto_bom=function(blob){if(/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)){return new Blob(["\ufeff",blob],{type:blob.type})}return blob},FileSaver=function(blob,name,no_auto_bom){if(!no_auto_bom){blob=auto_bom(blob)}var filesaver=this,type=blob.type,blob_changed=false,object_url,target_view,dispatch_all=function(){dispatch(filesaver,"writestart progress write writeend".split(" "))},fs_error=function(){if(target_view&&is_safari&&typeof FileReader!=="undefined"){var reader=new FileReader;reader.onloadend=function(){var base64Data=reader.result;target_view.location.href="data:attachment/file"+base64Data.slice(base64Data.search(/[,;]/));filesaver.readyState=filesaver.DONE;dispatch_all()};reader.readAsDataURL(blob);filesaver.readyState=filesaver.INIT;return}if(blob_changed||!object_url){object_url=get_URL().createObjectURL(blob)}if(target_view){target_view.location.href=object_url}else{var new_tab=view.open(object_url,"_blank");if(new_tab==undefined&&is_safari){view.location.href=object_url}}filesaver.readyState=filesaver.DONE;dispatch_all();revoke(object_url)},abortable=function(func){return function(){if(filesaver.readyState!==filesaver.DONE){return func.apply(this,arguments)}}},create_if_not_found={create:true,exclusive:false},slice;filesaver.readyState=filesaver.INIT;if(!name){name="download"}if(can_use_save_link){object_url=get_URL().createObjectURL(blob);setTimeout(function(){save_link.href=object_url;save_link.download=name;click(save_link);dispatch_all();revoke(object_url);filesaver.readyState=filesaver.DONE});return}if(view.chrome&&type&&type!==force_saveable_type){slice=blob.slice||blob.webkitSlice;blob=slice.call(blob,0,blob.size,force_saveable_type);blob_changed=true}if(webkit_req_fs&&name!=="download"){name+=".download"}if(type===force_saveable_type||webkit_req_fs){target_view=view}if(!req_fs){fs_error();return}fs_min_size+=blob.size;req_fs(view.TEMPORARY,fs_min_size,abortable(function(fs){fs.root.getDirectory("saved",create_if_not_found,abortable(function(dir){var save=function(){dir.getFile(name,create_if_not_found,abortable(function(file){file.createWriter(abortable(function(writer){writer.onwriteend=function(event){target_view.location.href=file.toURL();filesaver.readyState=filesaver.DONE;dispatch(filesaver,"writeend",event);revoke(file)};writer.onerror=function(){var error=writer.error;if(error.code!==error.ABORT_ERR){fs_error()}};"writestart progress write abort".split(" ").forEach(function(event){writer["on"+event]=filesaver["on"+event]});writer.write(blob);filesaver.abort=function(){writer.abort();filesaver.readyState=filesaver.DONE};filesaver.readyState=filesaver.WRITING}),fs_error)}),fs_error)};dir.getFile(name,{create:false},abortable(function(file){file.remove();save()}),abortable(function(ex){if(ex.code===ex.NOT_FOUND_ERR){save()}else{fs_error()}}))}),fs_error)}),fs_error)},FS_proto=FileSaver.prototype,saveAs=function(blob,name,no_auto_bom){return new FileSaver(blob,name,no_auto_bom)};if(typeof navigator!=="undefined"&&navigator.msSaveOrOpenBlob){return function(blob,name,no_auto_bom){if(!no_auto_bom){blob=auto_bom(blob)}return navigator.msSaveOrOpenBlob(blob,name||"download")}}FS_proto.abort=function(){var filesaver=this;filesaver.readyState=filesaver.DONE;dispatch(filesaver,"abort")};FS_proto.readyState=FS_proto.INIT=0;FS_proto.WRITING=1;FS_proto.DONE=2;FS_proto.error=FS_proto.onwritestart=FS_proto.onprogress=FS_proto.onwrite=FS_proto.onabort=FS_proto.onerror=FS_proto.onwriteend=null;return saveAs}(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||this.content);if(typeof module!=="undefined"&&module.exports){module.exports.saveAs=saveAs}else if(typeof define!=="undefined"&&define!==null&&define.amd!=null){define([],function(){return saveAs})}
var saveAs=saveAs||function(e){"use strict";if(typeof e==="undefined"||typeof navigator!=="undefined"&&/MSIE [1-9]\./.test(navigator.userAgent)){return}var t=e.document,n=function(){return e.URL||e.webkitURL||e},r=t.createElementNS("http://www.w3.org/1999/xhtml","a"),o="download"in r,i=function(e){var t=new MouseEvent("click");e.dispatchEvent(t)},a=/constructor/i.test(e.HTMLElement),f=/CriOS\/[\d]+/.test(navigator.userAgent),u=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},d="application/octet-stream",s=1e3*40,c=function(e){var t=function(){if(typeof e==="string"){n().revokeObjectURL(e)}else{e.remove()}};setTimeout(t,s)},l=function(e,t,n){t=[].concat(t);var r=t.length;while(r--){var o=e["on"+t[r]];if(typeof o==="function"){try{o.call(e,n||e)}catch(i){u(i)}}}},p=function(e){if(/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)){return new Blob([String.fromCharCode(65279),e],{type:e.type})}return e},v=function(t,u,s){if(!s){t=p(t)}var v=this,w=t.type,m=w===d,y,h=function(){l(v,"writestart progress write writeend".split(" "))},S=function(){if((f||m&&a)&&e.FileReader){var r=new FileReader;r.onloadend=function(){var t=f?r.result:r.result.replace(/^data:[^;]*;/,"data:attachment/file;");var n=e.open(t,"_blank");if(!n)e.location.href=t;t=undefined;v.readyState=v.DONE;h()};r.readAsDataURL(t);v.readyState=v.INIT;return}if(!y){y=n().createObjectURL(t)}if(m){e.location.href=y}else{var o=e.open(y,"_blank");if(!o){e.location.href=y}}v.readyState=v.DONE;h();c(y)};v.readyState=v.INIT;if(o){y=n().createObjectURL(t);setTimeout(function(){r.href=y;r.download=u;i(r);h();c(y);v.readyState=v.DONE});return}S()},w=v.prototype,m=function(e,t,n){return new v(e,t||e.name||"download",n)};if(typeof navigator!=="undefined"&&navigator.msSaveOrOpenBlob){return function(e,t,n){t=t||e.name||"download";if(!n){e=p(e)}return navigator.msSaveOrOpenBlob(e,t)}}w.abort=function(){};w.readyState=w.INIT=0;w.WRITING=1;w.DONE=2;w.error=w.onwritestart=w.onprogress=w.onwrite=w.onabort=w.onerror=w.onwriteend=null;return m}(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||this.content);if(typeof module!=="undefined"&&module.exports){module.exports.saveAs=saveAs}else if(typeof define!=="undefined"&&define!==null&&define.amd!==null){define([],function(){return saveAs})}
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
/**
* Javascript client library for OpenCPU
* Version 0.5.0
* Depends: jQuery
* Requires HTML5 FormData support for file uploads
* http://github.com/jeroenooms/opencpu.js
*
* Include this file in your apps and packages.
* You only need to use ocpu.seturl if this page is hosted outside of the OpenCPU package. For example:
*
* ocpu.seturl("../R") //default, use for apps
* ocpu.seturl("//public.opencpu.org/ocpu/library/mypackage/R") //CORS
* ocpu.seturl("/ocpu/library/mypackage/R") //hardcode path
* ocpu.seturl("https://user:secret/my.server.com/ocpu/library/pkg/R") // basic auth
*/
//Warning for the newbies
if(!window.jQuery) {
alert("Could not find jQuery! The HTML must include jquery.js before opencpu.js!")
}
(function ( $ ) {
//global variable
var r_cors = false;
var r_path = document.createElement('a');
r_path.href = "../R";
//new Session()
function Session(loc, key, txt){
this.loc = loc;
this.key = key;
this.txt = txt;
this.output = txt.split(/\r\n|\r|\n/g);
this.getKey = function(){
return key;
};
this.getLoc = function(){
return loc;
};
this.getFileURL = function(path){
var new_url = document.createElement('a');
new_url.href = this.getLoc() + "files/" + path;
new_url.username = r_path.username;
new_url.password = r_path.password
return new_url.href;
};
this.getFile = function(path, success){
var url = this.getFileURL(path);
return $.get(url, success);
};
this.getObject = function(name, data, success){
//in case of no arguments
name = name || ".val";
//first arg is a function
if(name instanceof Function){
//pass on to second arg
success = name;
name = ".val";
}
var url = this.getLoc() + "R/" + name;
return $.get(url, data, success);
};
this.getGraphics = function (index, data, success) {
index = index || 1;
var url = this.getLoc() + "graphics/" + index;
return $.get(url, data, success);
};
this.getStdout = function(success){
var url = this.getLoc() + "stdout/text";
return $.get(url, success);
};
this.getConsole = function(success){
var url = this.getLoc() + "console/text";
return $.get(url, success);
};
}
//for POSTing raw code snippets
//new Snippet("rnorm(100)")
function Snippet(code){
this.code = code || "NULL";
this.getCode = function(){
return code;
};
}
//for POSTing files
//new Upload($('#file')[0].files)
function Upload(file){
if(file instanceof File){
this.file = file;
} else if(file instanceof FileList){
this.file = file[0];
} else if (file.files instanceof FileList){
this.file = file.files[0];
} else if (file.length > 0 && file[0].files instanceof FileList){
this.file = file[0].files[0];
} else {
throw 'invalid new Upload(file). Argument file must be a HTML <input type="file"></input>';
}
this.getFile = function(){
return file;
};
}
function stringify(x){
if(x instanceof Session){
return x.getKey();
} else if(x instanceof Snippet){
return x.getCode();
} else if(x instanceof Upload){
return x.getFile();
} else if(x instanceof File){
return x;
} else if(x instanceof FileList){
return x[0];
} else if(x && x.files instanceof FileList){
return x.files[0];
} else if(x && x.length && x[0].files instanceof FileList){
return x[0].files[0];
} else {
return JSON.stringify(x);
}
}
//low level call
function r_fun_ajax(fun, settings, handler){
//validate input
if(!fun) throw "r_fun_call called without fun";
settings = settings || {};
handler = handler || function(){};
//set global settings
settings.url = settings.url || (r_path.href + "/" + fun);
settings.type = settings.type || "POST";
settings.data = settings.data || {};
settings.dataType = settings.dataType || "text";
//ajax call
var jqxhr = $.ajax(settings).done(function(){
var loc = jqxhr.getResponseHeader('Location') || console.log("Location response header missing.");
var key = jqxhr.getResponseHeader('X-ocpu-session') || console.log("X-ocpu-session response header missing.");
var txt = jqxhr.responseText;
//in case of cors we translate relative paths to the target domain
if(r_cors && loc.match("^/[^/]")){
loc = r_path.protocol + "//" + r_path.host + loc;
}
handler(new Session(loc, key, txt));
}).fail(function(){
console.log("OpenCPU error HTTP " + jqxhr.status + "\n" + jqxhr.responseText);
});
//function chaining
return jqxhr;
}
//call a function using protobuf arguments
function r_fun_call_proto(fun, args, handler) {
return r_fun_ajax(fun, {
data : new Uint8Array(args.toArrayBuffer()),
contentType : 'application/x-protobuf',
processData : false
}, handler);
}
//call a function using json arguments
function r_fun_call_json(fun, args, handler) {
return r_fun_ajax(fun, {
data: JSON.stringify(args || {}),
contentType: 'application/json'
}, handler);
}
//call function using url encoding
//needs to wrap arguments in quotes, etc
function r_fun_call_urlencoded(fun, args, handler){
var data = {};
$.each(args, function(key, val){
data[key] = stringify(val);
});
return r_fun_ajax(fun, {
data: $.param(data)
}, handler);
}
//call a function using multipart/form-data
//use for file uploads. Requires HTML5
function r_fun_call_multipart(fun, args, handler){
testhtml5();
var formdata = new FormData();
$.each(args, function(key, value) {
formdata.append(key, stringify(value));
});
return r_fun_ajax(fun, {
data: formdata,
cache: false,
contentType: false,
processData: false
}, handler);
}
//Automatically determines type based on argument classes.
function r_fun_call(fun, args, handler, useProtobuf){
useProtobuf = useProtobuf || false;
args = args || {};
var hasfiles = false;
var hascode = false;
//find argument types
$.each(args, function(key, value){
if(value instanceof File || value instanceof Upload || value instanceof FileList){
hasfiles = true;
} else if (value instanceof Snippet || value instanceof Session){
hascode = true;
}
});
//determine type
if(hasfiles){
return r_fun_call_multipart(fun, args, handler);
} else if(hascode){
return r_fun_call_urlencoded(fun, args, handler);
} else if (useProtobuf) {
return r_fun_call_proto(fun, args, handler);
} else {
return r_fun_call_json(fun, args, handler);
}
}
//call a function and return JSON
function rpc(fun, args, handler, useProtobuf){
useProtobuf = useProtobuf || false;
return r_fun_call(fun, args, function(session){
session.getObject(function(data){
if(handler) handler(data);
}).fail(function(){
console.log("Failed to get JSON response for " + session.getLoc());
});
}, useProtobuf);
}
//plotting widget
//to be called on an (empty) div.
$.fn.rplot = function(fun, args, cb) {
var targetdiv = this;
var myplot = initplot(targetdiv);
//reset state
myplot.setlocation();
myplot.spinner.show();
// call the function
return r_fun_call(fun, args, function(tmp) {
myplot.setlocation(tmp.getLoc());
//call success handler as well
if(cb) cb(tmp);
}).always(function(){
myplot.spinner.hide();
});
};
$.fn.graphic = function(session, n){
initplot(this).setlocation(session.getLoc(), n || "last");
}
function initplot(targetdiv){
if(targetdiv.data("ocpuplot")){
return targetdiv.data("ocpuplot");
}
var ocpuplot = function(){
//local variables
var Location;
var n = "last";
var pngwidth;
var pngheight;
var plotdiv = $('<div />').attr({
style: "width: 100%; height:100%; min-width: 100px; min-height: 100px; position:relative; background-repeat:no-repeat; background-size: 100% 100%;"
}).appendTo(targetdiv).css("background-image", "none");
var spinner = $('<span />').attr({
style : "position: absolute; top: 20px; left: 20px; z-index:1000; font-family: monospace;"
}).text("loading...").appendTo(plotdiv).hide();
var pdf = $('<a />').attr({
target: "_blank",
style: "position: absolute; top: 10px; right: 10px; z-index:1000; text-decoration:underline; font-family: monospace;"
}).text("pdf").appendTo(plotdiv);
var svg = $('<a />').attr({
target: "_blank",
style: "position: absolute; top: 30px; right: 10px; z-index:1000; text-decoration:underline; font-family: monospace;"
}).text("svg").appendTo(plotdiv);
var png = $('<a />').attr({
target: "_blank",
style: "position: absolute; top: 50px; right: 10px; z-index:1000; text-decoration:underline; font-family: monospace;"
}).text("png").appendTo(plotdiv);
function updatepng(){
if(!Location) return;
pngwidth = plotdiv.width();
pngheight = plotdiv.height();
plotdiv.css("background-image", "url(" + Location + "graphics/" + n + "/png?width=" + pngwidth + "&height=" + pngheight + ")");
}
function setlocation(newloc, newn){
n = newn || n;
Location = newloc;
if(!Location){
pdf.hide();
svg.hide();
png.hide();
plotdiv.css("background-image", "");
} else {
pdf.attr("href", Location + "graphics/" + n + "/pdf?width=11.69&height=8.27&paper=a4r").show();
svg.attr("href", Location + "graphics/" + n + "/svg?width=11&height=6").show();
png.attr("href", Location + "graphics/" + n + "/png?width=800&height=600").show();
updatepng();
}
}
// function to update the png image
var onresize = debounce(function(e) {
if(pngwidth == plotdiv.width() && pngheight == plotdiv.height()){
return;
}
if(plotdiv.is(":visible")){
updatepng();
}
}, 500);
// register update handlers
plotdiv.on("resize", onresize);
$(window).on("resize", onresize);
//return objects
return {
setlocation: setlocation,
spinner : spinner
};
}();
targetdiv.data("ocpuplot", ocpuplot);
return ocpuplot;
}
// from understore.js
function debounce(func, wait, immediate) {
var result;
var timeout = null;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate)
result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow)
result = func.apply(context, args);
return result;
};
}
function testhtml5(){
if( window.FormData === undefined ) {
alert("Uploading of files requires HTML5. It looks like you are using an outdated browser that does not support this. Please install Firefox, Chrome or Internet Explorer 10+");
throw "HTML5 required.";
}
}
//export
window.ocpu = window.ocpu || {};
var ocpu = window.ocpu;
//global settings
function seturl(newpath){
if(!newpath.match("/R$")){
alert("ERROR! Trying to set R url to: " + newpath +". Path to an OpenCPU R package must end with '/R'");
} else {
r_path = document.createElement('a');
r_path.href = newpath;
r_path.href = r_path.href; //IE needs this
if(location.protocol != r_path.protocol || location.host != r_path.host){
r_cors = true;
if (!('withCredentials' in new XMLHttpRequest())) {
alert("This browser does not support CORS. Try using Firefox or Chrome.");
} else if(r_path.username && r_path.password) {
//should only do this for calls to opencpu maybe
var regex = new RegExp(r_path.host);
$.ajaxSetup({
beforeSend: function(xhr, settings) {
//only use auth for ajax requests to ocpu
if(regex.test(settings.url)){
//settings.username = r_path.username;
//settings.password = r_path.password;
/* take out user:pass from target url */
var target = document.createElement('a');
target.href = settings.url;
settings.url = target.protocol + "//" + target.host + target.pathname
/* set basic auth header */
settings.xhrFields = settings.xhrFields || {};
settings.xhrFields.withCredentials = true;
settings.crossDomain = true;
xhr.setRequestHeader("Authorization", "Basic " + btoa(r_path.username + ":" + r_path.password));
/* debug */
console.log("Authenticated request to: " + settings.url + " (" + r_path.username + ", " + r_path.password + ")")
}
}
});
}
}
if(location.protocol == "https:" && r_path.protocol != "https:"){
alert("Page is hosted on HTTPS but using a (non-SSL) HTTP OpenCPU server. This is insecure and most browsers will not allow this.")
}
if(r_cors){
console.log("Setting path to CORS server " + r_path.href);
} else {
console.log("Setting path to local (non-CORS) server " + r_path.href);
}
//CORS disallows redirects.
return $.get(r_path.href + "/", function(resdata){
//console.log("Path updated. Available objects/functions:\n" + resdata);
}).fail(function(xhr, textStatus, errorThrown){
alert("Connection to OpenCPU failed:\n" + textStatus + "\n" + xhr.responseText + "\n" + errorThrown);
});
}
}
//exported functions
ocpu.call = r_fun_call;
ocpu.rpc = rpc;
ocpu.seturl = seturl;
ocpu.mycall = r_fun_ajax;
//exported constructors
ocpu.Snippet = Snippet;
ocpu.Upload = Upload;
//for innernetz exploder
if (typeof console == "undefined") {
this.console = {log: function() {}};
}
}( jQuery ));
......@@ -334,6 +334,7 @@ morpheus.TcgaUtil.getDataset = function (options) {
f(datasetToReturn);
});
}
datasetToReturn.setESSession();
returnDeferred.resolve(datasetToReturn);
});
return returnDeferred;
......
......@@ -160,6 +160,33 @@ morpheus.Dataset.prototype = {
this.seriesArrays.push(options.array != null ? options.array
: morpheus.Dataset.createArray(options));
return this.seriesNames.length - 1;
},
setESSession : function () {
var _this = this;
if (this.esSession != null) {
return this.esSession;
}
else {
var protoMessage = morpheus.DatasetUtil.toProtoMessage(this);
var blob = new Blob(new Uint8Array(protoMessage), {type: "application/octet-stream"});
saveAs(blob, "test.bin");
var req = ocpu.call("createES", protoMessage, function (session) {
console.log(session);
_this.esSession = session;
}, true);
req.fail(function () {
alert("failed to create ExpressionSet of dataset");
})
}
},
getESSession : function () {
if (this.esSession == null) {
this.setESSession();
}
return this.esSession;
}
};
morpheus.Util.extend(morpheus.Dataset, morpheus.AbstractDataset);
\ No newline at end of file
......@@ -805,3 +805,118 @@ morpheus.DatasetUtil.getNonEmptyRows = function (dataset) {
}
return rowsToKeep;
};
morpheus.DatasetUtil.getContentArray = function (dataset) {
var array = [];
var nr = dataset.rows;
var nc = dataset.columns;
for (var i = 0; i < nr; i++) {
for (var j = 0; j < nc; j++) {
array.push(dataset.getValue(i, j));
}
}
return array;
};
morpheus.DatasetUtil.getMetadataArray = function (dataset) {
var pDataArray = [];
var participantID = [];
var labelDescription = [];
var columnMeta = dataset.getColumnMetadata();
var n = columnMeta.getMetadataCount();
var m = dataset.columns;
for (var i = 0; i < n; i++) {
var vecI = columnMeta.get(i);
if (vecI.getName() == "participant_id") {
for (var j = 0; j < m; j++) {
participantID.push({
strval : vecI.getValue(j),
isNA : false
});
}
}
else {
for (j = 0; j < m; j++) {
pDataArray.push({
strval : vecI.getValue(j).toString(),
isNA : false
});
}
labelDescription.push({
strval : vecI.getName(),
isNA : false
});
}
}
var rowMeta = dataset.getRowMetadata();
var rowNames = [];
var rowNamesVec = rowMeta.getByName("id");
for (j = 0; j < dataset.rows; j++) {
rowNames.push({
strval : rowNamesVec.getValue(j),
isNA : false
})
}
return {pdata : pDataArray, participants : participantID, labels : labelDescription, rownames : rowNames};
};
morpheus.DatasetUtil.toProtoMessage = function (dataset) {
var array = morpheus.DatasetUtil.getContentArray(dataset);
var meta = morpheus.DatasetUtil.getMetadataArray(dataset);
var messageJSON = {
rclass : "LIST",
rexpValue : [{
rclass : "REAL",
realValue : array,
attrName : "dim",
attrValue : {
rclass : "INTEGER",
intValue : [dataset.rows, dataset.columns]
}
}, {
rclass : "STRING",
stringValue : meta.pdata,
attrName : "dim",
attrValue : {
rclass : "INTEGER",
intValue : [dataset.getColumnMetadata().getMetadataCount() - 1, dataset.columns]
}
}, {
rclass : "STRING",
stringValue : meta.labels
}, {
rclass : "STRING",
stringValue : meta.participants
}, {
rclass : "STRING",
stringValue : meta.rownames
}],
attrName : "names",
attrValue : {
rclass : "STRING",
stringValue : [{
strval : "data",
isNA : false
}, {
strval : "pData",
isNA : false
}, {
strval : "labelDescription",
isNA : false
}, {
strval : "colNames",
isNA : false
}, {
strval : "rowNames",
isNA : false
}]
}
};
ProtoBuf = dcodeIO.ProtoBuf;
var builder = ProtoBuf.protoFromFile("./message.proto"),
rexp = builder.build("rexp"),
REXP = rexp.REXP;
return new REXP(messageJSON);
};
\ No newline at end of file
......@@ -13,6 +13,7 @@ morpheus.Project = function(dataset) {
this.columnSelectionModel = new morpheus.SelectionModel(this, true);
this.rowSelectionModel = new morpheus.SelectionModel(this, false);
this.elementSelectionModel = new morpheus.ElementSelectionModel(this);
morpheus.Project._recomputeCalculatedFields(this.originalDataset);
morpheus.Project
._recomputeCalculatedFields(new morpheus.TransposedDatasetView(
......@@ -99,6 +100,8 @@ morpheus.Project.prototype = {
this.columnSelectionModel.clear();
this.rowSelectionModel.clear();
this.elementSelectionModel.clear();
this.setESSession(dataset);
if (notify) {
this.trigger(morpheus.Project.Events.DATASET_CHANGED);
}
......
morpheus.PcaPlotTool = function (chartOptions) {
var _this = this;
this.getVisibleTrackNames = chartOptions.getVisibleTrackNames;
this.project = chartOptions.project;
var project = this.project;
var nr = project.getRowSelectionModel().count();
if (nr != 2) {
alert("Choose exactly two rows to construct pcaPlot");
}
var nc = project.getColumnSelectionModel().count();
if (nc == 0) {
alert("Choose some columns");
}
var selectedDataset = project.getSelectedDataset();
this.$el = $('<div class="container-fluid">'
+ '<div class="row">'
+ '<div data-name="configPane" class="col-xs-2"></div>'
+ '<div class="col-xs-10"><div style="position:relative;" data-name="chartDiv"></div></div>'
+ '</div></div>');
console.log(selectedDataset);
console.log(nr, nc);
var formBuilder = new morpheus.FormBuilder({
vertical: true
});
this.formBuilder = formBuilder;
var rowOptions = [];
var columnOptions = [];
var numericRowOptions = [];
var numericColumnOptions = [];
var options = [];
var numericOptions = [];
var updateOptions = function () {
var dataset = project.getFullDataset();
rowOptions = [{
name: '(None)',
value: ''
}];
columnOptions = [{
name: '(None)',
value: ''
}];
numericRowOptions = [{
name: '(None)',
value: ''
}];
numericColumnOptions = [{
name: '(None)',
value: ''
}];
options = [{
name: '(None)',
value: ''
}];
numericOptions = [{
name: '(None)',
value: ''
}];
morpheus.MetadataUtil.getMetadataNames(dataset.getRowMetadata())
.forEach(
function (name) {
var dataType = morpheus.VectorUtil
.getDataType(dataset.getRowMetadata()
.getByName(name));
if (dataType === 'number'
|| dataType === '[number]') {
numericRowOptions.push({
name: name + ' (row)',
value: name
});
}
rowOptions.push({
name: name + ' (row)',
value: name
});
});
morpheus.MetadataUtil.getMetadataNames(dataset.getColumnMetadata())
.forEach(
function (name) {
var dataType = morpheus.VectorUtil
.getDataType(dataset.getColumnMetadata()
.getByName(name));
if (dataType === 'number'
|| dataType === '[number]') {
numericColumnOptions.push({
name: name + ' (column)',
value: name
});
}
columnOptions.push({
name: name + ' (column)',
value: name
});
});
options = options.concat(rowOptions.slice(1));
options = options.concat(columnOptions.slice(1));
numericOptions = numericOptions.concat(numericRowOptions.slice(1));
numericOptions = numericOptions.concat(numericColumnOptions.slice(1));
};
updateOptions();
formBuilder.append({
name: 'group_columns_by',
type: 'bootstrap-select',
options: options
});
formBuilder.append({
name: 'group_rows_by',
type: 'bootstrap-select',
options: options
});
formBuilder.append({
name: 'size',
type: 'bootstrap-select',
options: numericOptions
});
formBuilder.append({
name: 'color',
type: 'bootstrap-select',
options: numericOptions
});
function setVisibility() {
formBuilder.setOptions('color', options, true);
formBuilder.setOptions('size', numericOptions, true);
}
this.tooltip = [];
formBuilder.$form.find('select').on('change', function (e) {
if ($(this).attr('name') === 'tooltip') {
var tooltipVal = _this.formBuilder.getValue('tooltip');
_this.tooltip = [];
if (tooltipVal != null) {
tooltipVal.forEach(function (tip) {
_this.tooltip.push(morpheus.ChartTool.getVectorInfo(tip));
});
}
} else {
setVisibility();
_this.draw();
}
});
formBuilder.$form.find('input').on('click', function () {
_this.draw();
});
setVisibility();
var draw = function () {
_.debounce(_this.draw(), 100);
};
var trackChanged = function () {
updateOptions();
setVisibility();
formBuilder.setOptions('group_columns_by', options, true);
formBuilder.setOptions('group_rows_by', options, true);
};
project.getColumnSelectionModel().on('selectionChanged.chart', draw);
project.getRowSelectionModel().on('selectionChanged.chart', draw);
project.on('trackChanged.chart', trackChanged);
this.$chart = this.$el.find('[data-name=chartDiv]');
var $dialog = $('<div style="background:white;" title="Chart"></div>');
var $configPane = this.$el.find('[data-name=configPane]');
formBuilder.$form.appendTo($configPane);
this.$el.appendTo($dialog);
$dialog.dialog({
close: function (event, ui) {
project.off('trackChanged.chart', trackChanged);
project.getRowSelectionModel().off('selectionChanged.chart', draw);
project.getColumnSelectionModel().off('selectionChanged.chart',
draw);
_this.$el.empty();
},
resizable: true,
height: 600,
width: 900
});
this.$dialog = $dialog;
this.draw();
};
morpheus.PcaPlotTool.getVectorInfo = function (value) {
var field = value.substring(0, value.length - 2);
var isColumns = value.substring(value.length - 2) === '_c';
return {
field: field,
isColumns: isColumns
};
};
morpheus.PcaPlotTool.prototype = {
annotate: function (options) {
var _this = this;
var formBuilder = new morpheus.FormBuilder();
formBuilder.append({
name: 'annotation_name',
type: 'text',
required: true
});
formBuilder.append({
name: 'annotation_value',
type: 'text',
required: true
});
morpheus.FormBuilder
.showOkCancel({
title: 'Annotate Selection',
content: formBuilder.$form,
okCallback: function () {
var dataset = options.dataset;
var eventData = options.eventData;
var array = options.array;
var value = formBuilder.getValue('annotation_value');
var annotationName = formBuilder
.getValue('annotation_name');
// var annotate = formBuilder.getValue('annotate');
var isRows = true;
var isColumns = true;
var existingRowVector = null;
var rowVector = null;
if (isRows) {
existingRowVector = dataset.getRowMetadata()
.getByName(annotationName);
rowVector = dataset.getRowMetadata().add(
annotationName);
}
var existingColumnVector = null;
var columnVector = null;
if (isColumns) {
existingColumnVector = dataset.getColumnMetadata()
.getByName(annotationName);
columnVector = dataset.getColumnMetadata().add(
annotationName);
}
for (var p = 0, nselected = eventData.points.length; p < nselected; p++) {
var item = array[eventData.points[p].pointNumber];
if (isRows) {
if (_.isArray(item.row)) {
item.row.forEach(function (r) {
rowVector.setValue(r, value);
});
} else {
rowVector.setValue(item.row, value);
}
}
if (isColumns) {
columnVector.setValue(item.column, value);
}
}
if (isRows) {
morpheus.VectorUtil
.maybeConvertStringToNumber(rowVector);
_this.project.trigger('trackChanged', {
vectors: [rowVector],
render: existingRowVector != null ? []
: [morpheus.VectorTrack.RENDER.TEXT],
columns: false
});
}
if (isColumns) {
morpheus.VectorUtil
.maybeConvertStringToNumber(columnVector);
_this.project.trigger('trackChanged', {
vectors: [columnVector],
render: existingColumnVector != null ? []
: [morpheus.VectorTrack.RENDER.TEXT],
columns: true
});
}
}
});
},
draw: function () {
var _this = this;
this.$chart.empty();
var plotlyDefaults = morpheus.ChartTool.getPlotlyDefaults();
var layout = plotlyDefaults.layout;
var config = plotlyDefaults.config;
var chartWidth = 400;
var chartHeight = 400;
var showPoints = this.formBuilder.getValue('show_points');
var groupColumnsBy = this.formBuilder.getValue('group_columns_by');
var axisLabel = this.formBuilder.getValue('axis_label');
var colorBy = this.formBuilder.getValue('color');
var sizeBy = this.formBuilder.getValue('size');
var groupRowsBy = this.formBuilder.getValue('group_rows_by');
var dataset = this.project.getSelectedDataset({
emptyToAll: false
});
this.dataset = dataset;
if (dataset.getRowCount() * dataset.getColumnCount() === 0 || dataset.getRowCount() != 2) {
$('<h4>Please select 2 rows and any number of columns in the heat map.</h4>')
.appendTo(this.$chart);
return;
}
if ((dataset.getRowCount() * dataset.getColumnCount()) > 100000) {
showPoints = false;
}
var project = this.project;
var expressionSet = project.getFullDataset().getESSession();
var columnIndices = dataset.columnIndices;
var rowIndices = dataset.rowIndices;
var req = ocpu.call("pcaPlot", {
es : expressionSet,
columns : columnIndices,
c1 : rowIndices[0],
c2 : rowIndices[1],
colour : colorBy,
size : sizeBy
}, function (session) {
var img = $('<img />', {src : session.getLoc() + 'graphics/1/png'});
_this.$chart.append(img);
});
req.fail(function () {
alert("failed to create pcaPlot");
})
}
};
......@@ -253,11 +253,8 @@ morpheus.HeatMapToolBar = function (controller) {
$buttons.on('click', '[name=pca]', function () {
console.log("test button clicked");
new morpheus.PcaPlotTool({
project: controller.getProject(),
getVisibleTrackNames: _.bind(
controller.getVisibleTrackNames, controller)
});
new morpheus.PcaPlotTool({project : controller.getProject()});
});
var $lineOneColumn = $el.find('[data-name=lineOneColumn]');
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment