<commit_before>function getGraphStep(minValue, maxValue, step) {

    if (step) return step;

    var copy = maxValue;

    if (minValue < 0) {
        copy = maxValue - minValue;
    }

    var pow = 1

    while (copy > 10) {

        copy = copy / 10;
        pow++;
    }

    return Math.pow(10, pow - 1);
}

function getGraphEnd(minValue, maxValue, s) {
    var step = getGraphStep(minValue, maxValue, s);

    var max = 0;

    while (max < maxValue) {

        max += step;
    }

    return max;
}

function getGraphBegin(minValue, maxValue, s) {
    if (minValue > 0) return 0;

    var step = getGraphStep(minValue, maxValue, s);
    var min = 0;

    while (min > minValue) {

        min -= step;
    }

    return min;
}

function getDxChart(graphControl) {

    if (graphControl) {

        if (graphControl.aasDxChart) {

            return graphControl.aasDxChart;

        } else if (graphControl.aasChartProperties) {

            return graphControl.aasChartProperties.dxChart;
        }
    }

    return null;
}
Global.DhtmlxChartService = {

    aasService: 'DhtmlxChartService',
    aasPublished: true,

    GetGraphEnd: function (minValue, maxValue) {
        return getGraphEnd(minValue, maxValue);
    },

    GetGraphStep: function (minValue, maxValue) {
        return getGraphStep(minValue, maxValue);
    },

    GetGraphBegin: function (minValue, maxValue) {
        return getGraphBegin(minValue, maxValue);
    },

    RefreshGraph: function (graphControlId) {

        var graphControl = document.getElementById(graphControlId);

        var dxChart = getDxChart(graphControl);

        if (graphControl && dxChart) {

            var rowCount = graphControl.aasRowCount;

            var currentWidth = graphControl.parentNode.clientWidth;

            graphControl.style.width = graphControl.parentNode.clientWidth + 'px';

            var xAxis = graphControl.aasChartProperties.xAxis;

            var pointWidth = graphControl.aasChartProperties.AllAxis[xAxis].PointWidth;

            if (currentWidth <= rowCount * pointWidth) {
                graphControl.style.width = rowCount * pointWidth + 'px';
            }
            else {
                graphControl.style.width = graphControl.parentNode.clientWidth + 'px';
            }

            Aspectize.ProtectedCall(dxChart, dxChart.refresh);
            Aspectize.ProtectedCall(dxChart, dxChart.resize);
        }
    },

    SetChartProperties: function (graphControlId, dhtmlxProperties) {

        var graphControl = document.getElementById(graphControlId);

        if (graphControl && graphControl.aasDxChart) {

            for (var k in dhtmlxProperties) {

                Aspectize.ProtectedCall(graphControl.aasDxChart, graphControl.aasDxChart.define, k, dhtmlxProperties[k]);
            }

            Aspectize.ProtectedCall(graphControl.aasDxChart, graphControl.aasDxChart.refresh);
        }
    },

    SetChartData: function (graphControlId, data) {

        var graphControl = document.getElementById(graphControlId);

        if (graphControl && graphControl.aasDxChart) {

            Aspectize.ProtectedCall(graphControl.aasDxChart, graphControl.aasDxChart.parse, data, 'json');
        }
    }

};

Global.DhtmlxChartBuilder = {

    aasService: 'DhtmlxChartBuilder',
    aasPublished: false,

    Build: function (controlInfo) {

        var ChartTypes = { Area: { View: 'area' }, Bar: { View: 'bar' }, StackedBar: { View: 'stackedBar' }, Line: { View: 'line' }, Spline: { View: 'spline' }, Pie: { View: 'pie' }, Radar: { View: 'radar' } };

        controlInfo.CreateInstance = function (ownerWindow, id) {

            var chart = Aspectize.createElement('div', ownerWindow);

            chart.aasSubControls = {};

            return chart;
        };

        controlInfo.InitGrid = function (control) {

            //control.style.height = '350px';
            control.style.height = '100%';
            control.style.width = '100%';
            control.style.minHeight = '100%';
            control.style.minWidth = '100%';

            if (control.parentNode.width) {
                control.style.width = control.parentNode.width;
            }

            control.parentNode.style.overflowX = "auto";
            control.parentNode.style.overflowY = "hidden";

            var chartType = null;

            switch (control.aasControlInfo.name) {

                case 'DhtmlxAreaChart': chartType = ChartTypes.Area; break;
                case 'DhtmlxBarChart': chartType = ChartTypes.Bar; break;
                case 'DhtmlxStackedBarChart': chartType = ChartTypes.StackedBar; break;
                case 'DhtmlxLineChart': chartType = ChartTypes.Line; break;
                case 'DhtmlxSplineChart': chartType = ChartTypes.Spline; break;
                case 'DhtmlxPieChart': chartType = ChartTypes.Pie; break;
                case 'DhtmlxRadarChart': chartType = ChartTypes.Radar; break;
                default: chartType = ChartTypes.Line; break;
            }

            var xAxis = null;
            var yAxis = null;
            var otherYAxis = [];

            var columnInfos = controlInfo.columnInfos;

            for (var n = 0; n < columnInfos.length; n++) {

                var columnInfo = columnInfos[n];

                var typeNameParts = columnInfo.typeName.split('.');

                var typeName = typeNameParts[typeNameParts.length - 1];

                switch (typeName) {

                    case 'DhtmlxChartXAxis': xAxis = columnInfo.name; break;
                    case 'DhtmlxChartYAxis':
                        {
                            if (yAxis === null) {

                                yAxis = columnInfo.name;
                            }
                            else {

                                if (control.aasControlInfo.name !== 'DhtmlxPieChart') {

                                    otherYAxis.push(columnInfo.name);
                                }
                            }

                            break;
                        }
                    default: break;
                }
            }

            if (!window.dhtmlXChart) throw new Error('Missing DHTMLX integration scripts in the app.ashx file ?');

            var chart = new dhtmlXChart({
                view: chartType.View,
                container: control.id,
                value: '#' + yAxis + '#',
                lines: false,
                label: '#' + yAxis + 'LabelValue#',
                xAxis: {
                    title: '',
                    template: '#' + xAxis + 'Label#',
                    lines: false
                }

                //                pieInnerText: function(obj) {
                //                    var sum = chart.sum('#' + yAxis + '#');
                //                    return Math.round(obj[yAxis] / sum * 100) + "%";
                //                }
            });

            for (var i = 0; i < otherYAxis.length; i++) {

                chart.addSeries({
                    value: '#' + otherYAxis[i] + '#',
                    label: '#' + otherYAxis[i] + 'LabelValue#',
                    color: "#2FA783",
                    item: { radius: 1, borderColor: '#2FA783', color: '#2FA783', borderWidth: 1 },
                    line: { color: "#2FA783", width: 3 }
                });
            }

            control.aasDxChart = chart;
            control.aasDxChartXAxis = xAxis;
            control.aasDxChartYAxis = yAxis;

            control.aasChartProperties = { XAxis: { Title: '', Label: '', PointWidth: 50 }, YAxis: {} };

            control.aasChartProperties.YAxis[yAxis] = { Title: '', LabelValue: '', ShowLine: false, Start: null, End: null, Step: null, LineColor: '#D4D4D4', LineWidth: 3, ItemColor: '#000000', ItemBorderColor: '#000000', ItemRadius: 4, ItemBorderWidth: 2 };

            for (var i = 0; i < otherYAxis.length; i++) {
                control.aasChartProperties.YAxis[otherYAxis[i]] = { Title: '', LabelValue: '', ShowLine: false, Start: null, End: null, Step: null, LineColor: '#D4D4D4', LineWidth: 3, ItemColor: '#000000', ItemBorderColor: '#000000', ItemRadius: 4, ItemBorderWidth: 2 };
            }

            //control.style.width = '2000px';

        };

        controlInfo.InitCellControl = function (control, cellControl, rowId, rowIndex, columnIndex, columnName) {

            cellControl.aasDxChart = control.aasDxChart;
            cellControl.aasDxChartXAxis = control.aasDxChartXAxis;
            cellControl.aasDxChartYAxis = control.aasDxChartYAxis;
            cellControl.aasChartProperties = control.aasChartProperties;
            cellControl.aasColumnName = columnName;

        };

        controlInfo.RowCreated = function (control, rowId, cellControls) {

            var chartItem = { id: rowId };

            for (var n = 0; n < cellControls.length; n++) {

                var cellControl = cellControls[n];

                chartItem[cellControl.aasColumnName] = cellControl.aasControlInfo.PropertyBag.Value.toString();

                if (cellControl.aasControlInfo.name == 'DhtmlxChartXAxis') {
                    if (cellControl.aasControlInfo.PropertyBag.Label != null) {
                        chartItem[cellControl.aasColumnName + 'Label'] = cellControl.aasControlInfo.PropertyBag.Label;
                    }
                    else {
                        chartItem[cellControl.aasColumnName + 'Label'] = cellControl.aasControlInfo.PropertyBag.Value.toString();
                    }
                }
                else if (cellControl.aasControlInfo.name == 'DhtmlxChartYAxis') {
                    if (cellControl.aasControlInfo.PropertyBag.LabelValue != null) {
                        chartItem[cellControl.aasColumnName + 'LabelValue'] = cellControl.aasControlInfo.PropertyBag.LabelValue;
                    }
                    else {
                        chartItem[cellControl.aasColumnName + 'LabelValue'] = cellControl.aasControlInfo.PropertyBag.Value.toString();
                    }
                }

                cellControl.aasChartItem = chartItem;
            }

            //control.aasDxChart.add(chartItem);
        };

        controlInfo.GridRendered = function (control, rowControls) {

            var data = []; var min = null; var max = null; var field = control.aasDxChartYAxis;

            for (var n = 0; n < rowControls.length; n++) {

                var rowControl = rowControls[n];

                if (rowControl.CellControls.length > 0) {

                    var chartItem = rowControl.CellControls[0].aasChartItem;

                    data.push(chartItem);

                    var fv = Number(chartItem[field]);

                    if (min == null) min = fv;
                    if (fv < min) min = fv;

                    if (max == null) max = fv;
                    if (fv > max) max = fv;
                }
            }

            var start = control.aasChartProperties.YAxis[control.aasDxChartYAxis].Start;
            if (!start) start = getGraphBegin(min, max);

            var step = control.aasChartProperties.YAxis[control.aasDxChartYAxis].Step;
            if (!step) step = getGraphStep(min, max);

            var end = control.aasChartProperties.YAxis[control.aasDxChartYAxis].End;
            if (!end) end = getGraphEnd(min, max);

            control.aasDxChart.define('yAxis', {
                start: start,
                end: end,
                step: step
            });

            var rowCount = rowControls.length; // control.aasDxChart.data.dataCount();

            control.aasRowCount = rowCount;

            var currentWidth = control.clientWidth;

            var pointWidth = control.aasChartProperties.XAxis.PointWidth;

            if (currentWidth < rowCount * pointWidth) {
                control.style.width = rowCount * pointWidth + 'px';
            }
            else {
                control.style.width = control.parentNode.clientWidth + 'px';
            }

            Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.clearAll);
            Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.refresh);

            if (rowControls.length > 0) {

                Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.parse, data, 'json');
                Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.refresh);
                Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.resize);
            }
        };

        controlInfo.OnCurrentIndexChanged = function (control, currentIndex) {

        };
    }
};

