From 2df75cd2b88d46eee817b76827c138a0a41683b4 Mon Sep 17 00:00:00 2001 From: baba-beda Date: Wed, 18 Oct 2017 20:03:10 +0300 Subject: [PATCH] added method selectMaxProbe for CollapseDatasetTool --- jasmine/spec/collapse_tool_test.js | 54 +++++++++++ js/morpheus-latest.min.js | 2 +- js/morpheus.js | 130 +++++++++++++++++++++++++-- src/algorithm/collapse_dataset.js | 80 +++++++++++++++++ src/matrix/multivariate_functions.js | 36 ++++++++ src/tools/collapse_dataset_tool.js | 13 +-- 6 files changed, 304 insertions(+), 11 deletions(-) create mode 100644 src/matrix/multivariate_functions.js diff --git a/jasmine/spec/collapse_tool_test.js b/jasmine/spec/collapse_tool_test.js index 6ab136e5..6f6d4cf8 100644 --- a/jasmine/spec/collapse_tool_test.js +++ b/jasmine/spec/collapse_tool_test.js @@ -1,4 +1,58 @@ describe('collapse_tool_test', function () { + it('maxmeanprobe', + function () { + var heatmap = new morpheus.HeatMap({ + dataset: new morpheus.Dataset({ + array: [[1, 3], [4, 6], [7, 9], [10, 12]], + rows: 4, + columns: 2 + }) + }); + heatmap.getProject().getFullDataset().getRowMetadata() + .add('id').array = ['a', 'b', 'a', 'a']; + var newHeatMap = new morpheus.CollapseDatasetTool().execute({ + heatMap: heatmap, + project: heatmap.getProject(), + input: { + collapse_method: 'Maximum Mean Probe', + collapse: 'Rows', + collapse_to_fields: ['id'] + } + }); + expect(newHeatMap.getProject().getFullDataset()) + .toBeDatasetValues(new morpheus.Dataset({ + array: [[10, 12], [4, 6]], + rows: 2, + columns: 2 + }), 0.00001); + }); + it('maxmedianprobe', + function () { + var heatmap = new morpheus.HeatMap({ + dataset: new morpheus.Dataset({ + array: [[1, 3], [4, 6], [7, 9], [10, 12]], + rows: 4, + columns: 2 + }) + }); + heatmap.getProject().getFullDataset().getRowMetadata() + .add('id').array = ['a', 'b', 'a', 'a']; + var newHeatMap = new morpheus.CollapseDatasetTool().execute({ + heatMap: heatmap, + project: heatmap.getProject(), + input: { + collapse_method: 'Maximum Median Probe', + collapse: 'Rows', + collapse_to_fields: ['id'] + } + }); + expect(newHeatMap.getProject().getFullDataset()) + .toBeDatasetValues(new morpheus.Dataset({ + array: [[10, 12], [4, 6]], + rows: 2, + columns: 2 + }), 0.00001); + }); it('mean', function () { var heatmap = new morpheus.HeatMap({ diff --git a/js/morpheus-latest.min.js b/js/morpheus-latest.min.js index f4ae3418..10501cd3 100644 --- a/js/morpheus-latest.min.js +++ b/js/morpheus-latest.min.js @@ -1 +1 @@ -(function(global){"use strict";var morpheus=typeof morpheus!=="undefined"?morpheus:{};if(typeof module!=="undefined"&&module.exports){module.exports=morpheus}else if(typeof define==="function"&&define.amd){define(function(){return morpheus})}else{global.morpheus=morpheus}morpheus.Util=function(){};morpheus.Util.RIGHT_ARROW=String.fromCharCode(8594);morpheus.Util.extend=function(c1,c2){for(var key in c2.prototype){if(!(key in c1.prototype)){c1.prototype[key]=c2.prototype[key]}}};morpheus.Util.isFetchStreamingSupported=function(){return typeof navigator!=="undefined"&&navigator.userAgent.indexOf("Chrome")!==-1};morpheus.Util.viewPortSize=function(){return window.getComputedStyle(document.body,":before").content.replace(/"/g,"")};morpheus.Util.TRACKING_ENABLED=true;morpheus.Util.TRACKING_CODE_LOADED=false;morpheus.Util.loadTrackingCode=function(){if(morpheus.Util.TRACKING_ENABLED&&typeof window!=="undefined"&&typeof navigator!=="undefined"&&navigator.onLine){if(morpheus.Util.TRACKING_CODE_LOADED){return}else if(typeof ga==="undefined"){morpheus.Util.TRACKING_CODE_LOADED=true;(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date;a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,"script","https://www.google-analytics.com/analytics.js","ga")}if(typeof ga!=="undefined"){ga("create","UA-53973555-1","auto","morpheus");ga("morpheus.send","pageview")}morpheus.Util.TRACKING_CODE_LOADED=true}};morpheus.Util.measureScrollbar=function(){var $c=$("
").appendTo("body");var dim={width:Math.max(0,$c.width()-$c[0].clientWidth),height:$c.height()-$c[0].clientHeight};$c.remove();return dim};morpheus.Util.trackEvent=function(options){if(typeof window!=="undefined"){if(!morpheus.Util.TRACKING_CODE_LOADED){morpheus.Util.loadTrackingCode()}if(morpheus.Util.TRACKING_CODE_LOADED&&typeof ga!=="undefined"){ga("morpheus.send",{hitType:"event",eventCategory:options.eventCategory,eventAction:options.eventAction,eventLabel:options.eventLabel})}}};morpheus.Util.isString=function(value){return typeof value==="string"||value instanceof String};morpheus.Util.getDataType=function(val){var dataType;var isArray=morpheus.Util.isArray(val);if(isArray&&val.length>0){val=val[0]}if(morpheus.Util.isString(val)){dataType="string"}else if(_.isNumber(val)){dataType="number"}else{dataType="object"}if(isArray){dataType="["+dataType+"]"}return dataType};morpheus.Util.isArray=function(array){var types=[Array,Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];for(var i=0,length=types.length;i0){searchObject=morpheus.Util.getQueryParams(window.location.search.substring(1))}if(window.location.hash.length>0){hashObject=morpheus.Util.getQueryParams(window.location.hash.substring(1))}return _.extend(hashObject,searchObject)};morpheus.Util.copyString=function(s){return(" "+s).substr(1)};morpheus.Util.getQueryParams=function(s){var params={};if(!s){return params}var search=decodeURIComponent(s);var keyValuePairs=search.split("&");for(var i=0;i=0;i--){var src=scripts[i].src;var index=src.lastIndexOf("/");if(index!==-1){src=src.substring(index+1)}if(src===name){return scripts[i].src}}if(name==="morpheus-latest.min.js"){return morpheus.Util.getScriptPath("morpheus.js")}return scripts.length>0?scripts[0].src:""};morpheus.Util.forceDelete=function(obj){try{var _garbageCollector=function(){var ef=URL.createObjectURL(new Blob([""],{type:"text/javascript"})),w=new Worker(ef);URL.revokeObjectURL(ef);return w}();_garbageCollector.postMessage(obj,[obj])}catch(x){console.log("Unable to delete")}};morpheus.Util.getFileName=function(fileOrUrl){if(morpheus.Util.isFile(fileOrUrl)){return fileOrUrl.name}if(fileOrUrl.name!==undefined){return fileOrUrl.name}var name=""+fileOrUrl;var question=name.indexOf("?");if(question!==-1){var params=name.substring(question+1);var keyValuePairs=decodeURIComponent(params).split("&");for(var i=0;i0){var suffix=name.substring(dotIndex+1).toLowerCase();if(suffix==="txt"||suffix==="gz"||suffix==="tsv"){var newPath=name.substring(0,dotIndex);var secondDotIndex=newPath.lastIndexOf(".");if(secondDotIndex>0){var secondSuffix=newPath.substring(secondDotIndex+1,newPath.length).toLowerCase();if(secondSuffix==="segtab"||secondSuffix==="seg"||secondSuffix==="maf"||secondSuffix==="gct"||secondSuffix==="txt"||secondSuffix==="gmt"){return secondSuffix}}}return suffix}return""};morpheus.Util.getBaseFileName=function(name){var dotIndex=name.lastIndexOf(".");if(dotIndex>0){var suffix=name.substring(dotIndex+1,name.length);if(suffix==="gz"||suffix==="zip"||suffix==="bz2"){return morpheus.Util.getBaseFileName(name.substring(0,dotIndex))}return name.substring(0,dotIndex)}return name};morpheus.Util.seq=function(length){var array=[];for(var i=0;i=suffix.length&&string.substr(string.length-suffix.length)===suffix};morpheus.Util.measureSvgText=function(text,classname){if(!text||text.length===0){return{height:0,width:0}}var container=d3.select("body").append("svg");if(classname){container.attr("class",classname)}container.append("text").attr({x:-1e3,y:-1e3}).text(text);var bbox=container.node().getBBox();container.remove();return{height:bbox.height,width:bbox.width}};morpheus.Util.IS_MAC=false;if(typeof navigator!=="undefined"){morpheus.Util.IS_MAC=navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i)?true:false}morpheus.Util.COMMAND_KEY=morpheus.Util.IS_MAC?"⌘":"Ctrl+";morpheus.Util.hammer=function(el,recognizers){if(typeof Hammer!=="undefined"){var hammer=new Hammer(el,{recognizers:[]});if(_.indexOf(recognizers,"pan")!==-1){hammer.add(new Hammer.Pan({threshold:1,direction:Hammer.DIRECTION_ALL}))}else if(_.indexOf(recognizers,"panh")!==-1){hammer.add(new Hammer.Pan({threshold:1,direction:Hammer.DIRECTION_HORIZONTAL}))}else if(_.indexOf(recognizers,"panv")!==-1){hammer.add(new Hammer.Pan({threshold:1,direction:Hammer.DIRECTION_VERTICAL}))}if(_.indexOf(recognizers,"tap")!==-1){hammer.add(new Hammer.Tap)}if(_.indexOf(recognizers,"pinch")!==-1){hammer.add(new Hammer.Pinch)}if(_.indexOf(recognizers,"longpress")!==-1){hammer.add(new Hammer.Press({event:"longpress",time:1e3}))}if(_.indexOf(recognizers,"press")!==-1){hammer.add(new Hammer.Press)}if(_.indexOf(recognizers,"swipe")!==-1){hammer.add(new Hammer.Swipe)}return hammer}else{return $()}};morpheus.Util.createTextDecoder=function(){if(typeof TextDecoder!=="undefined"){var textDecoder=new TextDecoder;return function(buf,start,end){return textDecoder.decode(buf.subarray(start,end))}}else{return function(buf,start,end){var s=[];for(var i=start;i"+value.replace(regexMatch,"$1")+""})});cb(matches)};morpheus.Util.setClipboardData=function(clipboardData,delay){var isRTL=document.documentElement.getAttribute("dir")=="rtl";var fakeElem=document.createElement("div");fakeElem.contentEditable=true;fakeElem.style.fontSize="12pt";fakeElem.style.border="0";fakeElem.style.padding="0";fakeElem.style.margin="0";fakeElem.style.position="absolute";fakeElem.style[isRTL?"right":"left"]="-999999px";fakeElem.style.top=(window.pageYOffset||document.documentElement.scrollTop)+"px";fakeElem.setAttribute("readonly","");var f=function(e){clipboardData.forEach(function(elem){e.clipboardData.setData(elem.format,elem.data)});e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();fakeElem.removeEventListener("copy",f)};fakeElem.addEventListener("copy",f);document.body.appendChild(fakeElem);fakeElem.focus();var selection=window.getSelection();var range=document.createRange();range.selectNodeContents(fakeElem);selection.removeAllRanges();selection.addRange(range);if(delay){setTimeout(function(){if(!document.execCommand("copy")){console.log("copy failed")}document.body.removeChild(fakeElem)},20)}else{if(!document.execCommand("copy")){console.log("copy failed")}document.body.removeChild(fakeElem)}};morpheus.Util.autosuggest=function(options){options=$.extend({},{multi:true,delay:500,minLength:0,suggestWhenEmpty:true},options);var searching=false;function _select(event,ui,isKey){if(ui.item.skip){return false}if(options.multi){var terms=morpheus.Util.getAutocompleteTokens(options.$el[0].value,{trim:false,selectionStart:options.$el[0].selectionStart});var field=event.toElement&&event.toElement.dataset?event.toElement.dataset.autocomplete:null;var value=field?ui.item[field]:ui.item.value;var show=ui.item.show;if(terms.length===0){terms.push(value)}else if(ui.item.clear){terms=[value]}else{terms[terms.selectionStartIndex===-1||terms.selectionStartIndex===undefined?terms.length-1:terms.selectionStartIndex]=value}options.$el[0].value=terms.join(" ");if(show&&!isKey||isKey&&event.which===13){searching=true;setTimeout(function(){options.$el.autocomplete("search",options.$el.val())},20);setTimeout(function(){searching=false},100)}if(!isKey&&options.select){options.select()}return false}if(!isKey&&options.select){options.select()}if(!isKey&&event.which===13){event.stopImmediatePropagation()}}options.$el.on("keydown",function(event){if(event.keyCode===$.ui.keyCode.TAB&&$(this).data("ui-autocomplete").menu.active){event.preventDefault()}}).autocomplete({minLength:options.minLength,delay:options.delay,source:function(request,response){if(request.term.history&&options.history){return options.history(response)}var terms=morpheus.Util.getAutocompleteTokens(request.term,{trim:false,selectionStart:options.$el[0].selectionStart});if(terms.selectionStartIndex===undefined||terms.selectionStartIndex===-1){terms.selectionStartIndex=terms.length-1}if(options.suggestWhenEmpty||terms.length>0){options.filter(terms,response)}},focus:function(event,ui){var original=event.originalEvent;while(original.originalEvent!=null){original=original.originalEvent}if(original&&/^key/.test(original.type)){return _select(original,ui,true)}return false},select:function(event,ui){return _select(event,ui,false)}});var instance=options.$el.autocomplete("instance");if(instance!=null){instance._renderItem=function(ul,item){if(item.value==null){return $('
  • ').append($("
    ").html(item.label)).appendTo(ul)}return $('
  • ').append($("
    ").html(item.label)).appendTo(ul)};instance._normalize=function(items){return items};instance._resizeMenu=function(){var ul=this.menu.element;ul.outerWidth(instance.element.outerWidth())}}var menu=options.$el.autocomplete("widget");menu.menu("option","items","> :not(.search-category)");if(menu){menu.addClass("search-menu")}if(options.suggestWhenEmpty){options.$el.on("focus",function(){options.$el.autocomplete("search",options.$el.val())})}options.$el.on("keyup",function(e){if(e.which===13&&!searching){options.$el.autocomplete("close")}else if(e.which===38&&options.history){options.$el.autocomplete("search",{history:true})}else if(options.suggestWhenEmpty&&options.$el.val()===""){options.$el.autocomplete("search","")}})};morpheus.Util.getAutocompleteTokens=function(text,options){options=$.extend({},{trim:true},options);if(options.trim){text=$.trim(text)}if(text===""){return[]}var inQuote=false;var inParen=false;var tokens=[];var currentToken=[];for(var i=0,n=text.length;i
    ");$el.appendTo($dialog);$dialog.appendTo($(document.body));if(!options){options={}}$dialog.dialog({width:670,height:590,title:title,close:function(event,ui){$dialog.remove();if(options.close){options.close()}}})};morpheus.Util.sheetToArray=function(sheet,delim){var r=XLSX.utils.decode_range(sheet["!ref"]);var rows=[];var colors=[];var header=[];for(var C=r.s.c;C<=r.e.c;++C){var val=sheet[XLSX.utils.encode_cell({c:C,r:r.s.r})];var txt=String(XLSX.utils.format_cell(val));header.push(txt)}for(var R=r.s.r;R<=r.e.r;++R){var row=[];var isRowEmpty=true;for(var C=r.s.c;C<=r.e.c;++C){var val=sheet[XLSX.utils.encode_cell({c:C,r:R})];if(!val){row.push("");continue}isRowEmpty=false;var txt=String(XLSX.utils.format_cell(val));if(val.s!=null&&val.s.fgColor!=null){var color="#"+val.s.fgColor.rgb;colors.push({header:header[row.length],color:color,value:txt})}row.push(txt)}if(!isRowEmpty){rows.push(delim?row.join(delim):row)}}rows.colors=colors;return rows};morpheus.Util.linesToObjects=function(lines){var header=lines[0];var array=[];var nfields=header.length;for(var i=1,length=lines.length;i1){var formBuilder=new morpheus.FormBuilder;formBuilder.append({name:"sheet",type:"bootstrap-select",options:sheetNames,required:true,style:"max-width:100px;"});morpheus.FormBuilder.showInModal({title:"Choose Sheet",html:formBuilder.$form,focus:document.activeElement,onClose:function(){var worksheet=workbook.Sheets[formBuilder.getValue("sheet")];var lines=morpheus.Util.sheetToArray(worksheet);callback(null,lines)}})}else{var worksheet=workbook.Sheets[sheetNames[0]];var lines=morpheus.Util.sheetToArray(worksheet);callback(null,lines)}};morpheus.Util.xlsxTo1dArray=function(options,callback){var workbook=XLSX.read(options.data,{type:"binary",cellFormula:false,cellHTML:false,cellStyles:true});var sheetNames=workbook.SheetNames;if(options.prompt&&sheetNames.length>1){var formBuilder=new morpheus.FormBuilder;formBuilder.append({name:"sheet",type:"bootstrap-select",options:sheetNames,required:true,style:"max-width:100px;"});morpheus.FormBuilder.showOkCancel({title:"Choose Sheet",cancel:false,focus:document.activeElement,content:formBuilder.$form,okCallback:function(){var worksheet=workbook.Sheets[formBuilder.getValue("sheet")];callback(null,morpheus.Util.sheetToArray(worksheet,"\t"))}})}else{var worksheet=workbook.Sheets[sheetNames[0]];callback(null,morpheus.Util.sheetToArray(worksheet,"\t"))}};morpheus.Util.getText=function(fileOrUrl){var deferred=$.Deferred();if(morpheus.Util.isString(fileOrUrl)){fetch(fileOrUrl).then(function(response){if(response.ok){return response.text()}else{deferred.reject(response.status+" "+response.statusText)}}).then(function(text){deferred.resolve(text)}).catch(function(err){deferred.reject(err)})}else if(morpheus.Util.isFile(fileOrUrl)){var reader=new FileReader;reader.onload=function(event){deferred.resolve(event.target.result)};reader.readAsText(fileOrUrl)}else{deferred.resolve(fileOrUrl)}return deferred.promise()};morpheus.Util.createOptions=function(values,none){var html=[];if(none){html.push('')}_.each(values,function(val){html.push('")});return html.join("")};morpheus.Util.rankIndexArray=function(index){var rank=[];var n=index.length;for(var j=0;jindex;i--,zeros--){if(str[i]!="0"){break}}if(zeros===index+1){return str.substring(0,index)}if(zeros0;var fieldRegExp=/\\:/g;var predicates=[];var defaultIsExactMatch=options.defaultMatchMode==="exact";tokens.forEach(function(token){var isNot=false;if(token[0]==="-"){token=token.substring(1);isNot=true}var field=null;var semi=token.indexOf(":");if(semi>0){if(!fieldSearchEnabled||token.charCodeAt(semi-1)===92){token=token.replace(fieldRegExp,":")}else{var possibleToken=$.trim(token.substring(semi+1));var possibleField=$.trim(token.substring(0,semi));if(possibleField.length>0&&possibleField[0]==='"'&&possibleField[possibleField.length-1]==='"'){possibleField=possibleField.substring(1,possibleField.length-1)}else if(possibleField.length>0&&possibleField[0]==='"'&&possibleToken[possibleToken.length-1]==='"'&&possibleToken[0]!=='"'){possibleField=possibleField.substring(1,possibleField.length);possibleToken='"'+possibleToken}if(!validateFieldNames||availableFields.indexOf(options.caseSensitive?possibleField:possibleField.toLowerCase())!==-1){token=possibleToken;field=possibleField}}}var predicate;var rangeIndex=-1;var rangeToken=null;var rangeIndicators=["..",">=",">","<=","<","="];for(var i=0;i"){var val=parseFloat(token.substring(rangeIndex+1));if(!isNaN(val)){predicate=new morpheus.Util.GreaterThanPredicate(field,val)}}else if(rangeToken===">="){var val=parseFloat(token.substring(rangeIndex+2));if(!isNaN(val)){predicate=new morpheus.Util.GreaterThanOrEqualPredicate(field,val)}}else if(rangeToken==="<"){var val=parseFloat(token.substring(rangeIndex+1));if(!isNaN(val)){predicate=new morpheus.Util.LessThanPredicate(field,val)}}else if(rangeToken==="<="){var val=parseFloat(token.substring(rangeIndex+2));if(!isNaN(val)){predicate=new morpheus.Util.LessThanOrEqualPredicate(field,val)}}else if(rangeToken==="="){var val=parseFloat(token.substring(rangeIndex+1));predicate=new morpheus.Util.EqualsPredicate(field,val)}else{console.log("Unknown range token:"+rangeToken)}}else if(token[0]==='"'&&token[token.length-1]==='"'){token=token.substring(1,token.length-1);predicate=new morpheus.Util.ExactTermPredicate(field,token)}else if(token[0]==="("&&token[token.length-1]===")"){token=token.substring(1,token.length-1);var values=morpheus.Util.getAutocompleteTokens(token);if(values.length>0){predicate=new morpheus.Util.ExactTermsPredicate(field,values.map(function(val){if(val[0]==='"'&&val[val.length-1]==='"'){val=val.substring(1,val.length-1)}return val.toLowerCase()}))}}else if(token.indexOf("*")!==-1){predicate=new morpheus.Util.RegexPredicate(field,token)}else{predicate=defaultIsExactMatch?new morpheus.Util.ExactTermPredicate(field,token):new morpheus.Util.RegexPredicate(field,token)}if(predicate!=null){predicates.push(isNot?new morpheus.Util.NotPredicate(predicate):predicate)}});return predicates};morpheus.Util.createRegExpStringToMatchText=function(text){var tokens=morpheus.Util.getAutocompleteTokens(text);if(tokens.length===0){return null}var regex=[];_.each(tokens,function(token){if(token[0]==='"'&&token[token.length-1]==='"'){token=token.substring(1,token.length-1);regex.push("^"+morpheus.Util.escapeRegex(token)+"$")}else{regex.push(morpheus.Util.escapeRegex(token))}});return"("+regex.join("|")+")"};morpheus.Util.createRegExpToMatchText=function(text){var s=morpheus.Util.createRegExpStringToMatchText(text);return s==null?null:new RegExp(s,"i")};morpheus.Util.reorderArray=function(array,index){var newArray=[];for(var i=0;i1?s.substring(1):""};morpheus.Util.splitLines=function(lines){var tab=/\t/;var tokens=[];for(var i=0,nlines=lines.length;i');html.push("M");html.push("O");html.push("R");html.push("P");html.push("H");html.push("E");html.push("U");html.push("S");html.push("");html.push("");var $div=$(html.join(""));var colorScale=d3.scale.linear().domain([0,4,7]).range(["#ca0020","#999999","#0571b0"]).clamp(true);var brands=$div.find("span");var index=0;var step=function(){brands[index].style.color=colorScale(index);index++;if(indexLoading...')};morpheus.Util.splitOnNewLine=function(text,commentChar){var commentCharCode=commentChar!==undefined?commentChar.charCodeAt(0):undefined;var lines=text.split(/\n/);if(lines.length===1){var tmp=text.split(/\r/);if(tmp.length>1){lines=tmp}}var rows=[];var rtrim=/\s+$/;for(var i=0,nlines=lines.length;i=this.min&&value<=this.max},getField:function(){return this.field},isNumber:function(){return true},toString:function(){return"NumberRangePredicate "+this.field+":"+this.min+"..."+this.max}};morpheus.Util.GreaterThanPredicate=function(field,val){this.field=field;this.val=val};morpheus.Util.GreaterThanPredicate.prototype={accept:function(value){return value>this.val},getField:function(){return this.field},isNumber:function(){return true}};morpheus.Util.GreaterThanOrEqualPredicate=function(field,val){this.field=field;this.val=val};morpheus.Util.GreaterThanOrEqualPredicate.prototype={accept:function(value){return value>=this.val},getField:function(){return this.field},isNumber:function(){return true}};morpheus.Util.LessThanPredicate=function(field,val){this.field=field;this.val=val};morpheus.Util.LessThanPredicate.prototype={accept:function(value){return value0){s.push(", ")}s.push(key);s.push("=");s.push(value)});return s.join("")},keys:function(){var keys=[];for(var key in this.map){var pair=this.map[key];keys.push(pair.key)}return keys},size:function(){return this.n},equals:function(m){if(m.size()!==this.size()){return false}var ret=true;try{this.forEach(function(value,key){if(value!==m.get(key)){ret=false;throw"break"}})}catch(e){}return ret},setAll:function(map){var _this=this;map.forEach(function(value,key){_this.set(key,value)})},set:function(key,value){var skey="\0"+key;var previous=this.map[skey];if(previous===undefined){this.n++}this.map[skey]={key:key,value:value}},forEach:function(callback){for(var key in this.map){var pair=this.map[key];callback(pair.value,pair.key)}},entries:function(){var array=[];this.forEach(function(value,key){array.push({value:value,key:key})});return array},values:function(){var values=[];for(var key in this.map){var pair=this.map[key];values.push(pair.value)}return values},get:function(key){var skey="\0"+key;var pair=this.map[skey];return pair!==undefined?pair.value:undefined},clear:function(){this.map={};this.n=0},remove:function(key){var skey="\0"+key;var pair=this.map[skey];if(pair!==undefined){delete this.map[skey];this.n--;return pair.value}},has:function(key){var skey="\0"+key;return this.map[skey]!==undefined}};morpheus.Map.fromJSON=function(json){var map=new morpheus.Map;for(var key in json){map.set(key,json[key])}return map};morpheus.Set=function(){this._map=new morpheus.Map};morpheus.Set.prototype={toJSON:function(){var json=[];this.forEach(function(value){json.push(value)});return json},toString:function(){var s=[];this.forEach(function(key){if(s.length>0){s.push(", ")}s.push(key)});return s.join("")},size:function(){return this._map.size()},equals:function(m){return this._map.equals(m)},forEach:function(callback){this._map.forEach(function(value,key){callback(key)})},add:function(value){this._map.set(value,true)},values:function(){var values=[];this._map.forEach(function(value,key){values.push(key)});return values},clear:function(){this._map.clear()},remove:function(key){this._map.remove(key)},has:function(key){return this._map.has(key)}};morpheus.Set.fromJSON=function(json){var set=new morpheus.Set;for(var i=0,length=json.length;i=bufferLength){return null}var buffer=this.buffer;var start=index;var end=start;for(;index");html.push("");html.push('
    "+"
    ");html.push(" Data Matrix');html.push("
    Column'+" Annotations");html.push("
    Row'+" Annotations");html.push('
    ');html.push("");var $el=$(html.join(""));morpheus.Util.readLines(fileOrUrl,true).done(function(lines){var tab=/\t/;for(var i=0,nrows=lines.length;i=dataColumnStart&&row>=dataRowStart){color="#b3cde3"}else if(row<=dataRowStart-1&&cell>=dataColumnStart){color="#fbb4ae"}else if(cell=dataRowStart){color="#ccebc5"}var html=['
    '];if(_.isNumber(value)){html.push(morpheus.Util.nf(value))}else if(morpheus.Util.isArray(value)){var s=[];for(var i=0,length=value.length;i0){s.push(", ")}var val=value[i];s.push(value[i])}html.push(s.join(""))}else{html.push(value)}html.push("
    ");return html.join("")}});var transposedLines;var transposedColumns;$el.find("[name=transpose]").on("click",function(e){if($(this).prop("checked")){if(transposedLines==null){transposedLines=[];for(var j=0,ncols=lines[0].length;jOK');footer.push('');var $footer=$(footer.join(""));morpheus.FormBuilder.showOkCancel({title:"Open",content:$el,close:false,focus:document.activeElement,cancelCallback:function(){callback(null)},okCallback:function(){_this._read(name,lines,dataColumnStart,dataRowStart,callback)}});grid.resizeCanvas()}).fail(function(err){callback(err)})},_read:function(datasetName,lines,dataColumnStart,dataRowStart,cb){var columnCount=lines[0].length;var columns=columnCount-dataColumnStart;var rows=lines.length-dataRowStart;var dataset=new morpheus.Dataset({name:datasetName,rows:rows,columns:columns,dataType:"Float32"});if(dataColumnStart>0){for(var i=0;i0){for(var j=0;j0){pw.push(" ")}pw.push(valueToIndex.get(vector.getValue(i)))}pw.push("\n");return pw.join("")}};morpheus.GctReader=function(){};morpheus.GctReader.prototype={getFormatName:function(){return"gct"},read:function(fileOrUrl,callback){var _this=this;if(morpheus.Util.isFile(fileOrUrl)){this._readChunking(fileOrUrl,callback,false)}else{if(morpheus.Util.isFetchStreamingSupported()){this._readChunking(fileOrUrl,callback,true)}else{this._readNoChunking(fileOrUrl,callback)}}},_readChunking:function(fileOrUrl,callback,useFetch){var _this=this;var lineNumber=0;var version;var numRowAnnotations=1;var numColumnAnnotations=0;var nrows=-1;var ncols=-1;var version=2;var rowMetadataNames=[];var columnMetadataNames=[];var rowMetadata=[[]];var columnMetadata=[[]];var dataColumnStart;var matrix=[];var dataMatrixLineNumberStart;var columnIdFieldName="id";var rowIdFieldName="id";var columnNamesArray;var handleTokens=function(tokens){if(lineNumber===0){var text=tokens[0].trim();if("#1.2"===text){version=2}else if("#1.3"===text){version=3}else{console.log("Unknown version: assuming version 2")}}else if(lineNumber===1){var dimensions=tokens;if(version===3){if(dimensions.length>=4){nrows=parseInt(dimensions[0]);ncols=parseInt(dimensions[1]);numRowAnnotations=parseInt(dimensions[2]);numColumnAnnotations=parseInt(dimensions[3])}else{numRowAnnotations=parseInt(dimensions[0]);numColumnAnnotations=parseInt(dimensions[1])}}else{nrows=parseInt(dimensions[0]);ncols=parseInt(dimensions[1]);if(nrows<=0||ncols<=0){callback("Number of rows and columns must be greater than 0.")}}dataColumnStart=numRowAnnotations+1}else if(lineNumber===2){columnNamesArray=tokens;for(var i=0;iexpectedColumns){var skip=columnNamesArray.length-1;for(var i=columnNamesArray.length-1;i>=0;i--,skip--){if(columnNamesArray[i]!==""){break}}if(skip!==columnNamesArray.length-1){columnNamesArray=columnNamesArray.slice(0,skip+1)}}if(columnNamesArray.length!==expectedColumns){return callback("Expected "+(expectedColumns-2)+" column names, but read "+(columnNamesArray.length-2)+" column names.")}}}var name=columnNamesArray[0];var slashIndex=name.lastIndexOf("/");if(slashIndex!=-1&&slashIndex=4){nrows=parseInt(dimensions[0]);ncols=parseInt(dimensions[1]);numRowAnnotations=parseInt(dimensions[2]);numColumnAnnotations=parseInt(dimensions[3])}else{numRowAnnotations=parseInt(dimensions[0]);numColumnAnnotations=parseInt(dimensions[1])}}else{nrows=parseInt(dimensions[0]);ncols=parseInt(dimensions[1]);if(nrows<=0||ncols<=0){throw new Error("Number of rows and columns must be greater than 0.")}}var columnNamesLine=morpheus.Util.copyString(reader.readLine());if(columnNamesLine==null){throw new Error("No column annotations")}var columnNamesArray=columnNamesLine.split(tab);if(ncols===-1){ncols=columnNamesArray.length-numRowAnnotations-1}if(version==2){var expectedColumns=ncols+2;if(columnNamesArray.length!==expectedColumns){throw new Error("Expected "+(expectedColumns-2)+" column names, but read "+(columnNamesArray.length-2)+" column names.")}}var name=columnNamesArray[0];var slashIndex=name.lastIndexOf("/");var columnIdFieldName="id";var rowIdFieldName="id";if(slashIndex!=-1&&slashIndex0){for(var columnAnnotationIndex=0;columnAnnotationIndex0){for(var columnAnnotationIndex=0;columnAnnotationIndex0){pw.push("\t")}var vector=rowMetadata.get(rowMetadataIndex);var value=vector.getValue(i);if(value!==null){var toString=morpheus.VectorTrack.vectorToString(vector);pw.push(toString(value))}}for(var j=0;j0){pw.push("\t")}var name=rowMetadata.get(i).getName();if(i===0&&name!==columnMetadata.get(0).getName()){name=name+"/"+columnMetadata.get(0).getName()}pw.push(name)}var toString=morpheus.VectorTrack.vectorToString(columnMetadata.get(0));for(var j=0;j1){rowDescriptions=rowMetadata.get(1)}var rowIdToString=morpheus.VectorTrack.vectorToString(rowIds);var rowDescriptionToString=rowDescriptions!=null?morpheus.VectorTrack.vectorToString(rowDescriptions):null;var nf=this.nf;for(var i=0;i1?tokens[1].trim():"";if("BLANK"===description){description=""}var ids=[];for(var i=2;i0){bins[value-1]++}}vector.setValue(i,bins)}};morpheus.MafFileReader.getField=function(fieldNames,headerToIndex){var name;var index;for(var i=0;i "+String(tokens[tumorAllelColumn])}var wrappedVariant=morpheus.Util.wrapNumber(variantCode,variantObject);var variantRow=variantMatrix[rowIndex];if(variantRow===undefined){variantRow=[];variantMatrix[rowIndex]=variantRow}var ccf=-1;var priorCcf=-1;if(ccfColumnIndex!==undefined){var ccfRow=ccfMatrix[rowIndex];if(ccfRow===undefined){ccfRow=[];ccfMatrix[rowIndex]=ccfRow}ccf=parseFloat(tokens[ccfColumnIndex]);priorCcf=ccfRow[columnIndex]||-1}var priorValue=variantRow[columnIndex]||-1;if(variantCode>priorValue){variantRow[columnIndex]=wrappedVariant;if(ccfColumnIndex!==undefined){ccfRow[columnIndex]=ccf}}else if(variantCode===priorValue&&ccf>priorCcf){variantRow[columnIndex]=wrappedVariant;ccfRow[columnIndex]=ccf}}}var dataset=new morpheus.Dataset({name:datasetName,array:variantMatrix,dataType:"Number",rows:geneSymbolToIndex.size(),columns:sampleIdToIndex.size()});var columnIds=dataset.getColumnMetadata().add("id");sampleIdToIndex.forEach(function(index,id){columnIds.setValue(index,id)});var rowIds=dataset.getRowMetadata().add("id");geneSymbolToIndex.forEach(function(index,id){rowIds.setValue(index,id)});for(var i=0,nrows=dataset.getRowCount(),ncols=dataset.getColumnCount();i0){var pairs=[];customNumberToValueMap.forEach(function(value,key){pairs.push({key:key,value:value})});pairs.sort(function(a,b){return a.key===b.key?0:a.key=region.start&&end<=region.end){rowIndices.push(i)}}if(rowIndices.length>0){var slice=morpheus.DatasetUtil.slicedView(dataset,rowIndices,null);var columnView=new morpheus.DatasetColumnView(slice);for(var j=0;j0){dataset=morpheus.SegTabReader.binByRegion(dataset,this.regions)}return dataset},read:function(fileOrUrl,callback){var _this=this;var name=morpheus.Util.getBaseFileName(morpheus.Util.getFileName(fileOrUrl));morpheus.ArrayBufferReader.getArrayBuffer(fileOrUrl,function(err,arrayBuffer){if(err){callback(err)}else{callback(null,_this._read(name,new morpheus.ArrayBufferReader(new Uint8Array(arrayBuffer))))}})}};morpheus.TcgaUtil=function(){};morpheus.TcgaUtil.DISEASE_STUDIES={ACC:"Adrenocortical carcinoma",BLCA:"Bladder Urothelial Carcinoma",BRCA:"Breast invasive carcinoma",CESC:"Cervical squamous cell carcinoma and endocervical adenocarcinoma",CHOL:"Cholangiocarcinoma",COAD:"Colon adenocarcinoma",COADREAD:"Colonrectal adenocarcinoma",DLBC:"Lymphoid Neoplasm Diffuse Large B-cell Lymphoma",ESCA:"Esophageal carcinoma ",GBM:"Glioblastoma multiforme",GBMLGG:"Glioma",HNSC:"Head and Neck squamous cell carcinoma",KICH:"Kidney Chromophobe",KIPAN:"Pan-Kidney Cohort",KIRC:"Kidney renal clear cell carcinoma",KIRP:"Kidney renal papillary cell carcinoma",LAML:"Acute Myeloid Leukemia",LCML:"Chronic Myelogenous Leukemia",LGG:"Brain Lower Grade Glioma",LIHC:"Liver hepatocellular carcinoma",LUAD:"Lung adenocarcinoma",LUSC:"Lung squamous cell carcinoma",MESO:"Mesothelioma",OV:"Ovarian serous cystadenocarcinoma",PAAD:"Pancreatic adenocarcinoma",PCPG:"Pheochromocytoma and Paraganglioma",PRAD:"Prostate adenocarcinoma",READ:"Rectum adenocarcinoma",SARC:"Sarcoma",SKCM:"Skin Cutaneous Melanoma",STAD:"Stomach adenocarcinoma",STES:"Stomach and Esophageal Carcinoma",TGCT:"Testicular Germ Cell Tumors",THCA:"Thyroid carcinoma",THYM:"Thymoma",UCEC:"Uterine Corpus Endometrial Carcinoma",UCS:"Uterine Carcinosarcoma",UVM:"Uveal Melanoma"};morpheus.TcgaUtil.SAMPLE_TYPES={"01":"Primary solid Tumor","02":"Recurrent Solid Tumor","03":"Primary Blood Derived Cancer - Peripheral Blood","04":"Recurrent Blood Derived Cancer - Bone Marrow","05":"Additional - New Primary","06":"Metastatic","07":"Additional Metastatic","08":"Human Tumor Original Cells","09":"Primary Blood Derived Cancer - Bone Marrow",10:"Blood Derived Normal",11:"Solid Tissue Normal",12:"Buccal Cell Normal",13:"EBV Immortalized Normal",14:"Bone Marrow Normal",20:"Control Analyte",40:"Recurrent Blood Derived Cancer - Peripheral Blood",50:"Cell Lines",60:"Primary Xenograft Tissue",61:"Cell Line Derived Xenograft Tissue"};morpheus.TcgaUtil.barcode=function(s){var tokens=s.split("-");var id=tokens[2];var sampleType;if(tokens.length>3){sampleType=tokens[3];if(sampleType.length>2){sampleType=sampleType.substring(0,2)}sampleType=morpheus.TcgaUtil.SAMPLE_TYPES[sampleType]}else{sampleType=morpheus.TcgaUtil.SAMPLE_TYPES["01"]}return{id:id.toLowerCase(),sampleType:sampleType}};morpheus.TcgaUtil.setIdAndSampleType=function(dataset){var idVector=dataset.getColumnMetadata().get(0);var participantId=dataset.getColumnMetadata().add("participant_id");var sampleType=dataset.getColumnMetadata().add("sample_type");for(var i=0,size=idVector.size();imaxColumns){maxColumns=datasets[i].getColumnCount();maxIndex=i}if(datasets[i].getName()==="mutations_merged.maf"){maxColumns=Number.MAX_VALUE;maxIndex=i}}var datasetIndices=[];datasetIndices.push(maxIndex);for(var i=0;i1){for(var i=1;istandardDeviation){returnValue=minStdev}if(returnValue=groupingValue){aHit++}else{aMiss++}}}var bHit=0;var bMiss=0;for(var j=0,size=listTwo.size();j=groupingValue){bHit++}else{bMiss++}}}var N=aHit+aMiss+bHit+bMiss;var K=aHit+bHit;var n=aHit+aMiss;var k=aHit;var a=k;var b=K-k;var c=n-k;var d=N+k-n-K;return[a,b,c,d]};morpheus.FisherExact=function(listOne,listTwo){var abcd=morpheus.createContingencyTable(listOne,listTwo,1);return morpheus.FisherExact.fisherTest(abcd[0],abcd[1],abcd[2],abcd[3])};morpheus.createFisherExact=function(groupingValue){var f=function(listOne,listTwo){var abcd=morpheus.createContingencyTable(listOne,listTwo,groupingValue);return morpheus.FisherExact.fisherTest(abcd[0],abcd[1],abcd[2],abcd[3])};return f};morpheus.FisherExact.phyper=function(a,b,c,d){return Math.exp(morpheus.FisherExact.logFactorial(a+b)+morpheus.FisherExact.logFactorial(c+d)+morpheus.FisherExact.logFactorial(a+c)+morpheus.FisherExact.logFactorial(b+d)-(morpheus.FisherExact.logFactorial(a)+morpheus.FisherExact.logFactorial(b)+morpheus.FisherExact.logFactorial(c)+morpheus.FisherExact.logFactorial(d)+morpheus.FisherExact.logFactorial(a+b+c+d)))};morpheus.FisherExact.logFactorials=[0,0,.6931471805599453,1.791759469228055,3.1780538303479458,4.787491742782046,6.579251212010101,8.525161361065415,10.60460290274525,12.801827480081469,15.104412573075516,17.502307845873887,19.987214495661885,22.552163853123425,25.19122118273868,27.89927138384089,30.671860106080672,33.50507345013689,36.39544520803305,39.339884187199495,42.335616460753485,45.38013889847691,48.47118135183523,51.60667556776438,54.78472939811232,58.00360522298052,61.261701761002,64.55753862700634,67.88974313718154,71.25703896716801];morpheus.FisherExact.logFactorial=function(k){if(k>=30){var C0=.9189385332046728;var C1=.08333333333333333;var C3=-.002777777777777778;var C5=.0007936507936507937;var C7=-.0005952380952380953;var r=1/k;var rr=r*r;return(k+.5)*Math.log(k)-k+C0+r*(C1+rr*(C3+rr*(C5+rr*C7)))}return morpheus.FisherExact.logFactorials[k]};morpheus.FisherExact.fisherTest=function(a,b,c,d){var p=morpheus.FisherExact.phyper(a,b,c,d);var sum=p;for(var _a=0,n=a+b+c+d;_a<=n;_a++){var _b=a+b-_a;var _c=a+c-_a;var _d=b+d-_b;if(_a!==a&&_b>=0&&_c>=0&&_d>=0){var _p=morpheus.FisherExact.phyper(_a,_b,_c,_d);if(_p<=p){sum+=_p}}}return Math.min(1,sum)};morpheus.FisherExact.toString=function(){return"Fisher Exact Test"};morpheus.FoldChange=function(list1,list2){var m1=morpheus.Mean(list1);var m2=morpheus.Mean(list2);return m1/m2};morpheus.FoldChange.toString=function(){return"Fold Change"};morpheus.MeanDifference=function(list1,list2){var m1=morpheus.Mean(list1);var m2=morpheus.Mean(list2);var diff=m1-m2;return diff};morpheus.MeanDifference.toString=function(){return"Mean Difference"};morpheus.TTest=function(list1,list2){var m1=morpheus.Mean(list1);var m2=morpheus.Mean(list2);var s1=Math.sqrt(morpheus.Variance(list1,m1));var s2=Math.sqrt(morpheus.Variance(list2,m2));var n1=morpheus.CountNonNaN(list1);var n2=morpheus.CountNonNaN(list2);return(m1-m2)/Math.sqrt(s1*s1/n1+s2*s2/n2)};morpheus.TTest.toString=function(){return"T-Test"};morpheus.DegreesOfFreedom=function(v1,v2,n1,n2){return(v1/n1+v2/n2)*(v1/n1+v2/n2)/(v1*v1/(n1*n1*(n1-1))+v2*v2/(n2*n2*(n2-1)))};morpheus.Spearman=function(list1,list2){var flist1=[];var flist2=[];for(var i=0,n=list1.size();i0;var y=yval>0;if(x&&y){andCount++}else if(x||y){orCount++}}if(orCount===0){return 1}return 1-andCount/orCount};morpheus.Jaccard.toString=function(){return"Jaccard distance"};morpheus.Cosine=function(listOne,listTwo){var sumX2=0;var sumY2=0;var sumXY=0;for(var i=0,size=listOne.size();iCause: ");message.push(err.message)}retDef.reject(message.join(""))});promises.push(p)});if(promises.length===0){retDef.reject("No datasets specified.")}$.when.apply($,promises).then(function(){retDef.resolve(morpheus.DatasetUtil.join(loadedDatasets,"id"))});return retDef};morpheus.DatasetUtil.annotate=function(options){var retDef=$.Deferred();var promises=[];var functions=[];var isColumns=options.isColumns;_.each(options.annotations,function(ann,annotationIndex){if(morpheus.Util.isArray(ann.file)){functions[annotationIndex]=function(dataset){(new morpheus.OpenFileTool).annotate(ann.file,dataset,isColumns,null,ann.datasetField,ann.fileField,ann.include)}}else{var result=morpheus.Util.readLines(ann.file);var fileName=morpheus.Util.getFileName(ann.file);var deferred=$.Deferred();promises.push(deferred);result.fail(function(message){deferred.reject(message)});result.done(function(lines){if(morpheus.Util.endsWith(fileName,".gmt")){var sets=(new morpheus.GmtReader).parseLines(lines);functions[annotationIndex]=function(dataset){(new morpheus.OpenFileTool).annotate(null,dataset,isColumns,sets,ann.datasetField,ann.fileField)};deferred.resolve()}else if(morpheus.Util.endsWith(fileName,".cls")){functions[annotationIndex]=function(dataset){(new morpheus.OpenFileTool).annotateCls(null,dataset,fileName,isColumns,lines)};deferred.resolve()}else{functions[annotationIndex]=function(dataset){(new morpheus.OpenFileTool).annotate(lines,dataset,isColumns,null,ann.datasetField,ann.fileField,ann.include,ann.transposed)};deferred.resolve()}})}});$.when.apply($,promises).then(function(){retDef.resolve(functions)});return retDef};morpheus.DatasetUtil.read=function(fileOrUrl,options){if(fileOrUrl==null){throw"File is null"}if(options==null){options={}}var isFile=morpheus.Util.isFile(fileOrUrl);var isString=morpheus.Util.isString(fileOrUrl);var ext=options.extension?options.extension:morpheus.Util.getExtension(morpheus.Util.getFileName(fileOrUrl));var datasetReader;var str=fileOrUrl.toString();if(ext===""&&str!=null&&str.indexOf("blob:")===0){datasetReader=options.interactive?new morpheus.Array2dReaderInteractive:new morpheus.TxtReader}else{datasetReader=morpheus.DatasetUtil.getDatasetReader(ext,options);if(datasetReader==null){datasetReader=isFile?options.interactive?new morpheus.Array2dReaderInteractive:new morpheus.TxtReader:new morpheus.GctReader}}if(isString||isFile){var deferred=$.Deferred();if(options.background){var path=morpheus.Util.getScriptPath();var blob=new Blob(["self.onmessage = function(e) {"+"importScripts(e.data.path);"+"var ext = morpheus.Util.getExtension(morpheus.Util"+".getFileName(e.data.fileOrUrl));"+"var datasetReader = morpheus.DatasetUtil.getDatasetReader(ext,"+"\te.data.options);"+"datasetReader.read(e.data.fileOrUrl, function(err,dataset) {"+"\tself.postMessage(dataset);"+"\t});"+"}"]);var blobURL=window.URL.createObjectURL(blob);var worker=new Worker(blobURL);worker.addEventListener("message",function(e){deferred.resolve(morpheus.Dataset.fromJSON(e.data));window.URL.revokeObjectURL(blobURL)},false);worker.postMessage({path:path,fileOrUrl:fileOrUrl,options:options})}else{datasetReader.read(fileOrUrl,function(err,dataset){if(err){deferred.reject(err)}else{deferred.resolve(dataset)}})}var pr=deferred.promise();pr.toString=function(){return""+fileOrUrl};return pr}else if(typeof fileOrUrl.done==="function"){return fileOrUrl}else{if(fileOrUrl.promise){return fileOrUrl}var deferred=$.Deferred();if(fileOrUrl.getRowCount){deferred.resolve(fileOrUrl)}else{deferred.resolve(morpheus.Dataset.fromJSON(fileOrUrl))}return deferred.promise()}};morpheus.DatasetUtil.toObjectArray=function(dataset,options){var columns=options.columns||[0];var columnFields=options.columnFields||["value"];if(columnFields.length!==columns.length){throw"columns.length !== columnFields.length"}var metadataFields=options.metadataFields;var rowMetadata=dataset.getRowMetadata();if(!metadataFields){metadataFields=morpheus.MetadataUtil.getMetadataNames(rowMetadata)}var vectors=morpheus.MetadataUtil.getVectors(rowMetadata,metadataFields);var array=[];for(var i=0;i0?tokens[tokens.selectionStartIndex]:"";token=$.trim(token);var seriesIndices=[];for(var i=0,nrows=dataset.getRowCount();i'+field+":",show:true})});return cb(matches)}var field=null;var semi=token.indexOf(":");if(semi>0){if(token.charCodeAt(semi-1)!==92){var possibleField=$.trim(token.substring(0,semi));if(possibleField.length>0&&possibleField[0]==='"'&&possibleField[token.length-1]==='"'){possibleField=possibleField.substring(1,possibleField.length-1)}var index=fields.indexOf(possibleField);if(index!==-1){token=$.trim(token.substring(semi+1));field=possibleField}}}var set=new morpheus.Set;var regex=new RegExp("^"+morpheus.Util.escapeRegex(token),"i");var max=10;loop:for(var k=0,nseries=seriesIndices.length;k'+field+":"+''+val+""})});if(field==null){fields.forEach(function(field){if(regex.test(field)){matches.push({value:field+":",label:''+field+":",show:true})}})}cb(matches)}};morpheus.DatasetUtil.fill=function(dataset,value,seriesIndex){seriesIndex=seriesIndex||0;for(var i=0,nrows=dataset.getRowCount(),ncols=dataset.getColumnCount();i0){newDataset.addSeries({name:dataset.getName(seriesIndex),rows:dataset.getRowCount(),columns:dataset.getColumnCount(),dataType:dataset.getDataType(seriesIndex)})}for(var i=0,nrows=dataset.getRowCount(),ncols=dataset.getColumnCount();i0){s.push(", ")}s.push(morpheus.Util.nf(dataset.getValue(i,j,seriesIndex)))}s.push("\n")}return s.join("")};morpheus.DatasetUtil.getNonEmptyRows=function(dataset){var rowsToKeep=[];for(var i=0,nrows=dataset.getRowCount();i0}};morpheus.Util.extend(morpheus.CombinedFilter,morpheus.Events);morpheus.IndexFilter=function(acceptIndicesSet,name,isColumns){this.acceptIndicesSet=acceptIndicesSet;this.name=name;this.columns=isColumns};morpheus.IndexFilter.prototype={enabled:true,isColumns:function(){return this.columns},isEnabled:function(){return this.enabled},setAcceptIndicesSet:function(acceptIndicesSet){this.acceptIndicesSet=acceptIndicesSet},setEnabled:function(enabled){this.enabled=enabled},equals:function(filter){return filter instanceof morpheus.IndexFilter&&this.acceptIndicesSet.equals(filter.acceptIndicesSet)},init:function(dataset){},toString:function(){return this.name},accept:function(index){return this.acceptIndicesSet.has(index)}};morpheus.VectorFilter=function(set,maxSetSize,name,isColumns){this.set=set;this.name=name;this.maxSetSize=maxSetSize;this.columns=isColumns};morpheus.VectorFilter.prototype={enabled:true,isColumns:function(){return this.columns},isEnabled:function(){return this.enabled&&this.set.size()>0&&this.set.size()!==this.maxSetSize&&this.vector!=null},setEnabled:function(enabled){this.enabled=enabled},equals:function(filter){return filter instanceof morpheus.VectorFilter&&this.name===filter.name},init:function(dataset){this.vector=dataset.getRowMetadata().getByName(this.name)},toString:function(){return this.name},accept:function(index){return this.set.has(this.vector.getValue(index))}};morpheus.NotNullFilter=function(name,isColumns){this.name=name;this.columns=isColumns};morpheus.NotNullFilter.prototype={enabled:true,isColumns:function(){return this.columns},isEnabled:function(){return this.enabled&&this.vector!=null},setEnabled:function(enabled){this.enabled=enabled},equals:function(filter){return filter instanceof morpheus.NotNullFilter&&this.name===filter.name},init:function(dataset){this.vector=dataset.getRowMetadata().getByName(this.name)},toString:function(){return this.name},accept:function(index){return this.vector.getValue(index)!=null}};morpheus.RangeFilter=function(min,max,name,isColumns){this.min=min;this.max=max;this.name=name;this.columns=isColumns};morpheus.RangeFilter.prototype={enabled:true,isColumns:function(){return this.columns},isEnabled:function(){return this.enabled&&(!isNaN(this.min)||!isNaN(this.max))&&this.vector},setEnabled:function(enabled){this.enabled=enabled},setMin:function(value){this.min=isNaN(value)?-Number.MAX_VALUE:value},setMax:function(value){this.max=isNaN(value)?Number.MAX_VALUE:value},equals:function(filter){return filter instanceof morpheus.RangeFilter&&this.name===filter.name},init:function(dataset){this.vector=dataset.getRowMetadata().getByName(this.name)},toString:function(){return this.name},accept:function(index){var value=this.vector.getValue(index);return value>=this.min&&value<=this.max}};morpheus.TopNFilter=function(n,direction,name,isColumns){this.n=n;this.direction=direction;this.name=name;this.columns=isColumns};morpheus.TopNFilter.TOP=0;morpheus.TopNFilter.BOTTOM=1;morpheus.TopNFilter.TOP_BOTTOM=2;morpheus.TopNFilter.prototype={enabled:true,isColumns:function(){return this.columns},isEnabled:function(){return this.enabled&&this.n>0&&this.vector},setEnabled:function(enabled){this.enabled=enabled},setN:function(value){this.n=value},setDirection:function(direction){this.direction=direction},equals:function(filter){return filter instanceof morpheus.TopNFilter&&this.name===filter.name&&this.n===filter.n&&this.direction===filter.direction},init:function(dataset){if(!this.vector||this.vector!==dataset.getRowMetadata().getByName(this.name)){var vector=dataset.getRowMetadata().getByName(this.name);if(vector==null){vector={getValue:function(){},size:function(){return 0}}}this.vector=vector;var set=new morpheus.Set;for(var i=0,size=vector.size();i=topAndBottomValues[0]}}else if(this.direction===morpheus.TopNFilter.BOTTOM){this.f=function(val){return isNaN(val)?false:val<=topAndBottomValues[1]}}else{this.f=function(val){return isNaN(val)?false:val>=topAndBottomValues[0]||val<=topAndBottomValues[1]}}},accept:function(index){return this.f(this.vector.getValue(index))},toString:function(){return this.name}};morpheus.AlwaysTrueFilter=function(){};morpheus.AlwaysTrueFilter.prototype={isEnabled:function(){return false},setEnabled:function(enabled){},equals:function(filter){return filter instanceof morpheus.AlwaysTrueFilter},init:function(dataset){},toString:function(){return"AlwaysTrue"},accept:function(index){return true}};morpheus.CombinedFilter.fromJSON=function(combinedFilter,json){combinedFilter.setAnd(json.isAnd);json.filters.forEach(function(filter){var name=filter.name!=null?filter.name:filter.field;if(filter.type==="set"){var set=new morpheus.Set;filter.values.forEach(function(value){set.add(value)});combinedFilter.add(new morpheus.VectorFilter(set,filter.maxSetSize,name,filter.isColumns))}else if(filter.type==="range"){combinedFilter.add(new morpheus.RangeFilter(filter.min,filter.max,name,filter.isColumns))}else if(filter.type==="top"){if(_.isString(filter.direction)){if(filter.direction==="top"){filter.direction=morpheus.TopNFilter.TOP}else if(filter.direction==="bottom"){filter.direction=morpheus.TopNFilter.BOTTOM}else if(filter.direction==="topAndBottom"){filter.direction=morpheus.TopNFilter.TOP_BOTTOM}}combinedFilter.add(new morpheus.TopNFilter(filter.n,filter.direction,name,filter.isColumns))}else if(filter.type==="index"){var set=new morpheus.Set;filter.indices.forEach(function(value){set.add(value)});combinedFilter.add(new morpheus.IndexFilter(set,name,filter.isColumns))}else{console.log("Unknown filter type")}})};morpheus.CombinedFilter.toJSON=function(filter){var json={isAnd:filter.isAnd(),filters:[]};filter.getFilters().forEach(function(filter){if(filter.isEnabled()){if(filter instanceof morpheus.VectorFilter){json.filters.push({name:filter.name,isColumns:filter.isColumns(),values:filter.set.values(),maxSetSize:filter.maxSetSize,type:"set"})}else if(filter instanceof morpheus.RangeFilter){json.filters.push({name:filter.name,isColumns:filter.isColumns(),min:filter.min,max:filter.max,type:"range"})}else if(filter instanceof morpheus.TopNFilter){json.filters.push({name:filter.name,isColumns:filter.isColumns(),n:filter.n,direction:filter.direction,type:"top"})}else if(filter instanceof morpheus.IndexFilter){json.filters.push({name:filter.name,isColumns:filter.isColumns(),indices:filter.acceptIndicesSet.values(),type:"index"})}}});return json};morpheus.IndexMapper=function(project,isRows){this.project=project;this.isRows=isRows;this.sortKeys=[];this.modelToView=null;this.filteredModelIndices=null;this.filteredSortedModelIndices=null;this.filter=new morpheus.CombinedFilter(true);this._filter();this._sort()};morpheus.IndexMapper.prototype={convertModelIndexToView:function(modelIndex){var index=this.modelToView.get(modelIndex);return index!==undefined?index:-1},convertViewIndexToModel:function(viewIndex){return viewIndex=0?this.filteredSortedModelIndices[viewIndex]:-1},convertToView:function(){return this.filteredSortedModelIndices},setFilter:function(filter){this.filter=filter;this._filter();this._sort()},_filter:function(){var filter=this.filter;var dataset=this.project.getFullDataset();var count=this.isRows?dataset.getRowCount():dataset.getColumnCount();var filteredModelIndices;if(filter!=null){filter.init(dataset);if(filter.isEnabled()){filteredModelIndices=[];for(var i=0;i0){var dataset=this.project.getFullDataset();var nkeys=sortKeys.length;for(var i=0;i=this.indices.length){throw"index out of bounds"}return this.model.get(this.indices[index])},remove:function(index){if(index<0||index>=this.indices.length){throw"index out of bounds"}var v=this.model.remove(this.indices[index]);this.indices.splice(index,1);return v},getByName:function(name){var index=morpheus.MetadataUtil.indexOf(this,name);return index!==-1?this.get(index):undefined}};morpheus.Util.extend(morpheus.MetadataModelColumnView,morpheus.MetadataModelAdapter);morpheus.MetadataModelItemView=function(model,indices){this.model=model;this.indices=indices};morpheus.MetadataModelItemView.prototype={add:function(name){var v=this.model.add(name);return new morpheus.SlicedVector(v,this.indices)},getItemCount:function(){return this.indices.length},get:function(index){var v=this.model.get(index);if(v===undefined){return undefined}return new morpheus.SlicedVector(v,this.indices)},getByName:function(name){var v=this.model.getByName(name);if(v===undefined){return undefined}return new morpheus.SlicedVector(v,this.indices)},getMetadataCount:function(){return this.model.getMetadataCount()}};morpheus.Util.extend(morpheus.MetadataModelItemView,morpheus.MetadataModelAdapter);morpheus.MetadataModel=function(itemCount){this.itemCount=itemCount;this.vectors=[]};morpheus.MetadataModel.prototype={add:function(name,options){var index=morpheus.MetadataUtil.indexOf(this,name);var oldVector;if(index!==-1){oldVector=this.get(index)}var v=new morpheus.Vector(name,this.getItemCount());if(oldVector!=null){for(var i=0,size=oldVector.size();i0?tokens[tokens.selectionStartIndex]:"";token=$.trim(token);var fieldSearchFieldName=null;if(token!==""){var semi=token.indexOf(":");if(semi>0){if(token.charCodeAt(semi-1)!==92){var possibleField=$.trim(token.substring(0,semi));if(possibleField.length>0&&possibleField[0]==='"'&&possibleField[token.length-1]==='"'){possibleField=possibleField.substring(1,possibleField.length-1)}var index=morpheus.MetadataUtil.indexOf(searchModel,possibleField);if(index!==-1){fieldSearchFieldName=possibleField;token=$.trim(token.substring(semi+1));searchModel=new morpheus.MetadataModelColumnView(model,[index])}}}var set=new morpheus.Set;regex=new RegExp(morpheus.Util.escapeRegex(token),"i");regexMatch=new RegExp("("+morpheus.Util.escapeRegex(token)+")","i");var max=10;var vectors=[];var isArray=[];for(var j=0;j'+field+":"+""+val.replace(regexMatch,"$1")+""})})}if(regex==null){regex=new RegExp(".*","i")}for(var j=0;j'+(regexMatch==null?field:field.replace(regexMatch,"$1"))+":"+(dataType==="number"?".., >, <, >=, <=,'+" =":""),show:true})}}}cb(matches)}};morpheus.MetadataUtil.getMetadataNames=function(metadataModel){var names=[];for(var i=0,count=metadataModel.getMetadataCount();i>1;var midVal=this.getPosition(mid);var size=this.getItemSize(mid);if(midVal<=position&&positionposition){high=mid-1}else{return mid}}return-1},binaryInExactSearch:function(position){var low=0;var high=this.getLength()-1;var maxIndex=this.getLength()-1;if(position<=this.getPosition(0)){return 0}while(low<=high){var mid=low+high>>1;var midVal=this.getPosition(mid);var size=this.getItemSize(mid);var nextStart=maxIndex===mid?midVal+size:this.getPosition(mid+1);if(midVal<=position&&positionposition){high=mid-1}else{return mid}}return low-1}};morpheus.Util.extend(morpheus.Positions,morpheus.Events);morpheus.Project=function(dataset){this.originalDataset=dataset;this.rowIndexMapper=new morpheus.IndexMapper(this,true);this.columnIndexMapper=new morpheus.IndexMapper(this,false);this.groupRows=[];this.groupColumns=[];this.rowColorModel=new morpheus.VectorColorModel;this.columnColorModel=new morpheus.VectorColorModel;this.rowShapeModel=new morpheus.VectorShapeModel;this.columnShapeModel=new morpheus.VectorShapeModel;this.rowFontModel=new morpheus.VectorFontModel;this.columnFontModel=new morpheus.VectorFontModel;this.hoverColumnIndex=-1;this.hoverRowIndex=-1;this.columnSelectionModel=new morpheus.SelectionModel(this,true);this.rowSelectionModel=new morpheus.SelectionModel(this,false);this.elementSelectionModel=new morpheus.ElementSelectionModel(this);this.symmetricProjectListener=null;morpheus.Project._recomputeCalculatedColumnFields(this.originalDataset,morpheus.VectorKeys.RECOMPUTE_FUNCTION_NEW_HEAT_MAP);morpheus.Project._recomputeCalculatedColumnFields(new morpheus.TransposedDatasetView(this.originalDataset),morpheus.VectorKeys.RECOMPUTE_FUNCTION_NEW_HEAT_MAP)};morpheus.Project.Events={DATASET_CHANGED:"datasetChanged",ROW_GROUP_BY_CHANGED:"rowGroupByChanged",COLUMN_GROUP_BY_CHANGED:"columnGroupByChanged",ROW_FILTER_CHANGED:"rowFilterChanged",COLUMN_FILTER_CHANGED:"columnFilterChanged",ROW_SORT_ORDER_CHANGED:"rowSortOrderChanged",COLUMN_SORT_ORDER_CHANGED:"columnSortOrderChanged",ROW_TRACK_REMOVED:"rowTrackRemoved",COLUMN_TRACK_REMOVED:"columnTrackRemoved"};morpheus.Project._recomputeCalculatedColumnFields=function(dataset,key){var metadata=dataset.getColumnMetadata();var view=new morpheus.DatasetColumnView(dataset);var nfound=0;for(var metadataIndex=0,count=metadata.getMetadataCount();metadataIndexs2.data){return 1}return 0})}for(i=0;i.4){data.setValue(ind,j,.5*(row_mean[Math.floor(ranks[i])-1]+row_mean[Math.floor(ranks[i])]))}else{data.setValue(ind,j,row_mean[Math.floor(ranks[i])-1])}}}};morpheus.QNorm.get_di_matrix=function(data){var i,j;var rows=data.getRowCount();var cols=data.getColumnCount();var dimat=[];for(j=0;j=0;i++,bottomIndex--,counter++){indexCounterPairs.push([bottomPairs[bottomIndex].index,counter])}for(var i=indexCounterPairs.length-1,j=0;i>=0;i--,j++){var item_i=indexCounterPairs[i];var item_j=indexCounterPairs[j];modelIndexToValue[item_i[0]]=item_j[1]}}for(var i=0,length=missingIndices.length;i1?morpheus.Median:function(row){return row.getValue(0)};if(this.sortOrder===morpheus.SortKey.SortOrder.TOP_N){var pairs=[];var missingIndices=[];for(var i=0,nrows=visibleModelIndices.length;i=0;i++,bottomIndex--,counter++){indexCounterPairs.push([bottomPairs[bottomIndex].index,counter])}for(var i=indexCounterPairs.length-1,j=0;i>=0;i--,j++){var item_i=indexCounterPairs[i];var item_j=indexCounterPairs[j];modelIndexToValue[item_i[0]]=item_j[1]}}for(var i=0,length=missingIndices.length;i=0){aPosMax=value>aPosMax?value:aPosMax}else{aNegMax=valuea?aNegMax:a}}return a};morpheus.SortKey.ARRAY_ASCENDING_COMPARATOR=function(summary){return function(a,b){var aNaN=a==null;var bNaN=b==null;if(aNaN&&bNaN){return 0}if(aNaN){return 1}if(bNaN){return-1}a=summary(a);b=summary(b);aNaN=isNaN(a);bNaN=isNaN(b);if(aNaN&&bNaN){return 0}if(aNaN){return 1}if(bNaN){return-1}return a===b?0:a0){var existingIndex=-1;for(var j=0;jMath.abs(max)){max=p}}return max};f.toString=function(){var s=["Maximum of "];for(var i=0,length=percentiles.length;i0&&length>2){s.push(", ")}if(i===length-1){s.push(length==2?" and ":"and ")}s.push(percentiles[i])}s.push(" percentiles");return s.join("")};return f};morpheus.CountIf=function(vector,criteria){if(!/[<>=!]/.test(criteria)){criteria='=="'+criteria+'"'}var matches=0;for(var i=0,size=vector.size();i0;i--){var bigPValue=nominalPValues[pValueIndices[i]];var smallPValue=nominalPValues[pValueIndices[i-1]];if(bigPValue==smallPValue){ranks[pValueIndices[i-1]]=ranks[pValueIndices[i]]}}for(var i=0;i=lowerOutlier){lowerAdjacentValue=Math.min(lowerAdjacentValue,value)}sum+=value}var mean=sum/values.length;if(lowerAdjacentValue>q1){lowerAdjacentValue=q1}if(upperAdjacentValue=min&&value<=max){var bin=Math.floor((value-min)/binSize);if(bin<0){bin=0}else if(bin>=numberOfBins){bin=numberOfBins-1}binNumberToOccurences[bin]++}total++}}if(cumulative){for(var i=numberOfBins-2;i>=0;i--){binNumberToOccurences[i]+=binNumberToOccurences[i+1]}}if(percent){var percents=new Float32Array(numberOfBins);for(var i=0;i1){found=true}}}if(found){for(var i=0,nrows=newValues.length;in){return true}}return false};morpheus.VectorUtil.createSpanMap=function(vector){var previous=vector.getValue(0);var startIndexToEndIndex=new morpheus.Map;var start=0;for(var i=1,nrows=vector.size();imax?value:max}}}}}else if(isArray){for(var i=0,size=vector.size();imax?value:max}}}}}else{for(var i=0,size=vector.size();imax?value:max}}}return{min:min,max:max}};morpheus.VectorUtil.getFirstNonNull=function(vector){for(var i=0,length=vector.size();i
  • Home
  • ');html.push('
  • Contact
  • ');html.push('
  • Documentation
  • ');html.push('
  • Tutorial
  • ');html.push('
  • Configuration
  • ');html.push('
  • Source Code
  • ');html.push('
  • R Interface
  • ');html.push('
  • Command Line
  • ');html.push("");this.$el=$(html.join(""));this.$el.find("[data-name=contact]").on("click",function(e){morpheus.FormBuilder.showInModal({title:"Contact",html:"Please email us at morpheus@broadinstitute.org",focus:document.activeElement});e.preventDefault()})};morpheus.HistogramLegend=function(dataset,colorScheme,metadataValue){morpheus.AbstractCanvas.call(this,true);this.colorScheme=colorScheme;this.metadataValue=metadataValue;this.dataset=dataset;this.binNumberToOccurences=null;this.setBounds({width:250,height:70});this.name=null;this.canvas.style.position="";this.canvas.style.border="1px solid LightGrey"};morpheus.HistogramLegend.prototype={binSize:0,maxCount:0,total:0,setName:function(name){this.name=name},setBinSize:function(binSize){this.binSize=binSize},buildHistogram:function(){var binSize=this.binSize;var dataset=this.dataset;var metadataValue=this.metadataValue;var colorScheme=this.colorScheme;var min=colorScheme.getMin();var max=colorScheme.getMax();if(min===max){min-=.5;max+=.5}var vector=dataset.getRowMetadata().getByName(colorScheme.getSeparateColorSchemeForRowMetadataField());var numberOfBins=Math.ceil((max-min)/binSize);var binNumberToOccurences=new Uint32Array(numberOfBins);this.binNumberToOccurences=binNumberToOccurences;var index=0;for(var i=0,nrows=dataset.getRowCount();i=numberOfBins){bin=numberOfBins-1}binNumberToOccurences[bin]++}}}var maxCount=0;var total=0;for(var i=0;i=maxCount?count:maxCount;total+=count}this.maxCount=maxCount;this.total=total},draw:function(clip,context){this.buildHistogram();var colorScheme=this.colorScheme;var canvasWidth=this.getUnscaledWidth()-50;var valueToPosition=d3.scale.linear().domain([colorScheme.getMin(),colorScheme.getMax()]).range([0,canvasWidth]).clamp(true);var histogramHeight=30;var countToPosition=d3.scale.linear().domain([0,this.maxCount/this.total]).range([histogramHeight,0]).clamp(true);var binNumberToOccurences=this.binNumberToOccurences;var min=colorScheme.getMin();var binSize=this.binSize;var y0=countToPosition(0);if(this.name!=null){context.font="11px "+morpheus.CanvasUtil.getFontFamily(context);context.fillStyle="black";context.lineWidth=1;context.fillText(this.name,.5,12);context.translate(0,14)}context.lineWidth=.2;context.strokeStyle="#D3D2C2";context.fillStyle="#D3D2C2";context.translate(25,0);context.beginPath();context.moveTo(0,y0);context.lineTo(canvasWidth,y0);context.stroke();context.lineWidth=1;context.strokeStyle="white";for(var i=0,numberOfBins=binNumberToOccurences.length;i0){count/=this.total;var start=min+i*binSize;var end=start+binSize;var x=valueToPosition(start);var width=valueToPosition(end)-x;var y=countToPosition(count);context.rect(x,y0,width,y-y0);context.fill();context.stroke()}}context.translate(0,histogramHeight+1);context.fillStyle="black";morpheus.HeatMapColorSchemeLegend.drawColorScheme(context,this.colorScheme,canvasWidth,false,false,6)}};morpheus.Util.extend(morpheus.HistogramLegend,morpheus.AbstractCanvas);morpheus.LegendWithStops=function(){var _this=this;morpheus.AbstractCanvas.call(this,false);this.setBounds({width:300,height:40});$(this.canvas).on("mousedown",function(event){var position=morpheus.CanvasUtil.getMousePos(event.target,event);_this.selectedIndex=_this.findIndexForPosition(position);_this.trigger("selectedIndex",{selectedIndex:_this.selectedIndex})});this.hammer=morpheus.Util.hammer(this.canvas,["pan"]).on("panmove",this.panmove=function(event){if(_this.selectedIndex!==-1){var position=morpheus.CanvasUtil.getMousePos(event.target,event);var fraction=_this.fractionToStopPix.invert(position.x);fraction=Math.max(0,fraction);fraction=Math.min(1,fraction);_this.trigger("moved",{fraction:fraction})}}).on("panstart",this.panstart=function(event){}).on("panend",this.panend=function(event){_this.selectedIndex=-1});$(this.canvas).on("keydown",function(e){if((e.which==8||e.which==46)&&_this.selectedIndex!==-1){_this.trigger("delete");e.preventDefault();e.stopPropagation();e.stopImmediatePropagation()}})};morpheus.LegendWithStops.prototype={border:7,stopHalfSize:5,selectedIndex:-1,destroy:function(){$(this.canvas).off("keyup").off("mousedown");this.hammer.off("panstart",this.panstart).off("panmove",this.panmove);this.hammer.destroy()},setSelectedIndex:function(index){this.selectedIndex=index},findIndexForPosition:function(position){if(position.y>=22){for(var i=0,length=this.fractions.length;i=start&&position.x<=end){return i}}}return-1},draw:function(fractions,colors,stepped,fractionToStopPix){this.fractions=fractions;this.colors=colors;this.stepped=stepped;this.fractionToStopPix=fractionToStopPix;var context=this.canvas.getContext("2d");morpheus.CanvasUtil.resetTransform(context);context.clearRect(0,0,this.getUnscaledWidth(),this.getUnscaledHeight());context.translate(this.border,0);morpheus.HeatMapColorSchemeLegend.draw(context,fractions,colors,this.getUnscaledWidth()-2*this.border,this.getUnscaledHeight()-20,stepped);context.translate(-this.border,0);context.lineWidth=1;context.strokeStyle="Grey";context.strokeRect(this.border,0,this.getUnscaledWidth()-2*this.border,this.getUnscaledHeight()-20);for(var i=0;i0&&fractions[i]===fractions[i-1]){continue}context.fillStyle=colors[i];var pix=fractionToStopPix(fractions[i]);context.fillRect(pix-this.stopHalfSize,22,this.stopHalfSize*2,this.stopHalfSize*2);if(this.selectedIndex===i){context.lineWidth=2;context.strokeStyle="black"}else{context.lineWidth=1;context.strokeStyle="Grey"}context.strokeRect(pix-this.stopHalfSize,22,this.stopHalfSize*2,this.stopHalfSize*2)}}};morpheus.Util.extend(morpheus.LegendWithStops,morpheus.AbstractCanvas);morpheus.Util.extend(morpheus.LegendWithStops,morpheus.Events);morpheus.Popup={};morpheus.Popup.initted=false;morpheus.Popup.init=function(){if(morpheus.Popup.initted){return}morpheus.Popup.initted=true;morpheus.Popup.$popupDiv=$(document.createElement("div"));morpheus.Popup.$popupDiv.css("position","absolute").css("zIndex",1050).css("overflow","auto").addClass("dropdown clearfix");morpheus.Popup.$contextMenu=$(document.createElement("ul"));morpheus.Popup.$contextMenu.addClass("dropdown-menu").css("display","block").css("position","static").css("margin-bottom","5px");morpheus.Popup.$contextMenu.appendTo(morpheus.Popup.$popupDiv);morpheus.Popup.$contextMenu.on("click","a",function(e){e.preventDefault();var $this=$(this);morpheus.Popup.popupCallback(e,$this.data("name"));morpheus.Popup.hide()})};morpheus.Popup.popupInDom=false;morpheus.Popup.hidePopupMenu=function(e){if(morpheus.Popup.component==e.target){e.preventDefault();e.stopPropagation()}morpheus.Popup.hide()};morpheus.Popup.hide=function(){morpheus.Popup.$popupDiv.hide();$(document.body).off("mousedown",morpheus.Popup.hidePopupMenu);morpheus.Popup.popupCallback=null;morpheus.Popup.component=null};morpheus.Popup.showPopup=function(menuItems,position,component,callback){morpheus.Popup.init();if(morpheus.Popup.component==component){morpheus.Popup.hide();return}morpheus.Popup.popupCallback=callback;morpheus.Popup.component=component;var html=[];for(var i=0,length=menuItems.length;i'+item.name+"")}else if(item.separator){html.push('
  • ')}else{html.push('
  • ");if(item.checked){html.push('')}html.push(item.name);if(item.icon){html.push('')}html.push("");html.push("
  • ")}}morpheus.Popup.$contextMenu.html(html.join(""));if(!morpheus.Popup.popupInDom){morpheus.Popup.popupInDom=true;morpheus.Popup.$popupDiv.appendTo($(document.body))}var $body=$(document.body);var $window=$(window);var windowWidth=$window.width();var windowHeight=$window.height();var popupWidth=morpheus.Popup.$popupDiv.width();var popupHeight=morpheus.Popup.$popupDiv.height();var left=position.x;var top=position.y;if(left+popupWidth>=windowWidth){left-=popupWidth;left=Math.max(4,left)}if(top+popupHeight>=windowHeight){top-=popupHeight;top=Math.max(4,top)}morpheus.Popup.$popupDiv.css({display:"block",left:left,top:top});morpheus.Popup.$popupDiv.show();$body.off("mousedown",morpheus.Popup.hidePopupMenu);window.setTimeout(function(){$body.on("mousedown",function(e){var $target=$(e.target);if($target[0]!==morpheus.Popup.$popupDiv[0]&&$target.data("type")!=="popup-item"){morpheus.Popup.hidePopupMenu(e)}})},1)};morpheus.RowDendrogram=function(heatMap,tree,positions,project){morpheus.AbstractDendrogram.call(this,heatMap,tree,positions,project,morpheus.AbstractDendrogram.Type.ROW)};morpheus.RowDendrogram.prototype={drawNode:function(context,node){var radius=this.getNodeRadius(node);var pix=this.toPix(node);context.beginPath();context.arc(pix[0],pix[1],radius,Math.PI*2,false);context.fill()},isDragHotSpot:function(p){return Math.abs(this.scale(this.cutHeight)-p.x)<=2},drawCutSlider:function(clip,context){if(context.setLineDash){context.setLineDash([5])}context.strokeStyle="black";var nx=this.scale(this.cutHeight);context.beginPath();context.moveTo(nx,clip.y);context.lineTo(nx,this.getUnscaledHeight());context.stroke();if(context.setLineDash){context.setLineDash([])}},getPreferredSize:function(){return{width:100,height:Math.ceil(this.positions.getPosition(this.positions.getLength()-1)+this.positions.getItemSize(this.positions.getLength()-1))}},paintMouseOver:function(clip,context){if(this.project.getHoverRowIndex()!==-1){morpheus.CanvasUtil.resetTransform(context);context.translate(0,-clip.y);this.drawRowBorder(context,this.positions,this.project.getHoverRowIndex(),this.getUnscaledWidth())}},drawRowBorder:function(context,positions,index,gridSize){var size=positions.getItemSize(index);var pix=positions.getPosition(index);context.beginPath();context.moveTo(0,pix+size);context.lineTo(gridSize,pix+size);context.stroke();context.beginPath();context.moveTo(0,pix);context.lineTo(gridSize,pix);context.stroke()},createScale:function(){return d3.scale.linear().domain([0,this.tree.maxHeight]).range([this.getUnscaledWidth(),0])},getMaxIndex:function(clip){return morpheus.Positions.getBottom(clip,this.positions)},getMinIndex:function(clip){return morpheus.Positions.getTop(clip,this.positions)},toPix:function(node){var min=this.positions.getPosition(node.minIndex)+this.positions.getItemSize(node.minIndex)/2;var max=this.positions.getPosition(node.maxIndex)+this.positions.getItemSize(node.maxIndex)/2;return[this.scale(node.height),(min+max)/2]},drawPathFromNodeToParent:function(context,node){var pix=this.toPix(node);var parentPix=this.toPix(node.parent);context.beginPath();context.moveTo(pix[0],pix[1]);context.lineTo(parentPix[0],pix[1]);context.lineTo(parentPix[0],parentPix[1]);context.stroke()},drawNodePath:function(context,node,minIndex,maxIndex){var children=node.children;var left=children[0];var right=children[1];var ry=this.toPix(right)[1];var rx=this.scale(right.height);var ly=this.toPix(left)[1];var lx=this.scale(left.height);var nx=this.scale(node.height);var x;var y;if(!this.drawLeafNodes){var leftIsLeaf=left.children!==undefined;var rightIsLeaf=right.children!==undefined;if(leftIsLeaf){lx=nx+4}if(rightIsLeaf){rx=nx+4}x=[rx,nx,nx,lx];y=[ry,ry,ly,ly]}else{x=[rx,nx,nx,lx];y=[ry,ry,ly,ly]}context.beginPath();context.moveTo(x[0],y[0]);for(var i=1,length=x.length;i=0};if(isVertical){heatMap.setToolTip(indices.length>=0?indices:null,-1,tipOptions)}else{heatMap.setToolTip(-1,indices.length>=0?indices:null,tipOptions)}};var mouseExit=function(e){document.body.style.cursor="default";scrollbar.canvas.style.cursor="default";heatMap.setToolTip(-1,-1,{event:e})};$(scrollbar.canvas).on("mousemove.morpheus",mouseMove).on("mouseout.morpheus",mouseExit)};morpheus.ScentedSearch.LINE_HEIGHT=3.5;morpheus.ScentedSearch.prototype={mouseMovedIndex:-1,getIndex:function(event){var pix=morpheus.CanvasUtil.getMousePos(event.target,event);var val=pix[this.isVertical?"y":"x"];return this.getIndexForPix(val)},getSearchIndices:function(event){var pix=morpheus.CanvasUtil.getMousePos(event.target,event);var val=pix[this.isVertical?"y":"x"];return this.getSearchIndicesForPix(val)},getSearchIndicesForPix:function(pix){var indices=this.searchIndices;if(indices==null){return[]}var scale=this.scale;var tolerance=morpheus.ScentedSearch.LINE_HEIGHT;var matches=[];for(var i=0,length=indices.length;i0){var midVal=this.positions.getPosition(indices[this.mouseMovedIndex])*scale;if(Math.abs(midVal-pix)<=tolerance){return this.mouseMovedIndex}}var low=0;var scale=this.scale;var high=indices.length-1;while(low<=high){var mid=low+high>>1;var midVal=this.positions.getPosition(indices[mid])*scale;var cmp=0;if(Math.abs(midVal-pix)<=tolerance){cmp=0}else if(midValpix){cmp=1}if(cmp<0)low=mid+1;else if(cmp>0)high=mid-1;else return mid}return-1},tap:function(position){var val=position[this.isVertical?"y":"x"];var index=this.getIndexForPix(val);this.scrollbar.canvas.style.cursor=index<0?"default":"pointer";if(index>=0){if(this.isVertical){this.heatMap.scrollTop(this.positions.getPosition(this.searchIndices[index]))}else{this.heatMap.scrollLeft(this.positions.getPosition(this.searchIndices[index]))}return true}return false},update:function(){this.searchIndices=this.model.getViewIndices().values().sort(function(a,b){return a=that.thumbPos&&position[that.field]<=that.thumbPos+that.thumbExtent;if(that.thumbMouseOver!==mouseOver){that.thumbMouseOver=mouseOver;that.repaint()}}};var mouseExit=function(e){if(!morpheus.CanvasUtil.dragging&&that.thumbMouseOver){that.thumbMouseOver=false;that.repaint()}};$(this.canvas).on("mousemove",mouseMove).on("mouseout",mouseExit).on("mouseenter",mouseMove);this.hammer=morpheus.Util.hammer(this.canvas,[this.isVertical?"panv":"panh","tap"]).on("panstart",this.panstart=function(event){var position=morpheus.CanvasUtil.getMousePos(event.target,event,true);if(position[that.field]>=that.thumbPos&&position[that.field]<=that.thumbPos+that.thumbExtent){that.draggingThumb=true;that.dragStartThumbPos=that.thumbPos}else{that.draggingThumb=false}}).on("panend",this.panend=function(event){that.draggingThumb=false}).on("panmove",this.panmove=function(event){if(that.draggingThumb){var position=morpheus.CanvasUtil.getMousePos(event.target,event);var thumbPosPix=that.dragStartThumbPos+(that.isVertical?event.deltaY:event.deltaX);var f=thumbPosPix/(that.visibleExtent-that.thumbExtent);var value=f*that.maxValue;that.setValue(value,true);event.preventDefault();event.srcEvent.stopPropagation();event.srcEvent.stopImmediatePropagation()}}).on("tap doubletap",this.tap=function(event){if(!that.draggingThumb){var position=morpheus.CanvasUtil.getMousePos(event.target,event);if(!that.decorator.tap(position)){var thumbExtentToValue=that.thumbExtent/that.totalExtent*that.totalExtent;that.scrollToTop=position[that.field]'];map.forEach(function(val,key){html.push("');html.push(key);html.push("")});html.push("");formBuilder.append({name:"selected_value",type:"custom",value:html.join("")});var shapeField=new morpheus.ShapeField({showNone:true});formBuilder.append({style:"max-width:50px;",name:"selected_shape",type:"custom",value:'
    '});shapeField.$el.appendTo(formBuilder.$form.find("[data-name=shape]"));var $valuePicker=formBuilder.$form.find("[name=valuePicker]");var selectedVal=$valuePicker.val();var _this=this;shapeField.setShapeValue(map.get(selectedVal));shapeField.on("change",function(e){map.set(selectedVal,e.shape);_this.trigger("change",{value:selectedVal,shape:e.shape})});$valuePicker.selectpicker().change(function(){selectedVal=$valuePicker.val();shapeField.setShapeValue(map.get(selectedVal))});this.$div=formBuilder.$form};morpheus.ShapeChooser.prototype={};morpheus.Util.extend(morpheus.ShapeChooser,morpheus.Events);morpheus.ShapeField=function(options){var shapes=options.shapes||morpheus.VectorShapeModel.SHAPES;var _this=this;var html=[];var size2=8;var x=4;var y=4;html.push('
    ');html.push('');html.push('
    ");var $el=$(html.join(""));var $header=$el.find("[data-name=selection]");$el.on("click","li > a",function(e){e.preventDefault();var shape=$(this).data("name");setShapeValue(shape);_this.trigger("change",{shape:shape})});var setShapeValue=function(val){if(val==="none"){$header.html("(None)")}else{var context=new C2S(size2*2,size2*2);context.translate(4,4);morpheus.CanvasUtil.drawShape(context,val,x,y,size2);$header.html(context.getSerializedSvg())}};this.setShapeValue=setShapeValue;this.$el=$el};morpheus.ShapeField.prototype={};morpheus.Util.extend(morpheus.ShapeField,morpheus.Events);morpheus.SortByValuesIndicator=function(project,isVertical,positions){morpheus.AbstractCanvas.call(this,true);this.project=project;this.isVertical=isVertical;this.positions=positions;this.lastPosition={start:-1,end:-1}};morpheus.SortByValuesIndicator.prototype={prePaint:function(clip,context){var positions=this.positions;var start=0;var end=positions.getLength();if(!this.isVertical){start=morpheus.Positions.getLeft(clip,positions);end=morpheus.Positions.getRight(clip,positions)}else{start=morpheus.Positions.getTop(clip,positions);end=morpheus.Positions.getBottom(clip,positions)}if(this.invalid||start!==this.lastPosition.start||end!==this.lastPosition.end){this.lastPosition.start=start;this.lastPosition.end=end;this.invalid=true}},draw:function(clip,context){var project=this.project;var isVertical=this.isVertical;var positions=this.positions;var sortKeys=isVertical?project.getColumnSortKeys():project.getRowSortKeys();context.translate(-clip.x,-clip.y);context.fillStyle="black";context.textBaseline="top";context.textAlign="left";context.font="8px "+morpheus.CanvasUtil.getFontFamily(context);var start=0;var end=positions.getLength();if(!isVertical){start=morpheus.Positions.getLeft(clip,positions);end=morpheus.Positions.getRight(clip,positions)}else{start=morpheus.Positions.getTop(clip,positions);end=morpheus.Positions.getBottom(clip,positions)}var arrowWidth=3;var arrowHeight=4;for(var i=0;i=start&&view');var $div=$('
    ');var html=[];html.push('
    ');html.push('
    ');html.push('
    ');html.push('
    ');html.push('
    ');html.push('
    ');html.push("
    ");html.push("
    ");html.push("
    ");$chooserDiv.html(html.join(""));function toggle(isColumns){_this.isColumns=isColumns;var $element=_this.build(project,isColumns);$div.empty().html($element);$div.on("click","[data-name=delete]",function(e){var $this=$(this);e.preventDefault();$this.closest("div.row").remove()});$div.on("click","[data-name=add]",function(e){var $this=$(this);var level=[];var $sibling=$this.closest("div.row");_this.createLevel(level,new morpheus.SortKey("",morpheus.SortKey.SortOrder.ASCENDING),_this.fields);$sibling.after($(level.join("")));e.preventDefault()})}$chooserDiv.on("change","[name=rowsOrColumns]",function(e){var $this=$(this);toggle($this.val()==="columns")});toggle(false);var $outer=$("
    ");$chooserDiv.appendTo($outer);$div.appendTo($outer);morpheus.FormBuilder.showOkCancel({title:"Sort",content:$outer,okCallback:function(){var $forms=$div.find("form");var sortBy=$forms.find("[name=sortBy]").map(function(){return $(this).val()});var lockOrder=$forms.find("[name=lockOrder]").map(function(){return $(this).prop("checked")});var sortOrder=$forms.find("[name=sortOrder]:checked").map(function(){return $(this).val()});var groupBy=$div.find("[name=groupBy]").val();var newSortKeys=[];var modelIndices=_this.isColumns?project.getRowSelectionModel().toModelIndices():project.getColumnSelectionModel().toModelIndices();var existingSortKeys=_this.isColumns?project.getColumnSortKeys():project.getRowSortKeys();for(var i=0;i');html.push('
    ');html.push('
    ');html.push('
    ');var groupByKeys=(isColumns?project.getGroupColumns():project.getGroupRows()).map(function(key){return key.field});html.push('");html.push("
    ");html.push("");var $div=$(html.join(""));$div.find(".selectpicker").selectpicker({iconBase:"fa",tickIcon:"fa-check",style:"btn-default btn-sm"});return $div},createLevel0:function(html){html.push('
    ');html.push('');html.push('
    ');html.push('Add sort level');html.push("
    ");html.push("");html.push("
    ")},createLevel:function(html,key,fields){html.push('
    ');html.push('
    ');html.push('
    ');html.push('
    ');html.push('");html.push("
    ");html.push('
    ');html.push('
    ");html.push('
    ");html.push("
    ");html.push('
    ');html.push('Delete');html.push("
    ");html.push('
    ');html.push('
    ");html.push("
    ");html.push('
    ');html.push("
    ");html.push('Add sort level');html.push("
    ");html.push("
    ");html.push("
    ")}};morpheus.SteppedColorSupplier=function(){morpheus.AbstractColorSupplier.call(this);this.hiddenValue=0;this.hiddenValues=new morpheus.Set;this.stepped=true};morpheus.SteppedColorSupplier.linearScale=function(value,input0,input1,pix0,pix1){return(value-input0)/(input1-input0)*(pix1-pix0)+pix0};morpheus.SteppedColorSupplier.prototype={createInstance:function(){return new morpheus.SteppedColorSupplier},isStepped:function(){return true},getHiddenValues:function(){return this.hiddenValues},getIndexForFraction:function(f){var fractions=this.fractions;if(f<=fractions[0]){return 0}if(f>=fractions[fractions.length-1]){return fractions.length-1}for(var i=0;i=left&&f=max){return colors[colors.length-1]}var fraction=morpheus.SteppedColorSupplier.linearScale(value,min,max,0,100)/100;return colors[this.getIndexForFraction(fraction)]}};morpheus.Util.extend(morpheus.SteppedColorSupplier,morpheus.AbstractColorSupplier);morpheus.TabManager=function(options){this.options=$.extend({},{autohideTabBar:false,rename:true},options);var _this=this;this.activeTabObject=null;this.activeTabId=null;this.idToTabObject=new morpheus.Map;this.$nav=$('');this.$nav.sortable({containment:"parent",axis:"x",helper:"clone",cancel:"li:not(.morpheus-sortable)",items:"li.morpheus-sortable"});this.$nav.sortable("disable");this.$nav.on("click","li > a",function(e){var tabId=$(this).data("link");if(tabId!=null){e.preventDefault();if(_this.activeTabId!==tabId){$(this).tab("show")}}});if(this.options.autohideTabBar){this.$nav.css("display","none")}if(options.dropTab){var html=[];html.push('");var $tabDrop=$(html.join(""));var $tabDropMenu=$tabDrop.find(".dropdown-menu");$tabDrop.appendTo(this.$nav);var updateDropTab=function(){var totalWith=_this.$nav.width()-17;var sum=0;var tabDropItems=[];_this.$nav.find("> li").each(function(){var $li=$(this);var $a=$li.find("a");if(!$li.hasClass("morpheus-tab-addon")){var title=$a.contents().first().text();var isActive=$li.hasClass("active");var href=$a.attr("href");tabDropItems.push('
  • '+title+"
  • ");sum+=$li.outerWidth();if(sum>=totalWith){$li.css("display","none")}else{$li.css("display","")}}});$tabDrop.css("display",tabDropItems.length>0?"":"none");$tabDropMenu.html(tabDropItems.join(""))};$tabDrop.css("display","none");this.$nav.on("sortstop",function(event,ui){updateDropTab()});$(window).on("resize",updateDropTab);this.$nav.on("remove",function(){$(window).off("resize",updateDropTab)});this.on("add remove rename reorder change",function(){updateDropTab()})}this.$nav.on("dblclick","li > a",function(e){e.preventDefault();var $a=$(this);var $li=$a.parent("li");if($li.hasClass("morpheus-tab-addon")){return}_this.rename($a.data("link"))});this.$nav.on("contextmenu.morpheus","li > a",function(e){e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();var $a=$(this);var $li=$a.parent("li");if($li.hasClass("morpheus-tab-addon")){return}var menuItems=[];if($a.data("morpheus-rename")&&_this.options.rename){menuItems.push({name:"Rename"})}if($a.data("morpheus-pin")){menuItems.push({name:"Unpin tab"})}else{menuItems.push({name:"Pin tab"})}if(menuItems.length>0){morpheus.Popup.showPopup(menuItems,{x:e.pageX,y:e.pageY},e.target,function(event,item){if(item==="Rename"){_this.rename($a.data("link"))}else if(item==="Pin tab"){$a.data("morpheus-pin",true);$li.removeClass("morpheus-sortable");$li.detach();_this.$nav.prepend($li);$a.find(".close").hide();_this.$nav.sortable("option","items","li.morpheus-sortable");_this.$nav.sortable("refresh")}else if(item==="Unpin tab"){$a.data("morpheus-pin",false);$li.addClass("morpheus-sortable");$a.find(".close").show();_this.$nav.sortable("option","items","li.morpheus-sortable");_this.$nav.sortable("refresh")}})}return false});this.$nav.on("click","button",function(e){e.preventDefault();var target=$(this).attr("data-target");if(target!=null){target=target.substring(1);_this.remove(target)}});this.$tabContent=$('
    ');this.$nav.on("shown.bs.tab",'a[data-toggle="tab"]',function(e){var previous=_this.activeTabId;_this.activeTabId=$(e.target).data("link");_this.activeTabObject=_this.idToTabObject.get(_this.activeTabId);_this.$nav.find("li").removeClass("active");_this.$nav.find("[data-link="+_this.activeTabId+"]").each(function(){$(this).parent().addClass("active")});var scrollTop=document.body.scrollTop;$("#"+_this.activeTabId).focus();document.body.scrollTop=scrollTop;if(_this.adding){return}_this.trigger("change",{tab:_this.activeTabId,previous:previous})})};morpheus.TabManager.prototype={getTabText:function(id){return this.$nav.find("> li > a").filter("a[data-link="+id+"]").contents().first().text()},getTabCount:function(){return this.idToTabObject.size()},setTabText:function(id,text){this.$nav.find("> li > a").filter("[data-link="+id+"]").contents().first().replaceWith(text+" ");this.idToTabObject.get(id).setName(name)},addTask:function(task){},removeTask:function(task){},getWidth:function(){return this.$tabContent.outerWidth()||$(window).width()},getActiveTab:function(){return this.activeTabObject},getActiveTabId:function(){return this.activeTabId},add:function(options){this.adding=true;var id=_.uniqueId("morpheus-tab");this.idToTabObject.set(id,options.object);var li=[];li.push('");var $link=$(li.join(""));$link.appendTo(this.$nav);var $panel=$('
    ');options.$el.appendTo($panel);$panel.appendTo(this.$tabContent);if(options.enabled===false){$link.addClass("disabled");$link.find("a").addClass("btn disabled")}if(options.focus){this.$nav.find('> li > a[data-toggle="tab"]:last').tab("show");this.activeTabId=id;this.activeTabObject=options.object;$panel.focus()}if(this.options.autohideTabBar){this.$nav.css("display",this.idToTabObject.size()>1?"":"none")}this.getTabCount()<=1?this.$nav.sortable("disable"):this.$nav.sortable("enable");this.adding=false;this.trigger("add");return{$panel:$panel,id:id}},appendTo:function($target){this.$nav.appendTo($target);this.$tabContent.appendTo($target)},remove:function(target){if(target===undefined){target=this.activeTabId}var obj=this.idToTabObject.remove(target);$("#"+target).remove();this.activeTabObject=null;this._getA(target).parent().remove();this.$tabContent.find(target).remove();var $a=this.$nav.find('> li > a[data-toggle="tab"]:last');if($a.length===0){if(this.options.landingPage){if(typeof this.options.landingPage==="function"){this.options.landingPage().show()}else{this.options.landingPage.show()}}}$a.tab("show");if(this.options.autohideTabBar){this.$nav.css("display",this.idToTabObject.size()>1?"":"none")}this.getTabCount()<=1?this.$nav.sortable("disable"):this.$nav.sortable("enable");if(this.idToTabObject.size()>0){$($a.attr("href")).focus()}if(obj!=null&&obj.onRemove){obj.onRemove()}this.trigger("remove",{tab:target})},setOptions:function(options){this.options=options;if(this.options.autohideTabBar){this.$nav.css("display",this.idToTabObject.size()>1?"":"none")}},getOptions:function(){return this.options},setActiveTab:function(id){if(id!==this.activeTabId){var $a=this._getA(id);$a.parent().removeClass("disabled");$a.removeClass("btn disabled");$a.tab("show");var previous=this.activeTabId;this.activeTabId=id;this.activeTabObject=this.idToTabObject.get(this.activeTabId);this.trigger("change",{tab:this.activeTabId,previous:previous})}},setTabTitle:function(id,title){this._getA(id).attr("title",title)},_getA:function(id){if(id[0]==="#"){id=id.substring(1)}return this.$nav.find("> li > a[data-link="+id+"]:first")},setTabEnabled:function(id,enabled){var $a=this._getA(id);if(enabled){$a.parent().removeClass("disabled");$a.removeClass("btn disabled")}else{$a.parent().addClass("disabled");$a.addClass("btn disabled")}},getIdToTabObject:function(){return this.idToTabObject},getTabObject:function(id){return this.idToTabObject.get(id)},rename:function(id){var $a=this._getA(id);var $li=$a.parent();if($li.hasClass("morpheus-tab-addon")){return}if(!$a.data("morpheus-rename")||!this.options.rename){return}var _this=this;var builder=new morpheus.FormBuilder;builder.append({name:"name",type:"text",value:$.trim($a.contents().first().text())});morpheus.FormBuilder.showOkCancel({title:"Rename Tab",content:builder.$form,focus:document.activeElement,okCallback:function(){var name=$.trim(builder.getValue("name"));if(name!==""){if(_this.activeTabObject!=null&&_this.activeTabObject.setName){_this.activeTabObject.setName(name)}$a.contents().first().replaceWith(name+" ");_this.trigger("rename")}}})}};morpheus.Util.extend(morpheus.TabManager,morpheus.Events);morpheus.Table=function(options){options=morpheus.Table.createOptions(options);this.options=options;if(!options.width){options.width=options.$el.attr("class")}var _this=this;var height=options.height;var $gridDiv=$('
    ');this.$gridDiv=$gridDiv;$gridDiv.appendTo(options.$el);var columns=options.columns;this.columns=columns;var visibleColumns=columns.filter(function(c){return c.visible});var grid=new morpheus.Grid({gridOptions:{select:options.select,rowHeight:options.rowHeight,autoEdit:false,editable:false,autoHeight:options.height==="auto",enableTextSelectionOnCells:true},$el:$gridDiv,items:options.items,columns:visibleColumns});this.grid=grid;this.searchFunction=null;var searchFilter={isEmpty:function(){return _this.searchFunction==null},init:function(){},accept:function(item){return _this.searchFunction(item)}};this.grid.getFilter().add(searchFilter);var $header=$('
    ');this.$header=$header;var $right=$header.find(".pull-right");if(options.search){var tableSearch=new morpheus.TableSearchUI({$el:$header.find("[name=top]"),$right:$right});tableSearch.setTable(this);this.tableSearch=tableSearch}if(options.columnPicker&&visibleColumns.length!==this.columns.length){var select=[];select.push('");var $select=$(select.join(""));$select.appendTo($right);$select.selectpicker({iconBase:"fa",tickIcon:"fa-check",style:"btn-default btn-xs"});$select.on("change",function(){var oldColumns=grid.getColumns().map(function(c){return c.id});var selectedColumnIndices=$select.val();visibleColumns=[];for(var i=0;ioldColumns.length){var set=new morpheus.Set;for(var i=0;i1){collapsed=true;$gridDiv.addClass("slick-stacked");_this.grid.grid.getOptions().rowHeight=(options.collapsedRowHeight?options.collapsedRowHeight:options.rowHeight)*visibleColumns.length;_this.grid.grid.setColumns([{id:0,tooltip:function(item,value){var html=[];for(var i=0;i")},collapsed:true,getter:function(item){return item},formatter:function(row,cell,value,columnDef,dataContext){var html=[];html.push('
    ');if(options.rowHeader){html.push(options.rowHeader(dataContext));html.push('
    ')}for(var i=0;i0){html.push('
    ')}var c=visibleColumns[i];html.push(c.name);html.push(":");var s=c.renderer(dataContext,c.getter(dataContext));html.push(s)}html.push("
    ");return html.join("")},sortable:false,name:""}]);$gridDiv.find(".slick-header").hide();_this.grid.grid.resizeCanvas();_this.grid.grid.invalidate()}else if(collapsed&&gridWidth>=options.collapseBreakpoint){$gridDiv.removeClass("slick-stacked");collapsed=false;if(options.showHeader){$gridDiv.find(".slick-header").show()}_this.grid.grid.getOptions().rowHeight=options.rowHeight;_this.grid.grid.setColumns(visibleColumns);_this.grid.grid.resizeCanvas();if(options.select){_this.grid.grid.setSelectedRows(_this.grid.grid.getSelectedRows())}_this.grid.grid.invalidate()}else{_this.grid.grid.resizeCanvas();_this.grid.grid.invalidate()}_this.grid.maybeAutoResizeColumns()};if(!options.showHeader){$gridDiv.find(".slick-header").hide()}if(options.responsive){$(window).on("resize orientationchange",resize);$gridDiv.on("remove",function(){$(window).off("resize",resize)});resize()}this.resize=resize;if(visibleColumns.length>1&&options.items!=null&&options.items.length>0){this.setItems(options.items)}if(!$gridDiv.is(":visible")){var $parent=$gridDiv;var observer=new MutationObserver(function(mutations){if(window.getComputedStyle($parent[0]).display!=="none"){observer.disconnect();resize()}});while($parent.length>0){if(window.getComputedStyle($parent[0]).display==="none"){break}$parent=$parent.parent()}if($parent.length>0){observer.observe($parent[0],{attributes:true,childList:false,characterData:false})}}};morpheus.Table.defaultRenderer=function(item,value){if(value==null){return""}else if(_.isNumber(value)){return morpheus.Util.nf(value)}else if(morpheus.Util.isArray(value)){var s=[];for(var i=0,length=value.length;i0){s.push(", ")}var val=value[i];s.push(value[i])}return s.join("")}else{return""+value}};morpheus.Table.prototype={toText:function(){var text=[];var items=this.getItems();var columns=this.columns.filter(function(c){return c.visible});for(var j=0;j0){text.push("\t")}text.push(columns[j].name)}text.push("\n");for(var i=0;i0){text.push("\t")}var value=columns[j].getter(item);text.push(morpheus.Util.toString(value))}text.push("\n")}return text.join("")},setHeight:function(height){this.options.height=height;if(height==="auto"){this.$gridDiv.css("height","");this.grid.grid.getOptions().autoHeight=true;this.grid.grid.setOptions(this.grid.grid.getOptions())}else{this.$gridDiv.css("height",height)}this.grid.grid.resizeCanvas();if(height==="auto"){var height=this.getItems().length*this.options.rowHeight+this.options.rowHeight;this.$gridDiv.find(".slick-viewport").css("height",height+"px")}this.grid.grid.invalidate()},setSearchVisible:function(visible){this.$header.find("[name=search]").css("display",visible?"":"none")},autocomplete:function(tokens,response){var matches=[];var token=tokens!=null&&tokens.length>0?tokens[tokens.selectionStartIndex]:"";token=$.trim(token);var columns=this.columns.filter(function(c){return c.searchable&&c.visible||c.alwaysSearch});var ncolumns=columns.length;var showField=ncolumns>1;if(token===""){if(ncolumns<=1){return response(matches)}for(var i=0;i'+field+":",show:true})}matches.sort(function(a,b){return a.value===b.value?0:a.value0){if(token.charCodeAt(semi-1)!==92){var possibleField=$.trim(token.substring(0,semi));if(possibleField.length>0&&possibleField[0]==='"'&&possibleField[token.length-1]==='"'){possibleField=possibleField.substring(1,possibleField.length-1)}var columnNameToColumn=new morpheus.Map;var columnNames=columns.map(function(c){return c.name});for(var i=0;i1){var regex=new RegExp("^"+morpheus.Util.escapeRegex(token),"i");for(var j=0;j'+field+":",show:true})}}}var set=new morpheus.Set;var regex=new RegExp("^"+morpheus.Util.escapeRegex(token),"i");var items=this.getItems();var dataTypes=[];var filteredColumns=[];columns.forEach(function(c){var dataType=null;for(var i=0,nitems=items.length;i'+field+":"+''+val+"":''+val+""})}if(matches.length===maxSize){return response(matches)}}}else{if(regex.test(value)&&!set.has(value)){set.add(value);matches.push({value:showField?field+":"+value:value,label:showField?''+field+":"+''+value+"":''+value+""});if(matches.length===maxSize){return response(matches)}}}}}return response(matches)},searchWithPredicates:function(predicates){if(predicates==null||predicates.length===0){this.searchFunction=null;this.grid.setFilter(this.grid.getFilter());return}var columns=this.columns.filter(function(c){return c.searchable&&c.visible||c.alwaysSearch});var columnNameToColumn=new morpheus.Map;var columnNames=columns.map(function(c){return c.name});for(var i=0;i
    ');if(options.rowHeader&&cell===0){html.push(options.rowHeader(dataContext))}html.push(column.renderer(dataContext,value));html.push("
    ");return html.join("")},comparator:function(a,b){var aNaN=a==null||_.isNumber(a)&&isNaN(a);var bNaN=b==null||_.isNumber(b)&&isNaN(b);if(aNaN&&bNaN){return 0}if(aNaN){return 1}if(bNaN){return-1}if(a.toLowerCase){a=a.toLowerCase()}if(b.toLowerCase){b=b.toLowerCase()}return a===b?0:a');$search.appendTo(options.$el);this.$search=$search;this.$searchResults=$('');this.$showAll=$('
    Show'+" all
    ");this.$searchResults.appendTo(options.$right);this.$showAll.appendTo(options.$right);this.$showAll.on("click",function(e){e.preventDefault();$search.val("");_this.table.search("");_this.table.trigger("showAll",{table:_this.table})});$search.on("keyup",_.debounce(function(){_this.table.search($.trim($(this).val()))},100));morpheus.Util.autosuggest({$el:$search,suggestWhenEmpty:true,filter:function(tokens,response){_this.table.autocomplete(tokens,response)},select:function(){_this.table.search($.trim($search.val()))}})};morpheus.TableSearchUI.prototype={updateSearchLabel:function(){var text="Showing: "+morpheus.Util.intFormat(this.table.getFilteredItemCount())+" / "+morpheus.Util.intFormat(this.table.getAllItemCount());this.$searchResults.html(text)},setTable:function(table){this.table=table;var _this=this;table.on("filter",function(){_this.updateSearchLabel()})}};morpheus.TrackSelection=function(track,positions,selectionModel,isColumns,heatMap){var canvas=track.canvas;var startIndex=-1;var coord=isColumns?"x":"y";function getPosition(event,useDelta){if(track.settings.squished){var total=positions.getPosition(positions.getLength()-1)+positions.getItemSize(positions.getLength()-1);var squishFactor=total/(isColumns?track.getUnscaledWidth():track.getUnscaledHeight());var clientXY=morpheus.CanvasUtil.getClientXY(event,useDelta);var p=morpheus.CanvasUtil.getMousePosWithScroll(event.target,event,0,0,useDelta);p[coord]*=squishFactor;return p}else{return morpheus.CanvasUtil.getMousePosWithScroll(event.target,event,heatMap.scrollLeft(),heatMap.scrollTop(),useDelta)}}var panning=false;var scrollIntervalId;var lastScrollTime=(new Date).getTime();var _this=this;var throttlePanMove=50;function mouseleave(e){var scroll=function(){var now=(new Date).getTime();var rect=canvas.getBoundingClientRect();var doPan=false;if(!isColumns){if(e.clientY>rect.bottom||e.clientYrect.right||e.clientXendIndex){var tmp=endIndex;endIndex=_startIndex;_startIndex=tmp}for(var i=_startIndex;i<=endIndex;i++){viewIndices.add(i)}selectionModel.setViewIndices(viewIndices,true);if(!isColumns){var scrollTop=heatMap.scrollTop();var heatMapHeight=heatMap.heatmap.getUnscaledHeight();var scrollBottom=scrollTop+heatMapHeight;if(position.y>scrollBottom){heatMap.scrollTop(position.y+8-heatMapHeight)}else if(position.yscrollRight){heatMap.scrollLeft(position.x+8-heatMapWidth)}else if(position.x1){if(isColumns&&!heatMap.options.columnsSortable||!isColumns&&!heatMap.options.rowsSortable){return}heatMap.sortBasedOnSelection(null,isColumns,event.srcEvent.shiftKey)}else{heatMap.setSelectedTrack(track.name,isColumns);var commandKey=morpheus.Util.IS_MAC?event.srcEvent.metaKey:event.srcEvent.ctrlKey;if(morpheus.Util.IS_MAC&&event.srcEvent.ctrlKey){return}var viewIndices;if(commandKey){viewIndices=selectionModel.getViewIndices();if(viewIndices.has(index)){viewIndices.remove(index)}else{viewIndices.add(index)}}else if(event.srcEvent.shiftKey){viewIndices=selectionModel.getViewIndices();var min=Number.MAX_VALUE;var max=-Number.MAX_VALUE;viewIndices.forEach(function(viewIndex){min=Math.min(viewIndex,min);max=Math.max(viewIndex,max)});if(index>=max){for(var i=max;i<=index;i++){viewIndices.add(i)}}else{for(var i=Math.min(index,min),max=Math.max(index,min);i<=max;i++){viewIndices.add(i)}}}else{viewIndices=new morpheus.Set;viewIndices.add(index)}selectionModel.setViewIndices(viewIndices,true)}})};morpheus.TrackSelection.prototype={dispose:function(){this.hammer.off("longpress",this.longpress).off("panstart",this.panstart).off("panmove",this.panmove).off("panend",this.panend).off("tap",this.tap).off("doubletap",this.tap);this.hammer.destroy()}};morpheus.VectorTrackHeader=function(project,name,isColumns,heatMap){morpheus.AbstractCanvas.call(this);this.font={weight:"400"};this.project=project;this.name=name;this.isColumns=isColumns;var canvas=this.canvas;this.heatMap=heatMap;this.selectedBackgroundColor="#c8c8c8";this.backgroundColor="rgb(255,255,255)";var vector=(isColumns?project.getFullDataset().getColumnMetadata():project.getFullDataset().getRowMetadata()).getByName(name);if(vector&&vector.getProperties().has(morpheus.VectorKeys.TITLE)){this.canvas.setAttribute("title",vector.getProperties().get(morpheus.VectorKeys.TITLE));$(this.canvas).tooltip()}var _this=this;this.setBounds({height:this.defaultFontHeight+morpheus.VectorTrackHeader.FONT_OFFSET});function getResizeCursor(pos){if(isColumns){if(pos.y<3){return{cursor:"ns-resize",isPrevious:true}}if(pos.y>=_this.getUnscaledHeight()-3){return{cursor:"ns-resize",isPrevious:false}}if(pos.x>=_this.getUnscaledWidth()-3){return{isPrevious:false,cursor:"ew-resize"}}}else{if(pos.x<3&&heatMap.getTrackIndex(name,isColumns)>0){return{cursor:"ew-resize",isPrevious:true}}if(pos.x>=_this.getUnscaledWidth()-3){return{cursor:"ew-resize",isPrevious:false}}}}var mouseMove=function(event){if(!morpheus.CanvasUtil.dragging){var pos=morpheus.CanvasUtil.getMousePos(event.target,event);var resizeCursor=getResizeCursor(pos);canvas.style.cursor=resizeCursor==null?"default":resizeCursor.cursor;_this.isMouseOver=true;_this.repaint()}};var mouseExit=function(e){if(!morpheus.CanvasUtil.dragging){canvas.style.cursor="default"}_this.isMouseOver=false;_this.repaint()};var showPopup=function(e){heatMap.setSelectedTrack(_this.name,isColumns);var track=heatMap.getTrack(_this.name,isColumns);if(!track){throw _this.name+" track not found"}e.preventDefault();if(e.stopPropagation){e.stopPropagation()}if(e.stopImmediatePropagation){e.stopImmediatePropagation()}track.showPopup(e,true);return false};$(this.canvas).css({"background-color":this.backgroundColor}).on("mousemove.morpheus",mouseMove).on("mouseout.morpheus",mouseExit).on("mouseenter.morpheus",mouseMove).on("contextmenu.morpheus",showPopup).addClass("morpheus-track-header "+(isColumns?"morpheus-columns":"morpheus-rows"));var resizeCursor;var dragStartWidth=0;var dragStartHeight=0;var reorderingTrack=false;var dragStartPosition;var resizeTrackName;this.hammer=morpheus.Util.hammer(canvas,["pan","tap","longpress"]).on("longpress",this.longpress=function(event){event.preventDefault();heatMap.setSelectedTrack(_this.name,isColumns);var track=heatMap.getTrack(_this.name,isColumns);track.showPopup(event.srcEvent,true)}).on("panend",this.panend=function(event){_this.isMouseOver=false;morpheus.CanvasUtil.dragging=false;canvas.style.cursor="default";var index=heatMap.getTrackIndex(_this.name,isColumns);var header=heatMap.getTrackHeaderByIndex(index,isColumns);var track=heatMap.getTrackByIndex(index,isColumns);var $canvas=$(track.canvas);$canvas.css("z-index","0");$(header.canvas).css("z-index","0");heatMap.revalidate()}).on("panstart",this.panstart=function(event){_this.isMouseOver=false;if(morpheus.CanvasUtil.dragging){return}if(resizeCursor!=null){morpheus.CanvasUtil.dragging=true;canvas.style.cursor=resizeCursor.cursor;if(resizeCursor.isPrevious){var index=heatMap.getTrackIndex(_this.name,isColumns);index--;if(index===-1){index=0}var header=heatMap.getTrackHeaderByIndex(index,isColumns);dragStartWidth=header.getUnscaledWidth();dragStartHeight=header.getUnscaledHeight();resizeTrackName=header.name}else{resizeTrackName=null;dragStartWidth=_this.getUnscaledWidth();dragStartHeight=_this.getUnscaledHeight()}event.preventDefault();reorderingTrack=false}else{var index=heatMap.getTrackIndex(_this.name,isColumns);if(index==-1){throw _this.name+" not found"}var header=heatMap.getTrackHeaderByIndex(index,isColumns);var track=heatMap.getTrackByIndex(index,isColumns);heatMap.setSelectedTrack(_this.name,isColumns);var $canvas=$(track.canvas);dragStartPosition=$canvas.position();$canvas.css("z-index","100");$(header.canvas).css("z-index","100");morpheus.CanvasUtil.dragging=true;resizeCursor=undefined;reorderingTrack=true}}).on("panmove",this.panmove=function(event){_this.isMouseOver=false;if(resizeCursor!=null){var width;var height;if(resizeCursor.cursor==="ew-resize"){var dx=event.deltaX;width=Math.max(8,dragStartWidth+dx)}if(resizeCursor.cursor==="ns-resize"){var dy=event.deltaY;height=Math.max(8,dragStartHeight+dy)}heatMap.resizeTrack(resizeTrackName==null?_this.name:resizeTrackName,width,height,isColumns)}else if(reorderingTrack){var index=heatMap.getTrackIndex(_this.name,isColumns);var header=heatMap.getTrackHeaderByIndex(index,isColumns);var track=heatMap.getTrackByIndex(index,isColumns);var ntracks=heatMap.getNumTracks(isColumns);var delta=isColumns?event.deltaY:event.deltaX;var newIndex=index+(delta>0?1:-1);newIndex=Math.min(Math.max(0,newIndex),ntracks-1);var prop=isColumns?"top":"left";var w=isColumns?"getUnscaledHeight":"getUnscaledWidth";var trackBounds={};trackBounds[prop]=dragStartPosition[prop]+delta;track.setBounds(trackBounds);header.setBounds(trackBounds);var dragOverTrack=heatMap.getTrackByIndex(newIndex,isColumns);var dragOverWidth=dragOverTrack[w]();var dragOverLeft=$(dragOverTrack.canvas).position()[prop];var dragleft=dragStartPosition[prop]+delta;var dragright=dragleft+track[w]();if(delta>0&&dragright>=dragOverLeft+dragOverWidth/2||delta<0&&dragleft<=dragOverLeft+dragOverWidth/2){if(index!==newIndex){heatMap.moveTrack(index,newIndex,isColumns);var otherHeader=heatMap.getTrackHeaderByIndex(index,isColumns);var otherTrack=heatMap.getTrackByIndex(index,isColumns);var $movedCanvas=$(otherTrack.canvas);var newLeft=$movedCanvas.position()[prop];if(delta<0){newLeft+=track[w]()}else{newLeft-=track[w]()}var otherBounds={};otherBounds[prop]=newLeft;otherTrack.setBounds(otherBounds);otherHeader.setBounds(otherBounds)}}}}).on("tap",this.tap=function(event){if(morpheus.Util.IS_MAC&&event.srcEvent.ctrlKey){return}_this.isMouseOver=false;heatMap.setSelectedTrack(_this.name,isColumns);var vector=(isColumns?project.getFullDataset().getColumnMetadata():project.getFullDataset().getRowMetadata()).getByName(name);if(isColumns&&!heatMap.options.columnsSortable||vector==null){return}if(!isColumns&&!heatMap.options.rowsSortable||vector==null){return}var additionalSort=event.srcEvent.shiftKey;var isGroupBy=false;var existingSortKeyIndex=_this.getSortKeyIndexForColumnName(_this.getSortKeys(),_this.name);var sortOrder;var sortKey;var dataType=morpheus.VectorUtil.getDataType(vector);if(existingSortKeyIndex!=null){sortKey=_this.getSortKeys()[existingSortKeyIndex.index];if(sortKey.getSortOrder()===morpheus.SortKey.SortOrder.UNSORTED){sortOrder=morpheus.SortKey.SortOrder.ASCENDING}else if(sortKey.getSortOrder()===morpheus.SortKey.SortOrder.ASCENDING){sortOrder=morpheus.SortKey.SortOrder.DESCENDING}else if(sortKey.getSortOrder()===morpheus.SortKey.SortOrder.TOP_N){sortOrder=morpheus.SortKey.SortOrder.UNSORTED}else{sortOrder=dataType==="number"||dataType==="[number]"?morpheus.SortKey.SortOrder.TOP_N:morpheus.SortKey.SortOrder.UNSORTED}}else{sortKey=new morpheus.SortKey(_this.name,morpheus.SortKey.SortOrder.ASCENDING);sortOrder=morpheus.SortKey.SortOrder.ASCENDING}if(sortKey!=null){sortKey.setSortOrder(sortOrder);_this.setSortingStatus(_this.getSortKeys(),sortKey,additionalSort,isGroupBy)}});$(this.canvas).on("mousedown",function(event){resizeCursor=getResizeCursor(morpheus.CanvasUtil.getMousePos(event.target,event,true))})};morpheus.VectorTrackHeader.FONT_OFFSET=2;morpheus.VectorTrackHeader.prototype={selected:false,isMouseOver:false,defaultFontHeight:11,dispose:function(){morpheus.AbstractCanvas.prototype.dispose.call(this);this.hammer.off("longpress",this.longpress).off("panend",this.panend).off("panstart",this.panstart).off("panmove",this.panmove).off("tap",this.tap);this.hammer.destroy()},getPreferredSize:function(){var size=this.getPrintSize();size.width+=24;if(!this.isColumns){size.height=this.defaultFontHeight+morpheus.VectorTrackHeader.FONT_OFFSET}return size},getPrintSize:function(){var context=this.canvas.getContext("2d");context.font=this.fontWeight+" "+this.defaultFontHeight+"px "+morpheus.CanvasUtil.getFontFamily(context);var textWidth=4+context.measureText(this.name).width;return{width:textWidth,height:this.defaultFontHeight+morpheus.VectorTrackHeader.FONT_OFFSET}},getSortKeys:function(){return this.isColumns?this.project.getColumnSortKeys():this.project.getRowSortKeys()},setOrder:function(sortKeys){if(this.isColumns){this.project.setColumnSortKeys(morpheus.SortKey.keepExistingSortKeys(sortKeys,this.project.getColumnSortKeys()),false)}else{this.project.setRowSortKeys(morpheus.SortKey.keepExistingSortKeys(sortKeys,this.project.getRowSortKeys()),false)}},setGroupBy:function(groupBy){var existingGroupBy=this.isColumns?this.project.groupColumns:this.project.groupRows;var index=-1;for(var i=0,length=existingGroupBy.length;i1){xpix-=6}}context.fillStyle=morpheus.CanvasUtil.FONT_COLOR;var ypix=this.isColumns?this.getUnscaledHeight()/2:this.getUnscaledHeight()-(this.defaultFontHeight+morpheus.VectorTrackHeader.FONT_OFFSET)/2;context.textBaseline="middle";if(this.isMouseOver){var xdot=xpix-(isColumns?textWidth+4:4);var ydot=ypix-3;for(var i=0;i<2;i++){for(var j=0;j<3;j++){context.fillRect(xdot-i*3,ydot+j*3,1.5,1.5)}}}var fontHeight=Math.min(this.defaultFontHeight,this.getUnscaledHeight()-morpheus.VectorTrackHeader.FONT_OFFSET);fontHeight=Math.min(fontHeight,morpheus.VectorTrack.MAX_FONT_SIZE);context.font=this.font.weight+" "+fontHeight+"px "+morpheus.CanvasUtil.getFontFamily(context);context.fillText(name,xpix,ypix);context.fillStyle=morpheus.CanvasUtil.FONT_COLOR;if(existingSortKeyIndex!==null){context.beginPath();var x=this.isColumns?xpix+4:xpix+textWidth+6;var arrowHeight=Math.min(8,this.getUnscaledHeight()/2-1);var arrowWidth=3;if(sortKeys[existingSortKeyIndex.index].getSortOrder()===morpheus.SortKey.SortOrder.ASCENDING){context.translate(x,ypix-arrowHeight);context.moveTo(0,0);context.lineTo(arrowWidth,arrowHeight);context.lineTo(-arrowWidth,arrowHeight)}else if(sortKeys[existingSortKeyIndex.index].getSortOrder()===morpheus.SortKey.SortOrder.DESCENDING){context.translate(x,ypix);context.moveTo(0,arrowHeight);context.lineTo(arrowWidth,0);context.lineTo(-arrowWidth,0)}else{context.translate(x,ypix-arrowHeight/2);context.moveTo(0,0);context.lineTo(arrowWidth,arrowHeight/2);context.lineTo(0,arrowHeight);context.lineTo(-arrowWidth,arrowHeight/2)}context.fill();morpheus.CanvasUtil.resetTransform(context);context.textAlign="left";if(unlockableSortKeys.length>1){context.font="8px "+morpheus.CanvasUtil.getFontFamily(context);var sortIndex=""+existingSortKeyIndex.number;context.fillText(sortIndex,x+4,ypix-2);x+=context.measureText(sortIndex).width}if(sortKeys[existingSortKeyIndex.index].getLockOrder()!==0){context.font=fontHeight+"px FontAwesome";context.fillText("",x+arrowWidth+2,ypix)}}}};morpheus.Util.extend(morpheus.VectorTrackHeader,morpheus.AbstractCanvas);morpheus.VectorTrack=function(project,name,positions,isColumns,heatmap){morpheus.AbstractCanvas.call(this,true);this.preferredSize={width:0,height:0};this.project=project;this.positions=positions;this.isColumns=isColumns;this.name=name;this.visible=true;this.heatmap=heatmap;this.id=_.uniqueId();var _this=this;this.updateSpanMapFunction=function(){_this.spanMap=morpheus.VectorUtil.createSpanMap(_this.getVector())};this.lastPosition={start:-1,end:-1};this.events="rowSortOrderChanged rowFilterChanged datasetChanged";var mouseMoved=function(event){var index=-1;if(event.type!=="mouseout"){var position=morpheus.CanvasUtil.getMousePosWithScroll(event.target,event,heatmap.scrollLeft(),heatmap.scrollTop());if(_this.settings.squished){var total=positions.getPosition(positions.getLength()-1)+positions.getItemSize(positions.getLength()-1);var squishFactor=total/(isColumns?_this.getUnscaledWidth():_this.getUnscaledHeight());position[isColumns?"x":"y"]*=squishFactor}index=!isColumns?_this.positions.getIndex(position.y,false):_this.positions.getIndex(position.x,false)}if(isColumns){heatmap.setMousePosition(-1,index,{name:_this.name,event:event})}else{heatmap.setMousePosition(index,-1,{name:_this.name,event:event})}};$(this.canvas).on("contextmenu.morpheus",function(e){e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();heatmap.setSelectedTrack(_this.name,isColumns);_this.showPopup(e);return false});this.settings={maxTextWidth:undefined,squished:false,inlineTooltip:false,tooltip:true,highlightMatchingValues:false,colorBarSize:12,stackedBar:false,display:[],selectionColor:"rgb(182,213,253)",colorByField:null,fontField:null,barColor:"#bdbdbd",barSize:40,min:undefined,mid:undefined,max:undefined,autoscaleAlways:false,minMaxReversed:false};$(this.canvas).on("mousemove.morpheus mouseout.morpheus",mouseMoved)};morpheus.VectorTrack.RENDER={TEXT:"text",COLOR:"color",BAR:"bar",MOLECULE:"molecule",TEXT_AND_COLOR:"text_and_color",TEXT_AND_FONT:"text_and_font",SHAPE:"shape",ARC:"arc",BOX_PLOT:"box_plot",HEAT_MAP:"heat_map"};morpheus.VectorTrack.vectorToString=function(vector){var dataType=morpheus.VectorUtil.getDataType(vector);var formatter=vector.getProperties().get(morpheus.VectorKeys.FORMATTER);if(formatter!=null){if(typeof formatter==="object"){formatter=morpheus.Util.createNumberFormat(formatter.pattern);if(dataType==="[number]"){var nf=formatter;formatter=function(v){var s=[];if(v!=null){for(var i=0,arrayLength=v.length;i=6){var context=this.canvas.getContext("2d");var textWidth=morpheus.CanvasUtil.getVectorStringWidth(context,this.getVector(),this.positions,forPrint?-1:this.isColumns?120:100);if(!forPrint){this.settings.maxTextWidth=textWidth}width+=textWidth}else if(!forPrint){this.settings.maxTextWidth=0}}if(this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)){width+=this.settings.barSize}if(this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)){width+=this.settings.colorBarSize}if(this.isRenderAs(morpheus.VectorTrack.RENDER.SHAPE)){width+=this.settings.colorBarSize}if(this.isRenderAs(morpheus.VectorTrack.RENDER.MOLECULE)){width+=300}if(this.isRenderAs(morpheus.VectorTrack.RENDER.ARC)){width+=this.settings.arcSize}if(this.isRenderAs(morpheus.VectorTrack.RENDER.BOX_PLOT)){width+=100}if(this.isRenderAs(morpheus.VectorTrack.RENDER.HEAT_MAP)){width+=100}var nkeys=this.settings.display.length;if(nkeys>0){width+=(nkeys-1)*2}width=Math.max(0,width);return this.isColumns?{width:height,height:width}:{width:width,height:height}},getPreferredSize:function(){return this.preferredSize},getPrintSize:function(){return this._computePreferredSize(true)},_createDiscreteValueMap:function(){var values=morpheus.VectorUtil.getValues(this.getFullVector());values.sort(morpheus.SortKey.ASCENDING_COMPARATOR);this.discreteValueMap=new morpheus.Map;for(var i=0,length=values.length;i0){doRequest(values.pop())}_this.invalid=true;_this.repaint()})};for(var i=0;i<6;i++){doRequest(values.pop())}}this.updateSpanMapFunction()}}this._updatePreferredSize()},postPaint:function(clip,context){context.lineWidth=1;context.strokeStyle="Grey";var project=this.project;var setup=this._setup(context,clip);var vector=setup.vector;var start=setup.start;var end=setup.end;if(this.isColumns){if(project.getHoverColumnIndex()!==-1){this.drawColumnBorder(context,this.positions,project.getHoverColumnIndex(),this.getUnscaledHeight())}}else{if(project.getHoverRowIndex()!==-1){this.drawRowBorder(context,this.positions,project.getHoverRowIndex(),this.getUnscaledWidth())}}this._highlightMatchingValues(context,vector,start,end)},_highlightMatchingValues:function(context,viewVector,start,end){var project=this.project;var positions=this.positions;context.strokeStyle="black";context.lineWidth=3;var hoverIndex=this.isColumns?project.getHoverColumnIndex():project.getHoverRowIndex();var value=viewVector.getValue(hoverIndex);if(this.settings.highlightMatchingValues&&hoverIndex!==-1&&this.heatmap.mousePositionOptions&&this.heatmap.mousePositionOptions.name===viewVector.getName()){var valueToModelIndices=this.getFullVector().getProperties().get(morpheus.VectorKeys.VALUE_TO_INDICES);if(!valueToModelIndices){var fullVector=this.getFullVector();valueToModelIndices=morpheus.VectorUtil.createValueToIndicesMap(fullVector);fullVector.getProperties().set(morpheus.VectorKeys.VALUE_TO_INDICES,valueToModelIndices)}var indices=valueToModelIndices.get(value);if(indices==null){console.log("valueToModelIndices error");return}if(indices.length<=1){return}if(this.isColumns){if(project.getHoverColumnIndex()!==-1){var height=this.getUnscaledHeight();context.beginPath();for(var i=0,nindices=indices.length;i=start&&viewIndex=start&&viewIndex=start&&i<=end){var size=positions.getItemSize(i);var pix=positions.getPosition(i);context.fillRect(pix,0,size,height)}})}else{var width=this.getUnscaledWidth();if(!this.isRenderAs(morpheus.VectorTrack.RENDER.MOLECULE)){var viewIndices=project.getRowSelectionModel().getViewIndices();viewIndices.forEach(function(i){if(i>=start&&i<=end){var size=positions.getItemSize(i);var pix=positions.getPosition(i);context.fillRect(0,pix,width,size)}})}}},prePaint:function(clip,context){var project=this.project;var positions=this.positions;var setup=this._setup(context,clip);var start=setup.start;var end=setup.end;this.drawSelection({context:context,start:start,end:end});if(this.invalid||start!==this.lastPosition.start||end!==this.lastPosition.end){this.lastPosition.start=start;this.lastPosition.end=end;this.invalid=true}},drawRowBorder:function(context,positions,index,gridSize){var size=positions.getItemSize(index);var pix=positions.getPosition(index);context.beginPath();context.moveTo(0,pix+size);context.lineTo(gridSize,pix+size);context.stroke();context.beginPath();context.moveTo(0,pix);context.lineTo(gridSize,pix);context.stroke()},drawColumnBorder:function(context,positions,index,gridSize){var size=positions.getItemSize(index);var pix=positions.getPosition(index);context.beginPath();context.moveTo(pix+size,0);context.lineTo(pix+size,gridSize);context.stroke();context.beginPath();context.moveTo(pix,0);context.lineTo(pix,gridSize);context.stroke()},isSquished:function(){return this.settings.squished},_setup:function(context,clip){var start=0;var vector=this.getVector();var end=vector.size();var settings=this.settings;var positions=this.positions;var width=clip.width;var height=clip.height;if(!settings.squished){if(this.isColumns){start=morpheus.Positions.getLeft(clip,positions);end=morpheus.Positions.getRight(clip,positions)}else{start=morpheus.Positions.getTop(clip,positions);end=morpheus.Positions.getBottom(clip,positions)}}if(settings.squished){var total=positions.getPosition(positions.getLength()-1)+positions.getItemSize(positions.getLength()-1);if(!this.isColumns){var squishFactor=height/total;context.scale(1,squishFactor)}else{var squishFactor=width/total;context.scale(squishFactor,1)}}else{context.translate(-clip.x,-clip.y)}return{start:start,end:end,vector:vector}},draw:function(clip,context){var setup=this._setup(context,clip);this._draw({start:setup.start,end:setup.end,vector:setup.vector,context:context,availableSpace:this.isColumns?this.getUnscaledHeight():this.getUnscaledWidth(),clip:clip})},print:function(clip,context){var vector=this.getVector();this._draw({start:0,end:vector.size(),vector:vector,context:context,availableSpace:this.isColumns?clip.height:clip.width,clip:clip})},_draw:function(options){var _this=this;var context=options.context;var vector=options.vector;var availableSpace=options.availableSpace;var fullAvailableSpace=options.availableSpace;var start=options.start;var end=options.end;var clip=options.clip;var positions=this.positions;if(this.settings.autoscaleAlways){this._setChartMinMax()}context.textAlign="left";context.fillStyle=morpheus.CanvasUtil.FONT_COLOR;var fontSize=Math.min(morpheus.VectorTrack.MAX_FONT_SIZE,positions.getSize()-2);var size=0;context.font=fontSize+"px "+morpheus.CanvasUtil.getFontFamily(context);context.strokeStyle=morpheus.HeatMapElementCanvas.GRID_COLOR;context.lineWidth=.1;if(this.heatmap.heatmap.isDrawGrid()&&!this.settings.squished){if(this.isColumns){var gridSize=availableSpace;context.beginPath();for(var i=start;i7){context.moveTo(pix+size,0);context.lineTo(pix+size,gridSize)}}context.stroke()}else{if(!this.isRenderAs(morpheus.VectorTrack.RENDER.MOLECULE)){var gridSize=availableSpace;context.beginPath();for(var i=start;i7){context.moveTo(0,pix+size);context.lineTo(gridSize,pix+size)}}context.stroke()}}}context.lineWidth=1;var offset=1;if(this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)){this.renderColor(context,vector,start,end,clip,this.isColumns?availableSpace:0,!this.getFullVector().getProperties().get(morpheus.VectorKeys.DISCRETE));offset+=this.settings.colorBarSize+2;availableSpace-=offset}if(!this.settings.squished&&this.isRenderAs(morpheus.VectorTrack.RENDER.SHAPE)){this.renderShape(context,vector,start,end,clip,this.isColumns?availableSpace-offset:offset);offset+=this.settings.colorBarSize+2;availableSpace-=offset}if(this.isRenderAs(morpheus.VectorTrack.RENDER.ARC)){this.renderArc(context,vector,start,end,clip,this.settings.arcSize);offset+=this.settings.arcSize+2;availableSpace-=offset}if(!this.settings.squished&&this.isRenderAs(morpheus.VectorTrack.RENDER.MOLECULE)){this.renderMolecule(context,vector,start,end,clip,offset,availableSpace)}if(this.isRenderAs(morpheus.VectorTrack.RENDER.BOX_PLOT)){var barSize=!this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)?availableSpace-2:this.settings.barSize;offset++;this.renderBoxPlot(context,vector,start,end,clip,offset,barSize);offset+=barSize+2;availableSpace-=offset}if(this.isRenderAs(morpheus.VectorTrack.RENDER.HEAT_MAP)){var barSize=!this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)?availableSpace-2:this.settings.barSize;offset++;this.renderHeatMap(context,vector,start,end,clip,barSize);offset+=barSize+2;availableSpace-=offset}if(this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)){var barSize=!this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)?availableSpace-1:this.settings.barSize;if(this.settings.stackedBar){this.renderStackedBar(context,vector,start,end,clip,offset,barSize)}else{var fields=vector.getProperties().get(morpheus.VectorKeys.FIELDS);var visibleFieldIndices=vector.getProperties().get(morpheus.VectorKeys.VISIBLE_FIELDS);if(fields!=null&&visibleFieldIndices==null){visibleFieldIndices=morpheus.Util.seq(fields.length)}if(fields!=null){this.renderUnstackedBar(context,vector,start,end,clip,offset,barSize,visibleFieldIndices)}else{this.renderBar(context,vector,start,end,clip,this.isColumns?fullAvailableSpace-offset-barSize:offset,barSize)}}offset+=barSize+2;availableSpace-=offset}if(!this.settings.squished&&this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)&&(this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT))){context.fillStyle=morpheus.CanvasUtil.FONT_COLOR;this.renderText(context,vector,this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR),this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT),start,end,clip,this.isColumns?fullAvailableSpace-offset:offset);offset+=this.settings.maxTextWidth+2;availableSpace-=offset}if(!this.settings.squished&&this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)&&!this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR)&&!this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT)){context.fillStyle=morpheus.CanvasUtil.FONT_COLOR;var dataType=morpheus.VectorUtil.getDataType(vector);if(dataType==="url"){context.fillStyle="blue";this.canvas.style.cursor="pointer"}this.renderText(context,vector,false,false,start,end,clip,this.isColumns?fullAvailableSpace-offset:offset)}},showPopup:function(e,isHeader){var _this=this;var project=this.project;var isColumns=this.isColumns;var hasSelection=isColumns?project.getColumnSelectionModel().count()>0:project.getRowSelectionModel().count()>0;var ANNOTATE_SELECTION="Annotate Selection";var INVERT_SELECTION="Invert Selection";var SELECT_ALL="Select All";var SHOW_SELECTION_ONLY="Show Selection Only";var CLEAR_SELECTION="Clear Selection";var HIGHLIGHT_MATCHING_VALUES="Highlight Matching Values";var FIELDS="Choose Fields...";var DELETE="Delete...";var TOOLTIP="Show In Tooltip";var HIDE="Hide";var HIDE_OTHERS="Hide Others";var REMOVE_SHOW_SELECTION_ONLY="Show All";var SORT_ASC="Sort Ascending";var SORT_DESC="Sort Descending";var MOVE_TO_TOP="Move To Top";var SORT_SEL_ASC="Sort Heat Map Ascending ↑";var SORT_SEL_DESC="Sort Heat Map Descending ↓";var SORT_SEL_TOP_N="Sort Heat Map Descending/Ascending";var DISPLAY_BAR="Show Bar Chart";var NUMBER_FORMAT="Format";var DISPLAY_STACKED_BAR="Show Stacked Bar Chart";var DISPLAY_BOX_PLOT="Show Box Plot";var DISPLAY_COLOR="Show Color";var COLOR_BAR_SIZE="Color Bar Size...";var DISPLAY_TEXT="Show Text";var DISPLAY_SHAPE="Show Shape";var DISPLAY_ARC="Show Arc";var DISPLAY_TEXT_AND_COLOR="Encode Text Using Color";var DISPLAY_TEXT_AND_FONT="Encode Text Using Font";var DISPLAY_STRUCTURE="Show Chemical Structure";var DISPLAY_CONTINUOUS="Continuous";var positions=this.positions;var heatmap=this.heatmap;var sectionToItems={Sort:[],Selection:[],Display:[]};var customItems=this.heatmap.getPopupItems();if(customItems&&customItems.length>0){customItems.forEach(function(item){if(item.columns===isColumns){sectionToItems[item.section].push(item)}})}if(sectionToItems.Selection.length>0){sectionToItems.Selection.push({separator:true})}sectionToItems.Selection.push({name:MOVE_TO_TOP});if(this.heatmap.options.menu.Edit&&this.heatmap.options.menu.Edit.indexOf("Annotate"+" Selected Rows")!==-1){sectionToItems.Selection.push({name:ANNOTATE_SELECTION})}sectionToItems.Selection.push({name:"Copy",class:"copy"});sectionToItems.Selection.push({name:INVERT_SELECTION});sectionToItems.Selection.push({name:SELECT_ALL});sectionToItems.Selection.push({name:CLEAR_SELECTION});var combinedFilter=isColumns?project.getColumnFilter():project.getRowFilter();var showSelectionOnlyIndex=combinedFilter.indexOf(SHOW_SELECTION_ONLY);if(showSelectionOnlyIndex!==-1){sectionToItems.Selection.push({name:REMOVE_SHOW_SELECTION_ONLY})}if(!isHeader){sectionToItems["Sort"].push({name:SORT_SEL_ASC,disabled:!hasSelection});sectionToItems["Sort"].push({name:SORT_SEL_DESC,disabled:!hasSelection});sectionToItems["Sort"].push({name:SORT_SEL_TOP_N,disabled:!hasSelection})}var dataType=morpheus.VectorUtil.getDataType(this.getFullVector());var arrayFields=this.getFullVector().getProperties().get(morpheus.VectorKeys.FIELDS);var isArray=arrayFields!==undefined;var isNumber=dataType==="number"||dataType==="[number]";if(isNumber||isArray){sectionToItems.Display.push({name:NUMBER_FORMAT});sectionToItems.Display.push({separator:true});sectionToItems.Display.push({name:DISPLAY_BAR,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)})}if(isArray){sectionToItems.Display.push({name:DISPLAY_STACKED_BAR,checked:this.settings.stackedBar});sectionToItems.Display.push({name:DISPLAY_BOX_PLOT,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.BOX_PLOT)});sectionToItems.Display.push({name:FIELDS})}if(dataType!=="url"){sectionToItems.Display.push({name:DISPLAY_TEXT,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)});if(this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)){sectionToItems.Display.push({name:DISPLAY_TEXT_AND_COLOR,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR)});sectionToItems.Display.push({name:DISPLAY_TEXT_AND_FONT,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT)})}sectionToItems.Display.push({separator:true});sectionToItems.Display.push({name:DISPLAY_COLOR,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)});if(this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)){sectionToItems.Display.push({name:COLOR_BAR_SIZE})}}if(!isArray&&dataType!=="url"){sectionToItems.Display.push({name:DISPLAY_SHAPE,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.SHAPE)})}if(!isArray&&!isNumber&&!this.isColumns&&name.toLowerCase().indexOf("smile")!==-1){sectionToItems.Display.push({name:DISPLAY_STRUCTURE,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.MOLECULE)})}sectionToItems.Display.push({name:TOOLTIP,checked:this.settings.inlineTooltip});if(!isArray&&dataType!=="url"){sectionToItems.Display.push({name:HIGHLIGHT_MATCHING_VALUES,checked:this.settings.highlightMatchingValues})}if(dataType!=="url"){}if(this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)||this.isRenderAs(morpheus.VectorTrack.RENDER.BOX_PLOT)){sectionToItems.Display.push({separator:true});if(this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)){sectionToItems.Display.push({name:"Edit Bar Color..."})}sectionToItems.Display.push({name:"Auto Range"});sectionToItems.Display.push({name:"Custom Range..."})}if(this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT)||this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)||this.isRenderAs(morpheus.VectorTrack.RENDER.SHAPE)){sectionToItems.Display.push({separator:true});if(isNumber){sectionToItems.Display.push({name:DISPLAY_CONTINUOUS,checked:!this.getFullVector().getProperties().get(morpheus.VectorKeys.DISCRETE)})}if(this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)&&isArray){sectionToItems.Display.push({name:"Edit Colors..."})}if(this.isRenderAs(morpheus.VectorTrack.RENDER.SHAPE)){sectionToItems.Display.push({name:"Edit Shapes..."})}if(this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT)){sectionToItems.Display.push({name:"Edit Fonts..."})}if(this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)&&isArray){sectionToItems.Display.push({name:"Color Key",icon:"fa fa-key"})}}if(this.isRenderAs(morpheus.VectorTrack.RENDER.SHAPE)){sectionToItems.Display.push({name:"Shape Key",icon:"fa fa-key"})}if(this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT)){sectionToItems.Display.push({name:"Font Key",icon:"fa fa-key"})}sectionToItems.Display.push({separator:true});sectionToItems.Display.push({name:HIDE});sectionToItems.Display.push({name:HIDE_OTHERS,disabled:heatmap.getVisibleTrackNames(this.isColumns).length<=1});sectionToItems.Display.push({separator:true});sectionToItems.Display.push({name:DELETE});var items=[];function addSection(name){if(items.length>0){items.push({separator:true})}items=items.concat(sectionToItems[name])}addSection("Sort");_.each(sectionToItems.Selection,function(item){if(item.name!==REMOVE_SHOW_SELECTION_ONLY&&item.name!==SELECT_ALL){item.disabled=!hasSelection}});if(!isHeader){addSection("Selection")}else if(this.heatmap.options.toolbar.options){addSection("Display")}if(e.preventDefault){e.preventDefault()}if(items.length===0){return}morpheus.Popup.showPopup(items,{x:e.pageX,y:e.pageY},e.target,function(event,item){var customItem;if(item===NUMBER_FORMAT){var vector=_this.getFullVector();var formatter=vector.getProperties().get(morpheus.VectorKeys.FORMATTER);if(formatter!=null){if(typeof formatter==="object"){formatter=morpheus.Util.createNumberFormat(formatter.pattern);vector.getProperties().set(morpheus.VectorKeys.FORMATTER,formatter)}}var pattern=formatter!=null?formatter.toJSON().pattern:".2f";var formBuilder=new morpheus.FormBuilder;formBuilder.append({name:"number_of_fraction_digits",type:"number",value:morpheus.Util.getNumberFormatPatternFractionDigits(pattern),required:true,style:"max-width:60px;"});formBuilder.find("number_of_fraction_digits").on("keyup input",_.debounce(function(){var n=parseInt($(this).val());if(n>=0){vector.getProperties().set(morpheus.VectorKeys.FORMATTER,{pattern:"."+n+"f"});_this.setInvalid(true);_this.repaint()}},100));morpheus.FormBuilder.showInModal({title:"Format",close:"Close",html:formBuilder.$form,focus:heatmap.getFocusEl()})}else if(item==="Copy"){heatmap.getActionManager().execute(isColumns?"Copy Selected Columns":"Copy"+" Selected Rows")}else if(item===FIELDS){var visibleFieldIndices=_this.getFullVector().getProperties().get(morpheus.VectorKeys.VISIBLE_FIELDS);var visibleFields;if(visibleFieldIndices==null){visibleFields=arrayFields.slice(0)}else{visibleFields=[];for(var i=0;i0){_this.settings.colorBarSize=val;_this.setInvalid(true);_this.repaint()}});morpheus.FormBuilder.showInModal({title:"Color Bar Size",close:"Close",html:formBuilder.$form,focus:heatmap.getFocusEl()})}else if(item===ANNOTATE_SELECTION){heatmap.getActionManager().execute(isColumns?"Annotate Selected Columns":"Annotate"+" Selected Rows")}else if(item===DELETE){morpheus.FormBuilder.showOkCancel({title:"Delete",content:"Are you sure you want to delete "+_this.name+"?",okCallback:function(){var metadata=isColumns?project.getFullDataset().getColumnMetadata():project.getFullDataset().getRowMetadata();metadata.remove(morpheus.MetadataUtil.indexOf(metadata,_this.name));var sortKeys=isColumns?project.getColumnSortKeys():project.getRowSortKeys();var sortKeyIndex=_.indexOf(sortKeys.map(function(key){return key.field}),_this.name);if(sortKeyIndex!==-1){sortKeys.splice(sortKeyIndex,1);if(isColumns){project.setColumnSortKeys(sortKeys,true)}else{project.setRowSortKeys(sortKeys,true)}}var groupByKeys=isColumns?project.getGroupColumns():project.getGroupRows();var groupByKeyIndex=_.indexOf(groupByKeys.map(function(key){return key.field}),_this.name);if(groupByKeyIndex!==-1){groupByKeys.splice(groupByKeyIndex,1);if(isColumns){project.setGroupColumns(groupByKeys,true)}else{project.setGroupRows(groupByKeys,true)}}if(!isColumns){project.trigger("rowTrackRemoved",{vector:_this.getFullVector()})}else{project.trigger("columnTrackRemoved",{vector:_this.getFullVector()})}}})}else if(item===CLEAR_SELECTION){heatmap.getActionManager().execute(isColumns?"Clear Selected Columns":"Clear"+" Selected Rows")}else if(item===INVERT_SELECTION){heatmap.getActionManager().execute(isColumns?"Invert Selected Columns":"Invert"+" Selected Rows")}else if(item===MOVE_TO_TOP){heatmap.getActionManager().execute(isColumns?"Move Selected Columns To Top":"Move"+" Selected Rows To Top")}else if(item===SORT_ASC||item===SORT_DESC){var sortKey=new morpheus.SortKey(_this.name,item===SORT_ASC?morpheus.SortKey.SortOrder.ASCENDING:morpheus.SortKey.SortOrder.DESCENDING);if(_this.isColumns){_this.project.setColumnSortKeys(morpheus.SortKey.keepExistingSortKeys([sortKey],project.getColumnSortKeys()),true)}else{_this.project.setRowSortKeys(morpheus.SortKey.keepExistingSortKeys([sortKey],project.getRowSortKeys()),true)}}else if(item==SORT_SEL_ASC||item==SORT_SEL_DESC||item===SORT_SEL_TOP_N){var sortOrder;if(item===SORT_SEL_ASC){sortOrder=morpheus.SortKey.SortOrder.ASCENDING}else if(item===SORT_SEL_DESC){sortOrder=morpheus.SortKey.SortOrder.DESCENDING}else{sortOrder=morpheus.SortKey.SortOrder.TOP_N}heatmap.sortBasedOnSelection(sortOrder,isColumns,e&&e.shiftKey)}else if(item===SELECT_ALL){heatmap.getActionManager().execute(isColumns?"Select All Columns":"Select All Rows")}else if(item==="Auto Range"){delete _this.settings.min;delete _this.settings.max;delete _this.settings.mid;_this._update();heatmap.revalidate()}else if(item==="Custom Range..."){var formBuilder=new morpheus.FormBuilder;var items=[{name:"min",required:true,type:"number",value:_this.settings.min},{name:"mid",required:true,type:"number",value:_this.settings.mid},{name:"max",required:true,type:"number",value:_this.settings.max}];_.each(items,function(item){formBuilder.append(item)});morpheus.FormBuilder.showOkCancel({title:"Range",content:formBuilder.$form,okCallback:function(){_this.settings.min=parseFloat(formBuilder.getValue("min"));_this.settings.mid=parseFloat(formBuilder.getValue("mid"));_this.settings.max=parseFloat(formBuilder.getValue("max"));_this._update();heatmap.revalidate()}})}else if(item==="Squished"){_this.settings.squished=!_this.settings.squished;heatmap.revalidate()}else if(item==="Color Key"){var legend=new morpheus.HeatMapTrackColorLegend([_this],isColumns?_this.project.getColumnColorModel():_this.project.getRowColorModel());var size=legend.getPreferredSize();legend.setBounds(size);legend.repaint();morpheus.FormBuilder.showInModal({title:"Color Key",html:legend.canvas,focus:heatmap.getFocusEl()})}else if(item==="Shape Key"){var legend=new morpheus.HeatMapTrackShapeLegend([_this],isColumns?_this.project.getColumnShapeModel():_this.project.getRowShapeModel());var size=legend.getPreferredSize();legend.setBounds(size);legend.repaint();morpheus.FormBuilder.showInModal({title:"Shape Key",html:legend.canvas,focus:heatmap.getFocusEl()})}else if(item==="Font Key"){var legend=new morpheus.HeatMapTrackFontLegend([_this],isColumns?_this.project.getColumnFontModel():_this.project.getRowFontModel());var size=legend.getPreferredSize();legend.setBounds(size);legend.repaint();morpheus.FormBuilder.showInModal({title:"Font Key",html:legend.canvas,focus:heatmap.getFocusEl()})}else if(item==="Edit Fonts..."){heatmap.getActionManager().execute("Edit Fonts")}else if(item==="Edit Shapes..."){var shapeFormBuilder=new morpheus.FormBuilder;var shapeModel=isColumns?_this.project.getColumnShapeModel():_this.project.getRowShapeModel();var chooser=new morpheus.ShapeChooser({map:shapeModel.getMap(_this.name)});chooser.on("change",function(event){shapeModel.setMappedValue(_this.getFullVector(),event.value,event.shape);_this.setInvalid(true);_this.repaint()});morpheus.FormBuilder.showInModal({title:"Edit Shapes",html:chooser.$div,close:"Close",focus:heatmap.getFocusEl()})}else if(item==="Edit Colors..."){var colorModel=isColumns?_this.project.getColumnColorModel():_this.project.getRowColorModel();var colorSchemeChooser=new morpheus.ColorSchemeChooser({track:_this,heatMap:_this.heatmap,colorModel:colorModel});morpheus.FormBuilder.showInModal({title:"Edit Colors",html:colorSchemeChooser.$div,close:"Close",focus:heatmap.getFocusEl()})}else if(item===TOOLTIP){_this.settings.inlineTooltip=!_this.settings.inlineTooltip}else if(item===HIGHLIGHT_MATCHING_VALUES){_this.settings.highlightMatchingValues=!_this.settings.highlightMatchingValues}else if(customItem=_.find(customItems,function(customItem){return customItem.name===item&&customItem.columns===isColumns})){if(customItem.task){var task={tabId:_this.heatmap.getTabManager().getActiveTabId()};_this.heatmap.getTabManager().addTask(task);setTimeout(function(){customItem.callback(heatmap);_this.heatmap.getTabManager().removeTask(task)},1)}else{customItem.callback(heatmap)}}else if(item===DISPLAY_CONTINUOUS){var discrete=_this.getFullVector().getProperties().get(morpheus.VectorKeys.DISCRETE)||false;_this.getFullVector().getProperties().set(morpheus.VectorKeys.DISCRETE,!discrete);_this._setChartMinMax();_this.setInvalid(true);_this.repaint()}else if(item===HIDE){heatmap.setTrackVisible(_this.name,false,_this.isColumns);heatmap.revalidate()}else if(item===HIDE_OTHERS){var names=heatmap.getVisibleTrackNames(_this.isColumns);for(var i=0;icanvasSize){colorBarSize=canvasSize>=5?canvasSize-1:canvasSize}var getColor;if(!continuous){getColor=_.bind(colorModel.getMappedValue,colorModel)}else{getColor=_.bind(colorModel.getContinuousMappedValue,colorModel)}if(vector.getProperties().get(morpheus.VectorKeys.FIELDS)!=null){var visibleFieldIndices=vector.getProperties().get(morpheus.VectorKeys.VISIBLE_FIELDS);if(visibleFieldIndices==null){visibleFieldIndices=morpheus.Util.seq(vector.getProperties().get(morpheus.VectorKeys.FIELDS).length)}colorBarSize/=visibleFieldIndices.length;var nvisibleFieldIndices=visibleFieldIndices.length;for(var i=start;icanvasSize){colorBarSize=canvasSize>=5?canvasSize-1:canvasSize}context.fillStyle="black";context.strokeStyle="black";var lineWidth=context.lineWidth;context.lineWidth=1;for(var i=start;i10){context.strokeStyle=gridColor;context.lineWidth=gridThickness;context.beginPath();for(var j=0;j').appendTo($(document.body));this.jsme=new JSApplet.JSME(this.jsmeId,"380px","340px",{})}this.jsme.readMolFile(sdf);var svg=$("#"+this.jsmeId+" > div > div > div:nth-child(2) > svg");var svgWidth=svg.width.baseVal.value;var svgHeight=svg.height.baseVal.value;var scale=Math.min(width/svgWidth,height/svgHeight);var text=''+svg.innerHTML+"";return text},renderMolecule:function(context,vector,start,end,clip,offset){var isColumns=this.isColumns;var positions=this.positions;context.fillStyle=morpheus.CanvasUtil.FONT_COLOR;context.strokeStyle="black";var width=this.getUnscaledWidth();var customUrlProvider=this.heatmap.options.structureUrlProvider!==undefined;var dummyTarget={childNodes:[],getContext:function(){return context}};for(var i=start;i=this.settings.mid){positivePairs.push({value:value,index:j})}else if(value<0){negativePairs.push({value:value,index:j})}}var positiveIndices=morpheus.Util.indexSortPairs(positivePairs,false);for(var j=0,length=positiveIndices.length;j1;n--){morpheus.HCluster.findClosestPair(n,distmatrix,r);result[nelements-n]={};result[nelements-n].distance=r.distance;var is=r.ip;var js=r.jp;result[nelements-n].left=clusterid[is];result[nelements-n].right=clusterid[js];var sum=number[is]+number[js];for(j=0;j1;n--){morpheus.HCluster.findClosestPair(n,distmatrix,r);result[nelements-n].distance=r.distance;var is=r.ip;var js=r.jp;for(j=0;j=order2){neworder[j]+=increase}if(clusterid==i2&&order1order2){neworder[j]+=increase}if(clusterid==i2&&order1<=order2){neworder[j]+=increase}if(clusterid==i1||clusterid==i2){clusterids[j]=-i-1}}}}return morpheus.Util.indexSort(neworder,true)};morpheus.KMeansPlusPlusClusterer=function(k,maxIterations,distanceFunction){var distance=function(points1,points2){return distanceFunction(points1.getPoint(),points2.getPoint())};function nextInt(upperBound){return Math.floor(Math.random()*upperBound)|0}function nextDouble(){return Math.random()}function PointWrapper(point){this.getPoint=function(){return point}}function CentroidCluster(center){var centroidPoints=[];this.addPoint=function(p){centroidPoints.push(p)};this.getPoints=function(){return centroidPoints};this.getCenter=function(){return center}}function cluster(points){if(points.length=r){nextPointIndex=i;break}}}if(nextPointIndex===-1){for(var i=numPoints-1;i>=0;i--){if(!taken[i]){nextPointIndex=i;break}}}if(nextPointIndex>=0){var p=pointList[nextPointIndex];resultSet.push(new CentroidCluster(p));taken[nextPointIndex]=true;if(resultSet.length0){var center=cluster.getCenter();var points=cluster.getPoints();var distances=new Float32Array(points.length);for(var i=0;imaxVariance){maxVariance=variance;selected=cluster}}}if(selected==null){throw"All clusters are empty"}var selectedPoints=selected.getPoints();return selectedPoints.splice(nextInt(selectedPoints.length),1)}function getNearestCluster(clusters,point){var minDistance=Number.MAX_VALUE;var clusterIndex=0;var minCluster=0;for(var i=0;i=score){rowSpecificPValues[i]++}}}var N=numPermutations;var kArray=new Uint32Array(numRows);for(var i=0;i=1;i--){var j=getRandomIntInclusive(0,i);var tmp=indices[j];indices[j]=indices[i];indices[i]=tmp}return indices}};morpheus.UnbalancedPermuter=function(numClassZero,numClassOne){var assignments=new Uint32Array(numClassZero+numClassOne);var indices=new Uint32Array(numClassZero+numClassOne);for(var i=0;i=1;i--){var j=getRandomIntInclusive(0,i);var tmp=indices[j];indices[j]=indices[i];indices[i]=tmp}for(var i=0;iranks[i-1].value){pos=i+1;if(tiesTrace.length>1){morpheus.Ranking.fillAverage(out,tiesTrace)}tiesTrace=[];tiesTrace.push(ranks[i].position)}else{tiesTrace.push(ranks[i].position)}out[ranks[i].position]=pos}if(tiesTrace.length>1){morpheus.Ranking.fillAverage(out,tiesTrace)}return out};morpheus.Ranking.fill=function(data,tiesTrace,value){for(var i=0,length=tiesTrace.length;i=temp[j]){if(result[j].distance=result[vector[j]].distance){vector[j]=i}}}for(i=0;iterm2)return+1;return 0});for(i=0;i").appendTo("body");var dim={width:Math.max(0,$c.width()-$c[0].clientWidth),height:$c.height()-$c[0].clientHeight};$c.remove();return dim};morpheus.Util.trackEvent=function(options){if(typeof window!=="undefined"){if(!morpheus.Util.TRACKING_CODE_LOADED){morpheus.Util.loadTrackingCode()}if(morpheus.Util.TRACKING_CODE_LOADED&&typeof ga!=="undefined"){ga("morpheus.send",{hitType:"event",eventCategory:options.eventCategory,eventAction:options.eventAction,eventLabel:options.eventLabel})}}};morpheus.Util.isString=function(value){return typeof value==="string"||value instanceof String};morpheus.Util.getDataType=function(val){var dataType;var isArray=morpheus.Util.isArray(val);if(isArray&&val.length>0){val=val[0]}if(morpheus.Util.isString(val)){dataType="string"}else if(_.isNumber(val)){dataType="number"}else{dataType="object"}if(isArray){dataType="["+dataType+"]"}return dataType};morpheus.Util.isArray=function(array){var types=[Array,Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];for(var i=0,length=types.length;i0){searchObject=morpheus.Util.getQueryParams(window.location.search.substring(1))}if(window.location.hash.length>0){hashObject=morpheus.Util.getQueryParams(window.location.hash.substring(1))}return _.extend(hashObject,searchObject)};morpheus.Util.copyString=function(s){return(" "+s).substr(1)};morpheus.Util.getQueryParams=function(s){var params={};if(!s){return params}var search=decodeURIComponent(s);var keyValuePairs=search.split("&");for(var i=0;i=0;i--){var src=scripts[i].src;var index=src.lastIndexOf("/");if(index!==-1){src=src.substring(index+1)}if(src===name){return scripts[i].src}}if(name==="morpheus-latest.min.js"){return morpheus.Util.getScriptPath("morpheus.js")}return scripts.length>0?scripts[0].src:""};morpheus.Util.forceDelete=function(obj){try{var _garbageCollector=function(){var ef=URL.createObjectURL(new Blob([""],{type:"text/javascript"})),w=new Worker(ef);URL.revokeObjectURL(ef);return w}();_garbageCollector.postMessage(obj,[obj])}catch(x){console.log("Unable to delete")}};morpheus.Util.getFileName=function(fileOrUrl){if(morpheus.Util.isFile(fileOrUrl)){return fileOrUrl.name}if(fileOrUrl.name!==undefined){return fileOrUrl.name}var name=""+fileOrUrl;var question=name.indexOf("?");if(question!==-1){var params=name.substring(question+1);var keyValuePairs=decodeURIComponent(params).split("&");for(var i=0;i0){var suffix=name.substring(dotIndex+1).toLowerCase();if(suffix==="txt"||suffix==="gz"||suffix==="tsv"){var newPath=name.substring(0,dotIndex);var secondDotIndex=newPath.lastIndexOf(".");if(secondDotIndex>0){var secondSuffix=newPath.substring(secondDotIndex+1,newPath.length).toLowerCase();if(secondSuffix==="segtab"||secondSuffix==="seg"||secondSuffix==="maf"||secondSuffix==="gct"||secondSuffix==="txt"||secondSuffix==="gmt"){return secondSuffix}}}return suffix}return""};morpheus.Util.getBaseFileName=function(name){var dotIndex=name.lastIndexOf(".");if(dotIndex>0){var suffix=name.substring(dotIndex+1,name.length);if(suffix==="gz"||suffix==="zip"||suffix==="bz2"){return morpheus.Util.getBaseFileName(name.substring(0,dotIndex))}return name.substring(0,dotIndex)}return name};morpheus.Util.seq=function(length){var array=[];for(var i=0;i=suffix.length&&string.substr(string.length-suffix.length)===suffix};morpheus.Util.measureSvgText=function(text,classname){if(!text||text.length===0){return{height:0,width:0}}var container=d3.select("body").append("svg");if(classname){container.attr("class",classname)}container.append("text").attr({x:-1e3,y:-1e3}).text(text);var bbox=container.node().getBBox();container.remove();return{height:bbox.height,width:bbox.width}};morpheus.Util.IS_MAC=false;if(typeof navigator!=="undefined"){morpheus.Util.IS_MAC=navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i)?true:false}morpheus.Util.COMMAND_KEY=morpheus.Util.IS_MAC?"⌘":"Ctrl+";morpheus.Util.hammer=function(el,recognizers){if(typeof Hammer!=="undefined"){var hammer=new Hammer(el,{recognizers:[]});if(_.indexOf(recognizers,"pan")!==-1){hammer.add(new Hammer.Pan({threshold:1,direction:Hammer.DIRECTION_ALL}))}else if(_.indexOf(recognizers,"panh")!==-1){hammer.add(new Hammer.Pan({threshold:1,direction:Hammer.DIRECTION_HORIZONTAL}))}else if(_.indexOf(recognizers,"panv")!==-1){hammer.add(new Hammer.Pan({threshold:1,direction:Hammer.DIRECTION_VERTICAL}))}if(_.indexOf(recognizers,"tap")!==-1){hammer.add(new Hammer.Tap)}if(_.indexOf(recognizers,"pinch")!==-1){hammer.add(new Hammer.Pinch)}if(_.indexOf(recognizers,"longpress")!==-1){hammer.add(new Hammer.Press({event:"longpress",time:1e3}))}if(_.indexOf(recognizers,"press")!==-1){hammer.add(new Hammer.Press)}if(_.indexOf(recognizers,"swipe")!==-1){hammer.add(new Hammer.Swipe)}return hammer}else{return $()}};morpheus.Util.createTextDecoder=function(){if(typeof TextDecoder!=="undefined"){var textDecoder=new TextDecoder;return function(buf,start,end){return textDecoder.decode(buf.subarray(start,end))}}else{return function(buf,start,end){var s=[];for(var i=start;i"+value.replace(regexMatch,"$1")+""})});cb(matches)};morpheus.Util.setClipboardData=function(clipboardData,delay){var isRTL=document.documentElement.getAttribute("dir")=="rtl";var fakeElem=document.createElement("div");fakeElem.contentEditable=true;fakeElem.style.fontSize="12pt";fakeElem.style.border="0";fakeElem.style.padding="0";fakeElem.style.margin="0";fakeElem.style.position="absolute";fakeElem.style[isRTL?"right":"left"]="-999999px";fakeElem.style.top=(window.pageYOffset||document.documentElement.scrollTop)+"px";fakeElem.setAttribute("readonly","");var f=function(e){clipboardData.forEach(function(elem){e.clipboardData.setData(elem.format,elem.data)});e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();fakeElem.removeEventListener("copy",f)};fakeElem.addEventListener("copy",f);document.body.appendChild(fakeElem);fakeElem.focus();var selection=window.getSelection();var range=document.createRange();range.selectNodeContents(fakeElem);selection.removeAllRanges();selection.addRange(range);if(delay){setTimeout(function(){if(!document.execCommand("copy")){console.log("copy failed")}document.body.removeChild(fakeElem)},20)}else{if(!document.execCommand("copy")){console.log("copy failed")}document.body.removeChild(fakeElem)}};morpheus.Util.autosuggest=function(options){options=$.extend({},{multi:true,delay:500,minLength:0,suggestWhenEmpty:true},options);var searching=false;function _select(event,ui,isKey){if(ui.item.skip){return false}if(options.multi){var terms=morpheus.Util.getAutocompleteTokens(options.$el[0].value,{trim:false,selectionStart:options.$el[0].selectionStart});var field=event.toElement&&event.toElement.dataset?event.toElement.dataset.autocomplete:null;var value=field?ui.item[field]:ui.item.value;var show=ui.item.show;if(terms.length===0){terms.push(value)}else if(ui.item.clear){terms=[value]}else{terms[terms.selectionStartIndex===-1||terms.selectionStartIndex===undefined?terms.length-1:terms.selectionStartIndex]=value}options.$el[0].value=terms.join(" ");if(show&&!isKey||isKey&&event.which===13){searching=true;setTimeout(function(){options.$el.autocomplete("search",options.$el.val())},20);setTimeout(function(){searching=false},100)}if(!isKey&&options.select){options.select()}return false}if(!isKey&&options.select){options.select()}if(!isKey&&event.which===13){event.stopImmediatePropagation()}}options.$el.on("keydown",function(event){if(event.keyCode===$.ui.keyCode.TAB&&$(this).data("ui-autocomplete").menu.active){event.preventDefault()}}).autocomplete({minLength:options.minLength,delay:options.delay,source:function(request,response){if(request.term.history&&options.history){return options.history(response)}var terms=morpheus.Util.getAutocompleteTokens(request.term,{trim:false,selectionStart:options.$el[0].selectionStart});if(terms.selectionStartIndex===undefined||terms.selectionStartIndex===-1){terms.selectionStartIndex=terms.length-1}if(options.suggestWhenEmpty||terms.length>0){options.filter(terms,response)}},focus:function(event,ui){var original=event.originalEvent;while(original.originalEvent!=null){original=original.originalEvent}if(original&&/^key/.test(original.type)){return _select(original,ui,true)}return false},select:function(event,ui){return _select(event,ui,false)}});var instance=options.$el.autocomplete("instance");if(instance!=null){instance._renderItem=function(ul,item){if(item.value==null){return $('
  • ').append($("
    ").html(item.label)).appendTo(ul)}return $('
  • ').append($("
    ").html(item.label)).appendTo(ul)};instance._normalize=function(items){return items};instance._resizeMenu=function(){var ul=this.menu.element;ul.outerWidth(instance.element.outerWidth())}}var menu=options.$el.autocomplete("widget");menu.menu("option","items","> :not(.search-category)");if(menu){menu.addClass("search-menu")}if(options.suggestWhenEmpty){options.$el.on("focus",function(){options.$el.autocomplete("search",options.$el.val())})}options.$el.on("keyup",function(e){if(e.which===13&&!searching){options.$el.autocomplete("close")}else if(e.which===38&&options.history){options.$el.autocomplete("search",{history:true})}else if(options.suggestWhenEmpty&&options.$el.val()===""){options.$el.autocomplete("search","")}})};morpheus.Util.getAutocompleteTokens=function(text,options){options=$.extend({},{trim:true},options);if(options.trim){text=$.trim(text)}if(text===""){return[]}var inQuote=false;var inParen=false;var tokens=[];var currentToken=[];for(var i=0,n=text.length;i
    ");$el.appendTo($dialog);$dialog.appendTo($(document.body));if(!options){options={}}$dialog.dialog({width:670,height:590,title:title,close:function(event,ui){$dialog.remove();if(options.close){options.close()}}})};morpheus.Util.sheetToArray=function(sheet,delim){var r=XLSX.utils.decode_range(sheet["!ref"]);var rows=[];var colors=[];var header=[];for(var C=r.s.c;C<=r.e.c;++C){var val=sheet[XLSX.utils.encode_cell({c:C,r:r.s.r})];var txt=String(XLSX.utils.format_cell(val));header.push(txt)}for(var R=r.s.r;R<=r.e.r;++R){var row=[];var isRowEmpty=true;for(var C=r.s.c;C<=r.e.c;++C){var val=sheet[XLSX.utils.encode_cell({c:C,r:R})];if(!val){row.push("");continue}isRowEmpty=false;var txt=String(XLSX.utils.format_cell(val));if(val.s!=null&&val.s.fgColor!=null){var color="#"+val.s.fgColor.rgb;colors.push({header:header[row.length],color:color,value:txt})}row.push(txt)}if(!isRowEmpty){rows.push(delim?row.join(delim):row)}}rows.colors=colors;return rows};morpheus.Util.linesToObjects=function(lines){var header=lines[0];var array=[];var nfields=header.length;for(var i=1,length=lines.length;i1){var formBuilder=new morpheus.FormBuilder;formBuilder.append({name:"sheet",type:"bootstrap-select",options:sheetNames,required:true,style:"max-width:100px;"});morpheus.FormBuilder.showInModal({title:"Choose Sheet",html:formBuilder.$form,focus:document.activeElement,onClose:function(){var worksheet=workbook.Sheets[formBuilder.getValue("sheet")];var lines=morpheus.Util.sheetToArray(worksheet);callback(null,lines)}})}else{var worksheet=workbook.Sheets[sheetNames[0]];var lines=morpheus.Util.sheetToArray(worksheet);callback(null,lines)}};morpheus.Util.xlsxTo1dArray=function(options,callback){var workbook=XLSX.read(options.data,{type:"binary",cellFormula:false,cellHTML:false,cellStyles:true});var sheetNames=workbook.SheetNames;if(options.prompt&&sheetNames.length>1){var formBuilder=new morpheus.FormBuilder;formBuilder.append({name:"sheet",type:"bootstrap-select",options:sheetNames,required:true,style:"max-width:100px;"});morpheus.FormBuilder.showOkCancel({title:"Choose Sheet",cancel:false,focus:document.activeElement,content:formBuilder.$form,okCallback:function(){var worksheet=workbook.Sheets[formBuilder.getValue("sheet")];callback(null,morpheus.Util.sheetToArray(worksheet,"\t"))}})}else{var worksheet=workbook.Sheets[sheetNames[0]];callback(null,morpheus.Util.sheetToArray(worksheet,"\t"))}};morpheus.Util.getText=function(fileOrUrl){var deferred=$.Deferred();if(morpheus.Util.isString(fileOrUrl)){fetch(fileOrUrl).then(function(response){if(response.ok){return response.text()}else{deferred.reject(response.status+" "+response.statusText)}}).then(function(text){deferred.resolve(text)}).catch(function(err){deferred.reject(err)})}else if(morpheus.Util.isFile(fileOrUrl)){var reader=new FileReader;reader.onload=function(event){deferred.resolve(event.target.result)};reader.readAsText(fileOrUrl)}else{deferred.resolve(fileOrUrl)}return deferred.promise()};morpheus.Util.createOptions=function(values,none){var html=[];if(none){html.push('')}_.each(values,function(val){html.push('")});return html.join("")};morpheus.Util.rankIndexArray=function(index){var rank=[];var n=index.length;for(var j=0;jindex;i--,zeros--){if(str[i]!="0"){break}}if(zeros===index+1){return str.substring(0,index)}if(zeros0;var fieldRegExp=/\\:/g;var predicates=[];var defaultIsExactMatch=options.defaultMatchMode==="exact";tokens.forEach(function(token){var isNot=false;if(token[0]==="-"){token=token.substring(1);isNot=true}var field=null;var semi=token.indexOf(":");if(semi>0){if(!fieldSearchEnabled||token.charCodeAt(semi-1)===92){token=token.replace(fieldRegExp,":")}else{var possibleToken=$.trim(token.substring(semi+1));var possibleField=$.trim(token.substring(0,semi));if(possibleField.length>0&&possibleField[0]==='"'&&possibleField[possibleField.length-1]==='"'){possibleField=possibleField.substring(1,possibleField.length-1)}else if(possibleField.length>0&&possibleField[0]==='"'&&possibleToken[possibleToken.length-1]==='"'&&possibleToken[0]!=='"'){possibleField=possibleField.substring(1,possibleField.length);possibleToken='"'+possibleToken}if(!validateFieldNames||availableFields.indexOf(options.caseSensitive?possibleField:possibleField.toLowerCase())!==-1){token=possibleToken;field=possibleField}}}var predicate;var rangeIndex=-1;var rangeToken=null;var rangeIndicators=["..",">=",">","<=","<","="];for(var i=0;i"){var val=parseFloat(token.substring(rangeIndex+1));if(!isNaN(val)){predicate=new morpheus.Util.GreaterThanPredicate(field,val)}}else if(rangeToken===">="){var val=parseFloat(token.substring(rangeIndex+2));if(!isNaN(val)){predicate=new morpheus.Util.GreaterThanOrEqualPredicate(field,val)}}else if(rangeToken==="<"){var val=parseFloat(token.substring(rangeIndex+1));if(!isNaN(val)){predicate=new morpheus.Util.LessThanPredicate(field,val)}}else if(rangeToken==="<="){var val=parseFloat(token.substring(rangeIndex+2));if(!isNaN(val)){predicate=new morpheus.Util.LessThanOrEqualPredicate(field,val)}}else if(rangeToken==="="){var val=parseFloat(token.substring(rangeIndex+1));predicate=new morpheus.Util.EqualsPredicate(field,val)}else{console.log("Unknown range token:"+rangeToken)}}else if(token[0]==='"'&&token[token.length-1]==='"'){token=token.substring(1,token.length-1);predicate=new morpheus.Util.ExactTermPredicate(field,token)}else if(token[0]==="("&&token[token.length-1]===")"){token=token.substring(1,token.length-1);var values=morpheus.Util.getAutocompleteTokens(token);if(values.length>0){predicate=new morpheus.Util.ExactTermsPredicate(field,values.map(function(val){if(val[0]==='"'&&val[val.length-1]==='"'){val=val.substring(1,val.length-1)}return val.toLowerCase()}))}}else if(token.indexOf("*")!==-1){predicate=new morpheus.Util.RegexPredicate(field,token)}else{predicate=defaultIsExactMatch?new morpheus.Util.ExactTermPredicate(field,token):new morpheus.Util.RegexPredicate(field,token)}if(predicate!=null){predicates.push(isNot?new morpheus.Util.NotPredicate(predicate):predicate)}});return predicates};morpheus.Util.createRegExpStringToMatchText=function(text){var tokens=morpheus.Util.getAutocompleteTokens(text);if(tokens.length===0){return null}var regex=[];_.each(tokens,function(token){if(token[0]==='"'&&token[token.length-1]==='"'){token=token.substring(1,token.length-1);regex.push("^"+morpheus.Util.escapeRegex(token)+"$")}else{regex.push(morpheus.Util.escapeRegex(token))}});return"("+regex.join("|")+")"};morpheus.Util.createRegExpToMatchText=function(text){var s=morpheus.Util.createRegExpStringToMatchText(text);return s==null?null:new RegExp(s,"i")};morpheus.Util.reorderArray=function(array,index){var newArray=[];for(var i=0;i1?s.substring(1):""};morpheus.Util.splitLines=function(lines){var tab=/\t/;var tokens=[];for(var i=0,nlines=lines.length;i');html.push("M");html.push("O");html.push("R");html.push("P");html.push("H");html.push("E");html.push("U");html.push("S");html.push("");html.push("");var $div=$(html.join(""));var colorScale=d3.scale.linear().domain([0,4,7]).range(["#ca0020","#999999","#0571b0"]).clamp(true);var brands=$div.find("span");var index=0;var step=function(){brands[index].style.color=colorScale(index);index++;if(indexLoading...')};morpheus.Util.splitOnNewLine=function(text,commentChar){var commentCharCode=commentChar!==undefined?commentChar.charCodeAt(0):undefined;var lines=text.split(/\n/);if(lines.length===1){var tmp=text.split(/\r/);if(tmp.length>1){lines=tmp}}var rows=[];var rtrim=/\s+$/;for(var i=0,nlines=lines.length;i=this.min&&value<=this.max},getField:function(){return this.field},isNumber:function(){return true},toString:function(){return"NumberRangePredicate "+this.field+":"+this.min+"..."+this.max}};morpheus.Util.GreaterThanPredicate=function(field,val){this.field=field;this.val=val};morpheus.Util.GreaterThanPredicate.prototype={accept:function(value){return value>this.val},getField:function(){return this.field},isNumber:function(){return true}};morpheus.Util.GreaterThanOrEqualPredicate=function(field,val){this.field=field;this.val=val};morpheus.Util.GreaterThanOrEqualPredicate.prototype={accept:function(value){return value>=this.val},getField:function(){return this.field},isNumber:function(){return true}};morpheus.Util.LessThanPredicate=function(field,val){this.field=field;this.val=val};morpheus.Util.LessThanPredicate.prototype={accept:function(value){return value0){s.push(", ")}s.push(key);s.push("=");s.push(value)});return s.join("")},keys:function(){var keys=[];for(var key in this.map){var pair=this.map[key];keys.push(pair.key)}return keys},size:function(){return this.n},equals:function(m){if(m.size()!==this.size()){return false}var ret=true;try{this.forEach(function(value,key){if(value!==m.get(key)){ret=false;throw"break"}})}catch(e){}return ret},setAll:function(map){var _this=this;map.forEach(function(value,key){_this.set(key,value)})},set:function(key,value){var skey="\0"+key;var previous=this.map[skey];if(previous===undefined){this.n++}this.map[skey]={key:key,value:value}},forEach:function(callback){for(var key in this.map){var pair=this.map[key];callback(pair.value,pair.key)}},entries:function(){var array=[];this.forEach(function(value,key){array.push({value:value,key:key})});return array},values:function(){var values=[];for(var key in this.map){var pair=this.map[key];values.push(pair.value)}return values},get:function(key){var skey="\0"+key;var pair=this.map[skey];return pair!==undefined?pair.value:undefined},clear:function(){this.map={};this.n=0},remove:function(key){var skey="\0"+key;var pair=this.map[skey];if(pair!==undefined){delete this.map[skey];this.n--;return pair.value}},has:function(key){var skey="\0"+key;return this.map[skey]!==undefined}};morpheus.Map.fromJSON=function(json){var map=new morpheus.Map;for(var key in json){map.set(key,json[key])}return map};morpheus.Set=function(){this._map=new morpheus.Map};morpheus.Set.prototype={toJSON:function(){var json=[];this.forEach(function(value){json.push(value)});return json},toString:function(){var s=[];this.forEach(function(key){if(s.length>0){s.push(", ")}s.push(key)});return s.join("")},size:function(){return this._map.size()},equals:function(m){return this._map.equals(m)},forEach:function(callback){this._map.forEach(function(value,key){callback(key)})},add:function(value){this._map.set(value,true)},values:function(){var values=[];this._map.forEach(function(value,key){values.push(key)});return values},clear:function(){this._map.clear()},remove:function(key){this._map.remove(key)},has:function(key){return this._map.has(key)}};morpheus.Set.fromJSON=function(json){var set=new morpheus.Set;for(var i=0,length=json.length;i=bufferLength){return null}var buffer=this.buffer;var start=index;var end=start;for(;index");html.push("");html.push('
    "+"
    ");html.push(" Data Matrix');html.push("
    Column'+" Annotations");html.push("
    Row'+" Annotations");html.push('
    ');html.push("");var $el=$(html.join(""));morpheus.Util.readLines(fileOrUrl,true).done(function(lines){var tab=/\t/;for(var i=0,nrows=lines.length;i=dataColumnStart&&row>=dataRowStart){color="#b3cde3"}else if(row<=dataRowStart-1&&cell>=dataColumnStart){color="#fbb4ae"}else if(cell=dataRowStart){color="#ccebc5"}var html=['
    '];if(_.isNumber(value)){html.push(morpheus.Util.nf(value))}else if(morpheus.Util.isArray(value)){var s=[];for(var i=0,length=value.length;i0){s.push(", ")}var val=value[i];s.push(value[i])}html.push(s.join(""))}else{html.push(value)}html.push("
    ");return html.join("")}});var transposedLines;var transposedColumns;$el.find("[name=transpose]").on("click",function(e){if($(this).prop("checked")){if(transposedLines==null){transposedLines=[];for(var j=0,ncols=lines[0].length;jOK');footer.push('');var $footer=$(footer.join(""));morpheus.FormBuilder.showOkCancel({title:"Open",content:$el,close:false,focus:document.activeElement,cancelCallback:function(){callback(null)},okCallback:function(){_this._read(name,lines,dataColumnStart,dataRowStart,callback)}});grid.resizeCanvas()}).fail(function(err){callback(err)})},_read:function(datasetName,lines,dataColumnStart,dataRowStart,cb){var columnCount=lines[0].length;var columns=columnCount-dataColumnStart;var rows=lines.length-dataRowStart;var dataset=new morpheus.Dataset({name:datasetName,rows:rows,columns:columns,dataType:"Float32"});if(dataColumnStart>0){for(var i=0;i0){for(var j=0;j0){pw.push(" ")}pw.push(valueToIndex.get(vector.getValue(i)))}pw.push("\n");return pw.join("")}};morpheus.GctReader=function(){};morpheus.GctReader.prototype={getFormatName:function(){return"gct"},read:function(fileOrUrl,callback){var _this=this;if(morpheus.Util.isFile(fileOrUrl)){this._readChunking(fileOrUrl,callback,false)}else{if(morpheus.Util.isFetchStreamingSupported()){this._readChunking(fileOrUrl,callback,true)}else{this._readNoChunking(fileOrUrl,callback)}}},_readChunking:function(fileOrUrl,callback,useFetch){var _this=this;var lineNumber=0;var version;var numRowAnnotations=1;var numColumnAnnotations=0;var nrows=-1;var ncols=-1;var version=2;var rowMetadataNames=[];var columnMetadataNames=[];var rowMetadata=[[]];var columnMetadata=[[]];var dataColumnStart;var matrix=[];var dataMatrixLineNumberStart;var columnIdFieldName="id";var rowIdFieldName="id";var columnNamesArray;var handleTokens=function(tokens){if(lineNumber===0){var text=tokens[0].trim();if("#1.2"===text){version=2}else if("#1.3"===text){version=3}else{console.log("Unknown version: assuming version 2")}}else if(lineNumber===1){var dimensions=tokens;if(version===3){if(dimensions.length>=4){nrows=parseInt(dimensions[0]);ncols=parseInt(dimensions[1]);numRowAnnotations=parseInt(dimensions[2]);numColumnAnnotations=parseInt(dimensions[3])}else{numRowAnnotations=parseInt(dimensions[0]);numColumnAnnotations=parseInt(dimensions[1])}}else{nrows=parseInt(dimensions[0]);ncols=parseInt(dimensions[1]);if(nrows<=0||ncols<=0){callback("Number of rows and columns must be greater than 0.")}}dataColumnStart=numRowAnnotations+1}else if(lineNumber===2){columnNamesArray=tokens;for(var i=0;iexpectedColumns){var skip=columnNamesArray.length-1;for(var i=columnNamesArray.length-1;i>=0;i--,skip--){if(columnNamesArray[i]!==""){break}}if(skip!==columnNamesArray.length-1){columnNamesArray=columnNamesArray.slice(0,skip+1)}}if(columnNamesArray.length!==expectedColumns){return callback("Expected "+(expectedColumns-2)+" column names, but read "+(columnNamesArray.length-2)+" column names.")}}}var name=columnNamesArray[0];var slashIndex=name.lastIndexOf("/");if(slashIndex!=-1&&slashIndex=4){nrows=parseInt(dimensions[0]);ncols=parseInt(dimensions[1]);numRowAnnotations=parseInt(dimensions[2]);numColumnAnnotations=parseInt(dimensions[3])}else{numRowAnnotations=parseInt(dimensions[0]);numColumnAnnotations=parseInt(dimensions[1])}}else{nrows=parseInt(dimensions[0]);ncols=parseInt(dimensions[1]);if(nrows<=0||ncols<=0){throw new Error("Number of rows and columns must be greater than 0.")}}var columnNamesLine=morpheus.Util.copyString(reader.readLine());if(columnNamesLine==null){throw new Error("No column annotations")}var columnNamesArray=columnNamesLine.split(tab);if(ncols===-1){ncols=columnNamesArray.length-numRowAnnotations-1}if(version==2){var expectedColumns=ncols+2;if(columnNamesArray.length!==expectedColumns){throw new Error("Expected "+(expectedColumns-2)+" column names, but read "+(columnNamesArray.length-2)+" column names.")}}var name=columnNamesArray[0];var slashIndex=name.lastIndexOf("/");var columnIdFieldName="id";var rowIdFieldName="id";if(slashIndex!=-1&&slashIndex0){for(var columnAnnotationIndex=0;columnAnnotationIndex0){for(var columnAnnotationIndex=0;columnAnnotationIndex0){pw.push("\t")}var vector=rowMetadata.get(rowMetadataIndex);var value=vector.getValue(i);if(value!==null){var toString=morpheus.VectorTrack.vectorToString(vector);pw.push(toString(value))}}for(var j=0;j0){pw.push("\t")}var name=rowMetadata.get(i).getName();if(i===0&&name!==columnMetadata.get(0).getName()){name=name+"/"+columnMetadata.get(0).getName()}pw.push(name)}var toString=morpheus.VectorTrack.vectorToString(columnMetadata.get(0));for(var j=0;j1){rowDescriptions=rowMetadata.get(1)}var rowIdToString=morpheus.VectorTrack.vectorToString(rowIds);var rowDescriptionToString=rowDescriptions!=null?morpheus.VectorTrack.vectorToString(rowDescriptions):null;var nf=this.nf;for(var i=0;i1?tokens[1].trim():"";if("BLANK"===description){description=""}var ids=[];for(var i=2;i0){bins[value-1]++}}vector.setValue(i,bins)}};morpheus.MafFileReader.getField=function(fieldNames,headerToIndex){var name;var index;for(var i=0;i "+String(tokens[tumorAllelColumn])}var wrappedVariant=morpheus.Util.wrapNumber(variantCode,variantObject);var variantRow=variantMatrix[rowIndex];if(variantRow===undefined){variantRow=[];variantMatrix[rowIndex]=variantRow}var ccf=-1;var priorCcf=-1;if(ccfColumnIndex!==undefined){var ccfRow=ccfMatrix[rowIndex];if(ccfRow===undefined){ccfRow=[];ccfMatrix[rowIndex]=ccfRow}ccf=parseFloat(tokens[ccfColumnIndex]);priorCcf=ccfRow[columnIndex]||-1}var priorValue=variantRow[columnIndex]||-1;if(variantCode>priorValue){variantRow[columnIndex]=wrappedVariant;if(ccfColumnIndex!==undefined){ccfRow[columnIndex]=ccf}}else if(variantCode===priorValue&&ccf>priorCcf){variantRow[columnIndex]=wrappedVariant;ccfRow[columnIndex]=ccf}}}var dataset=new morpheus.Dataset({name:datasetName,array:variantMatrix,dataType:"Number",rows:geneSymbolToIndex.size(),columns:sampleIdToIndex.size()});var columnIds=dataset.getColumnMetadata().add("id");sampleIdToIndex.forEach(function(index,id){columnIds.setValue(index,id)});var rowIds=dataset.getRowMetadata().add("id");geneSymbolToIndex.forEach(function(index,id){rowIds.setValue(index,id)});for(var i=0,nrows=dataset.getRowCount(),ncols=dataset.getColumnCount();i0){var pairs=[];customNumberToValueMap.forEach(function(value,key){pairs.push({key:key,value:value})});pairs.sort(function(a,b){return a.key===b.key?0:a.key=region.start&&end<=region.end){rowIndices.push(i)}}if(rowIndices.length>0){var slice=morpheus.DatasetUtil.slicedView(dataset,rowIndices,null);var columnView=new morpheus.DatasetColumnView(slice);for(var j=0;j0){dataset=morpheus.SegTabReader.binByRegion(dataset,this.regions)}return dataset},read:function(fileOrUrl,callback){var _this=this;var name=morpheus.Util.getBaseFileName(morpheus.Util.getFileName(fileOrUrl));morpheus.ArrayBufferReader.getArrayBuffer(fileOrUrl,function(err,arrayBuffer){if(err){callback(err)}else{callback(null,_this._read(name,new morpheus.ArrayBufferReader(new Uint8Array(arrayBuffer))))}})}};morpheus.TcgaUtil=function(){};morpheus.TcgaUtil.DISEASE_STUDIES={ACC:"Adrenocortical carcinoma",BLCA:"Bladder Urothelial Carcinoma",BRCA:"Breast invasive carcinoma",CESC:"Cervical squamous cell carcinoma and endocervical adenocarcinoma",CHOL:"Cholangiocarcinoma",COAD:"Colon adenocarcinoma",COADREAD:"Colonrectal adenocarcinoma",DLBC:"Lymphoid Neoplasm Diffuse Large B-cell Lymphoma",ESCA:"Esophageal carcinoma ",GBM:"Glioblastoma multiforme",GBMLGG:"Glioma",HNSC:"Head and Neck squamous cell carcinoma",KICH:"Kidney Chromophobe",KIPAN:"Pan-Kidney Cohort",KIRC:"Kidney renal clear cell carcinoma",KIRP:"Kidney renal papillary cell carcinoma",LAML:"Acute Myeloid Leukemia",LCML:"Chronic Myelogenous Leukemia",LGG:"Brain Lower Grade Glioma",LIHC:"Liver hepatocellular carcinoma",LUAD:"Lung adenocarcinoma",LUSC:"Lung squamous cell carcinoma",MESO:"Mesothelioma",OV:"Ovarian serous cystadenocarcinoma",PAAD:"Pancreatic adenocarcinoma",PCPG:"Pheochromocytoma and Paraganglioma",PRAD:"Prostate adenocarcinoma",READ:"Rectum adenocarcinoma",SARC:"Sarcoma",SKCM:"Skin Cutaneous Melanoma",STAD:"Stomach adenocarcinoma",STES:"Stomach and Esophageal Carcinoma",TGCT:"Testicular Germ Cell Tumors",THCA:"Thyroid carcinoma",THYM:"Thymoma",UCEC:"Uterine Corpus Endometrial Carcinoma",UCS:"Uterine Carcinosarcoma",UVM:"Uveal Melanoma"};morpheus.TcgaUtil.SAMPLE_TYPES={"01":"Primary solid Tumor","02":"Recurrent Solid Tumor","03":"Primary Blood Derived Cancer - Peripheral Blood","04":"Recurrent Blood Derived Cancer - Bone Marrow","05":"Additional - New Primary","06":"Metastatic","07":"Additional Metastatic","08":"Human Tumor Original Cells","09":"Primary Blood Derived Cancer - Bone Marrow",10:"Blood Derived Normal",11:"Solid Tissue Normal",12:"Buccal Cell Normal",13:"EBV Immortalized Normal",14:"Bone Marrow Normal",20:"Control Analyte",40:"Recurrent Blood Derived Cancer - Peripheral Blood",50:"Cell Lines",60:"Primary Xenograft Tissue",61:"Cell Line Derived Xenograft Tissue"};morpheus.TcgaUtil.barcode=function(s){var tokens=s.split("-");var id=tokens[2];var sampleType;if(tokens.length>3){sampleType=tokens[3];if(sampleType.length>2){sampleType=sampleType.substring(0,2)}sampleType=morpheus.TcgaUtil.SAMPLE_TYPES[sampleType]}else{sampleType=morpheus.TcgaUtil.SAMPLE_TYPES["01"]}return{id:id.toLowerCase(),sampleType:sampleType}};morpheus.TcgaUtil.setIdAndSampleType=function(dataset){var idVector=dataset.getColumnMetadata().get(0);var participantId=dataset.getColumnMetadata().add("participant_id");var sampleType=dataset.getColumnMetadata().add("sample_type");for(var i=0,size=idVector.size();imaxColumns){maxColumns=datasets[i].getColumnCount();maxIndex=i}if(datasets[i].getName()==="mutations_merged.maf"){maxColumns=Number.MAX_VALUE;maxIndex=i}}var datasetIndices=[];datasetIndices.push(maxIndex);for(var i=0;i1){for(var i=1;istandardDeviation){returnValue=minStdev}if(returnValue=groupingValue){aHit++}else{aMiss++}}}var bHit=0;var bMiss=0;for(var j=0,size=listTwo.size();j=groupingValue){bHit++}else{bMiss++}}}var N=aHit+aMiss+bHit+bMiss;var K=aHit+bHit;var n=aHit+aMiss;var k=aHit;var a=k;var b=K-k;var c=n-k;var d=N+k-n-K;return[a,b,c,d]};morpheus.FisherExact=function(listOne,listTwo){var abcd=morpheus.createContingencyTable(listOne,listTwo,1);return morpheus.FisherExact.fisherTest(abcd[0],abcd[1],abcd[2],abcd[3])};morpheus.createFisherExact=function(groupingValue){var f=function(listOne,listTwo){var abcd=morpheus.createContingencyTable(listOne,listTwo,groupingValue);return morpheus.FisherExact.fisherTest(abcd[0],abcd[1],abcd[2],abcd[3])};return f};morpheus.FisherExact.phyper=function(a,b,c,d){return Math.exp(morpheus.FisherExact.logFactorial(a+b)+morpheus.FisherExact.logFactorial(c+d)+morpheus.FisherExact.logFactorial(a+c)+morpheus.FisherExact.logFactorial(b+d)-(morpheus.FisherExact.logFactorial(a)+morpheus.FisherExact.logFactorial(b)+morpheus.FisherExact.logFactorial(c)+morpheus.FisherExact.logFactorial(d)+morpheus.FisherExact.logFactorial(a+b+c+d)))};morpheus.FisherExact.logFactorials=[0,0,.6931471805599453,1.791759469228055,3.1780538303479458,4.787491742782046,6.579251212010101,8.525161361065415,10.60460290274525,12.801827480081469,15.104412573075516,17.502307845873887,19.987214495661885,22.552163853123425,25.19122118273868,27.89927138384089,30.671860106080672,33.50507345013689,36.39544520803305,39.339884187199495,42.335616460753485,45.38013889847691,48.47118135183523,51.60667556776438,54.78472939811232,58.00360522298052,61.261701761002,64.55753862700634,67.88974313718154,71.25703896716801];morpheus.FisherExact.logFactorial=function(k){if(k>=30){var C0=.9189385332046728;var C1=.08333333333333333;var C3=-.002777777777777778;var C5=.0007936507936507937;var C7=-.0005952380952380953;var r=1/k;var rr=r*r;return(k+.5)*Math.log(k)-k+C0+r*(C1+rr*(C3+rr*(C5+rr*C7)))}return morpheus.FisherExact.logFactorials[k]};morpheus.FisherExact.fisherTest=function(a,b,c,d){var p=morpheus.FisherExact.phyper(a,b,c,d);var sum=p;for(var _a=0,n=a+b+c+d;_a<=n;_a++){var _b=a+b-_a;var _c=a+c-_a;var _d=b+d-_b;if(_a!==a&&_b>=0&&_c>=0&&_d>=0){var _p=morpheus.FisherExact.phyper(_a,_b,_c,_d);if(_p<=p){sum+=_p}}}return Math.min(1,sum)};morpheus.FisherExact.toString=function(){return"Fisher Exact Test"};morpheus.FoldChange=function(list1,list2){var m1=morpheus.Mean(list1);var m2=morpheus.Mean(list2);return m1/m2};morpheus.FoldChange.toString=function(){return"Fold Change"};morpheus.MeanDifference=function(list1,list2){var m1=morpheus.Mean(list1);var m2=morpheus.Mean(list2);var diff=m1-m2;return diff};morpheus.MeanDifference.toString=function(){return"Mean Difference"};morpheus.TTest=function(list1,list2){var m1=morpheus.Mean(list1);var m2=morpheus.Mean(list2);var s1=Math.sqrt(morpheus.Variance(list1,m1));var s2=Math.sqrt(morpheus.Variance(list2,m2));var n1=morpheus.CountNonNaN(list1);var n2=morpheus.CountNonNaN(list2);return(m1-m2)/Math.sqrt(s1*s1/n1+s2*s2/n2)};morpheus.TTest.toString=function(){return"T-Test"};morpheus.DegreesOfFreedom=function(v1,v2,n1,n2){return(v1/n1+v2/n2)*(v1/n1+v2/n2)/(v1*v1/(n1*n1*(n1-1))+v2*v2/(n2*n2*(n2-1)))};morpheus.Spearman=function(list1,list2){var flist1=[];var flist2=[];for(var i=0,n=list1.size();i0;var y=yval>0;if(x&&y){andCount++}else if(x||y){orCount++}}if(orCount===0){return 1}return 1-andCount/orCount};morpheus.Jaccard.toString=function(){return"Jaccard distance"};morpheus.Cosine=function(listOne,listTwo){var sumX2=0;var sumY2=0;var sumXY=0;for(var i=0,size=listOne.size();iCause: ");message.push(err.message)}retDef.reject(message.join(""))});promises.push(p)});if(promises.length===0){retDef.reject("No datasets specified.")}$.when.apply($,promises).then(function(){retDef.resolve(morpheus.DatasetUtil.join(loadedDatasets,"id"))});return retDef};morpheus.DatasetUtil.annotate=function(options){var retDef=$.Deferred();var promises=[];var functions=[];var isColumns=options.isColumns;_.each(options.annotations,function(ann,annotationIndex){if(morpheus.Util.isArray(ann.file)){functions[annotationIndex]=function(dataset){(new morpheus.OpenFileTool).annotate(ann.file,dataset,isColumns,null,ann.datasetField,ann.fileField,ann.include)}}else{var result=morpheus.Util.readLines(ann.file);var fileName=morpheus.Util.getFileName(ann.file);var deferred=$.Deferred();promises.push(deferred);result.fail(function(message){deferred.reject(message)});result.done(function(lines){if(morpheus.Util.endsWith(fileName,".gmt")){var sets=(new morpheus.GmtReader).parseLines(lines);functions[annotationIndex]=function(dataset){(new morpheus.OpenFileTool).annotate(null,dataset,isColumns,sets,ann.datasetField,ann.fileField)};deferred.resolve()}else if(morpheus.Util.endsWith(fileName,".cls")){functions[annotationIndex]=function(dataset){(new morpheus.OpenFileTool).annotateCls(null,dataset,fileName,isColumns,lines)};deferred.resolve()}else{functions[annotationIndex]=function(dataset){(new morpheus.OpenFileTool).annotate(lines,dataset,isColumns,null,ann.datasetField,ann.fileField,ann.include,ann.transposed)};deferred.resolve()}})}});$.when.apply($,promises).then(function(){retDef.resolve(functions)});return retDef};morpheus.DatasetUtil.read=function(fileOrUrl,options){if(fileOrUrl==null){throw"File is null"}if(options==null){options={}}var isFile=morpheus.Util.isFile(fileOrUrl);var isString=morpheus.Util.isString(fileOrUrl);var ext=options.extension?options.extension:morpheus.Util.getExtension(morpheus.Util.getFileName(fileOrUrl));var datasetReader;var str=fileOrUrl.toString();if(ext===""&&str!=null&&str.indexOf("blob:")===0){datasetReader=options.interactive?new morpheus.Array2dReaderInteractive:new morpheus.TxtReader}else{datasetReader=morpheus.DatasetUtil.getDatasetReader(ext,options);if(datasetReader==null){datasetReader=isFile?options.interactive?new morpheus.Array2dReaderInteractive:new morpheus.TxtReader:new morpheus.GctReader}}if(isString||isFile){var deferred=$.Deferred();if(options.background){var path=morpheus.Util.getScriptPath();var blob=new Blob(["self.onmessage = function(e) {"+"importScripts(e.data.path);"+"var ext = morpheus.Util.getExtension(morpheus.Util"+".getFileName(e.data.fileOrUrl));"+"var datasetReader = morpheus.DatasetUtil.getDatasetReader(ext,"+"\te.data.options);"+"datasetReader.read(e.data.fileOrUrl, function(err,dataset) {"+"\tself.postMessage(dataset);"+"\t});"+"}"]);var blobURL=window.URL.createObjectURL(blob);var worker=new Worker(blobURL);worker.addEventListener("message",function(e){deferred.resolve(morpheus.Dataset.fromJSON(e.data));window.URL.revokeObjectURL(blobURL)},false);worker.postMessage({path:path,fileOrUrl:fileOrUrl,options:options})}else{datasetReader.read(fileOrUrl,function(err,dataset){if(err){deferred.reject(err)}else{deferred.resolve(dataset)}})}var pr=deferred.promise();pr.toString=function(){return""+fileOrUrl};return pr}else if(typeof fileOrUrl.done==="function"){return fileOrUrl}else{if(fileOrUrl.promise){return fileOrUrl}var deferred=$.Deferred();if(fileOrUrl.getRowCount){deferred.resolve(fileOrUrl)}else{deferred.resolve(morpheus.Dataset.fromJSON(fileOrUrl))}return deferred.promise()}};morpheus.DatasetUtil.toObjectArray=function(dataset,options){var columns=options.columns||[0];var columnFields=options.columnFields||["value"];if(columnFields.length!==columns.length){throw"columns.length !== columnFields.length"}var metadataFields=options.metadataFields;var rowMetadata=dataset.getRowMetadata();if(!metadataFields){metadataFields=morpheus.MetadataUtil.getMetadataNames(rowMetadata)}var vectors=morpheus.MetadataUtil.getVectors(rowMetadata,metadataFields);var array=[];for(var i=0;i0?tokens[tokens.selectionStartIndex]:"";token=$.trim(token);var seriesIndices=[];for(var i=0,nrows=dataset.getRowCount();i'+field+":",show:true})});return cb(matches)}var field=null;var semi=token.indexOf(":");if(semi>0){if(token.charCodeAt(semi-1)!==92){var possibleField=$.trim(token.substring(0,semi));if(possibleField.length>0&&possibleField[0]==='"'&&possibleField[token.length-1]==='"'){possibleField=possibleField.substring(1,possibleField.length-1)}var index=fields.indexOf(possibleField);if(index!==-1){token=$.trim(token.substring(semi+1));field=possibleField}}}var set=new morpheus.Set;var regex=new RegExp("^"+morpheus.Util.escapeRegex(token),"i");var max=10;loop:for(var k=0,nseries=seriesIndices.length;k'+field+":"+''+val+""})});if(field==null){fields.forEach(function(field){if(regex.test(field)){matches.push({value:field+":",label:''+field+":",show:true})}})}cb(matches)}};morpheus.DatasetUtil.fill=function(dataset,value,seriesIndex){seriesIndex=seriesIndex||0;for(var i=0,nrows=dataset.getRowCount(),ncols=dataset.getColumnCount();i0){newDataset.addSeries({name:dataset.getName(seriesIndex),rows:dataset.getRowCount(),columns:dataset.getColumnCount(),dataType:dataset.getDataType(seriesIndex)})}for(var i=0,nrows=dataset.getRowCount(),ncols=dataset.getColumnCount();i0){s.push(", ")}s.push(morpheus.Util.nf(dataset.getValue(i,j,seriesIndex)))}s.push("\n")}return s.join("")};morpheus.DatasetUtil.getNonEmptyRows=function(dataset){var rowsToKeep=[];for(var i=0,nrows=dataset.getRowCount();i0}};morpheus.Util.extend(morpheus.CombinedFilter,morpheus.Events);morpheus.IndexFilter=function(acceptIndicesSet,name,isColumns){this.acceptIndicesSet=acceptIndicesSet;this.name=name;this.columns=isColumns};morpheus.IndexFilter.prototype={enabled:true,isColumns:function(){return this.columns},isEnabled:function(){return this.enabled},setAcceptIndicesSet:function(acceptIndicesSet){this.acceptIndicesSet=acceptIndicesSet},setEnabled:function(enabled){this.enabled=enabled},equals:function(filter){return filter instanceof morpheus.IndexFilter&&this.acceptIndicesSet.equals(filter.acceptIndicesSet)},init:function(dataset){},toString:function(){return this.name},accept:function(index){return this.acceptIndicesSet.has(index)}};morpheus.VectorFilter=function(set,maxSetSize,name,isColumns){this.set=set;this.name=name;this.maxSetSize=maxSetSize;this.columns=isColumns};morpheus.VectorFilter.prototype={enabled:true,isColumns:function(){return this.columns},isEnabled:function(){return this.enabled&&this.set.size()>0&&this.set.size()!==this.maxSetSize&&this.vector!=null},setEnabled:function(enabled){this.enabled=enabled},equals:function(filter){return filter instanceof morpheus.VectorFilter&&this.name===filter.name},init:function(dataset){this.vector=dataset.getRowMetadata().getByName(this.name)},toString:function(){return this.name},accept:function(index){return this.set.has(this.vector.getValue(index))}};morpheus.NotNullFilter=function(name,isColumns){this.name=name;this.columns=isColumns};morpheus.NotNullFilter.prototype={enabled:true,isColumns:function(){return this.columns},isEnabled:function(){return this.enabled&&this.vector!=null},setEnabled:function(enabled){this.enabled=enabled},equals:function(filter){return filter instanceof morpheus.NotNullFilter&&this.name===filter.name},init:function(dataset){this.vector=dataset.getRowMetadata().getByName(this.name)},toString:function(){return this.name},accept:function(index){return this.vector.getValue(index)!=null}};morpheus.RangeFilter=function(min,max,name,isColumns){this.min=min;this.max=max;this.name=name;this.columns=isColumns};morpheus.RangeFilter.prototype={enabled:true,isColumns:function(){return this.columns},isEnabled:function(){return this.enabled&&(!isNaN(this.min)||!isNaN(this.max))&&this.vector},setEnabled:function(enabled){this.enabled=enabled},setMin:function(value){this.min=isNaN(value)?-Number.MAX_VALUE:value},setMax:function(value){this.max=isNaN(value)?Number.MAX_VALUE:value},equals:function(filter){return filter instanceof morpheus.RangeFilter&&this.name===filter.name},init:function(dataset){this.vector=dataset.getRowMetadata().getByName(this.name)},toString:function(){return this.name},accept:function(index){var value=this.vector.getValue(index);return value>=this.min&&value<=this.max}};morpheus.TopNFilter=function(n,direction,name,isColumns){this.n=n;this.direction=direction;this.name=name;this.columns=isColumns};morpheus.TopNFilter.TOP=0;morpheus.TopNFilter.BOTTOM=1;morpheus.TopNFilter.TOP_BOTTOM=2;morpheus.TopNFilter.prototype={enabled:true,isColumns:function(){return this.columns},isEnabled:function(){return this.enabled&&this.n>0&&this.vector},setEnabled:function(enabled){this.enabled=enabled},setN:function(value){this.n=value},setDirection:function(direction){this.direction=direction},equals:function(filter){return filter instanceof morpheus.TopNFilter&&this.name===filter.name&&this.n===filter.n&&this.direction===filter.direction},init:function(dataset){if(!this.vector||this.vector!==dataset.getRowMetadata().getByName(this.name)){var vector=dataset.getRowMetadata().getByName(this.name);if(vector==null){vector={getValue:function(){},size:function(){return 0}}}this.vector=vector;var set=new morpheus.Set;for(var i=0,size=vector.size();i=topAndBottomValues[0]}}else if(this.direction===morpheus.TopNFilter.BOTTOM){this.f=function(val){return isNaN(val)?false:val<=topAndBottomValues[1]}}else{this.f=function(val){return isNaN(val)?false:val>=topAndBottomValues[0]||val<=topAndBottomValues[1]}}},accept:function(index){return this.f(this.vector.getValue(index))},toString:function(){return this.name}};morpheus.AlwaysTrueFilter=function(){};morpheus.AlwaysTrueFilter.prototype={isEnabled:function(){return false},setEnabled:function(enabled){},equals:function(filter){return filter instanceof morpheus.AlwaysTrueFilter},init:function(dataset){},toString:function(){return"AlwaysTrue"},accept:function(index){return true}};morpheus.CombinedFilter.fromJSON=function(combinedFilter,json){combinedFilter.setAnd(json.isAnd);json.filters.forEach(function(filter){var name=filter.name!=null?filter.name:filter.field;if(filter.type==="set"){var set=new morpheus.Set;filter.values.forEach(function(value){set.add(value)});combinedFilter.add(new morpheus.VectorFilter(set,filter.maxSetSize,name,filter.isColumns))}else if(filter.type==="range"){combinedFilter.add(new morpheus.RangeFilter(filter.min,filter.max,name,filter.isColumns))}else if(filter.type==="top"){if(_.isString(filter.direction)){if(filter.direction==="top"){filter.direction=morpheus.TopNFilter.TOP}else if(filter.direction==="bottom"){filter.direction=morpheus.TopNFilter.BOTTOM}else if(filter.direction==="topAndBottom"){filter.direction=morpheus.TopNFilter.TOP_BOTTOM}}combinedFilter.add(new morpheus.TopNFilter(filter.n,filter.direction,name,filter.isColumns))}else if(filter.type==="index"){var set=new morpheus.Set;filter.indices.forEach(function(value){set.add(value)});combinedFilter.add(new morpheus.IndexFilter(set,name,filter.isColumns))}else{console.log("Unknown filter type")}})};morpheus.CombinedFilter.toJSON=function(filter){var json={isAnd:filter.isAnd(),filters:[]};filter.getFilters().forEach(function(filter){if(filter.isEnabled()){if(filter instanceof morpheus.VectorFilter){json.filters.push({name:filter.name,isColumns:filter.isColumns(),values:filter.set.values(),maxSetSize:filter.maxSetSize,type:"set"})}else if(filter instanceof morpheus.RangeFilter){json.filters.push({name:filter.name,isColumns:filter.isColumns(),min:filter.min,max:filter.max,type:"range"})}else if(filter instanceof morpheus.TopNFilter){json.filters.push({name:filter.name,isColumns:filter.isColumns(),n:filter.n,direction:filter.direction,type:"top"})}else if(filter instanceof morpheus.IndexFilter){json.filters.push({name:filter.name,isColumns:filter.isColumns(),indices:filter.acceptIndicesSet.values(),type:"index"})}}});return json};morpheus.IndexMapper=function(project,isRows){this.project=project;this.isRows=isRows;this.sortKeys=[];this.modelToView=null;this.filteredModelIndices=null;this.filteredSortedModelIndices=null;this.filter=new morpheus.CombinedFilter(true);this._filter();this._sort()};morpheus.IndexMapper.prototype={convertModelIndexToView:function(modelIndex){var index=this.modelToView.get(modelIndex);return index!==undefined?index:-1},convertViewIndexToModel:function(viewIndex){return viewIndex=0?this.filteredSortedModelIndices[viewIndex]:-1},convertToView:function(){return this.filteredSortedModelIndices},setFilter:function(filter){this.filter=filter;this._filter();this._sort()},_filter:function(){var filter=this.filter;var dataset=this.project.getFullDataset();var count=this.isRows?dataset.getRowCount():dataset.getColumnCount();var filteredModelIndices;if(filter!=null){filter.init(dataset);if(filter.isEnabled()){filteredModelIndices=[];for(var i=0;i0){var dataset=this.project.getFullDataset();var nkeys=sortKeys.length;for(var i=0;i=this.indices.length){throw"index out of bounds"}return this.model.get(this.indices[index])},remove:function(index){if(index<0||index>=this.indices.length){throw"index out of bounds"}var v=this.model.remove(this.indices[index]);this.indices.splice(index,1);return v},getByName:function(name){var index=morpheus.MetadataUtil.indexOf(this,name);return index!==-1?this.get(index):undefined}};morpheus.Util.extend(morpheus.MetadataModelColumnView,morpheus.MetadataModelAdapter);morpheus.MetadataModelItemView=function(model,indices){this.model=model;this.indices=indices};morpheus.MetadataModelItemView.prototype={add:function(name){var v=this.model.add(name);return new morpheus.SlicedVector(v,this.indices)},getItemCount:function(){return this.indices.length},get:function(index){var v=this.model.get(index);if(v===undefined){return undefined}return new morpheus.SlicedVector(v,this.indices)},getByName:function(name){var v=this.model.getByName(name);if(v===undefined){return undefined}return new morpheus.SlicedVector(v,this.indices)},getMetadataCount:function(){return this.model.getMetadataCount()}};morpheus.Util.extend(morpheus.MetadataModelItemView,morpheus.MetadataModelAdapter);morpheus.MetadataModel=function(itemCount){this.itemCount=itemCount;this.vectors=[]};morpheus.MetadataModel.prototype={add:function(name,options){var index=morpheus.MetadataUtil.indexOf(this,name);var oldVector;if(index!==-1){oldVector=this.get(index)}var v=new morpheus.Vector(name,this.getItemCount());if(oldVector!=null){for(var i=0,size=oldVector.size();i0?tokens[tokens.selectionStartIndex]:"";token=$.trim(token);var fieldSearchFieldName=null;if(token!==""){var semi=token.indexOf(":");if(semi>0){if(token.charCodeAt(semi-1)!==92){var possibleField=$.trim(token.substring(0,semi));if(possibleField.length>0&&possibleField[0]==='"'&&possibleField[token.length-1]==='"'){possibleField=possibleField.substring(1,possibleField.length-1)}var index=morpheus.MetadataUtil.indexOf(searchModel,possibleField);if(index!==-1){fieldSearchFieldName=possibleField;token=$.trim(token.substring(semi+1));searchModel=new morpheus.MetadataModelColumnView(model,[index])}}}var set=new morpheus.Set;regex=new RegExp(morpheus.Util.escapeRegex(token),"i");regexMatch=new RegExp("("+morpheus.Util.escapeRegex(token)+")","i");var max=10;var vectors=[];var isArray=[];for(var j=0;j'+field+":"+""+val.replace(regexMatch,"$1")+""})})}if(regex==null){regex=new RegExp(".*","i")}for(var j=0;j'+(regexMatch==null?field:field.replace(regexMatch,"$1"))+":"+(dataType==="number"?".., >, <, >=, <=,'+" =":""),show:true})}}}cb(matches)}};morpheus.MetadataUtil.getMetadataNames=function(metadataModel){var names=[];for(var i=0,count=metadataModel.getMetadataCount();icurMax){curMax=mean;curIndex=i}}return{value:curMax,index:curIndex}};morpheus.Positions=function(){this.spaces=undefined;this.defaultPositionFunction=function(index){return this.size*index};this.squishedPositionFunction=function(index){return this.positions[index]};this.positionFunction=this.defaultPositionFunction;this.squishedIndices={};this.isSquished=false};morpheus.Positions.getBottom=function(rect,rowPositions){var bottom=rowPositions.getLength();if(rect!=null){bottom=1+rowPositions.getIndex(rect.y+rect.height,false);bottom=Math.max(0,bottom);bottom=Math.min(rowPositions.getLength(),bottom)}return bottom};morpheus.Positions.getTop=function(rect,rowPositions){var top=0;if(rect!=null){top=rowPositions.getIndex(rect.y,false)-1;top=Math.max(0,top);top=Math.min(rowPositions.getLength(),top)}return top};morpheus.Positions.getLeft=function(rect,columnPositions){var left=0;if(rect!=null){left=columnPositions.getIndex(rect.x,false)-1;left=Math.max(0,left);left=Math.min(columnPositions.getLength(),left)}return left};morpheus.Positions.getRight=function(rect,columnPositions){var right=columnPositions.getLength();if(rect!=null){right=1+columnPositions.getIndex(rect.x+rect.width,false);right=Math.min(columnPositions.getLength(),right)}return right};morpheus.Positions.prototype={length:0,size:13,squishFactor:.1,compress:true,copy:function(){var copy=new morpheus.Positions;if(this.spaces){copy.spaces=this.spaces.slice()}copy.compress=this.compress;copy.squishFactor=this.squishFactor;copy.size=this.size;copy.length=this.length;if(this.isSquished){copy.positionFunction=copy.squishedPositionFunction;copy.squishedIndices=_.clone(this.squishedIndices);copy.isSquished=true}return copy},getIndex:function(position,exact){if(this.getLength()===0){return-1}if(exact){return this.binaryExactSearch(position)}else{return this.binaryInExactSearch(position)}},getLength:function(){return this.length},getPosition:function(index){return this.positionFunction(index)+(this.spaces!==undefined?this.spaces[index]:0)},getItemSize:function(index){return this.squishedIndices[index]===true?this.size*this.squishFactor:this.size},getSize:function(){return this.size},setSpaces:function(spaces){this.spaces=spaces},setLength:function(length){this.length=length;this.trigger("change",{source:this,value:"length"})},setSize:function(size){this.size=size;if(this.isSquished){this.setSquishedIndices(this.squishedIndices)}this.trigger("change",{source:this,value:"size"})},setSquishedIndices:function(squishedIndices){if(squishedIndices!=null){var compress=this.compress;this.squishedIndices=squishedIndices;var positions=[];var squishFactor=this.squishFactor;var size=this.size;var position=0;for(var i=0,length=this.getLength();i>1;var midVal=this.getPosition(mid);var size=this.getItemSize(mid);if(midVal<=position&&positionposition){high=mid-1}else{return mid}}return-1},binaryInExactSearch:function(position){var low=0;var high=this.getLength()-1;var maxIndex=this.getLength()-1;if(position<=this.getPosition(0)){return 0}while(low<=high){var mid=low+high>>1;var midVal=this.getPosition(mid);var size=this.getItemSize(mid);var nextStart=maxIndex===mid?midVal+size:this.getPosition(mid+1);if(midVal<=position&&positionposition){high=mid-1}else{return mid}}return low-1}};morpheus.Util.extend(morpheus.Positions,morpheus.Events);morpheus.Project=function(dataset){this.originalDataset=dataset;this.rowIndexMapper=new morpheus.IndexMapper(this,true);this.columnIndexMapper=new morpheus.IndexMapper(this,false);this.groupRows=[];this.groupColumns=[];this.rowColorModel=new morpheus.VectorColorModel;this.columnColorModel=new morpheus.VectorColorModel;this.rowShapeModel=new morpheus.VectorShapeModel;this.columnShapeModel=new morpheus.VectorShapeModel;this.rowFontModel=new morpheus.VectorFontModel;this.columnFontModel=new morpheus.VectorFontModel;this.hoverColumnIndex=-1;this.hoverRowIndex=-1;this.columnSelectionModel=new morpheus.SelectionModel(this,true);this.rowSelectionModel=new morpheus.SelectionModel(this,false);this.elementSelectionModel=new morpheus.ElementSelectionModel(this);this.symmetricProjectListener=null;morpheus.Project._recomputeCalculatedColumnFields(this.originalDataset,morpheus.VectorKeys.RECOMPUTE_FUNCTION_NEW_HEAT_MAP);morpheus.Project._recomputeCalculatedColumnFields(new morpheus.TransposedDatasetView(this.originalDataset),morpheus.VectorKeys.RECOMPUTE_FUNCTION_NEW_HEAT_MAP)};morpheus.Project.Events={DATASET_CHANGED:"datasetChanged",ROW_GROUP_BY_CHANGED:"rowGroupByChanged",COLUMN_GROUP_BY_CHANGED:"columnGroupByChanged",ROW_FILTER_CHANGED:"rowFilterChanged",COLUMN_FILTER_CHANGED:"columnFilterChanged",ROW_SORT_ORDER_CHANGED:"rowSortOrderChanged",COLUMN_SORT_ORDER_CHANGED:"columnSortOrderChanged",ROW_TRACK_REMOVED:"rowTrackRemoved",COLUMN_TRACK_REMOVED:"columnTrackRemoved"};morpheus.Project._recomputeCalculatedColumnFields=function(dataset,key){var metadata=dataset.getColumnMetadata();var view=new morpheus.DatasetColumnView(dataset);var nfound=0;for(var metadataIndex=0,count=metadata.getMetadataCount();metadataIndexs2.data){return 1}return 0})}for(i=0;i.4){data.setValue(ind,j,.5*(row_mean[Math.floor(ranks[i])-1]+row_mean[Math.floor(ranks[i])]))}else{data.setValue(ind,j,row_mean[Math.floor(ranks[i])-1])}}}};morpheus.QNorm.get_di_matrix=function(data){var i,j;var rows=data.getRowCount();var cols=data.getColumnCount();var dimat=[];for(j=0;j=0;i++,bottomIndex--,counter++){indexCounterPairs.push([bottomPairs[bottomIndex].index,counter])}for(var i=indexCounterPairs.length-1,j=0;i>=0;i--,j++){var item_i=indexCounterPairs[i];var item_j=indexCounterPairs[j];modelIndexToValue[item_i[0]]=item_j[1]}}for(var i=0,length=missingIndices.length;i1?morpheus.Median:function(row){return row.getValue(0)};if(this.sortOrder===morpheus.SortKey.SortOrder.TOP_N){var pairs=[];var missingIndices=[];for(var i=0,nrows=visibleModelIndices.length;i=0;i++,bottomIndex--,counter++){indexCounterPairs.push([bottomPairs[bottomIndex].index,counter])}for(var i=indexCounterPairs.length-1,j=0;i>=0;i--,j++){var item_i=indexCounterPairs[i];var item_j=indexCounterPairs[j];modelIndexToValue[item_i[0]]=item_j[1]}}for(var i=0,length=missingIndices.length;i=0){aPosMax=value>aPosMax?value:aPosMax}else{aNegMax=valuea?aNegMax:a}}return a};morpheus.SortKey.ARRAY_ASCENDING_COMPARATOR=function(summary){return function(a,b){var aNaN=a==null;var bNaN=b==null;if(aNaN&&bNaN){return 0}if(aNaN){return 1}if(bNaN){return-1}a=summary(a);b=summary(b);aNaN=isNaN(a);bNaN=isNaN(b);if(aNaN&&bNaN){return 0}if(aNaN){return 1}if(bNaN){return-1}return a===b?0:a0){var existingIndex=-1;for(var j=0;jMath.abs(max)){max=p}}return max};f.toString=function(){var s=["Maximum of "];for(var i=0,length=percentiles.length;i0&&length>2){s.push(", ")}if(i===length-1){s.push(length==2?" and ":"and ")}s.push(percentiles[i])}s.push(" percentiles");return s.join("")};return f};morpheus.CountIf=function(vector,criteria){if(!/[<>=!]/.test(criteria)){criteria='=="'+criteria+'"'}var matches=0;for(var i=0,size=vector.size();i0;i--){var bigPValue=nominalPValues[pValueIndices[i]];var smallPValue=nominalPValues[pValueIndices[i-1]];if(bigPValue==smallPValue){ranks[pValueIndices[i-1]]=ranks[pValueIndices[i]]}}for(var i=0;i=lowerOutlier){lowerAdjacentValue=Math.min(lowerAdjacentValue,value)}sum+=value}var mean=sum/values.length;if(lowerAdjacentValue>q1){lowerAdjacentValue=q1}if(upperAdjacentValue=min&&value<=max){var bin=Math.floor((value-min)/binSize);if(bin<0){bin=0}else if(bin>=numberOfBins){bin=numberOfBins-1}binNumberToOccurences[bin]++}total++}}if(cumulative){for(var i=numberOfBins-2;i>=0;i--){binNumberToOccurences[i]+=binNumberToOccurences[i+1]}}if(percent){var percents=new Float32Array(numberOfBins);for(var i=0;i1){found=true}}}if(found){for(var i=0,nrows=newValues.length;in){return true}}return false};morpheus.VectorUtil.createSpanMap=function(vector){var previous=vector.getValue(0);var startIndexToEndIndex=new morpheus.Map;var start=0;for(var i=1,nrows=vector.size();imax?value:max}}}}}else if(isArray){for(var i=0,size=vector.size();imax?value:max}}}}}else{for(var i=0,size=vector.size();imax?value:max}}}return{min:min,max:max}};morpheus.VectorUtil.getFirstNonNull=function(vector){for(var i=0,length=vector.size();i
  • Home
  • ');html.push('
  • Contact
  • ');html.push('
  • Documentation
  • ');html.push('
  • Tutorial
  • ');html.push('
  • Configuration
  • ');html.push('
  • Source Code
  • ');html.push('
  • R Interface
  • ');html.push('
  • Command Line
  • ');html.push("");this.$el=$(html.join(""));this.$el.find("[data-name=contact]").on("click",function(e){morpheus.FormBuilder.showInModal({title:"Contact",html:"Please email us at morpheus@broadinstitute.org",focus:document.activeElement});e.preventDefault()})};morpheus.HistogramLegend=function(dataset,colorScheme,metadataValue){morpheus.AbstractCanvas.call(this,true);this.colorScheme=colorScheme;this.metadataValue=metadataValue;this.dataset=dataset;this.binNumberToOccurences=null;this.setBounds({width:250,height:70});this.name=null;this.canvas.style.position="";this.canvas.style.border="1px solid LightGrey"};morpheus.HistogramLegend.prototype={binSize:0,maxCount:0,total:0,setName:function(name){this.name=name},setBinSize:function(binSize){this.binSize=binSize},buildHistogram:function(){var binSize=this.binSize;var dataset=this.dataset;var metadataValue=this.metadataValue;var colorScheme=this.colorScheme;var min=colorScheme.getMin();var max=colorScheme.getMax();if(min===max){min-=.5;max+=.5}var vector=dataset.getRowMetadata().getByName(colorScheme.getSeparateColorSchemeForRowMetadataField());var numberOfBins=Math.ceil((max-min)/binSize);var binNumberToOccurences=new Uint32Array(numberOfBins);this.binNumberToOccurences=binNumberToOccurences;var index=0;for(var i=0,nrows=dataset.getRowCount();i=numberOfBins){bin=numberOfBins-1}binNumberToOccurences[bin]++}}}var maxCount=0;var total=0;for(var i=0;i=maxCount?count:maxCount;total+=count}this.maxCount=maxCount;this.total=total},draw:function(clip,context){this.buildHistogram();var colorScheme=this.colorScheme;var canvasWidth=this.getUnscaledWidth()-50;var valueToPosition=d3.scale.linear().domain([colorScheme.getMin(),colorScheme.getMax()]).range([0,canvasWidth]).clamp(true);var histogramHeight=30;var countToPosition=d3.scale.linear().domain([0,this.maxCount/this.total]).range([histogramHeight,0]).clamp(true);var binNumberToOccurences=this.binNumberToOccurences;var min=colorScheme.getMin();var binSize=this.binSize;var y0=countToPosition(0);if(this.name!=null){context.font="11px "+morpheus.CanvasUtil.getFontFamily(context);context.fillStyle="black";context.lineWidth=1;context.fillText(this.name,.5,12);context.translate(0,14)}context.lineWidth=.2;context.strokeStyle="#D3D2C2";context.fillStyle="#D3D2C2";context.translate(25,0);context.beginPath();context.moveTo(0,y0);context.lineTo(canvasWidth,y0);context.stroke();context.lineWidth=1;context.strokeStyle="white";for(var i=0,numberOfBins=binNumberToOccurences.length;i0){count/=this.total;var start=min+i*binSize;var end=start+binSize;var x=valueToPosition(start);var width=valueToPosition(end)-x;var y=countToPosition(count);context.rect(x,y0,width,y-y0);context.fill();context.stroke()}}context.translate(0,histogramHeight+1);context.fillStyle="black";morpheus.HeatMapColorSchemeLegend.drawColorScheme(context,this.colorScheme,canvasWidth,false,false,6)}};morpheus.Util.extend(morpheus.HistogramLegend,morpheus.AbstractCanvas);morpheus.LegendWithStops=function(){var _this=this;morpheus.AbstractCanvas.call(this,false);this.setBounds({width:300,height:40});$(this.canvas).on("mousedown",function(event){var position=morpheus.CanvasUtil.getMousePos(event.target,event);_this.selectedIndex=_this.findIndexForPosition(position);_this.trigger("selectedIndex",{selectedIndex:_this.selectedIndex})});this.hammer=morpheus.Util.hammer(this.canvas,["pan"]).on("panmove",this.panmove=function(event){if(_this.selectedIndex!==-1){var position=morpheus.CanvasUtil.getMousePos(event.target,event);var fraction=_this.fractionToStopPix.invert(position.x);fraction=Math.max(0,fraction);fraction=Math.min(1,fraction);_this.trigger("moved",{fraction:fraction})}}).on("panstart",this.panstart=function(event){}).on("panend",this.panend=function(event){_this.selectedIndex=-1});$(this.canvas).on("keydown",function(e){if((e.which==8||e.which==46)&&_this.selectedIndex!==-1){_this.trigger("delete");e.preventDefault();e.stopPropagation();e.stopImmediatePropagation()}})};morpheus.LegendWithStops.prototype={border:7,stopHalfSize:5,selectedIndex:-1,destroy:function(){$(this.canvas).off("keyup").off("mousedown");this.hammer.off("panstart",this.panstart).off("panmove",this.panmove);this.hammer.destroy()},setSelectedIndex:function(index){this.selectedIndex=index},findIndexForPosition:function(position){if(position.y>=22){for(var i=0,length=this.fractions.length;i=start&&position.x<=end){return i}}}return-1},draw:function(fractions,colors,stepped,fractionToStopPix){this.fractions=fractions;this.colors=colors;this.stepped=stepped;this.fractionToStopPix=fractionToStopPix;var context=this.canvas.getContext("2d");morpheus.CanvasUtil.resetTransform(context);context.clearRect(0,0,this.getUnscaledWidth(),this.getUnscaledHeight());context.translate(this.border,0);morpheus.HeatMapColorSchemeLegend.draw(context,fractions,colors,this.getUnscaledWidth()-2*this.border,this.getUnscaledHeight()-20,stepped);context.translate(-this.border,0);context.lineWidth=1;context.strokeStyle="Grey";context.strokeRect(this.border,0,this.getUnscaledWidth()-2*this.border,this.getUnscaledHeight()-20);for(var i=0;i0&&fractions[i]===fractions[i-1]){continue}context.fillStyle=colors[i];var pix=fractionToStopPix(fractions[i]);context.fillRect(pix-this.stopHalfSize,22,this.stopHalfSize*2,this.stopHalfSize*2);if(this.selectedIndex===i){context.lineWidth=2;context.strokeStyle="black"}else{context.lineWidth=1;context.strokeStyle="Grey"}context.strokeRect(pix-this.stopHalfSize,22,this.stopHalfSize*2,this.stopHalfSize*2)}}};morpheus.Util.extend(morpheus.LegendWithStops,morpheus.AbstractCanvas);morpheus.Util.extend(morpheus.LegendWithStops,morpheus.Events);morpheus.Popup={};morpheus.Popup.initted=false;morpheus.Popup.init=function(){if(morpheus.Popup.initted){return}morpheus.Popup.initted=true;morpheus.Popup.$popupDiv=$(document.createElement("div"));morpheus.Popup.$popupDiv.css("position","absolute").css("zIndex",1050).css("overflow","auto").addClass("dropdown clearfix");morpheus.Popup.$contextMenu=$(document.createElement("ul"));morpheus.Popup.$contextMenu.addClass("dropdown-menu").css("display","block").css("position","static").css("margin-bottom","5px");morpheus.Popup.$contextMenu.appendTo(morpheus.Popup.$popupDiv);morpheus.Popup.$contextMenu.on("click","a",function(e){e.preventDefault();var $this=$(this);morpheus.Popup.popupCallback(e,$this.data("name"));morpheus.Popup.hide()})};morpheus.Popup.popupInDom=false;morpheus.Popup.hidePopupMenu=function(e){if(morpheus.Popup.component==e.target){e.preventDefault();e.stopPropagation()}morpheus.Popup.hide()};morpheus.Popup.hide=function(){morpheus.Popup.$popupDiv.hide();$(document.body).off("mousedown",morpheus.Popup.hidePopupMenu);morpheus.Popup.popupCallback=null;morpheus.Popup.component=null};morpheus.Popup.showPopup=function(menuItems,position,component,callback){morpheus.Popup.init();if(morpheus.Popup.component==component){morpheus.Popup.hide();return}morpheus.Popup.popupCallback=callback;morpheus.Popup.component=component;var html=[];for(var i=0,length=menuItems.length;i'+item.name+"")}else if(item.separator){html.push('
  • ')}else{html.push('
  • ");if(item.checked){html.push('')}html.push(item.name);if(item.icon){html.push('')}html.push("");html.push("
  • ")}}morpheus.Popup.$contextMenu.html(html.join(""));if(!morpheus.Popup.popupInDom){morpheus.Popup.popupInDom=true;morpheus.Popup.$popupDiv.appendTo($(document.body))}var $body=$(document.body);var $window=$(window);var windowWidth=$window.width();var windowHeight=$window.height();var popupWidth=morpheus.Popup.$popupDiv.width();var popupHeight=morpheus.Popup.$popupDiv.height();var left=position.x;var top=position.y;if(left+popupWidth>=windowWidth){left-=popupWidth;left=Math.max(4,left)}if(top+popupHeight>=windowHeight){top-=popupHeight;top=Math.max(4,top)}morpheus.Popup.$popupDiv.css({display:"block",left:left,top:top});morpheus.Popup.$popupDiv.show();$body.off("mousedown",morpheus.Popup.hidePopupMenu);window.setTimeout(function(){$body.on("mousedown",function(e){var $target=$(e.target);if($target[0]!==morpheus.Popup.$popupDiv[0]&&$target.data("type")!=="popup-item"){morpheus.Popup.hidePopupMenu(e)}})},1)};morpheus.RowDendrogram=function(heatMap,tree,positions,project){morpheus.AbstractDendrogram.call(this,heatMap,tree,positions,project,morpheus.AbstractDendrogram.Type.ROW)};morpheus.RowDendrogram.prototype={drawNode:function(context,node){var radius=this.getNodeRadius(node);var pix=this.toPix(node);context.beginPath();context.arc(pix[0],pix[1],radius,Math.PI*2,false);context.fill()},isDragHotSpot:function(p){return Math.abs(this.scale(this.cutHeight)-p.x)<=2},drawCutSlider:function(clip,context){if(context.setLineDash){context.setLineDash([5])}context.strokeStyle="black";var nx=this.scale(this.cutHeight);context.beginPath();context.moveTo(nx,clip.y);context.lineTo(nx,this.getUnscaledHeight());context.stroke();if(context.setLineDash){context.setLineDash([])}},getPreferredSize:function(){return{width:100,height:Math.ceil(this.positions.getPosition(this.positions.getLength()-1)+this.positions.getItemSize(this.positions.getLength()-1))}},paintMouseOver:function(clip,context){if(this.project.getHoverRowIndex()!==-1){morpheus.CanvasUtil.resetTransform(context);context.translate(0,-clip.y);this.drawRowBorder(context,this.positions,this.project.getHoverRowIndex(),this.getUnscaledWidth())}},drawRowBorder:function(context,positions,index,gridSize){var size=positions.getItemSize(index);var pix=positions.getPosition(index);context.beginPath();context.moveTo(0,pix+size);context.lineTo(gridSize,pix+size);context.stroke();context.beginPath();context.moveTo(0,pix);context.lineTo(gridSize,pix);context.stroke()},createScale:function(){return d3.scale.linear().domain([0,this.tree.maxHeight]).range([this.getUnscaledWidth(),0])},getMaxIndex:function(clip){return morpheus.Positions.getBottom(clip,this.positions)},getMinIndex:function(clip){return morpheus.Positions.getTop(clip,this.positions)},toPix:function(node){var min=this.positions.getPosition(node.minIndex)+this.positions.getItemSize(node.minIndex)/2;var max=this.positions.getPosition(node.maxIndex)+this.positions.getItemSize(node.maxIndex)/2;return[this.scale(node.height),(min+max)/2]},drawPathFromNodeToParent:function(context,node){var pix=this.toPix(node);var parentPix=this.toPix(node.parent);context.beginPath();context.moveTo(pix[0],pix[1]);context.lineTo(parentPix[0],pix[1]);context.lineTo(parentPix[0],parentPix[1]);context.stroke()},drawNodePath:function(context,node,minIndex,maxIndex){var children=node.children;var left=children[0];var right=children[1];var ry=this.toPix(right)[1];var rx=this.scale(right.height);var ly=this.toPix(left)[1];var lx=this.scale(left.height);var nx=this.scale(node.height);var x;var y;if(!this.drawLeafNodes){var leftIsLeaf=left.children!==undefined;var rightIsLeaf=right.children!==undefined;if(leftIsLeaf){lx=nx+4}if(rightIsLeaf){rx=nx+4}x=[rx,nx,nx,lx];y=[ry,ry,ly,ly]}else{x=[rx,nx,nx,lx];y=[ry,ry,ly,ly]}context.beginPath();context.moveTo(x[0],y[0]);for(var i=1,length=x.length;i=0};if(isVertical){heatMap.setToolTip(indices.length>=0?indices:null,-1,tipOptions)}else{heatMap.setToolTip(-1,indices.length>=0?indices:null,tipOptions)}};var mouseExit=function(e){document.body.style.cursor="default";scrollbar.canvas.style.cursor="default";heatMap.setToolTip(-1,-1,{event:e})};$(scrollbar.canvas).on("mousemove.morpheus",mouseMove).on("mouseout.morpheus",mouseExit)};morpheus.ScentedSearch.LINE_HEIGHT=3.5;morpheus.ScentedSearch.prototype={mouseMovedIndex:-1,getIndex:function(event){var pix=morpheus.CanvasUtil.getMousePos(event.target,event);var val=pix[this.isVertical?"y":"x"];return this.getIndexForPix(val)},getSearchIndices:function(event){var pix=morpheus.CanvasUtil.getMousePos(event.target,event);var val=pix[this.isVertical?"y":"x"];return this.getSearchIndicesForPix(val)},getSearchIndicesForPix:function(pix){var indices=this.searchIndices;if(indices==null){return[]}var scale=this.scale;var tolerance=morpheus.ScentedSearch.LINE_HEIGHT;var matches=[];for(var i=0,length=indices.length;i0){var midVal=this.positions.getPosition(indices[this.mouseMovedIndex])*scale;if(Math.abs(midVal-pix)<=tolerance){return this.mouseMovedIndex}}var low=0;var scale=this.scale;var high=indices.length-1;while(low<=high){var mid=low+high>>1;var midVal=this.positions.getPosition(indices[mid])*scale;var cmp=0;if(Math.abs(midVal-pix)<=tolerance){cmp=0}else if(midValpix){cmp=1}if(cmp<0)low=mid+1;else if(cmp>0)high=mid-1;else return mid}return-1},tap:function(position){var val=position[this.isVertical?"y":"x"];var index=this.getIndexForPix(val);this.scrollbar.canvas.style.cursor=index<0?"default":"pointer";if(index>=0){if(this.isVertical){this.heatMap.scrollTop(this.positions.getPosition(this.searchIndices[index]))}else{this.heatMap.scrollLeft(this.positions.getPosition(this.searchIndices[index]))}return true}return false},update:function(){this.searchIndices=this.model.getViewIndices().values().sort(function(a,b){return a=that.thumbPos&&position[that.field]<=that.thumbPos+that.thumbExtent;if(that.thumbMouseOver!==mouseOver){that.thumbMouseOver=mouseOver;that.repaint()}}};var mouseExit=function(e){if(!morpheus.CanvasUtil.dragging&&that.thumbMouseOver){that.thumbMouseOver=false;that.repaint()}};$(this.canvas).on("mousemove",mouseMove).on("mouseout",mouseExit).on("mouseenter",mouseMove);this.hammer=morpheus.Util.hammer(this.canvas,[this.isVertical?"panv":"panh","tap"]).on("panstart",this.panstart=function(event){var position=morpheus.CanvasUtil.getMousePos(event.target,event,true);if(position[that.field]>=that.thumbPos&&position[that.field]<=that.thumbPos+that.thumbExtent){that.draggingThumb=true;that.dragStartThumbPos=that.thumbPos}else{that.draggingThumb=false}}).on("panend",this.panend=function(event){that.draggingThumb=false}).on("panmove",this.panmove=function(event){if(that.draggingThumb){var position=morpheus.CanvasUtil.getMousePos(event.target,event);var thumbPosPix=that.dragStartThumbPos+(that.isVertical?event.deltaY:event.deltaX);var f=thumbPosPix/(that.visibleExtent-that.thumbExtent);var value=f*that.maxValue;that.setValue(value,true);event.preventDefault();event.srcEvent.stopPropagation();event.srcEvent.stopImmediatePropagation()}}).on("tap doubletap",this.tap=function(event){if(!that.draggingThumb){var position=morpheus.CanvasUtil.getMousePos(event.target,event);if(!that.decorator.tap(position)){var thumbExtentToValue=that.thumbExtent/that.totalExtent*that.totalExtent;that.scrollToTop=position[that.field]'];map.forEach(function(val,key){html.push("');html.push(key);html.push("")});html.push("");formBuilder.append({name:"selected_value",type:"custom",value:html.join("")});var shapeField=new morpheus.ShapeField({showNone:true});formBuilder.append({style:"max-width:50px;",name:"selected_shape",type:"custom",value:'
    '});shapeField.$el.appendTo(formBuilder.$form.find("[data-name=shape]"));var $valuePicker=formBuilder.$form.find("[name=valuePicker]");var selectedVal=$valuePicker.val();var _this=this;shapeField.setShapeValue(map.get(selectedVal));shapeField.on("change",function(e){map.set(selectedVal,e.shape);_this.trigger("change",{value:selectedVal,shape:e.shape})});$valuePicker.selectpicker().change(function(){selectedVal=$valuePicker.val();shapeField.setShapeValue(map.get(selectedVal))});this.$div=formBuilder.$form};morpheus.ShapeChooser.prototype={};morpheus.Util.extend(morpheus.ShapeChooser,morpheus.Events);morpheus.ShapeField=function(options){var shapes=options.shapes||morpheus.VectorShapeModel.SHAPES;var _this=this;var html=[];var size2=8;var x=4;var y=4;html.push('
    ');html.push('');html.push('
    ");var $el=$(html.join(""));var $header=$el.find("[data-name=selection]");$el.on("click","li > a",function(e){e.preventDefault();var shape=$(this).data("name");setShapeValue(shape);_this.trigger("change",{shape:shape})});var setShapeValue=function(val){if(val==="none"){$header.html("(None)")}else{var context=new C2S(size2*2,size2*2);context.translate(4,4);morpheus.CanvasUtil.drawShape(context,val,x,y,size2);$header.html(context.getSerializedSvg())}};this.setShapeValue=setShapeValue;this.$el=$el};morpheus.ShapeField.prototype={};morpheus.Util.extend(morpheus.ShapeField,morpheus.Events);morpheus.SortByValuesIndicator=function(project,isVertical,positions){morpheus.AbstractCanvas.call(this,true);this.project=project;this.isVertical=isVertical;this.positions=positions;this.lastPosition={start:-1,end:-1}};morpheus.SortByValuesIndicator.prototype={prePaint:function(clip,context){var positions=this.positions;var start=0;var end=positions.getLength();if(!this.isVertical){start=morpheus.Positions.getLeft(clip,positions);end=morpheus.Positions.getRight(clip,positions)}else{start=morpheus.Positions.getTop(clip,positions);end=morpheus.Positions.getBottom(clip,positions)}if(this.invalid||start!==this.lastPosition.start||end!==this.lastPosition.end){this.lastPosition.start=start;this.lastPosition.end=end;this.invalid=true}},draw:function(clip,context){var project=this.project;var isVertical=this.isVertical;var positions=this.positions;var sortKeys=isVertical?project.getColumnSortKeys():project.getRowSortKeys();context.translate(-clip.x,-clip.y);context.fillStyle="black";context.textBaseline="top";context.textAlign="left";context.font="8px "+morpheus.CanvasUtil.getFontFamily(context);var start=0;var end=positions.getLength();if(!isVertical){start=morpheus.Positions.getLeft(clip,positions);end=morpheus.Positions.getRight(clip,positions)}else{start=morpheus.Positions.getTop(clip,positions);end=morpheus.Positions.getBottom(clip,positions)}var arrowWidth=3;var arrowHeight=4;for(var i=0;i=start&&view');var $div=$('
    ');var html=[];html.push('
    ');html.push('
    ');html.push('
    ');html.push('
    ');html.push('
    ');html.push('
    ');html.push("
    ");html.push("
    ");html.push("
    ");$chooserDiv.html(html.join(""));function toggle(isColumns){_this.isColumns=isColumns;var $element=_this.build(project,isColumns);$div.empty().html($element);$div.on("click","[data-name=delete]",function(e){var $this=$(this);e.preventDefault();$this.closest("div.row").remove()});$div.on("click","[data-name=add]",function(e){var $this=$(this);var level=[];var $sibling=$this.closest("div.row");_this.createLevel(level,new morpheus.SortKey("",morpheus.SortKey.SortOrder.ASCENDING),_this.fields);$sibling.after($(level.join("")));e.preventDefault()})}$chooserDiv.on("change","[name=rowsOrColumns]",function(e){var $this=$(this);toggle($this.val()==="columns")});toggle(false);var $outer=$("
    ");$chooserDiv.appendTo($outer);$div.appendTo($outer);morpheus.FormBuilder.showOkCancel({title:"Sort",content:$outer,okCallback:function(){var $forms=$div.find("form");var sortBy=$forms.find("[name=sortBy]").map(function(){return $(this).val()});var lockOrder=$forms.find("[name=lockOrder]").map(function(){return $(this).prop("checked")});var sortOrder=$forms.find("[name=sortOrder]:checked").map(function(){return $(this).val()});var groupBy=$div.find("[name=groupBy]").val();var newSortKeys=[];var modelIndices=_this.isColumns?project.getRowSelectionModel().toModelIndices():project.getColumnSelectionModel().toModelIndices();var existingSortKeys=_this.isColumns?project.getColumnSortKeys():project.getRowSortKeys();for(var i=0;i');html.push('
    ');html.push('
    ');html.push('
    ');var groupByKeys=(isColumns?project.getGroupColumns():project.getGroupRows()).map(function(key){return key.field});html.push('");html.push("
    ");html.push("");var $div=$(html.join(""));$div.find(".selectpicker").selectpicker({iconBase:"fa",tickIcon:"fa-check",style:"btn-default btn-sm"});return $div},createLevel0:function(html){html.push('
    ');html.push('');html.push('
    ');html.push('Add sort level');html.push("
    ");html.push("");html.push("
    ")},createLevel:function(html,key,fields){html.push('
    ');html.push('
    ');html.push('
    ');html.push('
    ');html.push('");html.push("
    ");html.push('
    ');html.push('
    ");html.push('
    ");html.push("
    ");html.push('
    ');html.push('Delete');html.push("
    ");html.push('
    ');html.push('
    ");html.push("
    ");html.push('
    ');html.push("
    ");html.push('Add sort level');html.push("
    ");html.push("
    ");html.push("
    ")}};morpheus.SteppedColorSupplier=function(){morpheus.AbstractColorSupplier.call(this);this.hiddenValue=0;this.hiddenValues=new morpheus.Set;this.stepped=true};morpheus.SteppedColorSupplier.linearScale=function(value,input0,input1,pix0,pix1){return(value-input0)/(input1-input0)*(pix1-pix0)+pix0};morpheus.SteppedColorSupplier.prototype={createInstance:function(){return new morpheus.SteppedColorSupplier},isStepped:function(){return true},getHiddenValues:function(){return this.hiddenValues},getIndexForFraction:function(f){var fractions=this.fractions;if(f<=fractions[0]){return 0}if(f>=fractions[fractions.length-1]){return fractions.length-1}for(var i=0;i=left&&f=max){return colors[colors.length-1]}var fraction=morpheus.SteppedColorSupplier.linearScale(value,min,max,0,100)/100;return colors[this.getIndexForFraction(fraction)]}};morpheus.Util.extend(morpheus.SteppedColorSupplier,morpheus.AbstractColorSupplier);morpheus.TabManager=function(options){this.options=$.extend({},{autohideTabBar:false,rename:true},options);var _this=this;this.activeTabObject=null;this.activeTabId=null;this.idToTabObject=new morpheus.Map;this.$nav=$('');this.$nav.sortable({containment:"parent",axis:"x",helper:"clone",cancel:"li:not(.morpheus-sortable)",items:"li.morpheus-sortable"});this.$nav.sortable("disable");this.$nav.on("click","li > a",function(e){var tabId=$(this).data("link");if(tabId!=null){e.preventDefault();if(_this.activeTabId!==tabId){$(this).tab("show")}}});if(this.options.autohideTabBar){this.$nav.css("display","none")}if(options.dropTab){var html=[];html.push('");var $tabDrop=$(html.join(""));var $tabDropMenu=$tabDrop.find(".dropdown-menu");$tabDrop.appendTo(this.$nav);var updateDropTab=function(){var totalWith=_this.$nav.width()-17;var sum=0;var tabDropItems=[];_this.$nav.find("> li").each(function(){var $li=$(this);var $a=$li.find("a");if(!$li.hasClass("morpheus-tab-addon")){var title=$a.contents().first().text();var isActive=$li.hasClass("active");var href=$a.attr("href");tabDropItems.push('
  • '+title+"
  • ");sum+=$li.outerWidth();if(sum>=totalWith){$li.css("display","none")}else{$li.css("display","")}}});$tabDrop.css("display",tabDropItems.length>0?"":"none");$tabDropMenu.html(tabDropItems.join(""))};$tabDrop.css("display","none");this.$nav.on("sortstop",function(event,ui){updateDropTab()});$(window).on("resize",updateDropTab);this.$nav.on("remove",function(){$(window).off("resize",updateDropTab)});this.on("add remove rename reorder change",function(){updateDropTab()})}this.$nav.on("dblclick","li > a",function(e){e.preventDefault();var $a=$(this);var $li=$a.parent("li");if($li.hasClass("morpheus-tab-addon")){return}_this.rename($a.data("link"))});this.$nav.on("contextmenu.morpheus","li > a",function(e){e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();var $a=$(this);var $li=$a.parent("li");if($li.hasClass("morpheus-tab-addon")){return}var menuItems=[];if($a.data("morpheus-rename")&&_this.options.rename){menuItems.push({name:"Rename"})}if($a.data("morpheus-pin")){menuItems.push({name:"Unpin tab"})}else{menuItems.push({name:"Pin tab"})}if(menuItems.length>0){morpheus.Popup.showPopup(menuItems,{x:e.pageX,y:e.pageY},e.target,function(event,item){if(item==="Rename"){_this.rename($a.data("link"))}else if(item==="Pin tab"){$a.data("morpheus-pin",true);$li.removeClass("morpheus-sortable");$li.detach();_this.$nav.prepend($li);$a.find(".close").hide();_this.$nav.sortable("option","items","li.morpheus-sortable");_this.$nav.sortable("refresh")}else if(item==="Unpin tab"){$a.data("morpheus-pin",false);$li.addClass("morpheus-sortable");$a.find(".close").show();_this.$nav.sortable("option","items","li.morpheus-sortable");_this.$nav.sortable("refresh")}})}return false});this.$nav.on("click","button",function(e){e.preventDefault();var target=$(this).attr("data-target");if(target!=null){target=target.substring(1);_this.remove(target)}});this.$tabContent=$('
    ');this.$nav.on("shown.bs.tab",'a[data-toggle="tab"]',function(e){var previous=_this.activeTabId;_this.activeTabId=$(e.target).data("link");_this.activeTabObject=_this.idToTabObject.get(_this.activeTabId);_this.$nav.find("li").removeClass("active");_this.$nav.find("[data-link="+_this.activeTabId+"]").each(function(){$(this).parent().addClass("active")});var scrollTop=document.body.scrollTop;$("#"+_this.activeTabId).focus();document.body.scrollTop=scrollTop;if(_this.adding){return}_this.trigger("change",{tab:_this.activeTabId,previous:previous})})};morpheus.TabManager.prototype={getTabText:function(id){return this.$nav.find("> li > a").filter("a[data-link="+id+"]").contents().first().text()},getTabCount:function(){return this.idToTabObject.size()},setTabText:function(id,text){this.$nav.find("> li > a").filter("[data-link="+id+"]").contents().first().replaceWith(text+" ");this.idToTabObject.get(id).setName(name)},addTask:function(task){},removeTask:function(task){},getWidth:function(){return this.$tabContent.outerWidth()||$(window).width()},getActiveTab:function(){return this.activeTabObject},getActiveTabId:function(){return this.activeTabId},add:function(options){this.adding=true;var id=_.uniqueId("morpheus-tab");this.idToTabObject.set(id,options.object);var li=[];li.push('");var $link=$(li.join(""));$link.appendTo(this.$nav);var $panel=$('
    ');options.$el.appendTo($panel);$panel.appendTo(this.$tabContent);if(options.enabled===false){$link.addClass("disabled");$link.find("a").addClass("btn disabled")}if(options.focus){this.$nav.find('> li > a[data-toggle="tab"]:last').tab("show");this.activeTabId=id;this.activeTabObject=options.object;$panel.focus()}if(this.options.autohideTabBar){this.$nav.css("display",this.idToTabObject.size()>1?"":"none")}this.getTabCount()<=1?this.$nav.sortable("disable"):this.$nav.sortable("enable");this.adding=false;this.trigger("add");return{$panel:$panel,id:id}},appendTo:function($target){this.$nav.appendTo($target);this.$tabContent.appendTo($target)},remove:function(target){if(target===undefined){target=this.activeTabId}var obj=this.idToTabObject.remove(target);$("#"+target).remove();this.activeTabObject=null;this._getA(target).parent().remove();this.$tabContent.find(target).remove();var $a=this.$nav.find('> li > a[data-toggle="tab"]:last');if($a.length===0){if(this.options.landingPage){if(typeof this.options.landingPage==="function"){this.options.landingPage().show()}else{this.options.landingPage.show()}}}$a.tab("show");if(this.options.autohideTabBar){this.$nav.css("display",this.idToTabObject.size()>1?"":"none")}this.getTabCount()<=1?this.$nav.sortable("disable"):this.$nav.sortable("enable");if(this.idToTabObject.size()>0){$($a.attr("href")).focus()}if(obj!=null&&obj.onRemove){obj.onRemove()}this.trigger("remove",{tab:target})},setOptions:function(options){this.options=options;if(this.options.autohideTabBar){this.$nav.css("display",this.idToTabObject.size()>1?"":"none")}},getOptions:function(){return this.options},setActiveTab:function(id){if(id!==this.activeTabId){var $a=this._getA(id);$a.parent().removeClass("disabled");$a.removeClass("btn disabled");$a.tab("show");var previous=this.activeTabId;this.activeTabId=id;this.activeTabObject=this.idToTabObject.get(this.activeTabId);this.trigger("change",{tab:this.activeTabId,previous:previous})}},setTabTitle:function(id,title){this._getA(id).attr("title",title)},_getA:function(id){if(id[0]==="#"){id=id.substring(1)}return this.$nav.find("> li > a[data-link="+id+"]:first")},setTabEnabled:function(id,enabled){var $a=this._getA(id);if(enabled){$a.parent().removeClass("disabled");$a.removeClass("btn disabled")}else{$a.parent().addClass("disabled");$a.addClass("btn disabled")}},getIdToTabObject:function(){return this.idToTabObject},getTabObject:function(id){return this.idToTabObject.get(id)},rename:function(id){var $a=this._getA(id);var $li=$a.parent();if($li.hasClass("morpheus-tab-addon")){return}if(!$a.data("morpheus-rename")||!this.options.rename){return}var _this=this;var builder=new morpheus.FormBuilder;builder.append({name:"name",type:"text",value:$.trim($a.contents().first().text())});morpheus.FormBuilder.showOkCancel({title:"Rename Tab",content:builder.$form,focus:document.activeElement,okCallback:function(){var name=$.trim(builder.getValue("name"));if(name!==""){if(_this.activeTabObject!=null&&_this.activeTabObject.setName){_this.activeTabObject.setName(name)}$a.contents().first().replaceWith(name+" ");_this.trigger("rename")}}})}};morpheus.Util.extend(morpheus.TabManager,morpheus.Events);morpheus.Table=function(options){options=morpheus.Table.createOptions(options);this.options=options;if(!options.width){options.width=options.$el.attr("class")}var _this=this;var height=options.height;var $gridDiv=$('
    ');this.$gridDiv=$gridDiv;$gridDiv.appendTo(options.$el);var columns=options.columns;this.columns=columns;var visibleColumns=columns.filter(function(c){return c.visible});var grid=new morpheus.Grid({gridOptions:{select:options.select,rowHeight:options.rowHeight,autoEdit:false,editable:false,autoHeight:options.height==="auto",enableTextSelectionOnCells:true},$el:$gridDiv,items:options.items,columns:visibleColumns});this.grid=grid;this.searchFunction=null;var searchFilter={isEmpty:function(){return _this.searchFunction==null},init:function(){},accept:function(item){return _this.searchFunction(item)}};this.grid.getFilter().add(searchFilter);var $header=$('
    ');this.$header=$header;var $right=$header.find(".pull-right");if(options.search){var tableSearch=new morpheus.TableSearchUI({$el:$header.find("[name=top]"),$right:$right});tableSearch.setTable(this);this.tableSearch=tableSearch}if(options.columnPicker&&visibleColumns.length!==this.columns.length){var select=[];select.push('");var $select=$(select.join(""));$select.appendTo($right);$select.selectpicker({iconBase:"fa",tickIcon:"fa-check",style:"btn-default btn-xs"});$select.on("change",function(){var oldColumns=grid.getColumns().map(function(c){return c.id});var selectedColumnIndices=$select.val();visibleColumns=[];for(var i=0;ioldColumns.length){var set=new morpheus.Set;for(var i=0;i1){collapsed=true;$gridDiv.addClass("slick-stacked");_this.grid.grid.getOptions().rowHeight=(options.collapsedRowHeight?options.collapsedRowHeight:options.rowHeight)*visibleColumns.length;_this.grid.grid.setColumns([{id:0,tooltip:function(item,value){var html=[];for(var i=0;i")},collapsed:true,getter:function(item){return item},formatter:function(row,cell,value,columnDef,dataContext){var html=[];html.push('
    ');if(options.rowHeader){html.push(options.rowHeader(dataContext));html.push('
    ')}for(var i=0;i0){html.push('
    ')}var c=visibleColumns[i];html.push(c.name);html.push(":");var s=c.renderer(dataContext,c.getter(dataContext));html.push(s)}html.push("
    ");return html.join("")},sortable:false,name:""}]);$gridDiv.find(".slick-header").hide();_this.grid.grid.resizeCanvas();_this.grid.grid.invalidate()}else if(collapsed&&gridWidth>=options.collapseBreakpoint){$gridDiv.removeClass("slick-stacked");collapsed=false;if(options.showHeader){$gridDiv.find(".slick-header").show()}_this.grid.grid.getOptions().rowHeight=options.rowHeight;_this.grid.grid.setColumns(visibleColumns);_this.grid.grid.resizeCanvas();if(options.select){_this.grid.grid.setSelectedRows(_this.grid.grid.getSelectedRows())}_this.grid.grid.invalidate()}else{_this.grid.grid.resizeCanvas();_this.grid.grid.invalidate()}_this.grid.maybeAutoResizeColumns()};if(!options.showHeader){$gridDiv.find(".slick-header").hide()}if(options.responsive){$(window).on("resize orientationchange",resize);$gridDiv.on("remove",function(){$(window).off("resize",resize)});resize()}this.resize=resize;if(visibleColumns.length>1&&options.items!=null&&options.items.length>0){this.setItems(options.items)}if(!$gridDiv.is(":visible")){var $parent=$gridDiv;var observer=new MutationObserver(function(mutations){if(window.getComputedStyle($parent[0]).display!=="none"){observer.disconnect();resize()}});while($parent.length>0){if(window.getComputedStyle($parent[0]).display==="none"){break}$parent=$parent.parent()}if($parent.length>0){observer.observe($parent[0],{attributes:true,childList:false,characterData:false})}}};morpheus.Table.defaultRenderer=function(item,value){if(value==null){return""}else if(_.isNumber(value)){return morpheus.Util.nf(value)}else if(morpheus.Util.isArray(value)){var s=[];for(var i=0,length=value.length;i0){s.push(", ")}var val=value[i];s.push(value[i])}return s.join("")}else{return""+value}};morpheus.Table.prototype={toText:function(){var text=[];var items=this.getItems();var columns=this.columns.filter(function(c){return c.visible});for(var j=0;j0){text.push("\t")}text.push(columns[j].name)}text.push("\n");for(var i=0;i0){text.push("\t")}var value=columns[j].getter(item);text.push(morpheus.Util.toString(value))}text.push("\n")}return text.join("")},setHeight:function(height){this.options.height=height;if(height==="auto"){this.$gridDiv.css("height","");this.grid.grid.getOptions().autoHeight=true;this.grid.grid.setOptions(this.grid.grid.getOptions())}else{this.$gridDiv.css("height",height)}this.grid.grid.resizeCanvas();if(height==="auto"){var height=this.getItems().length*this.options.rowHeight+this.options.rowHeight;this.$gridDiv.find(".slick-viewport").css("height",height+"px")}this.grid.grid.invalidate()},setSearchVisible:function(visible){this.$header.find("[name=search]").css("display",visible?"":"none")},autocomplete:function(tokens,response){var matches=[];var token=tokens!=null&&tokens.length>0?tokens[tokens.selectionStartIndex]:"";token=$.trim(token);var columns=this.columns.filter(function(c){return c.searchable&&c.visible||c.alwaysSearch});var ncolumns=columns.length;var showField=ncolumns>1;if(token===""){if(ncolumns<=1){return response(matches)}for(var i=0;i'+field+":",show:true})}matches.sort(function(a,b){return a.value===b.value?0:a.value0){if(token.charCodeAt(semi-1)!==92){var possibleField=$.trim(token.substring(0,semi));if(possibleField.length>0&&possibleField[0]==='"'&&possibleField[token.length-1]==='"'){possibleField=possibleField.substring(1,possibleField.length-1)}var columnNameToColumn=new morpheus.Map;var columnNames=columns.map(function(c){return c.name});for(var i=0;i1){var regex=new RegExp("^"+morpheus.Util.escapeRegex(token),"i");for(var j=0;j'+field+":",show:true})}}}var set=new morpheus.Set;var regex=new RegExp("^"+morpheus.Util.escapeRegex(token),"i");var items=this.getItems();var dataTypes=[];var filteredColumns=[];columns.forEach(function(c){var dataType=null;for(var i=0,nitems=items.length;i'+field+":"+''+val+"":''+val+""})}if(matches.length===maxSize){return response(matches)}}}else{if(regex.test(value)&&!set.has(value)){set.add(value);matches.push({value:showField?field+":"+value:value,label:showField?''+field+":"+''+value+"":''+value+""});if(matches.length===maxSize){return response(matches)}}}}}return response(matches)},searchWithPredicates:function(predicates){if(predicates==null||predicates.length===0){this.searchFunction=null;this.grid.setFilter(this.grid.getFilter());return}var columns=this.columns.filter(function(c){return c.searchable&&c.visible||c.alwaysSearch});var columnNameToColumn=new morpheus.Map;var columnNames=columns.map(function(c){return c.name});for(var i=0;i
    ');if(options.rowHeader&&cell===0){html.push(options.rowHeader(dataContext))}html.push(column.renderer(dataContext,value));html.push("
    ");return html.join("")},comparator:function(a,b){var aNaN=a==null||_.isNumber(a)&&isNaN(a);var bNaN=b==null||_.isNumber(b)&&isNaN(b);if(aNaN&&bNaN){return 0}if(aNaN){return 1}if(bNaN){return-1}if(a.toLowerCase){a=a.toLowerCase()}if(b.toLowerCase){b=b.toLowerCase()}return a===b?0:a');$search.appendTo(options.$el);this.$search=$search;this.$searchResults=$('');this.$showAll=$('
    Show'+" all
    ");this.$searchResults.appendTo(options.$right);this.$showAll.appendTo(options.$right);this.$showAll.on("click",function(e){e.preventDefault();$search.val("");_this.table.search("");_this.table.trigger("showAll",{table:_this.table})});$search.on("keyup",_.debounce(function(){_this.table.search($.trim($(this).val()))},100));morpheus.Util.autosuggest({$el:$search,suggestWhenEmpty:true,filter:function(tokens,response){_this.table.autocomplete(tokens,response)},select:function(){_this.table.search($.trim($search.val()))}})};morpheus.TableSearchUI.prototype={updateSearchLabel:function(){var text="Showing: "+morpheus.Util.intFormat(this.table.getFilteredItemCount())+" / "+morpheus.Util.intFormat(this.table.getAllItemCount());this.$searchResults.html(text)},setTable:function(table){this.table=table;var _this=this;table.on("filter",function(){_this.updateSearchLabel()})}};morpheus.TrackSelection=function(track,positions,selectionModel,isColumns,heatMap){var canvas=track.canvas;var startIndex=-1;var coord=isColumns?"x":"y";function getPosition(event,useDelta){if(track.settings.squished){var total=positions.getPosition(positions.getLength()-1)+positions.getItemSize(positions.getLength()-1);var squishFactor=total/(isColumns?track.getUnscaledWidth():track.getUnscaledHeight());var clientXY=morpheus.CanvasUtil.getClientXY(event,useDelta);var p=morpheus.CanvasUtil.getMousePosWithScroll(event.target,event,0,0,useDelta);p[coord]*=squishFactor;return p}else{return morpheus.CanvasUtil.getMousePosWithScroll(event.target,event,heatMap.scrollLeft(),heatMap.scrollTop(),useDelta)}}var panning=false;var scrollIntervalId;var lastScrollTime=(new Date).getTime();var _this=this;var throttlePanMove=50;function mouseleave(e){var scroll=function(){var now=(new Date).getTime();var rect=canvas.getBoundingClientRect();var doPan=false;if(!isColumns){if(e.clientY>rect.bottom||e.clientYrect.right||e.clientXendIndex){var tmp=endIndex;endIndex=_startIndex;_startIndex=tmp}for(var i=_startIndex;i<=endIndex;i++){viewIndices.add(i)}selectionModel.setViewIndices(viewIndices,true);if(!isColumns){var scrollTop=heatMap.scrollTop();var heatMapHeight=heatMap.heatmap.getUnscaledHeight();var scrollBottom=scrollTop+heatMapHeight;if(position.y>scrollBottom){heatMap.scrollTop(position.y+8-heatMapHeight)}else if(position.yscrollRight){heatMap.scrollLeft(position.x+8-heatMapWidth)}else if(position.x1){if(isColumns&&!heatMap.options.columnsSortable||!isColumns&&!heatMap.options.rowsSortable){return}heatMap.sortBasedOnSelection(null,isColumns,event.srcEvent.shiftKey)}else{heatMap.setSelectedTrack(track.name,isColumns);var commandKey=morpheus.Util.IS_MAC?event.srcEvent.metaKey:event.srcEvent.ctrlKey;if(morpheus.Util.IS_MAC&&event.srcEvent.ctrlKey){return}var viewIndices;if(commandKey){viewIndices=selectionModel.getViewIndices();if(viewIndices.has(index)){viewIndices.remove(index)}else{viewIndices.add(index)}}else if(event.srcEvent.shiftKey){viewIndices=selectionModel.getViewIndices();var min=Number.MAX_VALUE;var max=-Number.MAX_VALUE;viewIndices.forEach(function(viewIndex){min=Math.min(viewIndex,min);max=Math.max(viewIndex,max)});if(index>=max){for(var i=max;i<=index;i++){viewIndices.add(i)}}else{for(var i=Math.min(index,min),max=Math.max(index,min);i<=max;i++){viewIndices.add(i)}}}else{viewIndices=new morpheus.Set;viewIndices.add(index)}selectionModel.setViewIndices(viewIndices,true)}})};morpheus.TrackSelection.prototype={dispose:function(){this.hammer.off("longpress",this.longpress).off("panstart",this.panstart).off("panmove",this.panmove).off("panend",this.panend).off("tap",this.tap).off("doubletap",this.tap);this.hammer.destroy()}};morpheus.VectorTrackHeader=function(project,name,isColumns,heatMap){morpheus.AbstractCanvas.call(this);this.font={weight:"400"};this.project=project;this.name=name;this.isColumns=isColumns;var canvas=this.canvas;this.heatMap=heatMap;this.selectedBackgroundColor="#c8c8c8";this.backgroundColor="rgb(255,255,255)";var vector=(isColumns?project.getFullDataset().getColumnMetadata():project.getFullDataset().getRowMetadata()).getByName(name);if(vector&&vector.getProperties().has(morpheus.VectorKeys.TITLE)){this.canvas.setAttribute("title",vector.getProperties().get(morpheus.VectorKeys.TITLE));$(this.canvas).tooltip()}var _this=this;this.setBounds({height:this.defaultFontHeight+morpheus.VectorTrackHeader.FONT_OFFSET});function getResizeCursor(pos){if(isColumns){if(pos.y<3){return{cursor:"ns-resize",isPrevious:true}}if(pos.y>=_this.getUnscaledHeight()-3){return{cursor:"ns-resize",isPrevious:false}}if(pos.x>=_this.getUnscaledWidth()-3){return{isPrevious:false,cursor:"ew-resize"}}}else{if(pos.x<3&&heatMap.getTrackIndex(name,isColumns)>0){return{cursor:"ew-resize",isPrevious:true}}if(pos.x>=_this.getUnscaledWidth()-3){return{cursor:"ew-resize",isPrevious:false}}}}var mouseMove=function(event){if(!morpheus.CanvasUtil.dragging){var pos=morpheus.CanvasUtil.getMousePos(event.target,event);var resizeCursor=getResizeCursor(pos);canvas.style.cursor=resizeCursor==null?"default":resizeCursor.cursor;_this.isMouseOver=true;_this.repaint()}};var mouseExit=function(e){if(!morpheus.CanvasUtil.dragging){canvas.style.cursor="default"}_this.isMouseOver=false;_this.repaint()};var showPopup=function(e){heatMap.setSelectedTrack(_this.name,isColumns);var track=heatMap.getTrack(_this.name,isColumns);if(!track){throw _this.name+" track not found"}e.preventDefault();if(e.stopPropagation){e.stopPropagation()}if(e.stopImmediatePropagation){e.stopImmediatePropagation()}track.showPopup(e,true);return false};$(this.canvas).css({"background-color":this.backgroundColor}).on("mousemove.morpheus",mouseMove).on("mouseout.morpheus",mouseExit).on("mouseenter.morpheus",mouseMove).on("contextmenu.morpheus",showPopup).addClass("morpheus-track-header "+(isColumns?"morpheus-columns":"morpheus-rows"));var resizeCursor;var dragStartWidth=0;var dragStartHeight=0;var reorderingTrack=false;var dragStartPosition;var resizeTrackName;this.hammer=morpheus.Util.hammer(canvas,["pan","tap","longpress"]).on("longpress",this.longpress=function(event){event.preventDefault();heatMap.setSelectedTrack(_this.name,isColumns);var track=heatMap.getTrack(_this.name,isColumns);track.showPopup(event.srcEvent,true)}).on("panend",this.panend=function(event){_this.isMouseOver=false;morpheus.CanvasUtil.dragging=false;canvas.style.cursor="default";var index=heatMap.getTrackIndex(_this.name,isColumns);var header=heatMap.getTrackHeaderByIndex(index,isColumns);var track=heatMap.getTrackByIndex(index,isColumns);var $canvas=$(track.canvas);$canvas.css("z-index","0");$(header.canvas).css("z-index","0");heatMap.revalidate()}).on("panstart",this.panstart=function(event){_this.isMouseOver=false;if(morpheus.CanvasUtil.dragging){return}if(resizeCursor!=null){morpheus.CanvasUtil.dragging=true;canvas.style.cursor=resizeCursor.cursor;if(resizeCursor.isPrevious){var index=heatMap.getTrackIndex(_this.name,isColumns);index--;if(index===-1){index=0}var header=heatMap.getTrackHeaderByIndex(index,isColumns);dragStartWidth=header.getUnscaledWidth();dragStartHeight=header.getUnscaledHeight();resizeTrackName=header.name}else{resizeTrackName=null;dragStartWidth=_this.getUnscaledWidth();dragStartHeight=_this.getUnscaledHeight()}event.preventDefault();reorderingTrack=false}else{var index=heatMap.getTrackIndex(_this.name,isColumns);if(index==-1){throw _this.name+" not found"}var header=heatMap.getTrackHeaderByIndex(index,isColumns);var track=heatMap.getTrackByIndex(index,isColumns);heatMap.setSelectedTrack(_this.name,isColumns);var $canvas=$(track.canvas);dragStartPosition=$canvas.position();$canvas.css("z-index","100");$(header.canvas).css("z-index","100");morpheus.CanvasUtil.dragging=true;resizeCursor=undefined;reorderingTrack=true}}).on("panmove",this.panmove=function(event){_this.isMouseOver=false;if(resizeCursor!=null){var width;var height;if(resizeCursor.cursor==="ew-resize"){var dx=event.deltaX;width=Math.max(8,dragStartWidth+dx)}if(resizeCursor.cursor==="ns-resize"){var dy=event.deltaY;height=Math.max(8,dragStartHeight+dy)}heatMap.resizeTrack(resizeTrackName==null?_this.name:resizeTrackName,width,height,isColumns)}else if(reorderingTrack){var index=heatMap.getTrackIndex(_this.name,isColumns);var header=heatMap.getTrackHeaderByIndex(index,isColumns);var track=heatMap.getTrackByIndex(index,isColumns);var ntracks=heatMap.getNumTracks(isColumns);var delta=isColumns?event.deltaY:event.deltaX;var newIndex=index+(delta>0?1:-1);newIndex=Math.min(Math.max(0,newIndex),ntracks-1);var prop=isColumns?"top":"left";var w=isColumns?"getUnscaledHeight":"getUnscaledWidth";var trackBounds={};trackBounds[prop]=dragStartPosition[prop]+delta;track.setBounds(trackBounds);header.setBounds(trackBounds);var dragOverTrack=heatMap.getTrackByIndex(newIndex,isColumns);var dragOverWidth=dragOverTrack[w]();var dragOverLeft=$(dragOverTrack.canvas).position()[prop];var dragleft=dragStartPosition[prop]+delta;var dragright=dragleft+track[w]();if(delta>0&&dragright>=dragOverLeft+dragOverWidth/2||delta<0&&dragleft<=dragOverLeft+dragOverWidth/2){if(index!==newIndex){heatMap.moveTrack(index,newIndex,isColumns);var otherHeader=heatMap.getTrackHeaderByIndex(index,isColumns);var otherTrack=heatMap.getTrackByIndex(index,isColumns);var $movedCanvas=$(otherTrack.canvas);var newLeft=$movedCanvas.position()[prop];if(delta<0){newLeft+=track[w]()}else{newLeft-=track[w]()}var otherBounds={};otherBounds[prop]=newLeft;otherTrack.setBounds(otherBounds);otherHeader.setBounds(otherBounds)}}}}).on("tap",this.tap=function(event){if(morpheus.Util.IS_MAC&&event.srcEvent.ctrlKey){return}_this.isMouseOver=false;heatMap.setSelectedTrack(_this.name,isColumns);var vector=(isColumns?project.getFullDataset().getColumnMetadata():project.getFullDataset().getRowMetadata()).getByName(name);if(isColumns&&!heatMap.options.columnsSortable||vector==null){return}if(!isColumns&&!heatMap.options.rowsSortable||vector==null){return}var additionalSort=event.srcEvent.shiftKey;var isGroupBy=false;var existingSortKeyIndex=_this.getSortKeyIndexForColumnName(_this.getSortKeys(),_this.name);var sortOrder;var sortKey;var dataType=morpheus.VectorUtil.getDataType(vector);if(existingSortKeyIndex!=null){sortKey=_this.getSortKeys()[existingSortKeyIndex.index];if(sortKey.getSortOrder()===morpheus.SortKey.SortOrder.UNSORTED){sortOrder=morpheus.SortKey.SortOrder.ASCENDING}else if(sortKey.getSortOrder()===morpheus.SortKey.SortOrder.ASCENDING){sortOrder=morpheus.SortKey.SortOrder.DESCENDING}else if(sortKey.getSortOrder()===morpheus.SortKey.SortOrder.TOP_N){sortOrder=morpheus.SortKey.SortOrder.UNSORTED}else{sortOrder=dataType==="number"||dataType==="[number]"?morpheus.SortKey.SortOrder.TOP_N:morpheus.SortKey.SortOrder.UNSORTED}}else{sortKey=new morpheus.SortKey(_this.name,morpheus.SortKey.SortOrder.ASCENDING);sortOrder=morpheus.SortKey.SortOrder.ASCENDING}if(sortKey!=null){sortKey.setSortOrder(sortOrder);_this.setSortingStatus(_this.getSortKeys(),sortKey,additionalSort,isGroupBy)}});$(this.canvas).on("mousedown",function(event){resizeCursor=getResizeCursor(morpheus.CanvasUtil.getMousePos(event.target,event,true))})};morpheus.VectorTrackHeader.FONT_OFFSET=2;morpheus.VectorTrackHeader.prototype={selected:false,isMouseOver:false,defaultFontHeight:11,dispose:function(){morpheus.AbstractCanvas.prototype.dispose.call(this);this.hammer.off("longpress",this.longpress).off("panend",this.panend).off("panstart",this.panstart).off("panmove",this.panmove).off("tap",this.tap);this.hammer.destroy()},getPreferredSize:function(){var size=this.getPrintSize();size.width+=24;if(!this.isColumns){size.height=this.defaultFontHeight+morpheus.VectorTrackHeader.FONT_OFFSET}return size},getPrintSize:function(){var context=this.canvas.getContext("2d");context.font=this.fontWeight+" "+this.defaultFontHeight+"px "+morpheus.CanvasUtil.getFontFamily(context);var textWidth=4+context.measureText(this.name).width;return{width:textWidth,height:this.defaultFontHeight+morpheus.VectorTrackHeader.FONT_OFFSET}},getSortKeys:function(){return this.isColumns?this.project.getColumnSortKeys():this.project.getRowSortKeys()},setOrder:function(sortKeys){if(this.isColumns){this.project.setColumnSortKeys(morpheus.SortKey.keepExistingSortKeys(sortKeys,this.project.getColumnSortKeys()),false)}else{this.project.setRowSortKeys(morpheus.SortKey.keepExistingSortKeys(sortKeys,this.project.getRowSortKeys()),false)}},setGroupBy:function(groupBy){var existingGroupBy=this.isColumns?this.project.groupColumns:this.project.groupRows;var index=-1;for(var i=0,length=existingGroupBy.length;i1){xpix-=6}}context.fillStyle=morpheus.CanvasUtil.FONT_COLOR;var ypix=this.isColumns?this.getUnscaledHeight()/2:this.getUnscaledHeight()-(this.defaultFontHeight+morpheus.VectorTrackHeader.FONT_OFFSET)/2;context.textBaseline="middle";if(this.isMouseOver){var xdot=xpix-(isColumns?textWidth+4:4);var ydot=ypix-3;for(var i=0;i<2;i++){for(var j=0;j<3;j++){context.fillRect(xdot-i*3,ydot+j*3,1.5,1.5)}}}var fontHeight=Math.min(this.defaultFontHeight,this.getUnscaledHeight()-morpheus.VectorTrackHeader.FONT_OFFSET);fontHeight=Math.min(fontHeight,morpheus.VectorTrack.MAX_FONT_SIZE);context.font=this.font.weight+" "+fontHeight+"px "+morpheus.CanvasUtil.getFontFamily(context);context.fillText(name,xpix,ypix);context.fillStyle=morpheus.CanvasUtil.FONT_COLOR;if(existingSortKeyIndex!==null){context.beginPath();var x=this.isColumns?xpix+4:xpix+textWidth+6;var arrowHeight=Math.min(8,this.getUnscaledHeight()/2-1);var arrowWidth=3;if(sortKeys[existingSortKeyIndex.index].getSortOrder()===morpheus.SortKey.SortOrder.ASCENDING){context.translate(x,ypix-arrowHeight);context.moveTo(0,0);context.lineTo(arrowWidth,arrowHeight);context.lineTo(-arrowWidth,arrowHeight)}else if(sortKeys[existingSortKeyIndex.index].getSortOrder()===morpheus.SortKey.SortOrder.DESCENDING){context.translate(x,ypix);context.moveTo(0,arrowHeight);context.lineTo(arrowWidth,0);context.lineTo(-arrowWidth,0)}else{context.translate(x,ypix-arrowHeight/2);context.moveTo(0,0);context.lineTo(arrowWidth,arrowHeight/2);context.lineTo(0,arrowHeight);context.lineTo(-arrowWidth,arrowHeight/2)}context.fill();morpheus.CanvasUtil.resetTransform(context);context.textAlign="left";if(unlockableSortKeys.length>1){context.font="8px "+morpheus.CanvasUtil.getFontFamily(context);var sortIndex=""+existingSortKeyIndex.number;context.fillText(sortIndex,x+4,ypix-2);x+=context.measureText(sortIndex).width}if(sortKeys[existingSortKeyIndex.index].getLockOrder()!==0){context.font=fontHeight+"px FontAwesome";context.fillText("",x+arrowWidth+2,ypix)}}}};morpheus.Util.extend(morpheus.VectorTrackHeader,morpheus.AbstractCanvas);morpheus.VectorTrack=function(project,name,positions,isColumns,heatmap){morpheus.AbstractCanvas.call(this,true);this.preferredSize={width:0,height:0};this.project=project;this.positions=positions;this.isColumns=isColumns;this.name=name;this.visible=true;this.heatmap=heatmap;this.id=_.uniqueId();var _this=this;this.updateSpanMapFunction=function(){_this.spanMap=morpheus.VectorUtil.createSpanMap(_this.getVector())};this.lastPosition={start:-1,end:-1};this.events="rowSortOrderChanged rowFilterChanged datasetChanged";var mouseMoved=function(event){var index=-1;if(event.type!=="mouseout"){var position=morpheus.CanvasUtil.getMousePosWithScroll(event.target,event,heatmap.scrollLeft(),heatmap.scrollTop());if(_this.settings.squished){var total=positions.getPosition(positions.getLength()-1)+positions.getItemSize(positions.getLength()-1);var squishFactor=total/(isColumns?_this.getUnscaledWidth():_this.getUnscaledHeight());position[isColumns?"x":"y"]*=squishFactor}index=!isColumns?_this.positions.getIndex(position.y,false):_this.positions.getIndex(position.x,false)}if(isColumns){heatmap.setMousePosition(-1,index,{name:_this.name,event:event})}else{heatmap.setMousePosition(index,-1,{name:_this.name,event:event})}};$(this.canvas).on("contextmenu.morpheus",function(e){e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();heatmap.setSelectedTrack(_this.name,isColumns);_this.showPopup(e);return false});this.settings={maxTextWidth:undefined,squished:false,inlineTooltip:false,tooltip:true,highlightMatchingValues:false,colorBarSize:12,stackedBar:false,display:[],selectionColor:"rgb(182,213,253)",colorByField:null,fontField:null,barColor:"#bdbdbd",barSize:40,min:undefined,mid:undefined,max:undefined,autoscaleAlways:false,minMaxReversed:false};$(this.canvas).on("mousemove.morpheus mouseout.morpheus",mouseMoved)};morpheus.VectorTrack.RENDER={TEXT:"text",COLOR:"color",BAR:"bar",MOLECULE:"molecule",TEXT_AND_COLOR:"text_and_color",TEXT_AND_FONT:"text_and_font",SHAPE:"shape",ARC:"arc",BOX_PLOT:"box_plot",HEAT_MAP:"heat_map"};morpheus.VectorTrack.vectorToString=function(vector){var dataType=morpheus.VectorUtil.getDataType(vector);var formatter=vector.getProperties().get(morpheus.VectorKeys.FORMATTER);if(formatter!=null){if(typeof formatter==="object"){formatter=morpheus.Util.createNumberFormat(formatter.pattern);if(dataType==="[number]"){var nf=formatter;formatter=function(v){var s=[];if(v!=null){for(var i=0,arrayLength=v.length;i=6){var context=this.canvas.getContext("2d");var textWidth=morpheus.CanvasUtil.getVectorStringWidth(context,this.getVector(),this.positions,forPrint?-1:this.isColumns?120:100);if(!forPrint){this.settings.maxTextWidth=textWidth}width+=textWidth}else if(!forPrint){this.settings.maxTextWidth=0}}if(this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)){width+=this.settings.barSize}if(this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)){width+=this.settings.colorBarSize}if(this.isRenderAs(morpheus.VectorTrack.RENDER.SHAPE)){width+=this.settings.colorBarSize}if(this.isRenderAs(morpheus.VectorTrack.RENDER.MOLECULE)){width+=300}if(this.isRenderAs(morpheus.VectorTrack.RENDER.ARC)){width+=this.settings.arcSize}if(this.isRenderAs(morpheus.VectorTrack.RENDER.BOX_PLOT)){width+=100}if(this.isRenderAs(morpheus.VectorTrack.RENDER.HEAT_MAP)){width+=100}var nkeys=this.settings.display.length;if(nkeys>0){width+=(nkeys-1)*2}width=Math.max(0,width);return this.isColumns?{width:height,height:width}:{width:width,height:height}},getPreferredSize:function(){return this.preferredSize},getPrintSize:function(){return this._computePreferredSize(true)},_createDiscreteValueMap:function(){var values=morpheus.VectorUtil.getValues(this.getFullVector());values.sort(morpheus.SortKey.ASCENDING_COMPARATOR);this.discreteValueMap=new morpheus.Map;for(var i=0,length=values.length;i0){doRequest(values.pop())}_this.invalid=true;_this.repaint()})};for(var i=0;i<6;i++){doRequest(values.pop())}}this.updateSpanMapFunction()}}this._updatePreferredSize()},postPaint:function(clip,context){context.lineWidth=1;context.strokeStyle="Grey";var project=this.project;var setup=this._setup(context,clip);var vector=setup.vector;var start=setup.start;var end=setup.end;if(this.isColumns){if(project.getHoverColumnIndex()!==-1){this.drawColumnBorder(context,this.positions,project.getHoverColumnIndex(),this.getUnscaledHeight())}}else{if(project.getHoverRowIndex()!==-1){this.drawRowBorder(context,this.positions,project.getHoverRowIndex(),this.getUnscaledWidth())}}this._highlightMatchingValues(context,vector,start,end)},_highlightMatchingValues:function(context,viewVector,start,end){var project=this.project;var positions=this.positions;context.strokeStyle="black";context.lineWidth=3;var hoverIndex=this.isColumns?project.getHoverColumnIndex():project.getHoverRowIndex();var value=viewVector.getValue(hoverIndex);if(this.settings.highlightMatchingValues&&hoverIndex!==-1&&this.heatmap.mousePositionOptions&&this.heatmap.mousePositionOptions.name===viewVector.getName()){var valueToModelIndices=this.getFullVector().getProperties().get(morpheus.VectorKeys.VALUE_TO_INDICES);if(!valueToModelIndices){var fullVector=this.getFullVector();valueToModelIndices=morpheus.VectorUtil.createValueToIndicesMap(fullVector);fullVector.getProperties().set(morpheus.VectorKeys.VALUE_TO_INDICES,valueToModelIndices)}var indices=valueToModelIndices.get(value);if(indices==null){console.log("valueToModelIndices error");return}if(indices.length<=1){return}if(this.isColumns){if(project.getHoverColumnIndex()!==-1){var height=this.getUnscaledHeight();context.beginPath();for(var i=0,nindices=indices.length;i=start&&viewIndex=start&&viewIndex=start&&i<=end){var size=positions.getItemSize(i);var pix=positions.getPosition(i);context.fillRect(pix,0,size,height)}})}else{var width=this.getUnscaledWidth();if(!this.isRenderAs(morpheus.VectorTrack.RENDER.MOLECULE)){var viewIndices=project.getRowSelectionModel().getViewIndices();viewIndices.forEach(function(i){if(i>=start&&i<=end){var size=positions.getItemSize(i);var pix=positions.getPosition(i);context.fillRect(0,pix,width,size)}})}}},prePaint:function(clip,context){var project=this.project;var positions=this.positions;var setup=this._setup(context,clip);var start=setup.start;var end=setup.end;this.drawSelection({context:context,start:start,end:end});if(this.invalid||start!==this.lastPosition.start||end!==this.lastPosition.end){this.lastPosition.start=start;this.lastPosition.end=end;this.invalid=true}},drawRowBorder:function(context,positions,index,gridSize){var size=positions.getItemSize(index);var pix=positions.getPosition(index);context.beginPath();context.moveTo(0,pix+size);context.lineTo(gridSize,pix+size);context.stroke();context.beginPath();context.moveTo(0,pix);context.lineTo(gridSize,pix);context.stroke()},drawColumnBorder:function(context,positions,index,gridSize){var size=positions.getItemSize(index);var pix=positions.getPosition(index);context.beginPath();context.moveTo(pix+size,0);context.lineTo(pix+size,gridSize);context.stroke();context.beginPath();context.moveTo(pix,0);context.lineTo(pix,gridSize);context.stroke()},isSquished:function(){return this.settings.squished},_setup:function(context,clip){var start=0;var vector=this.getVector();var end=vector.size();var settings=this.settings;var positions=this.positions;var width=clip.width;var height=clip.height;if(!settings.squished){if(this.isColumns){start=morpheus.Positions.getLeft(clip,positions);end=morpheus.Positions.getRight(clip,positions)}else{start=morpheus.Positions.getTop(clip,positions);end=morpheus.Positions.getBottom(clip,positions)}}if(settings.squished){var total=positions.getPosition(positions.getLength()-1)+positions.getItemSize(positions.getLength()-1);if(!this.isColumns){var squishFactor=height/total;context.scale(1,squishFactor)}else{var squishFactor=width/total;context.scale(squishFactor,1)}}else{context.translate(-clip.x,-clip.y)}return{start:start,end:end,vector:vector}},draw:function(clip,context){var setup=this._setup(context,clip);this._draw({start:setup.start,end:setup.end,vector:setup.vector,context:context,availableSpace:this.isColumns?this.getUnscaledHeight():this.getUnscaledWidth(),clip:clip})},print:function(clip,context){var vector=this.getVector();this._draw({start:0,end:vector.size(),vector:vector,context:context,availableSpace:this.isColumns?clip.height:clip.width,clip:clip})},_draw:function(options){var _this=this;var context=options.context;var vector=options.vector;var availableSpace=options.availableSpace;var fullAvailableSpace=options.availableSpace;var start=options.start;var end=options.end;var clip=options.clip;var positions=this.positions;if(this.settings.autoscaleAlways){this._setChartMinMax()}context.textAlign="left";context.fillStyle=morpheus.CanvasUtil.FONT_COLOR;var fontSize=Math.min(morpheus.VectorTrack.MAX_FONT_SIZE,positions.getSize()-2);var size=0;context.font=fontSize+"px "+morpheus.CanvasUtil.getFontFamily(context);context.strokeStyle=morpheus.HeatMapElementCanvas.GRID_COLOR;context.lineWidth=.1;if(this.heatmap.heatmap.isDrawGrid()&&!this.settings.squished){if(this.isColumns){var gridSize=availableSpace;context.beginPath();for(var i=start;i7){context.moveTo(pix+size,0);context.lineTo(pix+size,gridSize)}}context.stroke()}else{if(!this.isRenderAs(morpheus.VectorTrack.RENDER.MOLECULE)){var gridSize=availableSpace;context.beginPath();for(var i=start;i7){context.moveTo(0,pix+size);context.lineTo(gridSize,pix+size)}}context.stroke()}}}context.lineWidth=1;var offset=1;if(this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)){this.renderColor(context,vector,start,end,clip,this.isColumns?availableSpace:0,!this.getFullVector().getProperties().get(morpheus.VectorKeys.DISCRETE));offset+=this.settings.colorBarSize+2;availableSpace-=offset}if(!this.settings.squished&&this.isRenderAs(morpheus.VectorTrack.RENDER.SHAPE)){this.renderShape(context,vector,start,end,clip,this.isColumns?availableSpace-offset:offset);offset+=this.settings.colorBarSize+2;availableSpace-=offset}if(this.isRenderAs(morpheus.VectorTrack.RENDER.ARC)){this.renderArc(context,vector,start,end,clip,this.settings.arcSize);offset+=this.settings.arcSize+2;availableSpace-=offset}if(!this.settings.squished&&this.isRenderAs(morpheus.VectorTrack.RENDER.MOLECULE)){this.renderMolecule(context,vector,start,end,clip,offset,availableSpace)}if(this.isRenderAs(morpheus.VectorTrack.RENDER.BOX_PLOT)){var barSize=!this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)?availableSpace-2:this.settings.barSize;offset++;this.renderBoxPlot(context,vector,start,end,clip,offset,barSize);offset+=barSize+2;availableSpace-=offset}if(this.isRenderAs(morpheus.VectorTrack.RENDER.HEAT_MAP)){var barSize=!this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)?availableSpace-2:this.settings.barSize;offset++;this.renderHeatMap(context,vector,start,end,clip,barSize);offset+=barSize+2;availableSpace-=offset}if(this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)){var barSize=!this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)?availableSpace-1:this.settings.barSize;if(this.settings.stackedBar){this.renderStackedBar(context,vector,start,end,clip,offset,barSize)}else{var fields=vector.getProperties().get(morpheus.VectorKeys.FIELDS);var visibleFieldIndices=vector.getProperties().get(morpheus.VectorKeys.VISIBLE_FIELDS);if(fields!=null&&visibleFieldIndices==null){visibleFieldIndices=morpheus.Util.seq(fields.length)}if(fields!=null){this.renderUnstackedBar(context,vector,start,end,clip,offset,barSize,visibleFieldIndices)}else{this.renderBar(context,vector,start,end,clip,this.isColumns?fullAvailableSpace-offset-barSize:offset,barSize)}}offset+=barSize+2;availableSpace-=offset}if(!this.settings.squished&&this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)&&(this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT))){context.fillStyle=morpheus.CanvasUtil.FONT_COLOR;this.renderText(context,vector,this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR),this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT),start,end,clip,this.isColumns?fullAvailableSpace-offset:offset);offset+=this.settings.maxTextWidth+2;availableSpace-=offset}if(!this.settings.squished&&this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)&&!this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR)&&!this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT)){context.fillStyle=morpheus.CanvasUtil.FONT_COLOR;var dataType=morpheus.VectorUtil.getDataType(vector);if(dataType==="url"){context.fillStyle="blue";this.canvas.style.cursor="pointer"}this.renderText(context,vector,false,false,start,end,clip,this.isColumns?fullAvailableSpace-offset:offset)}},showPopup:function(e,isHeader){var _this=this;var project=this.project;var isColumns=this.isColumns;var hasSelection=isColumns?project.getColumnSelectionModel().count()>0:project.getRowSelectionModel().count()>0;var ANNOTATE_SELECTION="Annotate Selection";var INVERT_SELECTION="Invert Selection";var SELECT_ALL="Select All";var SHOW_SELECTION_ONLY="Show Selection Only";var CLEAR_SELECTION="Clear Selection";var HIGHLIGHT_MATCHING_VALUES="Highlight Matching Values";var FIELDS="Choose Fields...";var DELETE="Delete...";var TOOLTIP="Show In Tooltip";var HIDE="Hide";var HIDE_OTHERS="Hide Others";var REMOVE_SHOW_SELECTION_ONLY="Show All";var SORT_ASC="Sort Ascending";var SORT_DESC="Sort Descending";var MOVE_TO_TOP="Move To Top";var SORT_SEL_ASC="Sort Heat Map Ascending ↑";var SORT_SEL_DESC="Sort Heat Map Descending ↓";var SORT_SEL_TOP_N="Sort Heat Map Descending/Ascending";var DISPLAY_BAR="Show Bar Chart";var NUMBER_FORMAT="Format";var DISPLAY_STACKED_BAR="Show Stacked Bar Chart";var DISPLAY_BOX_PLOT="Show Box Plot";var DISPLAY_COLOR="Show Color";var COLOR_BAR_SIZE="Color Bar Size...";var DISPLAY_TEXT="Show Text";var DISPLAY_SHAPE="Show Shape";var DISPLAY_ARC="Show Arc";var DISPLAY_TEXT_AND_COLOR="Encode Text Using Color";var DISPLAY_TEXT_AND_FONT="Encode Text Using Font";var DISPLAY_STRUCTURE="Show Chemical Structure";var DISPLAY_CONTINUOUS="Continuous";var positions=this.positions;var heatmap=this.heatmap;var sectionToItems={Sort:[],Selection:[],Display:[]};var customItems=this.heatmap.getPopupItems();if(customItems&&customItems.length>0){customItems.forEach(function(item){if(item.columns===isColumns){sectionToItems[item.section].push(item)}})}if(sectionToItems.Selection.length>0){sectionToItems.Selection.push({separator:true})}sectionToItems.Selection.push({name:MOVE_TO_TOP});if(this.heatmap.options.menu.Edit&&this.heatmap.options.menu.Edit.indexOf("Annotate"+" Selected Rows")!==-1){sectionToItems.Selection.push({name:ANNOTATE_SELECTION})}sectionToItems.Selection.push({name:"Copy",class:"copy"});sectionToItems.Selection.push({name:INVERT_SELECTION});sectionToItems.Selection.push({name:SELECT_ALL});sectionToItems.Selection.push({name:CLEAR_SELECTION});var combinedFilter=isColumns?project.getColumnFilter():project.getRowFilter();var showSelectionOnlyIndex=combinedFilter.indexOf(SHOW_SELECTION_ONLY);if(showSelectionOnlyIndex!==-1){sectionToItems.Selection.push({name:REMOVE_SHOW_SELECTION_ONLY})}if(!isHeader){sectionToItems["Sort"].push({name:SORT_SEL_ASC,disabled:!hasSelection});sectionToItems["Sort"].push({name:SORT_SEL_DESC,disabled:!hasSelection});sectionToItems["Sort"].push({name:SORT_SEL_TOP_N,disabled:!hasSelection})}var dataType=morpheus.VectorUtil.getDataType(this.getFullVector());var arrayFields=this.getFullVector().getProperties().get(morpheus.VectorKeys.FIELDS);var isArray=arrayFields!==undefined;var isNumber=dataType==="number"||dataType==="[number]";if(isNumber||isArray){sectionToItems.Display.push({name:NUMBER_FORMAT});sectionToItems.Display.push({separator:true});sectionToItems.Display.push({name:DISPLAY_BAR,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)})}if(isArray){sectionToItems.Display.push({name:DISPLAY_STACKED_BAR,checked:this.settings.stackedBar});sectionToItems.Display.push({name:DISPLAY_BOX_PLOT,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.BOX_PLOT)});sectionToItems.Display.push({name:FIELDS})}if(dataType!=="url"){sectionToItems.Display.push({name:DISPLAY_TEXT,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)});if(this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT)){sectionToItems.Display.push({name:DISPLAY_TEXT_AND_COLOR,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR)});sectionToItems.Display.push({name:DISPLAY_TEXT_AND_FONT,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT)})}sectionToItems.Display.push({separator:true});sectionToItems.Display.push({name:DISPLAY_COLOR,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)});if(this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)){sectionToItems.Display.push({name:COLOR_BAR_SIZE})}}if(!isArray&&dataType!=="url"){sectionToItems.Display.push({name:DISPLAY_SHAPE,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.SHAPE)})}if(!isArray&&!isNumber&&!this.isColumns&&name.toLowerCase().indexOf("smile")!==-1){sectionToItems.Display.push({name:DISPLAY_STRUCTURE,checked:this.isRenderAs(morpheus.VectorTrack.RENDER.MOLECULE)})}sectionToItems.Display.push({name:TOOLTIP,checked:this.settings.inlineTooltip});if(!isArray&&dataType!=="url"){sectionToItems.Display.push({name:HIGHLIGHT_MATCHING_VALUES,checked:this.settings.highlightMatchingValues})}if(dataType!=="url"){}if(this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)||this.isRenderAs(morpheus.VectorTrack.RENDER.BOX_PLOT)){sectionToItems.Display.push({separator:true});if(this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)){sectionToItems.Display.push({name:"Edit Bar Color..."})}sectionToItems.Display.push({name:"Auto Range"});sectionToItems.Display.push({name:"Custom Range..."})}if(this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT)||this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)||this.isRenderAs(morpheus.VectorTrack.RENDER.SHAPE)){sectionToItems.Display.push({separator:true});if(isNumber){sectionToItems.Display.push({name:DISPLAY_CONTINUOUS,checked:!this.getFullVector().getProperties().get(morpheus.VectorKeys.DISCRETE)})}if(this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)&&isArray){sectionToItems.Display.push({name:"Edit Colors..."})}if(this.isRenderAs(morpheus.VectorTrack.RENDER.SHAPE)){sectionToItems.Display.push({name:"Edit Shapes..."})}if(this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT)){sectionToItems.Display.push({name:"Edit Fonts..."})}if(this.isRenderAs(morpheus.VectorTrack.RENDER.COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_COLOR)||this.isRenderAs(morpheus.VectorTrack.RENDER.BAR)&&isArray){sectionToItems.Display.push({name:"Color Key",icon:"fa fa-key"})}}if(this.isRenderAs(morpheus.VectorTrack.RENDER.SHAPE)){sectionToItems.Display.push({name:"Shape Key",icon:"fa fa-key"})}if(this.isRenderAs(morpheus.VectorTrack.RENDER.TEXT_AND_FONT)){sectionToItems.Display.push({name:"Font Key",icon:"fa fa-key"})}sectionToItems.Display.push({separator:true});sectionToItems.Display.push({name:HIDE});sectionToItems.Display.push({name:HIDE_OTHERS,disabled:heatmap.getVisibleTrackNames(this.isColumns).length<=1});sectionToItems.Display.push({separator:true});sectionToItems.Display.push({name:DELETE});var items=[];function addSection(name){if(items.length>0){items.push({separator:true})}items=items.concat(sectionToItems[name])}addSection("Sort");_.each(sectionToItems.Selection,function(item){if(item.name!==REMOVE_SHOW_SELECTION_ONLY&&item.name!==SELECT_ALL){item.disabled=!hasSelection}});if(!isHeader){addSection("Selection")}else if(this.heatmap.options.toolbar.options){addSection("Display")}if(e.preventDefault){e.preventDefault()}if(items.length===0){return}morpheus.Popup.showPopup(items,{x:e.pageX,y:e.pageY},e.target,function(event,item){var customItem;if(item===NUMBER_FORMAT){var vector=_this.getFullVector();var formatter=vector.getProperties().get(morpheus.VectorKeys.FORMATTER);if(formatter!=null){if(typeof formatter==="object"){formatter=morpheus.Util.createNumberFormat(formatter.pattern);vector.getProperties().set(morpheus.VectorKeys.FORMATTER,formatter)}}var pattern=formatter!=null?formatter.toJSON().pattern:".2f";var formBuilder=new morpheus.FormBuilder;formBuilder.append({name:"number_of_fraction_digits",type:"number",value:morpheus.Util.getNumberFormatPatternFractionDigits(pattern),required:true,style:"max-width:60px;"});formBuilder.find("number_of_fraction_digits").on("keyup input",_.debounce(function(){var n=parseInt($(this).val());if(n>=0){vector.getProperties().set(morpheus.VectorKeys.FORMATTER,{pattern:"."+n+"f"});_this.setInvalid(true);_this.repaint()}},100));morpheus.FormBuilder.showInModal({title:"Format",close:"Close",html:formBuilder.$form,focus:heatmap.getFocusEl()})}else if(item==="Copy"){heatmap.getActionManager().execute(isColumns?"Copy Selected Columns":"Copy"+" Selected Rows")}else if(item===FIELDS){var visibleFieldIndices=_this.getFullVector().getProperties().get(morpheus.VectorKeys.VISIBLE_FIELDS);var visibleFields;if(visibleFieldIndices==null){visibleFields=arrayFields.slice(0)}else{visibleFields=[];for(var i=0;i0){_this.settings.colorBarSize=val;_this.setInvalid(true);_this.repaint()}});morpheus.FormBuilder.showInModal({title:"Color Bar Size",close:"Close",html:formBuilder.$form,focus:heatmap.getFocusEl()})}else if(item===ANNOTATE_SELECTION){heatmap.getActionManager().execute(isColumns?"Annotate Selected Columns":"Annotate"+" Selected Rows")}else if(item===DELETE){morpheus.FormBuilder.showOkCancel({title:"Delete",content:"Are you sure you want to delete "+_this.name+"?",okCallback:function(){var metadata=isColumns?project.getFullDataset().getColumnMetadata():project.getFullDataset().getRowMetadata();metadata.remove(morpheus.MetadataUtil.indexOf(metadata,_this.name));var sortKeys=isColumns?project.getColumnSortKeys():project.getRowSortKeys();var sortKeyIndex=_.indexOf(sortKeys.map(function(key){return key.field}),_this.name);if(sortKeyIndex!==-1){sortKeys.splice(sortKeyIndex,1);if(isColumns){project.setColumnSortKeys(sortKeys,true)}else{project.setRowSortKeys(sortKeys,true)}}var groupByKeys=isColumns?project.getGroupColumns():project.getGroupRows();var groupByKeyIndex=_.indexOf(groupByKeys.map(function(key){return key.field}),_this.name);if(groupByKeyIndex!==-1){groupByKeys.splice(groupByKeyIndex,1);if(isColumns){project.setGroupColumns(groupByKeys,true)}else{project.setGroupRows(groupByKeys,true)}}if(!isColumns){project.trigger("rowTrackRemoved",{vector:_this.getFullVector()})}else{project.trigger("columnTrackRemoved",{vector:_this.getFullVector()})}}})}else if(item===CLEAR_SELECTION){heatmap.getActionManager().execute(isColumns?"Clear Selected Columns":"Clear"+" Selected Rows")}else if(item===INVERT_SELECTION){heatmap.getActionManager().execute(isColumns?"Invert Selected Columns":"Invert"+" Selected Rows")}else if(item===MOVE_TO_TOP){heatmap.getActionManager().execute(isColumns?"Move Selected Columns To Top":"Move"+" Selected Rows To Top")}else if(item===SORT_ASC||item===SORT_DESC){var sortKey=new morpheus.SortKey(_this.name,item===SORT_ASC?morpheus.SortKey.SortOrder.ASCENDING:morpheus.SortKey.SortOrder.DESCENDING);if(_this.isColumns){_this.project.setColumnSortKeys(morpheus.SortKey.keepExistingSortKeys([sortKey],project.getColumnSortKeys()),true)}else{_this.project.setRowSortKeys(morpheus.SortKey.keepExistingSortKeys([sortKey],project.getRowSortKeys()),true)}}else if(item==SORT_SEL_ASC||item==SORT_SEL_DESC||item===SORT_SEL_TOP_N){var sortOrder;if(item===SORT_SEL_ASC){sortOrder=morpheus.SortKey.SortOrder.ASCENDING}else if(item===SORT_SEL_DESC){sortOrder=morpheus.SortKey.SortOrder.DESCENDING}else{sortOrder=morpheus.SortKey.SortOrder.TOP_N}heatmap.sortBasedOnSelection(sortOrder,isColumns,e&&e.shiftKey)}else if(item===SELECT_ALL){heatmap.getActionManager().execute(isColumns?"Select All Columns":"Select All Rows")}else if(item==="Auto Range"){delete _this.settings.min;delete _this.settings.max;delete _this.settings.mid;_this._update();heatmap.revalidate()}else if(item==="Custom Range..."){var formBuilder=new morpheus.FormBuilder;var items=[{name:"min",required:true,type:"number",value:_this.settings.min},{name:"mid",required:true,type:"number",value:_this.settings.mid},{name:"max",required:true,type:"number",value:_this.settings.max}];_.each(items,function(item){formBuilder.append(item)});morpheus.FormBuilder.showOkCancel({title:"Range",content:formBuilder.$form,okCallback:function(){_this.settings.min=parseFloat(formBuilder.getValue("min"));_this.settings.mid=parseFloat(formBuilder.getValue("mid"));_this.settings.max=parseFloat(formBuilder.getValue("max"));_this._update();heatmap.revalidate()}})}else if(item==="Squished"){_this.settings.squished=!_this.settings.squished;heatmap.revalidate()}else if(item==="Color Key"){var legend=new morpheus.HeatMapTrackColorLegend([_this],isColumns?_this.project.getColumnColorModel():_this.project.getRowColorModel());var size=legend.getPreferredSize();legend.setBounds(size);legend.repaint();morpheus.FormBuilder.showInModal({title:"Color Key",html:legend.canvas,focus:heatmap.getFocusEl()})}else if(item==="Shape Key"){var legend=new morpheus.HeatMapTrackShapeLegend([_this],isColumns?_this.project.getColumnShapeModel():_this.project.getRowShapeModel());var size=legend.getPreferredSize();legend.setBounds(size);legend.repaint();morpheus.FormBuilder.showInModal({title:"Shape Key",html:legend.canvas,focus:heatmap.getFocusEl()})}else if(item==="Font Key"){var legend=new morpheus.HeatMapTrackFontLegend([_this],isColumns?_this.project.getColumnFontModel():_this.project.getRowFontModel());var size=legend.getPreferredSize();legend.setBounds(size);legend.repaint();morpheus.FormBuilder.showInModal({title:"Font Key",html:legend.canvas,focus:heatmap.getFocusEl()})}else if(item==="Edit Fonts..."){heatmap.getActionManager().execute("Edit Fonts")}else if(item==="Edit Shapes..."){var shapeFormBuilder=new morpheus.FormBuilder;var shapeModel=isColumns?_this.project.getColumnShapeModel():_this.project.getRowShapeModel();var chooser=new morpheus.ShapeChooser({map:shapeModel.getMap(_this.name)});chooser.on("change",function(event){shapeModel.setMappedValue(_this.getFullVector(),event.value,event.shape);_this.setInvalid(true);_this.repaint()});morpheus.FormBuilder.showInModal({title:"Edit Shapes",html:chooser.$div,close:"Close",focus:heatmap.getFocusEl()})}else if(item==="Edit Colors..."){var colorModel=isColumns?_this.project.getColumnColorModel():_this.project.getRowColorModel();var colorSchemeChooser=new morpheus.ColorSchemeChooser({track:_this,heatMap:_this.heatmap,colorModel:colorModel});morpheus.FormBuilder.showInModal({title:"Edit Colors",html:colorSchemeChooser.$div,close:"Close",focus:heatmap.getFocusEl()})}else if(item===TOOLTIP){_this.settings.inlineTooltip=!_this.settings.inlineTooltip}else if(item===HIGHLIGHT_MATCHING_VALUES){_this.settings.highlightMatchingValues=!_this.settings.highlightMatchingValues}else if(customItem=_.find(customItems,function(customItem){return customItem.name===item&&customItem.columns===isColumns})){if(customItem.task){var task={tabId:_this.heatmap.getTabManager().getActiveTabId()};_this.heatmap.getTabManager().addTask(task);setTimeout(function(){customItem.callback(heatmap);_this.heatmap.getTabManager().removeTask(task)},1)}else{customItem.callback(heatmap)}}else if(item===DISPLAY_CONTINUOUS){var discrete=_this.getFullVector().getProperties().get(morpheus.VectorKeys.DISCRETE)||false;_this.getFullVector().getProperties().set(morpheus.VectorKeys.DISCRETE,!discrete);_this._setChartMinMax();_this.setInvalid(true);_this.repaint()}else if(item===HIDE){heatmap.setTrackVisible(_this.name,false,_this.isColumns);heatmap.revalidate()}else if(item===HIDE_OTHERS){var names=heatmap.getVisibleTrackNames(_this.isColumns);for(var i=0;icanvasSize){colorBarSize=canvasSize>=5?canvasSize-1:canvasSize}var getColor;if(!continuous){getColor=_.bind(colorModel.getMappedValue,colorModel)}else{getColor=_.bind(colorModel.getContinuousMappedValue,colorModel)}if(vector.getProperties().get(morpheus.VectorKeys.FIELDS)!=null){var visibleFieldIndices=vector.getProperties().get(morpheus.VectorKeys.VISIBLE_FIELDS);if(visibleFieldIndices==null){visibleFieldIndices=morpheus.Util.seq(vector.getProperties().get(morpheus.VectorKeys.FIELDS).length)}colorBarSize/=visibleFieldIndices.length;var nvisibleFieldIndices=visibleFieldIndices.length;for(var i=start;icanvasSize){colorBarSize=canvasSize>=5?canvasSize-1:canvasSize}context.fillStyle="black";context.strokeStyle="black";var lineWidth=context.lineWidth;context.lineWidth=1;for(var i=start;i10){context.strokeStyle=gridColor;context.lineWidth=gridThickness;context.beginPath();for(var j=0;j').appendTo($(document.body));this.jsme=new JSApplet.JSME(this.jsmeId,"380px","340px",{})}this.jsme.readMolFile(sdf);var svg=$("#"+this.jsmeId+" > div > div > div:nth-child(2) > svg");var svgWidth=svg.width.baseVal.value;var svgHeight=svg.height.baseVal.value;var scale=Math.min(width/svgWidth,height/svgHeight);var text=''+svg.innerHTML+"";return text},renderMolecule:function(context,vector,start,end,clip,offset){var isColumns=this.isColumns;var positions=this.positions;context.fillStyle=morpheus.CanvasUtil.FONT_COLOR;context.strokeStyle="black";var width=this.getUnscaledWidth();var customUrlProvider=this.heatmap.options.structureUrlProvider!==undefined;var dummyTarget={childNodes:[],getContext:function(){return context}};for(var i=start;i=this.settings.mid){positivePairs.push({value:value,index:j})}else if(value<0){negativePairs.push({value:value,index:j})}}var positiveIndices=morpheus.Util.indexSortPairs(positivePairs,false);for(var j=0,length=positiveIndices.length;j1;n--){morpheus.HCluster.findClosestPair(n,distmatrix,r);result[nelements-n]={};result[nelements-n].distance=r.distance;var is=r.ip;var js=r.jp;result[nelements-n].left=clusterid[is];result[nelements-n].right=clusterid[js];var sum=number[is]+number[js];for(j=0;j1;n--){morpheus.HCluster.findClosestPair(n,distmatrix,r);result[nelements-n].distance=r.distance;var is=r.ip;var js=r.jp;for(j=0;j=order2){neworder[j]+=increase}if(clusterid==i2&&order1order2){neworder[j]+=increase}if(clusterid==i2&&order1<=order2){neworder[j]+=increase}if(clusterid==i1||clusterid==i2){clusterids[j]=-i-1}}}}return morpheus.Util.indexSort(neworder,true)};morpheus.KMeansPlusPlusClusterer=function(k,maxIterations,distanceFunction){var distance=function(points1,points2){return distanceFunction(points1.getPoint(),points2.getPoint())};function nextInt(upperBound){return Math.floor(Math.random()*upperBound)|0}function nextDouble(){return Math.random()}function PointWrapper(point){this.getPoint=function(){return point}}function CentroidCluster(center){var centroidPoints=[];this.addPoint=function(p){centroidPoints.push(p)};this.getPoints=function(){return centroidPoints};this.getCenter=function(){return center}}function cluster(points){if(points.length=r){nextPointIndex=i;break}}}if(nextPointIndex===-1){for(var i=numPoints-1;i>=0;i--){if(!taken[i]){nextPointIndex=i;break}}}if(nextPointIndex>=0){var p=pointList[nextPointIndex];resultSet.push(new CentroidCluster(p));taken[nextPointIndex]=true;if(resultSet.length0){var center=cluster.getCenter();var points=cluster.getPoints();var distances=new Float32Array(points.length);for(var i=0;imaxVariance){maxVariance=variance;selected=cluster}}}if(selected==null){throw"All clusters are empty"}var selectedPoints=selected.getPoints();return selectedPoints.splice(nextInt(selectedPoints.length),1)}function getNearestCluster(clusters,point){var minDistance=Number.MAX_VALUE;var clusterIndex=0;var minCluster=0;for(var i=0;i=score){rowSpecificPValues[i]++}}}var N=numPermutations;var kArray=new Uint32Array(numRows);for(var i=0;i=1;i--){var j=getRandomIntInclusive(0,i);var tmp=indices[j];indices[j]=indices[i];indices[i]=tmp}return indices}};morpheus.UnbalancedPermuter=function(numClassZero,numClassOne){var assignments=new Uint32Array(numClassZero+numClassOne);var indices=new Uint32Array(numClassZero+numClassOne);for(var i=0;i=1;i--){var j=getRandomIntInclusive(0,i);var tmp=indices[j];indices[j]=indices[i];indices[i]=tmp}for(var i=0;iranks[i-1].value){pos=i+1;if(tiesTrace.length>1){morpheus.Ranking.fillAverage(out,tiesTrace)}tiesTrace=[];tiesTrace.push(ranks[i].position)}else{tiesTrace.push(ranks[i].position)}out[ranks[i].position]=pos}if(tiesTrace.length>1){morpheus.Ranking.fillAverage(out,tiesTrace)}return out};morpheus.Ranking.fill=function(data,tiesTrace,value){for(var i=0,length=tiesTrace.length;i=temp[j]){if(result[j].distance=result[vector[j]].distance){vector[j]=i}}}for(i=0;iterm2)return+1;return 0});for(i=0;i curMax) { + curMax = mean; + curIndex = i; + } + } + return { + value : curMax, + index : curIndex + } +}; + morpheus.Positions = function () { this.spaces = undefined; this.defaultPositionFunction = function (index) { @@ -13317,7 +13354,8 @@ morpheus.ChartTool.getTooltip = function (options) { morpheus.CollapseDatasetTool = function () { }; morpheus.CollapseDatasetTool.Functions = [morpheus.Mean, morpheus.Median, - new morpheus.MaxPercentiles([25, 75]), morpheus.Min, morpheus.Max, morpheus.Percentile, morpheus.Sum]; + new morpheus.MaxPercentiles([25, 75]), morpheus.Min, morpheus.Max, morpheus.Percentile, morpheus.Sum, + morpheus.MaximumMeanProbe, morpheus.MaximumMedianProbe]; morpheus.CollapseDatasetTool.Functions.fromString = function (s) { for (var i = 0; i < morpheus.CollapseDatasetTool.Functions.length; i++) { if (morpheus.CollapseDatasetTool.Functions[i].toString() === s) { @@ -13344,6 +13382,7 @@ morpheus.CollapseDatasetTool.prototype = { form.setVisible('percentile', false); form.$form.find('[name=collapse_method]').on('change', function (e) { form.setVisible('percentile', $(this).val() === morpheus.Percentile.toString()); + form.setVisible('collapse', !morpheus.CollapseDatasetTool.Functions.fromString($(this).val()).selectOne); }); setValue('Rows'); @@ -13392,7 +13431,8 @@ morpheus.CollapseDatasetTool.prototype = { } var allFields = morpheus.MetadataUtil.getMetadataNames(dataset .getRowMetadata()); - dataset = morpheus.CollapseDataset(dataset, collapseToFields, f, true); + var collapseMethod = f.selectOne ? morpheus.SelectRow : morpheus.CollapseDataset; + dataset = collapseMethod(dataset, collapseToFields, f, true); if (!rows) { dataset = new morpheus.TransposedDatasetView(dataset); } @@ -13404,9 +13444,9 @@ morpheus.CollapseDatasetTool.prototype = { set.remove(field); }); // hide fields that were not part of collapse to - set.forEach(function (val, name) { - heatMap.setTrackVisible(name, false, !rows); - }); + // set.forEach(function (val, name) { + // heatMap.setTrackVisible(name, false, !rows); + // }); return new morpheus.HeatMap({ name: heatMap.getName(), dataset: dataset, @@ -38056,6 +38096,86 @@ morpheus.CollapseDataset = function (dataset, collapseToFields, return collapsedDataset; }; + +morpheus.SelectRow = function (dataset, collapseToFields, + summarizeFunction, shallowCopy) { + var vectors = []; + var nfields = collapseToFields.length; + + for (var i = 0; i < nfields; i++) { + var v = dataset.getRowMetadata().getByName(collapseToFields[i]); + if (!v) { + throw collapseToFields[i] + + ' not found. Available fields are ' + + morpheus.MetadataUtil.getMetadataNames(dataset + .getRowMetadata()); + } + vectors.push(v); + } + + var idToIndices = morpheus.VectorUtil.createValuesToIndicesMap(vectors); + + var collapsedDataset = new morpheus.Dataset({ + name: dataset.getName(), + rows: idToIndices.size(), + columns: dataset.getColumnCount(), + dataType: 'Float32' + }); + + + var nseries = dataset.getSeriesCount(); + for (var series = 1; series < nseries; series++) { + collapsedDataset.addSeries({ + name: dataset.getName(i), + dataType: 'Float32' + }); + } + if (shallowCopy) { + collapsedDataset.setColumnMetadata(dataset.getColumnMetadata()); + } else { + morpheus.MetadataUtil.copy(dataset.getColumnMetadata(), + collapsedDataset.getColumnMetadata()); + } + + var names = morpheus.MetadataUtil.getMetadataNames(dataset.getRowMetadata()); + var collapseToVectors = []; + var allvectors = []; + for (var i = 0; i < names.length; i++) { + var v = dataset.getRowMetadata().getByName(names[i]); + collapseToVectors.push(collapsedDataset.getRowMetadata().add(names[i])); + allvectors.push(v); + } + + var counter = 0; + + idToIndices + .forEach(function (rowIndices, key) { + var slice = morpheus.DatasetUtil.slicedView(dataset, + rowIndices, null); + var view = new morpheus.DatasetRowView(slice); + var indexInDataset; + for (var series = 0; series < nseries; series++) { + view.setSeriesIndex(series); + var chosenIndex = summarizeFunction(view).index; + view.setIndex(chosenIndex); + indexInDataset = view.dataset.rowIndices[chosenIndex]; + + for (var j = 0, ncols = dataset.getColumnCount(); j < ncols; j++) { + collapsedDataset.setValue(counter, j, + view.getValue(j), series); + } + } + for (var i = 0; i < names.length; i++) { + var collapsedToVector = collapseToVectors[i]; + var vector = allvectors[i]; + collapsedToVector.setValue(counter, vector + .getValue(indexInDataset)); + } + counter++; + }); + return collapsedDataset; +}; + morpheus.CompleteLinkage = function (nelements, distmatrix) { var j; var n; diff --git a/src/algorithm/collapse_dataset.js b/src/algorithm/collapse_dataset.js index e488a025..ce0d1658 100644 --- a/src/algorithm/collapse_dataset.js +++ b/src/algorithm/collapse_dataset.js @@ -70,3 +70,83 @@ morpheus.CollapseDataset = function (dataset, collapseToFields, } return collapsedDataset; }; + + +morpheus.SelectRow = function (dataset, collapseToFields, + summarizeFunction, shallowCopy) { + var vectors = []; + var nfields = collapseToFields.length; + + for (var i = 0; i < nfields; i++) { + var v = dataset.getRowMetadata().getByName(collapseToFields[i]); + if (!v) { + throw collapseToFields[i] + + ' not found. Available fields are ' + + morpheus.MetadataUtil.getMetadataNames(dataset + .getRowMetadata()); + } + vectors.push(v); + } + + var idToIndices = morpheus.VectorUtil.createValuesToIndicesMap(vectors); + + var collapsedDataset = new morpheus.Dataset({ + name: dataset.getName(), + rows: idToIndices.size(), + columns: dataset.getColumnCount(), + dataType: 'Float32' + }); + + + var nseries = dataset.getSeriesCount(); + for (var series = 1; series < nseries; series++) { + collapsedDataset.addSeries({ + name: dataset.getName(i), + dataType: 'Float32' + }); + } + if (shallowCopy) { + collapsedDataset.setColumnMetadata(dataset.getColumnMetadata()); + } else { + morpheus.MetadataUtil.copy(dataset.getColumnMetadata(), + collapsedDataset.getColumnMetadata()); + } + + var names = morpheus.MetadataUtil.getMetadataNames(dataset.getRowMetadata()); + var collapseToVectors = []; + var allvectors = []; + for (var i = 0; i < names.length; i++) { + var v = dataset.getRowMetadata().getByName(names[i]); + collapseToVectors.push(collapsedDataset.getRowMetadata().add(names[i])); + allvectors.push(v); + } + + var counter = 0; + + idToIndices + .forEach(function (rowIndices, key) { + var slice = morpheus.DatasetUtil.slicedView(dataset, + rowIndices, null); + var view = new morpheus.DatasetRowView(slice); + var indexInDataset; + for (var series = 0; series < nseries; series++) { + view.setSeriesIndex(series); + var chosenIndex = summarizeFunction(view).index; + view.setIndex(chosenIndex); + indexInDataset = view.dataset.rowIndices[chosenIndex]; + + for (var j = 0, ncols = dataset.getColumnCount(); j < ncols; j++) { + collapsedDataset.setValue(counter, j, + view.getValue(j), series); + } + } + for (var i = 0; i < names.length; i++) { + var collapsedToVector = collapseToVectors[i]; + var vector = allvectors[i]; + collapsedToVector.setValue(counter, vector + .getValue(indexInDataset)); + } + counter++; + }); + return collapsedDataset; +}; diff --git a/src/matrix/multivariate_functions.js b/src/matrix/multivariate_functions.js new file mode 100644 index 00000000..5bf44aa7 --- /dev/null +++ b/src/matrix/multivariate_functions.js @@ -0,0 +1,36 @@ +morpheus.MaximumMeanProbe = function(probes) { + return morpheus.MaximumUnivariateFunction(probes, morpheus.Mean); +}; + +morpheus.MaximumMeanProbe.toString = function() { + return "Maximum Mean Probe"; +}; + +morpheus.MaximumMeanProbe.selectOne = true; + +morpheus.MaximumMedianProbe = function(probes) { + return morpheus.MaximumUnivariateFunction(probes, morpheus.Median); +}; + +morpheus.MaximumMedianProbe.toString = function() { + return "Maximum Median Probe"; +}; + +morpheus.MaximumMedianProbe.selectOne = true; + +morpheus.MaximumUnivariateFunction = function(rowView, fun) { + var curMax = Number.NEGATIVE_INFINITY; + var curIndex = -1; + for (var i = 0; i < rowView.dataset.getRowCount(); i++) { + rowView.setIndex(i); + var mean = fun(rowView); + if (mean > curMax) { + curMax = mean; + curIndex = i; + } + } + return { + value : curMax, + index : curIndex + } +}; diff --git a/src/tools/collapse_dataset_tool.js b/src/tools/collapse_dataset_tool.js index a0aaf557..b84178f2 100644 --- a/src/tools/collapse_dataset_tool.js +++ b/src/tools/collapse_dataset_tool.js @@ -1,7 +1,8 @@ morpheus.CollapseDatasetTool = function () { }; morpheus.CollapseDatasetTool.Functions = [morpheus.Mean, morpheus.Median, - new morpheus.MaxPercentiles([25, 75]), morpheus.Min, morpheus.Max, morpheus.Percentile, morpheus.Sum]; + new morpheus.MaxPercentiles([25, 75]), morpheus.Min, morpheus.Max, morpheus.Percentile, morpheus.Sum, + morpheus.MaximumMeanProbe, morpheus.MaximumMedianProbe]; morpheus.CollapseDatasetTool.Functions.fromString = function (s) { for (var i = 0; i < morpheus.CollapseDatasetTool.Functions.length; i++) { if (morpheus.CollapseDatasetTool.Functions[i].toString() === s) { @@ -28,6 +29,7 @@ morpheus.CollapseDatasetTool.prototype = { form.setVisible('percentile', false); form.$form.find('[name=collapse_method]').on('change', function (e) { form.setVisible('percentile', $(this).val() === morpheus.Percentile.toString()); + form.setVisible('collapse', !morpheus.CollapseDatasetTool.Functions.fromString($(this).val()).selectOne); }); setValue('Rows'); @@ -76,7 +78,8 @@ morpheus.CollapseDatasetTool.prototype = { } var allFields = morpheus.MetadataUtil.getMetadataNames(dataset .getRowMetadata()); - dataset = morpheus.CollapseDataset(dataset, collapseToFields, f, true); + var collapseMethod = f.selectOne ? morpheus.SelectRow : morpheus.CollapseDataset; + dataset = collapseMethod(dataset, collapseToFields, f, true); if (!rows) { dataset = new morpheus.TransposedDatasetView(dataset); } @@ -88,9 +91,9 @@ morpheus.CollapseDatasetTool.prototype = { set.remove(field); }); // hide fields that were not part of collapse to - set.forEach(function (val, name) { - heatMap.setTrackVisible(name, false, !rows); - }); + // set.forEach(function (val, name) { + // heatMap.setTrackVisible(name, false, !rows); + // }); return new morpheus.HeatMap({ name: heatMap.getName(), dataset: dataset,