diff --git a/__init__.py b/__init__.py index 980a1ed..8e51bc3 100644 --- a/__init__.py +++ b/__init__.py @@ -8,6 +8,9 @@ # # it does nothing but report the version number +Version = "2.2" + +def version(): + return Version -Version = "2.0" diff --git a/cinema/explorer/2.0/css/viewer.css b/cinema/explorer/2.2/css/viewer.css similarity index 100% rename from cinema/explorer/2.0/css/viewer.css rename to cinema/explorer/2.2/css/viewer.css diff --git a/cinema/explorer/2.0/databases.json b/cinema/explorer/2.2/databases.json similarity index 100% rename from cinema/explorer/2.0/databases.json rename to cinema/explorer/2.2/databases.json diff --git a/cinema/explorer/2.0/js/main.js b/cinema/explorer/2.2/js/main.js similarity index 99% rename from cinema/explorer/2.0/js/main.js rename to cinema/explorer/2.2/js/main.js index aea4b8b..8cf9173 100644 --- a/cinema/explorer/2.0/js/main.js +++ b/cinema/explorer/2.2/js/main.js @@ -39,7 +39,7 @@ var currentDb; //whether or not the currentDb has extra axis ordering data var hasAxisOrdering = false; //this can be overriden with HTTP params -var databaseList = 'cinema/explorer/2.0/databases.json'; +var databaseList = 'cinema/explorer/2.2/databases.json'; var databaseListType = 'json'; var loaded = false; diff --git a/cinema/view/2.0/css/common.css b/cinema/lib/2.2/common.css similarity index 100% rename from cinema/view/2.0/css/common.css rename to cinema/lib/2.2/common.css diff --git a/cinema/lib/databases.js b/cinema/lib/2.2/databases.js similarity index 100% rename from cinema/lib/databases.js rename to cinema/lib/2.2/databases.js diff --git a/cinema/view/2.0/css/view.css b/cinema/lib/2.2/view.css similarity index 100% rename from cinema/view/2.0/css/view.css rename to cinema/lib/2.2/view.css diff --git a/cinema/lib/CinemaComponents.v2.7.1.min.css b/cinema/lib/CinemaComponents.v2.7.1.min.css new file mode 100644 index 0000000..9491593 --- /dev/null +++ b/cinema/lib/CinemaComponents.v2.7.1.min.css @@ -0,0 +1,479 @@ +.CINEMA_COMPONENT.GLYPH .axes path { + stroke-opacity: 0.4; + stroke: black; +} + +.CINEMA_COMPONENT.GLYPH .axes text { + text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff; +} + +.CINEMA_COMPONENT.GLYPH .glyph { + fill: rgba(0, 0, 0, 0.034); + stroke: rgba(95, 153, 201, 0.747); + stroke-width: 5px; + stroke-linejoin: round; +}.CINEMA_COMPONENT.IMAGE_SPREAD .header { + background: #e2e2e2; + padding: 5px 20px; + border-bottom: 3px solid dimgray; + box-sizing: border-box; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .controlPanel { + margin: 0px 10px; + display: inline-table; + color: black; + font-size: 14px; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .controlPanel.imageSize { + float: right; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .dataDisplay { + display: inline-block; + margin: 5px; + padding: 2px; + border: 4px solid black; + background-color: lightgray; + box-shadow: 1px 1px 2px black; +} +.CINEMA_COMPONENT.IMAGE_SPREAD .dataDisplay:hover { + box-shadow: 2px 4px 8px black; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .fileDisplay { + display: inline-block; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .fileDisplay .display { + margin: 2px; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .fileDisplay .display.image { + border: 2px solid black; + line-height: 0; + cursor: pointer; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .fileDisplay .display.image:hover { + border: 2px solid rgb(23, 165, 221); + box-shadow: 1px 1px 2px black; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .fileDisplay .displayLabel { + font-size: 12px; + text-align: center; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .fileDisplay .display.text { + text-align: center; + padding: 5px; + font-size: 14px; + font-weight: bold; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .fileDisplay .display.image img { + line-height: 0; +} + +.modalBackground { + position: fixed; + z-index: 3; + padding-top: 100px; + left: 0; + top: 0; + width: 100%; + height: 100%; + overflow: auto; + background-color: rgba(0,0,0,0.9); +} + +.modalImg { + margin: auto; + display: block; +} + +.modalViewer { + margin: auto; + width: 50%; + height: 80%; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .pageNavWrapper { + padding: initial; + z-index: 2; + position: fixed; + bottom: 30px; + left: 50%; + width: auto; + height: auto; + transform: translate(-50%,-50%); + border: 2px solid lightgray; + border-radius: 3px; + box-shadow: 3px 3px 10px dimgray; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .pageNav { + margin: initial; + padding: initial; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .pageButton { + cursor: pointer; + color: white; + font-size: 14px; + display: inline-flex; + background-color: rgba(25,25,25,0.85); + padding: 10px; +} +.CINEMA_COMPONENT.IMAGE_SPREAD .pageButton:hover { + background-color: rgba(50,50,50,0.85); +} +.CINEMA_COMPONENT.IMAGE_SPREAD .pageButton[mode='selected'], +.CINEMA_COMPONENT.IMAGE_SPREAD .pageButton[mode='selected']:hover { + color: white; + background-color: rgba(100,100,100,0.85); +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .pageReadout { + background-color: rgba(25,25,25,0.85); + color: white; + text-align: center; + font-size: 12px; + padding: 3px; +} + +.CINEMA_COMPONENT.IMAGE_SPREAD .noFileWarning { + padding: 10px; + width: 35%; + margin-left: auto; + margin-right: auto; + margin-top: 10px; + text-align: center; + background: rgb(201, 201, 201); + border: solid #333 5px; + border-radius: 10px; + box-shadow: 2px 2px 5px dimgray; + + color: black; + font-weight: bold; + font-size: 24px; + +} +.CINEMA_COMPONENT.LINE_CHART { + background: #e2e2e2; +} + +.CINEMA_COMPONENT.LINE_CHART .mainContainer { + background-color: white; + border: 2px solid black; + border-width: 2px 2px 0px 0px; +} + +.CINEMA_COMPONENT.LINE_CHART .dimensionSelect.x { + left: 50%; + transform: translateX(-50%); + bottom: 10px; +} + +.CINEMA_COMPONENT.LINE_CHART .tableContainer { + background-color: #eaeaea; + width: 135px; +} + +.CINEMA_COMPONENT.LINE_CHART .lineSelect.y td { + background-color: #eaeaea; + width: 135px; + white-space: nowrap; +} + +.CINEMA_COMPONENT.LINE_CHART .lineSelect.yGroup td { + background-color: #eaeaea; + width: 135px; + white-space: nowrap; +} + +.CINEMA_COMPONENT.LINE_CHART .lineSelect.checkboxtext{ + font-size: 10px; +} + +.CINEMA_COMPONENT.LINE_CHART .lineGroupSelect.checkboxtext{ + font-size: 10px; + font-weight: bold; +} + +.CINEMA_COMPONENT.LINE_CHART .lineChart { + font: 10px sans-serif; + background-color: whitesmoke; +} + +.CINEMA_COMPONENT.LINE_CHART .axisContainer { + pointer-events: none; + overflow: visible; +} + +.CINEMA_COMPONENT.LINE_CHART .axis line, +.CINEMA_COMPONENT.LINE_CHART .axis path { + fill: none; + stroke: black; + stroke-width: 2px; + shape-rendering: crispEdges; +} + +.CINEMA_COMPONENT.LINE_CHART .axis text { + fill: black; +} +CINEMA_COMPONENT.PCOORD.CANVAS .brush .extent { + fill-opacity: .3; + stroke: #fff; + shape-rendering: crispEdges; +} + +.CINEMA_COMPONENT.PCOORD.CANVAS .axis line, +.CINEMA_COMPONENT.PCOORD.CANVAS .axis path { + fill: none; + stroke: black; + shape-rendering: crispEdges; +} + +.CINEMA_COMPONENT.PCOORD.CANVAS .axisLabel rect { + fill: whitesmoke; +} + +.CINEMA_COMPONENT.PCOORD.CANVAS .axisLabel text { + fill: black; + cursor: move; +} + +.CINEMA_COMPONENT.PCOORD.CANVAS .axis path.NaNExtension, +.CINEMA_COMPONENT.PCOORD.CANVAS .axis .NaNExtensionTick line { + stroke: rgb(196, 23, 57); +} +.CINEMA_COMPONENT.PCOORD.CANVAS .axis .NaNExtensionTick text{ + fill: rgb(196, 23, 57); +} + +.CINEMA_COMPONENT.PCOORD.CANVAS .loadingIndicator { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%,-50%); + + color: white; + font-size: 12px; + background: rgba(0, 0, 0, 0.671); + border-radius: 5px; + padding: 5px; +}.CINEMA_COMPONENT.PCOORD.SVG { + font: 10px sans-serif; + background-color: whitesmoke; +} + +/*.CINEMA_COMPONENT.PCOORD.SVG .pathContainer, +.CINEMA_COMPONENT.PCOORD.SVG .pathContainer svg, +.CINEMA_COMPONENT.PCOORD.SVG .pathContainer svg .selectedPaths { + pointer-events: none; +}*/ + +.CINEMA_COMPONENT.PCOORD.SVG .selectedPaths path { + fill: none; + stroke-width: 2px; + stroke: lightgray; + stroke-opacity: 0.3; + vector-effect: non-scaling-stroke; +} + +.CINEMA_COMPONENT.PCOORD.SVG .highlightedPaths path { + pointer-events: none; + fill: none; + stroke-width: 4px; + stroke: lightskyblue; + stroke-opacity: 1; +} + +.CINEMA_COMPONENT.PCOORD.SVG .overlayPaths path { + fill: none; + pointer-events: none; + stroke-dasharray: 20, 10; + stroke: crimson; + stroke-width: 3px; + stroke-opacity: 1; +} + +.CINEMA_COMPONENT.PCOORD.SVG .brush .extent { + fill-opacity: .3; + stroke: #fff; + shape-rendering: crispEdges; +} + +.CINEMA_COMPONENT.PCOORD.SVG .axis line, +.CINEMA_COMPONENT.PCOORD.SVG .axis path { + fill: none; + stroke: black; + shape-rendering: crispEdges; +} + +.CINEMA_COMPONENT.PCOORD.SVG .axisLabel rect { + fill: whitesmoke; +} + +.CINEMA_COMPONENT.PCOORD.SVG .axisLabel text { + fill: black; + cursor: move; +} + +.CINEMA_COMPONENT.PCOORD.SVG .axis path.NaNExtension, +.CINEMA_COMPONENT.PCOORD.SVG .axis .NaNExtensionTick line { + stroke: rgb(196, 23, 57); +} +.CINEMA_COMPONENT.PCOORD.SVG .axis .NaNExtensionTick text{ + fill: rgb(196, 23, 57); +}.CINEMA_COMPONENT.QUERY { + font-size: 14px; + color: white; +} + +.CINEMA_COMPONENT.QUERY .thresholdInput { + width: 50px; +} + +.CINEMA_COMPONENT.QUERY .thresholdLabel, +.CINEMA_COMPONENT.QUERY .readout { + margin: 0px 10px; +} + +.CINEMA_COMPONENT.QUERY .inputRow { + height: 25px; + position: relative; + font-size: 14px; + margin: 5px; + border-bottom: 1px solid dimgray; +} +.CINEMA_COMPONENT.QUERY .inputRow .label { + text-align: center; + position: absolute; + top: 50%; + transform: translateY(-50%); +} +.CINEMA_COMPONENT.QUERY .inputRow input { + position: absolute; + top: 50%; + transform: translateY(-50%); +} +.CINEMA_COMPONENT.QUERY .inputRow input[type="range"] { + right: 10px; + width: 150px; +} +.CINEMA_COMPONENT.QUERY .inputRow input[type="checkbox"] { + right: 180px; + transform: translateY(-100%); +}.CINEMA_COMPONENT.SCATTER_PLOT.CANVAS .loadingIndicator { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%,-50%); + + color: white; + font-size: 12px; + background: rgba(0, 0, 0, 0.671); + border-radius: 5px; + padding: 5px; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.CANVAS .pointContainer { + background: white; + border: 2px solid black; + border-width: 2px 2px 0px 0px; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.CANVAS .dimensionSelect.x { + left: 50%; + transform: translateX(-50%); + bottom: 10px; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.CANVAS .dimensionSelect.y { + top: 50%; + transform: translateY(-50%); + left: 10px; + max-width: 100px; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.CANVAS .axisContainer { + pointer-events: none; + overflow: visible; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.CANVAS .axis line, +.CINEMA_COMPONENT.SCATTER_PLOT.CANVAS .axis path { + fill: none; + stroke: black; + stroke-width: 2px; + shape-rendering: crispEdges; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.CANVAS .axis text { + fill: black; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.CANVAS .warningReadout { + bottom: 10px; + right: 10px; + font-size: 12px; + color: darkred; +}.CINEMA_COMPONENT.SCATTER_PLOT.SVG .pointContainer { + background: white; + border: 2px solid black; + border-width: 2px 2px 0px 0px; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.SVG .dimensionSelect.x { + left: 50%; + transform: translateX(-50%); + bottom: 10px; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.SVG .dimensionSelect.y { + top: 50%; + transform: translateY(-50%); + left: 10px; + max-width: 100px; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.SVG .axisContainer { + pointer-events: none; + overflow: visible; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.SVG .axis line, +.CINEMA_COMPONENT.SCATTER_PLOT.SVG .axis path { + fill: none; + stroke: black; + stroke-width: 2px; + shape-rendering: crispEdges; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.SVG .axis text { + fill: black; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.SVG .selectedPoints circle { + fill: rgba(82, 137, 163, 0.521); + stroke: rgb(69, 121, 153); + stroke-width: 2px; +} + +.CINEMA_COMPONENT.SCATTER_PLOT.SVG .highlightedPoints circle { + pointer-events: none; + fill: rgb(252, 127, 127); + stroke: rgb(153, 80, 80); + stroke-width: 3px; +} + +.CINEMA_COMPONENT.SCATTER_PLOT .warningReadout { + bottom: 10px; + right: 10px; + font-size: 12px; + color: darkred; +} \ No newline at end of file diff --git a/cinema/lib/CinemaComponents.v2.7.1.min.js b/cinema/lib/CinemaComponents.v2.7.1.min.js new file mode 100644 index 0000000..7cc0f06 --- /dev/null +++ b/cinema/lib/CinemaComponents.v2.7.1.min.js @@ -0,0 +1,5055 @@ +'use strict'; +(function() { + /** + * CINEMA_COMPONENTS + * DATABASE + * + * The Database module for the CINEMA_COMPONENTS library. + * Contains functions and objects for dealing with the purely data-related + * parts of a SpecD database. (Parsing, Querying, etc. data. No GUI stuff) + * + * @exports CINEMA_COMPONENTS + * + * @author Cameron Tauxe + */ + + //If CINEMA_COMPONENTS is already defined, add to it, otherwise create it + var CINEMA_COMPONENTS = {} + if (window.CINEMA_COMPONENTS) + CINEMA_COMPONENTS = window.CINEMA_COMPONENTS; + else + window.CINEMA_COMPONENTS = CINEMA_COMPONENTS; + + /** @type {boolean} - Flag to indicate that the Database module has been included */ + CINEMA_COMPONENTS.DATABASE_INCLUDED = true; + + /** + * Enum for the type of dimension (column) + * @enum {number} + */ + CINEMA_COMPONENTS.DIMENSION_TYPE = Object.freeze({ + INTEGER: 0, + FLOAT: 1, + STRING: 2 + }); + + /** + * Database + * Creates a new instance of Database which represents the data in a SpecD Database + * + * @constructor + * @param {string} directory - Path to the '.cdb' directory containing the database + * @param {function({Database} self)} callback - Function to call when loading has finished + * (only called if loading finished without errors) + * @param {function({string} message)} errorCallback - Function to call if errors were found with data + * @param {Object} filter - An object defining a filter to apply to the incoming data (so that + * only some of the data from the file is actually represented in the database). Keys in the + * filter object should match a numeric dimension and contain an array of two values representing + * the minimum and maximum values to allow. + */ + CINEMA_COMPONENTS.Database = function(directory, callback, errorCallback, filter) { + /** @type {string} - Path to the '.cdb' directory containing the database */ + this.directory = directory; + + /** @type {boolean} - Whether or not the database has finished loading */ + this.loaded = false; + + /** @type {string?} - The error message for errors found in the data. Undefined if no errors */ + this.error; + + /** @type {Object[]} - An array of the data rows */ + this.data = []; + /** @type {string[]} - An array of dimension names for the data (column headers) */ + this.dimensions = []; + /** @type {Object} - Contains the type for each dimension */ + this.dimensionTypes = {}; + /** @type {Object} - Contains the domains for each dimension (formatted like the domain for a d3 scale) */ + this.dimensionDomains = {}; + + /** @type {Object} - The filter applied to incoming data */ + this.filter = filter + + /** @type {boolean} Whether or not this database has additional axis ordering data */ + this.hasAxisOrdering = false; + /** @type {Object} Axis Ordering data (if it exists) */ + this.axisOrderData; + + this.dispatch = d3.dispatch("dataUpdated"); + + this.errorCallback = errorCallback; + + var self = this; + self.path = directory+'/data.csv'; + getAndParseCSV(self.path, function(data_arr, request) { + self.prevContentLength = request.getResponseHeader('Content-Length'); + + //Check for errors + self.error = checkErrors(data_arr); + if (self.error) { + console.warn(self.error); + if (errorCallback) + errorCallback(); + return; + } + + calcData(self, data_arr); + + //Attempt to load an axis_order.csv file + getAndParseCSV(directory+'/axis_order.csv', + //Normal callback, if axis_order.csv found + function(axis_data_arr) { + var error = checkAxisDataErrors(axis_data_arr,self.dimensions); + if (!error) { + self.hasAxisOrdering = true; + self.axisOrderData = parseAxisOrderData(axis_data_arr); + } + else + console.warn("ERROR in axis_order.csv: " + error); + self.loaded = true; + if (callback) + callback(self); + }, + //Error callback, if axis_order.csv request fails + function() { + self.loaded = true; + if (callback) + callback(self); + } + ); + //errorCallback. If data.csv request fails + }, function() { + if (errorCallback) + errorCallback("Error loading data.csv!"); + }); + }; + + /** + * Shortcut function to check if a given dimension is of type string or not + * @param {string} dimension - The dimension to check + */ + CINEMA_COMPONENTS.Database.prototype.isStringDimension = function(dimension) { + return this.dimensionTypes[dimension] === CINEMA_COMPONENTS.DIMENSION_TYPE.STRING; + }; + + /** + * Set the database's data and calculate dimension information based off the given + * array of data. Sets the 'data', 'dimensions', 'dimensionTypes' and 'dimensionDomains' + * fields in the given database. + * @param {object} self - The database object + * @param {string} data_arr - The array of data (we assume it has already been error-checked) + */ + var calcData = function(self, data_arr) { + //Get dimensions (First row of data) + self.dimensions = data_arr[0]; + + //Convert rows from arrays to objects + self.data = data_arr.slice(1).map(function(d) { + var obj = {}; + self.dimensions.forEach(function(p,i){obj[p] = d[i];}); + return obj; + }); + + //Keep track of data that gets caught in the filter while parsing + //to remove after all the parsing has been done + var filterdOut = [] + + //Determine dimension types and calculate domains + self.dimensions.forEach(function(d) { + //The value used to determine the dimension type + //is the first defined value in the column + var val = self.data[0][d]; + var i = 0; + while (val === undefined && i < self.data.length) + val = self.data[++i][d]; + + //Check if value is a float or integer + //The text "NaN" (not case sensitive) counts as a float + if (!isNaN(val) || val.toUpperCase() === "NAN") { + if (isNaN(val) || !Number.isInteger(val)) + self.dimensionTypes[d] = CINEMA_COMPONENTS.DIMENSION_TYPE.FLOAT; + else + self.dimensionTypes[d] = CINEMA_COMPONENTS.DIMENSION_TYPE.INTEGER; + //Check if this dimension is listed in the filter + var filter = self.filter ? self.filter[d] : null + if (filter && (!Array.isArray(filter) || filter.length != 2)) { + console.warn("Filter for dimension '"+d+"' must be an array of length two.") + filter = null + } + //calculate domain for numeric dimension + var i;//the first index to contain a value that is not "NaN" + for (i = 0; i < self.data.length && isNaN(self.data[i][d]); i++) {} + if (i == self.data.length) + //if all values are NaN, domain is [0,0] + self.dimensionDomains[d] = [0,0] + else { + var min = self.data[i][d]; + var max = self.data[i][d]; + //Calculated min and max cannot extend outside of min and max + //defined in filter + if (filter) { + min = Math.max(min,filter[0]) + max = Math.min(max,filter[1]) + } + for (var j = i; j < self.data.length; j++) { + if (!isNaN(self.data[j][d])) { + //Ignore data that lies outside the min and max defined in the filter + if (filter && + (self.data[j][d] < filter[0] || self.data[j][d] > filter[1]) + ) { + filterdOut[j] = true; + continue; + } + min = Math.min(min,self.data[j][d]); + max = Math.max(max,self.data[j][d]); + } + } + self.dimensionDomains[d] = [min,max]; + } + } + //Anything else is a string type + else { + self.dimensionTypes[d] = CINEMA_COMPONENTS.DIMENSION_TYPE.STRING; + self.dimensionDomains[d] = self.data.map(function(p){return p[d];}); + } + });//end dimensions.foreach() + + //Remove any data that was marked to be filtered out while parsing + self.data = self.data.filter(function(d,i){return !filterdOut[i]}); + }; + + /** + * Reloads the database's CSV file and refreshes the data if changes have been made. + * If changes are found, sends an event through the dataUpdated dispatcher. + * By default, this will only check that the size of the CSV has changed (i.e. rows have + * been added or removed). Use the reloadAllData parameter to force an update of all data. + */ + CINEMA_COMPONENTS.Database.prototype.refreshData = function(reloadAllData) { + var self = this; + + if (reloadAllData) { + // Check all data in the file + getAndParseCSV(self.path, + function(data_arr, request) { + dataUpdateCallback(self, data_arr, request); + }, + self.errorCallback); + } + else { + // Only check for file size changes + var xhReq = new XMLHttpRequest(); + xhReq.open("HEAD", self.path, true);//HEAD request returns only Http response header + xhReq.onreadystatechange = function() { + if (xhReq.readyState === 4) { + if (xhReq.status === 200 || + //Safari returns 0 on success (while other browsers use 0 for an error) + (navigator.userAgent.match(/Safari/) && xhReq.status === 0) + ) { + //If contentLength is different, request the full file + //and update + var contentLength = xhReq.getResponseHeader('Content-Length'); + if (contentLength != self.prevContentLength) { + getAndParseCSV(self.path, + function(data_arr, request) { + dataUpdateCallback(self, data_arr, request); + }, + self.errorCallback); + } + } + } + } + + xhReq.send(null); + } + } + + /** + * Callback when getAndParseCSV returns a data array to update the data in the database. + * @param {object} self - The database object + * @param {string} data_arr = The data from the file (not yet error checked) + * @param {XMLHttpRequest} request = The request where we can get the response header information + */ + var dataUpdateCallback = function(self, data_arr, request) { + //Ensure that the dimensions have not changed + if (data_arr[0].length != self.dimensions.length) { + console.warn("Updates to data cannot change the number of dimensions!") + return; + } + for (var i in self.dimensions) { + if (self.dimensions[i] != data_arr[0][i]) { + console.warn("Updates to data cannot change the names of dimensions!") + return; + } + } + + //If there are errors in the data, don't update + var error = checkErrors(data_arr); + if (error) { + console.warn("Error in updated data!\n"+error); + return; + } + + // Get new content length + self.prevContentLength = request.getResponseHeader('Content-Length'); + + //Convert rows from arrays to objects + var newData = data_arr.slice(1).map(function(d) { + var obj = {}; + self.dimensions.forEach(function(p,i){obj[p] = d[i];}); + return obj; + }); + + // Determine whether there has been a change in the data + var updated = false; + var updateInfo = { added: [], modified: [], removed: [], oldData: self.data, oldDimensionDomains: self.dimensionDomains }; + for (var f = 0; f < self.data.length || f < newData.length; f++) { + if (f >= self.data.length) { + updateInfo.added.push(f); + updated = true; + } + else if (f >= newData.length) { + updateInfo.removed.push(f); + updated = true; + } + else if (!(JSON.stringify(self.data[f]) === JSON.stringify(newData[f])) ) { + updateInfo.modified.push(f); + updated = true; + } + } + + // If the data is updated, reset the dimensions and call the dataUpdated dispather. + if (updated) { + self.data = newData; + self.dimensionDomains = {}; + calcData(self, data_arr); + + self.dispatch.call("dataUpdated",self, updateInfo); + } + } + + /** + * Get data rows (returned as an array of indices) that are similar to the given data. + * Difference between two data points is measured as the Manhattan distance where each dimension + * is normalized. i.e. The sum of the differencs on each dimension (each scaled from 0 to 1). + * On string dimensions, the distance is considered 0 if the strings are the same, otherwise 1 + * NaN values have 0 distance from each other, but 1 from anything else + * undefined values 0 distance from each other, but 1 from defined values + * @param {Object} query - An object representing the data to compare against + * (it does not necessarily have to be a data point already in the database) + * (dimensions in query can be undefined and will not add to distance) + * @param {number} threshold - The value that the difference must be below to be considerd "similiar" + */ + CINEMA_COMPONENTS.Database.prototype.getSimilar = function(query, threshold) { + var self = this; + var similar = []; + this.data.forEach(function(row,index) { + var dist = 0; //manhattan distance + self.dimensions.forEach(function(d) { + if (query[d] !== undefined) { + //On string dimensions, the distance is considered 0 if the strings are the same, otherwise 1 + if (self.isStringDimension(d)) + dist += (row[d] == query[d] ? 0 : 1); + //Compare number dimensions + else { + //NaN values have 0 distance from each other, but 1 from anything else + if (isNaN(query[d])) + dist += (isNaN(row[d]) ? 0 : 1); + //undefined values 0 distance from each other, but 1 from defined values + else if (row[d] === undefined) + dist += 1; + //calculate normalized distance + else { + var extent = self.dimensionDomains[d]; + dist += Math.abs( + getNormalizedValue(query[d],extent[0],extent[1]) + - + getNormalizedValue(row[d],extent[0],extent[1]) + ); + } + } + } + });//end self.dimensions.forEach() + if (dist <= threshold) { + similar.push(index); + } + });//end this.data.forEach() + return similar; + } + + /** + * Parse this database's axis data from the given array of data (from axis_order.csv) + */ + var parseAxisOrderData = function(data_arr) { + var data = {}; + + data_arr.slice(1).forEach(function(row) { + var category = row[0]; + if (!data[category]) + data[category] = []; + var value = row[1]; + data[category].push({name: value}); + var ordering = data_arr[0].slice(2).map(function(d,i) { + return [row[i+2],i]; + }).sort(function(a,b) { + if (a[0] === undefined) {return 1;} + if (b[0] === undefined) {return -1;} + return a[0]-b[0]; + }).map(function(d) {return data_arr[0].slice(2)[d[1]];}); + data[category][data[category].length-1].order = ordering; + }); + + return data; + } + + /** + * Fetch a CSV file and parse the data into a two-dimensional array. + * @param {String} path URL of CSV file + * @param {Function} callback Callback if succesful, provides the data array and a reference + * to the XMLHttpRequest that retrieved it + * @param {Function} errorCallback Called if an error occured with the request + */ + var getAndParseCSV = function(path,callback,errorCallback) { + var request = new XMLHttpRequest(); + request.open("GET",path,true); + request.onreadystatechange = function() { + if (request.readyState === 4) { + if (request.status === 200 || + //Safari returns 0 on success (while other browsers use 0 for an error) + (navigator.userAgent.match(/Safari/) && request.status === 0) + ) { + var data = parseCSV(request.responseText); + if (callback) + callback(data, request); + } + else if (errorCallback) { + errorCallback(); + } + } + } + request.send(null); + } + + /** + * Get a value from 0 to 1 reprsenting where val lies between min and max + */ + var getNormalizedValue = function(val, min, max) { + return (max-min == 0) ? 0 : ((val-min) / (max-min)); + } + + /** + * Parse the text of a csv file into a 2 dimensional array. + * Distinguishes between empty strings and undefined values + * + * Based on example code from Ben Nadel + * https://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular-expression-command.htm + */ + var parseCSV = function(csvText) { + // (delimiter) (quoted value) (value) + var csvRegex = /(\,|\r?\n|\r|^)(?:"([^"]*(?:""[^"]*)*)"|([^\,\r\n]*))/gi; + var data = []; + var matches; + //If text is empty, stop now. Otherwise will get caught in infinite loop + if (csvText === "") + return data; + while (matches = csvRegex.exec(csvText)) { + //Newline,beginning of string, or a comma + var delimiter = matches[1]; + //If the value is in quotes, it will be here (without the outside quotes) + var quotedValue = matches[2]; + //If the value wasn't in quotes, it will be here + var value = matches[3]; + + //If the deilimiter is not a comma (meaning its a new line), + //add a row to the data + if (delimiter != ',') + data.push([]); + //If a quoted value, escape any pairs of quotes and add to data + if (quotedValue !== undefined) + data[data.length-1].push(quotedValue.replace(/""/g,"\"")); + //If an unquoted value, escape any pairs of quotes add to data, or undefined if empty + else + data[data.length-1].push(value === "" ? undefined : value.replace(/""/g,"\"")); + } + //If the last line is a single, undefined value (caused by a stray newline at the end of the file), remove it. + if (data.length > 1 && data[data.length-1].length == 1 && data[data.length-1][0] === undefined) { + data = data.slice(0,data.length-1); + } + return data; + } + + /** + * Check for critical errors in the given data. + * Returns an error message if an error was found. + * Doesn't return anything if no errors were found. + */ + var checkErrors = function(data) { + //Check that there are at least two lines of data + if (data.length < 2) + return "The first and second lines in the file are required."; + + //Check that there at least two dimensions to the data + if (data[0].length < 2) + return "The dataset must include at least two dimensions"; + + //Check that there are no empty values in the first row + var emptyValFound = false; + for (var i in data[0]) + emptyValFound = emptyValFound || (data[0][i] === undefined); + if (emptyValFound) + return "Empty values may not occur in the header (first line)."; + + //Check that all rows of data have the same length + var testLength = data[0].length; + for (var i in data) + if (data[i].length != testLength) + return "Each line must have an equal number of comma separated values (columns)."; + + //Check that no colummns have all undefined values + for (var i = 0; i < data[0].length; i++) { + var allEmpty = true; + for (var j = 0; j < data.length; j++) + allEmpty = allEmpty && (data[j][i] === undefined); + if (allEmpty) + return "There cannot be any columns with all undefined values."; + } + } + + /** + * Check for critical errors in the given axis data + * Checks against the given list of dimensions + * Returns an error message if an error was found. + * Doesn't return anything if no errors were found + */ + var checkAxisDataErrors = function(data, dimensions) { + //Check that there are at least two lines of data + if (data.length < 2) + return "The first and second lines in the file are required."; + + //Check that all rows of data have the same length + var testLength = data[0].length; + for (var i in data) + if (data[i].length != testLength) + return "Each line must have an equal number of comma separated values (columns)."; + + /*//Check that there are dimensions+2 columns (+2 for category and value columns) + if (data[0].length !== dimensions.length+2) + return "All dimensions must be specified in the header of the file."*/ + + //Check that each dimension in the header is valid + for (var i = 2; i < data[0].length; i++) { + if (!dimensions.includes(data[0][i])) + return "Dimension in axis order file '"+data[0][i]+"' is not valid"; + } + + //Check that the first two columns contain to undefined values + for (var i = 0; i < data.length; i++) { + if (data[i][0] === undefined) + return "Category cannot be undefined." + if (data[i][1] === undefined) + return "Value cannot be undefined." + } + + //Check that all other data are numbers + for (var i = 1; i < data.length; i++) { + for (var j = 2; j < data[i].length; j++) { + if (isNaN(data[i][j]) && data[i][j] !== undefined) + return "Values for dimensions cannot be NaN." + } + } + } + +})(); +'use strict'; +(function() { + /** + * CINEMA_COMPONENTS + * COMPONENT + * + * The Component module for the CINEMA_COMPONENTS library. + * Contiains the constructor for components (PcoordSVG,PcoordCanvas,Glyph, etc.) + * The object contains common methods and fields used by all components. + * + * Also contains definitions for a few classes that may be used by components. + * + * @exports CINEMA_COMPONENTS + * + * @author Cameron Tauxe + */ + + //If CINEMA_COMPONENTS is already defined, add to it, otherwise create it + var CINEMA_COMPONENTS = {} + if (window.CINEMA_COMPONENTS) + CINEMA_COMPONENTS = window.CINEMA_COMPONENTS; + else + window.CINEMA_COMPONENTS = CINEMA_COMPONENTS; + + //Require that the database module be included + if (!CINEMA_COMPONENTS.DATABASE_INCLUDED) + throw new Error("CINEMA_COMPONENTS Component module requires that Database"+ + " module be included. Please make sure that Database module"+ + " is included BEFORE Component module"); + + /** @type {boolean} - Flag to indicate that the Component module has been included */ + CINEMA_COMPONENTS.COMPONENT_INCLUDED = true; + + /** + * Abstract constructor for Component. + * Represents a component for displaying and interacting with a database. + * Objects such as Pcoord and Glyph inherit from this + * @param {DOM} parent - The DOM object to build this component inside of (all children will be removed) + * @param {CINEMA_COMPONENTS.Database} database - The database behind this component + * @param {RegExp} filterRegex - A regex to determine which dimensions to NOT show on the component + */ + CINEMA_COMPONENTS.Component = function(parent, database, filterRegex) { + if (this.constructor === CINEMA_COMPONENTS.Component) + throw new Error("Cannot instantiate abstract class 'Component.'"+ + " Please use a subclass."); + + /** @type {DOM} The parent DOM object to build this component inside of */ + this.parent = parent; + + //Clear children + this.parent.innerHTML = ''; + + /** @type {CINEMA_COMPONENTS.Database} A reference to the database behind this component */ + this.db = database; + /** @type {string[]} The filtered list of dimensions that are shown on the component */ + this.dimensions = []; + + //NOTE that this.dimensions is filtered to have only the dimensions shown on the component + //while this.db.dimensions includes all dimensions in the database + + /** @type {RegExp} The regex used to filter out dimensions to not be shown on the component*/ + this.filter = filterRegex; + + //Get filtered Dimensions according to filterRegex + this.dimensions = this.db.dimensions.filter(function(d) { + return filterRegex ? !filterRegex.test(d) : true; + }); + + //Create DOM content + /** @type {DOM} The whole content of the component*/ + this.container = parent.appendChild(document.createElement('div')); + this.container.setAttribute('class','CINEMA_COMPONENT'); + this.container.style.position = 'absolute'; + + CINEMA_COMPONENTS.Component.prototype.updateSize.call(this); + }; + + /** + * Resize this component to fit the size of its parent. + * This should be called every time the size of the component's + * parent changes. + */ + CINEMA_COMPONENTS.Component.prototype.updateSize = function(){ + this.margin = this.margin || new CINEMA_COMPONENTS.Margin(0,0,0,0); + this.parentRect = this.parent.getBoundingClientRect(); + this.internalWidth = this.parentRect.width - this.margin.left - this.margin.right; + this.internalHeight = this.parentRect.height - this.margin.top - this.margin.bottom; + + this.container.style.width = this.parentRect.width+'px'; + this.container.style.height = this.parentRect.height+'px'; + }; + + /** + * Remove this component from the scene + */ + CINEMA_COMPONENTS.Component.prototype.destroy = function() { + d3.select(this.container).remove(); + }; + + /** + * Constructor for Margin object + * Defines the top,right,bottom and left margins for drawing a component. + * @param {number} top - top margin (in pixels) + * @param {number} right - right margin (in pixels) + * @param {number} bottom - bottom margin (in pixels) + * @param {number} left - left margin (in pixels) + */ + CINEMA_COMPONENTS.Margin = function(top,right,bottom,left) { + this.top = top; + this.right = right; + this.bottom = bottom; + this.left = left; + } + + /** + * Constructor for ExtraData object + * Defines extra, custom data that may be shown on a component. + * @param {Object} data - The data to show + * (in the same format as the data points in the database) + * @param {any} style - Object representing how to draw the data. + * (the interpretation of this is up to specific components) + * (for example PcoordSVG expects a CSS string and + * PcoordCanvas expects an object with canvas context attributes) + */ + CINEMA_COMPONENTS.ExtraData = function(data, style) { + this.data = data; + this.style = style; + } +})();'use strict'; +(function() { + /** + * CINEMA_COMPONENTS + * GLYPH + * + * The Glyph Component for the CINEMA_COMPONENTS library. + * Contains the constructor for a Glyph component. + * The Glyph component allows for viewing one data point at a time in a glyph chart + * + * @exports CINEMA_COMPONENTS + * + * @author Cameron Tauxe + */ + + //If CINEMA_COMPONENTS is already defined, add to it, otherwise create it + var CINEMA_COMPONENTS = {} + if (window.CINEMA_COMPONENTS) + CINEMA_COMPONENTS = window.CINEMA_COMPONENTS; + else + window.CINEMA_COMPONENTS = CINEMA_COMPONENTS; + + //Require that the Component module be included + if (!CINEMA_COMPONENTS.COMPONENT_INCLUDED) + throw new Error("CINEMA_COMPONENTS Glyph module requires that Component"+ + " module be included. Please make sure that Component module"+ + " is included BEFORE Glyph module"); + + //Require that d3 be included + if (!window.d3) { + throw new Error("CINEMA_COMPONENTS Glyph module requires that"+ + " d3 be included (at least d3v4). Please make sure that d3 is included BEFORE the"+ + " the Glyph module"); + } + + /** @type {boolean} - Flag to indicate that the Glpyph module has been included */ + CINEMA_COMPONENTS.GLYPH_INCLUDED = true; + + //Constants + var RADTODEG = (180/Math.PI), + DEGTORAD = (Math.PI/180); + + CINEMA_COMPONENTS.Glyph = function(parent, database, filterRegex) { + var self = this; + + /*************************************** + * SIZING + ***************************************/ + + /** @type {CINEMA_COMPONENTS.Margin} Override default margin */ + this.margin = new CINEMA_COMPONENTS.Margin(50,50,50,50); + /** @type {number} the space between the center and lowest data values on the chart */ + this.innerMargin; + /** @type {number} The radius of the glyph */ + this.radius; + + //call super-constructor + CINEMA_COMPONENTS.Component.call(this,parent,database,filterRegex); + //after size is calculate in the super-constructor, set radius and innerMargin + this.radius = Math.min(this.internalHeight,this.internalWidth)/2; + this.innerMargin = this.radius/11; + + /*************************************** + * DATA + ***************************************/ + + /** @type {number} The index of the selected data point */ + this.selected = 0; + + /*************************************** + * SCALES + ***************************************/ + + /** @type {d3.scalePoint} Rotation scale. Maps dimensions to a rotation in radians */ + this.rotation = d3.scalePoint() + .domain(this.dimensions) + .range([0,Math.PI*2-Math.PI*2/(this.dimensions.length+1)]); + + /** @type {Object(d3.scale)} Scales for each dimension + * Maps a value to a distance from the center + */ + this.scales = {}; + this.dimensions.forEach(function(d) { + //Create point scale for string dimensions + if (self.db.isStringDimension(d)) + self.scales[d] = d3.scalePoint() + .domain(self.db.dimensionDomains[d]) + .range([self.radius-self.innerMargin,0]); + //Create linear scale for numeric dimensions + else + self.scales[d] = d3.scaleLinear() + .domain(self.db.dimensionDomains[d]) + .range([self.radius-self.innerMargin,0]); + }); + + /*************************************** + * DOM Content + ***************************************/ + + //Create DOM content + //Specify that this is a Glyph component + d3.select(this.container).classed('GLYPH',true); + + /** @type {d3.selection (svg)} The SVG element containing all the content of the component */ + this.svg = d3.select(this.container).append('svg') + .attr('class','glyphChart') + .attr('viewBox',(-this.margin.right)+' '+(-this.margin.top)+' '+ + (this.parentRect.width)+' '+ + (this.parentRect.height)) + .attr('preserveAspectRatio','none') + .attr('width','100%') + .attr('height','100%'); + + /** @type {d3.selection (path)} The path representing the selected data */ + this.path = this.svg.append('path') + .classed('glyph',true); + + /** @type {d3.selection g} Labels for each dimension */ + this.labels = self.svg.append('g') + .classed('labels',true) + .selectAll('g.label') + .data(this.dimensions) + .enter().append('g') + .classed('label',true) + .attr('transform',function(d){return self.getAxisTransform(d);}); + //Add label text + this.labels.append('text') + .style('text-anchor','middle') + .text(function(d){return d;}) + .attr('transform',function(d) { + return "translate(0 -15) " + +"rotate("+self.getTextRotation(d)+")"; + }); + + + /*************************************** + * AXES + ***************************************/ + + /** @type {d3.selection (g)} The SVG group containing all the axes */ + this.axisContainer = this.svg.append('g') + .classed('axisContainer',true); + + /** @type {d3.selection (g)} Groups for each axis*/ + this.axes = this.axisContainer.selectAll('.axisGroup') + .data(this.dimensions) + .enter().append('g') + .classed('axisGroup',true) + .attr('transform',function(d){return self.getAxisTransform(d);}); + //Create d3 axes + this.axes.append('g') + .classed('axis',true) + .each(function(d) { + d3.select(this).call(d3.axisLeft().scale(self.scales[d])); + d3.select(this).selectAll('text') + .style('text-anchor','end') + .attr('transform',"rotate("+self.getTextRotation(d)+" -15 0)"); + }); + + this.redraw(); + } + //establish prototype chain + CINEMA_COMPONENTS.Glyph.prototype = Object.create(CINEMA_COMPONENTS.Component.prototype); + CINEMA_COMPONENTS.Glyph.prototype.constructor = CINEMA_COMPONENTS.Glyph; + + /** + * Get the path (contents of the 'd' attribute) for the given data point + * @param {Object} p The data point + */ + CINEMA_COMPONENTS.Glyph.prototype.getPath = function(p) { + var self = this; + var path; + var startPoint; + this.dimensions.forEach(function(d,i) { + var point = self.getPoint(d,p); + if (i == 0) { + startPoint = point; + path = "M "+point.x+" "+point.y+" " + } + else if (i == self.dimensions.length-1) { + //loop back to the start point at the end to close the path + path += "L "+point.x+" "+point.y+" "+ + "L "+startPoint.x+" "+startPoint.y; + } + else { + path += "L "+point.x+" "+point.y+" "; + } + }); + return path; + } + + /** + * The x,y point on the chart where the given data point passes + * through the axis for the given dimension + * @param {string} d The dimension + * @param {Object} p The data point + */ + CINEMA_COMPONENTS.Glyph.prototype.getPoint = function(d,p) { + if (isNaN(p[d])) + //NaN values are placed in the center of the chart + return {x: this.radius, y: this.radius}; + var len = this.radius-this.scales[d](p[d]); + var rot = this.rotation(d)-Math.PI/2; + var x = Math.cos(rot)*len; + var y = Math.sin(rot)*len; + return {x: x+this.radius, y: y+this.radius}; + } + + /** + * Should be called every time the size of the chart's container changes. + * Updates the sizing and scaling of all parts of the chart and redraws + */ + CINEMA_COMPONENTS.Glyph.prototype.updateSize = function() { + var self = this; + + //Call super (will recalculate size) + CINEMA_COMPONENTS.Component.prototype.updateSize.call(this); + + //Update radius and innerMargin + this.radius = Math.min(this.internalHeight,this.internalWidth)/2; + this.innerMargin = this.radius/11; + + //Rescale SVG + this.svg.attr('viewBox',(-this.margin.right)+' '+(-this.margin.top)+' '+ + (this.parentRect.width)+' '+ + (this.parentRect.height)) + + //Rescale scales + this.dimensions.forEach(function (d) { + self.scales[d].range([self.radius-self.innerMargin,0]); + }); + + //Re-transform axes + this.axes.attr('transform',function(d){return self.getAxisTransform(d);}) + //Rebuild axes + .each(function(d) { + d3.select(this).select('.axis').call(d3.axisLeft().scale(self.scales[d])); + }); + + //Re-tranform labels + this.labels.attr('transform',function(d){return self.getAxisTransform(d);}); + + //Rebuild path + this.path.attr('d',function(d) {return self.getPath(self.db.data[d]);}); + }; + + /** + * Should be called whenever the data in the associated database changes. + * Will update scales, axes and selection to fit the new data. + */ + CINEMA_COMPONENTS.Glyph.prototype.updateData = function() { + var self = this; + + //Update scale domains + this.dimensions.forEach(function (d) { + self.scales[d].domain(self.db.dimensionDomains[d]); + }); + + //Rebuild axes + this.axes.each(function(d) { + d3.select(this).select('.axis').call(d3.axisLeft().scale(self.scales[d])); + }); + + this.redraw(); + } + + /** + * Set the selected data point to the one with the given index + */ + CINEMA_COMPONENTS.Glyph.prototype.setSelected = function(index) { + this.selected = index; + this.redraw(); + + }; + + /** + * Redraw the glyph path + */ + CINEMA_COMPONENTS.Glyph.prototype.redraw = function() { + var self = this; + this.path.datum(this.selected) + .transition(1000) + .attr('d',function(d){return self.getPath(self.db.data[d]);}); + } + + /** + * Get the transform attribute for an axis with the given dimension + * @param {string} d The dimension to transform to + */ + CINEMA_COMPONENTS.Glyph.prototype.getAxisTransform = function(d) { + var r = this.radius; + var rot = this.rotation(d)*RADTODEG; + return "translate("+r+") "+ + "rotate("+rot+" 0 "+r+")"; + }; + + /** + * Get the rotation (in degrees) for text on an axis with the given dimension + * so that the text will appear right-side-up + * @param {string} d The dimension to rotate for + */ + CINEMA_COMPONENTS.Glyph.prototype.getTextRotation = function(d) { + var rot = this.rotation(d)*(180/Math.PI); + return (rot > 90 && rot < 270) ? 180 : 0; + } + +})();'use strict'; +(function() { + /** + * CINEMA_COMPONENTS + * IMAGESPREAD + * + * The ImageSpread Component for the CINEMA_COMPONENTS library. + * Contains the constructor for the ImageSpread Component + * Which displays image data for a set of rows in a database. + * + * @exports CINEMA_COMPONENTS + * + * @author Cameron Tauxe + */ + + //If CINEMA_COMPONENTS is already defined, add to it, otherwise create it + var CINEMA_COMPONENTS = {} + if(window.CINEMA_COMPONENTS) + CINEMA_COMPONENTS = window.CINEMA_COMPONENTS; + else + window.CINEMA_COMPONENTS = CINEMA_COMPONENTS; + + //Require that the Component module be included + if(!CINEMA_COMPONENTS.COMPONENT_INCLUDED) + throw new Error("CINEMA_COMPONENTS ImageSpread module requires that Component" + + " module be included. Please make sure that Component module" + + " is included BEFORE ImageSpread module"); + + //Require that d3 be included + if(!window.d3) { + throw new Error("CINEMA_COMPONENTS ImageSpread module requires that" + + " d3 be included (at least d3v4). Please make sure that d3 is included BEFORE the" + + " the ImageSpread module"); + } + + /** @type {boolean} - Flag to indicate that the ImageSpread module has been included */ + CINEMA_COMPONENTS.IMAGE_SPREAD_INCLUDED = true; + + /** + * Checks if a dimension name starts with a string from the list + * @type {String} dimension - name of the dimension to check + * @type {Array} prefixList - list of prefixes + */ + var startsWithPrefixes = function(dimension, prefixList) { + if(typeof prefixList === 'undefined') + return false; + for(i = 0; i < prefixList.length; i++) { + if(dimension.startsWith(prefixList[i])) + return true; + } + return false; + } + + /** + * Constructor for ImageSpread Component + * Represents a component for viewing a spread of images from a selection of data + * @param {DOM} parent - The DOM object to build this component inside of + * @param {CINEMA_COMPONENTS.Database} database - The database behind this component + * (Note that ImageSpread does not use a filterRegex) + */ + CINEMA_COMPONENTS.ImageSpread = function(parent, database, image_measures, excluded_dimensions) { + var self = this; + + /*************************************** + * SIZING + ***************************************/ + + //Call super-constructor (will calculate size) + CINEMA_COMPONENTS.Component.call(this, parent, database); + + /*************************************** + * DATA + ***************************************/ + + //Allowed prefixes for image measures, check for unused beforehand + if(typeof image_measures !== 'undefined') { + this.allowedUPrefixes = []; + const image_measuresLength = image_measures.length; + for (var i = 0; i < image_measuresLength; i++) { + for (var key in self.db.dimensionTypes) { + if(key.startsWith(image_measures[i])) { + this.allowedUPrefixes.push(image_measures[i]); + break; + } + } + } + } + + //Excluded dimensions for x-axis + this.excludedDim = excluded_dimensions; + + //Get all non image measure and non file dimensions + this.validDim = []; + for(var i=0, len=self.dimensions.length; i < len; i++) { + if(!(self.dimensions[i].startsWith("FILE") || + startsWithPrefixes(self.dimensions[i], this.allowedUPrefixes) || + startsWithPrefixes(self.dimensions[i], this.excludedDim))) { + self.validDim.push(self.dimensions[i]); + } + } + + //override this.dimensions to include only FILE dimensions + this.dimensions = this.dimensions.filter(function(d) { + return (/^FILE/).test(d); + }); + /** @type {boolean} Whether any FILE dimensions exist in the dataset */ + this.hasFileDimensions = this.dimensions.length != 0; + + /** @type {number[]} Inidices of all the data points to display */ + this.selection = []; + + /** @type {number} The page number currently being viewed*/ + this.currentPage = 1; + + /*************************************** + * EVENTS + ***************************************/ + + /** @type {d3.dispatch} Hook for events on chart + * Set handlers with on() function. Ex: this.dispatch.on('mouseover',handlerFunction(i)) + * 'mouseover': Triggered when a set of images is moused over + * (arguments are the index of moused over data and mouse event) + */ + this.dispatch = d3.dispatch('mouseover'); + + /*************************************** + * DOM Content + ***************************************/ + + //Specify that this is an ImageSpread component + d3.select(this.container).classed('IMAGE_SPREAD', true); + + //If there are no file dimensions, place a warning and stop here + if(!this.hasFileDimensions) { + this.noFileWarning = d3.select(this.container).append('div') + .classed('noFileWarning', true) + .text("No file information to display"); + return; + } + + //NOTHING IN THE CONSTRUCTOR AFTER THIS POINT WILL BE EXECUTED + //IF THERE ARE NO FILE DIMENSIONS + + /** @type {d3.selection} The header/control panel */ + this.header = d3.select(this.container).append('div') + .classed('header', true) + .style('position', 'absolute') + .style('width', '100%'); + + /** @type {d3.selection} The container for all the images */ + this.imageContainer = d3.select(this.container).append('div') + .classed('imageContainer', true) + .style('position', 'absolute') + .style('width', '100%') + .style('overflow-y', 'auto'); + + /*************************************** + * HEADER/CONTROLS + ***************************************/ + + //pageSize controls + /** @type {d3.selection} The control panel for pageSize */ + this.pageSizeContainer = this.header.append('div') + .classed('controlPanel pageSize', true); + this.pageSizeContainer.append('span') + .classed('label', true) + .text("Results Per Page:"); + this.pageSizeContainer.append('br'); + /** @type {DOM (select)} The select node controlling page size */ + this.pageSizeNode = this.pageSizeContainer.append('select') + .on('change', function() { + self.updatePageNav(); + self.populateResults(); + }) + .node(); + //append options + d3.select(this.pageSizeNode).selectAll('option') + .data([10, 25, 50, 100]) + .enter().append('option') + .attr('value', function(d) { + return d; + }) + .text(function(d) { + return d; + }); + //Select 25 as default option + d3.select(this.pageSizeNode).select('option[value="25"]') + .attr('selected', 'true'); + + //sort controls + /** @type {d3.selection} The control panel for choosing sort dimension */ + this.sortContainer = this.header.append('div') + .classed('controlPanel sort', true); + this.sortContainer.append('span') + .classed('label', true) + .text("Sort By:"); + this.sortContainer.append('br'); + /** @type {DOM (select)} The select node controlling sort dimension */ + this.sortNode = this.sortContainer.append('select') + .on('change', function() { + self.selection.sort(self.getSortComparator()); + self.populateResults(); + }) + .node(); + //append options + d3.select(this.sortNode).selectAll('option') + .data(this.db.dimensions.filter(function(d) { + return !self.db.isStringDimension(d); + })) + .enter().append('option') + .attr('value', function(d) { + return d; + }) + .text(function(d) { + return d; + }); + + //sortOrder controls + /** @type {d3.selection} The control panel for toggling sort order */ + this.sortOrderContainer = this.header.append('div') + .classed('controlPanel sortOrder', true); + this.sortOrderContainer.append('span') + .classed('label', true) + .text("Reverse Sort Order:"); + this.sortOrderContainer.append('br'); + /** @type {DOM (input/checkbox)} The node for toggling sort order */ + this.sortOrderNode = this.sortOrderContainer.append('input') + .attr("type", "checkbox") + .on('change', function() { + self.selection.sort(self.getSortComparator()); + self.populateResults(); + }) + .node(); + + //grouping controls + /** @type {d3.selection} The control panel for toggling sort order */ + this.groupsortingContainer = this.header.append('div') + .classed('controlPanel groupingOption', true); + this.groupsortingContainer.append('span') + .classed('label', true) + .text("Group equal values:"); + this.groupsortingContainer.append('br'); + /** @type {DOM (input/checkbox)} The node for toggling grouping order */ + this.groupsortingNode = this.groupsortingContainer.append('input') + .attr('type', 'checkbox') + .on('change', function() { + self.selection.sort(self.getSortComparator()); + self.populateResults(); + }) + .node(); + + //imageSize controls + /** @type {d3.selection} The control panel for controlling image size */ + this.imageSizeContainer = this.header.append('div') + .classed('controlPanel imageSize', true); + this.imageSizeContainer.append('span') + .classed('label', true) + .text("Image Size: 150px"); + this.imageSizeContainer.append('br'); + /** @type {DOM (input/range)} The node for adjusting imageSize */ + this.imageSizeNode = this.imageSizeContainer.append('input') + .attr('type', 'range') + .attr('min', '100') + .attr('max', '500') + .on('input', function() { + d3.select(self.container).selectAll('.display') + .style('width', this.value + 'px'); + d3.select(self.container).select('.controlPanel.imageSize .label') + .text("Image Size: " + this.value + "px"); + }) + .node(); + this.imageSizeNode.value = 150; + + //Update size + this.updateSize(); + } + //establish prototype chain + CINEMA_COMPONENTS.ImageSpread.prototype = Object.create(CINEMA_COMPONENTS.Component.prototype); + CINEMA_COMPONENTS.ImageSpread.prototype.constructor = CINEMA_COMPONENTS.ImageSpread; + + /** + * Should be called every time the size of the component's container changes. + * Updates the sizing of the imageSpread container + */ + CINEMA_COMPONENTS.ImageSpread.prototype.updateSize = function() { + //Call super + CINEMA_COMPONENTS.Component.prototype.updateSize.call(this); + + if(this.hasFileDimensions) { + var headerSize = this.header.node().getBoundingClientRect().height; + this.imageContainer + .style('top', headerSize + 'px') + .style('height', (this.parentRect.height - headerSize) + 'px'); + } + }; + + /** + * Set the data to be shown to the data represented with the given array of indices + */ + CINEMA_COMPONENTS.ImageSpread.prototype.setSelection = function(indices) { + this.selection = indices; + this.selection.sort(this.getSortComparator()); + this.updatePageNav(); + this.populateResults(); + } + + /** + * Get a comparator function for sorting the selection + * according to selected sort dimension and the sortOrder checkbox + */ + CINEMA_COMPONENTS.ImageSpread.prototype.getSortComparator = function() { + var self = this; + var d = this.sortNode.value; + var checkedMultiplier = 1; + + if(this.sortOrderNode.checked) + checkedMultiplier = -1; + + //Group images with equal values, not looking at the sort dimension + //Then sort groups by the sorting dimension + if(this.groupsortingNode.checked) { + return function(a, b) { + if(self.db.data[a][d] === undefined) + return -1 * checkedMultiplier; + + if(self.db.data[b][d] === undefined) + return 1 * checkedMultiplier; + + if(isNaN(self.db.data[a][d])) + return -1 * checkedMultiplier; + + if(isNaN(self.db.data[b][d])) + return 1 * checkedMultiplier; + + //Get all vlid dimensions but the sorting dimension + const nonSortDimensions = self.validDim.filter(function(value) { + return value != d; + }); + //Grouping + for(var i = 0; i < nonSortDimensions.length; i += 1) { + if(self.db.data[a][nonSortDimensions[i]] == self.db.data[b][nonSortDimensions[i]]) { + continue; + } + else { + return (self.db.data[a][nonSortDimensions[i]] - self.db.data[b][nonSortDimensions[i]]) * checkedMultiplier; + } + } + //Equal non sorting dimensions, sort by sorting dimension + return (self.db.data[a][d] - self.db.data[b][d]) * checkedMultiplier; + } + } + //Only sort by sorting dimension + else { + return function(a, b) { + if(self.db.data[a][d] === undefined) + return -1 * checkedMultiplier; + + if(self.db.data[b][d] === undefined) + return 1 * checkedMultiplier; + + if(isNaN(self.db.data[a][d])) + return -1 * checkedMultiplier; + + if(isNaN(self.db.data[b][d])) + return 1 * checkedMultiplier; + + return (self.db.data[a][d] - self.db.data[b][d]) * checkedMultiplier; + } + } + } + + /** + * Fill the imageContainer with dataDisplays for the current page of results + */ + CINEMA_COMPONENTS.ImageSpread.prototype.populateResults = function() { + var self = this; + if(this.hasFileDimensions) { + var pageSize = this.pageSizeNode.value; + var pageData = this.selection.slice((this.currentPage - 1) * pageSize, + Math.min(this.currentPage * pageSize, this.selection.length)); + //Bind pageData and update dataDisplays + var displays = this.imageContainer.selectAll('.dataDisplay') + .data(pageData); + displays.exit().remove(); //remove unused dataDisplays + displays.enter() //add new dataDisplays + .append('div').classed('dataDisplay', true) + .merge(displays) //update + //Set up mouse events + .on('mouseenter', function(d) { + self.dispatch.call('mouseover', self, d, d3.event); + }) + .on('mouseleave', function(d) { + self.dispatch.call('mouseover', self, null, d3.event); + }) + //For each data display, create file displays for every file in it + .each(function(d) { + var files = self.dimensions.map(function(dimension) { + return self.db.data[d][dimension]; + }); + //bind files data + var fileDisplays = d3.select(this).selectAll('.fileDisplay') + .data(files); + fileDisplays.exit().remove(); + var ENTER = fileDisplays.enter().append('div') + .classed('fileDisplay', true); + ENTER.append('div').classed('display', true) + .style('width', self.imageSizeNode.value + 'px'); + ENTER.append('div').classed('displayLabel', true); + var UPDATE = ENTER.merge(fileDisplays) + //Create content of each file display + .each(function(f, i) { + d3.select(this).select('.display').html(''); + //Create an image in the display if the it is an image filetype + var ext = getFileExtension(f); + if(isValidFiletype(ext)) { + if(ext.toUpperCase() === 'VTI') { + d3.select(this).select('.display') + .classed('image', true) + .classed('text', false).append('img') + .attr('src', 'https://kitware.github.io/vtk-js/logo.svg') + .attr('width', '100%') + .on('click', function() {self.createModalVTI(self.db.directory + '/' + f);}); + } else if(ext.toUpperCase() === 'PDB') { + d3.select(this).select('.display') + .classed('image', true) + .classed('text', false).append('img') + .attr('src', 'https://kitware.github.io/vtk-js/logo.svg') + .attr('width', '100%') + .on('click', function() {self.createModalPDB(self.db.directory + '/' + f);}); + } else { + d3.select(this).select('.display') + .classed('image', true) + .classed('text', false) + .append('img') + .attr('src', self.db.directory + '/' + f) + .attr('width', '100%') + .on('click', self.createModalImg); + } + } + //Otherwise create an error message + else + d3.select(this).select('.display') + .classed('text', true) + .classed('image', false) + .append('div') + .attr('class', 'resultErrorText') + .text('Cannot display file: ' + f); + //Update label + d3.select(this).select('.displayLabel') + .text(self.dimensions[i]); + }); + }); + } + }; + + /** + * An event handler for an image that will create a modal overlay + * of the image when clicked + */ + CINEMA_COMPONENTS.ImageSpread.prototype.createModalImg = function() { + d3.select('body').append('div') + .attr('class', 'modalBackground') + .on('click', function() { + //clicking the modal removes it + d3.select(this).remove(); + }) + .append('img') + .attr('class', 'modalImg') + .attr('src', d3.select(this).attr('src')); + } + + /** + * An event handler for an image that will create a modal overlay + * of the image when clicked + */ + CINEMA_COMPONENTS.ImageSpread.prototype.createModalVTI = function(url) { + const rootContainer = d3.select('body'); + const backgroundContainer = d3.select('body').append('div'); + backgroundContainer.attr('class', 'modalBackground') + .on('click', function() { + //clicking the modal removes it + if(d3.event.target.tagName === 'IMG') { + d3.select(this).remove(); + } + }); + const container = backgroundContainer.append('div'); + container.attr('class', 'modalViewer').on('click', function() { + //clicking the modal removes it + //d3.select(this).remove(); + //d3.event.stopPropagation(); + }); + + var global = {}; + // ---------------------------------------------------------------------------- + // Standard rendering code setup + // ---------------------------------------------------------------------------- + + //const rootContainer = document.querySelector('body'); + const background = [0, 0, 0]; + const fullScreenRenderer = vtk.Rendering.Misc.vtkFullScreenRenderWindow.newInstance({ + background: background, + rootContainer: rootContainer.node(), + //containerStyle: { height: '100%' }, + container: container.node() + }); + const renderer = fullScreenRenderer.getRenderer(); + const renderWindow = fullScreenRenderer.getRenderWindow(); + + // ---------------------------------------------------------------------------- + // Example code + // ---------------------------------------------------------------------------- + + const reader = vtk.IO.Misc.vtkPDBReader.newInstance(); + const filter = vtk.Filters.General.vtkMoleculeToRepresentation.newInstance(); + const sphereMapper = vtk.Rendering.Core.vtkSphereMapper.newInstance(); + const stickMapper = vtk.Rendering.Core.vtkStickMapper.newInstance(); + const sphereActor = vtk.Rendering.Core.vtkActor.newInstance(); + const stickActor = vtk.Rendering.Core.vtkActor.newInstance(); + + const vtiReader = vtk.IO.XML.vtkXMLImageDataReader.newInstance(); + //vtiReader.parseAsArrayBuffer(fileContents); + + + filter.setInputConnection(reader.getOutputPort()); + //filter.setInputConnection(vtiReader.getOutputPort()); + filter.setHideElements(['H']); + + // render sphere + sphereMapper.setInputConnection(filter.getOutputPort(0)); + sphereMapper.setScaleArray(filter.getSphereScaleArrayName()); + sphereActor.setMapper(sphereMapper); + + // render sticks + stickMapper.setInputConnection(filter.getOutputPort(1)); + stickMapper.setScaleArray('stickScales'); + stickMapper.setOrientationArray('orientation'); + stickActor.setMapper(stickMapper); + + vtk.IO.Core.DataAccessHelper.get().fetchBinary(url, { + function(pe) { + console.log(pe); + }, + }).then((binary) => { + vtiReader.parseAsArrayBuffer(binary); + const source = vtiReader.getOutputData(0); + const mapper = vtk.Rendering.Core.vtkVolumeMapper.newInstance(); + const actor = vtk.Rendering.Core.vtkVolume.newInstance(); + + const dataArray = + source.getPointData().getScalars() || source.getPointData().getArrays()[0]; + const dataRange = dataArray.getRange(); + + const lookupTable = vtk.Rendering.Core.vtkColorTransferFunction.newInstance(); + const piecewiseFunction = vtk.Common.DataModel.vtkPiecewiseFunction.newInstance(); + + // Pipeline handling + actor.setMapper(mapper); + mapper.setInputData(source); + renderer.addActor(actor); + + // Configuration + const sampleDistance = + 0.7 * + Math.sqrt( + source + .getSpacing() + .map((v) => v * v) + .reduce((a, b) => a + b, 0) + ); + mapper.setSampleDistance(sampleDistance); + actor.getProperty().setRGBTransferFunction(0, lookupTable); + actor.getProperty().setScalarOpacity(0, piecewiseFunction); + // actor.getProperty().setInterpolationTypeToFastLinear(); + actor.getProperty().setInterpolationTypeToLinear(); + + // For better looking volume rendering + // - distance in world coordinates a scalar opacity of 1.0 + actor + .getProperty() + .setScalarOpacityUnitDistance( + 0, + vtk.Common.DataModel.vtkBoundingBox.getDiagonalLength(source.getBounds()) / + Math.max(...source.getDimensions()) + ); + // - control how we emphasize surface boundaries + // => max should be around the average gradient magnitude for the + // volume or maybe average plus one std dev of the gradient magnitude + // (adjusted for spacing, this is a world coordinate gradient, not a + // pixel gradient) + // => max hack: (dataRange[1] - dataRange[0]) * 0.05 + actor.getProperty().setGradientOpacityMinimumValue(0, 0); + actor + .getProperty() + .setGradientOpacityMaximumValue(0, (dataRange[1] - dataRange[0]) * 0.05); + // - Use shading based on gradient + actor.getProperty().setShade(true); + actor.getProperty().setUseGradientOpacity(0, true); + // - generic good default + actor.getProperty().setGradientOpacityMinimumOpacity(0, 0.0); + actor.getProperty().setGradientOpacityMaximumOpacity(0, 1.0); + actor.getProperty().setAmbient(0.2); + actor.getProperty().setDiffuse(0.7); + actor.getProperty().setSpecular(0.3); + actor.getProperty().setSpecularPower(8.0); + + // Control UI + const controllerWidget = vtk.Interaction.UI.vtkVolumeController.newInstance({ + size: [400, 150], + rescaleColorMap: true, + }); + const isBackgroundDark = background[0] + background[1] + background[2] < 1.5; + controllerWidget.setContainer(container.node()); + controllerWidget.setupContent(renderWindow, actor, isBackgroundDark); + fullScreenRenderer.setResizeCallback(({ + width, + height + }) => { + // 2px padding + 2x1px boder + 5px edge = 14 + if(width > 414) { + controllerWidget.setSize(400, 150); + } else { + controllerWidget.setSize(width - 14, 150); + } + controllerWidget.render(); + //fpsMonitor.update(); + }); + + // First render + renderer.resetCamera(); + renderWindow.render(); + + global.pipeline = { + actor, + renderer, + renderWindow, + lookupTable, + mapper, + source, + piecewiseFunction, + fullScreenRenderer, + }; + }); + } + /* .append('img') + .attr('class', 'modalImg') + .attr('src',d3.select(this).attr('src'));*/ + + + /** + * An event handler for an image that will create a modal overlay + * of the image when clicked + */ + CINEMA_COMPONENTS.ImageSpread.prototype.createModalPDB = function(url) { + const rootContainer = d3.select('body'); + const backgroundContainer = d3.select('body').append('div'); + backgroundContainer.attr('class', 'modalBackground') + .on('click', function() { + //clicking the modal removes it + if(d3.event.target.tagName === 'IMG') { + d3.select(this).remove(); + } + }); + const container = backgroundContainer.append('div'); + container.attr('class', 'modalViewer').on('click', function() { + //clicking the modal removes it + //d3.select(this).remove(); + //d3.event.stopPropagation(); + }); + + var global = {}; + // ---------------------------------------------------------------------------- + // Standard rendering code setup + // ---------------------------------------------------------------------------- + + //const rootContainer = document.querySelector('body'); + const background = [0, 0, 0]; + const fullScreenRenderer = vtk.Rendering.Misc.vtkFullScreenRenderWindow.newInstance({ + background: background, + rootContainer: rootContainer.node(), + //containerStyle: { height: '100%' }, + container: container.node() + }); + const renderer = fullScreenRenderer.getRenderer(); + const renderWindow = fullScreenRenderer.getRenderWindow(); + // ---------------------------------------------------------------------------- + // Example code + // ---------------------------------------------------------------------------- + + const reader = vtk.IO.Misc.vtkPDBReader.newInstance(); + const filter = vtk.Filters.General.vtkMoleculeToRepresentation.newInstance(); + const sphereMapper = vtk.Rendering.Core.vtkSphereMapper.newInstance(); + const stickMapper = vtk.Rendering.Core.vtkStickMapper.newInstance(); + const sphereActor = vtk.Rendering.Core.vtkActor.newInstance(); + const stickActor = vtk.Rendering.Core.vtkActor.newInstance(); + + + + + filter.setInputConnection(reader.getOutputPort()); + filter.setHideElements(['H']); + + // render sphere + sphereMapper.setInputConnection(filter.getOutputPort(0)); + sphereMapper.setScaleArray(filter.getSphereScaleArrayName()); + sphereActor.setMapper(sphereMapper); + + // render sticks + stickMapper.setInputConnection(filter.getOutputPort(1)); + stickMapper.setScaleArray('stickScales'); + stickMapper.setOrientationArray('orientation'); + stickActor.setMapper(stickMapper); + + // reader.setUrl(`${__BASE_PATH__}/data/molecule/pdb/caffeine.pdb`).then(() => { + reader.setUrl(url).then(() => { + renderer.resetCamera(); + renderWindow.render(); + }); + + renderer.addActor(sphereActor); + renderer.addActor(stickActor); + renderer.resetCamera(); + renderWindow.render(); + + // ----------------------------------------------------------- + // Make some variables global so that you can inspect and + // modify objects in your browser's developer console: + // ----------------------------------------------------------- + + global.reader = reader; + global.filter = filter; + global.sphereMapper = sphereMapper; + global.stickMapper = stickMapper; + global.sphereActor = sphereActor; + global.stickActor = stickActor; + global.renderer = renderer; + global.renderWindow = renderWindow; + } + + /** + * Calculate the number of pages needed to show all results and rebuild + * the page navigation widget. + */ + CINEMA_COMPONENTS.ImageSpread.prototype.updatePageNav = function() { + var self = this; + d3.select(this.container).select('.pageNavWrapper').remove(); //remove previous widget + var pageSize = this.pageSizeNode.value; + //If there are more results than can fit on one page, build a pageNav widget + if(this.selection.length > pageSize) { + //calculate number of pages needed + var numPages = Math.ceil(this.selection.length / pageSize); + //If the currently selected page is higher than the new number of pages, set to last page + if(this.currentPage > numPages) { + this.currentPage = numPages + }; + //Add pageNav and buttons + d3.select(this.container).append('div') + .classed('pageNavWrapper', true) + .append('ul') + .classed('pageNav', true) + .selectAll('li') + //Get data for which buttons to build, then build + .data(getPageButtons(numPages, this.currentPage)) + .enter().append('li') + .classed('pageButton', true) + .attr('mode', function(d) { + return d.page == self.currentPage ? 'selected' : 'default'; + }) + .text(function(d) { + return d.text; + }) + .on('click', function(d) { + if(d3.select(this).attr('mode') != 'selected') { + self.currentPage = d.page; + if(d.do_rebuild) { + self.updatePageNav(); + self.populateResults(); + } else { + d3.select(self.container).select('.pageButton[mode="selected"]') + .attr('mode', 'default'); + d3.select(this).attr('mode', 'selected'); + d3.select('.pageReadout').text(self.currentPage + " / " + numPages); + self.populateResults(); + } + } + }); + //Add readout of currentPage/totalPages + d3.select('.pageNavWrapper').append('div') + .classed('pageReadout', true) + .text(this.currentPage + " / " + numPages); + } //end if(this.selection.length > pageSize) + //Otherwise, don't build a widget and go to first (only) page + else { + this.currentPage = 1; + } + } + + /** + * Get the state of all inputs + */ + CINEMA_COMPONENTS.ImageSpread.prototype.getOptionsData = function() { + return { + pageSize: this.pageSizeNode.value, + sortDimension: this.sortNode.value, + sortOrderIsReversed: this.sortOrderNode.checked, + sortOrderIsGrouped: this.groupsortingNode.checked, + imageSize: this.imageSizeNode.value + }; + } + + /** + * Set the state of all inputs + */ + CINEMA_COMPONENTS.ImageSpread.prototype.setOptionsData = function(dataObject) { + d3.select(this.pageSizeNode).property("value", dataObject.pageSize); + d3.select(this.sortNode).property("value", dataObject.sortDimension); + d3.select(this.sortOrderNode).property("checked", dataObject.sortOrderIsReversed); + d3.select(this.groupsortingNode).property("checked", dataObject.sortOrderIsGrouped); + d3.select(this.imageSizeNode).property("value", dataObject.imageSize); + d3.select(this.container).select('.controlPanel.imageSize .label') + .text("Image Size: " + dataObject.imageSize + "px"); + } + + /** + * Given the number of pages needed and the currently selected page, return + * a list of objects represented the pageNav buttons to show + * objects are formatted like so: + * {text: [button_text], + * page: [pageNumber to link to], + * do_rebuild: [whether or not the pageNav widget should be rebuilt when this button is clicked]} + **/ + function getPageButtons(numPages, current) { + //If there are 7 or fewer pages, create a widget with a button for each page ([1|2|3|4|5|6|7]) + if(numPages <= 7) { + var pageData = []; + for (var i = 0; i < numPages; i++) + pageData.push({ + text: i + 1, + page: i + 1, + do_rebuild: false + }); + return pageData; + } + //Otherwise, create a widget with buttons for navigating relative to selected page ([|<|<<|10|20|30|>>|>|]) + else { + //step size is one order of magnitude below the total number of pages + var stepSize = Math.pow(10, Math.round(Math.log10(numPages) - 1)); + var pageData = []; + //Create buttons for selecting lower pages if current is not already one + if(current != 1) { + pageData.push({ + text: "|<", + page: 1, + do_rebuild: true + }); + pageData.push({ + text: "<", + page: current - 1, + do_rebuild: true + }); + var prevStep = current - stepSize >= 1 ? current - stepSize : current - 1; + pageData.push({ + text: prevStep, + page: prevStep, + do_rebuild: true + }); + } + //Create button for currently selected page + pageData.push({ + text: current, + page: current, + do_rebuild: false + }); + //Create buttons for selecting higher pages if current is not already at the end + if(current != numPages) { + var nextStep = current + stepSize <= numPages ? current + stepSize : current + 1; + pageData.push({ + text: nextStep, + page: nextStep, + do_rebuild: true + }); + pageData.push({ + text: ">", + page: current + 1, + do_rebuild: true + }); + pageData.push({ + text: ">|", + page: numPages, + do_rebuild: true + }); + } + return pageData; + } + } + + //Get if the given filetype is a valid image filetype + function isValidFiletype(type) { + if(!type) + return false; + var validFiletypes = ['JPG', 'JPEG', 'PNG', 'GIF', 'VTI', 'PDB']; + type = type.trimLeft().trimRight(); + var index = validFiletypes.indexOf(type.toUpperCase()); + + return (index >= 0); + } + + //Get the extension/filetype of the given path + function getFileExtension(path) { + return path ? path.substr(path.lastIndexOf('.') + 1).trimRight() : undefined; + } + +})(); +'use strict'; +(function() { + /** + * CINEMA_COMPONENTS + * PCOORD + * + * The Pcoord Component for the CINEMA_COMPONENTS library. + * Contains the constructor for Parallel Coordinates Components (e.g. PcoordSVG, PcoordCanvas) + * It is a sublcass of Component and contains methods and fields common to all Parallel Coordinates Components + * + * @exports CINEMA_COMPONENTS + * + * @author Cameron Tauxe + */ + + //If CINEMA_COMPONENTS is already defined, add to it, otherwise create it + var CINEMA_COMPONENTS = {} + if (window.CINEMA_COMPONENTS) + CINEMA_COMPONENTS = window.CINEMA_COMPONENTS; + else + window.CINEMA_COMPONENTS = CINEMA_COMPONENTS; + + //Require that the Component module be included + if (!CINEMA_COMPONENTS.COMPONENT_INCLUDED) + throw new Error("CINEMA_COMPONENTS Pcoord module requires that Component"+ + " module be included. Please make sure that Component module"+ + " is included BEFORE Pcoord module"); + + //Require that d3 be included + if (!window.d3) { + throw new Error("CINEMA_COMPONENTS Pcoord module requires that"+ + " d3 be included (at least d3v4). Please make sure that d3 is included BEFORE the"+ + " the Pcoord module"); + } + + /** @type {boolean} - Flag to indicate that the Pcoord module has been included */ + CINEMA_COMPONENTS.PCOORD_INCLUDED = true; + + /** + * Abstract constructor for Pcoord Components + * Represents a component for displaying and interacting with a database on a parallel coordinates chart + * Objects such as PcoordSVG and PcoordCanvas inherit from this + * @param {DOM} parent - The DOM object to build this component inside of + * @param {CINEMA_COMPONENTS.Database} database - The database behind this component + * @param {RegExp} filterRegex - A regex to determine which dimensions to NOT show on the component + */ + CINEMA_COMPONENTS.Pcoord = function(parent, database, filterRegex) { + if (this.constructor === CINEMA_COMPONENTS.Pcoord) + throw new Error("Cannot instantiate abstract class 'Pcoord'"+ + " Please use a subclass"); + + var self = this; + + /*************************************** + * SIZING + ***************************************/ + + /** @type {CINEMA_COMPONENTS.Margin} Override default margin */ + this.margin = new CINEMA_COMPONENTS.Margin(30,10,10,10); + /** @type {number} the room left at the bottom of the chart for NaN values */ + this.NaNMargin; + + //call super-constructor + CINEMA_COMPONENTS.Component.call(this,parent,database,filterRegex); + //after size is calculated in the super-constructor, Set NaNMargin + this.NaNMargin = this.internalHeight/11; + + /*************************************** + * DATA + ***************************************/ + + /** @type {number[]} Indices of all currently selected data */ + this.selection = d3.range(0,this.db.data.length); + /** @type {number} Indices of all currently highlighted data*/ + this.highlighted = []; + /** @type {CINEMA_COMPONENTS.ExtraData[]} Custom data to overlay on chart */ + this.overlayData = []; + + /*************************************** + * EVENTS + ***************************************/ + + /** @type {d3.dispatch} Hook for events on chart + * Set handlers with on() function. Ex: this.dispatch.on('click',handlerFunction(i)) + * 'selectionchange': Triggered when selection of data changes + * (called with array of indices of selected data) + * 'mouseover': Triggered when a path is moused over + * (called with index of moused over data and reference to mouse event) + * 'click': Triggered when a path is clicked on + * (called with index of clicked data and reference to mouse event) + * 'axisorderchange': Triggered when the axis ordering is manually changed + * (called with the list of the dimensions in the new order) + */ + this.dispatch = d3.dispatch("selectionchange", "mouseover", "click", "axisorderchange"); + + /*************************************** + * SCALES + ***************************************/ + + /** @type {d3.scalePoint} - Scale for x axis on chart + * Maps dimensions to position (in pixels) along width of chart.*/ + this.x = d3.scalePoint() + .domain(this.dimensions) + .range([0,this.internalWidth]) + .padding(1); + + /** @type {Object(d3.scale)} + * Scales for each dimension axis on the chart. One scale for each dimension */ + this.y = {}; + this.dimensions.forEach(function (d) { + //Create point scale for string dimensions + if (self.db.isStringDimension(d)) { + if (!self.y[d]) { + self.y[d] = d3.scalePoint(); + } + self.y[d].domain(self.db.dimensionDomains[d]) + .range([self.internalHeight,0]); + } + //Create linear scale for numeric dimensions + else { + if (!self.y[d]) { + self.y[d] = d3.scaleLinear(); + } + self.y[d].domain(self.db.dimensionDomains[d]) + .range([self.internalHeight-self.NaNMargin,0]); + } + }); + + /*************************************** + * DRAGGING + ***************************************/ + + /** @type {Object (numbers)} Keeps track of the x-position of each axis currently being dragged */ + this.dragging = {}; + + //Drag event handlers + this.axisDragStart = function(d) { + self.dragging[d] = self.x(d); + //Reorder axes such that the one being dragged is on top + self.axes.sort(function(a,b) { + if (a == d) return 1; + if (b == d) return -1; + return 0; + }); + }; + this.axisDrag = function(d) { + self.dragging[d] = Math.min(self.internalWidth,Math.max(0,d3.event.x)); + self.redrawPaths(); + var oldDimensions = self.dimensions.slice(); + self.dimensions.sort(function(a,b){ + return self.getXPosition(a)-self.getXPosition(b); + }); + if (!arraysEqual(oldDimensions,self.dimensions)) + self.dispatch.call('axisorderchange',self,self.dimensions); + self.x.domain(self.dimensions); + self.axes.attr('transform',function(d) { + return "translate("+self.getXPosition(d)+")"; + }); + }; + this.axisDragEnd = function(d) { + delete self.dragging[d]; + d3.select(this).attr('transform',"translate("+self.x(d)+")"); + //Reorder axes in DOM + self.axes.sort(function(a,b){ + return self.x(a) - self.x(b); + }); + self.redrawPaths(); + }; + + /** @type {d3.drag} */ + this.drag = d3.drag() + .subject(function(d){return {x: self.x(d)};}) + .on('start',this.axisDragStart) + .on('drag',this.axisDrag) + .on('end',this.axisDragEnd); + + /*************************************** + * BRUSHES + ***************************************/ + + /** @type {Object (Arrays)} Keeps track of the extents of the brush for each dimension*/ + this.brushExtents = {} + + /** @type {boolean} If true, don't update selection when brushes change */ + this.dontUpdateSelectionOnBrush = false; + + //Brush event handler + this.axisBrush = function(d) { + //If this is called due to an event (as opposed to manually called) + //update corresponding brush extent + if (d3.event != null) { + self.brushExtents[d] = d3.event.selection; + //Ignore brush if its start and end coordinates are the same + if (self.brushExtents[d] != null && self.brushExtents[d][0] === self.brushExtents[d][1]) + delete self.brushExtents[d]; + } + if (!self.dontUpdateSelectionOnBrush) + self.updateSelection(); + } + + /** @type {d3.brushY} The brushes for each axis */ + this.brush = d3.brushY() + .extent([[-8,0],[8,this.internalHeight]]) + .on('start', function(){d3.event.sourceEvent.stopPropagation();}) + .on('start brush',this.axisBrush); + + /*************************************** + * DOM Content + ***************************************/ + + //Create DOM content + //Specify that this is a Pcoord component + d3.select(this.container).classed('PCOORD',true); + /** @type {d3.selection} Where the paths for the chart will be drawn + * The actual drawing of paths depends on the specific Pcoord subclass + */ + this.pathContainer = d3.select(this.container).append('div') + .classed('pathContainer',true) + .style('position','absolute') + .style('width',this.parentRect.width+'px') + .style('height',this.parentRect.height+'px'); + + /** @type {boolean} Indicates if the lines on the chart should be smooth(curved) or not + * Be sure to call redrawPaths() after changing this so it takes effect + */ + this.smoothPaths = true; + + /*************************************** + * AXES + ***************************************/ + + /** @type {d3.selection} The container for all axes (as an svg object) */ + this.axisContainer = d3.select(this.container).append('svg') + .classed('axisContainer',true) + .style('position','absolute') + .attr('viewBox',(-this.margin.right)+' '+(-this.margin.top)+' '+ + (this.parentRect.width)+' '+ + (this.parentRect.height)) + .attr('preserveAspectRatio','none') + .attr('width','100%') + .attr('height','100%') + //disable pointer events on axisContainer so it doesn't block pathContainer + .style('pointer-events','none'); + /** @type {d3.selction} Groups for each axis */ + this.axes = this.axisContainer.selectAll('.axisGroup') + .data(this.dimensions) + .enter().append('g') + .classed('axisGroup',true) + .attr('dimension',function(d){return d;}) + .attr('transform', function(d) { + return "translate("+self.x(d)+")"; + }) + .call(this.drag) + //Add d3 axes to each axis group + this.axes.append('g') + .classed('axis',true) + .each(function(d) { + d3.select(this).call(d3.axisLeft().scale(self.y[d])); + if (!self.db.isStringDimension(d)) + self.addNaNExtensionToAxis(this); + }); + var labels = this.axes.append('g') + .classed('axisLabel',true) + //allow pointer-events on axisLabel so axes can be dragged + .style('pointer-events','initial') + //add text to each label + labels.append('text') + .style('text-anchor','middle') + .attr('y',-9) + .text(function(d){return d;}); + //prepend background rectangle to each label + labels.insert('rect',':first-child') + //each background is bound to their corresponding text's + //bounding box as data + .data(function() { + var boxes = []; + labels.selectAll('text').each(function(){ + boxes.push(this.getBBox()); + }); + return boxes; + }) + .attr('x',function(d){return d.x + 3;}) + .attr('y',function(d){return d.y;}) + .attr('width',function(d){return d.width - 6;}) + .attr('height',function(d){return d.height;}); + //Add brush group to each axis group + this.axes.append('g') + .classed('brush',true) + .each(function(){d3.select(this).call(self.brush);}); + + }; + //establish prototype chain + CINEMA_COMPONENTS.Pcoord.prototype = Object.create(CINEMA_COMPONENTS.Component.prototype); + CINEMA_COMPONENTS.Pcoord.prototype.constructor = CINEMA_COMPONENTS.Pcoord; + + /** + * Add an additional line segment and tick to the end of an axis to represent the area + * for NaN values. + * @param {DOM} node - The DOM node for the svg group containing the axis (g.axis) + */ + CINEMA_COMPONENTS.Pcoord.prototype.addNaNExtensionToAxis = function(node) { + d3.select(node).append('path') + .attr('class','NaNExtension') + .attr('d',"M0.5,"+String(this.internalHeight-this.NaNMargin+0.5)+"V"+String(this.internalHeight-0.5)); + var NaNTick = d3.select(node).append('g') + .attr('class','NaNExtensionTick') + .attr('transform',"translate(0,"+String(this.internalHeight-0.5)+")"); + NaNTick.append('line') + .attr('x2','-6'); + NaNTick.append('text') + .attr('x','-9') + .attr('dy','0.32em') + .text('NaN'); + } + + /** + * Should be called every time the size of the chart's container changes. + * Updates the sizing and scaling of all parts of the chart and redraws + */ + CINEMA_COMPONENTS.Pcoord.prototype.updateSize = function() { + var self = this; + var oldHeight = this.internalHeight;//old height needed to rescale brushes + + //Call super (will recalculate size) + CINEMA_COMPONENTS.Component.prototype.updateSize.call(this); + + //update NaNMargin + this.NaNMargin = this.internalHeight/11; + + //update PathContainer size + this.pathContainer + .style('width',this.parentRect.width+'px') + .style('height',this.parentRect.height+'px'); + + //Rescale x + this.x.range([0,this.internalWidth]); + + //Rescale y scales + this.dimensions.forEach(function(d) { + self.y[d].range([self.db.isStringDimension(d) ? self.internalHeight : self.internalHeight-self.NaNMargin, 0]); + }); + + this.redrawPaths(); + + //Reposition and rescale axes + this.axisContainer + .attr('viewBox',(-this.margin.right)+' '+(-this.margin.top)+' '+ + (this.parentRect.width)+' '+ + (this.parentRect.height)); + this.axes.attr("transform", function(d) { + return "translate("+self.getXPosition(d)+")"; + }); + this.axes.each(function(d) { + d3.select(this).select('.axis').call(d3.axisLeft().scale(self.y[d])); + //if scale is linear, then update the NaN extension on the axis + if (!self.db.isStringDimension(d)) { + d3.select(this).select('path.NaNExtension') + .attr('d',"M0.5,"+String(self.internalHeight-self.NaNMargin+0.5)+"V"+String(self.internalHeight-0.5)); + d3.select(this).select('.NaNExtensionTick') + .attr('transform',"translate(0,"+String(self.internalHeight-0.5)+")"); + } + }); + + //Redraw brushes + this.dontUpdateSelectionOnBrush = true; //avoid updating selection when resizing brushes + this.brush.extent([[-8,0],[8,this.internalHeight]]); + this.axes.selectAll('g.brush').each(function(d) { + d3.select(this).call(self.brush); + d3.select(this).call(self.brush.move, function() { + if (self.brushExtents[d] == null) + return null; + + return self.brushExtents[d].map(function(i) { + return i/oldHeight * self.internalHeight; + }); + }); + }); + this.dontUpdateSelectionOnBrush = false; + } + + /** + * Should be called whenever the data in the associated database changes. + * Will update scales, axes and selection to fit the new data. + */ + CINEMA_COMPONENTS.Pcoord.prototype.updateData = function() { + var self = this; + + //Update scale domains + this.dimensions.forEach(function(d){ + self.y[d].domain(self.db.dimensionDomains[d]); + }); + + //Rebuild axes + this.axes.each(function(d) { + d3.select(this).select('.axis').call(d3.axisLeft().scale(self.y[d])); + }); + + this.updateSelection(true); + } + + /** + * Called whenever a brush changes the selection + * Updates selection to hold the indices of all data points that are + * selected by the brushes. + * @param {bool} force - If true, selectionchange event will be triggered + * and paths will be redrawn even if the set the of selected points did + * not change. + */ + CINEMA_COMPONENTS.Pcoord.prototype.updateSelection = function(force) { + var self = this; + var newSelection = []; + this.db.data.forEach(function(d,i) { + var selected = true; + for (var p in self.dimensions) { + var extent = self.brushExtents[self.dimensions[p]]; + if (extent) { + var y = self.getYPosition(self.dimensions[p],d); + selected = selected && extent[0] <= y && y <= extent[1]; + if (!selected) + break; + } + } + if (selected) + newSelection.push(i); + }); + if (!arraysEqual(this.selection,newSelection) || force) { + this.selection = newSelection; + this.dispatch.call("selectionchange",this, this.selection.slice()); + this.redrawSelectedPaths(); + } + } + + /** + * Set the indices of the currently highlighted data + */ + CINEMA_COMPONENTS.Pcoord.prototype.setHighlightedPaths = function(indices) { + this.highlighted = indices; + this.redrawHighlightedPaths(); + } + + /** + * Set the current overlay paths + */ + CINEMA_COMPONENTS.Pcoord.prototype.setOverlayPaths = function(data) { + this.overlayData = data; + this.redrawOverlayPaths(); + }; + + //Shortcut function for redrawSelectedPaths, redrawHighlightedPath, redrawOverlayPaths + CINEMA_COMPONENTS.Pcoord.prototype.redrawPaths = function() { + this.redrawSelectedPaths(); + this.redrawHighlightedPaths(); + this.redrawOverlayPaths(); + } + + /** + * Set the chart's selection to encapsulate the data represented by + * the given array of indices + */ + CINEMA_COMPONENTS.Pcoord.prototype.setSelection = function(selection) { + var ranges = {}; + var self = this; + console.log(selection); + this.dimensions.forEach(function(d) { + ranges[d] = d3.extent(selection, function(i) { + return self.getYPosition(d, self.db.data[i]); + }); + }); + this.axes.selectAll('g.brush') + .each(function(d) { + d3.select(this).call(self.brush.move, function() { + return [ranges[d][0]-5,ranges[d][1]+5]; + }); + }); + //call brush event handler + this.axisBrush(); + } + + /** + * Set the chart's selection to match the ranges defined in the given + * filter. + * @param {Object} filter Object defining the filter. Each key is the name + * of numeric dimension and each value is a 2-length array containing the minimum + * and maximum values. + */ + CINEMA_COMPONENTS.Pcoord.prototype.filterSelection = function(filter) { + var self = this; + this.dimensions.forEach(function(d) { + //get filter for this particular dimension 'f' + var f = filter ? filter[d] : null + if (f && Array.isArray(f) && f.length == 2 && !isNaN(f[0]) && !isNaN(f[1])) { + //clamp range to bounds of chart + var range = [ + Math.max(self.y[d](f[1]),0), + Math.min(self.y[d](f[0]),self.internalHeight) + ] + self.axisContainer.select('.axisGroup[dimension='+d+']').select('g.brush') + .call(self.brush.move, function() {return range;}) + } + }); + //call brush event handler + this.axisBrush(); + } + + /** + * Reorder the axes to the order given + */ + CINEMA_COMPONENTS.Pcoord.prototype.setAxisOrder = function(order) { + var self = this; + //filter out dimensions in order, but not in chart's dimensions + var order = order.filter(function(d) { + return self.dimensions.includes(d); + }); + //Add any dimensions in chart's dimensions but not in order + this.dimensions.forEach(function(d) { + if (!order.includes[d]) + order.push(d); + }); + //update domain + this.x.domain(order); + //update dimensions list + self.dimensions.sort(function(a,b){ + return self.getXPosition(a)-self.getXPosition(b); + }); + //update axes + this.axes.attr('transform',function(d) { + return "translate("+self.getXPosition(d)+")"; + }); + //Reorder axes in DOM + self.axes.sort(function(a,b){ + return self.x(a) - self.x(b); + }); + //redraw + this.redrawPaths(); + } + + /** + * Redraw the current selection of paths. + * Actual implementation is up to specific subclasses + */ + CINEMA_COMPONENTS.Pcoord.prototype.redrawSelectedPaths = function() { + throw new Error("Cannot call abstract function 'redrawSelectedPaths()'!"+ + " Please override function in a subclass"); + } + + /** + * Redraw the currently highlighted path. + * Actual implementation is up to specific subclasses + */ + CINEMA_COMPONENTS.Pcoord.prototype.redrawHighlightedPaths = function() { + throw new Error("Cannot call abstract function 'redrawHighlightedPaths()'!"+ + " Please override function in a subclass"); + } + + /** + * Redraw the overlay paths. + * Actual implementation is up to specific subclasses + */ + CINEMA_COMPONENTS.Pcoord.prototype.redrawOverlayPaths = function() { + throw new Error("Cannot call abstract function 'redrawOverlayPaths()'!"+ + " Please override function in a subclass"); + } + + /** + * Get the path (the contents of the 'd' attribute) for the path + * represented by the given data point. + * Draws a physical break in the path where values are undefined. + * @param {Object} d The data point to base the path off + */ + CINEMA_COMPONENTS.Pcoord.prototype.getPath = function(d) { + var self = this; + var curveLength = this.smoothPaths ? this.internalWidth/this.dimensions.length/3 : 0; + var singleSegmentLength = this.internalWidth/this.dimensions.length/5; + var path = ''; + + //Split dimensions into sections deliminated by undefined values + var sections = []; + var currentSection = []; + this.dimensions.forEach(function(p) { + if (d[p] != undefined) { + currentSection.push(p); + } + else if (currentSection.length != 0) { + sections.push(currentSection.slice()); + currentSection = []; + } + }); + if (currentSection.length > 0) + sections.push(currentSection.slice()); + + //Draw individual sections + sections.forEach(function(section) { + //If a section contains only one dimension, draw a short line across the axis + if (section.length == 1) { + var p = section[0]; + var x = self.getXPosition(p); + var y = self.getYPosition(p,d); + path += ('M '+(x-singleSegmentLength/2)+' '+y+' L ')+ + ((x+singleSegmentLength/2)+' '+y); + } + else { + section.forEach(function (p,i) { + var x = self.getXPosition(p); + var y = self.getYPosition(p,d); + if (i == 0) {//beginning of path + path += ('M '+x+' '+y+' C ')+ + ((x+curveLength)+' '+y+' '); + } + else if (i == section.length-1) {//end of path + path += ((x-curveLength)+' '+y+' ')+ + (x+' '+y+' '); + } + else {//midpoints + path += ((x-curveLength)+' '+y+' ')+ + (x+' '+y+' ')+ + ((x+curveLength)+' '+y+' '); + } + }); + } + }); + return path; + } + + /** + * Get the x-coordinate of the axis representing the given dimension + * @param {string} d - The dimension to get the x-coordinate for + */ + CINEMA_COMPONENTS.Pcoord.prototype.getXPosition = function(d) { + var v = this.dragging[d]; + return v == null ? this.x(d) : v; + }; + + /** + * Get the y-coordinate of the line for data point p on dimension d + * @param {string} d - The dimension on the data point + * @param {Object} p - The data point + */ + CINEMA_COMPONENTS.Pcoord.prototype.getYPosition = function(d, p) { + if (!this.db.isStringDimension(d) && isNaN(p[d])) + //If the value is NaN on a linear scale, return internalHeight as the position + //(to place the line on the NaN tick) + return this.internalHeight; + return this.y[d](p[d]); + } + + /** + * Get the y-coordinate of the line for data point p on dimension d + * @param {Object} dimObject - dimension / startDate / endDate selected} + */ + CINEMA_COMPONENTS.Pcoord.prototype.addSelectionByDimensionValues = function(dimObject) { + var self = this; + + //Get pixel values of given dates + var startpx = this.y[dimObject.dimension](dimObject.startDate) + var endpx = this.y[dimObject.dimension](dimObject.endDate) + + //avoid 0px selection + if(startpx === endpx) { + startpx += 1; + endpx -= 1; + } + + //Check if inside boundary + var range = [ + Math.min(endpx,self.internalHeight), + Math.max(startpx,0) + ] + + //Set selection + self.axisContainer + .select('.axisGroup[dimension='+dimObject.dimension+']') + .select('g.brush') + .call(self.brush.move, function() {return range;}); + } + + /** + * Convenience function to compare arrays + * (used to compare the selection to the previous one) + */ + function arraysEqual(a, b) { + if (a === b) return true; + if (a == null || b == null) return false; + if (a.length != b.length) return false; + + for (var i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) return false; + } + return true; + } + +})(); +'use strict'; +(function() { + /** + * CINEMA_COMPONENTS + * PCOORD_CANVAS + * + * The PcoordSVG Component for the CINEMA_COMPONENTS library. + * Contains the constructor for the PcoordCanvas component: + * A subclass of Pcoord which draws a Paralell Coordinates chart using canvas elements. + * + * @exports CINEMA_COMPONENTS + * + * @author Cameron Tauxe + */ + + //If CINEMA_COMPONENTS is already defined, add to it, otherwise create it + var CINEMA_COMPONENTS = {} + if (window.CINEMA_COMPONENTS) + CINEMA_COMPONENTS = window.CINEMA_COMPONENTS; + else + window.CINEMA_COMPONENTS = CINEMA_COMPONENTS; + + //Require that the Pcoord Component be included + if (!CINEMA_COMPONENTS.PCOORD_INCLUDED) + throw new Error("CINEMA_COMPONENTS PcoordCanvas Component requires that Pcoord"+ + " component be included. Please make sure that Pcoord component"+ + " is included BEFORE PcoordCanvas module"); + + /** @type {boolean} - Flag to indicate that the PcoordCanvas Component has been included */ + CINEMA_COMPONENTS.PCOORD_CANVAS_INCLUDED = true; + + /** + * Constructor for PcoordCanvas Component + * Represents a component for displaying and interacting with a database on a parallel coordinates chart + * rendered with canvas elements + * @param {DOM} parent - The DOM object to build this component inside of + * @param {CINEMA_COMPONENTS.Database} database - The database behind this component + * @param {RegExp} filterRegex - A regex to determine which dimensions to NOT show on the component + */ + CINEMA_COMPONENTS.PcoordCanvas = function(parent, database, filterRegex) { + var self = this; + //call super-constructor + CINEMA_COMPONENTS.Pcoord.call(this,parent,database,filterRegex); + + //Specify that this is a Pcoord Canvas component + d3.select(this.container).classed('CANVAS',true); + + //Add canvases to pathContainer + this.selectedCanvas = this.pathContainer.append('canvas') + .classed('selectedCanvas',true) + .node(); + this.highlightedCanvas = this.pathContainer.append('canvas') + .classed('highlightedCanvas',true) + .node(); + this.overlayCanvas = this.pathContainer.append('canvas') + .classed('overlayCanvas',true) + .node(); + //Index canvas is invisible and draws in a unique color for each path + //Its color data is used to determine which path is being moused over + this.indexCanvas = this.pathContainer.append('canvas') + .classed('indexCanvas',true) + .style('display','none') + .node(); + //Size/position canvases + this.pathContainer.selectAll('canvas') + .style('position','absolute') + .style('top',this.margin.top+'px') + .style('left',this.margin.left+'px'); + + //Determine screen DPI to rescale canvas contexts + //(prevents artifacts and blurring on some displays) + //https://stackoverflow.com/a/15666143/2827258 + this.pixelRatio = (function() { + var ctx = document.createElement('canvas').getContext("2d"), + dpr = window.devicePixelRatio || 1, + bsr = ctx.webkitBackingStorePixelRatio || + ctx.mozBackingStorePixelRatio || + ctx.msBackingStorePixelRatio || + ctx.oBackingStorePixelRatio || + ctx.backingStorePixelRatio || 1; + return dpr / bsr; + })(); + + //Loading/still drawing indicator + this.loading = d3.select(this.container).append('div') + .classed('loadingIndicator',true) + .style('display','none') + .text('Drawing...'); + + //Set an interval to call drawIterator if it exists + //roughly 60 times a second + this.interval = setInterval(function(self) { + for (var i = 0; i < 25; i++) { + if (self.drawIterator) { + if (self.drawIterator.next().done) { + self.drawIterator = undefined; + self.loading.style('display','none'); + } + } + } + }, 16, this); + + //Set up mousemove listener to get moused-over paths + this.lastMouseMove = null; //remember last result, to prevent excessive dispatch calls + this.pathContainer.on('mousemove', function() { + var x = d3.mouse(self.selectedCanvas)[0]*self.pixelRatio; + var y = d3.mouse(self.selectedCanvas)[1]*self.pixelRatio; + if (x >= 0 && y >= 0) { + var index = getIndexAtPoint(x,y,self.indexCanvas); + if (index != -1) { + if (self.lastMouseMove != self.selection[index]) { + self.lastMouseMove = self.selection[index]; + self.dispatch.call('mouseover',self,self.selection[index],d3.event); + } + } + else { + if (self.lastMouseMove !== null) { + self.lastMouseMove = null; + self.dispatch.call('mouseover',self,null,d3.event); + } + } + } + }); + + this.updateSize(); + } + //establish prototype chain + CINEMA_COMPONENTS.PcoordCanvas.prototype = Object.create(CINEMA_COMPONENTS.Pcoord.prototype); + CINEMA_COMPONENTS.PcoordCanvas.prototype.constructor = CINEMA_COMPONENTS.PcoordCanvas; + + /************************** + * OVERRIDE METHODS + **************************/ + + CINEMA_COMPONENTS.PcoordCanvas.prototype.updateSize = function() { + var self = this; + //call super + CINEMA_COMPONENTS.Pcoord.prototype.updateSize.call(this); + + //Resize canvases + this.pathContainer.selectAll('canvas') + .style('width',this.internalWidth+'px') + .style('height',this.internalHeight+'px') + // width/height styles are distinct from attributes + // (attributes determine context size, style is the size the canvas appears in on screen) + .attr('width',this.internalWidth*this.pixelRatio+'px') + .attr('height',this.internalHeight*this.pixelRatio+'px') + .each(function(){ + this.getContext('2d').scale(self.pixelRatio,self.pixelRatio); + }); + //Init canvas contexts + var selectedContext = this.selectedCanvas.getContext('2d'); + selectedContext.strokeStyle = 'lightgray'; + selectedContext.globalAlpha = 0.3; + selectedContext.lineWidth = 2; + var highlightedContext = this.highlightedCanvas.getContext('2d'); + highlightedContext.strokeStyle = 'lightskyblue'; + highlightedContext.lineWidth = 4; + var indexContext = this.indexCanvas.getContext('2d'); + indexContext.lineWidth = 3; + + this.redrawPaths(); + } + + /** + * Redraw the current selection of paths. + */ + CINEMA_COMPONENTS.PcoordCanvas.prototype.redrawSelectedPaths = function() { + var self = this; + + var ctx = this.selectedCanvas.getContext('2d'); + ctx.clearRect(0,0,this.internalWidth,this.internalHeight); + + var indexCtx = this.indexCanvas.getContext('2d'); + indexCtx.clearRect(0,0,this.internalWidth,this.internalHeight); + + this.drawIterator = (function*(queue){ + self.loading.style('display','initial'); + var i = 0; + while (i < queue.length) { + var path = new Path2D(self.getPath(self.db.data[queue[i]])); + ctx.stroke(path); + + indexCtx.strokeStyle = indexToColor(i); + indexCtx.stroke(path); + + yield ++i; + } + })(this.selection); + } + + /** + * Redraw the currently highlighted path. + */ + CINEMA_COMPONENTS.PcoordCanvas.prototype.redrawHighlightedPaths = function() { + var self = this; + + var ctx = this.highlightedCanvas.getContext('2d'); + ctx.clearRect(0,0,this.internalWidth,this.internalHeight); + + this.highlighted.forEach(function(d) { + var path = new Path2D(self.getPath(self.db.data[d])); + ctx.stroke(path); + }); + } + + /** + * Redraw the overlay paths. + */ + CINEMA_COMPONENTS.PcoordCanvas.prototype.redrawOverlayPaths = function() { + var self = this; + + var ctx = this.overlayCanvas.getContext('2d'); + ctx.clearRect(0,0,this.internalWidth,this.internalHeight); + + this.overlayData.forEach(function(d) { + //Parse style + ctx.lineWidth = d.style.lineWidth || 1; + ctx.lineCap = d.style.lineCap || 'butt'; + ctx.lineJoin = d.style.lineJoin || 'miter'; + ctx.miterLimit = d.style.miterLimit || 10; + ctx.strokeStyle = d.style.strokeStyle || 'black'; + if (d.style.lineDash) + ctx.setLineDash(d.style.lineDash); + else + ctx.setLineDash([]); + //Draw line + var path = new Path2D(self.getPath(d.data)); + ctx.stroke(path); + }) + } + + /** + * Override destroy() to also clear interval + */ + CINEMA_COMPONENTS.PcoordCanvas.prototype.destroy = function() { + clearInterval(this.interval); + //Call super + CINEMA_COMPONENTS.Component.prototype.destroy.call(this); + } + + //Get the index of the path at the given point + //using the colors on the index canvas + //returns -1 if there is no path, or the area around the point is too noisy + var getIndexAtPoint = function(x,y,canvas) { + //get the color data for a 3x3 pixel area around the point + var colorData = canvas.getContext('2d').getImageData(x-1,y-1,3,3).data; + //get the index for each pixel + var indices = []; + for (var i = 0; i < colorData.length/4; i++) { + indices.push(colorToIndex(colorData.slice(i*4,i*4+3))); + } + + //for a positive match, must find at least 5 pixels with the same index + indices.sort(); + var matched = -1; + var count = 0; + var counting = -1; + for (var i = 0; i < indices.length; i++) { + if (counting != indices[i]) { + count = 1; + counting = indices[i]; + } + else { + count++; + if (count == 5) { + matched = counting; + break; + } + } + } + + return matched; + } + + //convert an index value to a color + //Mapping -1 through 256^3 to rgb(0,0,0) through rgb(255,255,255) + var indexToColor = function(i) { + if (i > 256*256*256) { + return 'rgb(255,255,255)'; + } + i++; + var b = Math.floor(i/256/256); + var g = Math.floor((i - b*256*256) / 256); + var r = (i - b*256*256 - g*256); + return 'rgb('+r+','+g+','+b+')'; + } + + //convert a color to an index value + //Mapping [0,0,0] through [255,255,255] to -1 through 256^3 + var colorToIndex = function(rgb) { + return (rgb[0] + rgb[1]*256 + rgb[2]*256*256)-1; + } + +})();'use strict'; +(function() { + /** + * CINEMA_COMPONENTS + * PCOORDSVG + * + * The PcoordSVG Component for the CINEMA_COMPONENTS library. + * Contains the constructor for the PcoordSVG component: + * A subclass of Pcoord which draws a Paralell Coordinates chart using SVG. + * + * @exports CINEMA_COMPONENTS + * + * @author Cameron Tauxe + */ + + //If CINEMA_COMPONENTS is already defined, add to it, otherwise create it + var CINEMA_COMPONENTS = {} + if (window.CINEMA_COMPONENTS) + CINEMA_COMPONENTS = window.CINEMA_COMPONENTS; + else + window.CINEMA_COMPONENTS = CINEMA_COMPONENTS; + + //Require that the Pcoord Component be included + if (!CINEMA_COMPONENTS.PCOORD_INCLUDED) + throw new Error("CINEMA_COMPONENTS PcoordSVG Component requires that Pcoord"+ + " component be included. Please make sure that Pcoord component"+ + " is included BEFORE PcoordSVG module"); + + /** @type {boolean} - Flag to indicate that the PcoordSVG Component has been included */ + CINEMA_COMPONENTS.PCOORDSVG_INCLUDED = true; + + /** + * Constructor for PcoordSVG Component + * Represents a component for displaying and interacting with a database on a parallel coordinates chart + * rendered with SVG + * @param {DOM} parent - The DOM object to build this component inside of + * @param {CINEMA_COMPONENTS.Database} database - The database behind this component + * @param {RegExp} filterRegex - A regex to determine which dimensions to NOT show on the component + */ + CINEMA_COMPONENTS.PcoordSVG = function(parent, database, filterRegex) { + //call super-constructor + CINEMA_COMPONENTS.Pcoord.call(this,parent,database,filterRegex); + + //Specify that this is a Pcoord SVG component + d3.select(this.container).classed('SVG',true); + + //Add SVG Components to pathContainer + this.svg = this.pathContainer.append('svg') + .style('position','absolute') + .style('top',this.margin.top+'px') + .style('left',this.margin.left+'px') + .attr('width',this.internalWidth+'px') + .attr('height',this.internalHeight+'px'); + //Add group for selected paths + this.selectedPaths = this.svg.append('g') + .classed('selectedPaths',true); + //Add group for highlighted paths + this.highlightedPaths = this.svg.append('g') + .classed('highlightedPaths',true); + //Add group for overlay paths + this.overlayPaths = this.svg.append('g') + .classed('overlayPaths',true); + + this.redrawPaths(); + } + //establish prototype chain + CINEMA_COMPONENTS.PcoordSVG.prototype = Object.create(CINEMA_COMPONENTS.Pcoord.prototype); + CINEMA_COMPONENTS.PcoordSVG.prototype.constructor = CINEMA_COMPONENTS.PcoordSVG; + + /************************** + * OVERRIDE METHODS + **************************/ + + CINEMA_COMPONENTS.PcoordSVG.prototype.updateSize = function() { + //call super + CINEMA_COMPONENTS.Pcoord.prototype.updateSize.call(this); + + //rescale svg + this.svg + .attr('width',this.internalWidth+'px') + .attr('height',this.internalHeight+'px'); + } + + /** + * Redraw the current selection of paths. + */ + CINEMA_COMPONENTS.PcoordSVG.prototype.redrawSelectedPaths = function() { + var self = this; + //Bind to selection and update + var update = this.selectedPaths + .selectAll('path').data(this.selection); + update.enter() //ENTER + .append('path') + .merge(update) //ENTER + UPDATE + .attr('index',function(d){return d;}) + .attr('d',function(d){ + return self.getPath(self.db.data[d]); + }) + .on('mouseenter',function(d){ + self.dispatch.call("mouseover",self,d,d3.event); + }) + .on('mouseleave',function(d){ + self.dispatch.call("mouseover",self,null,d3.event); + }) + .on('click', function(d) { + self.dispatch.call("click",self,d); + }); + update.exit() //EXIT + .remove(); + } + + /** + * Redraw the currently highlighted path. + */ + CINEMA_COMPONENTS.PcoordSVG.prototype.redrawHighlightedPaths = function() { + var self = this; + //Bind to highlighted and update + var update = this.highlightedPaths + .selectAll('path').data(this.highlighted); + update.enter() //ENTER + .append('path') + .merge(update) //ENTER + UPDATE + .attr('index',function(d){return d;}) + .attr('d',function(d){ + return self.getPath(self.db.data[d]); + }); + update.exit() //EXIT + .remove(); + } + + /** + * Redraw the overlay paths. + */ + CINEMA_COMPONENTS.PcoordSVG.prototype.redrawOverlayPaths = function() { + var self = this; + //Bind to overlayData and update + var update = this.overlayPaths + .selectAll('path').data(this.overlayData); + update.enter() //ENTER + .append('path') + .merge(update) //ENTER + UPDATE + .attr('style',function(d){return d.style;}) + .attr('d',function(d){ + return self.getPath(d.data); + }); + update.exit() //EXIT + .remove(); + } + +})();'use strict'; +(function() { + /** + * CINEMA_COMPONENTS + * QUERY + * + * The Query Component for the CINEMA_COMPONENTS library. + * Contains the constructor for the Query Component + * Which allows for defining a custom data point and querying + * a database for similar data points + * + * @exports CINEMA_COMPONENTS + * + * @author Cameron Tauxe + */ + + //If CINEMA_COMPONENTS is already defined, add to it, otherwise create it + var CINEMA_COMPONENTS = {} + if (window.CINEMA_COMPONENTS) + CINEMA_COMPONENTS = window.CINEMA_COMPONENTS; + else + window.CINEMA_COMPONENTS = CINEMA_COMPONENTS; + + //Require that the Component module be included + if (!CINEMA_COMPONENTS.COMPONENT_INCLUDED) + throw new Error("CINEMA_COMPONENTS Query module requires that Component"+ + " module be included. Please make sure that Component module"+ + " is included BEFORE Query module"); + + //Require that d3 be included + if (!window.d3) { + throw new Error("CINEMA_COMPONENTS Query module requires that"+ + " d3 be included (at least d3v4). Please make sure that d3 is included BEFORE the"+ + " the Query module"); + } + + /** @type {boolean} - Flag to indicate that the Query module has been included */ + CINEMA_COMPONENTS.QUERY_INCLUDED = true; + + /** + * Constructor for Query Component + * Represents a component for querying a database + * @param {DOM} parent - The DOM object to build this component inside of + * @param {CINEMA_COMPONENTS.Database} database - The database behind this component + * (Note that Query does not use a filterRegex) + */ + CINEMA_COMPONENTS.Query = function(parent, database) { + var self = this; + + /*************************************** + * SIZING + ***************************************/ + + //Call super-constructor (will calculate size) + CINEMA_COMPONENTS.Component.call(this,parent,database); + + /*************************************** + * DATA + ***************************************/ + + //override this.dimensions to include only numeric dimensions + this.dimensions = this.dimensions.filter(function(d) { + return !self.db.isStringDimension(d); + }); + + /** @type {number[]} Indices of the similar results to the last query */ + this.results = []; + + /** @type {CINEMA_COMPONENTS.ExtraData} The custom-defined data point */ + this.custom = new CINEMA_COMPONENTS.ExtraData({},""); + /** @type {CINEMA_COMPONENTS.ExtraData} Approximations of the boudnaries for similar data given the threshold */ + this.upper = new CINEMA_COMPONENTS.ExtraData({},""); + this.lower = new CINEMA_COMPONENTS.ExtraData({},""); + // (styles will be decided by a client program) + + /*************************************** + * EVENTS + ***************************************/ + + /** @type {d3.dispatch} Hook for events on chart + * Set handlers with on() function. Ex: this.dispatch.on('query',handlerFunction(results)) + * 'query': Triggered when a query is made + * (argument is the results of the query (as an array of indices)) + * 'customchange': Triggered when the custom-defined data point changes + * (arguemnt is an array with extra data custom,upper and lower (in that order)) + */ + this.dispatch = d3.dispatch('query','customchange'); + + /*************************************** + * SCALES + ***************************************/ + + //Input sliders for each dimension range from 0 to 100 + //So create scales to scale a slider's value to a value in its dimension + this.scales = {}; + this.dimensions.forEach(function(d) { + self.scales[d] = d3.scaleLinear() + .domain([0,100]) + .range(self.db.dimensionDomains[d]); + }); + + /*************************************** + * DOM Content + ***************************************/ + + //Specify that this is a Query component + d3.select(this.container).classed('QUERY',true); + + /** @type {DOM (button)} Button to perform a query when pressed */ + this.queryButton = d3.select(this.container).append('button') + .classed('queryButton',true) + .text("Find Similar") + .on('click',function() { + var results = self.db.getSimilar(self.custom.data,self.thresholdNode.value); + d3.select(self.readout).text(results.length+ " results found!"); + self.dispatch.call('query',self,results.slice()); + }) + .node(); + + /** @type {DOM (span)} Label for Threshold input */ + this.thresholdLabel = d3.select(this.container).append('span') + .classed('thresholdLabel',true) + .text("Threshold:") + .node(); + + /** @type {DOM (input/number)} Number input for threshold */ + this.thresholdNode = d3.select(this.container).append('input') + .classed('thresholdInput',true) + .attr('type','number') + .attr('max',this.dimensions.length) + .attr('min',0) + .attr('step',0.05) + .on('change',function() { + self.updateBounds(); + self.dispatch.call('customchange',self,[self.custom,self.upper,self.lower]); + }) + .node(); + this.thresholdNode.value = 1.0; + + /** @type {DOM (span)} Readout for number of found results */ + this.readout = d3.select(this.container).append('span') + .classed('readout',true) + .node(); + + /** @type {d3.selection} Input rows for each dimension */ + this.rows = d3.select(this.container).selectAll('.inputRow') + .data(this.dimensions) + .enter().append('div') + .classed('inputRow',true) + .style('position','relative'); + //Create contents of each input row + //labels + this.rows.append('span') + .classed('label',true) + .style('position','absolute') + .text(function(d){return d;}); + //checkbox + this.rows.append('input') + .attr('type','checkbox') + .style('position','absolute') + .on('input',function(d) { + if (this.checked) { + var slider = d3.select(this.parentNode).select('input[type="range"]'); + self.custom.data[d] = self.scales[d](slider.node().value); + } + else { + delete self.custom.data[d]; + } + self.updateBounds(); + self.dispatch.call('customchange',self,[self.custom,self.upper,self.lower]); + }); + //slider + this.rows.append('input') + .attr('type','range') + .attr('min',0) + .attr('max',100) + .attr('step',1) + .each(function(){this.value = 50;}) + .style('position','absolute') + .on('input',function(d){ + var check = d3.select(this.parentNode).select('input[type="checkbox"]'); + if (!check.node().checked) + check.node().checked = true; + self.custom.data[d] = self.scales[d](this.value); + self.updateBounds(); + self.dispatch.call('customchange',self,[self.custom,self.upper,self.lower]); + }); + + } + //establish prototype chain + CINEMA_COMPONENTS.Query.prototype = Object.create(CINEMA_COMPONENTS.Component.prototype); + CINEMA_COMPONENTS.Query.prototype.constructor = CINEMA_COMPONENTS.Query; + + /** + * Should be called whenever the data in the associated database changes. + * Will update scales to fit the new data. + */ + CINEMA_COMPONENTS.Query.prototype.updateData = function() { + var self = this; + + this.dimensions.forEach(function(d) { + self.scales[d].range(self.db.dimensionDomains[d]); + }) + } + + /** + * Update upper and lower data depending on custom data and current threshold value + */ + CINEMA_COMPONENTS.Query.prototype.updateBounds = function() { + var self = this; + var threshold = this.thresholdNode.value; + //average difference along each dimension + var avg = (threshold/d3.keys(this.custom.data).length)*100; + this.upper.data = {}; + this.lower.data = {}; + this.dimensions.forEach(function(d) { + if (self.custom.data[d] !== undefined) { + var s = self.scales[d]; + self.lower.data[d] = s(Math.max(s.invert(self.custom.data[d])-avg,0)); + self.upper.data[d] = s(Math.min(s.invert(self.custom.data[d])+avg,100)); + } + }); + } + +})();'use strict'; +(function() { + /** + * CINEMA_COMPONENTS + * SCATTER_PLOT + * + * The ScatterPlot component for the CINEMA_COMPONENTS library. + * Contains the constructor for ScatterPlot Components (Eg. ScatterPlotSVG, ScatterPlotCanvas) + * It is a subclass of Component and contains methods and fields common to all ScatterPlot Components + * + * @exports CINEMA_COMPONENTS + * + * @author Cameron Tauxe + */ + + //If CINEMA_COMPONENTS is already defined, add to it, otherwise create it + var CINEMA_COMPONENTS = {} + if (window.CINEMA_COMPONENTS) + CINEMA_COMPONENTS = window.CINEMA_COMPONENTS; + else + window.CINEMA_COMPONENTS = CINEMA_COMPONENTS; + + //Require that the Component module be included + if (!CINEMA_COMPONENTS.COMPONENT_INCLUDED) + throw new Error("CINEMA_COMPONENTS ScatterPlot module requires that Component"+ + " module be included. Please make sure that Component module"+ + " is included BEFORE ScatterPlot module"); + + //Require that d3 be included + if (!window.d3) { + throw new Error("CINEMA_COMPONENTS ScatterPlot module requires that"+ + " d3 be included (at least d3v4). Please make sure that d3 is included BEFORE the"+ + " the ScatterPlot module"); + } + + /** @type {boolean} - Flag to indicate that the ScatterPlot module has been included */ + CINEMA_COMPONENTS.SCATTER_PLOT_INCLUDED = true; + + /** + * Abstract constructor for ScatterPlot Components + * Represents a component for displaying the data in a database on a 2D scatter plot. + * Objects such as ScatterPlotSVG and ScatterPlotCanvas inherit from this. + * @param {DOM} parent - The DOM object to build this component inside of + * @param {CINEMA_COMPONENTS.Database} database - The database behind this component + * @param {RegExp} filterRegex - A regex to determine which dimensions to NOT show on the component + */ + CINEMA_COMPONENTS.ScatterPlot = function(parent, database, filterRegex) { + /*if (this.constructor === CINEMA_COMPONENTS.ScatterPlot) + throw new Error("Cannot instantiate abstract class 'ScatterPlot'"+ + "Please use a subclass.");*/ + + var self = this; + + /*************************************** + * SIZING + ***************************************/ + + /** @type {CINEMA_COMPONENTS.Margin} Override default margin */ + this.margin = new CINEMA_COMPONENTS.Margin(25,25,60,150); + + //Call super-constructor + CINEMA_COMPONENTS.Component.call(this,parent,database,filterRegex); + + /*************************************** + * DATA + ***************************************/ + + /** @type {number[]} Indices of all currently displayed data */ + this.selection = []; + /** @type {number} Indices of all currently highlighted data */ + this.highlighted = []; + /** @type {CINEMA_COMPONENTS.ExtraData[]} Custom data to overlay on chart */ + this.overlayData = []; + + /** @type {string} The currently selected dimensions for each axis*/ + this.xDimension = this.dimensions[0]; + this.yDimension = this.dimensions[1]; + + /*************************************** + * EVENTS + ***************************************/ + + /** @type {d3.dispatch} Hook for events on chart + * Set handlers with on() function. Ex: this.dispatch.on('mouseover',handlerFunction(i)) + * 'mouseover': Triggered when a point is moused over. + * (called with the index of moused over data and a reference to the mouse event) + * 'xchanged': Triggered when the x dimension being viewed is changed + * (called with the new dimension as an argument) + * 'ychanged': Triggered when the y dimension being viewed is changed + * (called with the new dimension as an argument) + */ + this.dispatch = d3.dispatch("mouseover",'xchanged','ychanged'); + + /*************************************** + * SCALES + ***************************************/ + + /** @type {d3.scale} The scales for the x and y axes */ + this.x = (this.db.isStringDimension(this.xDimension) ? d3.scalePoint() : d3.scaleLinear()) + .domain(this.db.dimensionDomains[this.xDimension]) + .range([15,this.internalWidth-15]); + this.y = (this.db.isStringDimension(this.yDimension) ? d3.scalePoint() : d3.scaleLinear()) + .domain(this.db.dimensionDomains[this.yDimension]) + .range([this.internalHeight-15,15]); + + /*************************************** + * DOM Content + ***************************************/ + + //Specify that this a ScatterPlot component + d3.select(this.container).classed('SCATTER_PLOT',true); + + /** @type {d3.selection} Where the data on the chart will be drawn + * The actual drawing depends on the specific ScatterPlot sublcass + */ + this.pointContainer = d3.select(this.container).append('div') + .classed('pointContainer',true) + .style('position','absolute') + .style('top',this.margin.top+'px') + .style('right',this.margin.right+'px') + .style('bottom',this.margin.bottom+'px') + .style('left',this.margin.left+'px') + .style('width',this.internalWidth+'px') + .style('height',this.internalHeight+'px'); + + /** @type {DOM (select)} The select elements for selecting the dimension for each axis */ + //x + this.xSelect = d3.select(this.container).append('select') + .classed('dimensionSelect x',true) + .style('position','absolute') + .node(); + //y + this.ySelect = d3.select(this.container).append('select') + .classed('dimensionSelect y',true) + .style('position','absolute') + .node(); + //Bind data and append options + //x + d3.select(this.xSelect).selectAll('option') + .data(this.dimensions) + .enter().append('option') + .attr('value',function(d){return d;}) + .text(function(d){return d;}); + d3.select(this.xSelect).node().value = this.xDimension; + //y + d3.select(this.ySelect).selectAll('option') + .data(this.dimensions) + .enter().append('option') + .attr('value',function(d){return d;}) + .text(function(d){return d;}); + d3.select(this.ySelect).node().value = this.yDimension; + //Add change listeners to select elements + //x + d3.select(this.xSelect).on('input',function() { + self.xDimension = this.value; + self.x = (self.db.isStringDimension(self.xDimension) ? d3.scalePoint() : d3.scaleLinear()) + .domain(self.db.dimensionDomains[self.xDimension]) + .range([0,self.internalWidth]); + self.xAxisContainer.select('.axis') + .call(d3.axisBottom().scale(self.x)); + self.dispatch.call('xchanged',self,self.xDimension); + self.redrawPoints(); + }); + //y + d3.select(this.ySelect).on('input',function() { + self.yDimension = this.value; + self.y = (self.db.isStringDimension(self.yDimension) ? d3.scalePoint() : d3.scaleLinear()) + .domain(self.db.dimensionDomains[self.yDimension]) + .range([self.internalHeight,0]); + self.yAxisContainer.select('.axis') + .call(d3.axisLeft().scale(self.y)); + self.dispatch.call('ychanged',self,self.yDimension); + self.redrawPoints(); + }); + + /** @type {d3.selection} A readout in the corner of the chart + * that warns if any data could not be plotted + */ + this.warningReadout = d3.select(this.container).append('div') + .classed('warningReadout',true) + .style('position','absolute'); + + /*************************************** + * AXES + ***************************************/ + + /** @type {d3.selection} The container for each axis */ + //x + this.xAxisContainer = d3.select(this.container).append('svg') + .classed('axisContainer x',true) + .style('position','absolute') + .style('width',this.internalWidth+'px') + .style('height',25+'px') + .style('top',this.margin.top+this.internalHeight+'px') + .style('left',this.margin.left+'px'); + //y + this.yAxisContainer = d3.select(this.container).append('svg') + .classed('axisContainer y',true) + .style('position','absolute') + .style('width',50+'px') + .style('height',this.internalHeight+'px') + .style('left',(this.margin.left-50)+'px') + .style('top',this.margin.top+'px'); + //Add axis to each axis container + //x + this.xAxisContainer.append('g') + .classed('axis',true) + .call(d3.axisBottom().scale(this.x)); + //y + this.yAxisContainer.append('g') + .classed('axis',true) + .attr('transform','translate(50)') + .call(d3.axisLeft().scale(this.y)); + + }; + //establish prototype chain + CINEMA_COMPONENTS.ScatterPlot.prototype = Object.create(CINEMA_COMPONENTS.Component.prototype); + CINEMA_COMPONENTS.ScatterPlot.prototype.constructor = CINEMA_COMPONENTS.ScatterPlot; + + /** + * Should be called every time the size of the chart's container changes. + * Updates the sizing and scaling of all parts of the chart and redraws + */ + CINEMA_COMPONENTS.ScatterPlot.prototype.updateSize = function() { + //Call super (will recalculate size) + CINEMA_COMPONENTS.Component.prototype.updateSize.call(this); + + //update pointContainer size + this.pointContainer + .style('width',this.internalWidth+'px') + .style('height',this.internalHeight+'px'); + + //Rescale + this.x.range([15,this.internalWidth-15]); + this.y.range([this.internalHeight-15,15]); + + //Reposition and rescale axes + this.xAxisContainer + .style('top',this.margin.top+this.internalHeight+'px') + .style('width',this.internalWidth+'px') + .select('.axis') + .call(d3.axisBottom().scale(this.x)); + this.yAxisContainer + .style('height',this.internalHeight+'px') + .select('.axis') + .call(d3.axisLeft().scale(this.y)); + + this.redrawPoints(); + } + + /** + * Should be called whenever the data in the associated database changes. + * Will update scales, axes and selection to fit the new data. + */ + CINEMA_COMPONENTS.ScatterPlot.prototype.updateData = function() { + + //Update scale domains + this.x.domain(this.db.dimensionDomains[this.xDimension]); + this.y.domain(this.db.dimensionDomains[this.yDimension]); + + //Rebuild axes + this.xAxisContainer.select('.axis') + .call(d3.axisBottom().scale(this.x)); + this.yAxisContainer.select('.axis') + .call(d3.axisLeft().scale(this.y)); + + this.redrawPoints(); + } + + //Shortcut function for redrawSelectedPoints, redrawHighlightedPoints and redrawOverlayPoints + CINEMA_COMPONENTS.ScatterPlot.prototype.redrawPoints = function() { + this.redrawSelectedPoints(); + this.redrawHighlightedPoints(); + this.redrawOverlayPoints(); + } + + /** + * Filter the given selection into only the points that can be shown + * on the plot (i.e. do not have NaN or undefined values on current dimensions) + */ + CINEMA_COMPONENTS.ScatterPlot.prototype.getPlottablePoints = function(selection) { + var self = this; + return selection.filter(function(d) { + var xCoord = self.x(self.db.data[d][self.xDimension]); + var yCoord = self.y(self.db.data[d][self.yDimension]); + return !(isNaN(xCoord) || isNaN(yCoord)); + }); + } + + /** + * Set the chart's selection of data to the data represented + * by the given list of indices + */ + CINEMA_COMPONENTS.ScatterPlot.prototype.setSelection = function(selection) { + this.selection = selection; + this.redrawSelectedPoints(); + } + + /** + * Set the chart's current highlighted data to the data represented + * by the given list of indices + */ + CINEMA_COMPONENTS.ScatterPlot.prototype.setHighlightedPoints = function(indices) { + this.highlighted = indices; + this.redrawHighlightedPoints(); + } + + /** + * Set the current overlay points + */ + CINEMA_COMPONENTS.ScatterPlot.prototype.setOverlayPoints = function(data) { + this.overlayData = data; + this.redrawOverlayPaths(); + }; + + /** + * Redraw the current selection of points. + * Actual implementation is up to specific subclasses + */ + CINEMA_COMPONENTS.ScatterPlot.prototype.redrawSelectedPoints = function() { + throw new Error("Cannot call abstract function 'redrawSelectedPoints()'!"+ + " Please override function in a subclass"); + } + + /** + * Redraw the currently highlighted points. + * Actual implementation is up to specific subclasses + */ + CINEMA_COMPONENTS.ScatterPlot.prototype.redrawHighlightedPoints = function() { + throw new Error("Cannot call abstract function 'redrawHighlightedPoints()'!"+ + " Please override function in a subclass"); + } + + /** + * Redraw the overlay points. + * Actual implementation is up to specific subclasses + */ + CINEMA_COMPONENTS.ScatterPlot.prototype.redrawOverlayPoints = function() { + throw new Error("Cannot call abstract function 'redrawOverlayPoints()'!"+ + " Please override function in a subclass"); + } +})(); +'use strict'; +(function() { + /** + * CINEMA_COMPONENTS + * SCATTER_PLOT_CANVAS + * + * The ScatterPlotCanvas Component for the CINEMA_COMPONENTS library. + * Contains the constructor for the ScatterplotCanvas Component: + * A subclass of ScatterPlot which draws data using canvas elements + * + * @exports CINEMA_COMPONENTS + * + * @author Cameron Tauxe + */ + + //If CINEMA_COMPONENTS is already defined, add to it, otherwise create it + var CINEMA_COMPONENTS = {} + if (window.CINEMA_COMPONENTS) + CINEMA_COMPONENTS = window.CINEMA_COMPONENTS; + else + window.CINEMA_COMPONENTS = CINEMA_COMPONENTS; + + //Require that the ScatterPlot Component be included + if (!CINEMA_COMPONENTS.SCATTER_PLOT_INCLUDED) + throw new Error("CINEMA_COMPONENTS ScatterPlotCanvas Component requires that ScatterPlot"+ + " component be included. Please make sure that ScatterPlot component"+ + " is included BEFORE ScatterPlotCanvas module"); + + /** @type {boolean} - Flag to indicate that the ScatterPlotSVG Component has been included */ + CINEMA_COMPONENTS.SCATTER_PLOT_CANVAS_INCLUDED = true; + + /** + * Constructor for ScatterPlotCanvas Component + * Represents a component for displaying data on a 2D Scatter Plot + * Rendered with canvas elements + * @param {DOM} parent - The DOM object to build this component inside of + * @param {CINEMA_COMPONENTS.Database} database - The database behind this component + * @param {RegExp} filterRegex - A regex to determine which dimensions to NOT show on the component + */ + CINEMA_COMPONENTS.ScatterPlotCanvas = function(parent, database, filterRegex) { + var self = this; + + //call super-constructor + CINEMA_COMPONENTS.ScatterPlot.call(this,parent,database,filterRegex); + + //specify that this is a ScatterPlot Canvas component. + d3.select(this.container).classed('CANVAS',true); + + //Because not every point in the selection will be on the plot, + //need to keep track of plottablePoints so that their + //index can be used on indexCanvas + this.plottablePoints = []; + + //Add canvases to pathContainer + this.selectedCanvas = this.pointContainer.append('canvas') + .classed('selectedCanvas',true) + .node(); + this.highlightedCanvas = this.pointContainer.append('canvas') + .classed('highlightedCanvas',true) + .node(); + this.overlayCanvas = this.pointContainer.append('canvas') + .classed('overlayCanvas',true) + .node(); + //Index canvas is invisible and draws in a unique color for each path + //Its color data is used to determine which path is being moused over + this.indexCanvas = this.pointContainer.append('canvas') + .classed('indexCanvas',true) + .style('display','none') + .node(); + //Size/position canvases + this.pointContainer.selectAll('canvas') + .style('position','absolute'); + + //Determine screen DPI to rescale canvas contexts + //(prevents artifacts and blurring on some displays) + //https://stackoverflow.com/a/15666143/2827258 + this.pixelRatio = (function() { + var ctx = document.createElement('canvas').getContext("2d"), + dpr = window.devicePixelRatio || 1, + bsr = ctx.webkitBackingStorePixelRatio || + ctx.mozBackingStorePixelRatio || + ctx.msBackingStorePixelRatio || + ctx.oBackingStorePixelRatio || + ctx.backingStorePixelRatio || 1; + return dpr / bsr; + })(); + + //Loading/still drawing indicator + this.loading = d3.select(this.container).append('div') + .classed('loadingIndicator',true) + .style('display','none') + .text('Drawing...'); + + //Set an interval to call drawIterator if it exists + //roughly 60 times a second + this.interval = setInterval(function(self) { + for (var i = 0; i < 25; i++) { + if (self.drawIterator) { + if (self.drawIterator.next().done) { + self.drawIterator = undefined; + self.loading.style('display','none'); + } + } + } + }, 16, this); + + //Set up mousemove listener to get moused-over paths + this.lastMouseMove = null; //remember last result, to prevent excessive dispatch calls + this.pointContainer.on('mousemove', function() { + var x = d3.mouse(self.selectedCanvas)[0]*self.pixelRatio; + var y = d3.mouse(self.selectedCanvas)[1]*self.pixelRatio; + if (x >= 0 && y >= 0) { + var index = getIndexAtPoint(x,y,self.indexCanvas); + if (index != -1) { + if (self.lastMouseMove != self.plottablePoints[index]) { + self.lastMouseMove = self.plottablePoints[index]; + self.dispatch.call('mouseover',self,self.plottablePoints[index],d3.event); + } + } + else { + if (self.lastMouseMove !== null) { + self.lastMouseMove = null; + self.dispatch.call('mouseover',self,null,d3.event); + } + } + } + }); + + this.updateSize(); + } + //establish prototype chain + CINEMA_COMPONENTS.ScatterPlotCanvas.prototype = Object.create(CINEMA_COMPONENTS.ScatterPlot.prototype); + CINEMA_COMPONENTS.ScatterPlotCanvas.prototype.constructor = CINEMA_COMPONENTS.ScatterPlotCanvas; + + /************************** + * OVERRIDE METHODS + **************************/ + + CINEMA_COMPONENTS.ScatterPlotCanvas.prototype.updateSize = function() { + var self = this; + //call super + CINEMA_COMPONENTS.ScatterPlot.prototype.updateSize.call(this); + + //Resize canvases + this.pointContainer.selectAll('canvas') + .style('width',this.internalWidth+'px') + .style('height',this.internalHeight+'px') + // width/height styles are distinct from attributes + // (attributes determine context size, style is the size the canvas appears in on screen) + .attr('width',this.internalWidth*this.pixelRatio+'px') + .attr('height',this.internalHeight*this.pixelRatio+'px') + .each(function(){ + this.getContext('2d').scale(self.pixelRatio,self.pixelRatio); + }); + //Init canvas contexts + var selectedContext = this.selectedCanvas.getContext('2d'); + selectedContext.fillStyle = 'rgba(82, 137, 163, 0.521)'; + selectedContext.strokeStyle = 'rgb(69, 121, 153)'; + selectedContext.lineWidth = 2; + var highlightedContext = this.highlightedCanvas.getContext('2d'); + highlightedContext.fillStyle = 'rgb(252, 127, 127)'; + highlightedContext.strokeStyle = 'rgb(153, 80, 80)'; + highlightedContext.lineWidth = 3; + + this.redrawPoints(); + } + + /** + * Redraw the current selection of points + */ + CINEMA_COMPONENTS.ScatterPlotCanvas.prototype.redrawSelectedPoints = function() { + var self = this; + + this.plottablePoints = this.getPlottablePoints(this.selection); + //Update warningReadout + if (this.plottablePoints.length < this.selection.length) + this.warningReadout.text((this.selection.length-this.plottablePoints.length) + + " point(s) could not be plotted (because they contain NaN or undefined values)."); + else + this.warningReadout.text(''); + + var ctx = this.selectedCanvas.getContext('2d'); + ctx.clearRect(0,0,this.internalWidth,this.internalHeight); + + var indexCtx = this.indexCanvas.getContext('2d'); + indexCtx.clearRect(0,0,this.internalWidth,this.internalHeight); + + this.drawIterator = (function*(queue){ + self.loading.style('display','initial'); + var i = 0; + while (i < queue.length) { + var x = self.x(self.db.data[queue[i]][self.xDimension]); + var y = self.y(self.db.data[queue[i]][self.yDimension]); + ctx.beginPath(); + ctx.arc(x,y,6,0,2*Math.PI); + ctx.fill(); + ctx.stroke(); + + indexCtx.fillStyle = indexToColor(i); + indexCtx.beginPath(); + indexCtx.arc(x,y,10,0,2*Math.PI); + indexCtx.fill(); + + yield ++i; + } + })(this.plottablePoints); + } + + /** + * Redraw the current selection of points + */ + CINEMA_COMPONENTS.ScatterPlotCanvas.prototype.redrawHighlightedPoints = function() { + var self = this; + + var plottable = this.getPlottablePoints(this.highlighted); + + var ctx = this.highlightedCanvas.getContext('2d'); + ctx.clearRect(0,0,this.internalWidth,this.internalHeight); + + plottable.forEach(function(d) { + var x = self.x(self.db.data[d][self.xDimension]); + var y = self.y(self.db.data[d][self.yDimension]); + ctx.beginPath(); + ctx.arc(x,y,10,0,2*Math.PI); + ctx.fill(); + ctx.stroke(); + }); + } + + /** + * Redraw the overlay points + */ + CINEMA_COMPONENTS.ScatterPlotCanvas.prototype.redrawOverlayPoints = function() { + var self = this; + + var ctx = this.overlayCanvas.getContext('2d'); + ctx.clearRect(0,0,this.internalWidth,this.internalHeight); + + this.overlayData.forEach(function(d) { + //Parse style + ctx.lineWidth = d.style.lineWidth || 0; + ctx.lineCap = d.style.lineCap || 'butt'; + ctx.lineJoin = d.style.lineJoin || 'miter'; + ctx.miterLimit = d.style.miterLimit || 10; + ctx.strokeStyle = d.style.strokeStyle || 'black'; + ctx.fillStyle = d.style.fillStyle || 'black'; + if (d.style.lineDash) + ctx.setLineDash(d.style.lineDash); + else + ctx.setLineDash([]); + //Draw line + var x = self.x(d.data[self.xDimension]); + var y = self.y(d.data[self.yDimension]); + ctx.beginPath(); + ctx.arc(x,y,(d.style.r || 6),0,2*Math.PI); + ctx.fill(); + ctx.stroke(); + }); + + } + + //Get the index of the path at the given point + //using the colors on the index canvas + //returns -1 if there is no path, or the area around the point is too noisy + var getIndexAtPoint = function(x,y,canvas) { + //get the color data for a 3x3 pixel area around the point + var colorData = canvas.getContext('2d').getImageData(x-1,y-1,3,3).data; + //get the index for each pixel + var indices = []; + for (var i = 0; i < colorData.length/4; i++) { + indices.push(colorToIndex(colorData.slice(i*4,i*4+3))); + } + + //for a positive match, must find at least 5 pixels with the same index + indices.sort(); + var matched = -1; + var count = 0; + var counting = -1; + for (var i = 0; i < indices.length; i++) { + if (counting != indices[i]) { + count = 1; + counting = indices[i]; + } + else { + count++; + if (count == 5) { + matched = counting; + break; + } + } + } + + return matched; + } + + //convert an index value to a color + //Mapping -1 through 256^3 to rgb(0,0,0) through rgb(255,255,255) + var indexToColor = function(i) { + if (i > 256*256*256) { + return 'rgb(255,255,255)'; + } + i++; + var b = Math.floor(i/256/256); + var g = Math.floor((i - b*256*256) / 256); + var r = (i - b*256*256 - g*256); + return 'rgb('+r+','+g+','+b+')'; + } + + //convert a color to an index value + //Mapping [0,0,0] through [255,255,255] to -1 through 256^3 + var colorToIndex = function(rgb) { + return (rgb[0] + rgb[1]*256 + rgb[2]*256*256)-1; + } + +})();'use strict'; +(function() { + /** + * CINEMA_COMPONENTS + * SCATTER_PLOT_SVG + * + * The ScatterPlotSVG Component for the CINEMA_COMPONENTS library. + * Contains the constructor for the ScatterplotSVG Component: + * A subclass of ScatterPlot which draws data using SVG + * + * @exports CINEMA_COMPONENTS + * + * @author Cameron Tauxe + */ + + //If CINEMA_COMPONENTS is already defined, add to it, otherwise create it + var CINEMA_COMPONENTS = {} + if (window.CINEMA_COMPONENTS) + CINEMA_COMPONENTS = window.CINEMA_COMPONENTS; + else + window.CINEMA_COMPONENTS = CINEMA_COMPONENTS; + + //Require that the ScatterPlot Component be included + if (!CINEMA_COMPONENTS.SCATTER_PLOT_INCLUDED) + throw new Error("CINEMA_COMPONENTS ScatterPlotSVG Component requires that ScatterPlot"+ + " component be included. Please make sure that ScatterPlot component"+ + " is included BEFORE ScatterPlotSVG module"); + + /** @type {boolean} - Flag to indicate that the ScatterPlotSVG Component has been included */ + CINEMA_COMPONENTS.SCATTER_PLOT_SVG_INCLUDED = true; + + /** + * Constructor for ScatterPlotSVG Component + * Represents a component for displaying data on a 2D Scatter Plot + * Rendered with SVG + * @param {DOM} parent - The DOM object to build this component inside of + * @param {CINEMA_COMPONENTS.Database} database - The database behind this component + * @param {RegExp} filterRegex - A regex to determine which dimensions to NOT show on the component + */ + CINEMA_COMPONENTS.ScatterPlotSVG = function(parent, database, filterRegex) { + //call super-constructor + CINEMA_COMPONENTS.ScatterPlot.call(this,parent,database,filterRegex); + + //specify that this is a ScatterPlot SVG component. + d3.select(this.container).classed('SVG',true); + + //Add SVG Components to pointContainer + this.svg = this.pointContainer.append('svg') + .style('position','absolute') + .attr('viewBox','0 0 '+this.internalWidth+' '+this.internalHeight) + .attr('preserveAspectRatio','none') + .attr('width','100%') + .attr('height','100%'); + //Add group for selected points + this.selectedPoints = this.svg.append('g') + .classed('selectedPoints',true); + //Add group for highlighted points + this.highlightedPoints = this.svg.append('g') + .classed('highlightedPoints',true); + //Add group for overlay points + this.overlayPoints = this.svg.append('g') + .classed('overlayPoints',true); + + this.redrawPoints(); + } + //establish prototype chain + CINEMA_COMPONENTS.ScatterPlotSVG.prototype = Object.create(CINEMA_COMPONENTS.ScatterPlot.prototype); + CINEMA_COMPONENTS.ScatterPlotSVG.prototype.constructor = CINEMA_COMPONENTS.ScatterPlotSVG; + + /************************** + * OVERRIDE METHODS + **************************/ + + CINEMA_COMPONENTS.ScatterPlotSVG.prototype.updateSize = function() { + //call super + CINEMA_COMPONENTS.ScatterPlot.prototype.updateSize.call(this); + + //rescale svg + this.svg.attr('viewBox','0 0 '+this.internalWidth+' '+this.internalHeight); + } + + /** + * Redraw the current selection of points + */ + CINEMA_COMPONENTS.ScatterPlotSVG.prototype.redrawSelectedPoints = function() { + var self = this; + var plottable = this.getPlottablePoints(this.selection); + //Update warningReadout + if (plottable.length < this.selection.length) + this.warningReadout.text((this.selection.length-plottable.length) + + " point(s) could not be plotted (because they contain NaN or undefined values)."); + else + this.warningReadout.text(''); + //Bind to selection and update + var update = this.selectedPoints + .selectAll('circle').data(plottable); + update.enter() //ENTER + .append('circle') + .attr('r','6') + .merge(update) //ENTER + UPDATE + .attr('index',function(d){return d;}) + .attr('cx',function(d) { + return self.x(self.db.data[d][self.xDimension]); + }) + .attr('cy',function(d) { + return self.y(self.db.data[d][self.yDimension]); + }) + .on('mouseenter',function(d) { + self.dispatch.call('mouseover',self,d,d3.event); + }) + .on('mouseleave',function(d) { + self.dispatch.call('mouseover',self,null,d3.event); + }); + update.exit() + .remove(); + } + + /** + * Redraw the set of highlighted points + */ + CINEMA_COMPONENTS.ScatterPlotSVG.prototype.redrawHighlightedPoints = function() { + var self = this; + //Bind to selection and update + var update = this.highlightedPoints + .selectAll('circle').data(this.getPlottablePoints(this.highlighted)); + update.enter() //ENTER + .append('circle') + .attr('r','10') + .merge(update) //ENTER + UPDATE + .attr('index',function(d){return d;}) + .attr('cx',function(d) { + return self.x(self.db.data[d][self.xDimension]); + }) + .attr('cy',function(d) { + return self.y(self.db.data[d][self.yDimension]); + }); + update.exit() + .remove(); + } + + /** + * Redraw the overlay points + */ + CINEMA_COMPONENTS.ScatterPlotSVG.prototype.redrawOverlayPoints = function() { + var self = this; + //Bind to selection and update + var update = this.overlayPoints + .selectAll('circle').data(this.overlayData); + update.enter() //ENTER + .append('circle') + .attr('r','5') + .merge(update) //ENTER + UPDATE + .attr('cx',function(d) { + return self.x(d.data[self.xDimension]); + }) + .attr('cy',function(d) { + return self.y(d.data[self.yDimension]); + }) + .attr('style',function(d) { + return d.style; + }); + update.exit() + .remove(); + } + +})(); +'use strict'; +(function() { + /** + * CINEMA_COMPONENTS + * LineChart + * + * The LineChart Component for the CINEMA_COMPONENTS library. + * It is a sublcass of Component + * + * This component views multiple parameters as a line chart. + * + * @exports CINEMA_COMPONENTS + * + * @author Robin Maack + */ + + //If CINEMA_COMPONENTS is already defined, add to it, otherwise create it + var CINEMA_COMPONENTS = {} + if (window.CINEMA_COMPONENTS) + CINEMA_COMPONENTS = window.CINEMA_COMPONENTS; + else + window.CINEMA_COMPONENTS = CINEMA_COMPONENTS; + + //Require that the Component module be included + if (!CINEMA_COMPONENTS.COMPONENT_INCLUDED) + throw new Error("CINEMA_COMPONENTS LineChart module requires that Component"+ + " module be included. Please make sure that Component module"+ + " is included BEFORE LineChart module"); + + //Require that d3 be included + if (!window.d3) { + throw new Error("CINEMA_COMPONENTS LineChart module requires that"+ + " d3 be included (at least d3v5). Please make sure that d3 is included BEFORE the"+ + " the Pcoord module"); + } + + /** @type {boolean} - Flag to indicate that the LineChart module has been included */ + CINEMA_COMPONENTS.LINECHART_INCLUDED = true; + + /** + * Abstract constructor for LineCart Components + * Represents a component for displaying and interacting with a database on a chart with multiple lines + * @param {DOM} parent - The DOM object to build this component inside of + * @param {CINEMA_COMPONENTS.Database} database - The database behind this component + * @param {RegExp} filterRegex - A regex to determine which dimensions to NOT show on the component + */ + CINEMA_COMPONENTS.LineChart = function(parent, database, filterRegex, image_measures, excluded_dimensions) { + var self = this; + + //call super-constructor + CINEMA_COMPONENTS.Component.call(this,parent,database,filterRegex); + + //Allowed prefixes for image measures, check for unused beforehand + if(typeof image_measures !== 'undefined') { + this.allowedUPrefixes = []; + const image_measuresLength = image_measures.length; + for (var i = 0; i < image_measuresLength; i++) { + for (var key in self.db.dimensionTypes) { + if(key.startsWith(image_measures[i])) { + this.allowedUPrefixes.push(image_measures[i]); + break; + } + } + } + } + + //Excluded dimensions for x-axis + this.excludedDim = excluded_dimensions; + + /*************************************** + * SIZING + ***************************************/ + + /** @type {CINEMA_COMPONENTS.Margin} Override default margin */ + this.margin = new CINEMA_COMPONENTS.Margin(20,30,50,170); + + /** @type {CINEMA_COMPONENTS.Margin} Margins of axis to the SVG plane */ + this.axismargin = new CINEMA_COMPONENTS.Margin(15,15,15,15); + + /*************************************** + * DATA + ***************************************/ + + /** @type {String} The currently selected dimensions for each axis*/ + this.xDimension = this.dimensions[0]; + + /** @type {Object} Currently selected data point*/ + this.currentlySelectedPoint = {}; + + /** @type {Object} Data to be shown by the plot*/ + this.plotData = {}; + + //Prepare the plot data + this.prepareData(); + + /*************************************** + * EVENTS + ***************************************/ + + /** @type {d3.dispatch} Hook for events on chart + * Set handlers with on() function. + * 'selectionchanged': Triggered when the user makes a selection. + * (called with the index of mouse up data and a reference to the mouse event) + * 'xchanged': Triggered when the x dimension being viewed is changed + * (called with the new dimension as an argument) + */ + this.dispatch = d3.dispatch("selectionchanged", "xchanged"); + + /*************************************** + * DRAGGING + ***************************************/ + + /** @type {boolean} Is left mouse button pushed down*/ + this.dragging = false; + + /** @type {int} svg x position where mouse left mouse button was pushed down*/ + this.dragStartX = 0; + + /** @type {Object} Save selected data when mouse button was pushed down*/ + this.dragStartData = {}; + + /** @type {Object} Save start and end data if drag action */ + this.dragResult = {}; + + /*************************************** + * DOM Content + ***************************************/ + + /** Main Container **/ + + //Give plot container a class + d3.select(this.container).classed('LINE_CHART',true); + + //Add a div as main container to add other components later + this.mainContainer = d3.select(this.container).append('div') + .classed('mainContainer',true) + .style('position','absolute') + .style('top',this.margin.top+'px') + .style('right',this.margin.right+'px') + .style('bottom',this.margin.bottom+'px') + .style('left',this.margin.left+'px') + .style('width',this.internalWidth+'px') + .style('height',this.internalHeight+'px'); + + /** Dimension selection for x-axis **/ + + //Get all non image measure and non file dimensions + this.validDim = []; + for(var i=0, len=self.dimensions.length; i < len; i++) { + if(!(self.dimensions[i].startsWith("FILE") || + startsWithPrefixes(self.dimensions[i], this.allowedUPrefixes) || + startsWithPrefixes(self.dimensions[i], this.excludedDim))) { + self.validDim.push(self.dimensions[i]); + } + } + + //Add Dimension selection dropdown menu + this.xSelect = d3.select(this.container).append('select') + .classed('dimensionSelect x', true) + .style('position','absolute') + .node(); + + //Add all options to dropdown menu + d3.select(this.xSelect).selectAll('option') + .data(this.validDim) + .enter().append('option') + .attr('value',function(d){return d;}) + .text(function(d){return d;}); + d3.select(this.xSelect).node().value = this.xDimension; + + //Define actions when a new Dimension is selected + d3.select(this.xSelect).on('input',function() { + self.xDimension = this.value; + self.prepareData(); + self.x = (self.db.isStringDimension(self.xDimension) ? d3.scalePoint() : d3.scaleLinear()) + .domain(self.plotData.dimensionDomain); + self.xAxisContainer.select('.axis') + .call(d3.axisBottom().scale(self.x)); + self.dispatch.call('xchanged',self,self.xDimension); + self.updateLineVisibility(); + self.redraw(); + }); + + /** Checkboxtable for selecting uncertainty measures **/ + + this.tableContainer = d3.select(this.container).append('div') + .classed('tableContainer',true) + .style('position','absolute') + .style('top', 20 + 'px') + .style('left', 5 + 'px') + .style('bottom',this.margin.bottom+'px') + .style('overflow-y', 'auto') + .style('overflow-x', 'hidden'); + + //Set the checkboxes for the whole group and update + this.updateLineGroupVisibility = function() { + d3.selectAll(".lineGroupSelectCheckbox").each(function(d) { + const cbgroup = d3.select(this); + d3.selectAll(".lineSelectCheckbox").each(function(d) { + const cb = d3.select(this); + if(cb.property("value").startsWith(cbgroup.property("value"))) + cb.property("checked", cbgroup.property("checked")); + }); + }); + self.updateLineVisibility(); + } + + //Function to toggle Checkboxes for uncertainty measures + this.updateLineVisibility = function() { + d3.selectAll(".lineSelectCheckbox").each(function(d) { + const cb = d3.select(this); + self.setLineVisibility(cb.property("value"), cb.property("checked")); + }); + self.redraw(); + } + + /** Measure group checkboxes **/ + + //Table containing the checkboxes + this.ySelectGroupTable = self.tableContainer + .append('table') + .classed("lineSelect yGroup", true); + + //Rows in the checkbox table + this.yTableGroupRows = this.ySelectGroupTable.selectAll('tr') + .classed("lineSelectRow y", true) + .data(this.allowedUPrefixes) + .enter().append('tr'); + + //Add checkboxes to the table + this.yTableGroupRows.selectAll('td') + .data((d) => [d]) + .enter() + .append('td') + .append("input") + .classed("lineGroupSelectCheckbox", true) + .attr("checked", true) + .attr("type", "checkbox") + .attr("id", function(d,i) { return 'a'+i; }) + .attr("value", (d) => d) + .on("change", self.updateLineGroupVisibility); + + //Add text next to the checkboxes + this.yTableGroupRows.selectAll("td") + .data((d) => [d]) + .append("text") + .classed("lineGroupSelect checkboxtext", true) + .text((d) => "All " + d); + + /** Measure checkboxes **/ + + //Table containing the checkboxes + this.ySelectTable = self.tableContainer + .append('table') + .classed("lineSelect y", true); + + //Rows in the checkbox table + this.yTableRows = this.ySelectTable.selectAll('tr') + .classed("lineSelectRow y", true) + .data(self.plotData.series) + .enter().append('tr'); + + //Add checkboxes to the table + this.yTableRows.selectAll('td') + .data((d) => [d]) + .enter() + .append('td') + .append("input") + .classed("lineSelectCheckbox", true) + .attr("checked", true) + .attr("type", "checkbox") + .attr("id", function(d,i) { return 'a'+i; }) + .attr("value", (d) => d.name) + .on("change", self.updateLineVisibility); + + //Add text next to the checkboxes + this.yTableRows.selectAll("td") + .data((d) => [d]) + .append("text") + .classed("lineSelect checkboxtext", true) + .text((d) => d.name); + + /** SVG plane **/ + + this.initChart = function() { + /** SVG plane creation **/ + + //Create svg plane + this.svg = this.mainContainer.append('svg') + .attr('class','lineChart') + .attr('viewBox','0 0 '+this.internalWidth+' '+this.internalHeight) + .attr('preserveAspectRatio','none') + .attr('width','100%') + .attr('height','100%'); + + //set svg position + this.svg.style("position", "relative"); + + //Add interaction to the svg plane + this.svg + .on('mousemove', function() { + self.moved(d3.event); + }) + .on('mouseenter', function() { + self.entered(d3.event); + }) + .on('mouseleave', function() { + self.left(d3.event); + }) + .on("mousedown", function() { + self.down(d3.event); + }) + .on("mouseup", function() { + self.up(d3.event); + }); + + /** + * Gets called when the mouse is moved inside the svg plane + * Highlights the selected path and changes the selected data point + * Updates the dragging square if currently dragging + * @type {Object} eventdata - Mouse event data + */ + this.moved = function(eventdata) { + var self = this; + if(this.getVisibileLineCount()) { + //Prevent selecting text + eventdata.preventDefault(); + + //Get currently selected data point + var currentDatapoint = this.getMousePositionData(eventdata); + + //If dragging update dragging square + if(this.dragging) { + //Startpoint is right of current position + if(self.dragStartX > eventdata.layerX){ + self.svg.select("rect") + .attr("x", eventdata.layerX) + .attr("width", self.dragStartX - eventdata.layerX); + } + //Startpoint is left of current position + else { + self.svg.select("rect") + .attr("width", eventdata.layerX - self.dragStartX); + } + } + + //Redraw paths and dot + this.path.selectAll("path").attr("stroke", d => d === currentDatapoint.series ? null : "#ddd").filter(d => d === currentDatapoint.series).raise(); + this.dot.attr("transform", `translate(${self.x(currentDatapoint.date)},${self.y(currentDatapoint.value)})`); + this.dot.select("#dot_name_text").attr("overflow", "visible").text(currentDatapoint.umeasurename); + this.dot.select("#dot_number_text").attr("overflow", "visible").text(currentDatapoint.value.toFixed(2)); + } + } + + /** + * Gets called when the mouse enters the svg plane + * Resets the paths and dot + * @type {Object} eventdata - Mouse event data + */ + this.entered = function() { + if(this.getVisibileLineCount()) { + this.path.selectAll("path").style("mix-blend-mode", null).attr("stroke", "#ddd"); + this.dot.attr("display", null); + } + } + + /** + * Gets called when the mouse leaves the svg plane + * Resets the paths and dot + * @type {Object} eventdata - Mouse event data + */ + this.left = function() { + var self = this; + + //Reset paths and dot + if(this.getVisibileLineCount()) { + this.path.selectAll("path").style("mix-blend-mode", "multiply").attr("stroke", null); + this.dot.attr("display", "none"); + } + //Prevent draging from continuing and show failure(red square) + if(self.dragging) { + self.dragging = false; + self.svg.selectAll("rect") + .transition() + .duration(100) + .attr("stroke-width", 10) + .attr("stroke", "red") + .delay(200) + .transition() + .duration(1000) + .attr("opacity", 0.0) + .remove(); + } + } + + /** + * Gets called when the mouse gets pushed down on the svg plane + * Saves the start position and data + * Creates the dragging rectange + * @type {Object} eventdata - Mouse event data + */ + this.down = function(eventdata) { + var self = this; + + if(eventdata.button === 0) { + //Prevent selecting text + eventdata.preventDefault(); + + //Set dragging values + self.dragging = true; + self.dragStartData = this.getMousePositionData(eventdata); + self.dragStartX = eventdata.layerX; + + //Create dragging rectange + var rect = this.svg.append("rect") + .attr("x", self.dragStartX) + .attr("y", 0) + .attr("width", 1) + .attr("height", self.svg.style("height")) + .attr("opacity", 0.5) + .attr("fill", "yellow"); + } + } + + /** + * Gets called when the mouse gets released on the svg plane + * Calculates the result of dragging(selected Data) + * Draws the "green rectange" and destroys it + * @type {Object} eventdata - Mouse event data + */ + this.up = function(eventdata) { + var self = this; + + if(eventdata.button === 0 && self.dragging) { + //Stop dragging + self.dragging = false; + + //Get data point ad end location + var dragEndData = this.getMousePositionData(eventdata); + + //Calculate the selected start and end date + self.dragResult = { + dimension : self.xDimension, + startDate: self.x(self.dragStartData.date) < self.x(dragEndData.date) ? self.dragStartData.date : dragEndData.date, + endDate: self.x(self.dragStartData.date) > self.x(dragEndData.date) ? self.dragStartData.date : dragEndData.date + } + + //Adjusted X and Y position of the rectange to include all selected data + var adjustedStartX = self.x(self.dragResult.startDate); + var adjustedEndX = self.x(self.dragResult.endDate); + + //Solve problem with 0 width rectange + if(adjustedStartX === adjustedEndX) { + adjustedStartX -= 1; + adjustedEndX += 1; + } + + //Draw animation and destroy + self.svg.selectAll("rect") + .transition() + .duration(500) + .attr("x", adjustedStartX) + .attr("width", adjustedEndX - adjustedStartX) + .delay(50) + .transition() + .duration(100) + .attr("stroke-width", 10) + .attr("stroke", "green") + .delay(200) + .transition() + .duration(1000) + .attr("opacity", 0.0) + .remove(); + + this.dispatch.call('selectionchanged',self, self.dragResult); + } + } + + /** Draw paths **/ + + //Line to draw on svg plane, mapping data and indexes to lines + this.chartline = d3.line() + .defined(d => !isNaN(d)) + .x((d, i) => this.x(this.plotData.dates[i])) + .y(d => this.y(d)); + + //Create all g elements for lines in the plot + this.path = this.svg.append("g") + .attr("fill", "none") + .attr("stroke", "steelblue") + .attr("stroke-width", 1.5) + .attr("stroke-linejoin", "round") + .attr("stroke-linecap", "round") + + //Add all chartlines + this.path.selectAll("path") + .data(this.plotData.series.filter(entry => entry.show)) + .join("path") + .style("mix-blend-mode", "multiply") + .attr("d", d => self.chartline(d.values)); + + /** Add dot/circle to show current data point **/ + + //create Dot g element to show currently selected data + this.dot = this.svg.append("g") + .attr("display", "none"); + + //Add the circle + this.dot.append("circle") + .attr("r", 2.5); + + //Add text showing the uncertainty measure name + this.dot.append("text") + .attr("id", "dot_name_text") + .style("font", "10px sans-serif") + .attr("text-anchor", "middle") + .attr("y", -6); + + //Add text showing the current value of the uncertainty measure + this.dot.append("text") + .attr("id", "dot_number_text") + .style("font", "10px sans-serif") + .attr("text-anchor", "middle") + .attr("y", +10); + + return this.svg.node(); + } + + /*************************************** + * AXES + ***************************************/ + + /** @type {d3.scalePoint} - Scale for x axis on chart + * Maps dimension value to position (in pixels) along width of chart.*/ + this.x = (this.db.isStringDimension(this.xDimension) ? d3.scalePoint() : d3.scaleLinear()) + .domain(self.plotData.dimensionDomain) + .range([this.axismargin.left,self.internalWidth - this.axismargin.right]); + + /** @type {d3.scalePoint} - Scale for x axis on chart + * Maps measure values to position (in pixels) along height of chart.*/ + this.y = d3.scaleLinear() + .domain([0, d3.max(this.plotData.series, d => d3.max(d.values))]).nice() + .range([self.internalHeight - this.axismargin.bottom,this.axismargin.top]); + + //Container for the x-axis + this.xAxisContainer = d3.select(this.container).append('svg') + .classed('axisContainer x',true) + .style('position','absolute') + .style('width',this.internalWidth+'px') + .style('height',25+'px') + .style('top',this.margin.top+this.internalHeight+'px') + .style('left',this.margin.left+'px'); + + //Container for the y-axis + this.yAxisContainer = d3.select(this.container).append('svg') + .classed('axisContainer y',true) + .style('position','absolute') + .style('width',50+'px') + .style('height',this.internalHeight+'px') + .style('left',(this.margin.left-50)+'px') + .style('top',this.margin.top+'px'); + + //Draw the x-axis + this.xAxisContainer.append('g') + .classed('axis',true) + .call(d3.axisBottom().scale(this.x)); + + //Draw the y-axis + this.yAxisContainer.append('g') + .classed('axis',true) + .attr('transform','translate(50)') + .call(d3.axisLeft().scale(this.y)); + + //Save the width of the axis line to adjust the graph later on + this.axislineWidth = parseInt(getComputedStyle( + document.querySelector('.CINEMA_COMPONENT.LINE_CHART .axis line')) + .getPropertyValue('stroke-width'), 10); + + //Set the position of both axis + this.xAxisContainer.style('top',this.margin.top+this.internalHeight+this.axislineWidth+'px'); + this.yAxisContainer.style('left', (this.margin.left - 50 - this.axislineWidth) +'px'); + + /** @type {d3.selection (svg)} The SVG element containing all the content of the svg plane */ + this.chart = this.initChart(); + + //Draw + this.redraw(); + } + //establish prototype chain + CINEMA_COMPONENTS.LineChart.prototype = Object.create(CINEMA_COMPONENTS.Component.prototype); + CINEMA_COMPONENTS.LineChart.prototype.constructor = CINEMA_COMPONENTS.LineChart; + /** + * Should be called every time the size of the chart's container changes. + * Updates the sizing and scaling of all parts of the chart and redraws + */ + CINEMA_COMPONENTS.LineChart.prototype.updateSize = function() { + var self = this; + + //Call super (will recalculate size) + CINEMA_COMPONENTS.Component.prototype.updateSize.call(this); + + if(this.internalHeight > 100){ + //update mainContainer size + this.mainContainer + .style('width',this.internalWidth+'px') + .style('height',this.internalHeight+'px'); + + //update svg plane size + this.svg.attr('viewBox','0 0 '+this.internalWidth+' '+this.internalHeight); + + //Rescale + this.x.range([this.axismargin.left, this.internalWidth - this.axismargin.right]); + this.y.range([this.internalHeight - this.axismargin.bottom, this.axismargin.top]); + + //Update the x-axis + this.xAxisContainer + .style('width',this.internalWidth+'px') + .style('top',this.margin.top+this.internalHeight+this.axislineWidth+'px') + .select('.axis') + .call(d3.axisBottom().scale(this.x)); + + //Update the y-axis + this.yAxisContainer + .style('height',this.internalHeight+'px') + .select('.axis') + .call(d3.axisLeft().scale(this.y)); + + //Update the chart line drawing method + this.chartline + .x((d, i) => (this.plotData.isNonNumberDomain ? + self.x(this.plotData.dimensionDomain[i]) : + self.x(this.plotData.dates[i]))) + .y(d => this.y(d)) + + //Redraw all paths + this.path.selectAll("path") + .attr("d", d => self.chartline(d.values)); + } + }; + + /** + * Receive the closest data point to the current mouse location + * @type {Object} eventdata - Mouse event data + */ + CINEMA_COMPONENTS.LineChart.prototype.getMousePositionData = function(eventdata) { + var self = this; + + var scaleBandInvert = function(scale) { + var domain = self.x.domain(); + var paddingOuter = self.x(domain[0]); + var eachBand = self.x.step(); + return function (value) { + return Math.floor(((value - paddingOuter + (eachBand / 2)) / eachBand)); + //return domain[Math.max(0,Math.min(index, domain.length-1))]; + } + } + + //If any line is visible + if(this.getVisibileLineCount()) { + //Get the index of the closest x; + var ym = this.y.invert(eventdata.layerY); + var i; + + if(self.plotData.isNonNumberDomain) { + i = scaleBandInvert(self.x)(eventdata.layerX); + } + else { + var xm = this.x.invert(eventdata.layerX); + var i1 = d3.bisectLeft(this.plotData.dates, xm, 1); + var i0 = i1 - 1; + i = xm - self.plotData.dates[i0] > self.plotData.dates[i1] - xm ? i1 : i0; + } + + //Find closest point + var s = this.plotData.series.filter(entry => entry.show).reduce((a, b) => Math.abs(a.values[i] - ym) < Math.abs(b.values[i] - ym) ? a : b); + + //Save the selected point + this.currentlySelectedPoint = { + date: self.plotData.dates[i], + value: s.values[i], + umeasurename: s.name, + series: s + } + return this.currentlySelectedPoint; + } + } + + /** + * Redraw the chart path + */ + CINEMA_COMPONENTS.LineChart.prototype.redraw = function() { + var self = this; + + //Rescale x-axis + self.x + .domain(self.plotData.dimensionDomain) + .range([self.axismargin.left, self.internalWidth - self.axismargin.right]); + + //Rescale y-axis + self.y + .domain([ + d3.min(self.plotData.series.filter(entry => entry.show), d => d3.min(d.values)), + d3.max(self.plotData.series.filter(entry => entry.show), d => d3.max(d.values)) + ]).nice() + .range([self.internalHeight - self.axismargin.bottom, self.axismargin.top]); + + //Redraw x-axis + self.xAxisContainer + .select('.axis') + .call(d3.axisBottom().scale(self.x)); + + //Redraw y-axis + self.yAxisContainer + .select('.axis') + .call(d3.axisLeft().scale(self.y)); + + //Recalculate chartline method + self.chartline + .x((d, i) => (this.plotData.isNonNumberDomain ? + self.x(this.plotData.dimensionDomain[i]) : + self.x(this.plotData.dates[i]))) + .y(d => self.y(d)); + + //Enter Update Exit paths + var updatePaths = self.path.selectAll("path") + .data(this.plotData.series.filter(entry => entry.show)); + + updatePaths.enter() + .append('path') + .merge(updatePaths) + .join("path") + .style("mix-blend-mode", "multiply") + .attr("d", d => self.chartline(d.values)); + + updatePaths.exit() + .remove(); + }; + + /** + * Take the data from cinema DB and put it in a format readable for the plot + */ + CINEMA_COMPONENTS.LineChart.prototype.prepareData = function() { + var self = this; + + //Check if non number dimensions + var isNonNumberDomain = isNaN(this.db.dimensionDomains[this.xDimension][0]); + + //Retrieve all uncertainty dimensions + var uncertaintyDims = []; + for(var i=0, len=this.dimensions.length; i < len; i++) + if(startsWithPrefixes(self.dimensions[i], this.allowedUPrefixes) + && !startsWithPrefixes(self.dimensions[i], this.excludedDim)) + uncertaintyDims.push(this.dimensions[i]); + + //Retrieve all possible values of the current dimension + var dataDates = []; + if(isNonNumberDomain) { + dataDates = self.db.dimensionDomains[self.xDimension]; + } + else { + this.db.data.forEach(function(value) { + if(!containedInArray.call(dataDates, Number(value[self.xDimension]))) { + dataDates.push(Number(value[self.xDimension])); + } + }); + dataDates.sort(function(a, b){return a-b}); + } + + //Create data template + var dataSeries = []; + uncertaintyDims.forEach(function(value) { + dataSeries.push({ + name: value, + values : Array(dataDates.length).fill(0), + occurences : Array(dataDates.length).fill(0), + show : true + }); + }); + + //Fill with data values / Sum on same dimension value and count occurences + this.db.data.forEach(function(dataRow) { + var currentIndex = 0; + if(isNonNumberDomain) { + currentIndex = dataDates.indexOf(dataRow[self.xDimension]); + } + else { + currentIndex = dataDates.indexOf(Number(dataRow[self.xDimension])); + } + + dataSeries.forEach(function(dataSeriesObject) { + if(!isNaN(dataRow[dataSeriesObject.name])) { + dataSeriesObject.values[currentIndex] += parseFloat(dataRow[dataSeriesObject.name]); + dataSeriesObject.occurences[currentIndex] += 1; + } + }); + }); + + //Divide by occurences to retrieve the average + dataSeries.forEach(function(dataSeriesObject, indexObject) { + dataSeriesObject.values.forEach(function(dataValue, index) { + dataSeries[indexObject].values[index] = dataValue / dataSeriesObject.occurences[index]; + }); + }); + + //Add summed uncertainty measures for each dimension type => e.g. Total avg brightness uncertainty + this.allowedUPrefixes.forEach(function(uncertaintyDim, index) { + var averageUncertainty = Array(dataDates.length).fill(0); + var count = 0; + + //Sum and count + dataSeries.forEach(function(dataSeriesObject, indexObject) { + if(dataSeriesObject.name.startsWith(uncertaintyDim)) + { + dataSeriesObject.values.forEach(function(value, index) { + averageUncertainty[index] += value; + }); + count += 1; + } + }); + + //Calculate averages + if(count > 0) { + averageUncertainty.forEach(function(value, index) { + averageUncertainty[index] = value / count; + }); + + //Put into object + dataSeries.push({ + name: uncertaintyDim + " Uncertainty", + values : averageUncertainty, + occurences : count, + show : true + }); + } + }); + + //Combine the data + this.plotData = { + series: dataSeries, + dates: dataDates, + dimensionDomain : self.db.dimensionDomains[self.xDimension], + isNonNumberDomain : isNonNumberDomain + }; + }; + + /** + * Set the visibility of a line by using the uncertainty measure name + * @type {String} name - name of uncertainty measure + * @type {boolean} isShown - if the line shoudl be shown + */ + CINEMA_COMPONENTS.LineChart.prototype.setLineVisibility = function(name, isShown) { + var self = this; + for(var i = 0; i < this.plotData.series.length; i++) { + if(self.plotData.series[i].name === name) { + self.plotData.series[i].show = isShown; + break; + } + } + } + + /** + * Retrieve the amount of visible lines + */ + CINEMA_COMPONENTS.LineChart.prototype.getVisibileLineCount = function() { + return this.plotData.series.filter(entry => entry.show).length; + } + + /** + * Get the state of all checkboxes + */ + CINEMA_COMPONENTS.LineChart.prototype.getCheckboxStates = function() { + var lineGroupSelectData = []; + d3.selectAll(".lineGroupSelectCheckbox").each(function(d) { + const cb = d3.select(this); + lineGroupSelectData.push([cb.property("value"), cb.property("checked")]); + }); + var lineSelectData = []; + d3.selectAll(".lineSelectCheckbox").each(function(d) { + const cb = d3.select(this); + lineSelectData.push([cb.property("value"), cb.property("checked")]); + }); + + return {lineGroup: lineGroupSelectData, line: lineSelectData}; + } + + /** + * Set the state of all checkboxes + */ + CINEMA_COMPONENTS.LineChart.prototype.setCheckboxStates = function(dataObject) { + d3.selectAll(".lineSelectCheckbox").each(function(d) { + const cb = d3.select(this); + for(var i = 0; i < dataObject.line.length; i++) { + if(dataObject.line[i][0] === cb.property("value")) + cb.property("checked", dataObject.line[i][1]) ; + } + }); + var lineGroupSelectData = []; + d3.selectAll(".lineGroupSelectCheckbox").each(function(d) { + const cb = d3.select(this); + for(var i = 0; i < dataObject.lineGroup.length; i++) { + if(dataObject.lineGroup[i][0] === cb.property("value")) + cb.property("checked", dataObject.lineGroup[i][1]); + } + }); + this.updateLineVisibility(); + } + + /** + * Retrieve if a value is contained in an array + * @param {ANY} needle - Element to search for in Array + */ + var containedInArray = function(needle) { + //Per spec, the way to identify NaN is that it is not equal to itself + var findNaN = needle !== needle; + var indexOf; + + if(!findNaN && typeof Array.prototype.indexOf === 'function') { + indexOf = Array.prototype.indexOf; + } + else { + indexOf = function(needle) { + var i = -1, index = -1; + + for(i = 0; i < this.length; i++) { + var item = this[i]; + + if((findNaN && item !== item) || item === needle) { + index = i; + break; + } + } + + return index; + }; + } + + return indexOf.call(this, needle) > -1; + }; + + /** @type {RegExp} - Regular Expression to check for scientific notation*/ + const scientificNotationRegExp = new RegExp(/^((\d)+|(\d+\.\d+))(e|E)(\+|-)(\d)+$/); + + /** + * Check if numberString is in scientifc notation + * @param {String} numberString - String which might contain a scientific notation + */ + var isInScientificNotation = function(numberString) { + if(typeof numberString === 'string' || numberString instanceof String) + if(scientificNotationRegExp.test(numberString)) + return true; + return false; + } + + /** + * Checks if a dimension name starts with a string from the list + * @type {String} dimension - name of the dimension to check + * @type {Array} prefixList - list of prefixes + */ + var startsWithPrefixes = function(dimension, prefixList) { + if(typeof prefixList === 'undefined') + return false; + for(var i = 0; i < prefixList.length; i++) { + if(dimension.startsWith(prefixList[i])) + return true; + } + return false; + } + +})(); diff --git a/cinema/lib/cinemacomponents.license.md b/cinema/lib/cinemacomponents.license.md new file mode 100644 index 0000000..dfa7aa1 --- /dev/null +++ b/cinema/lib/cinemacomponents.license.md @@ -0,0 +1,27 @@ +Copyright (c) 2018-2019, Triad National Security, LLC. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of Los Alamos National Security, LLC, Los Alamos National + Laboratory, LANL, the U.S. Government, nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE + COPYRIGHT HOLDERS CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED + WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + EVENT SHALL LOS ALAMOS NATIONAL SECURITY, LLC OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + DAMAGE. diff --git a/cinema/lib/d3.license.md b/cinema/lib/d3.license.md new file mode 100644 index 0000000..b014515 --- /dev/null +++ b/cinema/lib/d3.license.md @@ -0,0 +1,13 @@ +Copyright 2010-2021 Mike Bostock + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/cinema/lib/d3.v5.min.js b/cinema/lib/d3.v5.min.js new file mode 100644 index 0000000..6b882ae --- /dev/null +++ b/cinema/lib/d3.v5.min.js @@ -0,0 +1,2 @@ +// https://d3js.org v5.9.2 Copyright 2019 Mike Bostock +!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(t.d3=t.d3||{})}(this,function(t){"use strict";function n(t,n){return tn?1:t>=n?0:NaN}function e(t){var e;return 1===t.length&&(e=t,t=function(t,r){return n(e(t),r)}),{left:function(n,e,r,i){for(null==r&&(r=0),null==i&&(i=n.length);r>>1;t(n[o],e)<0?r=o+1:i=o}return r},right:function(n,e,r,i){for(null==r&&(r=0),null==i&&(i=n.length);r>>1;t(n[o],e)>0?i=o:r=o+1}return r}}}var r=e(n),i=r.right,o=r.left;function a(t,n){return[t,n]}function u(t){return null===t?NaN:+t}function c(t,n){var e,r,i=t.length,o=0,a=-1,c=0,f=0;if(null==n)for(;++a1)return f/(o-1)}function f(t,n){var e=c(t,n);return e?Math.sqrt(e):e}function s(t,n){var e,r,i,o=t.length,a=-1;if(null==n){for(;++a=e)for(r=i=e;++ae&&(r=e),i=e)for(r=i=e;++ae&&(r=e),i0)return[t];if((r=n0)for(t=Math.ceil(t/a),n=Math.floor(n/a),o=new Array(i=Math.ceil(n-t+1));++u=0?(o>=y?10:o>=_?5:o>=b?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(o>=y?10:o>=_?5:o>=b?2:1)}function w(t,n,e){var r=Math.abs(n-t)/Math.max(0,e),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),o=r/i;return o>=y?i*=10:o>=_?i*=5:o>=b&&(i*=2),n=1)return+e(t[r-1],r-1,t);var r,i=(r-1)*n,o=Math.floor(i),a=+e(t[o],o,t);return a+(+e(t[o+1],o+1,t)-a)*(i-o)}}function A(t,n){var e,r,i=t.length,o=-1;if(null==n){for(;++o=e)for(r=e;++or&&(r=e)}else for(;++o=e)for(r=e;++or&&(r=e);return r}function T(t){for(var n,e,r,i=t.length,o=-1,a=0;++o=0;)for(n=(r=t[i]).length;--n>=0;)e[--a]=r[n];return e}function S(t,n){var e,r,i=t.length,o=-1;if(null==n){for(;++o=e)for(r=e;++oe&&(r=e)}else for(;++o=e)for(r=e;++oe&&(r=e);return r}function k(t){if(!(i=t.length))return[];for(var n=-1,e=S(t,E),r=new Array(e);++n=0&&(n=t.slice(e+1),t=t.slice(0,e)),t&&!r.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}})),a=-1,u=o.length;if(!(arguments.length<2)){if(null!=n&&"function"!=typeof n)throw new Error("invalid callback: "+n);for(;++a0)for(var e,r,i=new Array(e),o=0;o=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),V.hasOwnProperty(n)?{space:V[n],local:t}:t}function W(t){var n=$(t);return(n.local?function(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}:function(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===G&&n.documentElement.namespaceURI===G?n.createElement(t):n.createElementNS(e,t)}})(n)}function Z(){}function Q(t){return null==t?Z:function(){return this.querySelector(t)}}function J(){return[]}function K(t){return null==t?J:function(){return this.querySelectorAll(t)}}function tt(t){return function(){return this.matches(t)}}function nt(t){return new Array(t.length)}function et(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}et.prototype={constructor:et,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,n){return this._parent.insertBefore(t,n)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var rt="$";function it(t,n,e,r,i,o){for(var a,u=0,c=n.length,f=o.length;un?1:t>=n?0:NaN}function ut(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function ct(t,n){return t.style.getPropertyValue(n)||ut(t).getComputedStyle(t,null).getPropertyValue(n)}function ft(t){return t.trim().split(/^|\s+/)}function st(t){return t.classList||new lt(t)}function lt(t){this._node=t,this._names=ft(t.getAttribute("class")||"")}function ht(t,n){for(var e=st(t),r=-1,i=n.length;++r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var wt={};(t.event=null,"undefined"!=typeof document)&&("onmouseenter"in document.documentElement||(wt={mouseenter:"mouseover",mouseleave:"mouseout"}));function Mt(t,n,e){return t=Nt(t,n,e),function(n){var e=n.relatedTarget;e&&(e===this||8&e.compareDocumentPosition(this))||t.call(this,n)}}function Nt(n,e,r){return function(i){var o=t.event;t.event=i;try{n.call(this,this.__data__,e,r)}finally{t.event=o}}}function At(t){return function(){var n=this.__on;if(n){for(var e,r=0,i=-1,o=n.length;r=x&&(x=m+1);!(b=y[x])&&++x=0;)(r=i[o])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=at);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?function(t){return function(){this.style.removeProperty(t)}}:"function"==typeof n?function(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}:function(t,n,e){return function(){this.style.setProperty(t,n,e)}})(t,n,null==e?"":e)):ct(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?function(t){return function(){delete this[t]}}:"function"==typeof n?function(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}:function(t,n){return function(){this[t]=n}})(t,n)):this.node()[t]},classed:function(t,n){var e=ft(t+"");if(arguments.length<2){for(var r=st(this.node()),i=-1,o=e.length;++i=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}})}(t+""),a=o.length;if(!(arguments.length<2)){for(u=n?Tt:At,null==e&&(e=!1),r=0;r>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):(n=rn.exec(t))?dn(parseInt(n[1],16)):(n=on.exec(t))?new yn(n[1],n[2],n[3],1):(n=an.exec(t))?new yn(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=un.exec(t))?pn(n[1],n[2],n[3],n[4]):(n=cn.exec(t))?pn(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=fn.exec(t))?bn(n[1],n[2]/100,n[3]/100,1):(n=sn.exec(t))?bn(n[1],n[2]/100,n[3]/100,n[4]):ln.hasOwnProperty(t)?dn(ln[t]):"transparent"===t?new yn(NaN,NaN,NaN,0):null}function dn(t){return new yn(t>>16&255,t>>8&255,255&t,1)}function pn(t,n,e,r){return r<=0&&(t=n=e=NaN),new yn(t,n,e,r)}function vn(t){return t instanceof Jt||(t=hn(t)),t?new yn((t=t.rgb()).r,t.g,t.b,t.opacity):new yn}function gn(t,n,e,r){return 1===arguments.length?vn(t):new yn(t,n,e,null==r?1:r)}function yn(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function _n(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function bn(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new xn(t,n,e,r)}function mn(t,n,e,r){return 1===arguments.length?function(t){if(t instanceof xn)return new xn(t.h,t.s,t.l,t.opacity);if(t instanceof Jt||(t=hn(t)),!t)return new xn;if(t instanceof xn)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),a=NaN,u=o-i,c=(o+i)/2;return u?(a=n===o?(e-r)/u+6*(e0&&c<1?0:a,new xn(a,u,c,t.opacity)}(t):new xn(t,n,e,null==r?1:r)}function xn(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function wn(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}Zt(Jt,hn,{displayable:function(){return this.rgb().displayable()},hex:function(){return this.rgb().hex()},toString:function(){return this.rgb()+""}}),Zt(yn,gn,Qt(Jt,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new yn(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new yn(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return 0<=this.r&&this.r<=255&&0<=this.g&&this.g<=255&&0<=this.b&&this.b<=255&&0<=this.opacity&&this.opacity<=1},hex:function(){return"#"+_n(this.r)+_n(this.g)+_n(this.b)},toString:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}})),Zt(xn,mn,Qt(Jt,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new xn(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new xn(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new yn(wn(t>=240?t-240:t+120,i,r),wn(t,i,r),wn(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1}}));var Mn=Math.PI/180,Nn=180/Math.PI,An=.96422,Tn=1,Sn=.82521,kn=4/29,En=6/29,Cn=3*En*En,Pn=En*En*En;function zn(t){if(t instanceof Dn)return new Dn(t.l,t.a,t.b,t.opacity);if(t instanceof Fn){if(isNaN(t.h))return new Dn(t.l,0,0,t.opacity);var n=t.h*Mn;return new Dn(t.l,Math.cos(n)*t.c,Math.sin(n)*t.c,t.opacity)}t instanceof yn||(t=vn(t));var e,r,i=On(t.r),o=On(t.g),a=On(t.b),u=qn((.2225045*i+.7168786*o+.0606169*a)/Tn);return i===o&&o===a?e=r=u:(e=qn((.4360747*i+.3850649*o+.1430804*a)/An),r=qn((.0139322*i+.0971045*o+.7141733*a)/Sn)),new Dn(116*u-16,500*(e-u),200*(u-r),t.opacity)}function Rn(t,n,e,r){return 1===arguments.length?zn(t):new Dn(t,n,e,null==r?1:r)}function Dn(t,n,e,r){this.l=+t,this.a=+n,this.b=+e,this.opacity=+r}function qn(t){return t>Pn?Math.pow(t,1/3):t/Cn+kn}function Ln(t){return t>En?t*t*t:Cn*(t-kn)}function Un(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function On(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Bn(t){if(t instanceof Fn)return new Fn(t.h,t.c,t.l,t.opacity);if(t instanceof Dn||(t=zn(t)),0===t.a&&0===t.b)return new Fn(NaN,0,t.l,t.opacity);var n=Math.atan2(t.b,t.a)*Nn;return new Fn(n<0?n+360:n,Math.sqrt(t.a*t.a+t.b*t.b),t.l,t.opacity)}function Yn(t,n,e,r){return 1===arguments.length?Bn(t):new Fn(t,n,e,null==r?1:r)}function Fn(t,n,e,r){this.h=+t,this.c=+n,this.l=+e,this.opacity=+r}Zt(Dn,Rn,Qt(Jt,{brighter:function(t){return new Dn(this.l+18*(null==t?1:t),this.a,this.b,this.opacity)},darker:function(t){return new Dn(this.l-18*(null==t?1:t),this.a,this.b,this.opacity)},rgb:function(){var t=(this.l+16)/116,n=isNaN(this.a)?t:t+this.a/500,e=isNaN(this.b)?t:t-this.b/200;return new yn(Un(3.1338561*(n=An*Ln(n))-1.6168667*(t=Tn*Ln(t))-.4906146*(e=Sn*Ln(e))),Un(-.9787684*n+1.9161415*t+.033454*e),Un(.0719453*n-.2289914*t+1.4052427*e),this.opacity)}})),Zt(Fn,Yn,Qt(Jt,{brighter:function(t){return new Fn(this.h,this.c,this.l+18*(null==t?1:t),this.opacity)},darker:function(t){return new Fn(this.h,this.c,this.l-18*(null==t?1:t),this.opacity)},rgb:function(){return zn(this).rgb()}}));var In=-.14861,jn=1.78277,Hn=-.29227,Xn=-.90649,Gn=1.97294,Vn=Gn*Xn,$n=Gn*jn,Wn=jn*Hn-Xn*In;function Zn(t,n,e,r){return 1===arguments.length?function(t){if(t instanceof Qn)return new Qn(t.h,t.s,t.l,t.opacity);t instanceof yn||(t=vn(t));var n=t.r/255,e=t.g/255,r=t.b/255,i=(Wn*r+Vn*n-$n*e)/(Wn+Vn-$n),o=r-i,a=(Gn*(e-i)-Hn*o)/Xn,u=Math.sqrt(a*a+o*o)/(Gn*i*(1-i)),c=u?Math.atan2(a,o)*Nn-120:NaN;return new Qn(c<0?c+360:c,u,i,t.opacity)}(t):new Qn(t,n,e,null==r?1:r)}function Qn(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function Jn(t,n,e,r,i){var o=t*t,a=o*t;return((1-3*t+3*o-a)*n+(4-6*o+3*a)*e+(1+3*t+3*o-3*a)*r+a*i)/6}function Kn(t){var n=t.length-1;return function(e){var r=e<=0?e=0:e>=1?(e=1,n-1):Math.floor(e*n),i=t[r],o=t[r+1],a=r>0?t[r-1]:2*i-o,u=r180||e<-180?e-360*Math.round(e/360):e):ne(isNaN(t)?n:t)}function ie(t){return 1==(t=+t)?oe:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):ne(isNaN(n)?e:n)}}function oe(t,n){var e=n-t;return e?ee(t,e):ne(isNaN(t)?n:t)}Zt(Qn,Zn,Qt(Jt,{brighter:function(t){return t=null==t?1/.7:Math.pow(1/.7,t),new Qn(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?.7:Math.pow(.7,t),new Qn(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=isNaN(this.h)?0:(this.h+120)*Mn,n=+this.l,e=isNaN(this.s)?0:this.s*n*(1-n),r=Math.cos(t),i=Math.sin(t);return new yn(255*(n+e*(In*r+jn*i)),255*(n+e*(Hn*r+Xn*i)),255*(n+e*(Gn*r)),this.opacity)}}));var ae=function t(n){var e=ie(n);function r(t,n){var r=e((t=gn(t)).r,(n=gn(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),a=oe(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=a(n),t+""}}return r.gamma=t,r}(1);function ue(t){return function(n){var e,r,i=n.length,o=new Array(i),a=new Array(i),u=new Array(i);for(e=0;eo&&(i=n.slice(o,i),u[a]?u[a]+=i:u[++a]=i),(e=e[0])===(r=r[0])?u[a]?u[a]+=r:u[++a]=r:(u[++a]=null,c.push({i:a,x:he(e,r)})),o=ve.lastIndex;return o180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:he(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,a.rotate,u,c),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:he(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,a.skewX,u,c),function(t,n,e,r,o,a){if(t!==e||n!==r){var u=o.push(i(o)+"scale(",null,",",null,")");a.push({i:u-4,x:he(t,e)},{i:u-2,x:he(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,a.scaleX,a.scaleY,u,c),o=a=null,function(t){for(var n,e=-1,r=c.length;++e=0&&n._call.call(null,t),n=n._next;--Ge}function ar(){Qe=(Ze=Ke.now())+Je,Ge=Ve=0;try{or()}finally{Ge=0,function(){var t,n,e=He,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:He=n);Xe=t,cr(r)}(),Qe=0}}function ur(){var t=Ke.now(),n=t-Ze;n>We&&(Je-=n,Ze=t)}function cr(t){Ge||(Ve&&(Ve=clearTimeout(Ve)),t-Qe>24?(t<1/0&&(Ve=setTimeout(ar,t-Ke.now()-Je)),$e&&($e=clearInterval($e))):($e||(Ze=Ke.now(),$e=setInterval(ur,We)),Ge=1,tr(ar)))}function fr(t,n,e){var r=new rr;return n=null==n?0:+n,r.restart(function(e){r.stop(),t(e+n)},n,e),r}rr.prototype=ir.prototype={constructor:rr,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?nr():+e)+(null==n?0:+n),this._next||Xe===this||(Xe?Xe._next=this:He=this,Xe=this),this._call=t,this._time=e,cr()},stop:function(){this._call&&(this._call=null,this._time=1/0,cr())}};var sr=I("start","end","cancel","interrupt"),lr=[],hr=0,dr=1,pr=2,vr=3,gr=4,yr=5,_r=6;function br(t,n,e,r,i,o){var a=t.__transition;if(a){if(e in a)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(c){var f,s,l,h;if(e.state!==dr)return u();for(f in i)if((h=i[f]).name===e.name){if(h.state===vr)return fr(o);h.state===gr?(h.state=_r,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[f]):+fhr)throw new Error("too late; already scheduled");return e}function xr(t,n){var e=wr(t,n);if(e.state>vr)throw new Error("too late; already running");return e}function wr(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function Mr(t,n){var e,r,i,o=t.__transition,a=!0;if(o){for(i in n=null==n?null:n+"",o)(e=o[i]).name===n?(r=e.state>pr&&e.state=0&&(t=t.slice(0,n)),!t||"start"===t})}(n)?mr:xr;return function(){var a=o(this,t),u=a.on;u!==r&&(i=(r=u).copy()).on(n,e),a.on=i}}(e,t,n))},attr:function(t,n){var e=$(t),r="transform"===e?ke:Ar;return this.attrTween(t,"function"==typeof n?(e.local?function(t,n,e){var r,i,o;return function(){var a,u,c=e(this);if(null!=c)return(a=this.getAttributeNS(t.space,t.local))===(u=c+"")?null:a===r&&u===i?o:(i=u,o=n(r=a,c));this.removeAttributeNS(t.space,t.local)}}:function(t,n,e){var r,i,o;return function(){var a,u,c=e(this);if(null!=c)return(a=this.getAttribute(t))===(u=c+"")?null:a===r&&u===i?o:(i=u,o=n(r=a,c));this.removeAttribute(t)}})(e,r,Nr(this,"attr."+t,n)):null==n?(e.local?function(t){return function(){this.removeAttributeNS(t.space,t.local)}}:function(t){return function(){this.removeAttribute(t)}})(e):(e.local?function(t,n,e){var r,i,o=e+"";return function(){var a=this.getAttributeNS(t.space,t.local);return a===o?null:a===r?i:i=n(r=a,e)}}:function(t,n,e){var r,i,o=e+"";return function(){var a=this.getAttribute(t);return a===o?null:a===r?i:i=n(r=a,e)}})(e,r,n))},attrTween:function(t,n){var e="attr."+t;if(arguments.length<2)return(e=this.tween(e))&&e._value;if(null==n)return this.tween(e,null);if("function"!=typeof n)throw new Error;var r=$(t);return this.tween(e,(r.local?function(t,n){var e,r;function i(){var i=n.apply(this,arguments);return i!==r&&(e=(r=i)&&function(t,n){return function(e){this.setAttributeNS(t.space,t.local,n(e))}}(t,i)),e}return i._value=n,i}:function(t,n){var e,r;function i(){var i=n.apply(this,arguments);return i!==r&&(e=(r=i)&&function(t,n){return function(e){this.setAttribute(t,n(e))}}(t,i)),e}return i._value=n,i})(r,n))},style:function(t,n,e){var r="transform"==(t+="")?Se:Ar;return null==n?this.styleTween(t,function(t,n){var e,r,i;return function(){var o=ct(this,t),a=(this.style.removeProperty(t),ct(this,t));return o===a?null:o===e&&a===r?i:i=n(e=o,r=a)}}(t,r)).on("end.style."+t,Sr(t)):"function"==typeof n?this.styleTween(t,function(t,n,e){var r,i,o;return function(){var a=ct(this,t),u=e(this),c=u+"";return null==u&&(this.style.removeProperty(t),c=u=ct(this,t)),a===c?null:a===r&&c===i?o:(i=c,o=n(r=a,u))}}(t,r,Nr(this,"style."+t,n))).each(function(t,n){var e,r,i,o,a="style."+n,u="end."+a;return function(){var c=xr(this,t),f=c.on,s=null==c.value[a]?o||(o=Sr(n)):void 0;f===e&&i===s||(r=(e=f).copy()).on(u,i=s),c.on=r}}(this._id,t)):this.styleTween(t,function(t,n,e){var r,i,o=e+"";return function(){var a=ct(this,t);return a===o?null:a===r?i:i=n(r=a,e)}}(t,r,n),e).on("end.style."+t,null)},styleTween:function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,function(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&function(t,n,e){return function(r){this.style.setProperty(t,n(r),e)}}(t,o,e)),r}return o._value=n,o}(t,n,null==e?"":e))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var n=t(this);this.textContent=null==n?"":n}}(Nr(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},remove:function(){return this.on("end.remove",(t=this._id,function(){var n=this.parentNode;for(var e in this.__transition)if(+e!==t)return;n&&n.removeChild(this)}));var t},tween:function(t,n){var e=this._id;if(t+="",arguments.length<2){for(var r,i=wr(this.node(),e).tween,o=0,a=i.length;o0&&(r=o-p),M<0?h=d-v:M>0&&(a=u-v),x=vi,L.attr("cursor",xi.selection),B());break;default:return}di()},!0).on("keyup.brush",function(){switch(t.event.keyCode){case 16:P&&(y=_=P=!1,B());break;case 18:x===yi&&(w<0?s=l:w>0&&(r=o),M<0?h=d:M>0&&(a=u),x=gi,B());break;case 32:x===vi&&(t.event.altKey?(w&&(s=l-p*w,r=o+p*w),M&&(h=d-v*M,a=u+v*M),x=yi):(w<0?s=l:w>0&&(r=o),M<0?h=d:M>0&&(a=u),x=gi),L.attr("cursor",xi[m]),B());break;default:return}di()},!0).on("mousemove.brush",O,!0).on("mouseup.brush",Y,!0);It(t.event.view)}hi(),Mr(b),c.call(b),D.start()}function O(){var t=Ot(b);!P||y||_||(Math.abs(t[0]-R[0])>Math.abs(t[1]-R[1])?_=!0:y=!0),R=t,g=!0,di(),B()}function B(){var t;switch(p=R[0]-z[0],v=R[1]-z[1],x){case vi:case pi:w&&(p=Math.max(S-r,Math.min(E-s,p)),o=r+p,l=s+p),M&&(v=Math.max(k-a,Math.min(C-h,v)),u=a+v,d=h+v);break;case gi:w<0?(p=Math.max(S-r,Math.min(E-r,p)),o=r+p,l=s):w>0&&(p=Math.max(S-s,Math.min(E-s,p)),o=r,l=s+p),M<0?(v=Math.max(k-a,Math.min(C-a,v)),u=a+v,d=h):M>0&&(v=Math.max(k-h,Math.min(C-h,v)),u=a,d=h+v);break;case yi:w&&(o=Math.max(S,Math.min(E,r-p*w)),l=Math.max(S,Math.min(E,s+p*w))),M&&(u=Math.max(k,Math.min(C,a-v*M)),d=Math.max(k,Math.min(C,h+v*M)))}l1e-6)if(Math.abs(s*u-c*f)>1e-6&&i){var h=e-o,d=r-a,p=u*u+c*c,v=h*h+d*d,g=Math.sqrt(p),y=Math.sqrt(l),_=i*Math.tan((Yi-Math.acos((p+l-v)/(2*g*y)))/2),b=_/y,m=_/g;Math.abs(b-1)>1e-6&&(this._+="L"+(t+b*f)+","+(n+b*s)),this._+="A"+i+","+i+",0,0,"+ +(s*h>f*d)+","+(this._x1=t+m*u)+","+(this._y1=n+m*c)}else this._+="L"+(this._x1=t)+","+(this._y1=n);else;},arc:function(t,n,e,r,i,o){t=+t,n=+n;var a=(e=+e)*Math.cos(r),u=e*Math.sin(r),c=t+a,f=n+u,s=1^o,l=o?r-i:i-r;if(e<0)throw new Error("negative radius: "+e);null===this._x1?this._+="M"+c+","+f:(Math.abs(this._x1-c)>1e-6||Math.abs(this._y1-f)>1e-6)&&(this._+="L"+c+","+f),e&&(l<0&&(l=l%Fi+Fi),l>Ii?this._+="A"+e+","+e+",0,1,"+s+","+(t-a)+","+(n-u)+"A"+e+","+e+",0,1,"+s+","+(this._x1=c)+","+(this._y1=f):l>1e-6&&(this._+="A"+e+","+e+",0,"+ +(l>=Yi)+","+s+","+(this._x1=t+e*Math.cos(i))+","+(this._y1=n+e*Math.sin(i))))},rect:function(t,n,e,r){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+n)+"h"+ +e+"v"+ +r+"h"+-e+"Z"},toString:function(){return this._}};function Zi(){}function Qi(t,n){var e=new Zi;if(t instanceof Zi)t.each(function(t,n){e.set(n,t)});else if(Array.isArray(t)){var r,i=-1,o=t.length;if(null==n)for(;++ir!=d>r&&e<(h-f)*(r-s)/(d-s)+f&&(i=-i)}return i}function so(t,n,e){var r,i,o,a;return function(t,n,e){return(n[0]-t[0])*(e[1]-t[1])==(e[0]-t[0])*(n[1]-t[1])}(t,n,e)&&(i=t[r=+(t[0]===n[0])],o=e[r],a=n[r],i<=o&&o<=a||a<=o&&o<=i)}function lo(){}var ho=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function po(){var t=1,n=1,e=M,r=u;function i(t){var n=e(t);if(Array.isArray(n))n=n.slice().sort(ao);else{var r=s(t),i=r[0],a=r[1];n=w(i,a,n),n=g(Math.floor(i/n)*n,Math.floor(a/n)*n,n)}return n.map(function(n){return o(t,n)})}function o(e,i){var o=[],u=[];return function(e,r,i){var o,u,c,f,s,l,h=new Array,d=new Array;o=u=-1,f=e[0]>=r,ho[f<<1].forEach(p);for(;++o=r,ho[c|f<<1].forEach(p);ho[f<<0].forEach(p);for(;++u=r,s=e[u*t]>=r,ho[f<<1|s<<2].forEach(p);++o=r,l=s,s=e[u*t+o+1]>=r,ho[c|f<<1|s<<2|l<<3].forEach(p);ho[f|s<<3].forEach(p)}o=-1,s=e[u*t]>=r,ho[s<<2].forEach(p);for(;++o=r,ho[s<<2|l<<3].forEach(p);function p(t){var n,e,r=[t[0][0]+o,t[0][1]+u],c=[t[1][0]+o,t[1][1]+u],f=a(r),s=a(c);(n=d[f])?(e=h[s])?(delete d[n.end],delete h[e.start],n===e?(n.ring.push(c),i(n.ring)):h[n.start]=d[e.end]={start:n.start,end:e.end,ring:n.ring.concat(e.ring)}):(delete d[n.end],n.ring.push(c),d[n.end=s]=n):(n=h[s])?(e=d[f])?(delete h[n.start],delete d[e.end],n===e?(n.ring.push(c),i(n.ring)):h[e.start]=d[n.end]={start:e.start,end:n.end,ring:e.ring.concat(n.ring)}):(delete h[n.start],n.ring.unshift(r),h[n.start=f]=n):h[f]=d[s]={start:f,end:s,ring:[r,c]}}ho[s<<3].forEach(p)}(e,i,function(t){r(t,e,i),function(t){for(var n=0,e=t.length,r=t[e-1][1]*t[0][0]-t[e-1][0]*t[0][1];++n0?o.push([t]):u.push(t)}),u.forEach(function(t){for(var n,e=0,r=o.length;e0&&a0&&u0&&o>0))throw new Error("invalid size");return t=r,n=o,i},i.thresholds=function(t){return arguments.length?(e="function"==typeof t?t:Array.isArray(t)?uo(oo.call(t)):uo(t),i):e},i.smooth=function(t){return arguments.length?(r=t?u:lo,i):r===u},i}function vo(t,n,e){for(var r=t.width,i=t.height,o=1+(e<<1),a=0;a=e&&(u>=o&&(c-=t.data[u-o+a*r]),n.data[u-e+a*r]=c/Math.min(u+1,r-1+o-u,o))}function go(t,n,e){for(var r=t.width,i=t.height,o=1+(e<<1),a=0;a=e&&(u>=o&&(c-=t.data[a+(u-o)*r]),n.data[a+(u-e)*r]=c/Math.min(u+1,i-1+o-u,o))}function yo(t){return t[0]}function _o(t){return t[1]}function bo(){return 1}var mo={},xo={},wo=34,Mo=10,No=13;function Ao(t){return new Function("d","return {"+t.map(function(t,n){return JSON.stringify(t)+": d["+n+"]"}).join(",")+"}")}function To(t){var n=Object.create(null),e=[];return t.forEach(function(t){for(var r in t)r in n||e.push(n[r]=r)}),e}function So(t,n){var e=t+"",r=e.length;return r9999?"+"+So(n,6):So(n,4))+"-"+So(t.getUTCMonth()+1,2)+"-"+So(t.getUTCDate(),2)+(o?"T"+So(e,2)+":"+So(r,2)+":"+So(i,2)+"."+So(o,3)+"Z":i?"T"+So(e,2)+":"+So(r,2)+":"+So(i,2)+"Z":r||e?"T"+So(e,2)+":"+So(r,2)+"Z":"")}function Eo(t){var n=new RegExp('["'+t+"\n\r]"),e=t.charCodeAt(0);function r(t,n){var r,i=[],o=t.length,a=0,u=0,c=o<=0,f=!1;function s(){if(c)return xo;if(f)return f=!1,mo;var n,r,i=a;if(t.charCodeAt(i)===wo){for(;a++=o?c=!0:(r=t.charCodeAt(a++))===Mo?f=!0:r===No&&(f=!0,t.charCodeAt(a)===Mo&&++a),t.slice(i+1,n-1).replace(/""/g,'"')}for(;a=(o=(v+y)/2))?v=o:y=o,(s=e>=(a=(g+_)/2))?g=a:_=a,i=d,!(d=d[l=s<<1|f]))return i[l]=p,t;if(u=+t._x.call(null,d.data),c=+t._y.call(null,d.data),n===u&&e===c)return p.next=d,i?i[l]=p:t._root=p,t;do{i=i?i[l]=new Array(4):t._root=new Array(4),(f=n>=(o=(v+y)/2))?v=o:y=o,(s=e>=(a=(g+_)/2))?g=a:_=a}while((l=s<<1|f)==(h=(c>=a)<<1|u>=o));return i[h]=d,i[l]=p,t}function ra(t,n,e,r,i){this.node=t,this.x0=n,this.y0=e,this.x1=r,this.y1=i}function ia(t){return t[0]}function oa(t){return t[1]}function aa(t,n,e){var r=new ua(null==n?ia:n,null==e?oa:e,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function ua(t,n,e,r,i,o){this._x=t,this._y=n,this._x0=e,this._y0=r,this._x1=i,this._y1=o,this._root=void 0}function ca(t){for(var n={data:t.data},e=n;t=t.next;)e=e.next={data:t.data};return n}var fa=aa.prototype=ua.prototype;function sa(t){return t.x+t.vx}function la(t){return t.y+t.vy}function ha(t){return t.index}function da(t,n){var e=t.get(n);if(!e)throw new Error("missing: "+n);return e}function pa(t){return t.x}function va(t){return t.y}fa.copy=function(){var t,n,e=new ua(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return e;if(!r.length)return e._root=ca(r),e;for(t=[{source:r,target:e._root=new Array(4)}];r=t.pop();)for(var i=0;i<4;++i)(n=r.source[i])&&(n.length?t.push({source:n,target:r.target[i]=new Array(4)}):r.target[i]=ca(n));return e},fa.add=function(t){var n=+this._x.call(null,t),e=+this._y.call(null,t);return ea(this.cover(n,e),n,e,t)},fa.addAll=function(t){var n,e,r,i,o=t.length,a=new Array(o),u=new Array(o),c=1/0,f=1/0,s=-1/0,l=-1/0;for(e=0;es&&(s=r),il&&(l=i));if(c>s||f>l)return this;for(this.cover(c,f).cover(s,l),e=0;et||t>=i||r>n||n>=o;)switch(u=(nh||(o=c.y0)>d||(a=c.x1)=y)<<1|t>=g)&&(c=p[p.length-1],p[p.length-1]=p[p.length-1-f],p[p.length-1-f]=c)}else{var _=t-+this._x.call(null,v.data),b=n-+this._y.call(null,v.data),m=_*_+b*b;if(m=(u=(p+g)/2))?p=u:g=u,(s=a>=(c=(v+y)/2))?v=c:y=c,n=d,!(d=d[l=s<<1|f]))return this;if(!d.length)break;(n[l+1&3]||n[l+2&3]||n[l+3&3])&&(e=n,h=l)}for(;d.data!==t;)if(r=d,!(d=d.next))return this;return(i=d.next)&&delete d.next,r?(i?r.next=i:delete r.next,this):n?(i?n[l]=i:delete n[l],(d=n[0]||n[1]||n[2]||n[3])&&d===(n[3]||n[2]||n[1]||n[0])&&!d.length&&(e?e[h]=d:this._root=d),this):(this._root=i,this)},fa.removeAll=function(t){for(var n=0,e=t.length;n1?r[0]+r.slice(2):r,+t.slice(e+1)]}function ba(t){return(t=_a(Math.abs(t)))?t[1]:NaN}var ma,xa=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function wa(t){return new Ma(t)}function Ma(t){if(!(n=xa.exec(t)))throw new Error("invalid format: "+t);var n;this.fill=n[1]||" ",this.align=n[2]||">",this.sign=n[3]||"-",this.symbol=n[4]||"",this.zero=!!n[5],this.width=n[6]&&+n[6],this.comma=!!n[7],this.precision=n[8]&&+n[8].slice(1),this.trim=!!n[9],this.type=n[10]||""}function Na(t,n){var e=_a(t,n);if(!e)return t+"";var r=e[0],i=e[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}wa.prototype=Ma.prototype,Ma.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(null==this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(null==this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};var Aa={"%":function(t,n){return(100*t).toFixed(n)},b:function(t){return Math.round(t).toString(2)},c:function(t){return t+""},d:function(t){return Math.round(t).toString(10)},e:function(t,n){return t.toExponential(n)},f:function(t,n){return t.toFixed(n)},g:function(t,n){return t.toPrecision(n)},o:function(t){return Math.round(t).toString(8)},p:function(t,n){return Na(100*t,n)},r:Na,s:function(t,n){var e=_a(t,n);if(!e)return t+"";var r=e[0],i=e[1],o=i-(ma=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,a=r.length;return o===a?r:o>a?r+new Array(o-a+1).join("0"):o>0?r.slice(0,o)+"."+r.slice(o):"0."+new Array(1-o).join("0")+_a(t,Math.max(0,n+o-1))[0]},X:function(t){return Math.round(t).toString(16).toUpperCase()},x:function(t){return Math.round(t).toString(16)}};function Ta(t){return t}var Sa,ka=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Ea(t){var n,e,r=t.grouping&&t.thousands?(n=t.grouping,e=t.thousands,function(t,r){for(var i=t.length,o=[],a=0,u=n[0],c=0;i>0&&u>0&&(c+u+1>r&&(u=Math.max(1,r-c)),o.push(t.substring(i-=u,i+u)),!((c+=u+1)>r));)u=n[a=(a+1)%n.length];return o.reverse().join(e)}):Ta,i=t.currency,o=t.decimal,a=t.numerals?function(t){return function(n){return n.replace(/[0-9]/g,function(n){return t[+n]})}}(t.numerals):Ta,u=t.percent||"%";function c(t){var n=(t=wa(t)).fill,e=t.align,c=t.sign,f=t.symbol,s=t.zero,l=t.width,h=t.comma,d=t.precision,p=t.trim,v=t.type;"n"===v?(h=!0,v="g"):Aa[v]||(null==d&&(d=12),p=!0,v="g"),(s||"0"===n&&"="===e)&&(s=!0,n="0",e="=");var g="$"===f?i[0]:"#"===f&&/[boxX]/.test(v)?"0"+v.toLowerCase():"",y="$"===f?i[1]:/[%p]/.test(v)?u:"",_=Aa[v],b=/[defgprs%]/.test(v);function m(t){var i,u,f,m=g,x=y;if("c"===v)x=_(t)+x,t="";else{var w=(t=+t)<0;if(t=_(Math.abs(t),d),p&&(t=function(t){t:for(var n,e=t.length,r=1,i=-1;r0){if(!+t[r])break t;i=0}}return i>0?t.slice(0,i)+t.slice(n+1):t}(t)),w&&0==+t&&(w=!1),m=(w?"("===c?c:"-":"-"===c||"("===c?"":c)+m,x=("s"===v?ka[8+ma/3]:"")+x+(w&&"("===c?")":""),b)for(i=-1,u=t.length;++i(f=t.charCodeAt(i))||f>57){x=(46===f?o+t.slice(i+1):t.slice(i))+x,t=t.slice(0,i);break}}h&&!s&&(t=r(t,1/0));var M=m.length+t.length+x.length,N=M>1)+m+t+x+N.slice(M);break;default:t=N+m+t+x}return a(t)}return d=null==d?6:/[gprs]/.test(v)?Math.max(1,Math.min(21,d)):Math.max(0,Math.min(20,d)),m.toString=function(){return t+""},m}return{format:c,formatPrefix:function(t,n){var e=c(((t=wa(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor(ba(n)/3))),i=Math.pow(10,-r),o=ka[8+r/3];return function(t){return e(i*t)+o}}}}function Ca(n){return Sa=Ea(n),t.format=Sa.format,t.formatPrefix=Sa.formatPrefix,Sa}function Pa(t){return Math.max(0,-ba(Math.abs(t)))}function za(t,n){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor(ba(n)/3)))-ba(Math.abs(t)))}function Ra(t,n){return t=Math.abs(t),n=Math.abs(n)-t,Math.max(0,ba(n)-ba(t))+1}function Da(){return new qa}function qa(){this.reset()}Ca({decimal:".",thousands:",",grouping:[3],currency:["$",""]}),qa.prototype={constructor:qa,reset:function(){this.s=this.t=0},add:function(t){Ua(La,t,this.t),Ua(this,La.s,this.s),this.s?this.t+=La.t:this.s=La.t},valueOf:function(){return this.s}};var La=new qa;function Ua(t,n,e){var r=t.s=n+e,i=r-n,o=r-i;t.t=n-o+(e-i)}var Oa=1e-6,Ba=1e-12,Ya=Math.PI,Fa=Ya/2,Ia=Ya/4,ja=2*Ya,Ha=180/Ya,Xa=Ya/180,Ga=Math.abs,Va=Math.atan,$a=Math.atan2,Wa=Math.cos,Za=Math.ceil,Qa=Math.exp,Ja=Math.log,Ka=Math.pow,tu=Math.sin,nu=Math.sign||function(t){return t>0?1:t<0?-1:0},eu=Math.sqrt,ru=Math.tan;function iu(t){return t>1?0:t<-1?Ya:Math.acos(t)}function ou(t){return t>1?Fa:t<-1?-Fa:Math.asin(t)}function au(t){return(t=tu(t/2))*t}function uu(){}function cu(t,n){t&&su.hasOwnProperty(t.type)&&su[t.type](t,n)}var fu={Feature:function(t,n){cu(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r=0?1:-1,i=r*e,o=Wa(n=(n*=Xa)/2+Ia),a=tu(n),u=_u*a,c=yu*o+u*Wa(i),f=u*r*tu(i);bu.add($a(f,c)),gu=t,yu=o,_u=a}function Tu(t){return[$a(t[1],t[0]),ou(t[2])]}function Su(t){var n=t[0],e=t[1],r=Wa(e);return[r*Wa(n),r*tu(n),tu(e)]}function ku(t,n){return t[0]*n[0]+t[1]*n[1]+t[2]*n[2]}function Eu(t,n){return[t[1]*n[2]-t[2]*n[1],t[2]*n[0]-t[0]*n[2],t[0]*n[1]-t[1]*n[0]]}function Cu(t,n){t[0]+=n[0],t[1]+=n[1],t[2]+=n[2]}function Pu(t,n){return[t[0]*n,t[1]*n,t[2]*n]}function zu(t){var n=eu(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=n,t[1]/=n,t[2]/=n}var Ru,Du,qu,Lu,Uu,Ou,Bu,Yu,Fu,Iu,ju,Hu,Xu,Gu,Vu,$u,Wu,Zu,Qu,Ju,Ku,tc,nc,ec,rc,ic,oc=Da(),ac={point:uc,lineStart:fc,lineEnd:sc,polygonStart:function(){ac.point=lc,ac.lineStart=hc,ac.lineEnd=dc,oc.reset(),xu.polygonStart()},polygonEnd:function(){xu.polygonEnd(),ac.point=uc,ac.lineStart=fc,ac.lineEnd=sc,bu<0?(Ru=-(qu=180),Du=-(Lu=90)):oc>Oa?Lu=90:oc<-Oa&&(Du=-90),Iu[0]=Ru,Iu[1]=qu}};function uc(t,n){Fu.push(Iu=[Ru=t,qu=t]),nLu&&(Lu=n)}function cc(t,n){var e=Su([t*Xa,n*Xa]);if(Yu){var r=Eu(Yu,e),i=Eu([r[1],-r[0],0],r);zu(i),i=Tu(i);var o,a=t-Uu,u=a>0?1:-1,c=i[0]*Ha*u,f=Ga(a)>180;f^(u*UuLu&&(Lu=o):f^(u*Uu<(c=(c+360)%360-180)&&cLu&&(Lu=n)),f?tpc(Ru,qu)&&(qu=t):pc(t,qu)>pc(Ru,qu)&&(Ru=t):qu>=Ru?(tqu&&(qu=t)):t>Uu?pc(Ru,t)>pc(Ru,qu)&&(qu=t):pc(t,qu)>pc(Ru,qu)&&(Ru=t)}else Fu.push(Iu=[Ru=t,qu=t]);nLu&&(Lu=n),Yu=e,Uu=t}function fc(){ac.point=cc}function sc(){Iu[0]=Ru,Iu[1]=qu,ac.point=uc,Yu=null}function lc(t,n){if(Yu){var e=t-Uu;oc.add(Ga(e)>180?e+(e>0?360:-360):e)}else Ou=t,Bu=n;xu.point(t,n),cc(t,n)}function hc(){xu.lineStart()}function dc(){lc(Ou,Bu),xu.lineEnd(),Ga(oc)>Oa&&(Ru=-(qu=180)),Iu[0]=Ru,Iu[1]=qu,Yu=null}function pc(t,n){return(n-=t)<0?n+360:n}function vc(t,n){return t[0]-n[0]}function gc(t,n){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:nYa?t+Math.round(-t/ja)*ja:t,n]}function Pc(t,n,e){return(t%=ja)?n||e?Ec(Rc(t),Dc(n,e)):Rc(t):n||e?Dc(n,e):Cc}function zc(t){return function(n,e){return[(n+=t)>Ya?n-ja:n<-Ya?n+ja:n,e]}}function Rc(t){var n=zc(t);return n.invert=zc(-t),n}function Dc(t,n){var e=Wa(t),r=tu(t),i=Wa(n),o=tu(n);function a(t,n){var a=Wa(n),u=Wa(t)*a,c=tu(t)*a,f=tu(n),s=f*e+u*r;return[$a(c*i-s*o,u*e-f*r),ou(s*i+c*o)]}return a.invert=function(t,n){var a=Wa(n),u=Wa(t)*a,c=tu(t)*a,f=tu(n),s=f*i-c*o;return[$a(c*i+f*o,u*e+s*r),ou(s*e-u*r)]},a}function qc(t){function n(n){return(n=t(n[0]*Xa,n[1]*Xa))[0]*=Ha,n[1]*=Ha,n}return t=Pc(t[0]*Xa,t[1]*Xa,t.length>2?t[2]*Xa:0),n.invert=function(n){return(n=t.invert(n[0]*Xa,n[1]*Xa))[0]*=Ha,n[1]*=Ha,n},n}function Lc(t,n,e,r,i,o){if(e){var a=Wa(n),u=tu(n),c=r*e;null==i?(i=n+r*ja,o=n-c/2):(i=Uc(a,i),o=Uc(a,o),(r>0?io)&&(i+=r*ja));for(var f,s=i;r>0?s>o:s1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function Bc(t,n){return Ga(t[0]-n[0])=0;--o)i.point((s=f[o])[0],s[1]);else r(h.x,h.p.x,-1,i);h=h.p}f=(h=h.o).z,d=!d}while(!h.v);i.lineEnd()}}}function Ic(t){if(n=t.length){for(var n,e,r=0,i=t[0];++r=0?1:-1,A=N*M,T=A>Ya,S=v*x;if(jc.add($a(S*N*tu(A),g*w+S*Wa(A))),a+=T?M+N*ja:M,T^d>=e^b>=e){var k=Eu(Su(h),Su(_));zu(k);var E=Eu(o,k);zu(E);var C=(T^M>=0?-1:1)*ou(E[2]);(r>C||r===C&&(k[0]||k[1]))&&(u+=T^M>=0?1:-1)}}return(a<-Oa||a0){for(l||(i.polygonStart(),l=!0),i.lineStart(),t=0;t1&&2&c&&h.push(h.pop().concat(h.shift())),a.push(h.filter(Gc))}return h}}function Gc(t){return t.length>1}function Vc(t,n){return((t=t.x)[0]<0?t[1]-Fa-Oa:Fa-t[1])-((n=n.x)[0]<0?n[1]-Fa-Oa:Fa-n[1])}var $c=Xc(function(){return!0},function(t){var n,e=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),n=1},point:function(o,a){var u=o>0?Ya:-Ya,c=Ga(o-e);Ga(c-Ya)0?Fa:-Fa),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),t.point(o,r),n=0):i!==u&&c>=Ya&&(Ga(e-i)Oa?Va((tu(n)*(o=Wa(r))*tu(e)-tu(r)*(i=Wa(n))*tu(t))/(i*o*a)):(n+r)/2}(e,r,o,a),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),n=0),t.point(e=o,r=a),i=u},lineEnd:function(){t.lineEnd(),e=r=NaN},clean:function(){return 2-n}}},function(t,n,e,r){var i;if(null==t)i=e*Fa,r.point(-Ya,i),r.point(0,i),r.point(Ya,i),r.point(Ya,0),r.point(Ya,-i),r.point(0,-i),r.point(-Ya,-i),r.point(-Ya,0),r.point(-Ya,i);else if(Ga(t[0]-n[0])>Oa){var o=t[0]0,i=Ga(n)>Oa;function o(t,e){return Wa(t)*Wa(e)>n}function a(t,e,r){var i=[1,0,0],o=Eu(Su(t),Su(e)),a=ku(o,o),u=o[0],c=a-u*u;if(!c)return!r&&t;var f=n*a/c,s=-n*u/c,l=Eu(i,o),h=Pu(i,f);Cu(h,Pu(o,s));var d=l,p=ku(h,d),v=ku(d,d),g=p*p-v*(ku(h,h)-1);if(!(g<0)){var y=eu(g),_=Pu(d,(-p-y)/v);if(Cu(_,h),_=Tu(_),!r)return _;var b,m=t[0],x=e[0],w=t[1],M=e[1];x0^_[1]<(Ga(_[0]-m)Ya^(m<=_[0]&&_[0]<=x)){var T=Pu(d,(-p+y)/v);return Cu(T,h),[_,Tu(T)]}}}function u(n,e){var i=r?t:Ya-t,o=0;return n<-i?o|=1:n>i&&(o|=2),e<-i?o|=4:e>i&&(o|=8),o}return Xc(o,function(t){var n,e,c,f,s;return{lineStart:function(){f=c=!1,s=1},point:function(l,h){var d,p=[l,h],v=o(l,h),g=r?v?0:u(l,h):v?u(l+(l<0?Ya:-Ya),h):0;if(!n&&(f=c=v)&&t.lineStart(),v!==c&&(!(d=a(n,p))||Bc(n,d)||Bc(p,d))&&(p[0]+=Oa,p[1]+=Oa,v=o(p[0],p[1])),v!==c)s=0,v?(t.lineStart(),d=a(p,n),t.point(d[0],d[1])):(d=a(n,p),t.point(d[0],d[1]),t.lineEnd()),n=d;else if(i&&n&&r^v){var y;g&e||!(y=a(p,n,!0))||(s=0,r?(t.lineStart(),t.point(y[0][0],y[0][1]),t.point(y[1][0],y[1][1]),t.lineEnd()):(t.point(y[1][0],y[1][1]),t.lineEnd(),t.lineStart(),t.point(y[0][0],y[0][1])))}!v||n&&Bc(n,p)||t.point(p[0],p[1]),n=p,c=v,e=g},lineEnd:function(){c&&t.lineEnd(),n=null},clean:function(){return s|(f&&c)<<1}}},function(n,r,i,o){Lc(o,t,e,i,n,r)},r?[0,-t]:[-Ya,t-Ya])}var Zc=1e9,Qc=-Zc;function Jc(t,n,e,r){function i(i,o){return t<=i&&i<=e&&n<=o&&o<=r}function o(i,o,u,f){var s=0,l=0;if(null==i||(s=a(i,u))!==(l=a(o,u))||c(i,o)<0^u>0)do{f.point(0===s||3===s?t:e,s>1?r:n)}while((s=(s+u+4)%4)!==l);else f.point(o[0],o[1])}function a(r,i){return Ga(r[0]-t)0?0:3:Ga(r[0]-e)0?2:1:Ga(r[1]-n)0?1:0:i>0?3:2}function u(t,n){return c(t.x,n.x)}function c(t,n){var e=a(t,1),r=a(n,1);return e!==r?e-r:0===e?n[1]-t[1]:1===e?t[0]-n[0]:2===e?t[1]-n[1]:n[0]-t[0]}return function(a){var c,f,s,l,h,d,p,v,g,y,_,b=a,m=Oc(),x={point:w,lineStart:function(){x.point=M,f&&f.push(s=[]);y=!0,g=!1,p=v=NaN},lineEnd:function(){c&&(M(l,h),d&&g&&m.rejoin(),c.push(m.result()));x.point=w,g&&b.lineEnd()},polygonStart:function(){b=m,c=[],f=[],_=!0},polygonEnd:function(){var n=function(){for(var n=0,e=0,i=f.length;er&&(h-o)*(r-a)>(d-a)*(t-o)&&++n:d<=r&&(h-o)*(r-a)<(d-a)*(t-o)&&--n;return n}(),e=_&&n,i=(c=T(c)).length;(e||i)&&(a.polygonStart(),e&&(a.lineStart(),o(null,null,1,a),a.lineEnd()),i&&Fc(c,u,n,o,a),a.polygonEnd());b=a,c=f=s=null}};function w(t,n){i(t,n)&&b.point(t,n)}function M(o,a){var u=i(o,a);if(f&&s.push([o,a]),y)l=o,h=a,d=u,y=!1,u&&(b.lineStart(),b.point(o,a));else if(u&&g)b.point(o,a);else{var c=[p=Math.max(Qc,Math.min(Zc,p)),v=Math.max(Qc,Math.min(Zc,v))],m=[o=Math.max(Qc,Math.min(Zc,o)),a=Math.max(Qc,Math.min(Zc,a))];!function(t,n,e,r,i,o){var a,u=t[0],c=t[1],f=0,s=1,l=n[0]-u,h=n[1]-c;if(a=e-u,l||!(a>0)){if(a/=l,l<0){if(a0){if(a>s)return;a>f&&(f=a)}if(a=i-u,l||!(a<0)){if(a/=l,l<0){if(a>s)return;a>f&&(f=a)}else if(l>0){if(a0)){if(a/=h,h<0){if(a0){if(a>s)return;a>f&&(f=a)}if(a=o-c,h||!(a<0)){if(a/=h,h<0){if(a>s)return;a>f&&(f=a)}else if(h>0){if(a0&&(t[0]=u+f*l,t[1]=c+f*h),s<1&&(n[0]=u+s*l,n[1]=c+s*h),!0}}}}}(c,m,t,n,e,r)?u&&(b.lineStart(),b.point(o,a),_=!1):(g||(b.lineStart(),b.point(c[0],c[1])),b.point(m[0],m[1]),u||b.lineEnd(),_=!1)}p=o,v=a,g=u}return x}}var Kc,tf,nf,ef=Da(),rf={sphere:uu,point:uu,lineStart:function(){rf.point=af,rf.lineEnd=of},lineEnd:uu,polygonStart:uu,polygonEnd:uu};function of(){rf.point=rf.lineEnd=uu}function af(t,n){Kc=t*=Xa,tf=tu(n*=Xa),nf=Wa(n),rf.point=uf}function uf(t,n){t*=Xa;var e=tu(n*=Xa),r=Wa(n),i=Ga(t-Kc),o=Wa(i),a=r*tu(i),u=nf*e-tf*r*o,c=tf*e+nf*r*o;ef.add($a(eu(a*a+u*u),c)),Kc=t,tf=e,nf=r}function cf(t){return ef.reset(),du(t,rf),+ef}var ff=[null,null],sf={type:"LineString",coordinates:ff};function lf(t,n){return ff[0]=t,ff[1]=n,cf(sf)}var hf={Feature:function(t,n){return pf(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++rOa}).map(c)).concat(g(Za(o/d)*d,i,d).filter(function(t){return Ga(t%v)>Oa}).map(f))}return _.lines=function(){return b().map(function(t){return{type:"LineString",coordinates:t}})},_.outline=function(){return{type:"Polygon",coordinates:[s(r).concat(l(a).slice(1),s(e).reverse().slice(1),l(u).reverse().slice(1))]}},_.extent=function(t){return arguments.length?_.extentMajor(t).extentMinor(t):_.extentMinor()},_.extentMajor=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],u=+t[0][1],a=+t[1][1],r>e&&(t=r,r=e,e=t),u>a&&(t=u,u=a,a=t),_.precision(y)):[[r,u],[e,a]]},_.extentMinor=function(e){return arguments.length?(n=+e[0][0],t=+e[1][0],o=+e[0][1],i=+e[1][1],n>t&&(e=n,n=t,t=e),o>i&&(e=o,o=i,i=e),_.precision(y)):[[n,o],[t,i]]},_.step=function(t){return arguments.length?_.stepMajor(t).stepMinor(t):_.stepMinor()},_.stepMajor=function(t){return arguments.length?(p=+t[0],v=+t[1],_):[p,v]},_.stepMinor=function(t){return arguments.length?(h=+t[0],d=+t[1],_):[h,d]},_.precision=function(h){return arguments.length?(y=+h,c=mf(o,i,90),f=xf(n,t,y),s=mf(u,a,90),l=xf(r,e,y),_):y},_.extentMajor([[-180,-90+Oa],[180,90-Oa]]).extentMinor([[-180,-80-Oa],[180,80+Oa]])}function Mf(t){return t}var Nf,Af,Tf,Sf,kf=Da(),Ef=Da(),Cf={point:uu,lineStart:uu,lineEnd:uu,polygonStart:function(){Cf.lineStart=Pf,Cf.lineEnd=Df},polygonEnd:function(){Cf.lineStart=Cf.lineEnd=Cf.point=uu,kf.add(Ga(Ef)),Ef.reset()},result:function(){var t=kf/2;return kf.reset(),t}};function Pf(){Cf.point=zf}function zf(t,n){Cf.point=Rf,Nf=Tf=t,Af=Sf=n}function Rf(t,n){Ef.add(Sf*t-Tf*n),Tf=t,Sf=n}function Df(){Rf(Nf,Af)}var qf=1/0,Lf=qf,Uf=-qf,Of=Uf,Bf={point:function(t,n){tUf&&(Uf=t);nOf&&(Of=n)},lineStart:uu,lineEnd:uu,polygonStart:uu,polygonEnd:uu,result:function(){var t=[[qf,Lf],[Uf,Of]];return Uf=Of=-(Lf=qf=1/0),t}};var Yf,Ff,If,jf,Hf=0,Xf=0,Gf=0,Vf=0,$f=0,Wf=0,Zf=0,Qf=0,Jf=0,Kf={point:ts,lineStart:ns,lineEnd:is,polygonStart:function(){Kf.lineStart=os,Kf.lineEnd=as},polygonEnd:function(){Kf.point=ts,Kf.lineStart=ns,Kf.lineEnd=is},result:function(){var t=Jf?[Zf/Jf,Qf/Jf]:Wf?[Vf/Wf,$f/Wf]:Gf?[Hf/Gf,Xf/Gf]:[NaN,NaN];return Hf=Xf=Gf=Vf=$f=Wf=Zf=Qf=Jf=0,t}};function ts(t,n){Hf+=t,Xf+=n,++Gf}function ns(){Kf.point=es}function es(t,n){Kf.point=rs,ts(If=t,jf=n)}function rs(t,n){var e=t-If,r=n-jf,i=eu(e*e+r*r);Vf+=i*(If+t)/2,$f+=i*(jf+n)/2,Wf+=i,ts(If=t,jf=n)}function is(){Kf.point=ts}function os(){Kf.point=us}function as(){cs(Yf,Ff)}function us(t,n){Kf.point=cs,ts(Yf=If=t,Ff=jf=n)}function cs(t,n){var e=t-If,r=n-jf,i=eu(e*e+r*r);Vf+=i*(If+t)/2,$f+=i*(jf+n)/2,Wf+=i,Zf+=(i=jf*t-If*n)*(If+t),Qf+=i*(jf+n),Jf+=3*i,ts(If=t,jf=n)}function fs(t){this._context=t}fs.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._context.moveTo(t,n),this._point=1;break;case 1:this._context.lineTo(t,n);break;default:this._context.moveTo(t+this._radius,n),this._context.arc(t,n,this._radius,0,ja)}},result:uu};var ss,ls,hs,ds,ps,vs=Da(),gs={point:uu,lineStart:function(){gs.point=ys},lineEnd:function(){ss&&_s(ls,hs),gs.point=uu},polygonStart:function(){ss=!0},polygonEnd:function(){ss=null},result:function(){var t=+vs;return vs.reset(),t}};function ys(t,n){gs.point=_s,ls=ds=t,hs=ps=n}function _s(t,n){ds-=t,ps-=n,vs.add(eu(ds*ds+ps*ps)),ds=t,ps=n}function bs(){this._string=[]}function ms(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function xs(t){return function(n){var e=new ws;for(var r in t)e[r]=t[r];return e.stream=n,e}}function ws(){}function Ms(t,n,e){var r=t.clipExtent&&t.clipExtent();return t.scale(150).translate([0,0]),null!=r&&t.clipExtent(null),du(e,t.stream(Bf)),n(Bf.result()),null!=r&&t.clipExtent(r),t}function Ns(t,n,e){return Ms(t,function(e){var r=n[1][0]-n[0][0],i=n[1][1]-n[0][1],o=Math.min(r/(e[1][0]-e[0][0]),i/(e[1][1]-e[0][1])),a=+n[0][0]+(r-o*(e[1][0]+e[0][0]))/2,u=+n[0][1]+(i-o*(e[1][1]+e[0][1]))/2;t.scale(150*o).translate([a,u])},e)}function As(t,n,e){return Ns(t,[[0,0],n],e)}function Ts(t,n,e){return Ms(t,function(e){var r=+n,i=r/(e[1][0]-e[0][0]),o=(r-i*(e[1][0]+e[0][0]))/2,a=-i*e[0][1];t.scale(150*i).translate([o,a])},e)}function Ss(t,n,e){return Ms(t,function(e){var r=+n,i=r/(e[1][1]-e[0][1]),o=-i*e[0][0],a=(r-i*(e[1][1]+e[0][1]))/2;t.scale(150*i).translate([o,a])},e)}bs.prototype={_radius:4.5,_circle:ms(4.5),pointRadius:function(t){return(t=+t)!==this._radius&&(this._radius=t,this._circle=null),this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._string.push("Z"),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._string.push("M",t,",",n),this._point=1;break;case 1:this._string.push("L",t,",",n);break;default:null==this._circle&&(this._circle=ms(this._radius)),this._string.push("M",t,",",n,this._circle)}},result:function(){if(this._string.length){var t=this._string.join("");return this._string=[],t}return null}},ws.prototype={constructor:ws,point:function(t,n){this.stream.point(t,n)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};var ks=16,Es=Wa(30*Xa);function Cs(t,n){return+n?function(t,n){function e(r,i,o,a,u,c,f,s,l,h,d,p,v,g){var y=f-r,_=s-i,b=y*y+_*_;if(b>4*n&&v--){var m=a+h,x=u+d,w=c+p,M=eu(m*m+x*x+w*w),N=ou(w/=M),A=Ga(Ga(w)-1)n||Ga((y*E+_*C)/b-.5)>.3||a*h+u*d+c*p2?t[2]%360*Xa:0,S()):[g*Ha,y*Ha,_*Ha]},A.angle=function(t){return arguments.length?(b=t%360*Xa,S()):b*Ha},A.precision=function(t){return arguments.length?(a=Cs(u,N=t*t),k()):eu(N)},A.fitExtent=function(t,n){return Ns(A,t,n)},A.fitSize=function(t,n){return As(A,t,n)},A.fitWidth=function(t,n){return Ts(A,t,n)},A.fitHeight=function(t,n){return Ss(A,t,n)},function(){return n=t.apply(this,arguments),A.invert=n.invert&&T,S()}}function qs(t){var n=0,e=Ya/3,r=Ds(t),i=r(n,e);return i.parallels=function(t){return arguments.length?r(n=t[0]*Xa,e=t[1]*Xa):[n*Ha,e*Ha]},i}function Ls(t,n){var e=tu(t),r=(e+tu(n))/2;if(Ga(r)0?n<-Fa+Oa&&(n=-Fa+Oa):n>Fa-Oa&&(n=Fa-Oa);var e=i/Ka(Xs(n),r);return[e*tu(r*t),i-e*Wa(r*t)]}return o.invert=function(t,n){var e=i-n,o=nu(r)*eu(t*t+e*e);return[$a(t,Ga(e))/r*nu(e),2*Va(Ka(i/o,1/r))-Fa]},o}function Vs(t,n){return[t,n]}function $s(t,n){var e=Wa(t),r=t===n?tu(t):(e-Wa(n))/(n-t),i=e/r+t;if(Ga(r)=0;)n+=e[r].value;else n=1;t.value=n}function ll(t,n){var e,r,i,o,a,u=new vl(t),c=+t.value&&(u.value=t.value),f=[u];for(null==n&&(n=hl);e=f.pop();)if(c&&(e.value=+e.data.value),(i=n(e.data))&&(a=i.length))for(e.children=new Array(a),o=a-1;o>=0;--o)f.push(r=e.children[o]=new vl(i[o])),r.parent=e,r.depth=e.depth+1;return u.eachBefore(pl)}function hl(t){return t.children}function dl(t){t.data=t.data.data}function pl(t){var n=0;do{t.height=n}while((t=t.parent)&&t.height<++n)}function vl(t){this.data=t,this.depth=this.height=0,this.parent=null}tl.invert=function(t,n){for(var e,r=n,i=r*r,o=i*i*i,a=0;a<12&&(o=(i=(r-=e=(r*(Ws+Zs*i+o*(Qs+Js*i))-n)/(Ws+3*Zs*i+o*(7*Qs+9*Js*i)))*r)*i*i,!(Ga(e)Oa&&--i>0);return[t/(.8707+(o=r*r)*(o*(o*o*o*(.003971-.001529*o)-.013791)-.131979)),r]},il.invert=Ys(ou),ol.invert=Ys(function(t){return 2*Va(t)}),al.invert=function(t,n){return[-n,2*Va(Qa(t))-Fa]},vl.prototype=ll.prototype={constructor:vl,count:function(){return this.eachAfter(sl)},each:function(t){var n,e,r,i,o=this,a=[o];do{for(n=a.reverse(),a=[];o=n.pop();)if(t(o),e=o.children)for(r=0,i=e.length;r=0;--e)i.push(n[e]);return this},sum:function(t){return this.eachAfter(function(n){for(var e=+t(n.data)||0,r=n.children,i=r&&r.length;--i>=0;)e+=r[i].value;n.value=e})},sort:function(t){return this.eachBefore(function(n){n.children&&n.children.sort(t)})},path:function(t){for(var n=this,e=function(t,n){if(t===n)return t;var e=t.ancestors(),r=n.ancestors(),i=null;for(t=e.pop(),n=r.pop();t===n;)i=t,t=e.pop(),n=r.pop();return i}(n,t),r=[n];n!==e;)n=n.parent,r.push(n);for(var i=r.length;t!==e;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,n=[t];t=t.parent;)n.push(t);return n},descendants:function(){var t=[];return this.each(function(n){t.push(n)}),t},leaves:function(){var t=[];return this.eachBefore(function(n){n.children||t.push(n)}),t},links:function(){var t=this,n=[];return t.each(function(e){e!==t&&n.push({source:e.parent,target:e})}),n},copy:function(){return ll(this).eachBefore(dl)}};var gl=Array.prototype.slice;function yl(t){for(var n,e,r=0,i=(t=function(t){for(var n,e,r=t.length;r;)e=Math.random()*r--|0,n=t[r],t[r]=t[e],t[e]=n;return t}(gl.call(t))).length,o=[];r0&&e*e>r*r+i*i}function xl(t,n){for(var e=0;e(a*=a)?(r=(f+a-i)/(2*f),o=Math.sqrt(Math.max(0,a/f-r*r)),e.x=t.x-r*u-o*c,e.y=t.y-r*c+o*u):(r=(f+i-a)/(2*f),o=Math.sqrt(Math.max(0,i/f-r*r)),e.x=n.x+r*u-o*c,e.y=n.y+r*c+o*u)):(e.x=n.x+e.r,e.y=n.y)}function Tl(t,n){var e=t.r+n.r-1e-6,r=n.x-t.x,i=n.y-t.y;return e>0&&e*e>r*r+i*i}function Sl(t){var n=t._,e=t.next._,r=n.r+e.r,i=(n.x*e.r+e.x*n.r)/r,o=(n.y*e.r+e.y*n.r)/r;return i*i+o*o}function kl(t){this._=t,this.next=null,this.previous=null}function El(t){if(!(i=t.length))return 0;var n,e,r,i,o,a,u,c,f,s,l;if((n=t[0]).x=0,n.y=0,!(i>1))return n.r;if(e=t[1],n.x=-e.r,e.x=n.r,e.y=0,!(i>2))return n.r+e.r;Al(e,n,r=t[2]),n=new kl(n),e=new kl(e),r=new kl(r),n.next=r.previous=e,e.next=n.previous=r,r.next=e.previous=n;t:for(u=3;uh&&(h=u),g=s*s*v,(d=Math.max(h/g,g/l))>p){s-=u;break}p=d}y.push(a={value:s,dice:c1?n:1)},e}(Ql);var th=function t(n){function e(t,e,r,i,o){if((a=t._squarify)&&a.ratio===n)for(var a,u,c,f,s,l=-1,h=a.length,d=t.value;++l1?n:1)},e}(Ql);function nh(t,n){return t[0]-n[0]||t[1]-n[1]}function eh(t){for(var n,e,r,i=t.length,o=[0,1],a=2,u=2;u1&&(n=t[o[a-2]],e=t[o[a-1]],r=t[u],(e[0]-n[0])*(r[1]-n[1])-(e[1]-n[1])*(r[0]-n[0])<=0);)--a;o[a++]=u}return o.slice(0,a)}function rh(){return Math.random()}var ih=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,1===arguments.length?(e=t,t=0):e-=t,function(){return n()*e+t}}return e.source=t,e}(rh),oh=function t(n){function e(t,e){var r,i;return t=null==t?0:+t,e=null==e?1:+e,function(){var o;if(null!=r)o=r,r=null;else do{r=2*n()-1,o=2*n()-1,i=r*r+o*o}while(!i||i>1);return t+e*o*Math.sqrt(-2*Math.log(i)/i)}}return e.source=t,e}(rh),ah=function t(n){function e(){var t=oh.source(n).apply(this,arguments);return function(){return Math.exp(t())}}return e.source=t,e}(rh),uh=function t(n){function e(t){return function(){for(var e=0,r=0;rr&&(n=e,e=r,r=n),function(t){return Math.max(e,Math.min(r,t))}}function Mh(t,n,e){var r=t[0],i=t[1],o=n[0],a=n[1];return i2?Nh:Mh,i=o=null,l}function l(n){return isNaN(n=+n)?e:(i||(i=r(a.map(t),u,c)))(t(f(n)))}return l.invert=function(e){return f(n((o||(o=r(u,a.map(t),he)))(e)))},l.domain=function(t){return arguments.length?(a=dh.call(t,_h),f===mh||(f=wh(a)),s()):a.slice()},l.range=function(t){return arguments.length?(u=ph.call(t),s()):u.slice()},l.rangeRound=function(t){return u=ph.call(t),c=_e,s()},l.clamp=function(t){return arguments.length?(f=t?wh(a):mh,l):f!==mh},l.interpolate=function(t){return arguments.length?(c=t,s()):c},l.unknown=function(t){return arguments.length?(e=t,l):e},function(e,r){return t=e,n=r,s()}}function Sh(t,n){return Th()(t,n)}function kh(n,e,r,i){var o,a=w(n,e,r);switch((i=wa(null==i?",f":i)).type){case"s":var u=Math.max(Math.abs(n),Math.abs(e));return null!=i.precision||isNaN(o=za(a,u))||(i.precision=o),t.formatPrefix(i,u);case"":case"e":case"g":case"p":case"r":null!=i.precision||isNaN(o=Ra(a,Math.max(Math.abs(n),Math.abs(e))))||(i.precision=o-("e"===i.type));break;case"f":case"%":null!=i.precision||isNaN(o=Pa(a))||(i.precision=o-2*("%"===i.type))}return t.format(i)}function Eh(t){var n=t.domain;return t.ticks=function(t){var e=n();return m(e[0],e[e.length-1],null==t?10:t)},t.tickFormat=function(t,e){var r=n();return kh(r[0],r[r.length-1],null==t?10:t,e)},t.nice=function(e){null==e&&(e=10);var r,i=n(),o=0,a=i.length-1,u=i[o],c=i[a];return c0?r=x(u=Math.floor(u/r)*r,c=Math.ceil(c/r)*r,e):r<0&&(r=x(u=Math.ceil(u*r)/r,c=Math.floor(c*r)/r,e)),r>0?(i[o]=Math.floor(u/r)*r,i[a]=Math.ceil(c/r)*r,n(i)):r<0&&(i[o]=Math.ceil(u*r)/r,i[a]=Math.floor(c*r)/r,n(i)),t},t}function Ch(t,n){var e,r=0,i=(t=t.slice()).length-1,o=t[r],a=t[i];return a0){for(;hc)break;v.push(l)}}else for(;h=1;--s)if(!((l=f*s)c)break;v.push(l)}}else v=m(h,d,Math.min(d-h,p)).map(r);return n?v.reverse():v},i.tickFormat=function(n,o){if(null==o&&(o=10===a?".0e":","),"function"!=typeof o&&(o=t.format(o)),n===1/0)return o;null==n&&(n=10);var u=Math.max(1,a*n/i.ticks().length);return function(t){var n=t/r(Math.round(e(t)));return n*a0))return u;do{u.push(a=new Date(+e)),n(e,o),t(e)}while(a=n)for(;t(n),!e(n);)n.setTime(n-1)},function(t,r){if(t>=t)if(r<0)for(;++r<=0;)for(;n(t,-1),!e(t););else for(;--r>=0;)for(;n(t,1),!e(t););})},e&&(i.count=function(n,r){return Gh.setTime(+n),Vh.setTime(+r),t(Gh),t(Vh),Math.floor(e(Gh,Vh))},i.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?i.filter(r?function(n){return r(n)%t==0}:function(n){return i.count(0,n)%t==0}):i:null}),i}var Wh=$h(function(){},function(t,n){t.setTime(+t+n)},function(t,n){return n-t});Wh.every=function(t){return t=Math.floor(t),isFinite(t)&&t>0?t>1?$h(function(n){n.setTime(Math.floor(n/t)*t)},function(n,e){n.setTime(+n+e*t)},function(n,e){return(e-n)/t}):Wh:null};var Zh=Wh.range,Qh=6e4,Jh=6048e5,Kh=$h(function(t){t.setTime(t-t.getMilliseconds())},function(t,n){t.setTime(+t+1e3*n)},function(t,n){return(n-t)/1e3},function(t){return t.getUTCSeconds()}),td=Kh.range,nd=$h(function(t){t.setTime(t-t.getMilliseconds()-1e3*t.getSeconds())},function(t,n){t.setTime(+t+n*Qh)},function(t,n){return(n-t)/Qh},function(t){return t.getMinutes()}),ed=nd.range,rd=$h(function(t){t.setTime(t-t.getMilliseconds()-1e3*t.getSeconds()-t.getMinutes()*Qh)},function(t,n){t.setTime(+t+36e5*n)},function(t,n){return(n-t)/36e5},function(t){return t.getHours()}),id=rd.range,od=$h(function(t){t.setHours(0,0,0,0)},function(t,n){t.setDate(t.getDate()+n)},function(t,n){return(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Qh)/864e5},function(t){return t.getDate()-1}),ad=od.range;function ud(t){return $h(function(n){n.setDate(n.getDate()-(n.getDay()+7-t)%7),n.setHours(0,0,0,0)},function(t,n){t.setDate(t.getDate()+7*n)},function(t,n){return(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Qh)/Jh})}var cd=ud(0),fd=ud(1),sd=ud(2),ld=ud(3),hd=ud(4),dd=ud(5),pd=ud(6),vd=cd.range,gd=fd.range,yd=sd.range,_d=ld.range,bd=hd.range,md=dd.range,xd=pd.range,wd=$h(function(t){t.setDate(1),t.setHours(0,0,0,0)},function(t,n){t.setMonth(t.getMonth()+n)},function(t,n){return n.getMonth()-t.getMonth()+12*(n.getFullYear()-t.getFullYear())},function(t){return t.getMonth()}),Md=wd.range,Nd=$h(function(t){t.setMonth(0,1),t.setHours(0,0,0,0)},function(t,n){t.setFullYear(t.getFullYear()+n)},function(t,n){return n.getFullYear()-t.getFullYear()},function(t){return t.getFullYear()});Nd.every=function(t){return isFinite(t=Math.floor(t))&&t>0?$h(function(n){n.setFullYear(Math.floor(n.getFullYear()/t)*t),n.setMonth(0,1),n.setHours(0,0,0,0)},function(n,e){n.setFullYear(n.getFullYear()+e*t)}):null};var Ad=Nd.range,Td=$h(function(t){t.setUTCSeconds(0,0)},function(t,n){t.setTime(+t+n*Qh)},function(t,n){return(n-t)/Qh},function(t){return t.getUTCMinutes()}),Sd=Td.range,kd=$h(function(t){t.setUTCMinutes(0,0,0)},function(t,n){t.setTime(+t+36e5*n)},function(t,n){return(n-t)/36e5},function(t){return t.getUTCHours()}),Ed=kd.range,Cd=$h(function(t){t.setUTCHours(0,0,0,0)},function(t,n){t.setUTCDate(t.getUTCDate()+n)},function(t,n){return(n-t)/864e5},function(t){return t.getUTCDate()-1}),Pd=Cd.range;function zd(t){return $h(function(n){n.setUTCDate(n.getUTCDate()-(n.getUTCDay()+7-t)%7),n.setUTCHours(0,0,0,0)},function(t,n){t.setUTCDate(t.getUTCDate()+7*n)},function(t,n){return(n-t)/Jh})}var Rd=zd(0),Dd=zd(1),qd=zd(2),Ld=zd(3),Ud=zd(4),Od=zd(5),Bd=zd(6),Yd=Rd.range,Fd=Dd.range,Id=qd.range,jd=Ld.range,Hd=Ud.range,Xd=Od.range,Gd=Bd.range,Vd=$h(function(t){t.setUTCDate(1),t.setUTCHours(0,0,0,0)},function(t,n){t.setUTCMonth(t.getUTCMonth()+n)},function(t,n){return n.getUTCMonth()-t.getUTCMonth()+12*(n.getUTCFullYear()-t.getUTCFullYear())},function(t){return t.getUTCMonth()}),$d=Vd.range,Wd=$h(function(t){t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},function(t,n){t.setUTCFullYear(t.getUTCFullYear()+n)},function(t,n){return n.getUTCFullYear()-t.getUTCFullYear()},function(t){return t.getUTCFullYear()});Wd.every=function(t){return isFinite(t=Math.floor(t))&&t>0?$h(function(n){n.setUTCFullYear(Math.floor(n.getUTCFullYear()/t)*t),n.setUTCMonth(0,1),n.setUTCHours(0,0,0,0)},function(n,e){n.setUTCFullYear(n.getUTCFullYear()+e*t)}):null};var Zd=Wd.range;function Qd(t){if(0<=t.y&&t.y<100){var n=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return n.setFullYear(t.y),n}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function Jd(t){if(0<=t.y&&t.y<100){var n=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return n.setUTCFullYear(t.y),n}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function Kd(t){return{y:t,m:0,d:1,H:0,M:0,S:0,L:0}}function tp(t){var n=t.dateTime,e=t.date,r=t.time,i=t.periods,o=t.days,a=t.shortDays,u=t.months,c=t.shortMonths,f=cp(i),s=fp(i),l=cp(o),h=fp(o),d=cp(a),p=fp(a),v=cp(u),g=fp(u),y=cp(c),_=fp(c),b={a:function(t){return a[t.getDay()]},A:function(t){return o[t.getDay()]},b:function(t){return c[t.getMonth()]},B:function(t){return u[t.getMonth()]},c:null,d:Ep,e:Ep,f:Dp,H:Cp,I:Pp,j:zp,L:Rp,m:qp,M:Lp,p:function(t){return i[+(t.getHours()>=12)]},Q:sv,s:lv,S:Up,u:Op,U:Bp,V:Yp,w:Fp,W:Ip,x:null,X:null,y:jp,Y:Hp,Z:Xp,"%":fv},m={a:function(t){return a[t.getUTCDay()]},A:function(t){return o[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return u[t.getUTCMonth()]},c:null,d:Gp,e:Gp,f:Qp,H:Vp,I:$p,j:Wp,L:Zp,m:Jp,M:Kp,p:function(t){return i[+(t.getUTCHours()>=12)]},Q:sv,s:lv,S:tv,u:nv,U:ev,V:rv,w:iv,W:ov,x:null,X:null,y:av,Y:uv,Z:cv,"%":fv},x={a:function(t,n,e){var r=d.exec(n.slice(e));return r?(t.w=p[r[0].toLowerCase()],e+r[0].length):-1},A:function(t,n,e){var r=l.exec(n.slice(e));return r?(t.w=h[r[0].toLowerCase()],e+r[0].length):-1},b:function(t,n,e){var r=y.exec(n.slice(e));return r?(t.m=_[r[0].toLowerCase()],e+r[0].length):-1},B:function(t,n,e){var r=v.exec(n.slice(e));return r?(t.m=g[r[0].toLowerCase()],e+r[0].length):-1},c:function(t,e,r){return N(t,n,e,r)},d:bp,e:bp,f:Ap,H:xp,I:xp,j:mp,L:Np,m:_p,M:wp,p:function(t,n,e){var r=f.exec(n.slice(e));return r?(t.p=s[r[0].toLowerCase()],e+r[0].length):-1},Q:Sp,s:kp,S:Mp,u:lp,U:hp,V:dp,w:sp,W:pp,x:function(t,n,r){return N(t,e,n,r)},X:function(t,n,e){return N(t,r,n,e)},y:gp,Y:vp,Z:yp,"%":Tp};function w(t,n){return function(e){var r,i,o,a=[],u=-1,c=0,f=t.length;for(e instanceof Date||(e=new Date(+e));++u53)return null;"w"in o||(o.w=1),"Z"in o?(i=(r=Jd(Kd(o.y))).getUTCDay(),r=i>4||0===i?Dd.ceil(r):Dd(r),r=Cd.offset(r,7*(o.V-1)),o.y=r.getUTCFullYear(),o.m=r.getUTCMonth(),o.d=r.getUTCDate()+(o.w+6)%7):(i=(r=n(Kd(o.y))).getDay(),r=i>4||0===i?fd.ceil(r):fd(r),r=od.offset(r,7*(o.V-1)),o.y=r.getFullYear(),o.m=r.getMonth(),o.d=r.getDate()+(o.w+6)%7)}else("W"in o||"U"in o)&&("w"in o||(o.w="u"in o?o.u%7:"W"in o?1:0),i="Z"in o?Jd(Kd(o.y)).getUTCDay():n(Kd(o.y)).getDay(),o.m=0,o.d="W"in o?(o.w+6)%7+7*o.W-(i+5)%7:o.w+7*o.U-(i+6)%7);return"Z"in o?(o.H+=o.Z/100|0,o.M+=o.Z%100,Jd(o)):n(o)}}function N(t,n,e,r){for(var i,o,a=0,u=n.length,c=e.length;a=c)return-1;if(37===(i=n.charCodeAt(a++))){if(i=n.charAt(a++),!(o=x[i in ep?n.charAt(a++):i])||(r=o(t,e,r))<0)return-1}else if(i!=e.charCodeAt(r++))return-1}return r}return b.x=w(e,b),b.X=w(r,b),b.c=w(n,b),m.x=w(e,m),m.X=w(r,m),m.c=w(n,m),{format:function(t){var n=w(t+="",b);return n.toString=function(){return t},n},parse:function(t){var n=M(t+="",Qd);return n.toString=function(){return t},n},utcFormat:function(t){var n=w(t+="",m);return n.toString=function(){return t},n},utcParse:function(t){var n=M(t,Jd);return n.toString=function(){return t},n}}}var np,ep={"-":"",_:" ",0:"0"},rp=/^\s*\d+/,ip=/^%/,op=/[\\^$*+?|[\]().{}]/g;function ap(t,n,e){var r=t<0?"-":"",i=(r?-t:t)+"",o=i.length;return r+(o68?1900:2e3),e+r[0].length):-1}function yp(t,n,e){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(n.slice(e,e+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),e+r[0].length):-1}function _p(t,n,e){var r=rp.exec(n.slice(e,e+2));return r?(t.m=r[0]-1,e+r[0].length):-1}function bp(t,n,e){var r=rp.exec(n.slice(e,e+2));return r?(t.d=+r[0],e+r[0].length):-1}function mp(t,n,e){var r=rp.exec(n.slice(e,e+3));return r?(t.m=0,t.d=+r[0],e+r[0].length):-1}function xp(t,n,e){var r=rp.exec(n.slice(e,e+2));return r?(t.H=+r[0],e+r[0].length):-1}function wp(t,n,e){var r=rp.exec(n.slice(e,e+2));return r?(t.M=+r[0],e+r[0].length):-1}function Mp(t,n,e){var r=rp.exec(n.slice(e,e+2));return r?(t.S=+r[0],e+r[0].length):-1}function Np(t,n,e){var r=rp.exec(n.slice(e,e+3));return r?(t.L=+r[0],e+r[0].length):-1}function Ap(t,n,e){var r=rp.exec(n.slice(e,e+6));return r?(t.L=Math.floor(r[0]/1e3),e+r[0].length):-1}function Tp(t,n,e){var r=ip.exec(n.slice(e,e+1));return r?e+r[0].length:-1}function Sp(t,n,e){var r=rp.exec(n.slice(e));return r?(t.Q=+r[0],e+r[0].length):-1}function kp(t,n,e){var r=rp.exec(n.slice(e));return r?(t.Q=1e3*+r[0],e+r[0].length):-1}function Ep(t,n){return ap(t.getDate(),n,2)}function Cp(t,n){return ap(t.getHours(),n,2)}function Pp(t,n){return ap(t.getHours()%12||12,n,2)}function zp(t,n){return ap(1+od.count(Nd(t),t),n,3)}function Rp(t,n){return ap(t.getMilliseconds(),n,3)}function Dp(t,n){return Rp(t,n)+"000"}function qp(t,n){return ap(t.getMonth()+1,n,2)}function Lp(t,n){return ap(t.getMinutes(),n,2)}function Up(t,n){return ap(t.getSeconds(),n,2)}function Op(t){var n=t.getDay();return 0===n?7:n}function Bp(t,n){return ap(cd.count(Nd(t),t),n,2)}function Yp(t,n){var e=t.getDay();return t=e>=4||0===e?hd(t):hd.ceil(t),ap(hd.count(Nd(t),t)+(4===Nd(t).getDay()),n,2)}function Fp(t){return t.getDay()}function Ip(t,n){return ap(fd.count(Nd(t),t),n,2)}function jp(t,n){return ap(t.getFullYear()%100,n,2)}function Hp(t,n){return ap(t.getFullYear()%1e4,n,4)}function Xp(t){var n=t.getTimezoneOffset();return(n>0?"-":(n*=-1,"+"))+ap(n/60|0,"0",2)+ap(n%60,"0",2)}function Gp(t,n){return ap(t.getUTCDate(),n,2)}function Vp(t,n){return ap(t.getUTCHours(),n,2)}function $p(t,n){return ap(t.getUTCHours()%12||12,n,2)}function Wp(t,n){return ap(1+Cd.count(Wd(t),t),n,3)}function Zp(t,n){return ap(t.getUTCMilliseconds(),n,3)}function Qp(t,n){return Zp(t,n)+"000"}function Jp(t,n){return ap(t.getUTCMonth()+1,n,2)}function Kp(t,n){return ap(t.getUTCMinutes(),n,2)}function tv(t,n){return ap(t.getUTCSeconds(),n,2)}function nv(t){var n=t.getUTCDay();return 0===n?7:n}function ev(t,n){return ap(Rd.count(Wd(t),t),n,2)}function rv(t,n){var e=t.getUTCDay();return t=e>=4||0===e?Ud(t):Ud.ceil(t),ap(Ud.count(Wd(t),t)+(4===Wd(t).getUTCDay()),n,2)}function iv(t){return t.getUTCDay()}function ov(t,n){return ap(Dd.count(Wd(t),t),n,2)}function av(t,n){return ap(t.getUTCFullYear()%100,n,2)}function uv(t,n){return ap(t.getUTCFullYear()%1e4,n,4)}function cv(){return"+0000"}function fv(){return"%"}function sv(t){return+t}function lv(t){return Math.floor(+t/1e3)}function hv(n){return np=tp(n),t.timeFormat=np.format,t.timeParse=np.parse,t.utcFormat=np.utcFormat,t.utcParse=np.utcParse,np}hv({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});var dv=Date.prototype.toISOString?function(t){return t.toISOString()}:t.utcFormat("%Y-%m-%dT%H:%M:%S.%LZ");var pv=+new Date("2000-01-01T00:00:00.000Z")?function(t){var n=new Date(t);return isNaN(n)?null:n}:t.utcParse("%Y-%m-%dT%H:%M:%S.%LZ"),vv=1e3,gv=60*vv,yv=60*gv,_v=24*yv,bv=7*_v,mv=30*_v,xv=365*_v;function wv(t){return new Date(t)}function Mv(t){return t instanceof Date?+t:+new Date(+t)}function Nv(t,n,r,i,o,a,u,c,f){var s=Sh(mh,mh),l=s.invert,h=s.domain,d=f(".%L"),p=f(":%S"),v=f("%I:%M"),g=f("%I %p"),y=f("%a %d"),_=f("%b %d"),b=f("%B"),m=f("%Y"),x=[[u,1,vv],[u,5,5*vv],[u,15,15*vv],[u,30,30*vv],[a,1,gv],[a,5,5*gv],[a,15,15*gv],[a,30,30*gv],[o,1,yv],[o,3,3*yv],[o,6,6*yv],[o,12,12*yv],[i,1,_v],[i,2,2*_v],[r,1,bv],[n,1,mv],[n,3,3*mv],[t,1,xv]];function M(e){return(u(e)=1?fy:t<=-1?-fy:Math.asin(t)}function hy(t){return t.innerRadius}function dy(t){return t.outerRadius}function py(t){return t.startAngle}function vy(t){return t.endAngle}function gy(t){return t&&t.padAngle}function yy(t,n,e,r,i,o,a){var u=t-e,c=n-r,f=(a?o:-o)/ay(u*u+c*c),s=f*c,l=-f*u,h=t+s,d=n+l,p=e+s,v=r+l,g=(h+p)/2,y=(d+v)/2,_=p-h,b=v-d,m=_*_+b*b,x=i-o,w=h*v-p*d,M=(b<0?-1:1)*ay(ry(0,x*x*m-w*w)),N=(w*b-_*M)/m,A=(-w*_-b*M)/m,T=(w*b+_*M)/m,S=(-w*_+b*M)/m,k=N-g,E=A-y,C=T-g,P=S-y;return k*k+E*E>C*C+P*P&&(N=T,A=S),{cx:N,cy:A,x01:-s,y01:-l,x11:N*(i/x-1),y11:A*(i/x-1)}}function _y(t){this._context=t}function by(t){return new _y(t)}function my(t){return t[0]}function xy(t){return t[1]}function wy(){var t=my,n=xy,e=Kg(!0),r=null,i=by,o=null;function a(a){var u,c,f,s=a.length,l=!1;for(null==r&&(o=i(f=Hi())),u=0;u<=s;++u)!(u=s;--l)u.point(g[l],y[l]);u.lineEnd(),u.areaEnd()}v&&(g[f]=+t(h,f,c),y[f]=+e(h,f,c),u.point(n?+n(h,f,c):g[f],r?+r(h,f,c):y[f]))}if(d)return u=null,d+""||null}function f(){return wy().defined(i).curve(a).context(o)}return c.x=function(e){return arguments.length?(t="function"==typeof e?e:Kg(+e),n=null,c):t},c.x0=function(n){return arguments.length?(t="function"==typeof n?n:Kg(+n),c):t},c.x1=function(t){return arguments.length?(n=null==t?null:"function"==typeof t?t:Kg(+t),c):n},c.y=function(t){return arguments.length?(e="function"==typeof t?t:Kg(+t),r=null,c):e},c.y0=function(t){return arguments.length?(e="function"==typeof t?t:Kg(+t),c):e},c.y1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:Kg(+t),c):r},c.lineX0=c.lineY0=function(){return f().x(t).y(e)},c.lineY1=function(){return f().x(t).y(r)},c.lineX1=function(){return f().x(n).y(e)},c.defined=function(t){return arguments.length?(i="function"==typeof t?t:Kg(!!t),c):i},c.curve=function(t){return arguments.length?(a=t,null!=o&&(u=a(o)),c):a},c.context=function(t){return arguments.length?(null==t?o=u=null:u=a(o=t),c):o},c}function Ny(t,n){return nt?1:n>=t?0:NaN}function Ay(t){return t}_y.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:this._context.lineTo(t,n)}}};var Ty=ky(by);function Sy(t){this._curve=t}function ky(t){function n(n){return new Sy(t(n))}return n._curve=t,n}function Ey(t){var n=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?n(ky(t)):n()._curve},t}function Cy(){return Ey(wy().curve(Ty))}function Py(){var t=My().curve(Ty),n=t.curve,e=t.lineX0,r=t.lineX1,i=t.lineY0,o=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return Ey(e())},delete t.lineX0,t.lineEndAngle=function(){return Ey(r())},delete t.lineX1,t.lineInnerRadius=function(){return Ey(i())},delete t.lineY0,t.lineOuterRadius=function(){return Ey(o())},delete t.lineY1,t.curve=function(t){return arguments.length?n(ky(t)):n()._curve},t}function zy(t,n){return[(n=+n)*Math.cos(t-=Math.PI/2),n*Math.sin(t)]}Sy.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,n){this._curve.point(n*Math.sin(t),n*-Math.cos(t))}};var Ry=Array.prototype.slice;function Dy(t){return t.source}function qy(t){return t.target}function Ly(t){var n=Dy,e=qy,r=my,i=xy,o=null;function a(){var a,u=Ry.call(arguments),c=n.apply(this,u),f=e.apply(this,u);if(o||(o=a=Hi()),t(o,+r.apply(this,(u[0]=c,u)),+i.apply(this,u),+r.apply(this,(u[0]=f,u)),+i.apply(this,u)),a)return o=null,a+""||null}return a.source=function(t){return arguments.length?(n=t,a):n},a.target=function(t){return arguments.length?(e=t,a):e},a.x=function(t){return arguments.length?(r="function"==typeof t?t:Kg(+t),a):r},a.y=function(t){return arguments.length?(i="function"==typeof t?t:Kg(+t),a):i},a.context=function(t){return arguments.length?(o=null==t?null:t,a):o},a}function Uy(t,n,e,r,i){t.moveTo(n,e),t.bezierCurveTo(n=(n+r)/2,e,n,i,r,i)}function Oy(t,n,e,r,i){t.moveTo(n,e),t.bezierCurveTo(n,e=(e+i)/2,r,e,r,i)}function By(t,n,e,r,i){var o=zy(n,e),a=zy(n,e=(e+i)/2),u=zy(r,e),c=zy(r,i);t.moveTo(o[0],o[1]),t.bezierCurveTo(a[0],a[1],u[0],u[1],c[0],c[1])}var Yy={draw:function(t,n){var e=Math.sqrt(n/cy);t.moveTo(e,0),t.arc(0,0,e,0,sy)}},Fy={draw:function(t,n){var e=Math.sqrt(n/5)/2;t.moveTo(-3*e,-e),t.lineTo(-e,-e),t.lineTo(-e,-3*e),t.lineTo(e,-3*e),t.lineTo(e,-e),t.lineTo(3*e,-e),t.lineTo(3*e,e),t.lineTo(e,e),t.lineTo(e,3*e),t.lineTo(-e,3*e),t.lineTo(-e,e),t.lineTo(-3*e,e),t.closePath()}},Iy=Math.sqrt(1/3),jy=2*Iy,Hy={draw:function(t,n){var e=Math.sqrt(n/jy),r=e*Iy;t.moveTo(0,-e),t.lineTo(r,0),t.lineTo(0,e),t.lineTo(-r,0),t.closePath()}},Xy=Math.sin(cy/10)/Math.sin(7*cy/10),Gy=Math.sin(sy/10)*Xy,Vy=-Math.cos(sy/10)*Xy,$y={draw:function(t,n){var e=Math.sqrt(.8908130915292852*n),r=Gy*e,i=Vy*e;t.moveTo(0,-e),t.lineTo(r,i);for(var o=1;o<5;++o){var a=sy*o/5,u=Math.cos(a),c=Math.sin(a);t.lineTo(c*e,-u*e),t.lineTo(u*r-c*i,c*r+u*i)}t.closePath()}},Wy={draw:function(t,n){var e=Math.sqrt(n),r=-e/2;t.rect(r,r,e,e)}},Zy=Math.sqrt(3),Qy={draw:function(t,n){var e=-Math.sqrt(n/(3*Zy));t.moveTo(0,2*e),t.lineTo(-Zy*e,-e),t.lineTo(Zy*e,-e),t.closePath()}},Jy=Math.sqrt(3)/2,Ky=1/Math.sqrt(12),t_=3*(Ky/2+1),n_={draw:function(t,n){var e=Math.sqrt(n/t_),r=e/2,i=e*Ky,o=r,a=e*Ky+e,u=-o,c=a;t.moveTo(r,i),t.lineTo(o,a),t.lineTo(u,c),t.lineTo(-.5*r-Jy*i,Jy*r+-.5*i),t.lineTo(-.5*o-Jy*a,Jy*o+-.5*a),t.lineTo(-.5*u-Jy*c,Jy*u+-.5*c),t.lineTo(-.5*r+Jy*i,-.5*i-Jy*r),t.lineTo(-.5*o+Jy*a,-.5*a-Jy*o),t.lineTo(-.5*u+Jy*c,-.5*c-Jy*u),t.closePath()}},e_=[Yy,Fy,Hy,Wy,$y,Qy,n_];function r_(){}function i_(t,n,e){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+n)/6,(t._y0+4*t._y1+e)/6)}function o_(t){this._context=t}function a_(t){this._context=t}function u_(t){this._context=t}function c_(t,n){this._basis=new o_(t),this._beta=n}o_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:i_(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:i_(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},a_.prototype={areaStart:r_,areaEnd:r_,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x2=t,this._y2=n;break;case 1:this._point=2,this._x3=t,this._y3=n;break;case 2:this._point=3,this._x4=t,this._y4=n,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+n)/6);break;default:i_(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},u_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var e=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+n)/6;this._line?this._context.lineTo(e,r):this._context.moveTo(e,r);break;case 3:this._point=4;default:i_(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},c_.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,n=this._y,e=t.length-1;if(e>0)for(var r,i=t[0],o=n[0],a=t[e]-i,u=n[e]-o,c=-1;++c<=e;)r=c/e,this._basis.point(this._beta*t[c]+(1-this._beta)*(i+r*a),this._beta*n[c]+(1-this._beta)*(o+r*u));this._x=this._y=null,this._basis.lineEnd()},point:function(t,n){this._x.push(+t),this._y.push(+n)}};var f_=function t(n){function e(t){return 1===n?new o_(t):new c_(t,n)}return e.beta=function(n){return t(+n)},e}(.85);function s_(t,n,e){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-n),t._y2+t._k*(t._y1-e),t._x2,t._y2)}function l_(t,n){this._context=t,this._k=(1-n)/6}l_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:s_(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2,this._x1=t,this._y1=n;break;case 2:this._point=3;default:s_(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var h_=function t(n){function e(t){return new l_(t,n)}return e.tension=function(n){return t(+n)},e}(0);function d_(t,n){this._context=t,this._k=(1-n)/6}d_.prototype={areaStart:r_,areaEnd:r_,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:s_(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var p_=function t(n){function e(t){return new d_(t,n)}return e.tension=function(n){return t(+n)},e}(0);function v_(t,n){this._context=t,this._k=(1-n)/6}v_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:s_(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var g_=function t(n){function e(t){return new v_(t,n)}return e.tension=function(n){return t(+n)},e}(0);function y_(t,n,e){var r=t._x1,i=t._y1,o=t._x2,a=t._y2;if(t._l01_a>uy){var u=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,c=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*u-t._x0*t._l12_2a+t._x2*t._l01_2a)/c,i=(i*u-t._y0*t._l12_2a+t._y2*t._l01_2a)/c}if(t._l23_a>uy){var f=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,s=3*t._l23_a*(t._l23_a+t._l12_a);o=(o*f+t._x1*t._l23_2a-n*t._l12_2a)/s,a=(a*f+t._y1*t._l23_2a-e*t._l12_2a)/s}t._context.bezierCurveTo(r,i,o,a,t._x2,t._y2)}function __(t,n){this._context=t,this._alpha=n}__.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3;default:y_(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var b_=function t(n){function e(t){return n?new __(t,n):new l_(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function m_(t,n){this._context=t,this._alpha=n}m_.prototype={areaStart:r_,areaEnd:r_,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:y_(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var x_=function t(n){function e(t){return n?new m_(t,n):new d_(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function w_(t,n){this._context=t,this._alpha=n}w_.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:y_(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var M_=function t(n){function e(t){return n?new w_(t,n):new v_(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function N_(t){this._context=t}function A_(t){return t<0?-1:1}function T_(t,n,e){var r=t._x1-t._x0,i=n-t._x1,o=(t._y1-t._y0)/(r||i<0&&-0),a=(e-t._y1)/(i||r<0&&-0),u=(o*i+a*r)/(r+i);return(A_(o)+A_(a))*Math.min(Math.abs(o),Math.abs(a),.5*Math.abs(u))||0}function S_(t,n){var e=t._x1-t._x0;return e?(3*(t._y1-t._y0)/e-n)/2:n}function k_(t,n,e){var r=t._x0,i=t._y0,o=t._x1,a=t._y1,u=(o-r)/3;t._context.bezierCurveTo(r+u,i+u*n,o-u,a-u*e,o,a)}function E_(t){this._context=t}function C_(t){this._context=new P_(t)}function P_(t){this._context=t}function z_(t){this._context=t}function R_(t){var n,e,r=t.length-1,i=new Array(r),o=new Array(r),a=new Array(r);for(i[0]=0,o[0]=2,a[0]=t[0]+2*t[1],n=1;n=0;--n)i[n]=(a[n]-i[n+1])/o[n];for(o[r-1]=(t[r]+i[r-1])/2,n=0;n1)for(var e,r,i,o=1,a=t[n[0]],u=a.length;o=0;)e[n]=n;return e}function U_(t,n){return t[n]}function O_(t){var n=t.map(B_);return L_(t).sort(function(t,e){return n[t]-n[e]})}function B_(t){for(var n,e=-1,r=0,i=t.length,o=-1/0;++eo&&(o=n,r=e);return r}function Y_(t){var n=t.map(F_);return L_(t).sort(function(t,e){return n[t]-n[e]})}function F_(t){for(var n,e=0,r=-1,i=t.length;++r0)){if(o/=h,h<0){if(o0){if(o>l)return;o>s&&(s=o)}if(o=r-c,h||!(o<0)){if(o/=h,h<0){if(o>l)return;o>s&&(s=o)}else if(h>0){if(o0)){if(o/=d,d<0){if(o0){if(o>l)return;o>s&&(s=o)}if(o=i-f,d||!(o<0)){if(o/=d,d<0){if(o>l)return;o>s&&(s=o)}else if(d>0){if(o0||l<1)||(s>0&&(t[0]=[c+s*h,f+s*d]),l<1&&(t[1]=[c+l*h,f+l*d]),!0)}}}}}function tb(t,n,e,r,i){var o=t[1];if(o)return!0;var a,u,c=t[0],f=t.left,s=t.right,l=f[0],h=f[1],d=s[0],p=s[1],v=(l+d)/2,g=(h+p)/2;if(p===h){if(v=r)return;if(l>d){if(c){if(c[1]>=i)return}else c=[v,e];o=[v,i]}else{if(c){if(c[1]1)if(l>d){if(c){if(c[1]>=i)return}else c=[(e-u)/a,e];o=[(i-u)/a,i]}else{if(c){if(c[1]=r)return}else c=[n,a*n+u];o=[r,a*r+u]}else{if(c){if(c[0]=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,n),this._context.lineTo(t,n);else{var e=this._x*(1-this._t)+t*this._t;this._context.lineTo(e,this._y),this._context.lineTo(e,n)}}this._x=t,this._y=n}},X_.prototype={constructor:X_,insert:function(t,n){var e,r,i;if(t){if(n.P=t,n.N=t.N,t.N&&(t.N.P=n),t.N=n,t.R){for(t=t.R;t.L;)t=t.L;t.L=n}else t.R=n;e=t}else this._?(t=W_(this._),n.P=null,n.N=t,t.P=t.L=n,e=t):(n.P=n.N=null,this._=n,e=null);for(n.L=n.R=null,n.U=e,n.C=!0,t=n;e&&e.C;)e===(r=e.U).L?(i=r.R)&&i.C?(e.C=i.C=!1,r.C=!0,t=r):(t===e.R&&(V_(this,e),e=(t=e).U),e.C=!1,r.C=!0,$_(this,r)):(i=r.L)&&i.C?(e.C=i.C=!1,r.C=!0,t=r):(t===e.L&&($_(this,e),e=(t=e).U),e.C=!1,r.C=!0,V_(this,r)),e=t.U;this._.C=!1},remove:function(t){t.N&&(t.N.P=t.P),t.P&&(t.P.N=t.N),t.N=t.P=null;var n,e,r,i=t.U,o=t.L,a=t.R;if(e=o?a?W_(a):o:a,i?i.L===t?i.L=e:i.R=e:this._=e,o&&a?(r=e.C,e.C=t.C,e.L=o,o.U=e,e!==a?(i=e.U,e.U=t.U,t=e.R,i.L=t,e.R=a,a.U=e):(e.U=i,i=e,t=e.R)):(r=t.C,t=e),t&&(t.U=i),!r)if(t&&t.C)t.C=!1;else{do{if(t===this._)break;if(t===i.L){if((n=i.R).C&&(n.C=!1,i.C=!0,V_(this,i),n=i.R),n.L&&n.L.C||n.R&&n.R.C){n.R&&n.R.C||(n.L.C=!1,n.C=!0,$_(this,n),n=i.R),n.C=i.C,i.C=n.R.C=!1,V_(this,i),t=this._;break}}else if((n=i.L).C&&(n.C=!1,i.C=!0,$_(this,i),n=i.L),n.L&&n.L.C||n.R&&n.R.C){n.L&&n.L.C||(n.R.C=!1,n.C=!0,V_(this,n),n=i.L),n.C=i.C,i.C=n.L.C=!1,$_(this,i),t=this._;break}n.C=!0,t=i,i=i.U}while(!t.C);t&&(t.C=!1)}}};var ib,ob=[];function ab(){G_(this),this.x=this.y=this.arc=this.site=this.cy=null}function ub(t){var n=t.P,e=t.N;if(n&&e){var r=n.site,i=t.site,o=e.site;if(r!==o){var a=i[0],u=i[1],c=r[0]-a,f=r[1]-u,s=o[0]-a,l=o[1]-u,h=2*(c*l-f*s);if(!(h>=-wb)){var d=c*c+f*f,p=s*s+l*l,v=(l*d-f*p)/h,g=(c*p-s*d)/h,y=ob.pop()||new ab;y.arc=t,y.site=i,y.x=v+a,y.y=(y.cy=g+u)+Math.sqrt(v*v+g*g),t.circle=y;for(var _=null,b=bb._;b;)if(y.yxb)u=u.L;else{if(!((i=o-gb(u,a))>xb)){r>-xb?(n=u.P,e=u):i>-xb?(n=u,e=u.N):n=e=u;break}if(!u.R){n=u;break}u=u.R}!function(t){_b[t.index]={site:t,halfedges:[]}}(t);var c=lb(t);if(yb.insert(n,c),n||e){if(n===e)return cb(n),e=lb(n.site),yb.insert(c,e),c.edge=e.edge=Z_(n.site,c.site),ub(n),void ub(e);if(e){cb(n),cb(e);var f=n.site,s=f[0],l=f[1],h=t[0]-s,d=t[1]-l,p=e.site,v=p[0]-s,g=p[1]-l,y=2*(h*g-d*v),_=h*h+d*d,b=v*v+g*g,m=[(g*_-d*b)/y+s,(h*b-v*_)/y+l];J_(e.edge,f,p,m),c.edge=Z_(f,t,null,m),e.edge=Z_(t,p,null,m),ub(n),ub(e)}else c.edge=Z_(n.site,c.site)}}function vb(t,n){var e=t.site,r=e[0],i=e[1],o=i-n;if(!o)return r;var a=t.P;if(!a)return-1/0;var u=(e=a.site)[0],c=e[1],f=c-n;if(!f)return u;var s=u-r,l=1/o-1/f,h=s/f;return l?(-h+Math.sqrt(h*h-2*l*(s*s/(-2*f)-c+f/2+i-o/2)))/l+r:(r+u)/2}function gb(t,n){var e=t.N;if(e)return vb(e,n);var r=t.site;return r[1]===n?r[0]:1/0}var yb,_b,bb,mb,xb=1e-6,wb=1e-12;function Mb(t,n){return n[1]-t[1]||n[0]-t[0]}function Nb(t,n){var e,r,i,o=t.sort(Mb).pop();for(mb=[],_b=new Array(t.length),yb=new X_,bb=new X_;;)if(i=ib,o&&(!i||o[1]xb||Math.abs(i[0][1]-i[1][1])>xb)||delete mb[o]}(a,u,c,f),function(t,n,e,r){var i,o,a,u,c,f,s,l,h,d,p,v,g=_b.length,y=!0;for(i=0;ixb||Math.abs(v-h)>xb)&&(c.splice(u,0,mb.push(Q_(a,d,Math.abs(p-t)xb?[t,Math.abs(l-t)xb?[Math.abs(h-r)xb?[e,Math.abs(l-e)xb?[Math.abs(h-n)=u)return null;var c=t-i.site[0],f=n-i.site[1],s=c*c+f*f;do{i=o.cells[r=a],a=null,i.halfedges.forEach(function(e){var r=o.edges[e],u=r.left;if(u!==i.site&&u||(u=r.right)){var c=t-u[0],f=n-u[1],l=c*c+f*f;lr?(r+i)/2:Math.min(0,r)||Math.max(0,i),a>o?(o+a)/2:Math.min(0,o)||Math.max(0,a))}Eb.prototype=Sb.prototype,t.version="5.9.2",t.bisect=i,t.bisectRight=i,t.bisectLeft=o,t.ascending=n,t.bisector=e,t.cross=function(t,n,e){var r,i,o,u,c=t.length,f=n.length,s=new Array(c*f);for(null==e&&(e=a),r=o=0;rt?1:n>=t?0:NaN},t.deviation=f,t.extent=s,t.histogram=function(){var t=v,n=s,e=M;function r(r){var o,a,u=r.length,c=new Array(u);for(o=0;ol;)h.pop(),--d;var p,v=new Array(d+1);for(o=0;o<=d;++o)(p=v[o]=[]).x0=o>0?h[o-1]:s,p.x1=o=r.length)return null!=t&&e.sort(t),null!=n?n(e):e;for(var c,f,s,l=-1,h=e.length,d=r[i++],p=Qi(),v=a();++lr.length)return e;var a,u=i[o-1];return null!=n&&o>=r.length?a=e.entries():(a=[],e.each(function(n,e){a.push({key:e,values:t(n,o)})})),null!=u?a.sort(function(t,n){return u(t.key,n.key)}):a}(o(t,0,to,no),0)},key:function(t){return r.push(t),e},sortKeys:function(t){return i[r.length-1]=t,e},sortValues:function(n){return t=n,e},rollup:function(t){return n=t,e}}},t.set=io,t.map=Qi,t.keys=function(t){var n=[];for(var e in t)n.push(e);return n},t.values=function(t){var n=[];for(var e in t)n.push(t[e]);return n},t.entries=function(t){var n=[];for(var e in t)n.push({key:e,value:t[e]});return n},t.color=hn,t.rgb=gn,t.hsl=mn,t.lab=Rn,t.hcl=Yn,t.lch=function(t,n,e,r){return 1===arguments.length?Bn(t):new Fn(e,n,t,null==r?1:r)},t.gray=function(t,n){return new Dn(t,0,0,null==n?1:n)},t.cubehelix=Zn,t.contours=po,t.contourDensity=function(){var t=yo,n=_o,e=bo,r=960,i=500,o=20,a=2,u=3*o,c=r+2*u>>a,f=i+2*u>>a,s=uo(20);function l(r){var i=new Float32Array(c*f),l=new Float32Array(c*f);r.forEach(function(r,o,s){var l=+t(r,o,s)+u>>a,h=+n(r,o,s)+u>>a,d=+e(r,o,s);l>=0&&l=0&&h>a),go({width:c,height:f,data:l},{width:c,height:f,data:i},o>>a),vo({width:c,height:f,data:i},{width:c,height:f,data:l},o>>a),go({width:c,height:f,data:l},{width:c,height:f,data:i},o>>a),vo({width:c,height:f,data:i},{width:c,height:f,data:l},o>>a),go({width:c,height:f,data:l},{width:c,height:f,data:i},o>>a);var d=s(i);if(!Array.isArray(d)){var p=A(i);d=w(0,p,d),(d=g(0,Math.floor(p/d)*d,d)).shift()}return po().thresholds(d).size([c,f])(i).map(h)}function h(t){return t.value*=Math.pow(2,-2*a),t.coordinates.forEach(d),t}function d(t){t.forEach(p)}function p(t){t.forEach(v)}function v(t){t[0]=t[0]*Math.pow(2,a)-u,t[1]=t[1]*Math.pow(2,a)-u}function y(){return c=r+2*(u=3*o)>>a,f=i+2*u>>a,l}return l.x=function(n){return arguments.length?(t="function"==typeof n?n:uo(+n),l):t},l.y=function(t){return arguments.length?(n="function"==typeof t?t:uo(+t),l):n},l.weight=function(t){return arguments.length?(e="function"==typeof t?t:uo(+t),l):e},l.size=function(t){if(!arguments.length)return[r,i];var n=Math.ceil(t[0]),e=Math.ceil(t[1]);if(!(n>=0||n>=0))throw new Error("invalid size");return r=n,i=e,y()},l.cellSize=function(t){if(!arguments.length)return 1<=1))throw new Error("invalid cell size");return a=Math.floor(Math.log(t)/Math.LN2),y()},l.thresholds=function(t){return arguments.length?(s="function"==typeof t?t:Array.isArray(t)?uo(oo.call(t)):uo(t),l):s},l.bandwidth=function(t){if(!arguments.length)return Math.sqrt(o*(o+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return o=Math.round((Math.sqrt(4*t*t+1)-1)/2),y()},l},t.dispatch=I,t.drag=function(){var n,e,r,i,o=Gt,a=Vt,u=$t,c=Wt,f={},s=I("start","drag","end"),l=0,h=0;function d(t){t.on("mousedown.drag",p).filter(c).on("touchstart.drag",y).on("touchmove.drag",_).on("touchend.drag touchcancel.drag",b).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(){if(!i&&o.apply(this,arguments)){var u=m("mouse",a.apply(this,arguments),Ot,this,arguments);u&&(zt(t.event.view).on("mousemove.drag",v,!0).on("mouseup.drag",g,!0),It(t.event.view),Yt(),r=!1,n=t.event.clientX,e=t.event.clientY,u("start"))}}function v(){if(Ft(),!r){var i=t.event.clientX-n,o=t.event.clientY-e;r=i*i+o*o>h}f.mouse("drag")}function g(){zt(t.event.view).on("mousemove.drag mouseup.drag",null),jt(t.event.view,r),Ft(),f.mouse("end")}function y(){if(o.apply(this,arguments)){var n,e,r=t.event.changedTouches,i=a.apply(this,arguments),u=r.length;for(n=0;nc+d||if+d||ou.index){var p=c-a.x-a.vx,v=f-a.y-a.vy,g=p*p+v*v;gt.r&&(t.r=t[n].r)}function u(){if(n){var r,i,o=n.length;for(e=new Array(o),r=0;r=a)){(t.data!==n||t.next)&&(0===s&&(d+=(s=na())*s),0===l&&(d+=(l=na())*l),d1?(null==e?u.remove(t):u.set(t,d(e)),n):u.get(t)},find:function(n,e,r){var i,o,a,u,c,f=0,s=t.length;for(null==r?r=1/0:r*=r,f=0;f1?(f.on(t,e),n):f.on(t)}}},t.forceX=function(t){var n,e,r,i=ta(.1);function o(t){for(var i,o=0,a=n.length;opc(r[0],r[1])&&(r[1]=i[1]),pc(i[0],r[1])>pc(r[0],r[1])&&(r[0]=i[0])):o.push(r=i);for(a=-1/0,n=0,r=o[e=o.length-1];n<=e;r=i,++n)i=o[n],(u=pc(r[1],i[0]))>a&&(a=u,Ru=i[0],qu=r[1])}return Fu=Iu=null,Ru===1/0||Du===1/0?[[NaN,NaN],[NaN,NaN]]:[[Ru,Du],[qu,Lu]]},t.geoCentroid=function(t){ju=Hu=Xu=Gu=Vu=$u=Wu=Zu=Qu=Ju=Ku=0,du(t,yc);var n=Qu,e=Ju,r=Ku,i=n*n+e*e+r*r;return i=.12&&i<.234&&r>=-.425&&r<-.214?u:i>=.166&&i<.234&&r>=-.214&&r<-.115?c:a).invert(t)},s.stream=function(e){return t&&n===e?t:(r=[a.stream(n=e),u.stream(e),c.stream(e)],i=r.length,t={point:function(t,n){for(var e=-1;++e2?t[2]+90:90]):[(t=e())[0],t[1],t[2]-90]},e([0,0,90]).scale(159.155)},t.geoTransverseMercatorRaw=al,t.geoRotation=qc,t.geoStream=du,t.geoTransform=function(t){return{stream:xs(t)}},t.cluster=function(){var t=ul,n=1,e=1,r=!1;function i(i){var o,a=0;i.eachAfter(function(n){var e=n.children;e?(n.x=function(t){return t.reduce(cl,0)/t.length}(e),n.y=function(t){return 1+t.reduce(fl,0)}(e)):(n.x=o?a+=t(n,o):0,n.y=0,o=n)});var u=function(t){for(var n;n=t.children;)t=n[0];return t}(i),c=function(t){for(var n;n=t.children;)t=n[n.length-1];return t}(i),f=u.x-t(u,c)/2,s=c.x+t(c,u)/2;return i.eachAfter(r?function(t){t.x=(t.x-i.x)*n,t.y=(i.y-t.y)*e}:function(t){t.x=(t.x-f)/(s-f)*n,t.y=(1-(i.y?t.y/i.y:1))*e})}return i.separation=function(n){return arguments.length?(t=n,i):t},i.size=function(t){return arguments.length?(r=!1,n=+t[0],e=+t[1],i):r?null:[n,e]},i.nodeSize=function(t){return arguments.length?(r=!0,n=+t[0],e=+t[1],i):r?[n,e]:null},i},t.hierarchy=ll,t.pack=function(){var t=null,n=1,e=1,r=Pl;function i(i){return i.x=n/2,i.y=e/2,t?i.eachBefore(Dl(t)).eachAfter(ql(r,.5)).eachBefore(Ll(1)):i.eachBefore(Dl(Rl)).eachAfter(ql(Pl,1)).eachAfter(ql(r,i.r/Math.min(n,e))).eachBefore(Ll(Math.min(n,e)/(2*i.r))),i}return i.radius=function(n){return arguments.length?(t=null==(e=n)?null:Cl(e),i):t;var e},i.size=function(t){return arguments.length?(n=+t[0],e=+t[1],i):[n,e]},i.padding=function(t){return arguments.length?(r="function"==typeof t?t:zl(+t),i):r},i},t.packSiblings=function(t){return El(t),t},t.packEnclose=yl,t.partition=function(){var t=1,n=1,e=0,r=!1;function i(i){var o=i.height+1;return i.x0=i.y0=e,i.x1=t,i.y1=n/o,i.eachBefore(function(t,n){return function(r){r.children&&Ol(r,r.x0,t*(r.depth+1)/n,r.x1,t*(r.depth+2)/n);var i=r.x0,o=r.y0,a=r.x1-e,u=r.y1-e;a0)throw new Error("cycle");return o}return e.id=function(n){return arguments.length?(t=Cl(n),e):t},e.parentId=function(t){return arguments.length?(n=Cl(t),e):n},e},t.tree=function(){var t=Hl,n=1,e=1,r=null;function i(i){var c=function(t){for(var n,e,r,i,o,a=new Wl(t,0),u=[a];n=u.pop();)if(r=n._.children)for(n.children=new Array(o=r.length),i=o-1;i>=0;--i)u.push(e=n.children[i]=new Wl(r[i],i)),e.parent=n;return(a.parent=new Wl(null,0)).children=[a],a}(i);if(c.eachAfter(o),c.parent.m=-c.z,c.eachBefore(a),r)i.eachBefore(u);else{var f=i,s=i,l=i;i.eachBefore(function(t){t.xs.x&&(s=t),t.depth>l.depth&&(l=t)});var h=f===s?1:t(f,s)/2,d=h-f.x,p=n/(s.x+h+d),v=e/(l.depth||1);i.eachBefore(function(t){t.x=(t.x+d)*p,t.y=t.depth*v})}return i}function o(n){var e=n.children,r=n.parent.children,i=n.i?r[n.i-1]:null;if(e){!function(t){for(var n,e=0,r=0,i=t.children,o=i.length;--o>=0;)(n=i[o]).z+=e,n.m+=e,e+=n.s+(r+=n.c)}(n);var o=(e[0].z+e[e.length-1].z)/2;i?(n.z=i.z+t(n._,i._),n.m=n.z-o):n.z=o}else i&&(n.z=i.z+t(n._,i._));n.parent.A=function(n,e,r){if(e){for(var i,o=n,a=n,u=e,c=o.parent.children[0],f=o.m,s=a.m,l=u.m,h=c.m;u=Gl(u),o=Xl(o),u&&o;)c=Xl(c),(a=Gl(a)).a=n,(i=u.z+l-o.z-f+t(u._,o._))>0&&(Vl($l(u,n,r),n,i),f+=i,s+=i),l+=u.m,f+=o.m,h+=c.m,s+=a.m;u&&!Gl(a)&&(a.t=u,a.m+=l-s),o&&!Xl(c)&&(c.t=o,c.m+=f-h,r=n)}return r}(n,i,n.parent.A||r[0])}function a(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function u(t){t.x*=n,t.y=t.depth*e}return i.separation=function(n){return arguments.length?(t=n,i):t},i.size=function(t){return arguments.length?(r=!1,n=+t[0],e=+t[1],i):r?null:[n,e]},i.nodeSize=function(t){return arguments.length?(r=!0,n=+t[0],e=+t[1],i):r?[n,e]:null},i},t.treemap=function(){var t=Kl,n=!1,e=1,r=1,i=[0],o=Pl,a=Pl,u=Pl,c=Pl,f=Pl;function s(t){return t.x0=t.y0=0,t.x1=e,t.y1=r,t.eachBefore(l),i=[0],n&&t.eachBefore(Ul),t}function l(n){var e=i[n.depth],r=n.x0+e,s=n.y0+e,l=n.x1-e,h=n.y1-e;l=e-1){var s=u[n];return s.x0=i,s.y0=o,s.x1=a,void(s.y1=c)}for(var l=f[n],h=r/2+l,d=n+1,p=e-1;d>>1;f[v]c-o){var _=(i*y+a*g)/r;t(n,d,g,i,o,_,c),t(d,e,y,_,o,a,c)}else{var b=(o*y+c*g)/r;t(n,d,g,i,o,a,b),t(d,e,y,i,b,a,c)}}(0,c,t.value,n,e,r,i)},t.treemapDice=Ol,t.treemapSlice=Zl,t.treemapSliceDice=function(t,n,e,r,i){(1&t.depth?Zl:Ol)(t,n,e,r,i)},t.treemapSquarify=Kl,t.treemapResquarify=th,t.interpolate=ye,t.interpolateArray=se,t.interpolateBasis=Kn,t.interpolateBasisClosed=te,t.interpolateDate=le,t.interpolateDiscrete=function(t){var n=t.length;return function(e){return t[Math.max(0,Math.min(n-1,Math.floor(e*n)))]}},t.interpolateHue=function(t,n){var e=re(+t,+n);return function(t){var n=e(t);return n-360*Math.floor(n/360)}},t.interpolateNumber=he,t.interpolateObject=de,t.interpolateRound=_e,t.interpolateString=ge,t.interpolateTransformCss=Se,t.interpolateTransformSvg=ke,t.interpolateZoom=De,t.interpolateRgb=ae,t.interpolateRgbBasis=ce,t.interpolateRgbBasisClosed=fe,t.interpolateHsl=Le,t.interpolateHslLong=Ue,t.interpolateLab=function(t,n){var e=oe((t=Rn(t)).l,(n=Rn(n)).l),r=oe(t.a,n.a),i=oe(t.b,n.b),o=oe(t.opacity,n.opacity);return function(n){return t.l=e(n),t.a=r(n),t.b=i(n),t.opacity=o(n),t+""}},t.interpolateHcl=Be,t.interpolateHclLong=Ye,t.interpolateCubehelix=Ie,t.interpolateCubehelixLong=je,t.piecewise=function(t,n){for(var e=0,r=n.length-1,i=n[0],o=new Array(r<0?0:r);e=0;--n)f.push(t[r[o[n]][2]]);for(n=+u;nu!=f>u&&a<(c-e)*(u-r)/(f-r)+e&&(s=!s),c=e,f=r;return s},t.polygonLength=function(t){for(var n,e,r=-1,i=t.length,o=t[i-1],a=o[0],u=o[1],c=0;++r0?a[n-1]:r[0],n=o?[a[o-1],r]:[a[n-1],a[n]]},c.unknown=function(t){return arguments.length?(n=t,c):c},c.thresholds=function(){return a.slice()},c.copy=function(){return t().domain([e,r]).range(u).unknown(n)},sh.apply(Eh(c),arguments)},t.scaleThreshold=function t(){var n,e=[.5],r=[0,1],o=1;function a(t){return t<=t?r[i(e,t,0,o)]:n}return a.domain=function(t){return arguments.length?(e=ph.call(t),o=Math.min(e.length,r.length-1),a):e.slice()},a.range=function(t){return arguments.length?(r=ph.call(t),o=Math.min(e.length,r.length-1),a):r.slice()},a.invertExtent=function(t){var n=r.indexOf(t);return[e[n-1],e[n]]},a.unknown=function(t){return arguments.length?(n=t,a):n},a.copy=function(){return t().domain(e).range(r).unknown(n)},sh.apply(a,arguments)},t.scaleTime=function(){return sh.apply(Nv(Nd,wd,cd,od,rd,nd,Kh,Wh,t.timeFormat).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)},t.scaleUtc=function(){return sh.apply(Nv(Wd,Vd,Rd,Cd,kd,Td,Kh,Wh,t.utcFormat).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)},t.scaleSequential=function t(){var n=Eh(Av()(mh));return n.copy=function(){return Tv(n,t())},lh.apply(n,arguments)},t.scaleSequentialLog=function t(){var n=Uh(Av()).domain([1,10]);return n.copy=function(){return Tv(n,t()).base(n.base())},lh.apply(n,arguments)},t.scaleSequentialPow=Sv,t.scaleSequentialSqrt=function(){return Sv.apply(null,arguments).exponent(.5)},t.scaleSequentialSymlog=function t(){var n=Yh(Av());return n.copy=function(){return Tv(n,t()).constant(n.constant())},lh.apply(n,arguments)},t.scaleSequentialQuantile=function t(){var e=[],r=mh;function o(t){if(!isNaN(t=+t))return r((i(e,t)-1)/(e.length-1))}return o.domain=function(t){if(!arguments.length)return e.slice();e=[];for(var r,i=0,a=t.length;i1)&&(t-=Math.floor(t));var n=Math.abs(t-.5);return Hg.h=360*t-100,Hg.s=1.5-1.5*n,Hg.l=.8-.9*n,Hg+""},t.interpolateWarm=Ig,t.interpolateCool=jg,t.interpolateSinebow=function(t){var n;return t=(.5-t)*Math.PI,Xg.r=255*(n=Math.sin(t))*n,Xg.g=255*(n=Math.sin(t+Gg))*n,Xg.b=255*(n=Math.sin(t+Vg))*n,Xg+""},t.interpolateViridis=Wg,t.interpolateMagma=Zg,t.interpolateInferno=Qg,t.interpolatePlasma=Jg,t.create=function(t){return zt(W(t).call(document.documentElement))},t.creator=W,t.local=Dt,t.matcher=tt,t.mouse=Ot,t.namespace=$,t.namespaces=V,t.clientPoint=Ut,t.select=zt,t.selectAll=function(t){return"string"==typeof t?new Ct([document.querySelectorAll(t)],[document.documentElement]):new Ct([null==t?[]:t],Et)},t.selection=Pt,t.selector=Q,t.selectorAll=K,t.style=ct,t.touch=Bt,t.touches=function(t,n){null==n&&(n=Lt().touches);for(var e=0,r=n?n.length:0,i=new Array(r);ed;if(u||(u=c=Hi()),huy)if(v>sy-uy)u.moveTo(h*ey(d),h*oy(d)),u.arc(0,0,h,d,p,!g),l>uy&&(u.moveTo(l*ey(p),l*oy(p)),u.arc(0,0,l,p,d,g));else{var y,_,b=d,m=p,x=d,w=p,M=v,N=v,A=a.apply(this,arguments)/2,T=A>uy&&(r?+r.apply(this,arguments):ay(l*l+h*h)),S=iy(ty(h-l)/2,+e.apply(this,arguments)),k=S,E=S;if(T>uy){var C=ly(T/l*oy(A)),P=ly(T/h*oy(A));(M-=2*C)>uy?(x+=C*=g?1:-1,w-=C):(M=0,x=w=(d+p)/2),(N-=2*P)>uy?(b+=P*=g?1:-1,m-=P):(N=0,b=m=(d+p)/2)}var z=h*ey(b),R=h*oy(b),D=l*ey(w),q=l*oy(w);if(S>uy){var L,U=h*ey(m),O=h*oy(m),B=l*ey(x),Y=l*oy(x);if(v1?0:s<-1?cy:Math.acos(s))/2),G=ay(L[0]*L[0]+L[1]*L[1]);k=iy(S,(l-G)/(X-1)),E=iy(S,(h-G)/(X+1))}}N>uy?E>uy?(y=yy(B,Y,z,R,h,E,g),_=yy(U,O,D,q,h,E,g),u.moveTo(y.cx+y.x01,y.cy+y.y01),Euy&&M>uy?k>uy?(y=yy(D,q,U,O,l,-k,g),_=yy(z,R,B,Y,l,-k,g),u.lineTo(y.cx+y.x01,y.cy+y.y01),k0&&(d+=l);for(null!=n?p.sort(function(t,e){return n(v[t],v[e])}):null!=e&&p.sort(function(t,n){return e(a[t],a[n])}),u=0,f=d?(y-h*b)/d:0;u0?l*f:0)+b,v[c]={data:a[c],index:u,value:l,startAngle:g,endAngle:s,padAngle:_};return v}return a.value=function(n){return arguments.length?(t="function"==typeof n?n:Kg(+n),a):t},a.sortValues=function(t){return arguments.length?(n=t,e=null,a):n},a.sort=function(t){return arguments.length?(e=t,n=null,a):e},a.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:Kg(+t),a):r},a.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:Kg(+t),a):i},a.padAngle=function(t){return arguments.length?(o="function"==typeof t?t:Kg(+t),a):o},a},t.areaRadial=Py,t.radialArea=Py,t.lineRadial=Cy,t.radialLine=Cy,t.pointRadial=zy,t.linkHorizontal=function(){return Ly(Uy)},t.linkVertical=function(){return Ly(Oy)},t.linkRadial=function(){var t=Ly(By);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t},t.symbol=function(){var t=Kg(Yy),n=Kg(64),e=null;function r(){var r;if(e||(e=r=Hi()),t.apply(this,arguments).draw(e,+n.apply(this,arguments)),r)return e=null,r+""||null}return r.type=function(n){return arguments.length?(t="function"==typeof n?n:Kg(n),r):t},r.size=function(t){return arguments.length?(n="function"==typeof t?t:Kg(+t),r):n},r.context=function(t){return arguments.length?(e=null==t?null:t,r):e},r},t.symbols=e_,t.symbolCircle=Yy,t.symbolCross=Fy,t.symbolDiamond=Hy,t.symbolSquare=Wy,t.symbolStar=$y,t.symbolTriangle=Qy,t.symbolWye=n_,t.curveBasisClosed=function(t){return new a_(t)},t.curveBasisOpen=function(t){return new u_(t)},t.curveBasis=function(t){return new o_(t)},t.curveBundle=f_,t.curveCardinalClosed=p_,t.curveCardinalOpen=g_,t.curveCardinal=h_,t.curveCatmullRomClosed=x_,t.curveCatmullRomOpen=M_,t.curveCatmullRom=b_,t.curveLinearClosed=function(t){return new N_(t)},t.curveLinear=by,t.curveMonotoneX=function(t){return new E_(t)},t.curveMonotoneY=function(t){return new C_(t)},t.curveNatural=function(t){return new z_(t)},t.curveStep=function(t){return new D_(t,.5)},t.curveStepAfter=function(t){return new D_(t,1)},t.curveStepBefore=function(t){return new D_(t,0)},t.stack=function(){var t=Kg([]),n=L_,e=q_,r=U_;function i(i){var o,a,u=t.apply(this,arguments),c=i.length,f=u.length,s=new Array(f);for(o=0;o0){for(var e,r,i,o=0,a=t[0].length;o1)for(var e,r,i,o,a,u,c=0,f=t[n[0]].length;c=0?(r[0]=o,r[1]=o+=i):i<0?(r[1]=a,r[0]=a+=i):r[0]=o},t.stackOffsetNone=q_,t.stackOffsetSilhouette=function(t,n){if((e=t.length)>0){for(var e,r=0,i=t[n[0]],o=i.length;r0&&(r=(e=t[n[0]]).length)>0){for(var e,r,i,o=0,a=1;adr&&e.name===n)return new Er([[t]],fi,n,+r);return null},t.interrupt=Mr,t.voronoi=function(){var t=j_,n=H_,e=null;function r(r){return new Nb(r.map(function(e,i){var o=[Math.round(t(e,i,r)/xb)*xb,Math.round(n(e,i,r)/xb)*xb];return o.index=i,o.data=e,o}),e)}return r.polygons=function(t){return r(t).polygons()},r.links=function(t){return r(t).links()},r.triangles=function(t){return r(t).triangles()},r.x=function(n){return arguments.length?(t="function"==typeof n?n:I_(+n),r):t},r.y=function(t){return arguments.length?(n="function"==typeof t?t:I_(+t),r):n},r.extent=function(t){return arguments.length?(e=null==t?null:[[+t[0][0],+t[0][1]],[+t[1][0],+t[1][1]]],r):e&&[[e[0][0],e[0][1]],[e[1][0],e[1][1]]]},r.size=function(t){return arguments.length?(e=null==t?null:[[0,0],[+t[0],+t[1]]],r):e&&[e[1][0]-e[0][0],e[1][1]-e[0][1]]},r},t.zoom=function(){var n,e,r=zb,i=Rb,o=Ub,a=qb,u=Lb,c=[0,1/0],f=[[-1/0,-1/0],[1/0,1/0]],s=250,l=De,h=[],d=I("start","zoom","end"),p=500,v=150,g=0;function y(t){t.property("__zoom",Db).on("wheel.zoom",N).on("mousedown.zoom",A).on("dblclick.zoom",T).filter(u).on("touchstart.zoom",S).on("touchmove.zoom",k).on("touchend.zoom touchcancel.zoom",E).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function _(t,n){return(n=Math.max(c[0],Math.min(c[1],n)))===t.k?t:new Sb(n,t.x,t.y)}function b(t,n,e){var r=n[0]-e[0]*t.k,i=n[1]-e[1]*t.k;return r===t.x&&i===t.y?t:new Sb(t.k,r,i)}function m(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function x(t,n,e){t.on("start.zoom",function(){w(this,arguments).start()}).on("interrupt.zoom end.zoom",function(){w(this,arguments).end()}).tween("zoom",function(){var t=arguments,r=w(this,t),o=i.apply(this,t),a=e||m(o),u=Math.max(o[1][0]-o[0][0],o[1][1]-o[0][1]),c=this.__zoom,f="function"==typeof n?n.apply(this,t):n,s=l(c.invert(a).concat(u/c.k),f.invert(a).concat(u/f.k));return function(t){if(1===t)t=f;else{var n=s(t),e=u/n[2];t=new Sb(e,a[0]-n[0]*e,a[1]-n[1]*e)}r.zoom(null,t)}})}function w(t,n){for(var e,r=0,i=h.length;rg}n.zoom("mouse",o(b(n.that.__zoom,n.mouse[0]=Ot(n.that),n.mouse[1]),n.extent,f))},!0).on("mouseup.zoom",function(){i.on("mousemove.zoom mouseup.zoom",null),jt(t.event.view,n.moved),Pb(),n.end()},!0),a=Ot(this),u=t.event.clientX,c=t.event.clientY;It(t.event.view),Cb(),n.mouse=[a,this.__zoom.invert(a)],Mr(this),n.start()}}function T(){if(r.apply(this,arguments)){var n=this.__zoom,e=Ot(this),a=n.invert(e),u=n.k*(t.event.shiftKey?.5:2),c=o(b(_(n,u),e,a),i.apply(this,arguments),f);Pb(),s>0?zt(this).transition().duration(s).call(x,c,e):zt(this).call(y.transform,c)}}function S(){if(r.apply(this,arguments)){var e,i,o,a,u=w(this,arguments),c=t.event.changedTouches,f=c.length;for(Cb(),i=0;i 1) { + var urlArgPairs = urlArgs[1].split('&'); + + // go through all the pairs, and if you find something you expect, deal with it + for (var i in urlArgPairs) { + var kvpair = urlArgPairs[i].split('='); + + // now look for the values you expect, and do something with them + // + // Note that this will not properly handle the case in which both parameters + // are set by url attributes + if (kvpair[0] == 'databases') { + databaseList = kvpair[1]; + } else if (kvpair[0] == 'assetname') { + AssetName = kvpair[1]; + } + } +} +// end override attributes + +function loadAttributes(callback) +{ + var xobj = new XMLHttpRequest(); + xobj.overrideMimeType("application/json"); + xobj.open('GET', "cinema/view/2.2/cinema_attributes.json", true); // Replace 'my_data' with the path to your file + xobj.onreadystatechange = function () { + if (xobj.readyState == 4 && (xobj.status == 0 || xobj.status == 200)) { + // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode + callback(xobj.responseText); + } + }; + xobj.send(null); +} + +function loadData(callback) +{ + var xobj = new XMLHttpRequest(); + xobj.overrideMimeType("application/json"); + xobj.open('GET', databaseList, true); // Replace 'my_data' with the path to your file + xobj.onreadystatechange = function () { + if (xobj.readyState == 4 && (xobj.status == 0 || xobj.status == 200)) { + // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode + callback(xobj.responseText); + } + }; + xobj.send(null); +} + + +function onlyUnique(value, index, self) +{ + return self.indexOf(value) === index; +} + +function getLookupKey(keys, query) +{ + var key = ""; + keys.forEach(function(item, index) { + key += query[item] + "_"; + }); + + return key; +} + + +// Initialize Dropdown list from JSON +var actual_JSON; + +databaseListType = db_get_database_list_type( databaseList ) +if (databaseListType == "json") { + loadData(function(response) + { + // Parse JSON string into object + actual_JSON = JSON.parse(response); + + var dbs = []; + for (i = 0; i < actual_JSON.length; i++) + { + dbs.push( actual_JSON[i].database_name ); + } + + var sel = document.getElementById('dbList'); + for(var i=0; i Cinema:Explorer + - - + + + + + + + + + + + + + - - - - - + +
@@ -117,7 +128,7 @@

Cinema:Explorer

- - + + diff --git a/cinema_simple.html b/cinema_simple.html new file mode 100644 index 0000000..609d780 --- /dev/null +++ b/cinema_simple.html @@ -0,0 +1,196 @@ + + + + + + + + + + + + + + + + + + +
+
+

Cinema:Simple

+
+ +
+
+
+
+
+
Image Size
+ +
+
+
+
+
+ +
 
+ +
+ + + + diff --git a/cinema_view.html b/cinema_view.html index 040b9ba..22515e4 100644 --- a/cinema_view.html +++ b/cinema_view.html @@ -15,17 +15,24 @@ flex-wrap: wrap; } - + - - + + + + + + + + + + + -

Cinema:View

@@ -58,333 +65,7 @@

Cinema:View

 
- - + + + diff --git a/cinema/testImages/sedov.png b/doc/img/sedov.png similarity index 100% rename from cinema/testImages/sedov.png rename to doc/img/sedov.png diff --git a/cinema/testImages/sphere.png b/doc/img/sphere.png similarity index 100% rename from cinema/testImages/sphere.png rename to doc/img/sphere.png diff --git a/doc/readme_view.md b/doc/readme_view.md index 0db50b8..12b8a2d 100644 --- a/doc/readme_view.md +++ b/doc/readme_view.md @@ -21,11 +21,11 @@ To use Cinema:View, you **MUST** allow local file access. Do this in the followi To use the viewer, select the database you want to see from the dropdown "Select a database". sphere test should look like: - + while sedov test should look like: - + ## Adding a database to the viewer diff --git a/readme.md b/readme.md index 7259408..cb7eeff 100644 --- a/readme.md +++ b/readme.md @@ -1,8 +1,9 @@ # Cinema Viewers repository -## Version 2.0 +## Version 2.1 Integration of Cinema:Explorer and Cinema:View repositories - [Cinema:Explorer](doc/readme_explorer.md) - [Cinema:View](doc/readme_view.md) +- Cinema:Simple, the simplest single/double viewer diff --git a/test_explorer.html b/testplan_explorer.html similarity index 100% rename from test_explorer.html rename to testplan_explorer.html diff --git a/test_view.html b/testplan_view.html similarity index 100% rename from test_view.html rename to testplan_view.html diff --git a/version.md b/version.md index cd5ac03..8bbe6cf 100644 --- a/version.md +++ b/version.md @@ -1 +1 @@ -2.0 +2.2