Global.DhtmlxChartAxisBuilder = {

    aasService: 'DhtmlxChartAxisBuilder',
    aasPublished: false,

    Build: function (controlInfo) {

        function translateToObjectProperty(p) {

            var obj = null;
            var property = null;

            if (p.indexOf('Line') === 0) obj = 'line';
            else if (p.indexOf('Item') === 0) obj = 'item';
            else obj = 'yAxis';

            switch (obj) {

                case 'line':
                case 'item': {

                    var stripedObj = p.substring(4);
                    property = stripedObj[0].toLowerCase() + stripedObj.substring(1);
                }

                case 'yAxis': {

                    property = (p === 'ShowLine') ? 'lines' : p.toLowerCase();
                }
            }

            return { Obj: obj, Property: property };
        }

        controlInfo.CreateInstance = function (ownerWindow, id) {

            var control = Aspectize.createElement('div', ownerWindow);

            controlInfo.aasLastSetValue = null;

            var needsFlush = false;
            function deferredFlush() {

                function flush() {

                    needsFlush = false;
                    Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.refresh);
                }

                if (!needsFlush) { needsFlush = true; setTimeout(flush, 0); }
            };

            controlInfo.ChangePropertyValue = function (property, newValue) {

                if (property === 'LabelValue') return;

                controlInfo.PropertyBag[property] = newValue;

                if (property === 'Value') {

                    if (controlInfo.aasLastSetValue !== newValue) {

                        controlInfo.aasLastSetValue = newValue;

                        if (control.aasChartItem) {

                            control.aasChartItem[control.aasColumnName] = newValue;

                            var index = control.aasDxChart.indexById(control.aasChartItem.id);

                            if (index !== -1) {

                                control.aasDxChart.remove(control.aasChartItem.id);
                                control.aasDxChart.add(control.aasChartItem, index);

                                deferredFlush();
                            }
                            else {

                                // Old point : should never happen !!!
                            }
                        }
                    }

                } else {

                    if (newValue === null) return;

                    if (controlInfo.name == 'DhtmlxChartXAxis') {

                        if (control.aasChartProperties.XAxis[property] !== newValue) {

                            control.aasChartProperties.XAxis[property] = newValue;

                            //                            if (property === 'Label') {
                            //                                control.aasDxChart.define('xAxis', {
                            //                                    template: function (obj) { return '' }
                            //                                });
                            //                            }

                            control.aasDxChart.define('xAxis', {
                                title: control.aasChartProperties.XAxis.Title,
                                template: '#' + control.aasDxChartXAxis + 'Label#'
                            });

                            deferredFlush();
                        }

                    } else if (controlInfo.name == 'DhtmlxChartYAxis') {

                        if (control.aasChartProperties.YAxis[control.aasColumnName][property] !== newValue) {

                            control.aasChartProperties.YAxis[control.aasColumnName][property] = newValue;

                            var t = translateToObjectProperty(property);

                            var o = {}; o[t.Property] = newValue;

                            control.aasDxChart.define(t.Obj, o);

                            //control.aasDxChart.define('yAxis', {
                            //    title: control.aasChartProperties.YAxis[control.aasColumnName].Title,
                            //    start: control.aasChartProperties.YAxis[control.aasColumnName].Start,
                            //    end: control.aasChartProperties.YAxis[control.aasColumnName].End,
                            //    step: control.aasChartProperties.YAxis[control.aasColumnName].Step,
                            //    lines: control.aasChartProperties.YAxis[control.aasColumnName].ShowLine
                            //});

                            //control.aasDxChart.define('item', {
                            //    borderColor: control.aasChartProperties.YAxis[control.aasColumnName].ItemBorderColor,
                            //    color: control.aasChartProperties.YAxis[control.aasColumnName].ItemColor,
                            //    borderWidth: control.aasChartProperties.YAxis[control.aasColumnName].ItemBorderWidth,
                            //    radius: control.aasChartProperties.YAxis[control.aasColumnName].ItemRadius
                            //});

                            //control.aasDxChart.define('line', {
                            //    color: control.aasChartProperties.YAxis[control.aasColumnName].LineColor,
                            //    width: control.aasChartProperties.YAxis[control.aasColumnName].LineWidth
                            //});

                            //                            if (!control.aasChartProperties.YAxis.LabelValue) {
                            //                                control.aasDxChart.define('label', '');
                            //                            }

                            deferredFlush();
                        }
                    }
                }
            };

            return control;
        };
    }
};

<commit_msg>Dhtmlx<commit_after>function getGraphStep(minValue, maxValue, step) {

    if (step) return step;

    var copy = maxValue;

    if (minValue < 0) {
        copy = maxValue - minValue;
    }

    var pow = 1

    while (copy > 10) {

        copy = copy / 10;
        pow++;
    }

    return Math.pow(10, pow - 1);
}

function getGraphEnd(minValue, maxValue, s) {
    var step = getGraphStep(minValue, maxValue, s);

    var max = 0;

    while (max < maxValue) {

        max += step;
    }

    return max;
}

function getGraphBegin(minValue, maxValue, s) {
    if (minValue > 0) return 0;

    var step = getGraphStep(minValue, maxValue, s);
    var min = 0;

    while (min > minValue) {

        min -= step;
    }

    return min;
}

function getDxChart(graphControl) {

    if (graphControl) {

        if (graphControl.aasDxChart) {

            return graphControl.aasDxChart;

        } else if (graphControl.aasChartProperties) {

            return graphControl.aasChartProperties.dxChart;
        }
    }

    return null;
}
Global.DhtmlxChartService = {

    aasService: 'DhtmlxChartService',
    aasPublished: true,

    GetGraphEnd: function (minValue, maxValue) {
        return getGraphEnd(minValue, maxValue);
    },

    GetGraphStep: function (minValue, maxValue) {
        return getGraphStep(minValue, maxValue);
    },

    GetGraphBegin: function (minValue, maxValue) {
        return getGraphBegin(minValue, maxValue);
    },

    RefreshGraph: function (graphControlId) {

        var graphControl = document.getElementById(graphControlId);

        if (graphControl.aasChartProperties) {

            gc.aasChartProperties.MustRebuildChart = true;
            gc.aasChartProperties.RefreshData();

        } else {

            var dxChart = getDxChart(graphControl);

            if (graphControl && dxChart) {

                var rowCount = graphControl.aasRowCount;

                var currentWidth = graphControl.parentNode.clientWidth;

                graphControl.style.width = graphControl.parentNode.clientWidth + 'px';

                var xAxis = graphControl.aasChartProperties.xAxis;

                var pointWidth = graphControl.aasChartProperties.AllAxis[xAxis].PointWidth;

                if (currentWidth <= rowCount * pointWidth) {
                    graphControl.style.width = rowCount * pointWidth + 'px';
                }
                else {
                    graphControl.style.width = graphControl.parentNode.clientWidth + 'px';
                }

                Aspectize.ProtectedCall(dxChart, dxChart.refresh);
                Aspectize.ProtectedCall(dxChart, dxChart.resize);
            }
        }
    },

    SetChartProperties: function (graphControlId, dhtmlxProperties) {

        var graphControl = document.getElementById(graphControlId);

        if (graphControl && graphControl.aasDxChart) {

            for (var k in dhtmlxProperties) {

                Aspectize.ProtectedCall(graphControl.aasDxChart, graphControl.aasDxChart.define, k, dhtmlxProperties[k]);
            }

            Aspectize.ProtectedCall(graphControl.aasDxChart, graphControl.aasDxChart.refresh);
        }
    },

    SetChartData: function (graphControlId, data) {

        var graphControl = document.getElementById(graphControlId);

        if (graphControl && graphControl.aasDxChart) {

            Aspectize.ProtectedCall(graphControl.aasDxChart, graphControl.aasDxChart.parse, data, 'json');
        }
    }

};

Global.DhtmlxChartBuilder = {

    aasService: 'DhtmlxChartBuilder',
    aasPublished: false,

    Build: function (controlInfo) {

        var ChartTypes = { Area: { View: 'area' }, Bar: { View: 'bar' }, StackedBar: { View: 'stackedBar' }, Line: { View: 'line' }, Spline: { View: 'spline' }, Pie: { View: 'pie' }, Radar: { View: 'radar' } };

        controlInfo.CreateInstance = function (ownerWindow, id) {

            var chart = Aspectize.createElement('div', ownerWindow);

            chart.aasSubControls = {};

            return chart;
        };

        controlInfo.InitGrid = function (control) {

            //control.style.height = '350px';
            control.style.height = '100%';
            control.style.width = '100%';
            control.style.minHeight = '100%';
            control.style.minWidth = '100%';

            if (control.parentNode.width) {
                control.style.width = control.parentNode.width;
            }

            control.parentNode.style.overflowX = "auto";
            control.parentNode.style.overflowY = "hidden";

            var chartType = null;

            switch (control.aasControlInfo.name) {

                case 'DhtmlxAreaChart': chartType = ChartTypes.Area; break;
                case 'DhtmlxBarChart': chartType = ChartTypes.Bar; break;
                case 'DhtmlxStackedBarChart': chartType = ChartTypes.StackedBar; break;
                case 'DhtmlxLineChart': chartType = ChartTypes.Line; break;
                case 'DhtmlxSplineChart': chartType = ChartTypes.Spline; break;
                case 'DhtmlxPieChart': chartType = ChartTypes.Pie; break;
                case 'DhtmlxRadarChart': chartType = ChartTypes.Radar; break;
                default: chartType = ChartTypes.Line; break;
            }

            var xAxis = null;
            var yAxis = null;
            var otherYAxis = [];

            var columnInfos = controlInfo.columnInfos;

            for (var n = 0; n < columnInfos.length; n++) {

                var columnInfo = columnInfos[n];

                var typeNameParts = columnInfo.typeName.split('.');

                var typeName = typeNameParts[typeNameParts.length - 1];

                switch (typeName) {

                    case 'DhtmlxChartXAxis': xAxis = columnInfo.name; break;
                    case 'DhtmlxChartYAxis':
                        {
                            if (yAxis === null) {

                                yAxis = columnInfo.name;
                            }
                            else {

                                if (control.aasControlInfo.name !== 'DhtmlxPieChart') {

                                    otherYAxis.push(columnInfo.name);
                                }
                            }

                            break;
                        }
                    default: break;
                }
            }

            if (!window.dhtmlXChart) throw new Error('Missing DHTMLX integration scripts in the app.ashx file ?');

            var chart = new dhtmlXChart({
                view: chartType.View,
                container: control.id,
                value: '#' + yAxis + '#',
                lines: false,
                label: '#' + yAxis + 'LabelValue#',
                xAxis: {
                    title: '',
                    template: '#' + xAxis + 'Label#',
                    lines: false
                }

                //                pieInnerText: function(obj) {
                //                    var sum = chart.sum('#' + yAxis + '#');
                //                    return Math.round(obj[yAxis] / sum * 100) + "%";
                //                }
            });

            for (var i = 0; i < otherYAxis.length; i++) {

                chart.addSeries({
                    value: '#' + otherYAxis[i] + '#',
                    label: '#' + otherYAxis[i] + 'LabelValue#',
                    color: "#2FA783",
                    item: { radius: 1, borderColor: '#2FA783', color: '#2FA783', borderWidth: 1 },
                    line: { color: "#2FA783", width: 3 }
                });
            }

            control.aasDxChart = chart;
            control.aasDxChartXAxis = xAxis;
            control.aasDxChartYAxis = yAxis;

            control.aasChartProperties = { XAxis: { Title: '', Label: '', PointWidth: 50 }, YAxis: {} };

            control.aasChartProperties.YAxis[yAxis] = { Title: '', LabelValue: '', ShowLine: false, Start: null, End: null, Step: null, LineColor: '#D4D4D4', LineWidth: 3, ItemColor: '#000000', ItemBorderColor: '#000000', ItemRadius: 4, ItemBorderWidth: 2 };

            for (var i = 0; i < otherYAxis.length; i++) {
                control.aasChartProperties.YAxis[otherYAxis[i]] = { Title: '', LabelValue: '', ShowLine: false, Start: null, End: null, Step: null, LineColor: '#D4D4D4', LineWidth: 3, ItemColor: '#000000', ItemBorderColor: '#000000', ItemRadius: 4, ItemBorderWidth: 2 };
            }

            //control.style.width = '2000px';

        };

        controlInfo.InitCellControl = function (control, cellControl, rowId, rowIndex, columnIndex, columnName) {

            cellControl.aasDxChart = control.aasDxChart;
            cellControl.aasDxChartXAxis = control.aasDxChartXAxis;
            cellControl.aasDxChartYAxis = control.aasDxChartYAxis;
            cellControl.aasChartProperties = control.aasChartProperties;
            cellControl.aasColumnName = columnName;

        };

        controlInfo.RowCreated = function (control, rowId, cellControls) {

            var chartItem = { id: rowId };

            for (var n = 0; n < cellControls.length; n++) {

                var cellControl = cellControls[n];

                chartItem[cellControl.aasColumnName] = cellControl.aasControlInfo.PropertyBag.Value.toString();

                if (cellControl.aasControlInfo.name == 'DhtmlxChartXAxis') {
                    if (cellControl.aasControlInfo.PropertyBag.Label != null) {
                        chartItem[cellControl.aasColumnName + 'Label'] = cellControl.aasControlInfo.PropertyBag.Label;
                    }
                    else {
                        chartItem[cellControl.aasColumnName + 'Label'] = cellControl.aasControlInfo.PropertyBag.Value.toString();
                    }
                }
                else if (cellControl.aasControlInfo.name == 'DhtmlxChartYAxis') {
                    if (cellControl.aasControlInfo.PropertyBag.LabelValue != null) {
                        chartItem[cellControl.aasColumnName + 'LabelValue'] = cellControl.aasControlInfo.PropertyBag.LabelValue;
                    }
                    else {
                        chartItem[cellControl.aasColumnName + 'LabelValue'] = cellControl.aasControlInfo.PropertyBag.Value.toString();
                    }
                }

                cellControl.aasChartItem = chartItem;
            }

            //control.aasDxChart.add(chartItem);
        };

        controlInfo.GridRendered = function (control, rowControls) {

            var data = []; var min = null; var max = null; var field = control.aasDxChartYAxis;

            for (var n = 0; n < rowControls.length; n++) {

                var rowControl = rowControls[n];

                if (rowControl.CellControls.length > 0) {

                    var chartItem = rowControl.CellControls[0].aasChartItem;

                    data.push(chartItem);

                    var fv = Number(chartItem[field]);

                    if (min == null) min = fv;
                    if (fv < min) min = fv;

                    if (max == null) max = fv;
                    if (fv > max) max = fv;
                }
            }

            var start = control.aasChartProperties.YAxis[control.aasDxChartYAxis].Start;
            if (!start) start = getGraphBegin(min, max);

            var step = control.aasChartProperties.YAxis[control.aasDxChartYAxis].Step;
            if (!step) step = getGraphStep(min, max);

            var end = control.aasChartProperties.YAxis[control.aasDxChartYAxis].End;
            if (!end) end = getGraphEnd(min, max);

            control.aasDxChart.define('yAxis', {
                start: start,
                end: end,
                step: step
            });

            var rowCount = rowControls.length; // control.aasDxChart.data.dataCount();

            control.aasRowCount = rowCount;

            var currentWidth = control.clientWidth;

            var pointWidth = control.aasChartProperties.XAxis.PointWidth;

            if (currentWidth < rowCount * pointWidth) {
                control.style.width = rowCount * pointWidth + 'px';
            }
            else {
                control.style.width = control.parentNode.clientWidth + 'px';
            }

            Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.clearAll);
            Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.refresh);

            if (rowControls.length > 0) {

                Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.parse, data, 'json');
                Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.refresh);
                Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.resize);
            }
        };

        controlInfo.OnCurrentIndexChanged = function (control, currentIndex) {

        };
    }
};

Global.DhtmlxChartAxisBuilder = {

    aasService: 'DhtmlxChartAxisBuilder',
    aasPublished: false,

    Build: function (controlInfo) {

        function translateToObjectProperty(p) {

            var obj = null;
            var property = null;

            if (p.indexOf('Line') === 0) obj = 'line';
            else if (p.indexOf('Item') === 0) obj = 'item';
            else obj = 'yAxis';

            switch (obj) {

                case 'line':
                case 'item': {

                    var stripedObj = p.substring(4);
                    property = stripedObj[0].toLowerCase() + stripedObj.substring(1);
                }

                case 'yAxis': {

                    property = (p === 'ShowLine') ? 'lines' : p.toLowerCase();
                }
            }

            return { Obj: obj, Property: property };
        }

        controlInfo.CreateInstance = function (ownerWindow, id) {

            var control = Aspectize.createElement('div', ownerWindow);

            controlInfo.aasLastSetValue = null;

            var needsFlush = false;
            function deferredFlush() {

                function flush() {

                    needsFlush = false;
                    Aspectize.ProtectedCall(control.aasDxChart, control.aasDxChart.refresh);
                }

                if (!needsFlush) { needsFlush = true; setTimeout(flush, 0); }
            };

            controlInfo.ChangePropertyValue = function (property, newValue) {

                if (property === 'LabelValue') return;

                controlInfo.PropertyBag[property] = newValue;

                if (property === 'Value') {

                    if (controlInfo.aasLastSetValue !== newValue) {

                        controlInfo.aasLastSetValue = newValue;

                        if (control.aasChartItem) {

                            control.aasChartItem[control.aasColumnName] = newValue;

                            var index = control.aasDxChart.indexById(control.aasChartItem.id);

                            if (index !== -1) {

                                control.aasDxChart.remove(control.aasChartItem.id);
                                control.aasDxChart.add(control.aasChartItem, index);

                                deferredFlush();
                            }
                            else {

                                // Old point : should never happen !!!
                            }
                        }
                    }

                } else {

                    if (newValue === null) return;

                    if (controlInfo.name == 'DhtmlxChartXAxis') {

                        if (control.aasChartProperties.XAxis[property] !== newValue) {

                            control.aasChartProperties.XAxis[property] = newValue;

                            //                            if (property === 'Label') {
                            //                                control.aasDxChart.define('xAxis', {
                            //                                    template: function (obj) { return '' }
                            //                                });
                            //                            }

                            control.aasDxChart.define('xAxis', {
                                title: control.aasChartProperties.XAxis.Title,
                                template: '#' + control.aasDxChartXAxis + 'Label#'
                            });

                            deferredFlush();
                        }

                    } else if (controlInfo.name == 'DhtmlxChartYAxis') {

                        if (control.aasChartProperties.YAxis[control.aasColumnName][property] !== newValue) {

                            control.aasChartProperties.YAxis[control.aasColumnName][property] = newValue;

                            var t = translateToObjectProperty(property);

                            var o = {}; o[t.Property] = newValue;

                            control.aasDxChart.define(t.Obj, o);

                            //control.aasDxChart.define('yAxis', {
                            //    title: control.aasChartProperties.YAxis[control.aasColumnName].Title,
                            //    start: control.aasChartProperties.YAxis[control.aasColumnName].Start,
                            //    end: control.aasChartProperties.YAxis[control.aasColumnName].End,
                            //    step: control.aasChartProperties.YAxis[control.aasColumnName].Step,
                            //    lines: control.aasChartProperties.YAxis[control.aasColumnName].ShowLine
                            //});

                            //control.aasDxChart.define('item', {
                            //    borderColor: control.aasChartProperties.YAxis[control.aasColumnName].ItemBorderColor,
                            //    color: control.aasChartProperties.YAxis[control.aasColumnName].ItemColor,
                            //    borderWidth: control.aasChartProperties.YAxis[control.aasColumnName].ItemBorderWidth,
                            //    radius: control.aasChartProperties.YAxis[control.aasColumnName].ItemRadius
                            //});

                            //control.aasDxChart.define('line', {
                            //    color: control.aasChartProperties.YAxis[control.aasColumnName].LineColor,
                            //    width: control.aasChartProperties.YAxis[control.aasColumnName].LineWidth
                            //});

                            //                            if (!control.aasChartProperties.YAxis.LabelValue) {
                            //                                control.aasDxChart.define('label', '');
                            //                            }

                            deferredFlush();
                        }
                    }
                }
            };

            return control;
        };
    }
};

<|endoftext|>


<commit_before>const gulp = require('gulp'),
      eventStream = require('event-stream'),
      gulpLoadPlugins = require('gulp-load-plugins'),
      fs = require('fs'),
      del = require('del'),
      path = require('path'),
      size = require('gulp-size'),
      uri = require('urijs'),
      urljoin = require('url-join'),
      s = require('underscore.string'),
      stringifyObject = require('stringify-object'),
      argv = require('yargs').argv,
      hawtio = require('hawtio-node-backend');

const package = require('./package.json');
const plugins = gulpLoadPlugins({});

var config = {
  main: '.',
  ts: ['plugins/**/*.ts'],
  dist: argv.out || './dist/',
  js: 'hawtio-kubernetes-api.js',
  dts: 'hawtio-kubernetes-api.d.ts',
  sourceMap: argv.sourcemap
};

const tsProject = plugins.typescript.createProject('tsconfig.json');

var normalSizeOptions = {
    showFiles: true
}, gZippedSizeOptions  = {
    showFiles: true,
    gzip: true
};

gulp.task('tsc', function() {
    const tsResult = tsProject.src()
    .pipe(plugins.if(config.sourceMap, plugins.sourcemaps.init()))
    .pipe(tsProject())
    .on('error', plugins.notify.onError({
      onLast : true,
      message: '<%= error.message %>',
      title  : 'Typescript compilation error'
    }));

    return eventStream.merge(
      tsResult.js
        .pipe(plugins.ngAnnotate())
        .pipe(plugins.if(config.sourceMap, plugins.sourcemaps.write()))
        .pipe(gulp.dest('.')),
      tsResult.dts
        .pipe(plugins.rename(config.dts))
        .pipe(gulp.dest(config.dist)));
});

gulp.task('concat', ['tsc'], function() {
  var gZipSize = size(gZippedSizeOptions);
  return gulp.src(['compiled.js'])
    .pipe(plugins.concat(config.js))
    .pipe(size(normalSizeOptions))
    .pipe(gZipSize)
    .pipe(gulp.dest(config.dist));
});

gulp.task('clean', ['concat'], function() {
  return del(['compiled.js']);
});

gulp.task('watch', ['build'], function() {
  plugins.watch(['node_modules/**/*.js', 'index.html', config.dist + '/' + config.js], ['reload']);
  plugins.watch(['node_modules/**/*.d.ts', config.ts], ['tsc', 'template', 'concat', 'clean']);
});

gulp.task('connect', ['watch'], function() {
  // lets disable unauthorised TLS issues with kube REST API
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

  var kubeBase = process.env.KUBERNETES_MASTER || 'https://localhost:8443';
  var kube = uri(urljoin(kubeBase, 'api'));
  var oapi = uri(urljoin(kubeBase, 'oapi'));
  console.log("Connecting to Kubernetes on: " + kube);

  var staticAssets = [{
      path: '/',
      dir: '.'
  }];

  var localProxies = [];
  var defaultProxies = [{
    proto: kube.protocol(),
    port: kube.port(),
    hostname: kube.hostname(),
    path: '/kubernetes/api',
    targetPath: kube.path()
  }, {
    proto: oapi.protocol(),
    port: oapi.port(),
    hostname: oapi.hostname(),
    path: '/kubernetes/oapi',
    targetPath: oapi.path()
  }, {
    proto: kube.protocol(),
    hostname: kube.hostname(),
    port: kube.port(),
    path: '/jolokia',
    targetPath: '/hawtio/jolokia'
  }, {
    proto: kube.protocol(),
    hostname: kube.hostname(),
    port: kube.port(),
    path: '/git',
    targetPath: '/hawtio/git'
  }];

  var staticProxies = localProxies.concat(defaultProxies);

  hawtio.setConfig({
    port: process.env.DEV_PORT || 2772,
    staticProxies: staticProxies,
    staticAssets: staticAssets,
    fallback: 'index.html',
    liveReload: {
      enabled: true
    }
  });
  var debugLoggingOfProxy = process.env.DEBUG_PROXY === "true";
  var useAuthentication = process.env.DISABLE_OAUTH !== "true";

  var googleClientId = process.env.GOOGLE_OAUTH_CLIENT_ID;
  var googleClientSecret = process.env.GOOGLE_OAUTH_CLIENT_SECRET;

  hawtio.use('/osconsole/config.js', function(req, res, next) {
    var config = {
      api: {
        openshift: {
          proto: oapi.protocol(),
          hostPort: oapi.host(),
          prefix: oapi.path()
        },
        k8s: {
          proto: kube.protocol(),
          hostPort: kube.host(),
          prefix: kube.path()
        }
      }
    };
    if (googleClientId && googleClientSecret) {
      config.master_uri = kubeBase;
      config.google = {
         clientId: googleClientId,
         clientSecret: googleClientSecret,
         authenticationURI: "https://accounts.google.com/o/oauth2/auth",
         authorizationURI: "https://accounts.google.com/o/oauth2/auth",
         scope: "profile",
         redirectURI: "http://localhost:9000"
      };

    } else if (useAuthentication) {
      config.master_uri = kubeBase;
      config.openshift = {
        oauth_authorize_uri: urljoin(kubeBase, '/oauth/authorize'),
        oauth_client_id    : 'system:serviceaccount:hawtio:hawtio-online-dev',
        scope              : 'user:info user:check-access role:edit:hawtio',
      };
    }
    var answer = "window.OPENSHIFT_CONFIG = window.HAWTIO_OAUTH_CONFIG = " + stringifyObject(config);
    res.set('Content-Type', 'application/javascript');
    res.send(answer);
  });

  hawtio.use('/', function(req, res, next) {
          var path = req.originalUrl;
          // avoid returning these files, they should get pulled from js
          if (s.startsWith(path, '/plugins/') && s.endsWith(path, 'html')) {
            console.log("returning 404 for: ", path);
            res.statusCode = 404;
            res.end();
          } else {
            if (debugLoggingOfProxy) {
              console.log("allowing: ", path);
            }
            next();
          }
        });
  hawtio.listen(function(server) {
    var host = server.address().address;
    var port = server.address().port;
    console.log("started from gulp file at ", host, ":", port);
  });
});

gulp.task('reload', function() {
  gulp.src('.')
    .pipe(hawtio.reload());
});

gulp.task('version', function() {
  return gulp.src(path.join(config.dist, config.js))
    .pipe(plugins.replace('PACKAGE_VERSION_PLACEHOLDER', package.version))
    .pipe(gulp.dest(config.dist));
});

gulp.task('build', ['tsc', 'concat', 'clean']);

gulp.task('default', ['connect']);
<commit_msg>build: Simplify Kubernetes master API proxying<commit_after>const gulp = require('gulp'),
      eventStream = require('event-stream'),
      gulpLoadPlugins = require('gulp-load-plugins'),
      del = require('del'),
      path = require('path'),
      size = require('gulp-size'),
      uri = require('urijs'),
      urljoin = require('url-join'),
      s = require('underscore.string'),
      stringifyObject = require('stringify-object'),
      argv = require('yargs').argv,
      hawtio = require('hawtio-node-backend');

const package = require('./package.json');
const plugins = gulpLoadPlugins({});

var config = {
  main: '.',
  ts: ['plugins/**/*.ts'],
  dist: argv.out || './dist/',
  js: 'hawtio-kubernetes-api.js',
  dts: 'hawtio-kubernetes-api.d.ts',
  sourceMap: argv.sourcemap
};

const tsProject = plugins.typescript.createProject('tsconfig.json');

var normalSizeOptions = {
    showFiles: true
}, gZippedSizeOptions  = {
    showFiles: true,
    gzip: true
};

gulp.task('tsc', function() {
    const tsResult = tsProject.src()
    .pipe(plugins.if(config.sourceMap, plugins.sourcemaps.init()))
    .pipe(tsProject())
    .on('error', plugins.notify.onError({
      onLast : true,
      message: '<%= error.message %>',
      title  : 'Typescript compilation error'
    }));

    return eventStream.merge(
      tsResult.js
        .pipe(plugins.ngAnnotate())
        .pipe(plugins.if(config.sourceMap, plugins.sourcemaps.write()))
        .pipe(gulp.dest('.')),
      tsResult.dts
        .pipe(plugins.rename(config.dts))
        .pipe(gulp.dest(config.dist)));
});

gulp.task('concat', ['tsc'], function() {
  var gZipSize = size(gZippedSizeOptions);
  return gulp.src(['compiled.js'])
    .pipe(plugins.concat(config.js))
    .pipe(size(normalSizeOptions))
    .pipe(gZipSize)
    .pipe(gulp.dest(config.dist));
});

gulp.task('clean', ['concat'], function() {
  return del(['compiled.js']);
});

gulp.task('watch', ['build'], function() {
  plugins.watch(['node_modules/**/*.js', 'index.html', config.dist + '/' + config.js], ['reload']);
  plugins.watch(['node_modules/**/*.d.ts', config.ts], ['tsc', 'template', 'concat', 'clean']);
});

gulp.task('connect', ['watch'], function() {
  // lets disable unauthorised TLS issues with kube REST API
  process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

  const kubeBase = process.env.KUBERNETES_MASTER || 'https://localhost:8443';
  const kube = uri(kubeBase);
  console.log("Connecting to Kubernetes on: " + kube);

  var staticAssets = [{
      path: '/',
      dir: '.'
  }];

  var localProxies = [];
  var defaultProxies = [{
    proto: kube.protocol(),
    port: kube.port(),
    hostname: kube.hostname(),
    path: '/kubernetes',
    targetPath: '/',
  }, {
    proto: kube.protocol(),
    hostname: kube.hostname(),
    port: kube.port(),
    path: '/jolokia',
    targetPath: '/hawtio/jolokia'
  }, {
    proto: kube.protocol(),
    hostname: kube.hostname(),
    port: kube.port(),
    path: '/git',
    targetPath: '/hawtio/git'
  }];

  var staticProxies = localProxies.concat(defaultProxies);

  hawtio.setConfig({
    port: process.env.DEV_PORT || 2772,
    staticProxies: staticProxies,
    staticAssets: staticAssets,
    fallback: 'index.html',
    liveReload: {
      enabled: true,
    }
  });
  var debugLoggingOfProxy = process.env.DEBUG_PROXY === "true";
  var useAuthentication = process.env.DISABLE_OAUTH !== "true";

  var googleClientId = process.env.GOOGLE_OAUTH_CLIENT_ID;
  var googleClientSecret = process.env.GOOGLE_OAUTH_CLIENT_SECRET;

  hawtio.use('/osconsole/config.js', function(req, res, next) {
    var config = {
      api: {
        openshift: {
          proto: kube.protocol(),
          hostPort: kube.host(),
        },
        k8s: {
          proto: kube.protocol(),
          hostPort: kube.host(),
        }
      }
    };
    if (googleClientId && googleClientSecret) {
      config.master_uri = kubeBase;
      config.google = {
         clientId: googleClientId,
         clientSecret: googleClientSecret,
         authenticationURI: "https://accounts.google.com/o/oauth2/auth",
         authorizationURI: "https://accounts.google.com/o/oauth2/auth",
         scope: "profile",
         redirectURI: "http://localhost:9000"
      };

    } else if (useAuthentication) {
      config.master_uri = kubeBase;
      config.openshift = {
        oauth_authorize_uri: urljoin(kubeBase, '/oauth/authorize'),
        oauth_client_id    : 'system:serviceaccount:hawtio:hawtio-online-dev',
        scope              : 'user:info user:check-access role:edit:hawtio',
      };
    }
    var answer = "window.OPENSHIFT_CONFIG = window.HAWTIO_OAUTH_CONFIG = " + stringifyObject(config);
    res.set('Content-Type', 'application/javascript');
    res.send(answer);
  });

  hawtio.use('/', function(req, res, next) {
          var path = req.originalUrl;
          // avoid returning these files, they should get pulled from js
          if (s.startsWith(path, '/plugins/') && s.endsWith(path, 'html')) {
            console.log("returning 404 for: ", path);
            res.statusCode = 404;
            res.end();
          } else {
            if (debugLoggingOfProxy) {
              console.log("allowing: ", path);
            }
            next();
          }
        });
  hawtio.listen(function(server) {
    var host = server.address().address;
    var port = server.address().port;
    console.log("started from gulp file at ", host, ":", port);
  });
});

gulp.task('reload', function() {
  gulp.src('.')
    .pipe(hawtio.reload());
});

gulp.task('version', function() {
  return gulp.src(path.join(config.dist, config.js))
    .pipe(plugins.replace('PACKAGE_VERSION_PLACEHOLDER', package.version))
    .pipe(gulp.dest(config.dist));
});

gulp.task('build', ['tsc', 'concat', 'clean']);

gulp.task('default', ['connect']);
<|endoftext|>


<commit_before>/**
* correlation coefficients plotting using d3
* Isaak Y Tecle <iyt2@cornell.edu>
*
*/

jQuery(document).ready( function () {
    var page = document.URL;

    if (page.match(/solgs\/traits\/all\//) != null ||
        page.match(/solgs\/models\/combined\/trials\//) != null) {
        listGenCorPopulations();
    } else {
        phenotypicCorrelation();
    }
});

jQuery("#run_genetic_correlation").live("click", function() {
    var popId   = jQuery("#corre_selected_population_id").val();
    var popType = jQuery("#corre_selected_population_type").val();

    jQuery("#correlation_canvas").empty();

    jQuery("#correlation_message")
        .css({"padding-left": '0px'})
        .html("Running genetic correlation analysis...");

    formatGenCorInputData(popId, popType);

});

function listGenCorPopulations ()  {
    var modelData = getTrainingPopulationData();

    var trainingPopIdName = JSON.stringify(modelData);

    var  popsList =  '
'
        + '
 Choose a population
'
        + '
'
        + '
'
        + '
'
        + '' + modelData.name + '' + trainingPopIdName + ''
        + '
';

    popsList += '

';

    jQuery("#corre_select_a_population_div").empty().append(popsList).show();

    var dbSelPopsList;
    if( modelData.id.match(/uploaded/) == null) {
        dbSelPopsList = addSelectionPopulations();
    }

    if (dbSelPopsList) {
            jQuery("#corre_select_a_population_div ul").append(dbSelPopsList);
    }

    var userUploadedSelExists = jQuery("#uploaded_selection_pops_table").doesExist();
    if( userUploadedSelExists == true) {

        var userSelPops = listUploadedSelPopulations();
        if (userSelPops) {

            jQuery("#corre_select_a_population_div ul").append(userSelPops);
        }
    }

   jQuery(".corre_dropdown dt a").click(function() {
            jQuery(".corre_dropdown dd ul").toggle();
        });

    jQuery(".corre_dropdown dd ul li a").click(function() {

        var text = jQuery(this).html();

        jQuery(".corre_dropdown dt a span").html(text);
        jQuery(".corre_dropdown dd ul").hide();

        var idPopName = jQuery("#corre_selected_population").find("dt a span.value").html();
        idPopName     = JSON.parse(idPopName);
        modelId = jQuery("#model_id").val();

        selectedPopId   = idPopName.id;
        selectedPopName = idPopName.name;
        selectedPopType = idPopName.pop_type;

        jQuery("#corre_selected_population_name").val(selectedPopName);
        jQuery("#corre_selected_population_id").val(selectedPopId);
        jQuery("#corre_selected_population_type").val(selectedPopType);

    });

    jQuery(".corre_dropdown").bind('click', function(e) {
        var clicked = jQuery(e.target);

        if (! clicked.parents().hasClass("corre_dropdown"))
            jQuery(".corre_dropdown dd ul").hide();

        e.preventDefault();

    });
}

function formatGenCorInputData (popId, type) {
    var modelDetail = getPopulationDetails();

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'model_id': modelDetail.population_id, 'corr_population_id': popId, 'type' : type},
        url: '/correlation/genetic/data/',
        success: function(response) {
                if(response.status == 'success') {
                    gebvsFile = response.gebvs_file;

                    var args = {
                        'model_id': modelDetail.population_id,
                        'corr_population_id': popId,
                        'type': type,
                        'gebvs_file': response.gebvs_file
                    };

                    runGenCorrelationAnalysis(args);
                } else {
                    jQuery("#correlation_message")
                        .css({"padding-left": '0px'})
                        .html("This population has no additive genetic data.");
                }
            },
            error: function(response) {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("Error occured preparing the additive genetic data for correlation analysis.");
            }
    });
}

function getPopulationDetails () {

    var populationId = jQuery("#population_id").val();
    var populationName = jQuery("#population_name").val();

    if(populationId == 'undefined' ) {
        populationId = jQuery("#model_id").val();
        populationName = jQuery("#model_name").val();
    }

    return {'population_id' : populationId,
            'population_name' : populationName
            };

}

function phenotypicCorrelation () {

    var population = getPopulationDetails();

    jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            data: {'population_id': population.population_id },
            url: '/correlation/phenotype/data/',
            success: function(response) {
                if(response.status == 'success') {
                    runPhenoCorrelationAnalysis();
                } else {
                    jQuery("#correlation_message")
                        .css({"padding-left": '0px'})
                        .html("This population has no phenotype data.");
                }
            },
            error: function(response) {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("Error occured preparing the phenotype data for correlation analysis.");
            }
    });

}

function runPhenoCorrelationAnalysis () {
    var population = getPopulationDetails();

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'population_id': population.population_id },
        url: '/phenotypic/correlation/analysis/output',
        success: function(response) {
            if (response.status == 'success') {
                plotCorrelation(response.data);
                jQuery("#correlation_message").empty();
            } else {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("There is no correlation output for this dataset.");
            }
        },
        error: function(response) {
            jQuery("#correlation_message")
                .css({"padding-left": '0px'})
                .html("Error occured running the correlation analysis.");
        }
    });

}

function runGenCorrelationAnalysis (args) {

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: args,
        url: '/genetic/correlation/analysis/output',
        success: function(response) {
            if (response.status == 'success') {

                plotCorrelation(response.data);
                jQuery("#correlation_message").empty();
            } else {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("There is no genetic correlation output for this dataset.");
            }
        },
        error: function(response) {
            jQuery("#correlation_message")
                .css({"padding-left": '0px'})
                .html("Error occured running the genetic correlation analysis.");
        }
    });

}

function plotCorrelation (data) {

    data = data.replace(/\s/g, '');
    data = data.replace(/\\/g, '');
    data = data.replace(/^\"/, '');
    data = data.replace(/\"$/, '');
    data = data.replace(/\"NA\"/g, 100);

    data = JSON.parse(data);

    var height = 400;
    var width  = 400;

    var nTraits = data.traits.length;

    if (nTraits < 8) {
        height = height * 0.5;
        width  = width  * 0.5;
    }

    var pad    = {left:70, top:20, right:100, bottom: 70};
    var totalH = height + pad.top + pad.bottom;
    var totalW = width + pad.left + pad.right;

    var corXscale = d3.scale.ordinal().domain(d3.range(nTraits)).rangeBands([0, width]);
    var corYscale = d3.scale.ordinal().domain(d3.range(nTraits)).rangeBands([height, 0]);
    var corZscale = d3.scale.linear().domain([-1, 0, 1]).range(["#A52A2A","white", "#0000A0"]);

    var xAxisScale = d3.scale.ordinal()
        .domain(data.traits)
        .rangeBands([0, width]);

    var yAxisScale = d3.scale.ordinal()
        .domain(data.traits)
        .rangeRoundBands([height, 0]);

    var svg = d3.select("#correlation_canvas")
        .append("svg")
        .attr("height", totalH)
        .attr("width", totalW);

    var xAxis = d3.svg.axis()
        .scale(xAxisScale)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(yAxisScale)
        .orient("left");

    var corrplot = svg.append("g")
        .attr("id", "correlation_plot")
        .attr("transform", "translate(" + pad.left + "," + pad.top + ")");

    corrplot.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height +")")
        .call(xAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", 10)
        .attr("dy", ".1em")
        .attr("transform", "rotate(90)")
        .attr("fill", "purple")
        .style({"text-anchor":"start", "fill": "purple"});

    corrplot.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate(0,0)")
        .call(yAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", -10)
        .attr("dy", ".1em")
        .attr("fill", "purple")
        .style("fill", "purple");

    var corr = [];
    var coefs = [];
    for (var i=0; i<data.coefficients.length; i++) {
        for  (var j=0;  j<data.coefficients[i].length; j++) {
            corr.push({"row":i, "col":j, "value": data.coefficients[i][j]});

            if(data.coefficients[i][j] != 100) {
                coefs.push(data.coefficients[i][j]);
            }
        }
    }

    var cell = corrplot.selectAll("rect")
        .data(corr)
        .enter().append("rect")
        .attr("class", "cell")
        .attr("x", function (d) { return corXscale(d.col)})
        .attr("y", function (d) { return corYscale(d.row)})
        .attr("width", corXscale.rangeBand())
        .attr("height", corYscale.rangeBand())
        .attr("fill", function (d) {
                if (d.value === 100) {return "white";}
                else {return corZscale(d.value)}
            })
        .attr("stroke", "white")
        .attr("stroke-width", 1)
        .on("mouseover", function (d) {
                if(d.value != 100) {
                    d3.select(this)
                        .attr("stroke", "green")
                    corrplot.append("text")
                        .attr("id", "corrtext")
                        .text("[" + data.traits[d.row]
                              + " vs. " + data.traits[d.col]
                              + ": " + d3.format(".2f")(d.value)
                              + "]")
                        .style("fill", "purple")
                        .attr("x", totalW * 0.5)
                        .attr("y", totalH * 0.5)
                        .attr("font-weight", "bold")
                        .attr("dominant-baseline", "middle")
                        .attr("text-anchor", "middle")
                }
        })
        .on("mouseout", function() {
                d3.selectAll("text.corrlabel").remove()
                d3.selectAll("text#corrtext").remove()
                d3.select(this).attr("stroke","white")
            });

    corrplot.append("rect")
        .attr("height", height)
        .attr("width", width)
        .attr("fill", "none")
        .attr("stroke", "purple")
        .attr("stroke-width", 1)
        .attr("pointer-events", "none");

    var legendValues = [];
    if (nTraits === 2) {
        if (d3.min(coefs) > 0 && d3.max(coefs) > 0 ) {
            legendValues = [[0, d3.max(coefs)], [1, 0]];
        } else if (d3.min(coefs) < 0 && d3.max(coefs) < 0 )  {
           legendValues = [[0, d3.min(coefs)], [1, 0]];
        } else {
           legendValues = [[0, d3.min(coefs)], [1, d3.max(coefs)]];
        }
    } else {
        legendValues = [[0, d3.min(coefs)], [1, 0], [2, d3.max(coefs)]];
    }

    var legend = corrplot.append("g")
        .attr("class", "cell")
        .attr("transform", "translate(" + (width + 10) + "," +  (height * 0.25) + ")")
        .attr("height", 100)
        .attr("width", 100);

    var recLH = 20;
    var recLW = 20;

    legend = legend.selectAll("rect")
        .data(legendValues)
        .enter()
        .append("rect")
        .attr("x", function (d) { return 1;})
        .attr("y",  function (d) {return 1 + (d[0] * recLH) + (d[0] * 5); })
        .attr("width", recLH)
        .attr("height", recLW)
        .style("stroke", "black")
        .attr("fill", function (d) {
            if (d === 100) {return "white"}
            else {return corZscale(d[1])}
        });

    var legendTxt = corrplot.append("g")
        .attr("transform", "translate(" + (width + 40) + "," + ((height * 0.25) + (0.5 * recLW)) + ")")
        .attr("id", "legendtext");

    legendTxt.selectAll("text")
        .data(legendValues)
        .enter()
        .append("text")
        .attr("fill", "green")
        .style("fill", "green")
        .attr("x", 1)
        .attr("y", function (d) { return 1 + (d[0] * recLH) + (d[0] * 5); })
        .text(function(d) {
            if (d[1] > 0) { return "Positive"; }
            else if (d[1] < 0) { return "Negative"; }
            else if (d[1] === 0) { return "Neutral"; }
        })
        .attr("dominant-baseline", "middle")
        .attr("text-anchor", "start");

}

<commit_msg>color harmony..<commit_after>/**
* correlation coefficients plotting using d3
* Isaak Y Tecle <iyt2@cornell.edu>
*
*/

jQuery(document).ready( function () {
    var page = document.URL;

    if (page.match(/solgs\/traits\/all\//) != null ||
        page.match(/solgs\/models\/combined\/trials\//) != null) {
        listGenCorPopulations();
    } else {
        phenotypicCorrelation();
    }
});

jQuery("#run_genetic_correlation").live("click", function() {
    var popId   = jQuery("#corre_selected_population_id").val();
    var popType = jQuery("#corre_selected_population_type").val();

    jQuery("#correlation_canvas").empty();

    jQuery("#correlation_message")
        .css({"padding-left": '0px'})
        .html("Running genetic correlation analysis...");

    formatGenCorInputData(popId, popType);

});

function listGenCorPopulations ()  {
    var modelData = getTrainingPopulationData();

    var trainingPopIdName = JSON.stringify(modelData);

    var  popsList =  '
'
        + '
 Choose a population
'
        + '
'
        + '
'
        + '
'
        + '' + modelData.name + '' + trainingPopIdName + ''
        + '
';

    popsList += '

';

    jQuery("#corre_select_a_population_div").empty().append(popsList).show();

    var dbSelPopsList;
    if( modelData.id.match(/uploaded/) == null) {
        dbSelPopsList = addSelectionPopulations();
    }

    if (dbSelPopsList) {
            jQuery("#corre_select_a_population_div ul").append(dbSelPopsList);
    }

    var userUploadedSelExists = jQuery("#uploaded_selection_pops_table").doesExist();
    if( userUploadedSelExists == true) {

        var userSelPops = listUploadedSelPopulations();
        if (userSelPops) {

            jQuery("#corre_select_a_population_div ul").append(userSelPops);
        }
    }

   jQuery(".corre_dropdown dt a").click(function() {
            jQuery(".corre_dropdown dd ul").toggle();
        });

    jQuery(".corre_dropdown dd ul li a").click(function() {

        var text = jQuery(this).html();

        jQuery(".corre_dropdown dt a span").html(text);
        jQuery(".corre_dropdown dd ul").hide();

        var idPopName = jQuery("#corre_selected_population").find("dt a span.value").html();
        idPopName     = JSON.parse(idPopName);
        modelId = jQuery("#model_id").val();

        selectedPopId   = idPopName.id;
        selectedPopName = idPopName.name;
        selectedPopType = idPopName.pop_type;

        jQuery("#corre_selected_population_name").val(selectedPopName);
        jQuery("#corre_selected_population_id").val(selectedPopId);
        jQuery("#corre_selected_population_type").val(selectedPopType);

    });

    jQuery(".corre_dropdown").bind('click', function(e) {
        var clicked = jQuery(e.target);

        if (! clicked.parents().hasClass("corre_dropdown"))
            jQuery(".corre_dropdown dd ul").hide();

        e.preventDefault();

    });
}

function formatGenCorInputData (popId, type) {
    var modelDetail = getPopulationDetails();

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'model_id': modelDetail.population_id, 'corr_population_id': popId, 'type' : type},
        url: '/correlation/genetic/data/',
        success: function(response) {
                if(response.status == 'success') {
                    gebvsFile = response.gebvs_file;

                    var args = {
                        'model_id': modelDetail.population_id,
                        'corr_population_id': popId,
                        'type': type,
                        'gebvs_file': response.gebvs_file
                    };

                    runGenCorrelationAnalysis(args);
                } else {
                    jQuery("#correlation_message")
                        .css({"padding-left": '0px'})
                        .html("This population has no additive genetic data.");
                }
            },
            error: function(response) {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("Error occured preparing the additive genetic data for correlation analysis.");
            }
    });
}

function getPopulationDetails () {

    var populationId = jQuery("#population_id").val();
    var populationName = jQuery("#population_name").val();

    if(populationId == 'undefined' ) {
        populationId = jQuery("#model_id").val();
        populationName = jQuery("#model_name").val();
    }

    return {'population_id' : populationId,
            'population_name' : populationName
            };

}

function phenotypicCorrelation () {

    var population = getPopulationDetails();

    jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            data: {'population_id': population.population_id },
            url: '/correlation/phenotype/data/',
            success: function(response) {
                if(response.status == 'success') {
                    runPhenoCorrelationAnalysis();
                } else {
                    jQuery("#correlation_message")
                        .css({"padding-left": '0px'})
                        .html("This population has no phenotype data.");
                }
            },
            error: function(response) {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("Error occured preparing the phenotype data for correlation analysis.");
            }
    });

}

function runPhenoCorrelationAnalysis () {
    var population = getPopulationDetails();

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'population_id': population.population_id },
        url: '/phenotypic/correlation/analysis/output',
        success: function(response) {
            if (response.status == 'success') {
                plotCorrelation(response.data);
                jQuery("#correlation_message").empty();
            } else {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("There is no correlation output for this dataset.");
            }
        },
        error: function(response) {
            jQuery("#correlation_message")
                .css({"padding-left": '0px'})
                .html("Error occured running the correlation analysis.");
        }
    });

}

function runGenCorrelationAnalysis (args) {

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: args,
        url: '/genetic/correlation/analysis/output',
        success: function(response) {
            if (response.status == 'success') {

                plotCorrelation(response.data);
                jQuery("#correlation_message").empty();
            } else {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("There is no genetic correlation output for this dataset.");
            }
        },
        error: function(response) {
            jQuery("#correlation_message")
                .css({"padding-left": '0px'})
                .html("Error occured running the genetic correlation analysis.");
        }
    });

}

function plotCorrelation (data) {

    data = data.replace(/\s/g, '');
    data = data.replace(/\\/g, '');
    data = data.replace(/^\"/, '');
    data = data.replace(/\"$/, '');
    data = data.replace(/\"NA\"/g, 100);

    data = JSON.parse(data);

    var height = 400;
    var width  = 400;

    var nTraits = data.traits.length;

    if (nTraits < 8) {
        height = height * 0.5;
        width  = width  * 0.5;
    }

    var pad    = {left:70, top:20, right:100, bottom: 70};
    var totalH = height + pad.top + pad.bottom;
    var totalW = width + pad.left + pad.right;

    var corXscale = d3.scale.ordinal().domain(d3.range(nTraits)).rangeBands([0, width]);
    var corYscale = d3.scale.ordinal().domain(d3.range(nTraits)).rangeBands([height, 0]);
    var corZscale = d3.scale.linear().domain([-1, 0, 1]).range(["#6A0888","white", "#86B404"]);

    var xAxisScale = d3.scale.ordinal()
        .domain(data.traits)
        .rangeBands([0, width]);

    var yAxisScale = d3.scale.ordinal()
        .domain(data.traits)
        .rangeRoundBands([height, 0]);

    var svg = d3.select("#correlation_canvas")
        .append("svg")
        .attr("height", totalH)
        .attr("width", totalW);

    var xAxis = d3.svg.axis()
        .scale(xAxisScale)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(yAxisScale)
        .orient("left");

    var corrplot = svg.append("g")
        .attr("id", "correlation_plot")
        .attr("transform", "translate(" + pad.left + "," + pad.top + ")");

    corrplot.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height +")")
        .call(xAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", 10)
        .attr("dy", ".1em")
        .attr("transform", "rotate(90)")
        .attr("fill", "purple")
        .style({"text-anchor":"start", "fill": "#3306FC"});

    corrplot.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate(0,0)")
        .call(yAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", -10)
        .attr("dy", ".1em")
        .attr("fill", "#523CB5")
        .style("fill", "#523CB5");

    var corr = [];
    var coefs = [];
    for (var i=0; i<data.coefficients.length; i++) {
        for  (var j=0;  j<data.coefficients[i].length; j++) {
            corr.push({"row":i, "col":j, "value": data.coefficients[i][j]});

            if(data.coefficients[i][j] != 100) {
                coefs.push(data.coefficients[i][j]);
            }
        }
    }

    var cell = corrplot.selectAll("rect")
        .data(corr)
        .enter().append("rect")
        .attr("class", "cell")
        .attr("x", function (d) { return corXscale(d.col)})
        .attr("y", function (d) { return corYscale(d.row)})
        .attr("width", corXscale.rangeBand())
        .attr("height", corYscale.rangeBand())
        .attr("fill", function (d) {
                if (d.value === 100) {return "white";}
                else {return corZscale(d.value)}
            })
        .attr("stroke", "white")
        .attr("stroke-width", 1)
        .on("mouseover", function (d) {
                if(d.value != 100) {
                    d3.select(this)
                        .attr("stroke", "green")
                    corrplot.append("text")
                        .attr("id", "corrtext")
                        .text("[" + data.traits[d.row]
                              + " vs. " + data.traits[d.col]
                              + ": " + d3.format(".2f")(d.value)
                              + "]")
                        .style("fill", "purple")
                        .attr("x", totalW * 0.5)
                        .attr("y", totalH * 0.5)
                        .attr("font-weight", "bold")
                        .attr("dominant-baseline", "middle")
                        .attr("text-anchor", "middle")
                }
        })
        .on("mouseout", function() {
                d3.selectAll("text.corrlabel").remove()
                d3.selectAll("text#corrtext").remove()
                d3.select(this).attr("stroke","white")
            });

    corrplot.append("rect")
        .attr("height", height)
        .attr("width", width)
        .attr("fill", "none")
        .attr("stroke", "#523CB5")
        .attr("stroke-width", 1)
        .attr("pointer-events", "none");

    var legendValues = [];
    if (nTraits === 2) {
        if (d3.min(coefs) > 0 && d3.max(coefs) > 0 ) {
            legendValues = [[0, d3.max(coefs)], [1, 0]];
        } else if (d3.min(coefs) < 0 && d3.max(coefs) < 0 )  {
           legendValues = [[0, d3.min(coefs)], [1, 0]];
        } else {
           legendValues = [[0, d3.min(coefs)], [1, d3.max(coefs)]];
        }
    } else {
        legendValues = [[0, d3.min(coefs)], [1, 0], [2, d3.max(coefs)]];
    }

    var legend = corrplot.append("g")
        .attr("class", "cell")
        .attr("transform", "translate(" + (width + 10) + "," +  (height * 0.25) + ")")
        .attr("height", 100)
        .attr("width", 100);

    var recLH = 20;
    var recLW = 20;

    legend = legend.selectAll("rect")
        .data(legendValues)
        .enter()
        .append("rect")
        .attr("x", function (d) { return 1;})
        .attr("y",  function (d) {return 1 + (d[0] * recLH) + (d[0] * 5); })
        .attr("width", recLH)
        .attr("height", recLW)
        .style("stroke", "black")
        .attr("fill", function (d) {
            if (d === 100) {return "white"}
            else {return corZscale(d[1])}
        });

    var legendTxt = corrplot.append("g")
        .attr("transform", "translate(" + (width + 40) + "," + ((height * 0.25) + (0.5 * recLW)) + ")")
        .attr("id", "legendtext");

    legendTxt.selectAll("text")
        .data(legendValues)
        .enter()
        .append("text")
        .attr("fill", "#523CB5")
        .style("fill", "#523CB5")
        .attr("x", 1)
        .attr("y", function (d) { return 1 + (d[0] * recLH) + (d[0] * 5); })
        .text(function(d) {
            if (d[1] > 0) { return "Positive"; }
            else if (d[1] < 0) { return "Negative"; }
            else if (d[1] === 0) { return "Neutral"; }
        })
        .attr("dominant-baseline", "middle")
        .attr("text-anchor", "start");

}

<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * Parser for VCF files.
 */

var igv = (function (igv) {

    igv.VcfParser = function () {

    }

    igv.VcfParser.prototype.parseHeader = function (data) {

        var lines = data.splitLines(),
            len = lines.length,
            line,
            i,
            j,
            tokens,
            header = {},
            id,
            values,
            ltIdx,
            gtIdx,
            type,
            self = this;

        this.header = header;

        // First line must be file format
        if (lines[0].startsWith("##fileformat")) {
            header.version = lines[0].substr(13);
        }
        else {
            throw new Error("Invalid VCF file: missing fileformat line");
        }

        for (i = 1; i < len; i++) {
            line = lines[i].trim();
            if (line.startsWith("#")) {

                id = null;
                values = {};

                if (line.startsWith("##")) {

                    if (line.startsWith("##INFO") || line.startsWith("##FILTER") || line.startsWith("##FORMAT")) {

                        ltIdx = line.indexOf("<");
                        gtIdx = line.lastIndexOf(">");

                        if (!(ltIdx > 2 && gtIdx > 0)) {
                            console.log("Malformed VCF header line: " + line);
                            continue;
                        }

                        type = line.substring(2, ltIdx - 1);
                        if (!header[type])  header[type] = {};

                        //##INFO=<ID=AF,Number=A,Type=Float,Description="Allele frequency based on Flow Evaluator observation counts">
                        // ##FILTER=<ID=NOCALL,Description="Generic filter. Filtering details stored in FR info tag.">
                        // ##FORMAT=<ID=AF,Number=A,Type=Float,Description="Allele frequency based on Flow Evaluator observation counts">

                        tokens = igv.splitStringRespectingQuotes(line.substring(ltIdx + 1, gtIdx - 1), ",");

                        tokens.forEach(function (token) {
                            var kv = token.split("=");
                            if (kv.length > 1) {
                                if (kv[0] === "ID") {
                                    id = kv[1];
                                }
                                else {
                                    values[kv[0]] = kv[1];
                                }
                            }
                        });

                        if (id) {
                            header[type][id] = values;
                        }
                    }
                    else {
                        // Ignoring other ## header lines
                    }
                }
                else if (line.startsWith("#CHROM")) {
                    // TODO -- parse this to get sample names
                    tokens = line.split("\t");
                    if(tokens.length > 9) {
                        header.callSets = [];
                        for(j = 9; j < tokens.length; j++) {
                            header.callSets.push({id: j, name: tokens[j]});
                        }
                    }
                }

            }
            else {
                break;
            }

        }
        return header;
    }

    /**
     * Parse data as a collection of Variant objects.
     *
     * @param data
     * @returns {Array}
     */
    igv.VcfParser.prototype.parseFeatures = function (data) {

        var lines = data.split("\n"),
            len = lines.length,
            tokens,
            allFeatures,
            line,
            i,
            variant;

        allFeatures = [];
        for (i = 0; i < len; i++) {
            line = lines[i];
            if (line.startsWith("#")) {
                continue;
            }
            else {
                tokens = lines[i].split("\t");
                variant = decode(tokens);
                if (variant != null) {
                    variant.header = this.header;       // Keep a pointer to the header to interpret fields for popup text
                    allFeatures.push(variant);
                }

            }
        }

        return allFeatures;

        function decode(tokens) {

            if (tokens.length < 8) {
                return null;
            }
            else {
                return new Variant(tokens);
            }

        }
    }

    function Variant(tokens) {

        var self = this,
            altTokens;

        this.chr = tokens[0]; // TODO -- use genome aliases
        this.pos = parseInt(tokens[1]);
        this.names = tokens[2];    // id in VCF
        this.referenceBases = tokens[3];
        this.alternateBases = tokens[4];
        this.quality = parseInt(tokens[5]);
        this.filter = tokens[6];
        this.info = tokens[7];

        // "ids" ("names" in ga4gh)

        //Alleles
        altTokens = this.alternateBases.split(",");

        if (altTokens.length > 0) {

            this.alleles = [];

            this.start = Number.MAX_VALUE;
            this.end = 0;

            altTokens.forEach(function (alt) {
                var a, s, e, diff;
                if (alt.length > 0) {

                    diff = self.referenceBases.length - alt.length;

                    if (diff > 0) {
                        // deletion, assume left padded
                        s = self.pos - 1 + alt.length;
                        e = s + diff;
                    } else if (diff < 0) {
                        // Insertion, assume left padded, insertion begins to "right" of last ref base
                        s = self.pos - 1 + self.referenceBases.length;
                        e = s + 1;     // Insertion between s & 3
                    }
                    else {
                        // Substitution, SNP if seq.length == 1
                        s = self.pos - 1;
                        e = s + alt.length;
                    }
                    self.alleles.push({allele: alt, start: s, end: e});
                    self.start = Math.min(self.start, s);
                    self.end = Math.max(self.end, e);
                }

            });
        }
        else {
            // Is this even legal VCF?  (NO alt alleles)
            this.start = this.pos - 1;
            this.end = this.pos;
        }

        // TODO -- genotype fields
    }

    Variant.prototype.popupData = function (genomicLocation) {

        var fields, infoFields, nameString;

        fields = [
            {name: "Names", value: this.names},
            {name: "Ref", value: this.referenceBases},
            {name: "Alt", value: this.alternateBases},
            {name: "Qual", value: this.quality},
            {name: "Filter", value: this.filter},
            "
"
        ];

        infoFields = this.info.split(";");
        infoFields.forEach(function (f) {
            var tokens = f.split("=");
            if (tokens.length > 1) {
                fields.push({name: tokens[0], value: tokens[1]});   // TODO -- use header to add descriptive tooltip
            }
        });

        return fields;

    }

    return igv;
})(igv || {});
<commit_msg>vcf parsing<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * Parser for VCF files.
 */

var igv = (function (igv) {

    igv.VcfParser = function () {

    }

    igv.VcfParser.prototype.parseHeader = function (data) {

        var lines = data.splitLines(),
            len = lines.length,
            line,
            i,
            j,
            tokens,
            header = {},
            id,
            values,
            ltIdx,
            gtIdx,
            type;

        // First line must be file format
        if (lines[0].startsWith("##fileformat")) {
            header.version = lines[0].substr(13);
        }
        else {
            throw new Error("Invalid VCF file: missing fileformat line");
        }

        for (i = 1; i < len; i++) {
            line = lines[i].trim();
            if (line.startsWith("#")) {

                id = null;
                values = {};

                if (line.startsWith("##")) {

                    if (line.startsWith("##INFO") || line.startsWith("##FILTER") || line.startsWith("##FORMAT")) {

                        ltIdx = line.indexOf("<");
                        gtIdx = line.lastIndexOf(">");

                        if (!(ltIdx > 2 && gtIdx > 0)) {
                            console.log("Malformed VCF header line: " + line);
                            continue;
                        }

                        type = line.substring(2, ltIdx - 1);
                        if (!header[type])  header[type] = {};

                        //##INFO=<ID=AF,Number=A,Type=Float,Description="Allele frequency based on Flow Evaluator observation counts">
                        // ##FILTER=<ID=NOCALL,Description="Generic filter. Filtering details stored in FR info tag.">
                        // ##FORMAT=<ID=AF,Number=A,Type=Float,Description="Allele frequency based on Flow Evaluator observation counts">

                        tokens = igv.splitStringRespectingQuotes(line.substring(ltIdx + 1, gtIdx - 1), ",");

                        tokens.forEach(function (token) {
                            var kv = token.split("=");
                            if (kv.length > 1) {
                                if (kv[0] === "ID") {
                                    id = kv[1];
                                }
                                else {
                                    values[kv[0]] = kv[1];
                                }
                            }
                        });

                        if (id) {
                            header[type][id] = values;
                        }
                    }
                    else {
                        // Ignoring other ## header lines
                    }
                }
                else if (line.startsWith("#CHROM")) {
                    // TODO -- parse this to get sample names
                    tokens = line.split("\t");

                    if (tokens.length > 8) {

                        // Format field
                        header.callKeys = tokens[8].split(":");

                        // call set names
                        header.callSets = [];
                        for (j = 9; j < tokens.length; j++) {
                            header.callSets.push({id: j, name: tokens[j]});
                        }
                    }
                }

            }
            else {
                break;
            }

        }

        this.header = header;  // Will need to intrepret genotypes and info field

        return header;
    }

    /**
     * Parse data as a collection of Variant objects.
     *
     * @param data
     * @returns {Array}
     */
    igv.VcfParser.prototype.parseFeatures = function (data) {

        var lines = data.split("\n"),
            len = lines.length,
            tokens,
            allFeatures,
            line,
            i,
            j,
            variant,
            call,
            callTokens;

        allFeatures = [];
        for (i = 0; i < len; i++) {
            line = lines[i];
            if (line.startsWith("#")) {
                continue;
            }
            else {
                tokens = lines[i].split("\t");
                if (tokens.length >= 8) {
                    variant = new Variant(tokens);
                    variant.header = this.header;       // Keep a pointer to the header to interpret fields for popup text
                    allFeatures.push(variant);

                    if (tokens.length > 9) {

                        for (j = 0; j < tokens.length; j++) {
                            callTokens = tokens[j].split(":");

                        }

                    }

                }
            }
        }

        return allFeatures;

    }

    function Call(string) {

        var tokens = string.split(":")

    }

    function Variant(tokens) {

        var self = this,
            altTokens;

        this.chr = tokens[0]; // TODO -- use genome aliases
        this.pos = parseInt(tokens[1]);
        this.names = tokens[2];    // id in VCF
        this.referenceBases = tokens[3];
        this.alternateBases = tokens[4];
        this.quality = parseInt(tokens[5]);
        this.filter = tokens[6];
        this.info = tokens[7];

        // "ids" ("names" in ga4gh)

        //Alleles
        altTokens = this.alternateBases.split(",");

        if (altTokens.length > 0) {

            this.alleles = [];

            this.start = Number.MAX_VALUE;
            this.end = 0;

            altTokens.forEach(function (alt) {
                var a, s, e, diff;
                if (alt.length > 0) {

                    diff = self.referenceBases.length - alt.length;

                    if (diff > 0) {
                        // deletion, assume left padded
                        s = self.pos - 1 + alt.length;
                        e = s + diff;
                    } else if (diff < 0) {
                        // Insertion, assume left padded, insertion begins to "right" of last ref base
                        s = self.pos - 1 + self.referenceBases.length;
                        e = s + 1;     // Insertion between s & 3
                    }
                    else {
                        // Substitution, SNP if seq.length == 1
                        s = self.pos - 1;
                        e = s + alt.length;
                    }
                    self.alleles.push({allele: alt, start: s, end: e});
                    self.start = Math.min(self.start, s);
                    self.end = Math.max(self.end, e);
                }

            });
        }
        else {
            // Is this even legal VCF?  (NO alt alleles)
            this.start = this.pos - 1;
            this.end = this.pos;
        }

        // TODO -- genotype fields
    }

    Variant.prototype.popupData = function (genomicLocation) {

        var fields, infoFields, nameString;

        fields = [
            {name: "Names", value: this.names},
            {name: "Ref", value: this.referenceBases},
            {name: "Alt", value: this.alternateBases},
            {name: "Qual", value: this.quality},
            {name: "Filter", value: this.filter},
            "
"
        ];

        infoFields = this.info.split(";");
        infoFields.forEach(function (f) {
            var tokens = f.split("=");
            if (tokens.length > 1) {
                fields.push({name: tokens[0], value: tokens[1]});   // TODO -- use header to add descriptive tooltip
            }
        });

        return fields;

    }

    return igv;
})(igv || {});
<|endoftext|>


<commit_before>/* eslint-env node */

"use strict";

const _ = require('lodash');
const gulp = require('gulp');
const path = require('path');
const watch = require('gulp-watch');

const BASE_DIRS = ['app', 'src'];
const DIST_DIRS = ['dist', 'dist/www'];

function copyJs(filePath, srcDir, distDir) {
    const relative = path.relative(path.join(__dirname, srcDir), filePath);
    const from = path.join(srcDir, relative);
    const to = path.dirname(path.join(distDir, relative));
    return gulp.src(from)
        .pipe(gulp.dest(to));
}

gulp.task('copy-src-dist', (_cb) => {
    const cb = _.after(BASE_DIRS.length, _cb);
    BASE_DIRS.forEach((srcDir, idx) => {
        gulp.src(`${srcDir}/**/!(*.ts|*.tsx)`)
            .pipe(gulp.dest(DIST_DIRS[idx]))
            .on('end', cb);
    });
});

gulp.task('watch', ['copy-src-dist'], () => {
    BASE_DIRS.forEach((srcDir, idx) => {
        watch(`${srcDir}/**/!(*.ts|*.tsx)`, file => {
            copyJs(file.path, srcDir, DIST_DIRS[idx]);
            console.log(`copied modified ${file.path} from ${srcDir} to ${DIST_DIRS[idx]}`);
        });
    });
});
<commit_msg>fixes #66<commit_after>/* eslint-env node */

"use strict";

const _ = require('lodash');
const gulp = require('gulp');
const path = require('path');
const watch = require('gulp-watch');

const BASE_DIRS = ['app', 'src', 'samples'];
const DIST_DIRS = ['dist', 'dist/www', 'dist/samples'];

function copyJs(filePath, srcDir, distDir) {
    const relative = path.relative(path.join(__dirname, srcDir), filePath);
    const from = path.join(srcDir, relative);
    const to = path.dirname(path.join(distDir, relative));
    return gulp.src(from)
        .pipe(gulp.dest(to));
}

gulp.task('copy-src-dist', (_cb) => {
    const cb = _.after(BASE_DIRS.length, _cb);
    BASE_DIRS.forEach((srcDir, idx) => {
        gulp.src(`${srcDir}/**/!(*.ts|*.tsx)`)
            .pipe(gulp.dest(DIST_DIRS[idx]))
            .on('end', cb);
    });
});

gulp.task('watch', ['copy-src-dist'], () => {
    BASE_DIRS.forEach((srcDir, idx) => {
        watch(`${srcDir}/**/!(*.ts|*.tsx)`, file => {
            copyJs(file.path, srcDir, DIST_DIRS[idx]);
            console.log(`copied modified ${file.path} from ${srcDir} to ${DIST_DIRS[idx]}`);
        });
    });
});
<|endoftext|>


<commit_before>var gulp = require('gulp');
var htmlmin = require('gulp-htmlmin');
var stripDebug = require('gulp-strip-debug');
var templateCache = require('gulp-angular-templatecache');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var concatCss = require('gulp-concat-css');
var ngAnnotate = require('gulp-ng-annotate');
var sourcemaps = require('gulp-sourcemaps');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var del = require('del');
var path = require('path');

gulp.task('clean', function() {
	return del['src/main/resources/static/**'];
});

gulp.task('templates', function(){
    return gulp.src([
        'src/main/js/**/*.html'
        ])
        .pipe(htmlmin({collapseWhitespace: false}))
        .pipe(templateCache({
            module : 'app.templates',
            standalone : true
        }))
        .pipe(concat('templates.js'))
        .pipe(gulp.dest('src/main/js/dist/'))
});

gulp.task('browserify', [ 'clean' ], function() {
	return browserify({
		entries : [ 'src/main/js/app.js' ],
		paths : [ 'src/main/js/' ]
	}).bundle().on('error', function(e) {
		gutil.log(e);
		process.exit(1);
	})
        .pipe(source('src/main/js/dist/bundle.js'))
        .pipe(buffer())
        .pipe(stripDebug())
        .pipe(ngAnnotate())
        .pipe(uglify().on('error', function(e){
            gutil.log(e);
        }))
        .pipe(gulp.dest('.'));

});

gulp.task('css',function(){
    return gulp.src([
        'src/main/js/views/**/*.css',
        'src/main/js/components/**/*.css'
        ])
        .pipe(concatCss('src/main/js/dist/bundle.css'))
        .pipe(gulp.dest('.'));
});

gulp.task('copy', [ 'browserify', 'css', 'templates' ], function() {
	return gulp.src('src/main/js/**').pipe(
			gulp.dest('src/main/resources/static/'));
});

gulp.task('default', [ 'copy' ]);
<commit_msg>CHNG: commented out the stripDebug()<commit_after>var gulp = require('gulp');
var htmlmin = require('gulp-htmlmin');
var stripDebug = require('gulp-strip-debug');
var templateCache = require('gulp-angular-templatecache');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var concatCss = require('gulp-concat-css');
var ngAnnotate = require('gulp-ng-annotate');
var sourcemaps = require('gulp-sourcemaps');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var gutil = require('gulp-util');
var del = require('del');
var path = require('path');

gulp.task('clean', function() {
	return del['src/main/resources/static/**'];
});

gulp.task('templates', function(){
    return gulp.src([
        'src/main/js/**/*.html'
        ])
        .pipe(htmlmin({collapseWhitespace: false}))
        .pipe(templateCache({
            module : 'app.templates',
            standalone : true
        }))
        .pipe(concat('templates.js'))
        .pipe(gulp.dest('src/main/js/dist/'))
});

gulp.task('browserify', [ 'clean' ], function() {
	return browserify({
		entries : [ 'src/main/js/app.js' ],
		paths : [ 'src/main/js/' ]
	}).bundle().on('error', function(e) {
		gutil.log(e);
		process.exit(1);
	})
        .pipe(source('src/main/js/dist/bundle.js'))
        .pipe(buffer())
//        .pipe(stripDebug())
        .pipe(ngAnnotate())
        .pipe(uglify().on('error', function(e){
            gutil.log(e);
        }))
        .pipe(gulp.dest('.'));

});

gulp.task('css',function(){
    return gulp.src([
        'src/main/js/views/**/*.css',
        'src/main/js/components/**/*.css'
        ])
        .pipe(concatCss('src/main/js/dist/bundle.css'))
        .pipe(gulp.dest('.'));
});

gulp.task('copy', [ 'browserify', 'css', 'templates' ], function() {
	return gulp.src('src/main/js/**').pipe(
			gulp.dest('src/main/resources/static/'));
});

gulp.task('default', [ 'copy' ]);
<|endoftext|>