Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Controllers/JobController.cs
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Controllers/JobController.cs	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Controllers/JobController.cs	(revision 13712)
@@ -38,6 +38,7 @@
             try
             {
-
-                vm.userJobs = client.GetJobs();
+                HiveClientWeb.Instance.Refresh();
+
+                vm.userJobs = HiveClientWeb.Instance.Jobs.ToList();
             }
             catch (Exception e)
@@ -57,13 +58,17 @@
             if (((HiveServiceLocatorWebManagerService)(HiveServiceLocatorWebManagerService.Instance)).CheckLogin())
             {
-                vm.userJobs = client.GetJobs();
-                vm.selectedJob = client.GetJob(id);
-
-                vm.lightJobTasks = client.GetLightweightJobTasks(id);
-                foreach (var light in vm.lightJobTasks)
-                {
-                    vm.filledJobTasks.Add(client.GetTask(light.Id));
-                }
-                ViewBag.Title = vm.selectedJob.Name + " - Jobs";
+                HiveClientWeb.Instance.Refresh();
+
+                vm.userJobs = HiveClientWeb.Instance.Jobs.ToList();
+                foreach(var j in vm.userJobs)
+                {
+                    if(j.Id == id)
+                    {
+                        vm.selectedJob = j;
+                    }
+                }
+                vm.selectedJob.RefreshAutomatically = true;
+                HiveClientWeb.LoadJob(vm.selectedJob);
+                ViewBag.Title = vm.selectedJob.Job.Name + " - Jobs";
                 return View("Index", vm);
             }
@@ -81,5 +86,7 @@
                 vm.message = client.GetJob(id).Name + " deleted";
                 client.DeleteJob(id);
-                vm.userJobs = client.GetJobs();
+                HiveClientWeb.Instance.Refresh();
+
+                vm.userJobs = HiveClientWeb.Instance.Jobs.ToList();
                 ViewBag.Title = "Jobs";
                 return View("Index", vm);
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/JobUpdaterHub.cs
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/JobUpdaterHub.cs	(revision 13712)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/JobUpdaterHub.cs	(revision 13712)
@@ -0,0 +1,22 @@
+﻿using Microsoft.AspNet.SignalR;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace HeuristicLab.Clients.Hive.WebJobManager
+{
+    public class JobUpdaterHub : Hub
+    {
+        private RefreshableJob Job;
+
+        public void initConnection(RefreshableJob j)
+        {
+            Job = j;
+        }
+        public void sendUpdate()
+        {
+            Clients.All.sendUpdate();
+        }
+    }
+}
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Models/AlgorithmContainer.cs
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Models/AlgorithmContainer.cs	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Models/AlgorithmContainer.cs	(revision 13712)
@@ -11,8 +11,10 @@
         public IAlgorithm algo { get; set; }
         public System.Random randy { get; set; }
-
-        public AlgorithmContainer(IAlgorithm al, System.Random r)
+        public List<int[]> depth { get; set; }
+        public AlgorithmContainer(IAlgorithm al, List<int[]> d, int[] v, System.Random r)
         {
             algo = al;
+            depth = d;
+            depth.Add(v);
             randy = r;
         }
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Models/HiveTaskContainer.cs
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Models/HiveTaskContainer.cs	(revision 13712)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Models/HiveTaskContainer.cs	(revision 13712)
@@ -0,0 +1,17 @@
+﻿using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace HeuristicLab.Clients.Hive.WebJobManager.Models
+{
+    public class HiveTaskContainer
+    {
+        public HiveTask hiveTask { get; set; }
+
+        public HiveTaskContainer(HiveTask hi)
+        {
+            hiveTask = hi;
+        }
+    }
+}
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/ProgressHub.cs
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/ProgressHub.cs	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/ProgressHub.cs	(revision 13712)
@@ -21,5 +21,6 @@
         public void ChangeName(string name)
         {
-            FileOpeningService.Instance.Job.Job.Name = name;
+            if (name != null)
+                FileOpeningService.Instance.Job.Job.Name = name;
         }
         public void ToggleChild(int[][] arr)
@@ -28,16 +29,69 @@
             HiveTask current = Job.HiveTasks.ToList()[0];
             //  IOptimizer current = Job.HiveTasks.ToArray() ;
-            for (var i = 0; i < arr.Length; i++)
+            if (arr.Length == 0)
             {
-
+                current.ItemTask.ComputeInParallel = !current.ItemTask.ComputeInParallel;
                 
-                if(i == arr.Length - 1)
+            }
+            else {
+                for (var i = 0; i < arr.Length; i++)
                 {
-                    current.ChildHiveTasks[arr[i][1]].ItemTask.ComputeInParallel = !current.ChildHiveTasks[arr[i][1]].ItemTask.ComputeInParallel;
 
 
+                    if (i == arr.Length - 1)
+                    {
+                        if (current.ItemTask.Item is BatchRun)
+                        {
+                            current.ChildHiveTasks[arr[i][1]].ItemTask.ComputeInParallel = !current.ChildHiveTasks[arr[i][1]].ItemTask.ComputeInParallel;
+                        }
+                        else if (current.ItemTask.Item is Experiment)
+                        {
+                            current.ChildHiveTasks[arr[i][0]].ItemTask.ComputeInParallel = !current.ChildHiveTasks[arr[i][0]].ItemTask.ComputeInParallel;
+                        }
+
+                    }
+                    else {
+                        if (current.ItemTask.Item is BatchRun)
+                            current = current.ChildHiveTasks[arr[i][1]]; // select right batch
+                        else if (current.ItemTask.Item is Experiment)
+                            current = current.ChildHiveTasks[arr[i][0]]; // select right sub task from experiment
+                    }
                 }
-                else
-                    current = current.ChildHiveTasks[arr[i][0]];
+            }
+        }
+        public void ChangePriority(int[][] arr, int prior)
+        {
+            Job = FileOpeningService.Instance.Job;
+            HiveTask current = Job.HiveTasks.ToList()[0];
+            //  IOptimizer current = Job.HiveTasks.ToArray() ;
+            if (arr.Length == 0)
+            {
+                current.Task.Priority = prior;
+
+            }
+            else {
+                for (var i = 0; i < arr.Length; i++)
+                {
+
+
+                    if (i == arr.Length - 1)
+                    {
+                        if (current.ItemTask.Item is BatchRun)
+                        {
+                            current.ChildHiveTasks[arr[i][1]].Task.Priority = prior;
+                        }
+                        else if (current.ItemTask.Item is Experiment)
+                        {
+                            current.ChildHiveTasks[arr[i][0]].Task.Priority = prior;
+                        }
+
+                    }
+                    else {
+                        if (current.ItemTask.Item is BatchRun)
+                            current = current.ChildHiveTasks[arr[i][1]]; // select right batch
+                        else if (current.ItemTask.Item is Experiment)
+                            current = current.ChildHiveTasks[arr[i][0]]; // select right sub task from experiment
+                    }
+                }
             }
         }
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/HiveClientWeb.cs
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/HiveClientWeb.cs	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/HiveClientWeb.cs	(revision 13712)
@@ -36,4 +36,5 @@
 using HeuristicLab.Clients.Common.Properties;
 using Microsoft.AspNet.Hosting;
+using HeuristicLab.Clients.Hive.WebJobManager.Services.Imports;
 
 namespace HeuristicLab.Clients.Hive.WebJobManager
@@ -320,5 +321,8 @@
                 }
 
-
+                foreach (OptimizerHiveTask hiveJob in refreshableJob.HiveTasks.OfType<OptimizerHiveTask>())
+                {
+                    hiveJob.SetIndexInParentOptimizerList(null);
+                }
 
                 // upload Job
@@ -486,5 +490,5 @@
             var hiveExperiment = refreshableJob.Job;
             refreshableJob.IsProgressing = true;
-            TaskDownloader downloader = null;
+            TaskDownloaderWeb downloader = null;
 
             try
@@ -499,5 +503,5 @@
 
                 refreshableJob.Progress.Status = "Downloading tasks...";
-                downloader = new TaskDownloader(allTasks.Select(x => x.Id));
+                downloader = new TaskDownloaderWeb(allTasks.Select(x => x.Id));
                 downloader.StartAsync();
 
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/HiveServiceLocatorWebManagerService.cs
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/HiveServiceLocatorWebManagerService.cs	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/HiveServiceLocatorWebManagerService.cs	(revision 13712)
@@ -149,4 +149,15 @@
             binding.AllowCookies = false;
 
+            binding.ReaderQuotas.MaxDepth = 32;
+            binding.ReaderQuotas.MaxStringContentLength = 200000000;
+            binding.ReaderQuotas.MaxArrayLength = 200000000;
+            binding.ReaderQuotas.MaxBytesPerRead = 4096;
+            binding.ReaderQuotas.MaxNameTableCharCount = 16384;
+
+            binding.ReliableSession.Ordered = true;
+            binding.ReliableSession.InactivityTimeout = TimeSpan.Parse("00:10:00");
+            binding.ReliableSession.Enabled = false;
+
+
             binding.Security.Mode = SecurityMode.Message;
             binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/Imports/ConcurrentTaskDownloaderWeb.cs
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/Imports/ConcurrentTaskDownloaderWeb.cs	(revision 13712)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/Imports/ConcurrentTaskDownloaderWeb.cs	(revision 13712)
@@ -0,0 +1,122 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+using HeuristicLab.Common;
+using HeuristicLab.Hive;
+
+namespace HeuristicLab.Clients.Hive.WebJobManager.Services.Imports
+{
+  /// <summary>
+  /// Downloads and deserializes jobs. It avoids too many jobs beeing downloaded or deserialized at the same time to avoid memory problems
+  /// </summary>
+  public class ConcurrentTaskDownloaderWeb<T> : IDisposable where T : class, ITask {
+    private bool abort = false;
+    // use semaphore to ensure only few concurrenct connections and few SerializedJob objects in memory
+    private Semaphore downloadSemaphore;
+    private Semaphore deserializeSemaphore;
+
+    public ConcurrentTaskDownloaderWeb(int concurrentDownloads, int concurrentDeserializations) {
+      downloadSemaphore = new Semaphore(concurrentDownloads, concurrentDownloads);
+      deserializeSemaphore = new Semaphore(concurrentDeserializations, concurrentDeserializations);
+    }
+
+    public void DownloadTaskData(Task t, Action<Task, T> onFinishedAction) {
+      Task<Tuple<Task, T>> task = Task<Tuple<Task, TaskData>>.Factory.StartNew(DownloadTaskData, t)
+                                     .ContinueWith((y) => DeserializeTask(y.Result));
+
+      task.ContinueWith((x) => OnTaskFinished(x, onFinishedAction), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion);
+      task.ContinueWith((x) => OnTaskFailed(x), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted);
+    }
+
+    public void DownloadTaskDataAndTask(Guid taskId, Action<Task, T> onFinishedAction) {
+      Task<Tuple<Task, T>> task = Task<Task>.Factory.StartNew(DownloadTask, taskId)
+                                     .ContinueWith((x) => DownloadTaskData(x.Result))
+                                     .ContinueWith((y) => DeserializeTask(y.Result));
+
+      task.ContinueWith((x) => OnTaskFinished(x, onFinishedAction), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion);
+      task.ContinueWith((x) => OnTaskFailed(x), TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted);
+    }
+
+    private void OnTaskFinished(Task<Tuple<Task, T>> task, Action<Task, T> onFinishedAction) {
+      onFinishedAction(task.Result.Item1, task.Result.Item2);
+    }
+    private void OnTaskFailed(Task<Tuple<Task, T>> task) {
+      task.Exception.Flatten().Handle((e) => { return true; });
+      OnExceptionOccured(task.Exception.Flatten());
+    }
+
+    private Task DownloadTask(object taskId) {
+      Task t = null;
+      HiveClientWeb.TryAndRepeat(() => {
+        t = HiveServiceLocatorWebManagerService.Instance.CallHiveService(s => s.GetTask((Guid)taskId));
+      }, Settings.Default.MaxRepeatServiceCalls, "Failed to download task.");
+      return t;
+    }
+
+    protected Tuple<Task, TaskData> DownloadTaskData(object taskId) {
+      return DownloadTaskData((Task)taskId);
+    }
+
+    protected Tuple<Task, TaskData> DownloadTaskData(Task task) {
+      downloadSemaphore.WaitOne();
+      TaskData result = null;
+      try {
+        if (abort) return null;
+        HiveClientWeb.TryAndRepeat(() => {
+          result = HiveServiceLocatorWebManagerService.Instance.CallHiveService(s => s.GetTaskData(task.Id));
+        }, Settings.Default.MaxRepeatServiceCalls, "Failed to download task data.");
+      }
+      finally {
+        downloadSemaphore.Release();
+      }
+      return new Tuple<Task, TaskData>(task, result);
+    }
+
+    protected Tuple<Task, T> DeserializeTask(Tuple<Task, TaskData> taskData) {
+      deserializeSemaphore.WaitOne();
+      try {
+        if (abort || taskData.Item2 == null || taskData.Item1 == null) return null;
+        var deserializedJob = PersistenceUtil.Deserialize<T>(taskData.Item2.Data);
+        taskData.Item2.Data = null; // reduce memory consumption.
+        return new Tuple<Task, T>(taskData.Item1, deserializedJob);
+      }
+      finally {
+        deserializeSemaphore.Release();
+      }
+    }
+
+    public event EventHandler<EventArgs<Exception>> ExceptionOccured;
+    private void OnExceptionOccured(Exception exception) {
+      var handler = ExceptionOccured;
+      if (handler != null) handler(this, new EventArgs<Exception>(exception));
+    }
+
+    #region IDisposable Members
+    public void Dispose() {
+      deserializeSemaphore.Dispose();
+      downloadSemaphore.Dispose();
+    }
+    #endregion
+  }
+}
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/Imports/TaskDownloaderWeb.cs
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/Imports/TaskDownloaderWeb.cs	(revision 13712)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Services/Imports/TaskDownloaderWeb.cs	(revision 13712)
@@ -0,0 +1,123 @@
+﻿#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
+ *
+ * This file is part of HeuristicLab.
+ *
+ * HeuristicLab is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * HeuristicLab is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
+ */
+#endregion
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using HeuristicLab.Common;
+
+namespace HeuristicLab.Clients.Hive.WebJobManager.Services.Imports {
+  public class TaskDownloaderWeb : IDisposable {
+    private IEnumerable<Guid> taskIds;
+    private ConcurrentTaskDownloaderWeb<ItemTask> taskDownloader;
+    private IDictionary<Guid, HiveTask> results;
+    private bool exceptionOccured = false;
+    private Exception currentException;
+    private ReaderWriterLockSlim resultsLock = new ReaderWriterLockSlim();
+
+    public bool IsFinished {
+      get {
+        try {
+          resultsLock.EnterReadLock();
+          return results.Count == taskIds.Count();
+        }
+        finally { resultsLock.ExitReadLock(); }
+      }
+    }
+
+    public bool IsFaulted {
+      get {
+        return exceptionOccured;
+      }
+    }
+
+    public Exception Exception {
+      get {
+        return currentException;
+      }
+    }
+
+    public int FinishedCount {
+      get {
+        try {
+          resultsLock.EnterReadLock();
+          return results.Count;
+        }
+        finally { resultsLock.ExitReadLock(); }
+      }
+    }
+
+    public IDictionary<Guid, HiveTask> Results {
+      get {
+        try {
+          resultsLock.EnterReadLock();
+          return results;
+        }
+        finally { resultsLock.ExitReadLock(); }
+      }
+    }
+
+    public TaskDownloaderWeb(IEnumerable<Guid> jobIds) {
+      taskIds = jobIds;
+      taskDownloader = new ConcurrentTaskDownloaderWeb<ItemTask>(Settings.Default.MaxParallelDownloads, Settings.Default.MaxParallelDownloads);
+      taskDownloader.ExceptionOccured += new EventHandler<EventArgs<Exception>>(taskDownloader_ExceptionOccured);
+      results = new Dictionary<Guid, HiveTask>();
+    }
+
+    public void StartAsync() {
+      foreach (Guid taskId in taskIds) {
+        taskDownloader.DownloadTaskDataAndTask(taskId,
+          (localTask, itemTask) => {
+            if (localTask != null && itemTask != null) {
+              HiveTask hiveTask = itemTask.CreateHiveTask();
+              hiveTask.Task = localTask;
+              try {
+                resultsLock.EnterWriteLock();
+                results.Add(localTask.Id, hiveTask);
+              }
+              finally { resultsLock.ExitWriteLock(); }
+            }
+          });
+      }
+    }
+
+    private void taskDownloader_ExceptionOccured(object sender, EventArgs<Exception> e) {
+      OnExceptionOccured(e.Value);
+    }
+
+    public event EventHandler<EventArgs<Exception>> ExceptionOccured;
+    private void OnExceptionOccured(Exception exception) {
+      exceptionOccured = true;
+      currentException = exception;
+      var handler = ExceptionOccured;
+      if (handler != null) handler(this, new EventArgs<Exception>(exception));
+    }
+
+    #region IDisposable Members
+    public void Dispose() {
+      taskDownloader.ExceptionOccured -= new EventHandler<EventArgs<Exception>>(taskDownloader_ExceptionOccured);
+      resultsLock.Dispose();
+      taskDownloader.Dispose();
+    }
+    #endregion
+  }
+}
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/ViewModels/JobViewModel.cs
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/ViewModels/JobViewModel.cs	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/ViewModels/JobViewModel.cs	(revision 13712)
@@ -8,9 +8,9 @@
     public class JobViewModel
     {
-        public List<Job> userJobs { get; set; }
+        public List<RefreshableJob> userJobs { get; set; }
 
-        public List<LightweightTask> lightJobTasks { get; set; }
-        public List<Task> filledJobTasks { get; set; }
-        public Job selectedJob { get; set; }
+        public RefreshableJob selectedJob { get; set; }
+
+        public List<HiveTask> selectedHiveTasks { get; set; }
         public string message { get; set; }
         public JobViewModel()
@@ -18,5 +18,5 @@
             userJobs = null;
             selectedJob = null;
-            filledJobTasks = new List<Task>();
+            selectedHiveTasks = new List<HiveTask>();
             message = "";
         }
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/Index.cshtml
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/Index.cshtml	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/Index.cshtml	(revision 13712)
@@ -18,5 +18,5 @@
         </a>
     </div>
-    <div class="row" style="padding:10px">
+    <div class="row" style="padding:10px; margin-right:0px!important">
         @if (Model.userJobs.Count == 0)
         {
@@ -34,7 +34,8 @@
                            asp-controller="Job"
                            asp-action="Selected"
-                           asp-route-id="@job.Id">
-                            @job.Name - @job.DateCreated
-                            <span class="badge">@job.JobCount</span>
+                           asp-route-id="@job.Id"
+                           onclick="showLoader()">
+                            @job.Job.Name - @job.Job.DateCreated
+                            <span class="badge">@job.Job.JobCount</span>
                         </a>
                     }
@@ -42,20 +43,25 @@
                 </div>
             </div>
+            <p style="display:none" id="loader" class="text-center">
+                <br /><br /><br /><br /><br /><br /><br />
+                <i class="fa fa-cog fa-spin fa-5x" id="spinner">
+                </i>
+            </p>
             @if (Model.selectedJob != null)
             {
-                <div class="col-sm-8" style="padding:5px; padding-left:10px;">
+                <div class="col-sm-8" id="content" style="padding:5px; padding-left:10px;">
                     <div class="row">
                         <h2 style="padding-left:20px">
-                            @Model.selectedJob.Name
+                            @Model.selectedJob.Job.Name
                             <a onclick="popUpDelete()"
-                               style="margin-bottom:10px;" 
-                               
+                               style="margin-bottom:10px;"
                                class='btn btn-danger'>
                                 <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
                             </a>
-                            <a style="display:none" 
-                               asp-action="Delete" 
-                               asp-route-id="@Model.selectedJob.Id" 
-                               asp-controller="Job" id="del"  ></a>
+                            <a style="display:none"
+                               asp-action="Delete"
+                               asp-route-id="@Model.selectedJob.Id"
+                               asp-controller="Job" id="del"
+                               onclick="showDeleter()"></a>
 
                             <script type="text/javascript">
@@ -67,42 +73,28 @@
                                 }
                             </script>
-            
+
                         </h2>
                         <div class="col-sm-6" style="padding-left:30px">
-                            <p>Description: @Model.selectedJob.Description</p>
-                            <p>Resources: @Model.selectedJob.ResourceNames</p>
-                            <p>Created: @Model.selectedJob.DateCreated</p>
-                            <p>Owned by: @Model.selectedJob.OwnerUsername</p>
+                            <p>Description: @Model.selectedJob.Job.Description</p>
+                            <p>Resources: @Model.selectedJob.Job.ResourceNames</p>
+                            <p>Created: @Model.selectedJob.Job.DateCreated</p>
+                            <p>Owned by: @Model.selectedJob.Job.OwnerUsername</p>
 
                         </div>
                         <div class="col-sm-6" style="padding-left:30px">
-                            <p>Calculating: @Model.selectedJob.CalculatingCount</p>
-                            <p>Finished: @Model.selectedJob.FinishedCount</p>
+                            <p>Calculating: @Model.selectedJob.Job.CalculatingCount</p>
+                            <p>Finished: @Model.selectedJob.Job.FinishedCount</p>
                         </div>
 
                     </div>
                     <div class="row">
-                        <h3 style="padding-left:20px">@Model.lightJobTasks.Count Task@(Model.lightJobTasks != null && Model.lightJobTasks.Count != 1 ? "s" : "" )</h3>
-                        @foreach (var task in Model.lightJobTasks)
+                        <h3 style="padding-left:20px">Tasks</h3>
+                        <script type="text/javascript">
+                            //TODO Globale variabele waar data per categorie in gestoken kan worden 
+                        </script>
+                        @foreach (var task in Model.selectedJob.HiveTasks)
                         {
-                            <table class="table " 
-                                   style="margin-left:20px;">
-                                <thead>
-                                    <tr>
-                                        <th>@task</th>
-                                    </tr>
-                                </thead>
-                                <tbody>
-                                    <tr>
-                                        <td>Last update @task.LastTaskDataUpdate</td>
-                                        <td>State: @task.State</td>
-                                        
-                                    </tr>
-                                    <tr>
-                                        <td>@task.ExecutionTime executed</td>
-                                        <td>Created: @task.DateCreated</td>
-                                    </tr>
-                                </tbody>
-                            </table>
+                            @Html.Partial("SelectedJobPartials/_TaskPartial",
+                           new HeuristicLab.Clients.Hive.WebJobManager.Models.HiveTaskContainer(task))
 
                         }
@@ -111,4 +103,15 @@
             }
         }
+        <script type="text/javascript">
+            function showLoader() {
+                document.getElementById("loader").style.display = "";
+                document.getElementById("content").style.display = "none";
+            }
+            function showDeleter() {
+                document.getElementById("loader").style.display = "";
+                document.getElementById("content").style.display = "none";
+                document.getElementById("spinner").className = "fa fa-trash-o fa-spin fa-5x";
+            }
+        </script>
     </div>
 </div>
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_Algorithm.cshtml
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_Algorithm.cshtml	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_Algorithm.cshtml	(revision 13712)
@@ -1,4 +1,5 @@
 ﻿@model HeuristicLab.Clients.Hive.WebJobManager.ViewModels.FileOpeningViewModel
-
+@{System.Random randomizer = new Random();
+    int randy = randomizer.Next(5000); }
 
 
@@ -8,9 +9,28 @@
     </div>
     <div class="row" style="text-align:left">
-        <h1 data-toggle="tooltip" title=" @Model.SelectedTask.ItemTask.ItemName
-            @Model.SelectedTask.ItemTask.Description ">
+        <h1 data-toggle="tooltip" title="@Model.SelectedTask.ItemTask.ItemName
+            @Model.SelectedTask.ItemTask.Description">
             <span class="label label-primary">Algorithm: @Model.SelectedTask.ItemTask.Name</span>
         </h1>
         <a class="btn btn-success" id="fakehiveadd" onclick="addtoHive()">Add to Hive</a>
+
+        <div class="btn-group">
+            <button 
+                    type="button" 
+                    id="prior@(randy)"
+                    class="btn btn-info dropdown-toggle" 
+                    data-toggle="dropdown" 
+                    aria-haspopup="true" aria-expanded="false">
+                Normal <span class="caret"></span>
+            </button>
+            <ul class="dropdown-menu">
+                <li><a onclick="changePriority([],0,@randy)">Low</a></li>
+                <li><a onclick="changePriority([],1,@randy)">Normal</a></li>
+                <li><a onclick="changePriority([],2,@randy)">Urgent</a></li>
+                <li><a onclick="changePriority([],3,@randy)">Critical</a></li>
+            </ul>
+        </div>
+
+
         <a class="btn btn-success" id="realhiveadd" asp-controller="Job" asp-action="AddToHive" style="display:none"></a>
         <h4 id="result" style="display:none">Start uploading algorithm...</h4>
@@ -24,4 +44,5 @@
         </div>
     </div>
+
     <div class="row">
         <div class="btn-group-justified">
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_AlgorithmSmall.cshtml
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_AlgorithmSmall.cshtml	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_AlgorithmSmall.cshtml	(revision 13712)
@@ -1,18 +1,42 @@
 ﻿@model HeuristicLab.Clients.Hive.WebJobManager.Models.AlgorithmContainer
-@{int randomal = Model.randy.Next(2000); }
+@{int randomal = Model.randy.Next(5000);
+    var builder = "[";
+    foreach (var arr in Model.depth)
+    {
+        builder += "[" + String.Join(",", arr) + "],";
+    }
+    builder += "]";
+}
 <p class="text-center">
-    <a class="btn btn-primary" 
-       data-toggle="collapse" 
-       href="#collapseExample@(randomal)"  
-       aria-expanded="false" 
+    <a class="btn btn-primary"
+       data-toggle="collapse"
+       href="#collapseExample@(randomal)"
+       aria-expanded="false"
        aria-controls="collapseExample@(randomal)">
         @Model.algo.Name
     </a>
+    
+</p>
+<div class="collapse" id="collapseExample@(randomal)" style="margin-left:10px;margin-right:10px;margin-top:-10px">
+    <img src="~/img/accoladealg.png" style="width:100%;" />
+    <div class="panel panel-primary" style="border-width:2px!important">
+        <div class="panel-heading panel-primary text-center">
+            <p>@Model.algo.Description</p>
 
-</p>
-<div class="collapse" id="collapseExample@(randomal)" style="margin-left:10px;margin-right:10px">
-    <div class="panel panel-primary">
-        <div class="panel-heading panel-primary text-center" >
-            <p>@Model.algo.Description</p>
+            <div class="btn-group">
+                <button type="button"
+                        id="prior@(randomal)"
+                        class="btn btn-info dropdown-toggle"
+                        data-toggle="dropdown"
+                        aria-haspopup="true" aria-expanded="false">
+                    Normal <span class="caret"></span>
+                </button>
+                <ul class="dropdown-menu">
+                    <li><a onclick="changePriority(@builder,0,@randomal)">Low</a></li>
+                    <li><a onclick="changePriority(@builder,1,@randomal)">Normal</a></li>
+                    <li><a onclick="changePriority(@builder,2,@randomal)">Urgent</a></li>
+                    <li><a onclick="changePriority(@builder,3,@randomal)">Critical</a></li>
+                </ul>
+            </div>
         </div>
         <table class="table table-responsive card-block" style="table-layout:fixed;overflow-wrap:break-word">
@@ -27,7 +51,7 @@
                 {
                     <tr>
-                        <td >@prob.Name</td>
+                        <td>@prob.Name</td>
 
-                        <td >@prob.ActualValue</td>
+                        <td>@prob.ActualValue</td>
                     </tr>
 
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_BatchRun.cshtml
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_BatchRun.cshtml	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_BatchRun.cshtml	(revision 13712)
@@ -1,5 +1,5 @@
 ﻿@model HeuristicLab.Clients.Hive.WebJobManager.ViewModels.FileOpeningViewModel
 @{System.Random randomizer = new Random();
-    int randy = randomizer.Next(2000); }
+    int randy = randomizer.Next(5000); }
 <div style="margin-left:20px;margin-right:20px">
     <div class="row" style="text-align:center">
@@ -12,4 +12,21 @@
         </h1>
         <a class="btn btn-success" id="fakehiveadd" onclick="addtoHive()">Add to Hive</a>
+
+        <div class="btn-group">
+            <button type="button"
+                    id="prior@(randy)"
+                    class="btn btn-info dropdown-toggle"
+                    data-toggle="dropdown"
+                    aria-haspopup="true" aria-expanded="false">
+                Normal <span class="caret"></span>
+            </button>
+            <ul class="dropdown-menu">
+                <li><a onclick="changePriority([],0,@randy)">Low</a></li>
+                <li><a onclick="changePriority([],1,@randy)">Normal</a></li>
+                <li><a onclick="changePriority([],2,@randy)">Urgent</a></li>
+                <li><a onclick="changePriority([],3,@randy)">Critical</a></li>
+            </ul>
+        </div>
+
         <a class="btn btn-success" id="realhiveadd" asp-controller="Job" asp-action="AddToHive" style="display:none"></a>
         <h4 id="result" style="display:none">Start uploading batch run...</h4>
@@ -25,10 +42,11 @@
     <h4>
         Repeats: @Model.SelectedBatchRun.Repetitions x
-        <label>
-            <input type="checkbox" checked data-toggle="toggle" data-onstyle="warning"
-                   onchange="toggleChild([], @randy)" />
-            Distribute child tasks
-        </label>
+
     </h4>
+    <p class="text-center">
+        <input type="checkbox" checked data-toggle="toggle" data-onstyle="warning"
+               onchange="toggleChild([], @randy)" />
+        Distribute child tasks
+    </p>
     <div id="childs@(randy)">
         @for (var k = 0; k < Model.SelectedBatchRun.Repetitions; k++)
@@ -39,4 +57,6 @@
                 new HeuristicLab.Clients.Hive.WebJobManager.Models.AlgorithmContainer(
                     ((HeuristicLab.Optimization.IAlgorithm)Model.SelectedBatchRun.Optimizer),
+                    new List<int[]>(),
+                    new int[] { 0, k },
                     randomizer));
 
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_BatchRunSmall.cshtml
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_BatchRunSmall.cshtml	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_BatchRunSmall.cshtml	(revision 13712)
@@ -1,5 +1,14 @@
 ﻿@model HeuristicLab.Clients.Hive.WebJobManager.Models.BatchRunContainer
 @{
-    int randombr = Model.randy.Next(2000); }
+    int randombr = Model.randy.Next(5000);
+    var builder = "[";
+    foreach (var arr in Model.depth)
+    {
+        builder += "[" + String.Join(",", arr) + "],";
+    }
+    builder += "]";
+}
+
+
 <p class="text-center">
     <a class="btn btn-warning"
@@ -12,24 +21,35 @@
 
 </p>
-<div class="collapse" id="collapseExample@(randombr)" style="margin-left:10px;margin-right:10px">
-    <div class="panel panel-warning">
-        <div class="panel-heading panel-warning text-center">
-            <p>
+<div class="collapse" 
+     id="collapseExample@(randombr)" style="margin-left:10px;margin-right:10px;margin-top:-10px ">
+    <img src="~/img/accoladebatch.png" style="width:100%" />
+    <div class="panel panel-warning" style="border-color:#f6cd94!important; border-width:2px!important">
+        <div class="panel-heading  text-center">
+            <p class="panel-title">
                 Repeats @Model.batch.Repetitions X
             </p>
             <p>
-                <label>
-                    @{ var builder = "[";
-                        foreach (var arr in Model.depth)
-                        {
-                            builder += "[" + String.Join(",", arr) + "],";
-                        }
-                        builder += "]";
-                    }
-                    <input type="checkbox" checked data-toggle="toggle" data-onstyle="warning"
-                           onchange="toggleChild(@builder, @randombr)" />
-                    Distribute child tasks
-                </label>
+
+
+                <input type="checkbox" checked data-toggle="toggle" data-onstyle="warning"
+                       onchange="toggleChild(@builder, @randombr)" />
+                Distribute child tasks
+
             </p>
+            <div class="btn-group">
+                <button type="button"
+                        id="prior@(randombr)"
+                        class="btn btn-info dropdown-toggle"
+                        data-toggle="dropdown"
+                        aria-haspopup="true" aria-expanded="false">
+                    Normal <span class="caret"></span>
+                </button>
+                <ul class="dropdown-menu">
+                    <li><a onclick="changePriority(@builder,0,@randombr)">Low</a></li>
+                    <li><a onclick="changePriority(@builder,1,@randombr)">Normal</a></li>
+                    <li><a onclick="changePriority(@builder,2,@randombr)">Urgent</a></li>
+                    <li><a onclick="changePriority(@builder,3,@randombr)">Critical</a></li>
+                </ul>
+            </div>
         </div>
         <div id="childs@(randombr)">
@@ -41,4 +61,6 @@
                     new HeuristicLab.Clients.Hive.WebJobManager.Models.AlgorithmContainer(
                         ((HeuristicLab.Optimization.IAlgorithm)Model.batch.Optimizer),
+                        Model.depth.ToList(),
+                        new int[] { 0, k },
                         Model.randy))
 
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_Experiment.cshtml
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_Experiment.cshtml	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_Experiment.cshtml	(revision 13712)
@@ -1,4 +1,5 @@
 ﻿@model HeuristicLab.Clients.Hive.WebJobManager.ViewModels.FileOpeningViewModel
-@{System.Random randomizer = new Random(); }
+@{System.Random randomizer = new Random();
+    int randy = randomizer.Next(5000); }
 <div style="margin-left:20px;margin-right:20px">
     <div class="row" style="text-align:center">
@@ -11,4 +12,21 @@
         </h1>
         <a class="btn btn-success" id="fakehiveadd" onclick="addtoHive()">Add to Hive</a>
+
+
+        <div class="btn-group">
+            <button type="button"
+                    id="prior@(randy)"
+                    class="btn btn-info dropdown-toggle"
+                    data-toggle="dropdown"
+                    aria-haspopup="true" aria-expanded="false">
+                Normal <span class="caret"></span>
+            </button>
+            <ul class="dropdown-menu">
+                <li><a onclick="changePriority([],0,@randy)">Low</a></li>
+                <li><a onclick="changePriority([],1,@randy)">Normal</a></li>
+                <li><a onclick="changePriority([],2,@randy)">Urgent</a></li>
+                <li><a onclick="changePriority([],3,@randy)">Critical</a></li>
+            </ul>
+        </div>
         <a class="btn btn-success" id="realhiveadd" asp-controller="Job" asp-action="AddToHive" style="display:none"></a>
         <h4 id="result" style="display:none">Start uploading experiment...</h4>
@@ -25,37 +43,45 @@
         Children: @Model.SelectedExperiment.Optimizers.Count
     </h4>
-    @for (var i = 0; i < Model.SelectedExperiment.Optimizers.Count; i++)
-    {
-        @if (Model.SelectedExperiment.Optimizers[i] is HeuristicLab.Optimization.IAlgorithm)
+    <p class="text-center">
+        <input type="checkbox" checked data-toggle="toggle" data-onstyle="danger"
+               onchange="toggleChild([], @randy)" />
+        Distribute child tasks
+    </p>
+    <div id="childs@(randy)">
+        @for (var i = 0; i < Model.SelectedExperiment.Optimizers.Count; i++)
         {
-            @Html.Partial("OpenFilePartials/_AlgorithmSmall",
-new HeuristicLab.Clients.Hive.WebJobManager.Models.AlgorithmContainer(
- ((HeuristicLab.Optimization.IAlgorithm)Model.SelectedExperiment.Optimizers[i]),
- randomizer));
+            @if (Model.SelectedExperiment.Optimizers[i] is HeuristicLab.Optimization.IAlgorithm)
+            {
+                @Html.Partial("OpenFilePartials/_AlgorithmSmall",
+                    new HeuristicLab.Clients.Hive.WebJobManager.Models.AlgorithmContainer(
+                    ((HeuristicLab.Optimization.IAlgorithm)Model.SelectedExperiment.Optimizers[i]),
+                    new List<int[]>(),
+                    new int[] { i, 0 },
+                    randomizer));
+
+            }
+            else if (Model.SelectedExperiment.Optimizers[i] is HeuristicLab.Optimization.BatchRun)
+            {
+                @Html.Partial("OpenFilePartials/_BatchRunSmall",
+                    new HeuristicLab.Clients.Hive.WebJobManager.Models.BatchRunContainer(
+                    ((HeuristicLab.Optimization.BatchRun)Model.SelectedExperiment.Optimizers[i]),
+                    new List<int[]>(),
+                    new int[] { i, 0 },
+                    randomizer)) ;
+
+            }
+            else if (Model.SelectedExperiment.Optimizers[i] is HeuristicLab.Optimization.Experiment)
+            {
+                @Html.Partial("OpenFilePartials/_ExperimentSmall",
+                    new HeuristicLab.Clients.Hive.WebJobManager.Models.ExperimentContainer(
+                    ((HeuristicLab.Optimization.Experiment)Model.SelectedExperiment.Optimizers[i]),
+                    new List<int[]>(),
+                    new int[] { i, 0 },
+                    randomizer)) ;
+
+            }
 
         }
-        else if (Model.SelectedExperiment.Optimizers[i] is HeuristicLab.Optimization.BatchRun)
-        {
-            @Html.Partial("OpenFilePartials/_BatchRunSmall",
-new HeuristicLab.Clients.Hive.WebJobManager.Models.BatchRunContainer(
-    ((HeuristicLab.Optimization.BatchRun)Model.SelectedExperiment.Optimizers[i]),
-    new List<int[]>(),
-    new int[] { i, 0 },
-    randomizer)) ;
-
-        }
-        else if (Model.SelectedExperiment.Optimizers[i] is HeuristicLab.Optimization.Experiment)
-        {
-            @Html.Partial("OpenFilePartials/_ExperimentSmall",
-new HeuristicLab.Clients.Hive.WebJobManager.Models.ExperimentContainer(
-    ((HeuristicLab.Optimization.Experiment)Model.SelectedExperiment.Optimizers[i]),
-    new List<int[]>(),
-    new int[] { i, 0 },
-           randomizer)) ;
-
-        }
-
-    }
-
+    </div>
     <script type="text/javascript">
 
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_ExperimentSmall.cshtml
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_ExperimentSmall.cshtml	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/OpenFilePartials/_ExperimentSmall.cshtml	(revision 13712)
@@ -1,32 +1,66 @@
 ﻿@model HeuristicLab.Clients.Hive.WebJobManager.Models.ExperimentContainer
-@{int randombr = Model.randy.Next(2000); }
+@{int randomex = Model.randy.Next(5000);
+    var builder = "[";
+    foreach (var arr in Model.depth)
+    {
+        builder += "[" + String.Join(",", arr) + "],";
+    }
+    builder += "]";
+}
 <p class="text-center">
     <a class="btn btn-danger"
        data-toggle="collapse"
-       href="#collapseExample@(randombr)"
+       href="#collapseExample@(randomex)"
        aria-expanded="false"
-       aria-controls="collapseExample@(randombr)">
+       aria-controls="collapseExample@(randomex)">
         @Model.exp.Name
     </a>
 
 </p>
-<div class="collapse" id="collapseExample@(randombr)" style="margin-left:10px;margin-right:10px">
-    <div class="panel panel-danger">
+<div class="collapse" id="collapseExample@(randomex)" style="margin-left:10px;margin-right:10px;margin-top:-10px">
+    <img src="~/img/accoladeexp.png" style="width:100%" />
+    <div class="panel panel-danger" style="border-color:#c12e2a!important; border-width:2px!important">
         <div class="panel-heading panel-danger text-center">
-            <p>Children: @Model.exp.Optimizers.Count</p>
+            <p class="panel-title">Children: @Model.exp.Optimizers.Count</p>
+            <p>
+                <label>
+
+                    <input type="checkbox" checked data-toggle="toggle" data-onstyle="danger"
+                           onchange="toggleChild(@builder, @randomex)" />
+                    Distribute child tasks
+                </label>
+            </p>
+            <div class="btn-group">
+                <button type="button"
+                        id="prior@(randomex)"
+                        class="btn btn-info dropdown-toggle"
+                        data-toggle="dropdown"
+                        aria-haspopup="true" aria-expanded="false">
+                    Normal <span class="caret"></span>
+                </button>
+                <ul class="dropdown-menu">
+                    <li><a onclick="changePriority(@builder,0,@randomex)">Low</a></li>
+                    <li><a onclick="changePriority(@builder,1,@randomex)">Normal</a></li>
+                    <li><a onclick="changePriority(@builder,2,@randomex)">Urgent</a></li>
+                    <li><a onclick="changePriority(@builder,3,@randomex)">Critical</a></li>
+                </ul>
+            </div>
         </div>
-        @for (var j = 0; j < Model.exp.Optimizers.Count; j++)
-        {
-            @if (Model.exp.Optimizers[j] is HeuristicLab.Optimization.IAlgorithm)
+        <div id="childs@(randomex)">
+            @for (var j = 0; j < Model.exp.Optimizers.Count; j++)
             {
-                @Html.Partial("OpenFilePartials/_AlgorithmSmall",
+                @if (Model.exp.Optimizers[j] is HeuristicLab.Optimization.IAlgorithm)
+                {
+                    @Html.Partial("OpenFilePartials/_AlgorithmSmall",
                     new HeuristicLab.Clients.Hive.WebJobManager.Models.AlgorithmContainer(
-                 ((HeuristicLab.Optimization.IAlgorithm)Model.exp.Optimizers[j]),
-                 Model.randy))
+                        ((HeuristicLab.Optimization.IAlgorithm)Model.exp.Optimizers[j]),
+                         Model.depth.ToList(),
+                        new int[] { j, 0 },
+                        Model.randy))
 
-            }
-            else if (Model.exp.Optimizers[j] is HeuristicLab.Optimization.BatchRun)
-            {
-                @Html.Partial("OpenFilePartials/_BatchRunSmall",
+                }
+                else if (Model.exp.Optimizers[j] is HeuristicLab.Optimization.BatchRun)
+                {
+                    @Html.Partial("OpenFilePartials/_BatchRunSmall",
                 new HeuristicLab.Clients.Hive.WebJobManager.Models.BatchRunContainer(
                     ((HeuristicLab.Optimization.BatchRun)Model.exp.Optimizers[j]),
@@ -35,8 +69,8 @@
                     Model.randy)) ;
 
-            }
-            else if (Model.exp.Optimizers[j] is HeuristicLab.Optimization.Experiment)
-            {
-                @Html.Partial("OpenFilePartials/_ExperimentSmall",
+                }
+                else if (Model.exp.Optimizers[j] is HeuristicLab.Optimization.Experiment)
+                {
+                    @Html.Partial("OpenFilePartials/_ExperimentSmall",
                 new HeuristicLab.Clients.Hive.WebJobManager.Models.ExperimentContainer(
                     ((HeuristicLab.Optimization.Experiment)Model.exp.Optimizers[j]),
@@ -45,6 +79,7 @@
                     Model.randy)) ;
 
+                }
             }
-        }
+        </div>
     </div>
 </div>
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/SelectedJobPartials/_AlgTask.cshtml
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/SelectedJobPartials/_AlgTask.cshtml	(revision 13712)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/SelectedJobPartials/_AlgTask.cshtml	(revision 13712)
@@ -0,0 +1,113 @@
+﻿@model HeuristicLab.Clients.Hive.WebJobManager.Models.HiveTaskContainer
+@using Newtonsoft.Json;
+<div class="panel panel-primary" style="border-width:2px!important">
+    <div class="panel-heading" 
+         data-toggle="collapse"
+         data-target="#panbody@(Model.hiveTask.Task.Id)"
+         onclick="redrawalg('@(Model.hiveTask.Task.Id)')"
+       aria-expanded="false"
+       aria-controls="panbody@(Model.hiveTask.Task.Id)">
+        <table class="table ">
+            <thead>
+                <tr>
+                    <th>Algorithm: @Model.hiveTask.ItemTask.Name</th>
+                    <th style="font-size:large">
+                        @if (Model.hiveTask.Task.Priority == 0)
+                        {
+                            <span class="label label-default"> Priority low</span>
+                        }
+                        else if (Model.hiveTask.Task.Priority == 1)
+                        {
+                            <span class="label label-info">Priority normal</span>
+                        }
+                        else if (Model.hiveTask.Task.Priority == 2)
+                        {
+                            <span class="label label-warning">Priority urgent</span>
+
+                        }
+                        else if (Model.hiveTask.Task.Priority == 3)
+                        {
+                            <span class="label label-danger">Priority critical</span>
+
+                        }
+                    </th>
+                </tr>
+            </thead>
+            <tbody>
+                <tr>
+                    <td>Last update @Model.hiveTask.Task.LastTaskDataUpdate </td>
+                    <td>State: @Model.hiveTask.Task.State</td>
+
+                </tr>
+                <tr>
+                    <td>@Model.hiveTask.Task.ExecutionTime executed</td>
+                    <td>Created: @Model.hiveTask.Task.DateCreated</td>
+                </tr>
+                <tr>
+                    <td>Statelogs: @Model.hiveTask.Task.StateLog.Count</td>
+                </tr>
+            </tbody>
+        </table>
+    </div>
+    <div class="panel-body ">
+        <div class="collapse" id="panbody@(Model.hiveTask.Task.Id)">
+            <h4>From @Model.hiveTask.Task.StateLog.First().DateTime <br />to @Model.hiveTask.Task.StateLog.Last().DateTime  </h4>
+            <div id="graph@(Model.hiveTask.Task.Id)"></div>
+        </div>
+    </div>
+    <script type="text/javascript">
+        var temp = @Html.Raw(JsonConvert.SerializeObject(Model.hiveTask.Task.StateLog));
+        var xarr = [];
+        var yarr = [];
+        var waiting = 0;
+        var transfer = 0;
+        var calc = 0;
+        for(var v = 0; v < temp.length; v++){
+            xarr.push(temp[v].DateTime.substr(11,8));
+            if(temp[v].State == 1){
+                yarr.push("Waiting");
+                if(v < (temp.length -1))
+                    waiting += Date.parse(temp[v+1].DateTime) - Date.parse(temp[v].DateTime);
+            }
+            else if(temp[v].State == 2){
+                yarr.push("Transferring");
+                if(v < (temp.length -1))
+                    transfer += Date.parse(temp[v+1].DateTime) - Date.parse(temp[v].DateTime);
+            }
+            else if(temp[v].State == 3){
+                yarr.push("Calculating");
+                if(v < (temp.length -1))
+                    calc += Date.parse(temp[v+1].DateTime) - Date.parse(temp[v].DateTime);
+            }
+
+            else if(temp[v].State == 5)
+                yarr.push("Finished");
+            else if(temp[v].State == 7)
+                yarr.push("Failed");
+        }
+
+        var data = [{
+            x: xarr,
+            y: yarr,
+            type:'scatter'
+        }];
+        var dats = [{
+            values:[waiting/1000/60,transfer/1000/60,calc/1000/60],
+            labels: ['Minutes waiting', 'Minutes transferring', 'Minutes calculating'],
+            type:'pie'
+        }];
+        console.log(dats);
+        document.getElementById("graph@(Model.hiveTask.Task.Id)").style = "width: 90%; height: 450px;";
+
+        Plotly.newPlot('graph@(Model.hiveTask.Task.Id)', dats);
+
+        function redrawalg(val){
+            setTimeout(function(){
+                Plotly.redraw('graph' + val);
+            }, 100);
+            
+
+        }
+
+    </script>
+</div>
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/SelectedJobPartials/_BatchTask.cshtml
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/SelectedJobPartials/_BatchTask.cshtml	(revision 13712)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/SelectedJobPartials/_BatchTask.cshtml	(revision 13712)
@@ -0,0 +1,114 @@
+﻿@model HeuristicLab.Clients.Hive.WebJobManager.Models.HiveTaskContainer
+@using Newtonsoft.Json;
+<div class="panel panel-warning" style="border-color:#f6cd94!important; border-width:2px!important">
+    <div class="panel-heading"
+         data-toggle="collapse"
+         data-target="#panbody@(Model.hiveTask.Task.Id)"
+         onclick="redrawbat('@(Model.hiveTask.Task.Id)')"
+       aria-expanded="false"
+       aria-controls="panbody@(Model.hiveTask.Task.Id)">
+        <table class="table ">
+            <thead>
+                <tr>
+                    <th>Batch run: @Model.hiveTask.ItemTask.Name</th>
+                    <th style="font-size:large">
+                        @if (Model.hiveTask.Task.Priority == 0)
+                        {
+                            <span class="label label-default"> Priority low</span>
+                        }
+                        else if (Model.hiveTask.Task.Priority == 1)
+                        {
+                            <span class="label label-info">Priority normal</span>
+                        }
+                        else if (Model.hiveTask.Task.Priority == 2)
+                        {
+                            <span class="label label-warning">Priority urgent</span>
+
+                        }
+                        else if (Model.hiveTask.Task.Priority == 3)
+                        {
+                            <span class="label label-danger">Priority critical</span>
+
+                        }
+                    </th>
+
+                </tr>
+            </thead>
+            <tbody>
+                <tr>
+                    <td>Last update @Model.hiveTask.Task.LastTaskDataUpdate </td>
+                    <td>State: @Model.hiveTask.Task.State</td>
+
+                </tr>
+                <tr>
+                    <td>@Model.hiveTask.Task.ExecutionTime executed</td>
+                    <td>Created: @Model.hiveTask.Task.DateCreated</td>
+                </tr>
+                <tr>
+                    <td>
+                        Child task distribution
+                        <input type="checkbox"
+                               disabled
+                               @(Model.hiveTask.ItemTask.ComputeInParallel ? "checked" : "" )
+                               data-toggle="toggle"
+                               data-onstyle="success" />
+                    </td>
+                    <td>Statelogs: @Model.hiveTask.Task.StateLog.Count</td>
+                </tr>
+            </tbody>
+        </table>
+    </div>
+    <div class="panel-body ">
+        <div class="collapse" id="panbody@(Model.hiveTask.Task.Id)">
+            <h4>From @Model.hiveTask.Task.StateLog.First().DateTime <br />to @Model.hiveTask.Task.StateLog.Last().DateTime  </h4>
+            <div id="graph@(Model.hiveTask.Task.Id)"></div>
+        </div>
+    </div>
+    @if (Model.hiveTask.ChildHiveTasks.Count > 0)
+    {
+        <div class="panel-body">
+            @foreach (var task in Model.hiveTask.ChildHiveTasks)
+            {
+                @Html.Partial("SelectedJobPartials/_TaskPartial",
+                        new HeuristicLab.Clients.Hive.WebJobManager.Models.HiveTaskContainer(task))
+
+            }
+        </div>
+    }
+    <script type="text/javascript">
+        var temp = @Html.Raw(JsonConvert.SerializeObject(Model.hiveTask.Task.StateLog));
+        var xarr = [];
+        var yarr = [];
+        for(var v = 0; v < temp.length; v++){
+            xarr.push(temp[v].DateTime.substr(11,8));
+            if(temp[v].State == 1)
+                yarr.push("Waiting");
+            else if(temp[v].State == 2)
+                yarr.push("Transferring");
+            else if(temp[v].State == 3)
+                yarr.push("Calculating");
+            else if(temp[v].State == 5)
+                yarr.push("Finished");
+            else if(temp[v].State == 7)
+                yarr.push("Failed");
+        }
+
+        var data = [{
+            x: xarr,
+            y: yarr,
+            type:'scatter'
+        }];
+        document.getElementById("graph@(Model.hiveTask.Task.Id)").style = "width: 90%; height: 450px;";
+
+        Plotly.newPlot('graph@(Model.hiveTask.Task.Id)', data);
+
+        function redrawbat(val){
+            setTimeout(function(){
+                Plotly.newPlot('graph' + val,data);
+            }, 100);
+            
+
+        }
+
+    </script>
+</div>
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/SelectedJobPartials/_ExpTask.cshtml
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/SelectedJobPartials/_ExpTask.cshtml	(revision 13712)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/SelectedJobPartials/_ExpTask.cshtml	(revision 13712)
@@ -0,0 +1,119 @@
+﻿@model HeuristicLab.Clients.Hive.WebJobManager.Models.HiveTaskContainer
+@using Newtonsoft.Json;
+
+<div class="panel panel-danger" style="border-color:#c12e2a!important; border-width:2px!important">
+    <div class="panel-heading"
+         data-toggle="collapse"
+         data-target="#panbody@(Model.hiveTask.Task.Id)"
+         onclick="redrawexp('@(Model.hiveTask.Task.Id)')"
+       aria-expanded="false"
+       aria-controls="panbody@(Model.hiveTask.Task.Id)">
+        <table class="table ">
+            <thead>
+                <tr>
+                    <th>Experiment: @Model.hiveTask.ItemTask.Name</th>
+                    <th style="font-size:large">
+                        @if (Model.hiveTask.Task.Priority == 0)
+                        {
+                            <span class="label label-default"> Priority low</span>
+                        }
+                        else if (Model.hiveTask.Task.Priority == 1)
+                        {
+                            <span class="label label-info">Priority normal</span>
+                        }
+                        else if (Model.hiveTask.Task.Priority == 2)
+                        {
+                            <span class="label label-warning">Priority urgent</span>
+
+                        }
+                        else if (Model.hiveTask.Task.Priority == 3)
+                        {
+                            <span class="label label-danger">Priority critical</span>
+
+                        }
+                    </th>
+
+                </tr>
+            </thead>
+            <tbody>
+                <tr>
+                    <td id="lastupdate@(Model.hiveTask.Task.Id)">
+                        Last update @Model.hiveTask.Task.LastTaskDataUpdate
+                    </td>
+                    <td id="state@(Model.hiveTask.Task.Id)">State: @Model.hiveTask.Task.State</td>
+
+                </tr>
+                <tr>
+                    <td id="exectime@(Model.hiveTask.Task.Id)">
+                        @Model.hiveTask.Task.ExecutionTime executed
+                    </td>
+                    <td>Created: @Model.hiveTask.Task.DateCreated</td>
+                </tr>
+                <tr>
+                    <td>
+                        Child task distribution
+                        <input type="checkbox"
+                               disabled
+                               @(Model.hiveTask.ItemTask.ComputeInParallel ? "checked" : "" )
+                               data-toggle="toggle"
+                               data-onstyle="success" />
+                    </td>
+                    <td>Statelogs: @Model.hiveTask.Task.StateLog.Count</td>
+                </tr>
+            </tbody>
+        </table>
+    </div>
+    <div class="panel-body ">
+        <div class="collapse" id="panbody@(Model.hiveTask.Task.Id)">
+            <h4>From @Model.hiveTask.Task.StateLog.First().DateTime <br />to @Model.hiveTask.Task.StateLog.Last().DateTime  </h4>
+            <div id="graph@(Model.hiveTask.Task.Id)"></div>
+        </div>
+    </div>
+    @if (Model.hiveTask.ChildHiveTasks.Count > 0)
+    {
+        <div class="panel-body ">
+            @foreach (var task in Model.hiveTask.ChildHiveTasks)
+            {
+                @Html.Partial("SelectedJobPartials/_TaskPartial",
+                    new HeuristicLab.Clients.Hive.WebJobManager.Models.HiveTaskContainer(task))
+
+            }
+        </div>
+    }
+    <script type="text/javascript">
+        var temp = @Html.Raw(JsonConvert.SerializeObject(Model.hiveTask.Task.StateLog));
+        var xarr = [];
+        var yarr = [];
+        for(var v = 0; v < temp.length; v++){
+            xarr.push(temp[v].DateTime.substr(11,8));
+            if(temp[v].State == 1)
+                yarr.push("Waiting");
+            else if(temp[v].State == 2)
+                yarr.push("Transferring");
+            else if(temp[v].State == 3)
+                yarr.push("Calculating");
+            else if(temp[v].State == 5)
+                yarr.push("Finished");
+            else if(temp[v].State == 7)
+                yarr.push("Failed");
+        }
+
+        var data = [{
+            x: xarr,
+            y: yarr,
+            type:'scatter'
+        }];
+        document.getElementById("graph@(Model.hiveTask.Task.Id)").style = "width: 90%; height: 450px;";
+
+        Plotly.newPlot('graph@(Model.hiveTask.Task.Id)', data);
+
+        function redrawexp(val){
+            setTimeout(function(){
+                Plotly.newPlot('graph' + val,data);
+            }, 100);
+            
+
+        }
+
+    </script>
+</div>
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/SelectedJobPartials/_TaskPartial.cshtml
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/SelectedJobPartials/_TaskPartial.cshtml	(revision 13712)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Job/SelectedJobPartials/_TaskPartial.cshtml	(revision 13712)
@@ -0,0 +1,21 @@
+﻿@model HeuristicLab.Clients.Hive.WebJobManager.Models.HiveTaskContainer
+
+        
+
+        @if (Model.hiveTask.ItemTask.Item is HeuristicLab.Optimization.IAlgorithm)
+        {
+            @Html.Partial("SelectedJobPartials/_AlgTask", Model)
+
+        }
+        else if (Model.hiveTask.ItemTask.Item is HeuristicLab.Optimization.Experiment)
+        {
+            @Html.Partial("SelectedJobPartials/_ExpTask", Model)
+
+        }
+        else if (Model.hiveTask.ItemTask.Item is HeuristicLab.Optimization.BatchRun)
+        {
+
+            @Html.Partial("SelectedJobPartials/_BatchTask", Model)
+        }
+
+        
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Shared/_Layout.cshtml
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Shared/_Layout.cshtml	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/Views/Shared/_Layout.cshtml	(revision 13712)
@@ -31,4 +31,5 @@
         <script src="~/js/npm.js"></script>
         <script src="~/js/raphael.js"></script>
+        <script src="~/js/plotly.js"></script>
         @RenderBody()
     </div>
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/css/StyleSheet.css
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/css/StyleSheet.css	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/css/StyleSheet.css	(revision 13712)
@@ -38,2 +38,10 @@
     text-align: center;
 }
+.panel-warning > .panel-heading{
+    background-image: linear-gradient(to bottom,#eb9114 0,#f1b25b 100%)!important;
+    color:white!important;
+}
+.panel-danger > .panel-heading{
+    background-image: linear-gradient(to bottom,#c12e2a 0,#d9534f 100%)!important;
+    color:white!important;
+}
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/js/Scripts/hubber.js
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/js/Scripts/hubber.js	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/js/Scripts/hubber.js	(revision 13712)
@@ -31,5 +31,5 @@
 
     var jobname = prompt("Please enter a job name", "Job");
-    if (jobname != "") {
+    if (jobname && jobname != "" && jobname != null) {
         hubber.server.changeName(jobname);
         document.getElementById("fakehiveadd").style.display = "none";
@@ -40,5 +40,5 @@
 }
 function toggleChild(arr, idchilds) {
-    console.log(arr);
+    console.log(arr + " toggled");
     hubber.server.toggleChild(arr);
     if ($("#childs" + idchilds).css("display") == "none")
@@ -47,2 +47,29 @@
         $("#childs" + idchilds).css("display", "none");
 }
+function changePriority(arr, prior, idprior) {
+    console.log(arr + " to priority " + prior);
+    hubber.server.changePriority(arr, prior);
+    resetPrior(idprior);
+    switch (prior) {
+        case 0:
+            document.getElementById("prior" + idprior).className += "btn-default";
+            document.getElementById("prior" + idprior).innerHTML = "Low"
+            break;
+        case 1:
+            document.getElementById("prior" + idprior).className += "btn-info";
+            document.getElementById("prior" + idprior).innerHTML = "Normal"
+            break;
+        case 2:
+            document.getElementById("prior" + idprior).className += "btn-warning";
+            document.getElementById("prior" + idprior).innerHTML = "Urgent"
+            break;
+        case 3:
+            document.getElementById("prior" + idprior).className += "btn-danger";
+            document.getElementById("prior" + idprior).innerHTML = "Critical";
+            break;
+    }
+    document.getElementById("prior" + idprior).innerHTML += "<span class='caret'></span>";
+}
+function resetPrior(id) {
+    document.getElementById("prior" + id).className = "btn dropdown-toggle ";
+}
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/js/plotly.js
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/js/plotly.js	(revision 13712)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/js/plotly.js	(revision 13712)
@@ -0,0 +1,89924 @@
+/**
+* plotly.js v1.6.3
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+* Licensed under the MIT license
+*/
+(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Plotly = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
+'use strict';
+
+var Plotly = require('../src/plotly');
+var rules = {
+    "X,X div": "font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;",
+    "X input,X button": "font-family:'Open Sans', verdana, arial, sans-serif;",
+    "X input:focus,X button:focus": "outline:none;",
+    "X a": "text-decoration:none;",
+    "X a:hover": "text-decoration:none;",
+    "X .crisp": "shape-rendering:crispEdges;",
+    "X svg": "overflow:hidden;",
+    "X svg a": "fill:#447adb;",
+    "X svg a:hover": "fill:#3c6dc5;",
+    "X .main-svg": "position:absolute;top:0;left:0;pointer-events:none;",
+    "X .main-svg .draglayer": "pointer-events:all;",
+    "X .cursor-pointer": "cursor:pointer;",
+    "X .cursor-crosshair": "cursor:crosshair;",
+    "X .cursor-move": "cursor:move;",
+    "X .cursor-col-resize": "cursor:col-resize;",
+    "X .cursor-row-resize": "cursor:row-resize;",
+    "X .cursor-ns-resize": "cursor:ns-resize;",
+    "X .cursor-ew-resize": "cursor:ew-resize;",
+    "X .cursor-sw-resize": "cursor:sw-resize;",
+    "X .cursor-s-resize": "cursor:s-resize;",
+    "X .cursor-se-resize": "cursor:se-resize;",
+    "X .cursor-w-resize": "cursor:w-resize;",
+    "X .cursor-e-resize": "cursor:e-resize;",
+    "X .cursor-nw-resize": "cursor:nw-resize;",
+    "X .cursor-n-resize": "cursor:n-resize;",
+    "X .cursor-ne-resize": "cursor:ne-resize;",
+    "X .modebar": "position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);",
+    "X .modebar--hover": "opacity:0;-webkit-transition:opacity 0.3s ease 0s;-moz-transition:opacity 0.3s ease 0s;-ms-transition:opacity 0.3s ease 0s;-o-transition:opacity 0.3s ease 0s;transition:opacity 0.3s ease 0s;",
+    "X:hover .modebar--hover": "opacity:1;",
+    "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;",
+    "X .modebar-group:first-child": "margin-left:0px;",
+    "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;",
+    "X .modebar-btn svg": "position:relative;top:2px;",
+    "X .modebar-btn path": "fill:rgba(0,31,95,0.3);",
+    "X .modebar-btn.active path,X .modebar-btn:hover path": "fill:rgba(0,22,72,0.5);",
+    "X .modebar-btn.modebar-btn--logo": "padding:3px 1px;",
+    "X .modebar-btn.modebar-btn--logo path": "fill:#447adb !important;",
+    "X [data-title]:before,X [data-title]:after": "position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;",
+    "X [data-title]:hover:before,X [data-title]:hover:after": "display:block;opacity:1;",
+    "X [data-title]:before": "content:'';position:absolute;background:transparent;border:6px solid transparent;z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;",
+    "X [data-title]:after": "content:attr(data-title);background:#69738a;color:white;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;",
+    "X .select-outline": "fill:none;stroke-width:1;shape-rendering:crispEdges;",
+    "X .select-outline-1": "stroke:white;",
+    "X .select-outline-2": "stroke:black;stroke-dasharray:2px 2px;",
+    Y: "font-family:'Open Sans';position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;",
+    "Y p": "margin:0;",
+    "Y .notifier-note": "min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,0.9);color:#fff;padding:10px;",
+    "Y .notifier-close": "color:#fff;opacity:0.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;",
+    "Y .notifier-close:hover": "color:#444;text-decoration:none;cursor:pointer;"
+};
+
+for(var selector in rules) {
+    var fullSelector = selector.replace(/^,/,' ,')
+        .replace(/X/g, '.js-plotly-plot .plotly')
+        .replace(/Y/g, '.plotly-notifier');
+    Plotly.Lib.addStyleRule(fullSelector, rules[selector]);
+}
+
+},{"../src/plotly":366}],2:[function(require,module,exports){
+'use strict';
+
+module.exports = {
+    'undo': {
+        'width': 857.1,
+        'path': 'm857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'home': {
+        'width': 928.6,
+        'path': 'm786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'camera-retro': {
+        'width': 1000,
+        'path': 'm518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'zoombox': {
+        'width': 1000,
+        'path': 'm1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'pan': {
+        'width': 1000,
+        'path': 'm1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'zoom_plus': {
+        'width': 1000,
+        'path': 'm1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'zoom_minus': {
+        'width': 1000,
+        'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'autoscale': {
+        'width': 1000,
+        'path': 'm250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'tooltip_basic': {
+        'width': 1500,
+        'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'tooltip_compare': {
+        'width': 1125,
+        'path': 'm187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'plotlylogo': {
+        'width': 1542,
+        'path': 'm0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'z-axis': {
+        'width': 1000,
+        'path': 'm833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z',
+        'ascent': 850,
+        'descent': -150
+    },
+    '3d_rotate': {
+        'width': 1000,
+        'path': 'm922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'camera': {
+        'width': 1000,
+        'path': 'm500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'movie': {
+        'width': 1000,
+        'path': 'm938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'question': {
+        'width': 857.1,
+        'path': 'm500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'disk': {
+        'width': 857.1,
+        'path': 'm214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'lasso': {
+        'width': 1031,
+        'path': 'm1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z',
+        'ascent': 850,
+        'descent': -150
+    },
+    'selectbox': {
+        'width': 1000,
+        'path': 'm0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z',
+        'ascent': 850,
+        'descent': -150
+    }
+};
+
+},{}],3:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/bar');
+
+},{"../src/traces/bar":429}],4:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/box');
+
+},{"../src/traces/box":440}],5:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/choropleth');
+
+},{"../src/traces/choropleth":448}],6:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/contour');
+
+},{"../src/traces/contour":455}],7:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/core');
+
+},{"../src/core":339}],8:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/heatmap');
+
+},{"../src/traces/heatmap":466}],9:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/histogram');
+
+},{"../src/traces/histogram":477}],10:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/histogram2d');
+
+},{"../src/traces/histogram2d":482}],11:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/histogram2dcontour');
+
+},{"../src/traces/histogram2dcontour":486}],12:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+/*
+ * This file is browserify'ed into a standalone 'Plotly' object.
+ */
+
+var Core = require('./core');
+
+// Load all trace modules
+Core.register([
+    require('./bar'),
+    require('./box'),
+    require('./heatmap'),
+    require('./histogram'),
+    require('./histogram2d'),
+    require('./histogram2dcontour'),
+    require('./pie'),
+    require('./contour'),
+    require('./scatter3d'),
+    require('./surface'),
+    require('./mesh3d'),
+    require('./scattergeo'),
+    require('./choropleth'),
+    require('./scattergl')
+]);
+
+module.exports = Core;
+
+},{"./bar":3,"./box":4,"./choropleth":5,"./contour":6,"./core":7,"./heatmap":8,"./histogram":9,"./histogram2d":10,"./histogram2dcontour":11,"./mesh3d":13,"./pie":14,"./scatter3d":15,"./scattergeo":16,"./scattergl":17,"./surface":18}],13:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/mesh3d');
+
+},{"../src/traces/mesh3d":490}],14:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/pie');
+
+},{"../src/traces/pie":495}],15:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/scatter3d');
+
+},{"../src/traces/scatter3d":528}],16:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/scattergeo');
+
+},{"../src/traces/scattergeo":532}],17:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/scattergl');
+
+},{"../src/traces/scattergl":537}],18:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+module.exports = require('../src/traces/surface');
+
+},{"../src/traces/surface":542}],19:[function(require,module,exports){
+'use strict'
+
+module.exports = createFilteredVector
+
+var cubicHermite = require('cubic-hermite')
+var bsearch = require('binary-search-bounds')
+
+function clamp(lo, hi, x) {
+  return Math.min(hi, Math.max(lo, x))
+}
+
+function FilteredVector(state0, velocity0, t0) {
+  this.dimension  = state0.length
+  this.bounds     = [ new Array(this.dimension), new Array(this.dimension) ]
+  for(var i=0; i<this.dimension; ++i) {
+    this.bounds[0][i] = -Infinity
+    this.bounds[1][i] = Infinity
+  }
+  this._state     = state0.slice().reverse()
+  this._velocity  = velocity0.slice().reverse()
+  this._time      = [ t0 ]
+  this._scratch   = [ state0.slice(), state0.slice(), state0.slice(), state0.slice(), state0.slice() ]
+}
+
+var proto = FilteredVector.prototype
+
+proto.flush = function(t) {
+  var idx = bsearch.gt(this._time, t) - 1
+  if(idx <= 0) {
+    return
+  }
+  this._time.splice(0, idx)
+  this._state.splice(0, idx * this.dimension)
+  this._velocity.splice(0, idx * this.dimension)
+}
+
+proto.curve = function(t) {
+  var time      = this._time
+  var n         = time.length
+  var idx       = bsearch.le(time, t)
+  var result    = this._scratch[0]
+  var state     = this._state
+  var velocity  = this._velocity
+  var d         = this.dimension
+  var bounds    = this.bounds
+  if(idx < 0) {
+    var ptr = d-1
+    for(var i=0; i<d; ++i, --ptr) {
+      result[i] = state[ptr]
+    }
+  } else if(idx >= n-1) {
+    var ptr = state.length-1
+    var tf = t - time[n-1]
+    for(var i=0; i<d; ++i, --ptr) {
+      result[i] = state[ptr] + tf * velocity[ptr]
+    }
+  } else {
+    var ptr = d * (idx+1) - 1
+    var t0  = time[idx]
+    var t1  = time[idx+1]
+    var dt  = (t1 - t0) || 1.0
+    var x0  = this._scratch[1]
+    var x1  = this._scratch[2]
+    var v0  = this._scratch[3]
+    var v1  = this._scratch[4]
+    var steady = true
+    for(var i=0; i<d; ++i, --ptr) {
+      x0[i] = state[ptr]
+      v0[i] = velocity[ptr] * dt
+      x1[i] = state[ptr+d]
+      v1[i] = velocity[ptr+d] * dt
+      steady = steady && (x0[i] === x1[i] && v0[i] === v1[i] && v0[i] === 0.0)
+    }
+    if(steady) {
+      for(var i=0; i<d; ++i) {
+        result[i] = x0[i]
+      }
+    } else {
+      cubicHermite(x0, v0, x1, v1, (t-t0)/dt, result)
+    }
+  }
+  var lo = bounds[0]
+  var hi = bounds[1]
+  for(var i=0; i<d; ++i) {
+    result[i] = clamp(lo[i], hi[i], result[i])
+  }
+  return result
+}
+
+proto.dcurve = function(t) {
+  var time     = this._time
+  var n        = time.length
+  var idx      = bsearch.le(time, t)
+  var result   = this._scratch[0]
+  var state    = this._state
+  var velocity = this._velocity
+  var d        = this.dimension
+  if(idx >= n-1) {
+    var ptr = state.length-1
+    var tf = t - time[n-1]
+    for(var i=0; i<d; ++i, --ptr) {
+      result[i] = velocity[ptr]
+    }
+  } else {
+    var ptr = d * (idx+1) - 1
+    var t0 = time[idx]
+    var t1 = time[idx+1]
+    var dt = (t1 - t0) || 1.0
+    var x0 = this._scratch[1]
+    var x1 = this._scratch[2]
+    var v0 = this._scratch[3]
+    var v1 = this._scratch[4]
+    var steady = true
+    for(var i=0; i<d; ++i, --ptr) {
+      x0[i] = state[ptr]
+      v0[i] = velocity[ptr] * dt
+      x1[i] = state[ptr+d]
+      v1[i] = velocity[ptr+d] * dt
+      steady = steady && (x0[i] === x1[i] && v0[i] === v1[i] && v0[i] === 0.0)
+    }
+    if(steady) {
+      for(var i=0; i<d; ++i) {
+        result[i] = 0.0
+      }
+    } else {
+      cubicHermite.derivative(x0, v0, x1, v1, (t-t0)/dt, result)
+      for(var i=0; i<d; ++i) {
+        result[i] /= dt
+      }
+    }
+  }
+  return result
+}
+
+proto.lastT = function() {
+  var time = this._time
+  return time[time.length-1]
+}
+
+proto.stable = function() {
+  var velocity = this._velocity
+  var ptr = velocity.length
+  for(var i=this.dimension-1; i>=0; --i) {
+    if(velocity[--ptr]) {
+      return false
+    }
+  }
+  return true
+}
+
+proto.jump = function(t) {
+  var t0 = this.lastT()
+  var d  = this.dimension
+  if(t < t0 || arguments.length !== d+1) {
+    return
+  }
+  var state     = this._state
+  var velocity  = this._velocity
+  var ptr       = state.length-this.dimension
+  var bounds    = this.bounds
+  var lo        = bounds[0]
+  var hi        = bounds[1]
+  this._time.push(t0, t)
+  for(var j=0; j<2; ++j) {
+    for(var i=0; i<d; ++i) {
+      state.push(state[ptr++])
+      velocity.push(0)
+    }
+  }
+  this._time.push(t)
+  for(var i=d; i>0; --i) {
+    state.push(clamp(lo[i-1], hi[i-1], arguments[i]))
+    velocity.push(0)
+  }
+}
+
+proto.push = function(t) {
+  var t0 = this.lastT()
+  var d  = this.dimension
+  if(t < t0 || arguments.length !== d+1) {
+    return
+  }
+  var state     = this._state
+  var velocity  = this._velocity
+  var ptr       = state.length-this.dimension
+  var dt        = t - t0
+  var bounds    = this.bounds
+  var lo        = bounds[0]
+  var hi        = bounds[1]
+  var sf        = (dt > 1e-6) ? 1/dt : 0
+  this._time.push(t)
+  for(var i=d; i>0; --i) {
+    var xc = clamp(lo[i-1], hi[i-1], arguments[i])
+    state.push(xc)
+    velocity.push((xc - state[ptr++]) * sf)
+  }
+}
+
+proto.set = function(t) {
+  var d = this.dimension
+  if(t < this.lastT() || arguments.length !== d+1) {
+    return
+  }
+  var state     = this._state
+  var velocity  = this._velocity
+  var bounds    = this.bounds
+  var lo        = bounds[0]
+  var hi        = bounds[1]
+  this._time.push(t)
+  for(var i=d; i>0; --i) {
+    state.push(clamp(lo[i-1], hi[i-1], arguments[i]))
+    velocity.push(0)
+  }
+}
+
+proto.move = function(t) {
+  var t0 = this.lastT()
+  var d  = this.dimension
+  if(t <= t0 || arguments.length !== d+1) {
+    return
+  }
+  var state    = this._state
+  var velocity = this._velocity
+  var statePtr = state.length - this.dimension
+  var bounds   = this.bounds
+  var lo       = bounds[0]
+  var hi       = bounds[1]
+  var dt       = t - t0
+  var sf       = (dt > 1e-6) ? 1/dt : 0.0
+  this._time.push(t)
+  for(var i=d; i>0; --i) {
+    var dx = arguments[i]
+    state.push(clamp(lo[i-1], hi[i-1], state[statePtr++] + dx))
+    velocity.push(dx * sf)
+  }
+}
+
+proto.idle = function(t) {
+  var t0 = this.lastT()
+  if(t < t0) {
+    return
+  }
+  var d        = this.dimension
+  var state    = this._state
+  var velocity = this._velocity
+  var statePtr = state.length-d
+  var bounds   = this.bounds
+  var lo       = bounds[0]
+  var hi       = bounds[1]
+  var dt       = t - t0
+  this._time.push(t)
+  for(var i=d-1; i>=0; --i) {
+    state.push(clamp(lo[i], hi[i], state[statePtr] + dt * velocity[statePtr]))
+    velocity.push(0)
+    statePtr += 1
+  }
+}
+
+function getZero(d) {
+  var result = new Array(d)
+  for(var i=0; i<d; ++i) {
+    result[i] = 0.0
+  }
+  return result
+}
+
+function createFilteredVector(initState, initVelocity, initTime) {
+  switch(arguments.length) {
+    case 0:
+      return new FilteredVector([0], [0], 0)
+    case 1:
+      if(typeof initState === 'number') {
+        var zero = getZero(initState)
+        return new FilteredVector(zero, zero, 0)
+      } else {
+        return new FilteredVector(initState, getZero(initState.length), 0)
+      }
+    case 2:
+      if(typeof initVelocity === 'number') {
+        var zero = getZero(initState.length)
+        return new FilteredVector(initState, zero, +initVelocity)
+      } else {
+        initTime = 0
+      }
+    case 3:
+      if(initState.length !== initVelocity.length) {
+        throw new Error('state and velocity lengths must match')
+      }
+      return new FilteredVector(initState, initVelocity, initTime)
+  }
+}
+
+},{"binary-search-bounds":20,"cubic-hermite":21}],20:[function(require,module,exports){
+"use strict"
+
+function compileSearch(funcName, predicate, reversed, extraArgs, useNdarray, earlyOut) {
+  var code = [
+    "function ", funcName, "(a,l,h,", extraArgs.join(","),  "){",
+earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"),
+";while(l<=h){\
+var m=(l+h)>>>1,x=a", useNdarray ? ".get(m)" : "[m]"]
+  if(earlyOut) {
+    if(predicate.indexOf("c") < 0) {
+      code.push(";if(x===y){return m}else if(x<=y){")
+    } else {
+      code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){")
+    }
+  } else {
+    code.push(";if(", predicate, "){i=m;")
+  }
+  if(reversed) {
+    code.push("l=m+1}else{h=m-1}")
+  } else {
+    code.push("h=m-1}else{l=m+1}")
+  }
+  code.push("}")
+  if(earlyOut) {
+    code.push("return -1};")
+  } else {
+    code.push("return i};")
+  }
+  return code.join("")
+}
+
+function compileBoundsSearch(predicate, reversed, suffix, earlyOut) {
+  var result = new Function([
+  compileSearch("A", "x" + predicate + "y", reversed, ["y"], false, earlyOut),
+  compileSearch("B", "x" + predicate + "y", reversed, ["y"], true, earlyOut),
+  compileSearch("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], false, earlyOut),
+  compileSearch("Q", "c(x,y)" + predicate + "0", reversed, ["y", "c"], true, earlyOut),
+"function dispatchBsearch", suffix, "(a,y,c,l,h){\
+if(a.shape){\
+if(typeof(c)==='function'){\
+return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)\
+}else{\
+return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)\
+}}else{\
+if(typeof(c)==='function'){\
+return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)\
+}else{\
+return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)\
+}}}\
+return dispatchBsearch", suffix].join(""))
+  return result()
+}
+
+module.exports = {
+  ge: compileBoundsSearch(">=", false, "GE"),
+  gt: compileBoundsSearch(">", false, "GT"),
+  lt: compileBoundsSearch("<", true, "LT"),
+  le: compileBoundsSearch("<=", true, "LE"),
+  eq: compileBoundsSearch("-", true, "EQ", true)
+}
+
+},{}],21:[function(require,module,exports){
+"use strict"
+
+function dcubicHermite(p0, v0, p1, v1, t, f) {
+  var dh00 = 6*t*t-6*t,
+      dh10 = 3*t*t-4*t + 1,
+      dh01 = -6*t*t+6*t,
+      dh11 = 3*t*t-2*t
+  if(p0.length) {
+    if(!f) {
+      f = new Array(p0.length)
+    }
+    for(var i=p0.length-1; i>=0; --i) {
+      f[i] = dh00*p0[i] + dh10*v0[i] + dh01*p1[i] + dh11*v1[i]
+    }
+    return f
+  }
+  return dh00*p0 + dh10*v0 + dh01*p1[i] + dh11*v1
+}
+
+function cubicHermite(p0, v0, p1, v1, t, f) {
+  var ti  = (t-1), t2 = t*t, ti2 = ti*ti,
+      h00 = (1+2*t)*ti2,
+      h10 = t*ti2,
+      h01 = t2*(3-2*t),
+      h11 = t2*ti
+  if(p0.length) {
+    if(!f) {
+      f = new Array(p0.length)
+    }
+    for(var i=p0.length-1; i>=0; --i) {
+      f[i] = h00*p0[i] + h10*v0[i] + h01*p1[i] + h11*v1[i]
+    }
+    return f
+  }
+  return h00*p0 + h10*v0 + h01*p1 + h11*v1
+}
+
+module.exports = cubicHermite
+module.exports.derivative = dcubicHermite
+},{}],22:[function(require,module,exports){
+module.exports = cross;
+
+/**
+ * Computes the cross product of two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {vec3} out
+ */
+function cross(out, a, b) {
+    var ax = a[0], ay = a[1], az = a[2],
+        bx = b[0], by = b[1], bz = b[2]
+
+    out[0] = ay * bz - az * by
+    out[1] = az * bx - ax * bz
+    out[2] = ax * by - ay * bx
+    return out
+}
+},{}],23:[function(require,module,exports){
+module.exports = dot;
+
+/**
+ * Calculates the dot product of two vec3's
+ *
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @returns {Number} dot product of a and b
+ */
+function dot(a, b) {
+    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
+}
+},{}],24:[function(require,module,exports){
+module.exports = length;
+
+/**
+ * Calculates the length of a vec3
+ *
+ * @param {vec3} a vector to calculate length of
+ * @returns {Number} length of a
+ */
+function length(a) {
+    var x = a[0],
+        y = a[1],
+        z = a[2]
+    return Math.sqrt(x*x + y*y + z*z)
+}
+},{}],25:[function(require,module,exports){
+module.exports = lerp;
+
+/**
+ * Performs a linear interpolation between two vec3's
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a the first operand
+ * @param {vec3} b the second operand
+ * @param {Number} t interpolation amount between the two inputs
+ * @returns {vec3} out
+ */
+function lerp(out, a, b, t) {
+    var ax = a[0],
+        ay = a[1],
+        az = a[2]
+    out[0] = ax + t * (b[0] - ax)
+    out[1] = ay + t * (b[1] - ay)
+    out[2] = az + t * (b[2] - az)
+    return out
+}
+},{}],26:[function(require,module,exports){
+module.exports = normalize;
+
+/**
+ * Normalize a vec3
+ *
+ * @param {vec3} out the receiving vector
+ * @param {vec3} a vector to normalize
+ * @returns {vec3} out
+ */
+function normalize(out, a) {
+    var x = a[0],
+        y = a[1],
+        z = a[2]
+    var len = x*x + y*y + z*z
+    if (len > 0) {
+        //TODO: evaluate use of glm_invsqrt here?
+        len = 1 / Math.sqrt(len)
+        out[0] = a[0] * len
+        out[1] = a[1] * len
+        out[2] = a[2] * len
+    }
+    return out
+}
+},{}],27:[function(require,module,exports){
+'use strict'
+
+var bsearch   = require('binary-search-bounds')
+var m4interp  = require('mat4-interpolate')
+var invert44  = require('gl-mat4/invert')
+var rotateX   = require('gl-mat4/rotateX')
+var rotateY   = require('gl-mat4/rotateY')
+var rotateZ   = require('gl-mat4/rotateZ')
+var lookAt    = require('gl-mat4/lookAt')
+var translate = require('gl-mat4/translate')
+var scale     = require('gl-mat4/scale')
+var normalize = require('gl-vec3/normalize')
+
+var DEFAULT_CENTER = [0,0,0]
+
+module.exports = createMatrixCameraController
+
+function MatrixCameraController(initialMatrix) {
+  this._components    = initialMatrix.slice()
+  this._time          = [0]
+  this.prevMatrix     = initialMatrix.slice()
+  this.nextMatrix     = initialMatrix.slice()
+  this.computedMatrix = initialMatrix.slice()
+  this.computedInverse = initialMatrix.slice()
+  this.computedEye    = [0,0,0]
+  this.computedUp     = [0,0,0]
+  this.computedCenter = [0,0,0]
+  this.computedRadius = [0]
+  this._limits        = [-Infinity, Infinity]
+}
+
+var proto = MatrixCameraController.prototype
+
+proto.recalcMatrix = function(t) {
+  var time = this._time
+  var tidx = bsearch.le(time, t)
+  var mat = this.computedMatrix
+  if(tidx < 0) {
+    return
+  }
+  var comps = this._components
+  if(tidx === time.length-1) {
+    var ptr = 16*tidx
+    for(var i=0; i<16; ++i) {
+      mat[i] = comps[ptr++]
+    }
+  } else {
+    var dt = (time[tidx+1] - time[tidx])
+    var ptr = 16*tidx
+    var prev = this.prevMatrix
+    var allEqual = true
+    for(var i=0; i<16; ++i) {
+      prev[i] = comps[ptr++]
+    }
+    var next = this.nextMatrix
+    for(var i=0; i<16; ++i) {
+      next[i] = comps[ptr++]
+      allEqual = allEqual && (prev[i] === next[i])
+    }
+    if(dt < 1e-6 || allEqual) {
+      for(var i=0; i<16; ++i) {
+        mat[i] = prev[i]
+      }
+    } else {
+      m4interp(mat, prev, next, (t - time[tidx])/dt)
+    }
+  }
+
+  var up = this.computedUp
+  up[0] = mat[1]
+  up[1] = mat[5]
+  up[2] = mat[6]
+  normalize(up, up)
+
+  var imat = this.computedInverse
+  invert44(imat, mat)
+  var eye = this.computedEye
+  var w = imat[15]
+  eye[0] = imat[12]/w
+  eye[1] = imat[13]/w
+  eye[2] = imat[14]/w
+
+  var center = this.computedCenter
+  var radius = Math.exp(this.computedRadius[0])
+  for(var i=0; i<3; ++i) {
+    center[i] = eye[i] - mat[2+4*i] * radius
+  }
+}
+
+proto.idle = function(t) {
+  if(t < this.lastT()) {
+    return
+  }
+  var mc = this._components
+  var ptr = mc.length-16
+  for(var i=0; i<16; ++i) {
+    mc.push(mc[ptr++])
+  }
+  this._time.push(t)
+}
+
+proto.flush = function(t) {
+  var idx = bsearch.gt(this._time, t) - 2
+  if(idx < 0) {
+    return
+  }
+  this._time.slice(0, idx)
+  this._components.slice(0, 16*idx)
+}
+
+proto.lastT = function() {
+  return this._time[this._time.length-1]
+}
+
+proto.lookAt = function(t, eye, center, up) {
+  this.recalcMatrix(t)
+  eye    = eye || this.computedEye
+  center = center || DEFAULT_CENTER
+  up     = up || this.computedUp
+  this.setMatrix(t, lookAt(this.computedMatrix, eye, center, up))
+  var d2 = 0.0
+  for(var i=0; i<3; ++i) {
+    d2 += Math.pow(center[i] - eye[i], 2)
+  }
+  d2 = Math.log(Math.sqrt(d2))
+  this.computedRadius[0] = d2
+}
+
+proto.rotate = function(t, yaw, pitch, roll) {
+  this.recalcMatrix(t)
+  var mat = this.computedInverse
+  if(yaw)   rotateY(mat, mat, yaw)
+  if(pitch) rotateX(mat, mat, pitch)
+  if(roll)  rotateZ(mat, mat, roll)
+  this.setMatrix(t, invert44(this.computedMatrix, mat))
+}
+
+var tvec = [0,0,0]
+
+proto.pan = function(t, dx, dy, dz) {
+  tvec[0] = -(dx || 0.0)
+  tvec[1] = -(dy || 0.0)
+  tvec[2] = -(dz || 0.0)
+  this.recalcMatrix(t)
+  var mat = this.computedInverse
+  translate(mat, mat, tvec)
+  this.setMatrix(t, invert44(mat, mat))
+}
+
+proto.translate = function(t, dx, dy, dz) {
+  tvec[0] = dx || 0.0
+  tvec[1] = dy || 0.0
+  tvec[2] = dz || 0.0
+  this.recalcMatrix(t)
+  var mat = this.computedMatrix
+  translate(mat, mat, tvec)
+  this.setMatrix(t, mat)
+}
+
+proto.setMatrix = function(t, mat) {
+  if(t < this.lastT()) {
+    return
+  }
+  this._time.push(t)
+  for(var i=0; i<16; ++i) {
+    this._components.push(mat[i])
+  }
+}
+
+proto.setDistance = function(t, d) {
+  this.computedRadius[0] = d
+}
+
+proto.setDistanceLimits = function(a,b) {
+  var lim = this._limits
+  lim[0] = a
+  lim[1] = b
+}
+
+proto.getDistanceLimits = function(out) {
+  var lim = this._limits
+  if(out) {
+    out[0] = lim[0]
+    out[1] = lim[1]
+    return out
+  }
+  return lim
+}
+
+function createMatrixCameraController(options) {
+  options = options || {}
+  var matrix = options.matrix || 
+              [1,0,0,0,
+               0,1,0,0,
+               0,0,1,0,
+               0,0,0,1]
+  return new MatrixCameraController(matrix)
+}
+},{"binary-search-bounds":28,"gl-mat4/invert":94,"gl-mat4/lookAt":95,"gl-mat4/rotateX":99,"gl-mat4/rotateY":100,"gl-mat4/rotateZ":101,"gl-mat4/scale":102,"gl-mat4/translate":103,"gl-vec3/normalize":26,"mat4-interpolate":29}],28:[function(require,module,exports){
+arguments[4][20][0].apply(exports,arguments)
+},{"dup":20}],29:[function(require,module,exports){
+var lerp = require('gl-vec3/lerp')
+
+var recompose = require('mat4-recompose')
+var decompose = require('mat4-decompose')
+var determinant = require('gl-mat4/determinant')
+var slerp = require('quat-slerp')
+
+var state0 = state()
+var state1 = state()
+var tmp = state()
+
+module.exports = interpolate
+function interpolate(out, start, end, alpha) {
+    if (determinant(start) === 0 || determinant(end) === 0)
+        return false
+
+    //decompose the start and end matrices into individual components
+    var r0 = decompose(start, state0.translate, state0.scale, state0.skew, state0.perspective, state0.quaternion)
+    var r1 = decompose(end, state1.translate, state1.scale, state1.skew, state1.perspective, state1.quaternion)
+    if (!r0 || !r1)
+        return false    
+
+
+    //now lerp/slerp the start and end components into a temporary     lerp(tmptranslate, state0.translate, state1.translate, alpha)
+    lerp(tmp.translate, state0.translate, state1.translate, alpha)
+    lerp(tmp.skew, state0.skew, state1.skew, alpha)
+    lerp(tmp.scale, state0.scale, state1.scale, alpha)
+    lerp(tmp.perspective, state0.perspective, state1.perspective, alpha)
+    slerp(tmp.quaternion, state0.quaternion, state1.quaternion, alpha)
+
+    //and recompose into our 'out' matrix
+    recompose(out, tmp.translate, tmp.scale, tmp.skew, tmp.perspective, tmp.quaternion)
+    return true
+}
+
+function state() {
+    return {
+        translate: vec3(),
+        scale: vec3(1),
+        skew: vec3(),
+        perspective: vec4(),
+        quaternion: vec4()
+    }
+}
+
+function vec3(n) {
+    return [n||0,n||0,n||0]
+}
+
+function vec4() {
+    return [0,0,0,1]
+}
+},{"gl-mat4/determinant":90,"gl-vec3/lerp":25,"mat4-decompose":30,"mat4-recompose":32,"quat-slerp":33}],30:[function(require,module,exports){
+/*jshint unused:true*/
+/*
+Input:  matrix      ; a 4x4 matrix
+Output: translation ; a 3 component vector
+        scale       ; a 3 component vector
+        skew        ; skew factors XY,XZ,YZ represented as a 3 component vector
+        perspective ; a 4 component vector
+        quaternion  ; a 4 component vector
+Returns false if the matrix cannot be decomposed, true if it can
+
+
+References:
+https://github.com/kamicane/matrix3d/blob/master/lib/Matrix3d.js
+https://github.com/ChromiumWebApps/chromium/blob/master/ui/gfx/transform_util.cc
+http://www.w3.org/TR/css3-transforms/#decomposing-a-3d-matrix
+*/
+
+var normalize = require('./normalize')
+
+var create = require('gl-mat4/create')
+var clone = require('gl-mat4/clone')
+var determinant = require('gl-mat4/determinant')
+var invert = require('gl-mat4/invert')
+var transpose = require('gl-mat4/transpose')
+var vec3 = {
+    length: require('gl-vec3/length'),
+    normalize: require('gl-vec3/normalize'),
+    dot: require('gl-vec3/dot'),
+    cross: require('gl-vec3/cross')
+}
+
+var tmp = create()
+var perspectiveMatrix = create()
+var tmpVec4 = [0, 0, 0, 0]
+var row = [ [0,0,0], [0,0,0], [0,0,0] ]
+var pdum3 = [0,0,0]
+
+module.exports = function decomposeMat4(matrix, translation, scale, skew, perspective, quaternion) {
+    if (!translation) translation = [0,0,0]
+    if (!scale) scale = [0,0,0]
+    if (!skew) skew = [0,0,0]
+    if (!perspective) perspective = [0,0,0,1]
+    if (!quaternion) quaternion = [0,0,0,1]
+
+    //normalize, if not possible then bail out early
+    if (!normalize(tmp, matrix))
+        return false
+
+    // perspectiveMatrix is used to solve for perspective, but it also provides
+    // an easy way to test for singularity of the upper 3x3 component.
+    clone(perspectiveMatrix, tmp)
+
+    perspectiveMatrix[3] = 0
+    perspectiveMatrix[7] = 0
+    perspectiveMatrix[11] = 0
+    perspectiveMatrix[15] = 1
+
+    // If the perspectiveMatrix is not invertible, we are also unable to
+    // decompose, so we'll bail early. Constant taken from SkMatrix44::invert.
+    if (Math.abs(determinant(perspectiveMatrix) < 1e-8))
+        return false
+
+    var a03 = tmp[3], a13 = tmp[7], a23 = tmp[11],
+            a30 = tmp[12], a31 = tmp[13], a32 = tmp[14], a33 = tmp[15]
+
+    // First, isolate perspective.
+    if (a03 !== 0 || a13 !== 0 || a23 !== 0) {
+        tmpVec4[0] = a03
+        tmpVec4[1] = a13
+        tmpVec4[2] = a23
+        tmpVec4[3] = a33
+
+        // Solve the equation by inverting perspectiveMatrix and multiplying
+        // rightHandSide by the inverse.
+        // resuing the perspectiveMatrix here since it's no longer needed
+        var ret = invert(perspectiveMatrix, perspectiveMatrix)
+        if (!ret) return false
+        transpose(perspectiveMatrix, perspectiveMatrix)
+
+        //multiply by transposed inverse perspective matrix, into perspective vec4
+        vec4multMat4(perspective, tmpVec4, perspectiveMatrix)
+    } else { 
+        //no perspective
+        perspective[0] = perspective[1] = perspective[2] = 0
+        perspective[3] = 1
+    }
+
+    // Next take care of translation
+    translation[0] = a30
+    translation[1] = a31
+    translation[2] = a32
+
+    // Now get scale and shear. 'row' is a 3 element array of 3 component vectors
+    mat3from4(row, tmp)
+
+    // Compute X scale factor and normalize first row.
+    scale[0] = vec3.length(row[0])
+    vec3.normalize(row[0], row[0])
+
+    // Compute XY shear factor and make 2nd row orthogonal to 1st.
+    skew[0] = vec3.dot(row[0], row[1])
+    combine(row[1], row[1], row[0], 1.0, -skew[0])
+
+    // Now, compute Y scale and normalize 2nd row.
+    scale[1] = vec3.length(row[1])
+    vec3.normalize(row[1], row[1])
+    skew[0] /= scale[1]
+
+    // Compute XZ and YZ shears, orthogonalize 3rd row
+    skew[1] = vec3.dot(row[0], row[2])
+    combine(row[2], row[2], row[0], 1.0, -skew[1])
+    skew[2] = vec3.dot(row[1], row[2])
+    combine(row[2], row[2], row[1], 1.0, -skew[2])
+
+    // Next, get Z scale and normalize 3rd row.
+    scale[2] = vec3.length(row[2])
+    vec3.normalize(row[2], row[2])
+    skew[1] /= scale[2]
+    skew[2] /= scale[2]
+
+
+    // At this point, the matrix (in rows) is orthonormal.
+    // Check for a coordinate system flip.  If the determinant
+    // is -1, then negate the matrix and the scaling factors.
+    vec3.cross(pdum3, row[1], row[2])
+    if (vec3.dot(row[0], pdum3) < 0) {
+        for (var i = 0; i < 3; i++) {
+            scale[i] *= -1;
+            row[i][0] *= -1
+            row[i][1] *= -1
+            row[i][2] *= -1
+        }
+    }
+
+    // Now, get the rotations out
+    quaternion[0] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] - row[1][1] - row[2][2], 0))
+    quaternion[1] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] + row[1][1] - row[2][2], 0))
+    quaternion[2] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] - row[1][1] + row[2][2], 0))
+    quaternion[3] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] + row[1][1] + row[2][2], 0))
+
+    if (row[2][1] > row[1][2])
+        quaternion[0] = -quaternion[0]
+    if (row[0][2] > row[2][0])
+        quaternion[1] = -quaternion[1]
+    if (row[1][0] > row[0][1])
+        quaternion[2] = -quaternion[2]
+    return true
+}
+
+//will be replaced by gl-vec4 eventually
+function vec4multMat4(out, a, m) {
+    var x = a[0], y = a[1], z = a[2], w = a[3];
+    out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
+    out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
+    out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
+    out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
+    return out;
+}
+
+//gets upper-left of a 4x4 matrix into a 3x3 of vectors
+function mat3from4(out, mat4x4) {
+    out[0][0] = mat4x4[0]
+    out[0][1] = mat4x4[1]
+    out[0][2] = mat4x4[2]
+    
+    out[1][0] = mat4x4[4]
+    out[1][1] = mat4x4[5]
+    out[1][2] = mat4x4[6]
+
+    out[2][0] = mat4x4[8]
+    out[2][1] = mat4x4[9]
+    out[2][2] = mat4x4[10]
+}
+
+function combine(out, a, b, scale1, scale2) {
+    out[0] = a[0] * scale1 + b[0] * scale2
+    out[1] = a[1] * scale1 + b[1] * scale2
+    out[2] = a[2] * scale1 + b[2] * scale2
+}
+},{"./normalize":31,"gl-mat4/clone":88,"gl-mat4/create":89,"gl-mat4/determinant":90,"gl-mat4/invert":94,"gl-mat4/transpose":104,"gl-vec3/cross":22,"gl-vec3/dot":23,"gl-vec3/length":24,"gl-vec3/normalize":26}],31:[function(require,module,exports){
+module.exports = function normalize(out, mat) {
+    var m44 = mat[15]
+    // Cannot normalize.
+    if (m44 === 0) 
+        return false
+    var scale = 1 / m44
+    for (var i=0; i<16; i++)
+        out[i] = mat[i] * scale
+    return true
+}
+},{}],32:[function(require,module,exports){
+/*
+Input:  translation ; a 3 component vector
+        scale       ; a 3 component vector
+        skew        ; skew factors XY,XZ,YZ represented as a 3 component vector
+        perspective ; a 4 component vector
+        quaternion  ; a 4 component vector
+Output: matrix      ; a 4x4 matrix
+
+From: http://www.w3.org/TR/css3-transforms/#recomposing-to-a-3d-matrix
+*/
+
+var mat4 = {
+    identity: require('gl-mat4/identity'),
+    translate: require('gl-mat4/translate'),
+    multiply: require('gl-mat4/multiply'),
+    create: require('gl-mat4/create'),
+    scale: require('gl-mat4/scale'),
+    fromRotationTranslation: require('gl-mat4/fromRotationTranslation')
+}
+
+var rotationMatrix = mat4.create()
+var temp = mat4.create()
+
+module.exports = function recomposeMat4(matrix, translation, scale, skew, perspective, quaternion) {
+    mat4.identity(matrix)
+
+    //apply translation & rotation
+    mat4.fromRotationTranslation(matrix, quaternion, translation)
+
+    //apply perspective
+    matrix[3] = perspective[0]
+    matrix[7] = perspective[1]
+    matrix[11] = perspective[2]
+    matrix[15] = perspective[3]
+        
+    // apply skew
+    // temp is a identity 4x4 matrix initially
+    mat4.identity(temp)
+
+    if (skew[2] !== 0) {
+        temp[9] = skew[2]
+        mat4.multiply(matrix, matrix, temp)
+    }
+
+    if (skew[1] !== 0) {
+        temp[9] = 0
+        temp[8] = skew[1]
+        mat4.multiply(matrix, matrix, temp)
+    }
+
+    if (skew[0] !== 0) {
+        temp[8] = 0
+        temp[4] = skew[0]
+        mat4.multiply(matrix, matrix, temp)
+    }
+
+    //apply scale
+    mat4.scale(matrix, matrix, scale)
+    return matrix
+}
+},{"gl-mat4/create":89,"gl-mat4/fromRotationTranslation":92,"gl-mat4/identity":93,"gl-mat4/multiply":96,"gl-mat4/scale":102,"gl-mat4/translate":103}],33:[function(require,module,exports){
+module.exports = require('gl-quat/slerp')
+},{"gl-quat/slerp":34}],34:[function(require,module,exports){
+module.exports = slerp
+
+/**
+ * Performs a spherical linear interpolation between two quat
+ *
+ * @param {quat} out the receiving quaternion
+ * @param {quat} a the first operand
+ * @param {quat} b the second operand
+ * @param {Number} t interpolation amount between the two inputs
+ * @returns {quat} out
+ */
+function slerp (out, a, b, t) {
+  // benchmarks:
+  //    http://jsperf.com/quaternion-slerp-implementations
+
+  var ax = a[0], ay = a[1], az = a[2], aw = a[3],
+    bx = b[0], by = b[1], bz = b[2], bw = b[3]
+
+  var omega, cosom, sinom, scale0, scale1
+
+  // calc cosine
+  cosom = ax * bx + ay * by + az * bz + aw * bw
+  // adjust signs (if necessary)
+  if (cosom < 0.0) {
+    cosom = -cosom
+    bx = -bx
+    by = -by
+    bz = -bz
+    bw = -bw
+  }
+  // calculate coefficients
+  if ((1.0 - cosom) > 0.000001) {
+    // standard case (slerp)
+    omega = Math.acos(cosom)
+    sinom = Math.sin(omega)
+    scale0 = Math.sin((1.0 - t) * omega) / sinom
+    scale1 = Math.sin(t * omega) / sinom
+  } else {
+    // "from" and "to" quaternions are very close
+    //  ... so we can do a linear interpolation
+    scale0 = 1.0 - t
+    scale1 = t
+  }
+  // calculate final values
+  out[0] = scale0 * ax + scale1 * bx
+  out[1] = scale0 * ay + scale1 * by
+  out[2] = scale0 * az + scale1 * bz
+  out[3] = scale0 * aw + scale1 * bw
+
+  return out
+}
+
+},{}],35:[function(require,module,exports){
+'use strict'
+
+module.exports = quatFromFrame
+
+function quatFromFrame(
+  out,
+  rx, ry, rz,
+  ux, uy, uz,
+  fx, fy, fz) {
+  var tr = rx + uy + fz
+  if(l > 0) {
+    var l = Math.sqrt(tr + 1.0)
+    out[0] = 0.5 * (uz - fy) / l
+    out[1] = 0.5 * (fx - rz) / l
+    out[2] = 0.5 * (ry - uy) / l
+    out[3] = 0.5 * l
+  } else {
+    var tf = Math.max(rx, uy, fz)
+    var l = Math.sqrt(2 * tf - tr + 1.0)
+    if(rx >= tf) {
+      //x y z  order
+      out[0] = 0.5 * l
+      out[1] = 0.5 * (ux + ry) / l
+      out[2] = 0.5 * (fx + rz) / l
+      out[3] = 0.5 * (uz - fy) / l
+    } else if(uy >= tf) {
+      //y z x  order
+      out[0] = 0.5 * (ry + ux) / l
+      out[1] = 0.5 * l
+      out[2] = 0.5 * (fy + uz) / l
+      out[3] = 0.5 * (fx - rz) / l
+    } else {
+      //z x y  order
+      out[0] = 0.5 * (rz + fx) / l
+      out[1] = 0.5 * (uz + fy) / l
+      out[2] = 0.5 * l
+      out[3] = 0.5 * (ry - ux) / l
+    }
+  }
+  return out
+}
+},{}],36:[function(require,module,exports){
+'use strict'
+
+module.exports = createOrbitController
+
+var filterVector  = require('filtered-vector')
+var lookAt        = require('gl-mat4/lookAt')
+var mat4FromQuat  = require('gl-mat4/fromQuat')
+var invert44      = require('gl-mat4/invert')
+var quatFromFrame = require('./lib/quatFromFrame')
+
+function len3(x,y,z) {
+  return Math.sqrt(Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2))
+}
+
+function len4(w,x,y,z) {
+  return Math.sqrt(Math.pow(w,2) + Math.pow(x,2) + Math.pow(y,2) + Math.pow(z,2))
+}
+
+function normalize4(out, a) {
+  var ax = a[0]
+  var ay = a[1]
+  var az = a[2]
+  var aw = a[3]
+  var al = len4(ax, ay, az, aw)
+  if(al > 1e-6) {
+    out[0] = ax/al
+    out[1] = ay/al
+    out[2] = az/al
+    out[3] = aw/al
+  } else {
+    out[0] = out[1] = out[2] = 0.0
+    out[3] = 1.0
+  }
+}
+
+function OrbitCameraController(initQuat, initCenter, initRadius) {
+  this.radius    = filterVector([initRadius])
+  this.center    = filterVector(initCenter)
+  this.rotation  = filterVector(initQuat)
+
+  this.computedRadius   = this.radius.curve(0)
+  this.computedCenter   = this.center.curve(0)
+  this.computedRotation = this.rotation.curve(0)
+  this.computedUp       = [0.1,0,0]
+  this.computedEye      = [0.1,0,0]
+  this.computedMatrix   = [0.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
+
+  this.recalcMatrix(0)
+}
+
+var proto = OrbitCameraController.prototype
+
+proto.lastT = function() {
+  return Math.max(
+    this.radius.lastT(),
+    this.center.lastT(),
+    this.rotation.lastT())
+}
+
+proto.recalcMatrix = function(t) {
+  this.radius.curve(t)
+  this.center.curve(t)
+  this.rotation.curve(t)
+
+  var quat = this.computedRotation
+  normalize4(quat, quat)
+
+  var mat = this.computedMatrix
+  mat4FromQuat(mat, quat)
+
+  var center = this.computedCenter
+  var eye    = this.computedEye
+  var up     = this.computedUp
+  var radius = Math.exp(this.computedRadius[0])
+
+  eye[0] = center[0] + radius * mat[2]
+  eye[1] = center[1] + radius * mat[6]
+  eye[2] = center[2] + radius * mat[10]
+  up[0] = mat[1]
+  up[1] = mat[5]
+  up[2] = mat[9]
+
+  for(var i=0; i<3; ++i) {
+    var rr = 0.0
+    for(var j=0; j<3; ++j) {
+      rr += mat[i+4*j] * eye[j]
+    }
+    mat[12+i] = -rr
+  }
+}
+
+proto.getMatrix = function(t, result) {
+  this.recalcMatrix(t)
+  var m = this.computedMatrix
+  if(result) {
+    for(var i=0; i<16; ++i) {
+      result[i] = m[i]
+    }
+    return result
+  }
+  return m
+}
+
+proto.idle = function(t) {
+  this.center.idle(t)
+  this.radius.idle(t)
+  this.rotation.idle(t)
+}
+
+proto.flush = function(t) {
+  this.center.flush(t)
+  this.radius.flush(t)
+  this.rotation.flush(t)
+}
+
+proto.pan = function(t, dx, dy, dz) {
+  dx = dx || 0.0
+  dy = dy || 0.0
+  dz = dz || 0.0
+
+  this.recalcMatrix(t)
+  var mat = this.computedMatrix
+
+  var ux = mat[1]
+  var uy = mat[5]
+  var uz = mat[9]
+  var ul = len3(ux, uy, uz)
+  ux /= ul
+  uy /= ul
+  uz /= ul
+
+  var rx = mat[0]
+  var ry = mat[4]
+  var rz = mat[8]
+  var ru = rx * ux + ry * uy + rz * uz
+  rx -= ux * ru
+  ry -= uy * ru
+  rz -= uz * ru
+  var rl = len3(rx, ry, rz)
+  rx /= rl
+  ry /= rl
+  rz /= rl
+
+  var fx = mat[2]
+  var fy = mat[6]
+  var fz = mat[10]
+  var fu = fx * ux + fy * uy + fz * uz
+  var fr = fx * rx + fy * ry + fz * rz
+  fx -= fu * ux + fr * rx
+  fy -= fu * uy + fr * ry
+  fz -= fu * uz + fr * rz
+  var fl = len3(fx, fy, fz)
+  fx /= fl
+  fy /= fl
+  fz /= fl
+
+  var vx = rx * dx + ux * dy
+  var vy = ry * dx + uy * dy
+  var vz = rz * dx + uz * dy
+
+  this.center.move(t, vx, vy, vz)
+
+  //Update z-component of radius
+  var radius = Math.exp(this.computedRadius[0])
+  radius = Math.max(1e-4, radius + dz)
+  this.radius.set(t, Math.log(radius))
+}
+
+proto.rotate = function(t, dx, dy, dz) {
+  this.recalcMatrix(t)
+
+  dx = dx||0.0
+  dy = dy||0.0
+
+  var mat = this.computedMatrix
+
+  var rx = mat[0]
+  var ry = mat[4]
+  var rz = mat[8]
+
+  var ux = mat[1]
+  var uy = mat[5]
+  var uz = mat[9]
+
+  var fx = mat[2]
+  var fy = mat[6]
+  var fz = mat[10]
+
+  var qx = dx * rx + dy * ux
+  var qy = dx * ry + dy * uy
+  var qz = dx * rz + dy * uz
+
+  var bx = -(fy * qz - fz * qy)
+  var by = -(fz * qx - fx * qz)
+  var bz = -(fx * qy - fy * qx)  
+  var bw = Math.sqrt(Math.max(0.0, 1.0 - Math.pow(bx,2) - Math.pow(by,2) - Math.pow(bz,2)))
+  var bl = len4(bx, by, bz, bw)
+  if(bl > 1e-6) {
+    bx /= bl
+    by /= bl
+    bz /= bl
+    bw /= bl
+  } else {
+    bx = by = bz = 0.0
+    bw = 1.0
+  }
+
+  var rotation = this.computedRotation
+  var ax = rotation[0]
+  var ay = rotation[1]
+  var az = rotation[2]
+  var aw = rotation[3]
+
+  var cx = ax*bw + aw*bx + ay*bz - az*by
+  var cy = ay*bw + aw*by + az*bx - ax*bz
+  var cz = az*bw + aw*bz + ax*by - ay*bx
+  var cw = aw*bw - ax*bx - ay*by - az*bz
+  
+  //Apply roll
+  if(dz) {
+    bx = fx
+    by = fy
+    bz = fz
+    var s = Math.sin(dz) / len3(bx, by, bz)
+    bx *= s
+    by *= s
+    bz *= s
+    bw = Math.cos(dx)
+    cx = cx*bw + cw*bx + cy*bz - cz*by
+    cy = cy*bw + cw*by + cz*bx - cx*bz
+    cz = cz*bw + cw*bz + cx*by - cy*bx
+    cw = cw*bw - cx*bx - cy*by - cz*bz
+  }
+
+  var cl = len4(cx, cy, cz, cw)
+  if(cl > 1e-6) {
+    cx /= cl
+    cy /= cl
+    cz /= cl
+    cw /= cl
+  } else {
+    cx = cy = cz = 0.0
+    cw = 1.0
+  }
+
+  this.rotation.set(t, cx, cy, cz, cw)
+}
+
+proto.lookAt = function(t, eye, center, up) {
+  this.recalcMatrix(t)
+
+  center = center || this.computedCenter
+  eye    = eye    || this.computedEye
+  up     = up     || this.computedUp
+
+  var mat = this.computedMatrix
+  lookAt(mat, eye, center, up)
+
+  var rotation = this.computedRotation
+  quatFromFrame(rotation,
+    mat[0], mat[1], mat[2],
+    mat[4], mat[5], mat[6],
+    mat[8], mat[9], mat[10])
+  normalize4(rotation, rotation)
+  this.rotation.set(t, rotation[0], rotation[1], rotation[2], rotation[3])
+
+  var fl = 0.0
+  for(var i=0; i<3; ++i) {
+    fl += Math.pow(center[i] - eye[i], 2)
+  }
+  this.radius.set(t, 0.5 * Math.log(Math.max(fl, 1e-6)))
+
+  this.center.set(t, center[0], center[1], center[2])
+}
+
+proto.translate = function(t, dx, dy, dz) {
+  this.center.move(t,
+    dx||0.0,
+    dy||0.0,
+    dz||0.0)
+}
+
+proto.setMatrix = function(t, matrix) {
+
+  var rotation = this.computedRotation
+  quatFromFrame(rotation,
+    matrix[0], matrix[1], matrix[2],
+    matrix[4], matrix[5], matrix[6],
+    matrix[8], matrix[9], matrix[10])
+  normalize4(rotation, rotation)
+  this.rotation.set(t, rotation[0], rotation[1], rotation[2], rotation[3])
+
+  var mat = this.computedMatrix
+  invert44(mat, matrix)
+  var w = mat[15]
+  if(Math.abs(w) > 1e-6) {
+    var cx = mat[12]/w
+    var cy = mat[13]/w
+    var cz = mat[14]/w
+
+    this.recalcMatrix(t)  
+    var r = Math.exp(this.computedRadius[0])
+    this.center.set(t, cx-mat[2]*r, cy-mat[6]*r, cz-mat[10]*r)
+    this.radius.idle(t)
+  } else {
+    this.center.idle(t)
+    this.radius.idle(t)
+  }
+}
+
+proto.setDistance = function(t, d) {
+  if(d > 0) {
+    this.radius.set(t, Math.log(d))
+  }
+}
+
+proto.setDistanceLimits = function(lo, hi) {
+  if(lo > 0) {
+    lo = Math.log(lo)
+  } else {
+    lo = -Infinity    
+  }
+  if(hi > 0) {
+    hi = Math.log(hi)
+  } else {
+    hi = Infinity
+  }
+  hi = Math.max(hi, lo)
+  this.radius.bounds[0][0] = lo
+  this.radius.bounds[1][0] = hi
+}
+
+proto.getDistanceLimits = function(out) {
+  var bounds = this.radius.bounds
+  if(out) {
+    out[0] = Math.exp(bounds[0][0])
+    out[1] = Math.exp(bounds[1][0])
+    return out
+  }
+  return [ Math.exp(bounds[0][0]), Math.exp(bounds[1][0]) ]
+}
+
+proto.toJSON = function() {
+  this.recalcMatrix(this.lastT())
+  return {
+    center:   this.computedCenter.slice(),
+    rotation: this.computedRotation.slice(),
+    distance: Math.log(this.computedRadius[0]),
+    zoomMin:  this.radius.bounds[0][0],
+    zoomMax:  this.radius.bounds[1][0]
+  }
+}
+
+proto.fromJSON = function(options) {
+  var t = this.lastT()
+  var c = options.center
+  if(c) {
+    this.center.set(t, c[0], c[1], c[2])
+  }
+  var r = options.rotation
+  if(r) {
+    this.rotation.set(t, r[0], r[1], r[2], r[3])
+  }
+  var d = options.distance
+  if(d && d > 0) {
+    this.radius.set(t, Math.log(d))
+  }
+  this.setDistanceLimits(options.zoomMin, options.zoomMax)
+}
+
+function createOrbitController(options) {
+  options = options || {}
+  var center   = options.center   || [0,0,0]
+  var rotation = options.rotation || [0,0,0,1]
+  var radius   = options.radius   || 1.0
+
+  center = [].slice.call(center, 0, 3)
+  rotation = [].slice.call(rotation, 0, 4)
+  normalize4(rotation, rotation)
+
+  var result = new OrbitCameraController(
+    rotation,
+    center,
+    Math.log(radius))
+
+  result.setDistanceLimits(options.zoomMin, options.zoomMax)
+
+  if('eye' in options || 'up' in options) {
+    result.lookAt(0, options.eye, options.center, options.up)
+  }
+
+  return result
+}
+},{"./lib/quatFromFrame":35,"filtered-vector":19,"gl-mat4/fromQuat":91,"gl-mat4/invert":94,"gl-mat4/lookAt":95}],37:[function(require,module,exports){
+'use strict'
+
+module.exports = createTurntableController
+
+var filterVector = require('filtered-vector')
+var invert44     = require('gl-mat4/invert')
+var rotateM      = require('gl-mat4/rotate')
+var cross        = require('gl-vec3/cross')
+var normalize3   = require('gl-vec3/normalize')
+var dot3         = require('gl-vec3/dot')
+
+function len3(x, y, z) {
+  return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2))
+}
+
+function clamp1(x) {
+  return Math.min(1.0, Math.max(-1.0, x))
+}
+
+function findOrthoPair(v) {
+  var vx = Math.abs(v[0])
+  var vy = Math.abs(v[1])
+  var vz = Math.abs(v[2])
+
+  var u = [0,0,0]
+  if(vx > Math.max(vy, vz)) {
+    u[2] = 1
+  } else if(vy > Math.max(vx, vz)) {
+    u[0] = 1
+  } else {
+    u[1] = 1
+  }
+
+  var vv = 0
+  var uv = 0
+  for(var i=0; i<3; ++i ) {
+    vv += v[i] * v[i]
+    uv += u[i] * v[i]
+  }
+  for(var i=0; i<3; ++i) {
+    u[i] -= (uv / vv) *  v[i]
+  }
+  normalize3(u, u)
+  return u
+}
+
+function TurntableController(zoomMin, zoomMax, center, up, right, radius, theta, phi) {
+  this.center = filterVector(center)
+  this.up     = filterVector(up)
+  this.right  = filterVector(right)
+  this.radius = filterVector([radius])
+  this.angle  = filterVector([theta, phi])
+  this.angle.bounds = [[-Infinity,-Math.PI/2], [Infinity,Math.PI/2]]
+  this.setDistanceLimits(zoomMin, zoomMax)
+
+  this.computedCenter = this.center.curve(0)
+  this.computedUp     = this.up.curve(0)
+  this.computedRight  = this.right.curve(0)
+  this.computedRadius = this.radius.curve(0)
+  this.computedAngle  = this.angle.curve(0)
+  this.computedToward = [0,0,0]
+  this.computedEye    = [0,0,0]
+  this.computedMatrix = new Array(16)
+  for(var i=0; i<16; ++i) {
+    this.computedMatrix[i] = 0.5
+  }
+
+  this.recalcMatrix(0)
+}
+
+var proto = TurntableController.prototype
+
+proto.setDistanceLimits = function(minDist, maxDist) {
+  if(minDist > 0) {
+    minDist = Math.log(minDist)
+  } else {
+    minDist = -Infinity
+  }
+  if(maxDist > 0) {
+    maxDist = Math.log(maxDist)
+  } else {
+    maxDist = Infinity
+  }
+  maxDist = Math.max(maxDist, minDist)
+  this.radius.bounds[0][0] = minDist
+  this.radius.bounds[1][0] = maxDist
+}
+
+proto.getDistanceLimits = function(out) {
+  var bounds = this.radius.bounds[0]
+  if(out) {
+    out[0] = Math.exp(bounds[0][0])
+    out[1] = Math.exp(bounds[1][0])
+    return out
+  }
+  return [ Math.exp(bounds[0][0]), Math.exp(bounds[1][0]) ]
+}
+
+proto.recalcMatrix = function(t) {
+  //Recompute curves
+  this.center.curve(t)
+  this.up.curve(t)
+  this.right.curve(t)
+  this.radius.curve(t)
+  this.angle.curve(t)
+
+  //Compute frame for camera matrix
+  var up     = this.computedUp
+  var right  = this.computedRight
+  var uu = 0.0
+  var ur = 0.0
+  for(var i=0; i<3; ++i) {
+    ur += up[i] * right[i]
+    uu += up[i] * up[i]
+  }
+  var ul = Math.sqrt(uu)
+  var rr = 0.0
+  for(var i=0; i<3; ++i) {
+    right[i] -= up[i] * ur / uu
+    rr       += right[i] * right[i]
+    up[i]    /= ul
+  }
+  var rl = Math.sqrt(rr)
+  for(var i=0; i<3; ++i) {
+    right[i] /= rl
+  }
+
+  //Compute toward vector
+  var toward = this.computedToward
+  cross(toward, up, right)
+  normalize3(toward, toward)
+
+  //Compute angular parameters
+  var radius = Math.exp(this.computedRadius[0])
+  var theta  = this.computedAngle[0]
+  var phi    = this.computedAngle[1]
+
+  var ctheta = Math.cos(theta)
+  var stheta = Math.sin(theta)
+  var cphi   = Math.cos(phi)
+  var sphi   = Math.sin(phi)
+
+  var center = this.computedCenter
+
+  var wx = ctheta * cphi 
+  var wy = stheta * cphi
+  var wz = sphi
+
+  var sx = -ctheta * sphi
+  var sy = -stheta * sphi
+  var sz = cphi
+
+  var eye = this.computedEye
+  var mat = this.computedMatrix
+  for(var i=0; i<3; ++i) {
+    var x      = wx * right[i] + wy * toward[i] + wz * up[i]
+    mat[4*i+1] = sx * right[i] + sy * toward[i] + sz * up[i]
+    mat[4*i+2] = x
+    mat[4*i+3] = 0.0
+  }
+
+  var ax = mat[1]
+  var ay = mat[5]
+  var az = mat[9]
+  var bx = mat[2]
+  var by = mat[6]
+  var bz = mat[10]
+  var cx = ay * bz - az * by
+  var cy = az * bx - ax * bz
+  var cz = ax * by - ay * bx
+  var cl = len3(cx, cy, cz)
+  cx /= cl
+  cy /= cl
+  cz /= cl
+  mat[0] = cx
+  mat[4] = cy
+  mat[8] = cz
+
+  for(var i=0; i<3; ++i) {
+    eye[i] = center[i] + mat[2+4*i]*radius
+  }
+
+  for(var i=0; i<3; ++i) {
+    var rr = 0.0
+    for(var j=0; j<3; ++j) {
+      rr += mat[i+4*j] * eye[j]
+    }
+    mat[12+i] = -rr
+  }
+  mat[15] = 1.0
+}
+
+proto.getMatrix = function(t, result) {
+  this.recalcMatrix(t)
+  var mat = this.computedMatrix
+  if(result) {
+    for(var i=0; i<16; ++i) {
+      result[i] = mat[i]
+    }
+    return result
+  }
+  return mat
+}
+
+var zAxis = [0,0,0]
+proto.rotate = function(t, dtheta, dphi, droll) {
+  this.angle.move(t, dtheta, dphi)
+  if(droll) {
+    this.recalcMatrix(t)
+
+    var mat = this.computedMatrix
+    zAxis[0] = mat[2]
+    zAxis[1] = mat[6]
+    zAxis[2] = mat[10]
+
+    var up     = this.computedUp
+    var right  = this.computedRight
+    var toward = this.computedToward
+
+    for(var i=0; i<3; ++i) {
+      mat[4*i]   = up[i]
+      mat[4*i+1] = right[i]
+      mat[4*i+2] = toward[i]
+    }
+    rotateM(mat, mat, droll, zAxis)
+    for(var i=0; i<3; ++i) {
+      up[i] =    mat[4*i]
+      right[i] = mat[4*i+1]
+    }
+
+    this.up.set(t, up[0], up[1], up[2])
+    this.right.set(t, right[0], right[1], right[2])
+  }
+}
+
+proto.pan = function(t, dx, dy, dz) {
+  dx = dx || 0.0
+  dy = dy || 0.0
+  dz = dz || 0.0
+
+  this.recalcMatrix(t)
+  var mat = this.computedMatrix
+
+  var dist = Math.exp(this.computedRadius[0])
+
+  var ux = mat[1]
+  var uy = mat[5]
+  var uz = mat[9]
+  var ul = len3(ux, uy, uz)
+  ux /= ul
+  uy /= ul
+  uz /= ul
+
+  var rx = mat[0]
+  var ry = mat[4]
+  var rz = mat[8]
+  var ru = rx * ux + ry * uy + rz * uz
+  rx -= ux * ru
+  ry -= uy * ru
+  rz -= uz * ru
+  var rl = len3(rx, ry, rz)
+  rx /= rl
+  ry /= rl
+  rz /= rl
+
+  var vx = rx * dx + ux * dy
+  var vy = ry * dx + uy * dy
+  var vz = rz * dx + uz * dy
+  this.center.move(t, vx, vy, vz)
+
+  //Update z-component of radius
+  var radius = Math.exp(this.computedRadius[0])
+  radius = Math.max(1e-4, radius + dz)
+  this.radius.set(t, Math.log(radius))
+}
+
+proto.translate = function(t, dx, dy, dz) {
+  this.center.move(t,
+    dx||0.0,
+    dy||0.0,
+    dz||0.0)
+}
+
+//Recenters the coordinate axes
+proto.setMatrix = function(t, mat, axes, noSnap) {
+  
+  //Get the axes for tare
+  var ushift = 1
+  if(typeof axes === 'number') {
+    ushift = (axes)|0
+  } 
+  if(ushift < 0 || ushift > 3) {
+    ushift = 1
+  }
+  var vshift = (ushift + 2) % 3
+  var fshift = (ushift + 1) % 3
+
+  //Recompute state for new t value
+  if(!mat) { 
+    this.recalcMatrix(t)
+    mat = this.computedMatrix
+  }
+
+  //Get right and up vectors
+  var ux = mat[ushift]
+  var uy = mat[ushift+4]
+  var uz = mat[ushift+8]
+  if(!noSnap) {
+    var ul = len3(ux, uy, uz)
+    ux /= ul
+    uy /= ul
+    uz /= ul
+  } else {
+    var ax = Math.abs(ux)
+    var ay = Math.abs(uy)
+    var az = Math.abs(uz)
+    var am = Math.max(ax,ay,az)
+    if(ax === am) {
+      ux = (ux < 0) ? -1 : 1
+      uy = uz = 0
+    } else if(az === am) {
+      uz = (uz < 0) ? -1 : 1
+      ux = uy = 0
+    } else {
+      uy = (uy < 0) ? -1 : 1
+      ux = uz = 0
+    }
+  }
+
+  var rx = mat[vshift]
+  var ry = mat[vshift+4]
+  var rz = mat[vshift+8]
+  var ru = rx * ux + ry * uy + rz * uz
+  rx -= ux * ru
+  ry -= uy * ru
+  rz -= uz * ru
+  var rl = len3(rx, ry, rz)
+  rx /= rl
+  ry /= rl
+  rz /= rl
+  
+  var fx = uy * rz - uz * ry
+  var fy = uz * rx - ux * rz
+  var fz = ux * ry - uy * rx
+  var fl = len3(fx, fy, fz)
+  fx /= fl
+  fy /= fl
+  fz /= fl
+
+  this.center.jump(t, ex, ey, ez)
+  this.radius.idle(t)
+  this.up.jump(t, ux, uy, uz)
+  this.right.jump(t, rx, ry, rz)
+
+  var phi, theta
+  if(ushift === 2) {
+    var cx = mat[1]
+    var cy = mat[5]
+    var cz = mat[9]
+    var cr = cx * rx + cy * ry + cz * rz
+    var cf = cx * fx + cy * fy + cz * fz
+    if(tu < 0) {
+      phi = -Math.PI/2
+    } else {
+      phi = Math.PI/2
+    }
+    theta = Math.atan2(cf, cr)
+  } else {
+    var tx = mat[2]
+    var ty = mat[6]
+    var tz = mat[10]
+    var tu = tx * ux + ty * uy + tz * uz
+    var tr = tx * rx + ty * ry + tz * rz
+    var tf = tx * fx + ty * fy + tz * fz
+
+    phi = Math.asin(clamp1(tu))
+    theta = Math.atan2(tf, tr)
+  }
+
+  this.angle.jump(t, theta, phi)
+
+  this.recalcMatrix(t)
+  var dx = mat[2]
+  var dy = mat[6]
+  var dz = mat[10]
+
+  var imat = this.computedMatrix
+  invert44(imat, mat)
+  var w  = imat[15]
+  var ex = imat[12] / w
+  var ey = imat[13] / w
+  var ez = imat[14] / w
+
+  var gs = Math.exp(this.computedRadius[0])
+  this.center.jump(t, ex-dx*gs, ey-dy*gs, ez-dz*gs)
+}
+
+proto.lastT = function() {
+  return Math.max(
+    this.center.lastT(),
+    this.up.lastT(),
+    this.right.lastT(),
+    this.radius.lastT(),
+    this.angle.lastT())
+}
+
+proto.idle = function(t) {
+  this.center.idle(t)
+  this.up.idle(t)
+  this.right.idle(t)
+  this.radius.idle(t)
+  this.angle.idle(t)
+}
+
+proto.flush = function(t) {
+  this.center.flush(t)
+  this.up.flush(t)
+  this.right.flush(t)
+  this.radius.flush(t)
+  this.angle.flush(t)
+}
+
+proto.setDistance = function(t, d) {
+  if(d > 0) {
+    this.radius.set(t, Math.log(d))
+  }
+}
+
+proto.lookAt = function(t, eye, center, up) {
+  this.recalcMatrix(t)
+
+  eye    = eye    || this.computedEye
+  center = center || this.computedCenter
+  up     = up     || this.computedUp
+
+  var ux = up[0]
+  var uy = up[1]
+  var uz = up[2]
+  var ul = len3(ux, uy, uz)
+  if(ul < 1e-6) {
+    return
+  }
+  ux /= ul
+  uy /= ul
+  uz /= ul
+
+  var tx = eye[0] - center[0]
+  var ty = eye[1] - center[1]
+  var tz = eye[2] - center[2]
+  var tl = len3(tx, ty, tz)
+  if(tl < 1e-6) {
+    return
+  }
+  tx /= tl
+  ty /= tl
+  tz /= tl
+
+  var right = this.computedRight
+  var rx = right[0]
+  var ry = right[1]
+  var rz = right[2]
+  var ru = ux*rx + uy*ry + uz*rz
+  rx -= ru * ux
+  ry -= ru * uy
+  rz -= ru * uz
+  var rl = len3(rx, ry, rz)
+
+  if(rl < 0.01) {
+    rx = uy * tz - uz * ty
+    ry = uz * tx - ux * tz
+    rz = ux * ty - uy * tx
+    rl = len3(rx, ry, rz)
+    if(rl < 1e-6) {
+      return
+    }
+  }
+  rx /= rl
+  ry /= rl
+  rz /= rl
+
+  this.up.set(t, ux, uy, uz)
+  this.right.set(t, rx, ry, rz)
+  this.center.set(t, center[0], center[1], center[2])
+  this.radius.set(t, Math.log(tl))
+
+  var fx = uy * rz - uz * ry
+  var fy = uz * rx - ux * rz
+  var fz = ux * ry - uy * rx
+  var fl = len3(fx, fy, fz)
+  fx /= fl
+  fy /= fl
+  fz /= fl
+
+  var tu = ux*tx + uy*ty + uz*tz
+  var tr = rx*tx + ry*ty + rz*tz
+  var tf = fx*tx + fy*ty + fz*tz
+
+  var phi   = Math.asin(clamp1(tu))
+  var theta = Math.atan2(tf, tr)
+
+  var angleState = this.angle._state
+  var lastTheta  = angleState[angleState.length-1]
+  var lastPhi    = angleState[angleState.length-2]
+  lastTheta      = lastTheta % (2.0 * Math.PI)
+  var dp = Math.abs(lastTheta + 2.0 * Math.PI - theta)
+  var d0 = Math.abs(lastTheta - theta)
+  var dn = Math.abs(lastTheta - 2.0 * Math.PI - theta)
+  if(dp < d0) {
+    lastTheta += 2.0 * Math.PI
+  }
+  if(dn < d0) {
+    lastTheta -= 2.0 * Math.PI
+  }
+
+  this.angle.jump(this.angle.lastT(), lastTheta, lastPhi)
+  this.angle.set(t, theta, phi)
+}
+
+function createTurntableController(options) {
+  options = options || {}
+
+  var center = options.center || [0,0,0]
+  var up     = options.up     || [0,1,0]
+  var right  = options.right  || findOrthoPair(up)
+  var radius = options.radius || 1.0
+  var theta  = options.theta  || 0.0
+  var phi    = options.phi    || 0.0
+
+  center = [].slice.call(center, 0, 3)
+
+  up = [].slice.call(up, 0, 3)
+  normalize3(up, up)
+
+  right = [].slice.call(right, 0, 3)
+  normalize3(right, right)
+
+  if('eye' in options) {
+    var eye = options.eye
+    var toward = [
+      eye[0]-center[0],
+      eye[1]-center[1],
+      eye[2]-center[2]
+    ]
+    cross(right, toward, up)
+    if(len3(right[0], right[1], right[2]) < 1e-6) {
+      right = findOrthoPair(up)
+    } else {
+      normalize3(right, right)
+    }
+
+    radius = len3(toward[0], toward[1], toward[2])
+
+    var ut = dot3(up, toward) / radius
+    var rt = dot3(right, toward) / radius
+    phi    = Math.acos(ut)
+    theta  = Math.acos(rt)
+  }
+
+  //Use logarithmic coordinates for radius
+  radius = Math.log(radius)
+
+  //Return the controller
+  return new TurntableController(
+    options.zoomMin,
+    options.zoomMax,
+    center,
+    up,
+    right,
+    radius,
+    theta,
+    phi)
+}
+},{"filtered-vector":19,"gl-mat4/invert":94,"gl-mat4/rotate":98,"gl-vec3/cross":22,"gl-vec3/dot":23,"gl-vec3/normalize":26}],38:[function(require,module,exports){
+'use strict'
+
+module.exports = createViewController
+
+var createTurntable = require('turntable-camera-controller')
+var createOrbit     = require('orbit-camera-controller')
+var createMatrix    = require('matrix-camera-controller')
+
+function ViewController(controllers, mode) {
+  this._controllerNames = Object.keys(controllers)
+  this._controllerList = this._controllerNames.map(function(n) {
+    return controllers[n]
+  })
+  this._mode   = mode
+  this._active = controllers[mode]
+  if(!this._active) {
+    this._mode   = 'turntable'
+    this._active = controllers.turntable
+  }
+  this.modes = this._controllerNames
+  this.computedMatrix = this._active.computedMatrix
+  this.computedEye    = this._active.computedEye
+  this.computedUp     = this._active.computedUp
+  this.computedCenter = this._active.computedCenter
+  this.computedRadius = this._active.computedRadius
+}
+
+var proto = ViewController.prototype
+
+var COMMON_METHODS = [
+  ['flush', 1],
+  ['idle', 1],
+  ['lookAt', 4],
+  ['rotate', 4],
+  ['pan', 4],
+  ['translate', 4],
+  ['setMatrix', 2],
+  ['setDistanceLimits', 2],
+  ['setDistance', 2]
+]
+
+COMMON_METHODS.forEach(function(method) {
+  var name = method[0]
+  var argNames = []
+  for(var i=0; i<method[1]; ++i) {
+    argNames.push('a'+i)
+  }
+  var code = 'var cc=this._controllerList;for(var i=0;i<cc.length;++i){cc[i].'+method[0]+'('+argNames.join()+')}'
+  proto[name] = Function.apply(null, argNames.concat(code))
+})
+
+proto.recalcMatrix = function(t) {
+  this._active.recalcMatrix(t)
+}
+
+proto.getDistance = function(t) {
+  return this._active.getDistance(t)
+}
+proto.getDistanceLimits = function(out) {
+  return this._active.getDistanceLimits(out)
+}
+
+proto.lastT = function() {
+  return this._active.lastT()
+}
+
+proto.setMode = function(mode) {
+  if(mode === this._mode) {
+    return
+  }
+  var idx = this._controllerNames.indexOf(mode)
+  if(idx < 0) {
+    return
+  }
+  var prev  = this._active
+  var next  = this._controllerList[idx]
+  var lastT = Math.max(prev.lastT(), next.lastT())
+
+  prev.recalcMatrix(lastT)
+  next.setMatrix(lastT, prev.computedMatrix)
+  
+  this._active = next
+  this._mode   = mode
+
+  //Update matrix properties
+  this.computedMatrix = this._active.computedMatrix
+  this.computedEye    = this._active.computedEye
+  this.computedUp     = this._active.computedUp
+  this.computedCenter = this._active.computedCenter
+  this.computedRadius = this._active.computedRadius
+}
+
+proto.getMode = function() {
+  return this._mode
+}
+
+function createViewController(options) {
+  options = options || {}
+
+  var eye       = options.eye    || [0,0,1]
+  var center    = options.center || [0,0,0]
+  var up        = options.up     || [0,1,0]
+  var limits    = options.distanceLimits || [0, Infinity]
+  var mode      = options.mode   || 'turntable'
+
+  var turntable = createTurntable()
+  var orbit     = createOrbit()
+  var matrix    = createMatrix()
+
+  turntable.setDistanceLimits(limits[0], limits[1])
+  turntable.lookAt(0, eye, center, up)
+  orbit.setDistanceLimits(limits[0], limits[1])
+  orbit.lookAt(0, eye, center, up)
+  matrix.setDistanceLimits(limits[0], limits[1])
+  matrix.lookAt(0, eye, center, up)
+
+  return new ViewController({
+    turntable: turntable,
+    orbit: orbit,
+    matrix: matrix
+  }, mode)
+}
+},{"matrix-camera-controller":27,"orbit-camera-controller":36,"turntable-camera-controller":37}],39:[function(require,module,exports){
+module.exports = alphaShape
+
+var ac = require('alpha-complex')
+var bnd = require('simplicial-complex-boundary')
+
+function alphaShape(alpha, points) {
+  return bnd(ac(alpha, points))
+}
+},{"alpha-complex":40,"simplicial-complex-boundary":43}],40:[function(require,module,exports){
+'use strict'
+
+module.exports = alphaComplex
+
+var delaunay = require('delaunay-triangulate')
+var circumradius = require('circumradius')
+
+function alphaComplex(alpha, points) {
+  return delaunay(points).filter(function(cell) {
+    var simplex = new Array(cell.length)
+    for(var i=0; i<cell.length; ++i) {
+      simplex[i] = points[cell[i]]
+    }
+    return circumradius(simplex) * alpha < 1
+  })
+}
+},{"circumradius":41,"delaunay-triangulate":71}],41:[function(require,module,exports){
+module.exports = circumradius
+
+var circumcenter = require('circumcenter')
+
+function circumradius(points) {
+  var center = circumcenter(points)
+  var avgDist = 0.0
+  for(var i=0; i<points.length; ++i) {
+    var p = points[i]
+    for(var j=0; j<center.length; ++j) {
+      avgDist += Math.pow(p[j] - center[j], 2)
+    }
+  }
+  return Math.sqrt(avgDist / points.length)
+}
+},{"circumcenter":42}],42:[function(require,module,exports){
+"use strict"
+
+var dup = require("dup")
+var solve = require("robust-linear-solve")
+
+function dot(a, b) {
+  var s = 0.0
+  var d = a.length
+  for(var i=0; i<d; ++i) {
+    s += a[i] * b[i]
+  }
+  return s
+}
+
+function barycentricCircumcenter(points) {
+  var N = points.length
+  if(N === 0) {
+    return []
+  }
+  
+  var D = points[0].length
+  var A = dup([points.length+1, points.length+1], 1.0)
+  var b = dup([points.length+1], 1.0)
+  A[N][N] = 0.0
+  for(var i=0; i<N; ++i) {
+    for(var j=0; j<=i; ++j) {
+      A[j][i] = A[i][j] = 2.0 * dot(points[i], points[j])
+    }
+    b[i] = dot(points[i], points[i])
+  }
+  var x = solve(A, b)
+
+  var denom = 0.0
+  var h = x[N+1]
+  for(var i=0; i<h.length; ++i) {
+    denom += h[i]
+  }
+
+  var y = new Array(N)
+  for(var i=0; i<N; ++i) {
+    var h = x[i]
+    var numer = 0.0
+    for(var j=0; j<h.length; ++j) {
+      numer += h[j]
+    }
+    y[i] =  numer / denom
+  }
+
+  return y
+}
+
+function circumcenter(points) {
+  if(points.length === 0) {
+    return []
+  }
+  var D = points[0].length
+  var result = dup([D])
+  var weights = barycentricCircumcenter(points)
+  for(var i=0; i<points.length; ++i) {
+    for(var j=0; j<D; ++j) {
+      result[j] += points[i][j] * weights[i]
+    }
+  }
+  return result
+}
+
+circumcenter.barycenetric = barycentricCircumcenter
+module.exports = circumcenter
+},{"dup":72,"robust-linear-solve":211}],43:[function(require,module,exports){
+'use strict'
+
+module.exports = boundary
+
+var bnd = require('boundary-cells')
+var reduce = require('reduce-simplicial-complex')
+
+function boundary(cells) {
+  return reduce(bnd(cells))
+}
+
+},{"boundary-cells":44,"reduce-simplicial-complex":47}],44:[function(require,module,exports){
+"use strict"
+
+module.exports = boundary
+
+function boundary(cells) {
+  var n = cells.length
+  var sz = 0
+  for(var i=0; i<n; ++i) {
+    sz += cells[i].length
+  }
+  var result = new Array(sz)
+  var ptr = 0
+  for(var i=0; i<n; ++i) {
+    var c = cells[i]
+    var d = c.length
+    for(var j=0; j<d; ++j) {
+      var b = result[ptr++] = new Array(d-1)
+      for(var k=1; k<d; ++k) {
+        b[k-1] = c[(j+k)%d]
+      }
+    }
+  }
+  return result
+}
+
+},{}],45:[function(require,module,exports){
+'use strict'
+
+module.exports = orientation
+
+function orientation(s) {
+  var p = 1
+  for(var i=1; i<s.length; ++i) {
+    for(var j=0; j<i; ++j) {
+      if(s[i] < s[j]) {
+        p = -p
+      } else if(s[j] === s[i]) {
+        return 0
+      }
+    }
+  }
+  return p
+}
+
+},{}],46:[function(require,module,exports){
+'use strict'
+
+var compareCells = require('compare-cell')
+var parity = require('cell-orientation')
+
+module.exports = compareOrientedCells
+
+function compareOrientedCells(a, b) {
+  return compareCells(a, b) || parity(a) - parity(b)
+}
+
+},{"cell-orientation":45,"compare-cell":59}],47:[function(require,module,exports){
+'use strict'
+
+var compareCell = require('compare-cell')
+var compareOrientedCell = require('compare-oriented-cell')
+var orientation = require('cell-orientation')
+
+module.exports = reduceCellComplex
+
+function reduceCellComplex(cells) {
+  cells.sort(compareOrientedCell)
+  var n = cells.length
+  var ptr = 0
+  for(var i=0; i<n; ++i) {
+    var c = cells[i]
+    var o = orientation(c)
+    if(o === 0) {
+      continue
+    }
+    if(ptr > 0) {
+      var f = cells[ptr-1]
+      if(compareCell(c, f) === 0 &&
+         orientation(f)    !== o) {
+        ptr -= 1
+        continue
+      }
+    }
+    cells[ptr++] = c
+  }
+  cells.length = ptr
+  return cells
+}
+
+},{"cell-orientation":45,"compare-cell":59,"compare-oriented-cell":46}],48:[function(require,module,exports){
+'use strict';
+
+var arraytools  = function () {
+
+  var that = {};
+
+  var RGB_REGEX =  /^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,.*)?\)$/;
+  var RGB_GROUP_REGEX = /^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,?\s*(.*)?\)$/;
+
+  function isPlainObject (v) {
+    return !Array.isArray(v) && v !== null && typeof v === 'object';
+  }
+
+  function linspace (start, end, num) {
+    var inc = (end - start) / Math.max(num - 1, 1);
+    var a = [];
+    for( var ii = 0; ii < num; ii++)
+      a.push(start + ii*inc);
+    return a;
+  }
+
+  function zip () {
+      var arrays = [].slice.call(arguments);
+      var lengths = arrays.map(function (a) {return a.length;});
+      var len = Math.min.apply(null, lengths);
+      var zipped = [];
+      for (var i = 0; i < len; i++) {
+          zipped[i] = [];
+          for (var j = 0; j < arrays.length; ++j) {
+              zipped[i][j] = arrays[j][i];
+          }
+      }
+      return zipped;
+  }
+
+  function zip3 (a, b, c) {
+      var len = Math.min.apply(null, [a.length, b.length, c.length]);
+      var result = [];
+      for (var n = 0; n < len; n++) {
+          result.push([a[n], b[n], c[n]]);
+      }
+      return result;
+  }
+
+  function sum (A) {
+    var acc = 0;
+    accumulate(A, acc);
+    function accumulate(x) {
+      for (var i = 0; i < x.length; i++) {
+        if (Array.isArray(x[i]))
+          accumulate(x[i], acc);
+        else
+          acc += x[i];
+      }
+    }
+    return acc;
+  }
+
+  function copy2D (arr) {
+    var carr = [];
+    for (var i = 0; i < arr.length; ++i) {
+      carr[i] = [];
+      for (var j = 0; j < arr[i].length; ++j) {
+        carr[i][j] = arr[i][j];
+      }
+    }
+
+    return carr;
+  }
+
+
+  function copy1D (arr) {
+    var carr = [];
+    for (var i = 0; i < arr.length; ++i) {
+      carr[i] = arr[i];
+    }
+
+    return carr;
+  }
+
+
+  function isEqual(arr1, arr2) {
+    if(arr1.length !== arr2.length)
+      return false;
+    for(var i = arr1.length; i--;) {
+      if(arr1[i] !== arr2[i])
+        return false;
+    }
+
+    return true;
+  }
+
+
+  function str2RgbArray(str, twoFiftySix) {
+    // convert hex or rbg strings to 0->1 or 0->255 rgb array
+    var rgb,
+        match;
+
+    if (typeof str !== 'string') return str;
+
+    rgb = [];
+    // hex notation
+    if (str[0] === '#') {
+      str = str.substr(1) // remove hash
+      if (str.length === 3) str += str // fff -> ffffff
+      match = parseInt(str, 16);
+      rgb[0] = ((match >> 16) & 255);
+      rgb[1] = ((match >> 8) & 255);
+      rgb[2] = (match & 255);
+    }
+
+    // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation
+    else if (RGB_REGEX.test(str)) {
+      match = str.match(RGB_GROUP_REGEX);
+      rgb[0] = parseInt(match[1]);
+      rgb[1] = parseInt(match[2]);
+      rgb[2] = parseInt(match[3]);
+    }
+
+    if (!twoFiftySix) {
+      for (var j=0; j<3; ++j) rgb[j] = rgb[j]/255
+    }
+
+
+    return rgb;
+  }
+
+
+  function str2RgbaArray(str, twoFiftySix) {
+    // convert hex or rbg strings to 0->1 or 0->255 rgb array
+    var rgb,
+        match;
+
+    if (typeof str !== 'string') return str;
+
+    rgb = [];
+    // hex notation
+    if (str[0] === '#') {
+      str = str.substr(1) // remove hash
+      if (str.length === 3) str += str // fff -> ffffff
+      match = parseInt(str, 16);
+      rgb[0] = ((match >> 16) & 255);
+      rgb[1] = ((match >> 8) & 255);
+      rgb[2] = (match & 255);
+    }
+
+    // rgb(34, 34, 127) or rgba(34, 34, 127, 0.1) notation
+    else if (RGB_REGEX.test(str)) {
+      match = str.match(RGB_GROUP_REGEX);
+      rgb[0] = parseInt(match[1]);
+      rgb[1] = parseInt(match[2]);
+      rgb[2] = parseInt(match[3]);
+      if (match[4]) rgb[3] = parseFloat(match[4]);
+      else rgb[3] = 1.0;
+    }
+
+
+
+    if (!twoFiftySix) {
+      for (var j=0; j<3; ++j) rgb[j] = rgb[j]/255
+    }
+
+
+    return rgb;
+  }
+
+
+
+
+
+  that.isPlainObject = isPlainObject;
+  that.linspace = linspace;
+  that.zip3 = zip3;
+  that.sum = sum;
+  that.zip = zip;
+  that.isEqual = isEqual;
+  that.copy2D = copy2D;
+  that.copy1D = copy1D;
+  that.str2RgbArray = str2RgbArray;
+  that.str2RgbaArray = str2RgbaArray;
+
+  return that
+
+}
+
+
+module.exports = arraytools();
+
+},{}],49:[function(require,module,exports){
+/**
+ * Bit twiddling hacks for JavaScript.
+ *
+ * Author: Mikola Lysenko
+ *
+ * Ported from Stanford bit twiddling hack library:
+ *    http://graphics.stanford.edu/~seander/bithacks.html
+ */
+
+"use strict"; "use restrict";
+
+//Number of bits in an integer
+var INT_BITS = 32;
+
+//Constants
+exports.INT_BITS  = INT_BITS;
+exports.INT_MAX   =  0x7fffffff;
+exports.INT_MIN   = -1<<(INT_BITS-1);
+
+//Returns -1, 0, +1 depending on sign of x
+exports.sign = function(v) {
+  return (v > 0) - (v < 0);
+}
+
+//Computes absolute value of integer
+exports.abs = function(v) {
+  var mask = v >> (INT_BITS-1);
+  return (v ^ mask) - mask;
+}
+
+//Computes minimum of integers x and y
+exports.min = function(x, y) {
+  return y ^ ((x ^ y) & -(x < y));
+}
+
+//Computes maximum of integers x and y
+exports.max = function(x, y) {
+  return x ^ ((x ^ y) & -(x < y));
+}
+
+//Checks if a number is a power of two
+exports.isPow2 = function(v) {
+  return !(v & (v-1)) && (!!v);
+}
+
+//Computes log base 2 of v
+exports.log2 = function(v) {
+  var r, shift;
+  r =     (v > 0xFFFF) << 4; v >>>= r;
+  shift = (v > 0xFF  ) << 3; v >>>= shift; r |= shift;
+  shift = (v > 0xF   ) << 2; v >>>= shift; r |= shift;
+  shift = (v > 0x3   ) << 1; v >>>= shift; r |= shift;
+  return r | (v >> 1);
+}
+
+//Computes log base 10 of v
+exports.log10 = function(v) {
+  return  (v >= 1000000000) ? 9 : (v >= 100000000) ? 8 : (v >= 10000000) ? 7 :
+          (v >= 1000000) ? 6 : (v >= 100000) ? 5 : (v >= 10000) ? 4 :
+          (v >= 1000) ? 3 : (v >= 100) ? 2 : (v >= 10) ? 1 : 0;
+}
+
+//Counts number of bits
+exports.popCount = function(v) {
+  v = v - ((v >>> 1) & 0x55555555);
+  v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);
+  return ((v + (v >>> 4) & 0xF0F0F0F) * 0x1010101) >>> 24;
+}
+
+//Counts number of trailing zeros
+function countTrailingZeros(v) {
+  var c = 32;
+  v &= -v;
+  if (v) c--;
+  if (v & 0x0000FFFF) c -= 16;
+  if (v & 0x00FF00FF) c -= 8;
+  if (v & 0x0F0F0F0F) c -= 4;
+  if (v & 0x33333333) c -= 2;
+  if (v & 0x55555555) c -= 1;
+  return c;
+}
+exports.countTrailingZeros = countTrailingZeros;
+
+//Rounds to next power of 2
+exports.nextPow2 = function(v) {
+  v += v === 0;
+  --v;
+  v |= v >>> 1;
+  v |= v >>> 2;
+  v |= v >>> 4;
+  v |= v >>> 8;
+  v |= v >>> 16;
+  return v + 1;
+}
+
+//Rounds down to previous power of 2
+exports.prevPow2 = function(v) {
+  v |= v >>> 1;
+  v |= v >>> 2;
+  v |= v >>> 4;
+  v |= v >>> 8;
+  v |= v >>> 16;
+  return v - (v>>>1);
+}
+
+//Computes parity of word
+exports.parity = function(v) {
+  v ^= v >>> 16;
+  v ^= v >>> 8;
+  v ^= v >>> 4;
+  v &= 0xf;
+  return (0x6996 >>> v) & 1;
+}
+
+var REVERSE_TABLE = new Array(256);
+
+(function(tab) {
+  for(var i=0; i<256; ++i) {
+    var v = i, r = i, s = 7;
+    for (v >>>= 1; v; v >>>= 1) {
+      r <<= 1;
+      r |= v & 1;
+      --s;
+    }
+    tab[i] = (r << s) & 0xff;
+  }
+})(REVERSE_TABLE);
+
+//Reverse bits in a 32 bit word
+exports.reverse = function(v) {
+  return  (REVERSE_TABLE[ v         & 0xff] << 24) |
+          (REVERSE_TABLE[(v >>> 8)  & 0xff] << 16) |
+          (REVERSE_TABLE[(v >>> 16) & 0xff] << 8)  |
+           REVERSE_TABLE[(v >>> 24) & 0xff];
+}
+
+//Interleave bits of 2 coordinates with 16 bits.  Useful for fast quadtree codes
+exports.interleave2 = function(x, y) {
+  x &= 0xFFFF;
+  x = (x | (x << 8)) & 0x00FF00FF;
+  x = (x | (x << 4)) & 0x0F0F0F0F;
+  x = (x | (x << 2)) & 0x33333333;
+  x = (x | (x << 1)) & 0x55555555;
+
+  y &= 0xFFFF;
+  y = (y | (y << 8)) & 0x00FF00FF;
+  y = (y | (y << 4)) & 0x0F0F0F0F;
+  y = (y | (y << 2)) & 0x33333333;
+  y = (y | (y << 1)) & 0x55555555;
+
+  return x | (y << 1);
+}
+
+//Extracts the nth interleaved component
+exports.deinterleave2 = function(v, n) {
+  v = (v >>> n) & 0x55555555;
+  v = (v | (v >>> 1))  & 0x33333333;
+  v = (v | (v >>> 2))  & 0x0F0F0F0F;
+  v = (v | (v >>> 4))  & 0x00FF00FF;
+  v = (v | (v >>> 16)) & 0x000FFFF;
+  return (v << 16) >> 16;
+}
+
+
+//Interleave bits of 3 coordinates, each with 10 bits.  Useful for fast octree codes
+exports.interleave3 = function(x, y, z) {
+  x &= 0x3FF;
+  x  = (x | (x<<16)) & 4278190335;
+  x  = (x | (x<<8))  & 251719695;
+  x  = (x | (x<<4))  & 3272356035;
+  x  = (x | (x<<2))  & 1227133513;
+
+  y &= 0x3FF;
+  y  = (y | (y<<16)) & 4278190335;
+  y  = (y | (y<<8))  & 251719695;
+  y  = (y | (y<<4))  & 3272356035;
+  y  = (y | (y<<2))  & 1227133513;
+  x |= (y << 1);
+  
+  z &= 0x3FF;
+  z  = (z | (z<<16)) & 4278190335;
+  z  = (z | (z<<8))  & 251719695;
+  z  = (z | (z<<4))  & 3272356035;
+  z  = (z | (z<<2))  & 1227133513;
+  
+  return x | (z << 2);
+}
+
+//Extracts nth interleaved component of a 3-tuple
+exports.deinterleave3 = function(v, n) {
+  v = (v >>> n)       & 1227133513;
+  v = (v | (v>>>2))   & 3272356035;
+  v = (v | (v>>>4))   & 251719695;
+  v = (v | (v>>>8))   & 4278190335;
+  v = (v | (v>>>16))  & 0x3FF;
+  return (v<<22)>>22;
+}
+
+//Computes next combination in colexicographic order (this is mistakenly called nextPermutation on the bit twiddling hacks page)
+exports.nextCombination = function(v) {
+  var t = v | (v - 1);
+  return (t + 1) | (((~t & -~t) - 1) >>> (countTrailingZeros(v) + 1));
+}
+
+
+},{}],50:[function(require,module,exports){
+(function (global){
+/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
+ * @license  MIT
+ */
+/* eslint-disable no-proto */
+
+'use strict'
+
+var base64 = require('base64-js')
+var ieee754 = require('ieee754')
+var isArray = require('isarray')
+
+exports.Buffer = Buffer
+exports.SlowBuffer = SlowBuffer
+exports.INSPECT_MAX_BYTES = 50
+Buffer.poolSize = 8192 // not used by this implementation
+
+var rootParent = {}
+
+/**
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
+ *   === true    Use Uint8Array implementation (fastest)
+ *   === false   Use Object implementation (most compatible, even IE6)
+ *
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
+ * Opera 11.6+, iOS 4.2+.
+ *
+ * Due to various browser bugs, sometimes the Object implementation will be used even
+ * when the browser supports typed arrays.
+ *
+ * Note:
+ *
+ *   - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
+ *     See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
+ *
+ *   - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
+ *
+ *   - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
+ *     incorrect length in some situations.
+
+ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
+ * get the Object implementation, which is slower but behaves correctly.
+ */
+Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
+  ? global.TYPED_ARRAY_SUPPORT
+  : typedArraySupport()
+
+function typedArraySupport () {
+  try {
+    var arr = new Uint8Array(1)
+    arr.foo = function () { return 42 }
+    return arr.foo() === 42 && // typed array instances can be augmented
+        typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
+        arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
+  } catch (e) {
+    return false
+  }
+}
+
+function kMaxLength () {
+  return Buffer.TYPED_ARRAY_SUPPORT
+    ? 0x7fffffff
+    : 0x3fffffff
+}
+
+/**
+ * Class: Buffer
+ * =============
+ *
+ * The Buffer constructor returns instances of `Uint8Array` that are augmented
+ * with function properties for all the node `Buffer` API functions. We use
+ * `Uint8Array` so that square bracket notation works as expected -- it returns
+ * a single octet.
+ *
+ * By augmenting the instances, we can avoid modifying the `Uint8Array`
+ * prototype.
+ */
+function Buffer (arg) {
+  if (!(this instanceof Buffer)) {
+    // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
+    if (arguments.length > 1) return new Buffer(arg, arguments[1])
+    return new Buffer(arg)
+  }
+
+  if (!Buffer.TYPED_ARRAY_SUPPORT) {
+    this.length = 0
+    this.parent = undefined
+  }
+
+  // Common case.
+  if (typeof arg === 'number') {
+    return fromNumber(this, arg)
+  }
+
+  // Slightly less common case.
+  if (typeof arg === 'string') {
+    return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
+  }
+
+  // Unusual.
+  return fromObject(this, arg)
+}
+
+function fromNumber (that, length) {
+  that = allocate(that, length < 0 ? 0 : checked(length) | 0)
+  if (!Buffer.TYPED_ARRAY_SUPPORT) {
+    for (var i = 0; i < length; i++) {
+      that[i] = 0
+    }
+  }
+  return that
+}
+
+function fromString (that, string, encoding) {
+  if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
+
+  // Assumption: byteLength() return value is always < kMaxLength.
+  var length = byteLength(string, encoding) | 0
+  that = allocate(that, length)
+
+  that.write(string, encoding)
+  return that
+}
+
+function fromObject (that, object) {
+  if (Buffer.isBuffer(object)) return fromBuffer(that, object)
+
+  if (isArray(object)) return fromArray(that, object)
+
+  if (object == null) {
+    throw new TypeError('must start with number, buffer, array or string')
+  }
+
+  if (typeof ArrayBuffer !== 'undefined') {
+    if (object.buffer instanceof ArrayBuffer) {
+      return fromTypedArray(that, object)
+    }
+    if (object instanceof ArrayBuffer) {
+      return fromArrayBuffer(that, object)
+    }
+  }
+
+  if (object.length) return fromArrayLike(that, object)
+
+  return fromJsonObject(that, object)
+}
+
+function fromBuffer (that, buffer) {
+  var length = checked(buffer.length) | 0
+  that = allocate(that, length)
+  buffer.copy(that, 0, 0, length)
+  return that
+}
+
+function fromArray (that, array) {
+  var length = checked(array.length) | 0
+  that = allocate(that, length)
+  for (var i = 0; i < length; i += 1) {
+    that[i] = array[i] & 255
+  }
+  return that
+}
+
+// Duplicate of fromArray() to keep fromArray() monomorphic.
+function fromTypedArray (that, array) {
+  var length = checked(array.length) | 0
+  that = allocate(that, length)
+  // Truncating the elements is probably not what people expect from typed
+  // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
+  // of the old Buffer constructor.
+  for (var i = 0; i < length; i += 1) {
+    that[i] = array[i] & 255
+  }
+  return that
+}
+
+function fromArrayBuffer (that, array) {
+  array.byteLength // this throws if `array` is not a valid ArrayBuffer
+
+  if (Buffer.TYPED_ARRAY_SUPPORT) {
+    // Return an augmented `Uint8Array` instance, for best performance
+    that = new Uint8Array(array)
+    that.__proto__ = Buffer.prototype
+  } else {
+    // Fallback: Return an object instance of the Buffer class
+    that = fromTypedArray(that, new Uint8Array(array))
+  }
+  return that
+}
+
+function fromArrayLike (that, array) {
+  var length = checked(array.length) | 0
+  that = allocate(that, length)
+  for (var i = 0; i < length; i += 1) {
+    that[i] = array[i] & 255
+  }
+  return that
+}
+
+// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
+// Returns a zero-length buffer for inputs that don't conform to the spec.
+function fromJsonObject (that, object) {
+  var array
+  var length = 0
+
+  if (object.type === 'Buffer' && isArray(object.data)) {
+    array = object.data
+    length = checked(array.length) | 0
+  }
+  that = allocate(that, length)
+
+  for (var i = 0; i < length; i += 1) {
+    that[i] = array[i] & 255
+  }
+  return that
+}
+
+if (Buffer.TYPED_ARRAY_SUPPORT) {
+  Buffer.prototype.__proto__ = Uint8Array.prototype
+  Buffer.__proto__ = Uint8Array
+} else {
+  // pre-set for values that may exist in the future
+  Buffer.prototype.length = undefined
+  Buffer.prototype.parent = undefined
+}
+
+function allocate (that, length) {
+  if (Buffer.TYPED_ARRAY_SUPPORT) {
+    // Return an augmented `Uint8Array` instance, for best performance
+    that = new Uint8Array(length)
+    that.__proto__ = Buffer.prototype
+  } else {
+    // Fallback: Return an object instance of the Buffer class
+    that.length = length
+  }
+
+  var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
+  if (fromPool) that.parent = rootParent
+
+  return that
+}
+
+function checked (length) {
+  // Note: cannot use `length < kMaxLength` here because that fails when
+  // length is NaN (which is otherwise coerced to zero.)
+  if (length >= kMaxLength()) {
+    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
+                         'size: 0x' + kMaxLength().toString(16) + ' bytes')
+  }
+  return length | 0
+}
+
+function SlowBuffer (subject, encoding) {
+  if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
+
+  var buf = new Buffer(subject, encoding)
+  delete buf.parent
+  return buf
+}
+
+Buffer.isBuffer = function isBuffer (b) {
+  return !!(b != null && b._isBuffer)
+}
+
+Buffer.compare = function compare (a, b) {
+  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
+    throw new TypeError('Arguments must be Buffers')
+  }
+
+  if (a === b) return 0
+
+  var x = a.length
+  var y = b.length
+
+  var i = 0
+  var len = Math.min(x, y)
+  while (i < len) {
+    if (a[i] !== b[i]) break
+
+    ++i
+  }
+
+  if (i !== len) {
+    x = a[i]
+    y = b[i]
+  }
+
+  if (x < y) return -1
+  if (y < x) return 1
+  return 0
+}
+
+Buffer.isEncoding = function isEncoding (encoding) {
+  switch (String(encoding).toLowerCase()) {
+    case 'hex':
+    case 'utf8':
+    case 'utf-8':
+    case 'ascii':
+    case 'binary':
+    case 'base64':
+    case 'raw':
+    case 'ucs2':
+    case 'ucs-2':
+    case 'utf16le':
+    case 'utf-16le':
+      return true
+    default:
+      return false
+  }
+}
+
+Buffer.concat = function concat (list, length) {
+  if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
+
+  if (list.length === 0) {
+    return new Buffer(0)
+  }
+
+  var i
+  if (length === undefined) {
+    length = 0
+    for (i = 0; i < list.length; i++) {
+      length += list[i].length
+    }
+  }
+
+  var buf = new Buffer(length)
+  var pos = 0
+  for (i = 0; i < list.length; i++) {
+    var item = list[i]
+    item.copy(buf, pos)
+    pos += item.length
+  }
+  return buf
+}
+
+function byteLength (string, encoding) {
+  if (typeof string !== 'string') string = '' + string
+
+  var len = string.length
+  if (len === 0) return 0
+
+  // Use a for loop to avoid recursion
+  var loweredCase = false
+  for (;;) {
+    switch (encoding) {
+      case 'ascii':
+      case 'binary':
+      // Deprecated
+      case 'raw':
+      case 'raws':
+        return len
+      case 'utf8':
+      case 'utf-8':
+        return utf8ToBytes(string).length
+      case 'ucs2':
+      case 'ucs-2':
+      case 'utf16le':
+      case 'utf-16le':
+        return len * 2
+      case 'hex':
+        return len >>> 1
+      case 'base64':
+        return base64ToBytes(string).length
+      default:
+        if (loweredCase) return utf8ToBytes(string).length // assume utf8
+        encoding = ('' + encoding).toLowerCase()
+        loweredCase = true
+    }
+  }
+}
+Buffer.byteLength = byteLength
+
+function slowToString (encoding, start, end) {
+  var loweredCase = false
+
+  start = start | 0
+  end = end === undefined || end === Infinity ? this.length : end | 0
+
+  if (!encoding) encoding = 'utf8'
+  if (start < 0) start = 0
+  if (end > this.length) end = this.length
+  if (end <= start) return ''
+
+  while (true) {
+    switch (encoding) {
+      case 'hex':
+        return hexSlice(this, start, end)
+
+      case 'utf8':
+      case 'utf-8':
+        return utf8Slice(this, start, end)
+
+      case 'ascii':
+        return asciiSlice(this, start, end)
+
+      case 'binary':
+        return binarySlice(this, start, end)
+
+      case 'base64':
+        return base64Slice(this, start, end)
+
+      case 'ucs2':
+      case 'ucs-2':
+      case 'utf16le':
+      case 'utf-16le':
+        return utf16leSlice(this, start, end)
+
+      default:
+        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
+        encoding = (encoding + '').toLowerCase()
+        loweredCase = true
+    }
+  }
+}
+
+// Even though this property is private, it shouldn't be removed because it is
+// used by `is-buffer` to detect buffer instances in Safari 5-7.
+Buffer.prototype._isBuffer = true
+
+Buffer.prototype.toString = function toString () {
+  var length = this.length | 0
+  if (length === 0) return ''
+  if (arguments.length === 0) return utf8Slice(this, 0, length)
+  return slowToString.apply(this, arguments)
+}
+
+Buffer.prototype.equals = function equals (b) {
+  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
+  if (this === b) return true
+  return Buffer.compare(this, b) === 0
+}
+
+Buffer.prototype.inspect = function inspect () {
+  var str = ''
+  var max = exports.INSPECT_MAX_BYTES
+  if (this.length > 0) {
+    str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
+    if (this.length > max) str += ' ... '
+  }
+  return '<Buffer ' + str + '>'
+}
+
+Buffer.prototype.compare = function compare (b) {
+  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
+  if (this === b) return 0
+  return Buffer.compare(this, b)
+}
+
+Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
+  if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
+  else if (byteOffset < -0x80000000) byteOffset = -0x80000000
+  byteOffset >>= 0
+
+  if (this.length === 0) return -1
+  if (byteOffset >= this.length) return -1
+
+  // Negative offsets start from the end of the buffer
+  if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
+
+  if (typeof val === 'string') {
+    if (val.length === 0) return -1 // special case: looking for empty string always fails
+    return String.prototype.indexOf.call(this, val, byteOffset)
+  }
+  if (Buffer.isBuffer(val)) {
+    return arrayIndexOf(this, val, byteOffset)
+  }
+  if (typeof val === 'number') {
+    if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
+      return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
+    }
+    return arrayIndexOf(this, [ val ], byteOffset)
+  }
+
+  function arrayIndexOf (arr, val, byteOffset) {
+    var foundIndex = -1
+    for (var i = 0; byteOffset + i < arr.length; i++) {
+      if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
+        if (foundIndex === -1) foundIndex = i
+        if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
+      } else {
+        foundIndex = -1
+      }
+    }
+    return -1
+  }
+
+  throw new TypeError('val must be string, number or Buffer')
+}
+
+function hexWrite (buf, string, offset, length) {
+  offset = Number(offset) || 0
+  var remaining = buf.length - offset
+  if (!length) {
+    length = remaining
+  } else {
+    length = Number(length)
+    if (length > remaining) {
+      length = remaining
+    }
+  }
+
+  // must be an even number of digits
+  var strLen = string.length
+  if (strLen % 2 !== 0) throw new Error('Invalid hex string')
+
+  if (length > strLen / 2) {
+    length = strLen / 2
+  }
+  for (var i = 0; i < length; i++) {
+    var parsed = parseInt(string.substr(i * 2, 2), 16)
+    if (isNaN(parsed)) throw new Error('Invalid hex string')
+    buf[offset + i] = parsed
+  }
+  return i
+}
+
+function utf8Write (buf, string, offset, length) {
+  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
+}
+
+function asciiWrite (buf, string, offset, length) {
+  return blitBuffer(asciiToBytes(string), buf, offset, length)
+}
+
+function binaryWrite (buf, string, offset, length) {
+  return asciiWrite(buf, string, offset, length)
+}
+
+function base64Write (buf, string, offset, length) {
+  return blitBuffer(base64ToBytes(string), buf, offset, length)
+}
+
+function ucs2Write (buf, string, offset, length) {
+  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
+}
+
+Buffer.prototype.write = function write (string, offset, length, encoding) {
+  // Buffer#write(string)
+  if (offset === undefined) {
+    encoding = 'utf8'
+    length = this.length
+    offset = 0
+  // Buffer#write(string, encoding)
+  } else if (length === undefined && typeof offset === 'string') {
+    encoding = offset
+    length = this.length
+    offset = 0
+  // Buffer#write(string, offset[, length][, encoding])
+  } else if (isFinite(offset)) {
+    offset = offset | 0
+    if (isFinite(length)) {
+      length = length | 0
+      if (encoding === undefined) encoding = 'utf8'
+    } else {
+      encoding = length
+      length = undefined
+    }
+  // legacy write(string, encoding, offset, length) - remove in v0.13
+  } else {
+    var swap = encoding
+    encoding = offset
+    offset = length | 0
+    length = swap
+  }
+
+  var remaining = this.length - offset
+  if (length === undefined || length > remaining) length = remaining
+
+  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
+    throw new RangeError('attempt to write outside buffer bounds')
+  }
+
+  if (!encoding) encoding = 'utf8'
+
+  var loweredCase = false
+  for (;;) {
+    switch (encoding) {
+      case 'hex':
+        return hexWrite(this, string, offset, length)
+
+      case 'utf8':
+      case 'utf-8':
+        return utf8Write(this, string, offset, length)
+
+      case 'ascii':
+        return asciiWrite(this, string, offset, length)
+
+      case 'binary':
+        return binaryWrite(this, string, offset, length)
+
+      case 'base64':
+        // Warning: maxLength not taken into account in base64Write
+        return base64Write(this, string, offset, length)
+
+      case 'ucs2':
+      case 'ucs-2':
+      case 'utf16le':
+      case 'utf-16le':
+        return ucs2Write(this, string, offset, length)
+
+      default:
+        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
+        encoding = ('' + encoding).toLowerCase()
+        loweredCase = true
+    }
+  }
+}
+
+Buffer.prototype.toJSON = function toJSON () {
+  return {
+    type: 'Buffer',
+    data: Array.prototype.slice.call(this._arr || this, 0)
+  }
+}
+
+function base64Slice (buf, start, end) {
+  if (start === 0 && end === buf.length) {
+    return base64.fromByteArray(buf)
+  } else {
+    return base64.fromByteArray(buf.slice(start, end))
+  }
+}
+
+function utf8Slice (buf, start, end) {
+  end = Math.min(buf.length, end)
+  var res = []
+
+  var i = start
+  while (i < end) {
+    var firstByte = buf[i]
+    var codePoint = null
+    var bytesPerSequence = (firstByte > 0xEF) ? 4
+      : (firstByte > 0xDF) ? 3
+      : (firstByte > 0xBF) ? 2
+      : 1
+
+    if (i + bytesPerSequence <= end) {
+      var secondByte, thirdByte, fourthByte, tempCodePoint
+
+      switch (bytesPerSequence) {
+        case 1:
+          if (firstByte < 0x80) {
+            codePoint = firstByte
+          }
+          break
+        case 2:
+          secondByte = buf[i + 1]
+          if ((secondByte & 0xC0) === 0x80) {
+            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
+            if (tempCodePoint > 0x7F) {
+              codePoint = tempCodePoint
+            }
+          }
+          break
+        case 3:
+          secondByte = buf[i + 1]
+          thirdByte = buf[i + 2]
+          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
+            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
+            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
+              codePoint = tempCodePoint
+            }
+          }
+          break
+        case 4:
+          secondByte = buf[i + 1]
+          thirdByte = buf[i + 2]
+          fourthByte = buf[i + 3]
+          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
+            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
+            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
+              codePoint = tempCodePoint
+            }
+          }
+      }
+    }
+
+    if (codePoint === null) {
+      // we did not generate a valid codePoint so insert a
+      // replacement char (U+FFFD) and advance only 1 byte
+      codePoint = 0xFFFD
+      bytesPerSequence = 1
+    } else if (codePoint > 0xFFFF) {
+      // encode to utf16 (surrogate pair dance)
+      codePoint -= 0x10000
+      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
+      codePoint = 0xDC00 | codePoint & 0x3FF
+    }
+
+    res.push(codePoint)
+    i += bytesPerSequence
+  }
+
+  return decodeCodePointsArray(res)
+}
+
+// Based on http://stackoverflow.com/a/22747272/680742, the browser with
+// the lowest limit is Chrome, with 0x10000 args.
+// We go 1 magnitude less, for safety
+var MAX_ARGUMENTS_LENGTH = 0x1000
+
+function decodeCodePointsArray (codePoints) {
+  var len = codePoints.length
+  if (len <= MAX_ARGUMENTS_LENGTH) {
+    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
+  }
+
+  // Decode in chunks to avoid "call stack size exceeded".
+  var res = ''
+  var i = 0
+  while (i < len) {
+    res += String.fromCharCode.apply(
+      String,
+      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
+    )
+  }
+  return res
+}
+
+function asciiSlice (buf, start, end) {
+  var ret = ''
+  end = Math.min(buf.length, end)
+
+  for (var i = start; i < end; i++) {
+    ret += String.fromCharCode(buf[i] & 0x7F)
+  }
+  return ret
+}
+
+function binarySlice (buf, start, end) {
+  var ret = ''
+  end = Math.min(buf.length, end)
+
+  for (var i = start; i < end; i++) {
+    ret += String.fromCharCode(buf[i])
+  }
+  return ret
+}
+
+function hexSlice (buf, start, end) {
+  var len = buf.length
+
+  if (!start || start < 0) start = 0
+  if (!end || end < 0 || end > len) end = len
+
+  var out = ''
+  for (var i = start; i < end; i++) {
+    out += toHex(buf[i])
+  }
+  return out
+}
+
+function utf16leSlice (buf, start, end) {
+  var bytes = buf.slice(start, end)
+  var res = ''
+  for (var i = 0; i < bytes.length; i += 2) {
+    res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
+  }
+  return res
+}
+
+Buffer.prototype.slice = function slice (start, end) {
+  var len = this.length
+  start = ~~start
+  end = end === undefined ? len : ~~end
+
+  if (start < 0) {
+    start += len
+    if (start < 0) start = 0
+  } else if (start > len) {
+    start = len
+  }
+
+  if (end < 0) {
+    end += len
+    if (end < 0) end = 0
+  } else if (end > len) {
+    end = len
+  }
+
+  if (end < start) end = start
+
+  var newBuf
+  if (Buffer.TYPED_ARRAY_SUPPORT) {
+    newBuf = this.subarray(start, end)
+    newBuf.__proto__ = Buffer.prototype
+  } else {
+    var sliceLen = end - start
+    newBuf = new Buffer(sliceLen, undefined)
+    for (var i = 0; i < sliceLen; i++) {
+      newBuf[i] = this[i + start]
+    }
+  }
+
+  if (newBuf.length) newBuf.parent = this.parent || this
+
+  return newBuf
+}
+
+/*
+ * Need to make sure that buffer isn't trying to write out of bounds.
+ */
+function checkOffset (offset, ext, length) {
+  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
+  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
+}
+
+Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
+  offset = offset | 0
+  byteLength = byteLength | 0
+  if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+  var val = this[offset]
+  var mul = 1
+  var i = 0
+  while (++i < byteLength && (mul *= 0x100)) {
+    val += this[offset + i] * mul
+  }
+
+  return val
+}
+
+Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
+  offset = offset | 0
+  byteLength = byteLength | 0
+  if (!noAssert) {
+    checkOffset(offset, byteLength, this.length)
+  }
+
+  var val = this[offset + --byteLength]
+  var mul = 1
+  while (byteLength > 0 && (mul *= 0x100)) {
+    val += this[offset + --byteLength] * mul
+  }
+
+  return val
+}
+
+Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 1, this.length)
+  return this[offset]
+}
+
+Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 2, this.length)
+  return this[offset] | (this[offset + 1] << 8)
+}
+
+Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 2, this.length)
+  return (this[offset] << 8) | this[offset + 1]
+}
+
+Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 4, this.length)
+
+  return ((this[offset]) |
+      (this[offset + 1] << 8) |
+      (this[offset + 2] << 16)) +
+      (this[offset + 3] * 0x1000000)
+}
+
+Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 4, this.length)
+
+  return (this[offset] * 0x1000000) +
+    ((this[offset + 1] << 16) |
+    (this[offset + 2] << 8) |
+    this[offset + 3])
+}
+
+Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
+  offset = offset | 0
+  byteLength = byteLength | 0
+  if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+  var val = this[offset]
+  var mul = 1
+  var i = 0
+  while (++i < byteLength && (mul *= 0x100)) {
+    val += this[offset + i] * mul
+  }
+  mul *= 0x80
+
+  if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+
+  return val
+}
+
+Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
+  offset = offset | 0
+  byteLength = byteLength | 0
+  if (!noAssert) checkOffset(offset, byteLength, this.length)
+
+  var i = byteLength
+  var mul = 1
+  var val = this[offset + --i]
+  while (i > 0 && (mul *= 0x100)) {
+    val += this[offset + --i] * mul
+  }
+  mul *= 0x80
+
+  if (val >= mul) val -= Math.pow(2, 8 * byteLength)
+
+  return val
+}
+
+Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 1, this.length)
+  if (!(this[offset] & 0x80)) return (this[offset])
+  return ((0xff - this[offset] + 1) * -1)
+}
+
+Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 2, this.length)
+  var val = this[offset] | (this[offset + 1] << 8)
+  return (val & 0x8000) ? val | 0xFFFF0000 : val
+}
+
+Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 2, this.length)
+  var val = this[offset + 1] | (this[offset] << 8)
+  return (val & 0x8000) ? val | 0xFFFF0000 : val
+}
+
+Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 4, this.length)
+
+  return (this[offset]) |
+    (this[offset + 1] << 8) |
+    (this[offset + 2] << 16) |
+    (this[offset + 3] << 24)
+}
+
+Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 4, this.length)
+
+  return (this[offset] << 24) |
+    (this[offset + 1] << 16) |
+    (this[offset + 2] << 8) |
+    (this[offset + 3])
+}
+
+Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 4, this.length)
+  return ieee754.read(this, offset, true, 23, 4)
+}
+
+Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 4, this.length)
+  return ieee754.read(this, offset, false, 23, 4)
+}
+
+Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 8, this.length)
+  return ieee754.read(this, offset, true, 52, 8)
+}
+
+Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
+  if (!noAssert) checkOffset(offset, 8, this.length)
+  return ieee754.read(this, offset, false, 52, 8)
+}
+
+function checkInt (buf, value, offset, ext, max, min) {
+  if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
+  if (value > max || value < min) throw new RangeError('value is out of bounds')
+  if (offset + ext > buf.length) throw new RangeError('index out of range')
+}
+
+Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
+  value = +value
+  offset = offset | 0
+  byteLength = byteLength | 0
+  if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
+
+  var mul = 1
+  var i = 0
+  this[offset] = value & 0xFF
+  while (++i < byteLength && (mul *= 0x100)) {
+    this[offset + i] = (value / mul) & 0xFF
+  }
+
+  return offset + byteLength
+}
+
+Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
+  value = +value
+  offset = offset | 0
+  byteLength = byteLength | 0
+  if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
+
+  var i = byteLength - 1
+  var mul = 1
+  this[offset + i] = value & 0xFF
+  while (--i >= 0 && (mul *= 0x100)) {
+    this[offset + i] = (value / mul) & 0xFF
+  }
+
+  return offset + byteLength
+}
+
+Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
+  value = +value
+  offset = offset | 0
+  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
+  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
+  this[offset] = (value & 0xff)
+  return offset + 1
+}
+
+function objectWriteUInt16 (buf, value, offset, littleEndian) {
+  if (value < 0) value = 0xffff + value + 1
+  for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
+    buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
+      (littleEndian ? i : 1 - i) * 8
+  }
+}
+
+Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
+  value = +value
+  offset = offset | 0
+  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
+  if (Buffer.TYPED_ARRAY_SUPPORT) {
+    this[offset] = (value & 0xff)
+    this[offset + 1] = (value >>> 8)
+  } else {
+    objectWriteUInt16(this, value, offset, true)
+  }
+  return offset + 2
+}
+
+Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
+  value = +value
+  offset = offset | 0
+  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
+  if (Buffer.TYPED_ARRAY_SUPPORT) {
+    this[offset] = (value >>> 8)
+    this[offset + 1] = (value & 0xff)
+  } else {
+    objectWriteUInt16(this, value, offset, false)
+  }
+  return offset + 2
+}
+
+function objectWriteUInt32 (buf, value, offset, littleEndian) {
+  if (value < 0) value = 0xffffffff + value + 1
+  for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
+    buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
+  }
+}
+
+Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
+  value = +value
+  offset = offset | 0
+  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
+  if (Buffer.TYPED_ARRAY_SUPPORT) {
+    this[offset + 3] = (value >>> 24)
+    this[offset + 2] = (value >>> 16)
+    this[offset + 1] = (value >>> 8)
+    this[offset] = (value & 0xff)
+  } else {
+    objectWriteUInt32(this, value, offset, true)
+  }
+  return offset + 4
+}
+
+Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
+  value = +value
+  offset = offset | 0
+  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
+  if (Buffer.TYPED_ARRAY_SUPPORT) {
+    this[offset] = (value >>> 24)
+    this[offset + 1] = (value >>> 16)
+    this[offset + 2] = (value >>> 8)
+    this[offset + 3] = (value & 0xff)
+  } else {
+    objectWriteUInt32(this, value, offset, false)
+  }
+  return offset + 4
+}
+
+Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
+  value = +value
+  offset = offset | 0
+  if (!noAssert) {
+    var limit = Math.pow(2, 8 * byteLength - 1)
+
+    checkInt(this, value, offset, byteLength, limit - 1, -limit)
+  }
+
+  var i = 0
+  var mul = 1
+  var sub = value < 0 ? 1 : 0
+  this[offset] = value & 0xFF
+  while (++i < byteLength && (mul *= 0x100)) {
+    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+  }
+
+  return offset + byteLength
+}
+
+Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
+  value = +value
+  offset = offset | 0
+  if (!noAssert) {
+    var limit = Math.pow(2, 8 * byteLength - 1)
+
+    checkInt(this, value, offset, byteLength, limit - 1, -limit)
+  }
+
+  var i = byteLength - 1
+  var mul = 1
+  var sub = value < 0 ? 1 : 0
+  this[offset + i] = value & 0xFF
+  while (--i >= 0 && (mul *= 0x100)) {
+    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
+  }
+
+  return offset + byteLength
+}
+
+Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
+  value = +value
+  offset = offset | 0
+  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
+  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
+  if (value < 0) value = 0xff + value + 1
+  this[offset] = (value & 0xff)
+  return offset + 1
+}
+
+Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
+  value = +value
+  offset = offset | 0
+  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+  if (Buffer.TYPED_ARRAY_SUPPORT) {
+    this[offset] = (value & 0xff)
+    this[offset + 1] = (value >>> 8)
+  } else {
+    objectWriteUInt16(this, value, offset, true)
+  }
+  return offset + 2
+}
+
+Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
+  value = +value
+  offset = offset | 0
+  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
+  if (Buffer.TYPED_ARRAY_SUPPORT) {
+    this[offset] = (value >>> 8)
+    this[offset + 1] = (value & 0xff)
+  } else {
+    objectWriteUInt16(this, value, offset, false)
+  }
+  return offset + 2
+}
+
+Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
+  value = +value
+  offset = offset | 0
+  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+  if (Buffer.TYPED_ARRAY_SUPPORT) {
+    this[offset] = (value & 0xff)
+    this[offset + 1] = (value >>> 8)
+    this[offset + 2] = (value >>> 16)
+    this[offset + 3] = (value >>> 24)
+  } else {
+    objectWriteUInt32(this, value, offset, true)
+  }
+  return offset + 4
+}
+
+Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
+  value = +value
+  offset = offset | 0
+  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
+  if (value < 0) value = 0xffffffff + value + 1
+  if (Buffer.TYPED_ARRAY_SUPPORT) {
+    this[offset] = (value >>> 24)
+    this[offset + 1] = (value >>> 16)
+    this[offset + 2] = (value >>> 8)
+    this[offset + 3] = (value & 0xff)
+  } else {
+    objectWriteUInt32(this, value, offset, false)
+  }
+  return offset + 4
+}
+
+function checkIEEE754 (buf, value, offset, ext, max, min) {
+  if (value > max || value < min) throw new RangeError('value is out of bounds')
+  if (offset + ext > buf.length) throw new RangeError('index out of range')
+  if (offset < 0) throw new RangeError('index out of range')
+}
+
+function writeFloat (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
+  }
+  ieee754.write(buf, value, offset, littleEndian, 23, 4)
+  return offset + 4
+}
+
+Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
+  return writeFloat(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
+  return writeFloat(this, value, offset, false, noAssert)
+}
+
+function writeDouble (buf, value, offset, littleEndian, noAssert) {
+  if (!noAssert) {
+    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
+  }
+  ieee754.write(buf, value, offset, littleEndian, 52, 8)
+  return offset + 8
+}
+
+Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
+  return writeDouble(this, value, offset, true, noAssert)
+}
+
+Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
+  return writeDouble(this, value, offset, false, noAssert)
+}
+
+// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
+Buffer.prototype.copy = function copy (target, targetStart, start, end) {
+  if (!start) start = 0
+  if (!end && end !== 0) end = this.length
+  if (targetStart >= target.length) targetStart = target.length
+  if (!targetStart) targetStart = 0
+  if (end > 0 && end < start) end = start
+
+  // Copy 0 bytes; we're done
+  if (end === start) return 0
+  if (target.length === 0 || this.length === 0) return 0
+
+  // Fatal error conditions
+  if (targetStart < 0) {
+    throw new RangeError('targetStart out of bounds')
+  }
+  if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
+  if (end < 0) throw new RangeError('sourceEnd out of bounds')
+
+  // Are we oob?
+  if (end > this.length) end = this.length
+  if (target.length - targetStart < end - start) {
+    end = target.length - targetStart + start
+  }
+
+  var len = end - start
+  var i
+
+  if (this === target && start < targetStart && targetStart < end) {
+    // descending copy from end
+    for (i = len - 1; i >= 0; i--) {
+      target[i + targetStart] = this[i + start]
+    }
+  } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
+    // ascending copy from start
+    for (i = 0; i < len; i++) {
+      target[i + targetStart] = this[i + start]
+    }
+  } else {
+    Uint8Array.prototype.set.call(
+      target,
+      this.subarray(start, start + len),
+      targetStart
+    )
+  }
+
+  return len
+}
+
+// fill(value, start=0, end=buffer.length)
+Buffer.prototype.fill = function fill (value, start, end) {
+  if (!value) value = 0
+  if (!start) start = 0
+  if (!end) end = this.length
+
+  if (end < start) throw new RangeError('end < start')
+
+  // Fill 0 bytes; we're done
+  if (end === start) return
+  if (this.length === 0) return
+
+  if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
+  if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
+
+  var i
+  if (typeof value === 'number') {
+    for (i = start; i < end; i++) {
+      this[i] = value
+    }
+  } else {
+    var bytes = utf8ToBytes(value.toString())
+    var len = bytes.length
+    for (i = start; i < end; i++) {
+      this[i] = bytes[i % len]
+    }
+  }
+
+  return this
+}
+
+// HELPER FUNCTIONS
+// ================
+
+var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
+
+function base64clean (str) {
+  // Node strips out invalid characters like \n and \t from the string, base64-js does not
+  str = stringtrim(str).replace(INVALID_BASE64_RE, '')
+  // Node converts strings with length < 2 to ''
+  if (str.length < 2) return ''
+  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
+  while (str.length % 4 !== 0) {
+    str = str + '='
+  }
+  return str
+}
+
+function stringtrim (str) {
+  if (str.trim) return str.trim()
+  return str.replace(/^\s+|\s+$/g, '')
+}
+
+function toHex (n) {
+  if (n < 16) return '0' + n.toString(16)
+  return n.toString(16)
+}
+
+function utf8ToBytes (string, units) {
+  units = units || Infinity
+  var codePoint
+  var length = string.length
+  var leadSurrogate = null
+  var bytes = []
+
+  for (var i = 0; i < length; i++) {
+    codePoint = string.charCodeAt(i)
+
+    // is surrogate component
+    if (codePoint > 0xD7FF && codePoint < 0xE000) {
+      // last char was a lead
+      if (!leadSurrogate) {
+        // no lead yet
+        if (codePoint > 0xDBFF) {
+          // unexpected trail
+          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+          continue
+        } else if (i + 1 === length) {
+          // unpaired lead
+          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+          continue
+        }
+
+        // valid lead
+        leadSurrogate = codePoint
+
+        continue
+      }
+
+      // 2 leads in a row
+      if (codePoint < 0xDC00) {
+        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+        leadSurrogate = codePoint
+        continue
+      }
+
+      // valid surrogate pair
+      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
+    } else if (leadSurrogate) {
+      // valid bmp char, but last char was a lead
+      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+    }
+
+    leadSurrogate = null
+
+    // encode utf8
+    if (codePoint < 0x80) {
+      if ((units -= 1) < 0) break
+      bytes.push(codePoint)
+    } else if (codePoint < 0x800) {
+      if ((units -= 2) < 0) break
+      bytes.push(
+        codePoint >> 0x6 | 0xC0,
+        codePoint & 0x3F | 0x80
+      )
+    } else if (codePoint < 0x10000) {
+      if ((units -= 3) < 0) break
+      bytes.push(
+        codePoint >> 0xC | 0xE0,
+        codePoint >> 0x6 & 0x3F | 0x80,
+        codePoint & 0x3F | 0x80
+      )
+    } else if (codePoint < 0x110000) {
+      if ((units -= 4) < 0) break
+      bytes.push(
+        codePoint >> 0x12 | 0xF0,
+        codePoint >> 0xC & 0x3F | 0x80,
+        codePoint >> 0x6 & 0x3F | 0x80,
+        codePoint & 0x3F | 0x80
+      )
+    } else {
+      throw new Error('Invalid code point')
+    }
+  }
+
+  return bytes
+}
+
+function asciiToBytes (str) {
+  var byteArray = []
+  for (var i = 0; i < str.length; i++) {
+    // Node's code seems to be doing this and not & 0x7F..
+    byteArray.push(str.charCodeAt(i) & 0xFF)
+  }
+  return byteArray
+}
+
+function utf16leToBytes (str, units) {
+  var c, hi, lo
+  var byteArray = []
+  for (var i = 0; i < str.length; i++) {
+    if ((units -= 2) < 0) break
+
+    c = str.charCodeAt(i)
+    hi = c >> 8
+    lo = c % 256
+    byteArray.push(lo)
+    byteArray.push(hi)
+  }
+
+  return byteArray
+}
+
+function base64ToBytes (str) {
+  return base64.toByteArray(base64clean(str))
+}
+
+function blitBuffer (src, dst, offset, length) {
+  for (var i = 0; i < length; i++) {
+    if ((i + offset >= dst.length) || (i >= src.length)) break
+    dst[i + offset] = src[i]
+  }
+  return i
+}
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"base64-js":51,"ieee754":52,"isarray":53}],51:[function(require,module,exports){
+;(function (exports) {
+  'use strict'
+
+  var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
+
+  var Arr = (typeof Uint8Array !== 'undefined')
+    ? Uint8Array
+    : Array
+
+  var PLUS = '+'.charCodeAt(0)
+  var SLASH = '/'.charCodeAt(0)
+  var NUMBER = '0'.charCodeAt(0)
+  var LOWER = 'a'.charCodeAt(0)
+  var UPPER = 'A'.charCodeAt(0)
+  var PLUS_URL_SAFE = '-'.charCodeAt(0)
+  var SLASH_URL_SAFE = '_'.charCodeAt(0)
+
+  function decode (elt) {
+    var code = elt.charCodeAt(0)
+    if (code === PLUS || code === PLUS_URL_SAFE) return 62 // '+'
+    if (code === SLASH || code === SLASH_URL_SAFE) return 63 // '/'
+    if (code < NUMBER) return -1 // no match
+    if (code < NUMBER + 10) return code - NUMBER + 26 + 26
+    if (code < UPPER + 26) return code - UPPER
+    if (code < LOWER + 26) return code - LOWER + 26
+  }
+
+  function b64ToByteArray (b64) {
+    var i, j, l, tmp, placeHolders, arr
+
+    if (b64.length % 4 > 0) {
+      throw new Error('Invalid string. Length must be a multiple of 4')
+    }
+
+    // the number of equal signs (place holders)
+    // if there are two placeholders, than the two characters before it
+    // represent one byte
+    // if there is only one, then the three characters before it represent 2 bytes
+    // this is just a cheap hack to not do indexOf twice
+    var len = b64.length
+    placeHolders = b64.charAt(len - 2) === '=' ? 2 : b64.charAt(len - 1) === '=' ? 1 : 0
+
+    // base64 is 4/3 + up to two characters of the original data
+    arr = new Arr(b64.length * 3 / 4 - placeHolders)
+
+    // if there are placeholders, only get up to the last complete 4 chars
+    l = placeHolders > 0 ? b64.length - 4 : b64.length
+
+    var L = 0
+
+    function push (v) {
+      arr[L++] = v
+    }
+
+    for (i = 0, j = 0; i < l; i += 4, j += 3) {
+      tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
+      push((tmp & 0xFF0000) >> 16)
+      push((tmp & 0xFF00) >> 8)
+      push(tmp & 0xFF)
+    }
+
+    if (placeHolders === 2) {
+      tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
+      push(tmp & 0xFF)
+    } else if (placeHolders === 1) {
+      tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
+      push((tmp >> 8) & 0xFF)
+      push(tmp & 0xFF)
+    }
+
+    return arr
+  }
+
+  function uint8ToBase64 (uint8) {
+    var i
+    var extraBytes = uint8.length % 3 // if we have 1 byte left, pad 2 bytes
+    var output = ''
+    var temp, length
+
+    function encode (num) {
+      return lookup.charAt(num)
+    }
+
+    function tripletToBase64 (num) {
+      return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
+    }
+
+    // go through the array every three bytes, we'll deal with trailing stuff later
+    for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
+      temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
+      output += tripletToBase64(temp)
+    }
+
+    // pad the end with zeros, but make sure to not forget the extra bytes
+    switch (extraBytes) {
+      case 1:
+        temp = uint8[uint8.length - 1]
+        output += encode(temp >> 2)
+        output += encode((temp << 4) & 0x3F)
+        output += '=='
+        break
+      case 2:
+        temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
+        output += encode(temp >> 10)
+        output += encode((temp >> 4) & 0x3F)
+        output += encode((temp << 2) & 0x3F)
+        output += '='
+        break
+      default:
+        break
+    }
+
+    return output
+  }
+
+  exports.toByteArray = b64ToByteArray
+  exports.fromByteArray = uint8ToBase64
+}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
+
+},{}],52:[function(require,module,exports){
+exports.read = function (buffer, offset, isLE, mLen, nBytes) {
+  var e, m
+  var eLen = nBytes * 8 - mLen - 1
+  var eMax = (1 << eLen) - 1
+  var eBias = eMax >> 1
+  var nBits = -7
+  var i = isLE ? (nBytes - 1) : 0
+  var d = isLE ? -1 : 1
+  var s = buffer[offset + i]
+
+  i += d
+
+  e = s & ((1 << (-nBits)) - 1)
+  s >>= (-nBits)
+  nBits += eLen
+  for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+
+  m = e & ((1 << (-nBits)) - 1)
+  e >>= (-nBits)
+  nBits += mLen
+  for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
+
+  if (e === 0) {
+    e = 1 - eBias
+  } else if (e === eMax) {
+    return m ? NaN : ((s ? -1 : 1) * Infinity)
+  } else {
+    m = m + Math.pow(2, mLen)
+    e = e - eBias
+  }
+  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
+}
+
+exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
+  var e, m, c
+  var eLen = nBytes * 8 - mLen - 1
+  var eMax = (1 << eLen) - 1
+  var eBias = eMax >> 1
+  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
+  var i = isLE ? 0 : (nBytes - 1)
+  var d = isLE ? 1 : -1
+  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
+
+  value = Math.abs(value)
+
+  if (isNaN(value) || value === Infinity) {
+    m = isNaN(value) ? 1 : 0
+    e = eMax
+  } else {
+    e = Math.floor(Math.log(value) / Math.LN2)
+    if (value * (c = Math.pow(2, -e)) < 1) {
+      e--
+      c *= 2
+    }
+    if (e + eBias >= 1) {
+      value += rt / c
+    } else {
+      value += rt * Math.pow(2, 1 - eBias)
+    }
+    if (value * c >= 2) {
+      e++
+      c /= 2
+    }
+
+    if (e + eBias >= eMax) {
+      m = 0
+      e = eMax
+    } else if (e + eBias >= 1) {
+      m = (value * c - 1) * Math.pow(2, mLen)
+      e = e + eBias
+    } else {
+      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
+      e = 0
+    }
+  }
+
+  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
+
+  e = (e << mLen) | m
+  eLen += mLen
+  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
+
+  buffer[offset + i - d] |= s * 128
+}
+
+},{}],53:[function(require,module,exports){
+var toString = {}.toString;
+
+module.exports = Array.isArray || function (arr) {
+  return toString.call(arr) == '[object Array]';
+};
+
+},{}],54:[function(require,module,exports){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+function EventEmitter() {
+  this._events = this._events || {};
+  this._maxListeners = this._maxListeners || undefined;
+}
+module.exports = EventEmitter;
+
+// Backwards-compat with node 0.10.x
+EventEmitter.EventEmitter = EventEmitter;
+
+EventEmitter.prototype._events = undefined;
+EventEmitter.prototype._maxListeners = undefined;
+
+// By default EventEmitters will print a warning if more than 10 listeners are
+// added to it. This is a useful default which helps finding memory leaks.
+EventEmitter.defaultMaxListeners = 10;
+
+// Obviously not all Emitters should be limited to 10. This function allows
+// that to be increased. Set to zero for unlimited.
+EventEmitter.prototype.setMaxListeners = function(n) {
+  if (!isNumber(n) || n < 0 || isNaN(n))
+    throw TypeError('n must be a positive number');
+  this._maxListeners = n;
+  return this;
+};
+
+EventEmitter.prototype.emit = function(type) {
+  var er, handler, len, args, i, listeners;
+
+  if (!this._events)
+    this._events = {};
+
+  // If there is no 'error' event listener then throw.
+  if (type === 'error') {
+    if (!this._events.error ||
+        (isObject(this._events.error) && !this._events.error.length)) {
+      er = arguments[1];
+      if (er instanceof Error) {
+        throw er; // Unhandled 'error' event
+      }
+      throw TypeError('Uncaught, unspecified "error" event.');
+    }
+  }
+
+  handler = this._events[type];
+
+  if (isUndefined(handler))
+    return false;
+
+  if (isFunction(handler)) {
+    switch (arguments.length) {
+      // fast cases
+      case 1:
+        handler.call(this);
+        break;
+      case 2:
+        handler.call(this, arguments[1]);
+        break;
+      case 3:
+        handler.call(this, arguments[1], arguments[2]);
+        break;
+      // slower
+      default:
+        args = Array.prototype.slice.call(arguments, 1);
+        handler.apply(this, args);
+    }
+  } else if (isObject(handler)) {
+    args = Array.prototype.slice.call(arguments, 1);
+    listeners = handler.slice();
+    len = listeners.length;
+    for (i = 0; i < len; i++)
+      listeners[i].apply(this, args);
+  }
+
+  return true;
+};
+
+EventEmitter.prototype.addListener = function(type, listener) {
+  var m;
+
+  if (!isFunction(listener))
+    throw TypeError('listener must be a function');
+
+  if (!this._events)
+    this._events = {};
+
+  // To avoid recursion in the case that type === "newListener"! Before
+  // adding it to the listeners, first emit "newListener".
+  if (this._events.newListener)
+    this.emit('newListener', type,
+              isFunction(listener.listener) ?
+              listener.listener : listener);
+
+  if (!this._events[type])
+    // Optimize the case of one listener. Don't need the extra array object.
+    this._events[type] = listener;
+  else if (isObject(this._events[type]))
+    // If we've already got an array, just append.
+    this._events[type].push(listener);
+  else
+    // Adding the second element, need to change to array.
+    this._events[type] = [this._events[type], listener];
+
+  // Check for listener leak
+  if (isObject(this._events[type]) && !this._events[type].warned) {
+    if (!isUndefined(this._maxListeners)) {
+      m = this._maxListeners;
+    } else {
+      m = EventEmitter.defaultMaxListeners;
+    }
+
+    if (m && m > 0 && this._events[type].length > m) {
+      this._events[type].warned = true;
+      console.error('(node) warning: possible EventEmitter memory ' +
+                    'leak detected. %d listeners added. ' +
+                    'Use emitter.setMaxListeners() to increase limit.',
+                    this._events[type].length);
+      if (typeof console.trace === 'function') {
+        // not supported in IE 10
+        console.trace();
+      }
+    }
+  }
+
+  return this;
+};
+
+EventEmitter.prototype.on = EventEmitter.prototype.addListener;
+
+EventEmitter.prototype.once = function(type, listener) {
+  if (!isFunction(listener))
+    throw TypeError('listener must be a function');
+
+  var fired = false;
+
+  function g() {
+    this.removeListener(type, g);
+
+    if (!fired) {
+      fired = true;
+      listener.apply(this, arguments);
+    }
+  }
+
+  g.listener = listener;
+  this.on(type, g);
+
+  return this;
+};
+
+// emits a 'removeListener' event iff the listener was removed
+EventEmitter.prototype.removeListener = function(type, listener) {
+  var list, position, length, i;
+
+  if (!isFunction(listener))
+    throw TypeError('listener must be a function');
+
+  if (!this._events || !this._events[type])
+    return this;
+
+  list = this._events[type];
+  length = list.length;
+  position = -1;
+
+  if (list === listener ||
+      (isFunction(list.listener) && list.listener === listener)) {
+    delete this._events[type];
+    if (this._events.removeListener)
+      this.emit('removeListener', type, listener);
+
+  } else if (isObject(list)) {
+    for (i = length; i-- > 0;) {
+      if (list[i] === listener ||
+          (list[i].listener && list[i].listener === listener)) {
+        position = i;
+        break;
+      }
+    }
+
+    if (position < 0)
+      return this;
+
+    if (list.length === 1) {
+      list.length = 0;
+      delete this._events[type];
+    } else {
+      list.splice(position, 1);
+    }
+
+    if (this._events.removeListener)
+      this.emit('removeListener', type, listener);
+  }
+
+  return this;
+};
+
+EventEmitter.prototype.removeAllListeners = function(type) {
+  var key, listeners;
+
+  if (!this._events)
+    return this;
+
+  // not listening for removeListener, no need to emit
+  if (!this._events.removeListener) {
+    if (arguments.length === 0)
+      this._events = {};
+    else if (this._events[type])
+      delete this._events[type];
+    return this;
+  }
+
+  // emit removeListener for all listeners on all events
+  if (arguments.length === 0) {
+    for (key in this._events) {
+      if (key === 'removeListener') continue;
+      this.removeAllListeners(key);
+    }
+    this.removeAllListeners('removeListener');
+    this._events = {};
+    return this;
+  }
+
+  listeners = this._events[type];
+
+  if (isFunction(listeners)) {
+    this.removeListener(type, listeners);
+  } else if (listeners) {
+    // LIFO order
+    while (listeners.length)
+      this.removeListener(type, listeners[listeners.length - 1]);
+  }
+  delete this._events[type];
+
+  return this;
+};
+
+EventEmitter.prototype.listeners = function(type) {
+  var ret;
+  if (!this._events || !this._events[type])
+    ret = [];
+  else if (isFunction(this._events[type]))
+    ret = [this._events[type]];
+  else
+    ret = this._events[type].slice();
+  return ret;
+};
+
+EventEmitter.prototype.listenerCount = function(type) {
+  if (this._events) {
+    var evlistener = this._events[type];
+
+    if (isFunction(evlistener))
+      return 1;
+    else if (evlistener)
+      return evlistener.length;
+  }
+  return 0;
+};
+
+EventEmitter.listenerCount = function(emitter, type) {
+  return emitter.listenerCount(type);
+};
+
+function isFunction(arg) {
+  return typeof arg === 'function';
+}
+
+function isNumber(arg) {
+  return typeof arg === 'number';
+}
+
+function isObject(arg) {
+  return typeof arg === 'object' && arg !== null;
+}
+
+function isUndefined(arg) {
+  return arg === void 0;
+}
+
+},{}],55:[function(require,module,exports){
+// shim for using process in browser
+
+var process = module.exports = {};
+var queue = [];
+var draining = false;
+var currentQueue;
+var queueIndex = -1;
+
+function cleanUpNextTick() {
+    draining = false;
+    if (currentQueue.length) {
+        queue = currentQueue.concat(queue);
+    } else {
+        queueIndex = -1;
+    }
+    if (queue.length) {
+        drainQueue();
+    }
+}
+
+function drainQueue() {
+    if (draining) {
+        return;
+    }
+    var timeout = setTimeout(cleanUpNextTick);
+    draining = true;
+
+    var len = queue.length;
+    while(len) {
+        currentQueue = queue;
+        queue = [];
+        while (++queueIndex < len) {
+            if (currentQueue) {
+                currentQueue[queueIndex].run();
+            }
+        }
+        queueIndex = -1;
+        len = queue.length;
+    }
+    currentQueue = null;
+    draining = false;
+    clearTimeout(timeout);
+}
+
+process.nextTick = function (fun) {
+    var args = new Array(arguments.length - 1);
+    if (arguments.length > 1) {
+        for (var i = 1; i < arguments.length; i++) {
+            args[i - 1] = arguments[i];
+        }
+    }
+    queue.push(new Item(fun, args));
+    if (queue.length === 1 && !draining) {
+        setTimeout(drainQueue, 0);
+    }
+};
+
+// v8 likes predictible objects
+function Item(fun, array) {
+    this.fun = fun;
+    this.array = array;
+}
+Item.prototype.run = function () {
+    this.fun.apply(null, this.array);
+};
+process.title = 'browser';
+process.browser = true;
+process.env = {};
+process.argv = [];
+process.version = ''; // empty string to avoid regexp issues
+process.versions = {};
+
+function noop() {}
+
+process.on = noop;
+process.addListener = noop;
+process.once = noop;
+process.off = noop;
+process.removeListener = noop;
+process.removeAllListeners = noop;
+process.emit = noop;
+
+process.binding = function (name) {
+    throw new Error('process.binding is not supported');
+};
+
+process.cwd = function () { return '/' };
+process.chdir = function (dir) {
+    throw new Error('process.chdir is not supported');
+};
+process.umask = function() { return 0; };
+
+},{}],56:[function(require,module,exports){
+module.exports={"jet":[{"index":0,"rgb":[0,0,131]},{"index":0.125,"rgb":[0,60,170]},{"index":0.375,"rgb":[5,255,255]},{"index":0.625,"rgb":[255,255,0]},{"index":0.875,"rgb":[250,0,0]},{"index":1,"rgb":[128,0,0]}],"hsv":[{"index":0,"rgb":[255,0,0]},{"index":0.169,"rgb":[253,255,2]},{"index":0.173,"rgb":[247,255,2]},{"index":0.337,"rgb":[0,252,4]},{"index":0.341,"rgb":[0,252,10]},{"index":0.506,"rgb":[1,249,255]},{"index":0.671,"rgb":[2,0,253]},{"index":0.675,"rgb":[8,0,253]},{"index":0.839,"rgb":[255,0,251]},{"index":0.843,"rgb":[255,0,245]},{"index":1,"rgb":[255,0,6]}],"hot":[{"index":0,"rgb":[0,0,0]},{"index":0.3,"rgb":[230,0,0]},{"index":0.6,"rgb":[255,210,0]},{"index":1,"rgb":[255,255,255]}],"cool":[{"index":0,"rgb":[0,255,255]},{"index":1,"rgb":[255,0,255]}],"spring":[{"index":0,"rgb":[255,0,255]},{"index":1,"rgb":[255,255,0]}],"summer":[{"index":0,"rgb":[0,128,102]},{"index":1,"rgb":[255,255,102]}],"autumn":[{"index":0,"rgb":[255,0,0]},{"index":1,"rgb":[255,255,0]}],"winter":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[0,255,128]}],"bone":[{"index":0,"rgb":[0,0,0]},{"index":0.376,"rgb":[84,84,116]},{"index":0.753,"rgb":[169,200,200]},{"index":1,"rgb":[255,255,255]}],"copper":[{"index":0,"rgb":[0,0,0]},{"index":0.804,"rgb":[255,160,102]},{"index":1,"rgb":[255,199,127]}],"greys":[{"index":0,"rgb":[0,0,0]},{"index":1,"rgb":[255,255,255]}],"yignbu":[{"index":0,"rgb":[8,29,88]},{"index":0.125,"rgb":[37,52,148]},{"index":0.25,"rgb":[34,94,168]},{"index":0.375,"rgb":[29,145,192]},{"index":0.5,"rgb":[65,182,196]},{"index":0.625,"rgb":[127,205,187]},{"index":0.75,"rgb":[199,233,180]},{"index":0.875,"rgb":[237,248,217]},{"index":1,"rgb":[255,255,217]}],"greens":[{"index":0,"rgb":[0,68,27]},{"index":0.125,"rgb":[0,109,44]},{"index":0.25,"rgb":[35,139,69]},{"index":0.375,"rgb":[65,171,93]},{"index":0.5,"rgb":[116,196,118]},{"index":0.625,"rgb":[161,217,155]},{"index":0.75,"rgb":[199,233,192]},{"index":0.875,"rgb":[229,245,224]},{"index":1,"rgb":[247,252,245]}],"yiorrd":[{"index":0,"rgb":[128,0,38]},{"index":0.125,"rgb":[189,0,38]},{"index":0.25,"rgb":[227,26,28]},{"index":0.375,"rgb":[252,78,42]},{"index":0.5,"rgb":[253,141,60]},{"index":0.625,"rgb":[254,178,76]},{"index":0.75,"rgb":[254,217,118]},{"index":0.875,"rgb":[255,237,160]},{"index":1,"rgb":[255,255,204]}],"bluered":[{"index":0,"rgb":[0,0,255]},{"index":1,"rgb":[255,0,0]}],"rdbu":[{"index":0,"rgb":[5,10,172]},{"index":0.35,"rgb":[106,137,247]},{"index":0.5,"rgb":[190,190,190]},{"index":0.6,"rgb":[220,170,132]},{"index":0.7,"rgb":[230,145,90]},{"index":1,"rgb":[178,10,28]}],"picnic":[{"index":0,"rgb":[0,0,255]},{"index":0.1,"rgb":[51,153,255]},{"index":0.2,"rgb":[102,204,255]},{"index":0.3,"rgb":[153,204,255]},{"index":0.4,"rgb":[204,204,255]},{"index":0.5,"rgb":[255,255,255]},{"index":0.6,"rgb":[255,204,255]},{"index":0.7,"rgb":[255,153,255]},{"index":0.8,"rgb":[255,102,204]},{"index":0.9,"rgb":[255,102,102]},{"index":1,"rgb":[255,0,0]}],"rainbow":[{"index":0,"rgb":[150,0,90]},{"index":0.125,"rgb":[0,0,200]},{"index":0.25,"rgb":[0,25,255]},{"index":0.375,"rgb":[0,152,255]},{"index":0.5,"rgb":[44,255,150]},{"index":0.625,"rgb":[151,255,0]},{"index":0.75,"rgb":[255,234,0]},{"index":0.875,"rgb":[255,111,0]},{"index":1,"rgb":[255,0,0]}],"portland":[{"index":0,"rgb":[12,51,131]},{"index":0.25,"rgb":[10,136,186]},{"index":0.5,"rgb":[242,211,56]},{"index":0.75,"rgb":[242,143,56]},{"index":1,"rgb":[217,30,30]}],"blackbody":[{"index":0,"rgb":[0,0,0]},{"index":0.2,"rgb":[230,0,0]},{"index":0.4,"rgb":[230,210,0]},{"index":0.7,"rgb":[255,255,255]},{"index":1,"rgb":[160,200,255]}],"earth":[{"index":0,"rgb":[0,0,130]},{"index":0.1,"rgb":[0,180,180]},{"index":0.2,"rgb":[40,210,40]},{"index":0.4,"rgb":[230,230,50]},{"index":0.6,"rgb":[120,70,20]},{"index":1,"rgb":[255,255,255]}],"electric":[{"index":0,"rgb":[0,0,0]},{"index":0.15,"rgb":[30,0,100]},{"index":0.4,"rgb":[120,0,100]},{"index":0.6,"rgb":[160,90,0]},{"index":0.8,"rgb":[230,200,0]},{"index":1,"rgb":[255,250,220]}], "alpha": [{"index":0, "rgb": [255,255,255,0]},{"index":0, "rgb": [255,255,255,1]}]};
+
+},{}],57:[function(require,module,exports){
+/*
+ * Ben Postlethwaite
+ * January 2013
+ * License MIT
+ */
+'use strict';
+
+var at = require('arraytools');
+var clone = require('clone');
+var colorScale = require('./colorScales');
+
+module.exports = function (spec) {
+
+    /*
+     * Default Options
+     */
+    var indicies, rgba, fromrgba, torgba,
+        nsteps, cmap, colormap, format,
+        nshades, colors, alpha, index, i,
+        r = [],
+        g = [],
+        b = [],
+        a = [];
+
+    if ( !at.isPlainObject(spec) ) spec = {};
+
+    nshades = spec.nshades || 72;
+    format = spec.format || 'hex';
+
+    colormap = spec.colormap;
+    if (!colormap) colormap = 'jet';
+
+    if (typeof colormap === 'string') {
+        colormap = colormap.toLowerCase();
+
+        if (!colorScale[colormap]) {
+            throw Error(colormap + ' not a supported colorscale');
+        }
+
+        cmap = clone(colorScale[colormap]);
+
+    } else if (Array.isArray(colormap)) {
+        cmap = clone(colormap);
+
+    } else {
+        throw Error('unsupported colormap option', colormap);
+    }
+
+    if (cmap.length > nshades) {
+        throw new Error(
+            colormap+' map requires nshades to be at least size '+cmap.length
+        );
+    }
+
+    if (!Array.isArray(spec.alpha)) {
+
+        if (typeof spec.alpha === 'number') {
+            alpha = [spec.alpha, spec.alpha];
+
+        } else {
+            alpha = [1, 1];
+        }
+
+    } else if (spec.alpha.length !== 2) {
+        alpha = [1, 1];
+
+    } else {
+        alpha = clone(spec.alpha);
+    }
+
+    /*
+     * map index points from 0->1 to 0 -> n-1
+     */
+    indicies = cmap.map(function(c) {
+        return Math.round(c.index * nshades);
+    });
+
+    /*
+     * Add alpha channel to the map
+     */
+    if (alpha[0] < 0) alpha[0] = 0;
+    if (alpha[1] < 0) alpha[0] = 0;
+    if (alpha[0] > 1) alpha[0] = 1;
+    if (alpha[1] > 1) alpha[0] = 1;
+
+    for (i = 0; i < indicies.length; ++i) {
+        index = cmap[i].index;
+        rgba = cmap[i].rgb;
+
+        // if user supplies their own map use it
+        if (rgba.length === 4 && rgba[3] >= 0 && rgba[3] <= 1) continue;
+        rgba[3] = alpha[0] + (alpha[1] - alpha[0])*index;
+    }
+
+    /*
+     * map increasing linear values between indicies to
+     * linear steps in colorvalues
+     */
+    for (i = 0; i < indicies.length-1; ++i) {
+        nsteps = indicies[i+1] - indicies[i];
+        fromrgba = cmap[i].rgb;
+        torgba = cmap[i+1].rgb;
+        r = r.concat(at.linspace(fromrgba[0], torgba[0], nsteps ) );
+        g = g.concat(at.linspace(fromrgba[1], torgba[1], nsteps ) );
+        b = b.concat(at.linspace(fromrgba[2], torgba[2], nsteps ) );
+        a = a.concat(at.linspace(fromrgba[3], torgba[3], nsteps ) );
+    }
+
+    r = r.map( Math.round );
+    g = g.map( Math.round );
+    b = b.map( Math.round );
+
+    colors = at.zip(r, g, b, a);
+
+    if (format === 'hex') colors = colors.map( rgb2hex );
+    if (format === 'rgbaString') colors = colors.map( rgbaStr );
+
+    return colors;
+};
+
+
+function rgb2hex (rgba) {
+    var dig, hex = '#';
+    for (var i = 0; i < 3; ++i) {
+        dig = rgba[i];
+        dig = dig.toString(16);
+        hex += ('00' + dig).substr( dig.length );
+    }
+    return hex;
+}
+
+function rgbaStr (rgba) {
+    return 'rgba(' + rgba.join(',') + ')';
+}
+
+},{"./colorScales":56,"arraytools":48,"clone":58}],58:[function(require,module,exports){
+(function (Buffer){
+var clone = (function() {
+'use strict';
+
+/**
+ * Clones (copies) an Object using deep copying.
+ *
+ * This function supports circular references by default, but if you are certain
+ * there are no circular references in your object, you can save some CPU time
+ * by calling clone(obj, false).
+ *
+ * Caution: if `circular` is false and `parent` contains circular references,
+ * your program may enter an infinite loop and crash.
+ *
+ * @param `parent` - the object to be cloned
+ * @param `circular` - set to true if the object to be cloned may contain
+ *    circular references. (optional - true by default)
+ * @param `depth` - set to a number if the object is only to be cloned to
+ *    a particular depth. (optional - defaults to Infinity)
+ * @param `prototype` - sets the prototype to be used when cloning an object.
+ *    (optional - defaults to parent prototype).
+*/
+function clone(parent, circular, depth, prototype) {
+  var filter;
+  if (typeof circular === 'object') {
+    depth = circular.depth;
+    prototype = circular.prototype;
+    filter = circular.filter;
+    circular = circular.circular
+  }
+  // maintain two arrays for circular references, where corresponding parents
+  // and children have the same index
+  var allParents = [];
+  var allChildren = [];
+
+  var useBuffer = typeof Buffer != 'undefined';
+
+  if (typeof circular == 'undefined')
+    circular = true;
+
+  if (typeof depth == 'undefined')
+    depth = Infinity;
+
+  // recurse this function so we don't reset allParents and allChildren
+  function _clone(parent, depth) {
+    // cloning null always returns null
+    if (parent === null)
+      return null;
+
+    if (depth == 0)
+      return parent;
+
+    var child;
+    var proto;
+    if (typeof parent != 'object') {
+      return parent;
+    }
+
+    if (clone.__isArray(parent)) {
+      child = [];
+    } else if (clone.__isRegExp(parent)) {
+      child = new RegExp(parent.source, __getRegExpFlags(parent));
+      if (parent.lastIndex) child.lastIndex = parent.lastIndex;
+    } else if (clone.__isDate(parent)) {
+      child = new Date(parent.getTime());
+    } else if (useBuffer && Buffer.isBuffer(parent)) {
+      child = new Buffer(parent.length);
+      parent.copy(child);
+      return child;
+    } else {
+      if (typeof prototype == 'undefined') {
+        proto = Object.getPrototypeOf(parent);
+        child = Object.create(proto);
+      }
+      else {
+        child = Object.create(prototype);
+        proto = prototype;
+      }
+    }
+
+    if (circular) {
+      var index = allParents.indexOf(parent);
+
+      if (index != -1) {
+        return allChildren[index];
+      }
+      allParents.push(parent);
+      allChildren.push(child);
+    }
+
+    for (var i in parent) {
+      var attrs;
+      if (proto) {
+        attrs = Object.getOwnPropertyDescriptor(proto, i);
+      }
+
+      if (attrs && attrs.set == null) {
+        continue;
+      }
+      child[i] = _clone(parent[i], depth - 1);
+    }
+
+    return child;
+  }
+
+  return _clone(parent, depth);
+}
+
+/**
+ * Simple flat clone using prototype, accepts only objects, usefull for property
+ * override on FLAT configuration object (no nested props).
+ *
+ * USE WITH CAUTION! This may not behave as you wish if you do not know how this
+ * works.
+ */
+clone.clonePrototype = function clonePrototype(parent) {
+  if (parent === null)
+    return null;
+
+  var c = function () {};
+  c.prototype = parent;
+  return new c();
+};
+
+// private utility functions
+
+function __objToStr(o) {
+  return Object.prototype.toString.call(o);
+};
+clone.__objToStr = __objToStr;
+
+function __isDate(o) {
+  return typeof o === 'object' && __objToStr(o) === '[object Date]';
+};
+clone.__isDate = __isDate;
+
+function __isArray(o) {
+  return typeof o === 'object' && __objToStr(o) === '[object Array]';
+};
+clone.__isArray = __isArray;
+
+function __isRegExp(o) {
+  return typeof o === 'object' && __objToStr(o) === '[object RegExp]';
+};
+clone.__isRegExp = __isRegExp;
+
+function __getRegExpFlags(re) {
+  var flags = '';
+  if (re.global) flags += 'g';
+  if (re.ignoreCase) flags += 'i';
+  if (re.multiline) flags += 'm';
+  return flags;
+};
+clone.__getRegExpFlags = __getRegExpFlags;
+
+return clone;
+})();
+
+if (typeof module === 'object' && module.exports) {
+  module.exports = clone;
+}
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":50}],59:[function(require,module,exports){
+module.exports = compareCells
+
+var min = Math.min
+
+function compareInt(a, b) {
+  return a - b
+}
+
+function compareCells(a, b) {
+  var n = a.length
+    , t = a.length - b.length
+  if(t) {
+    return t
+  }
+  switch(n) {
+    case 0:
+      return 0
+    case 1:
+      return a[0] - b[0]
+    case 2:
+      return (a[0]+a[1]-b[0]-b[1]) ||
+             min(a[0],a[1]) - min(b[0],b[1])
+    case 3:
+      var l1 = a[0]+a[1]
+        , m1 = b[0]+b[1]
+      t = l1+a[2] - (m1+b[2])
+      if(t) {
+        return t
+      }
+      var l0 = min(a[0], a[1])
+        , m0 = min(b[0], b[1])
+      return min(l0, a[2]) - min(m0, b[2]) ||
+             min(l0+a[2], l1) - min(m0+b[2], m1)
+    case 4:
+      var aw=a[0], ax=a[1], ay=a[2], az=a[3]
+        , bw=b[0], bx=b[1], by=b[2], bz=b[3]
+      return (aw+ax+ay+az)-(bw+bx+by+bz) ||
+             min(aw,ax,ay,az)-min(bw,bx,by,bz,bw) ||
+             min(aw+ax,aw+ay,aw+az,ax+ay,ax+az,ay+az) -
+               min(bw+bx,bw+by,bw+bz,bx+by,bx+bz,by+bz) ||
+             min(aw+ax+ay,aw+ax+az,aw+ay+az,ax+ay+az) -
+               min(bw+bx+by,bw+bx+bz,bw+by+bz,bx+by+bz)
+    default:
+      var as = a.slice().sort(compareInt)
+      var bs = b.slice().sort(compareInt)
+      for(var i=0; i<n; ++i) {
+        t = as[i] - bs[i]
+        if(t) {
+          return t
+        }
+      }
+      return 0
+  }
+}
+
+},{}],60:[function(require,module,exports){
+"use strict"
+
+var convexHull1d = require('./lib/ch1d')
+var convexHull2d = require('./lib/ch2d')
+var convexHullnd = require('./lib/chnd')
+
+module.exports = convexHull
+
+function convexHull(points) {
+  var n = points.length
+  if(n === 0) {
+    return []
+  } else if(n === 1) {
+    return [[0]]
+  }
+  var d = points[0].length
+  if(d === 0) {
+    return []
+  } else if(d === 1) {
+    return convexHull1d(points)
+  } else if(d === 2) {
+    return convexHull2d(points)
+  }
+  return convexHullnd(points, d)
+}
+},{"./lib/ch1d":61,"./lib/ch2d":62,"./lib/chnd":63}],61:[function(require,module,exports){
+"use strict"
+
+module.exports = convexHull1d
+
+function convexHull1d(points) {
+  var lo = 0
+  var hi = 0
+  for(var i=1; i<points.length; ++i) {
+    if(points[i][0] < points[lo][0]) {
+      lo = i
+    }
+    if(points[i][0] > points[hi][0]) {
+      hi = i
+    }
+  }
+  if(lo < hi) {
+    return [[lo], [hi]]
+  } else if(lo > hi) {
+    return [[hi], [lo]]
+  } else {
+    return [[lo]]
+  }
+}
+},{}],62:[function(require,module,exports){
+'use strict'
+
+module.exports = convexHull2D
+
+var monotoneHull = require('monotone-convex-hull-2d')
+
+function convexHull2D(points) {
+  var hull = monotoneHull(points)
+  var h = hull.length
+  if(h <= 2) {
+    return []
+  }
+  var edges = new Array(h)
+  var a = hull[h-1]
+  for(var i=0; i<h; ++i) {
+    var b = hull[i]
+    edges[i] = [a,b]
+    a = b
+  }
+  return edges
+}
+
+},{"monotone-convex-hull-2d":65}],63:[function(require,module,exports){
+'use strict'
+
+module.exports = convexHullnD
+
+var ich = require('incremental-convex-hull')
+var aff = require('affine-hull')
+
+function permute(points, front) {
+  var n = points.length
+  var npoints = new Array(n)
+  for(var i=0; i<front.length; ++i) {
+    npoints[i] = points[front[i]]
+  }
+  var ptr = front.length
+  for(var i=0; i<n; ++i) {
+    if(front.indexOf(i) < 0) {
+      npoints[ptr++] = points[i]
+    }
+  }
+  return npoints
+}
+
+function invPermute(cells, front) {
+  var nc = cells.length
+  var nf = front.length
+  for(var i=0; i<nc; ++i) {
+    var c = cells[i]
+    for(var j=0; j<c.length; ++j) {
+      var x = c[j]
+      if(x < nf) {
+        c[j] = front[x]
+      } else {
+        x = x - nf
+        for(var k=0; k<nf; ++k) {
+          if(x >= front[k]) {
+            x += 1
+          }
+        }
+        c[j] = x
+      }
+    }
+  }
+  return cells
+}
+
+function convexHullnD(points, d) {
+  try {
+    return ich(points, true)
+  } catch(e) {
+    //If point set is degenerate, try to find a basis and rerun it
+    var ah = aff(points)
+    if(ah.length <= d) {
+      //No basis, no try
+      return []
+    }
+    var npoints = permute(points, ah)
+    var nhull   = ich(npoints, true)
+    return invPermute(nhull, ah)
+  }
+}
+},{"affine-hull":64,"incremental-convex-hull":191}],64:[function(require,module,exports){
+'use strict'
+
+module.exports = affineHull
+
+var orient = require('robust-orientation')
+
+function linearlyIndependent(points, d) {
+  var nhull = new Array(d+1)
+  for(var i=0; i<points.length; ++i) {
+    nhull[i] = points[i]
+  }
+  for(var i=0; i<=points.length; ++i) {
+    for(var j=points.length; j<=d; ++j) {
+      var x = new Array(d)
+      for(var k=0; k<d; ++k) {
+        x[k] = Math.pow(j+1-i, k)
+      }
+      nhull[j] = x
+    }
+    var o = orient.apply(void 0, nhull)
+    if(o) {
+      return true
+    }
+  }
+  return false
+}
+
+function affineHull(points) {
+  var n = points.length
+  if(n === 0) {
+    return []
+  }
+  if(n === 1) {
+    return [0]
+  }
+  var d = points[0].length
+  var frame = [ points[0] ]
+  var index = [ 0 ]
+  for(var i=1; i<n; ++i) {
+    frame.push(points[i])
+    if(!linearlyIndependent(frame, d)) {
+      frame.pop()
+      continue
+    }
+    index.push(i)
+    if(index.length === d+1) {
+      return index
+    }
+  }
+  return index
+}
+},{"robust-orientation":214}],65:[function(require,module,exports){
+'use strict'
+
+module.exports = monotoneConvexHull2D
+
+var orient = require('robust-orientation')[3]
+
+function monotoneConvexHull2D(points) {
+  var n = points.length
+
+  if(n < 3) {
+    var result = new Array(n)
+    for(var i=0; i<n; ++i) {
+      result[i] = i
+    }
+
+    if(n === 2 &&
+       points[0][0] === points[1][0] &&
+       points[0][1] === points[1][1]) {
+      return [0]
+    }
+
+    return result
+  }
+
+  //Sort point indices along x-axis
+  var sorted = new Array(n)
+  for(var i=0; i<n; ++i) {
+    sorted[i] = i
+  }
+  sorted.sort(function(a,b) {
+    var d = points[a][0]-points[b][0]
+    if(d) {
+      return d
+    }
+    return points[a][1] - points[b][1]
+  })
+
+  //Construct upper and lower hulls
+  var lower = [sorted[0], sorted[1]]
+  var upper = [sorted[0], sorted[1]]
+
+  for(var i=2; i<n; ++i) {
+    var idx = sorted[i]
+    var p   = points[idx]
+
+    //Insert into lower list
+    var m = lower.length
+    while(m > 1 && orient(
+        points[lower[m-2]], 
+        points[lower[m-1]], 
+        p) <= 0) {
+      m -= 1
+      lower.pop()
+    }
+    lower.push(idx)
+
+    //Insert into upper list
+    m = upper.length
+    while(m > 1 && orient(
+        points[upper[m-2]], 
+        points[upper[m-1]], 
+        p) >= 0) {
+      m -= 1
+      upper.pop()
+    }
+    upper.push(idx)
+  }
+
+  //Merge lists together
+  var result = new Array(upper.length + lower.length - 2)
+  var ptr    = 0
+  for(var i=0, nl=lower.length; i<nl; ++i) {
+    result[ptr++] = lower[i]
+  }
+  for(var j=upper.length-2; j>0; --j) {
+    result[ptr++] = upper[j]
+  }
+
+  //Return result
+  return result
+}
+},{"robust-orientation":214}],66:[function(require,module,exports){
+"use strict"
+
+var createThunk = require("./lib/thunk.js")
+
+function Procedure() {
+  this.argTypes = []
+  this.shimArgs = []
+  this.arrayArgs = []
+  this.arrayBlockIndices = []
+  this.scalarArgs = []
+  this.offsetArgs = []
+  this.offsetArgIndex = []
+  this.indexArgs = []
+  this.shapeArgs = []
+  this.funcName = ""
+  this.pre = null
+  this.body = null
+  this.post = null
+  this.debug = false
+}
+
+function compileCwise(user_args) {
+  //Create procedure
+  var proc = new Procedure()
+  
+  //Parse blocks
+  proc.pre    = user_args.pre
+  proc.body   = user_args.body
+  proc.post   = user_args.post
+
+  //Parse arguments
+  var proc_args = user_args.args.slice(0)
+  proc.argTypes = proc_args
+  for(var i=0; i<proc_args.length; ++i) {
+    var arg_type = proc_args[i]
+    if(arg_type === "array" || (typeof arg_type === "object" && arg_type.blockIndices)) {
+      proc.argTypes[i] = "array"
+      proc.arrayArgs.push(i)
+      proc.arrayBlockIndices.push(arg_type.blockIndices ? arg_type.blockIndices : 0)
+      proc.shimArgs.push("array" + i)
+      if(i < proc.pre.args.length && proc.pre.args[i].count>0) {
+        throw new Error("cwise: pre() block may not reference array args")
+      }
+      if(i < proc.post.args.length && proc.post.args[i].count>0) {
+        throw new Error("cwise: post() block may not reference array args")
+      }
+    } else if(arg_type === "scalar") {
+      proc.scalarArgs.push(i)
+      proc.shimArgs.push("scalar" + i)
+    } else if(arg_type === "index") {
+      proc.indexArgs.push(i)
+      if(i < proc.pre.args.length && proc.pre.args[i].count > 0) {
+        throw new Error("cwise: pre() block may not reference array index")
+      }
+      if(i < proc.body.args.length && proc.body.args[i].lvalue) {
+        throw new Error("cwise: body() block may not write to array index")
+      }
+      if(i < proc.post.args.length && proc.post.args[i].count > 0) {
+        throw new Error("cwise: post() block may not reference array index")
+      }
+    } else if(arg_type === "shape") {
+      proc.shapeArgs.push(i)
+      if(i < proc.pre.args.length && proc.pre.args[i].lvalue) {
+        throw new Error("cwise: pre() block may not write to array shape")
+      }
+      if(i < proc.body.args.length && proc.body.args[i].lvalue) {
+        throw new Error("cwise: body() block may not write to array shape")
+      }
+      if(i < proc.post.args.length && proc.post.args[i].lvalue) {
+        throw new Error("cwise: post() block may not write to array shape")
+      }
+    } else if(typeof arg_type === "object" && arg_type.offset) {
+      proc.argTypes[i] = "offset"
+      proc.offsetArgs.push({ array: arg_type.array, offset:arg_type.offset })
+      proc.offsetArgIndex.push(i)
+    } else {
+      throw new Error("cwise: Unknown argument type " + proc_args[i])
+    }
+  }
+  
+  //Make sure at least one array argument was specified
+  if(proc.arrayArgs.length <= 0) {
+    throw new Error("cwise: No array arguments specified")
+  }
+  
+  //Make sure arguments are correct
+  if(proc.pre.args.length > proc_args.length) {
+    throw new Error("cwise: Too many arguments in pre() block")
+  }
+  if(proc.body.args.length > proc_args.length) {
+    throw new Error("cwise: Too many arguments in body() block")
+  }
+  if(proc.post.args.length > proc_args.length) {
+    throw new Error("cwise: Too many arguments in post() block")
+  }
+
+  //Check debug flag
+  proc.debug = !!user_args.printCode || !!user_args.debug
+  
+  //Retrieve name
+  proc.funcName = user_args.funcName || "cwise"
+  
+  //Read in block size
+  proc.blockSize = user_args.blockSize || 64
+
+  return createThunk(proc)
+}
+
+module.exports = compileCwise
+
+},{"./lib/thunk.js":68}],67:[function(require,module,exports){
+"use strict"
+
+var uniq = require("uniq")
+
+// This function generates very simple loops analogous to how you typically traverse arrays (the outermost loop corresponds to the slowest changing index, the innermost loop to the fastest changing index)
+// TODO: If two arrays have the same strides (and offsets) there is potential for decreasing the number of "pointers" and related variables. The drawback is that the type signature would become more specific and that there would thus be less potential for caching, but it might still be worth it, especially when dealing with large numbers of arguments.
+function innerFill(order, proc, body) {
+  var dimension = order.length
+    , nargs = proc.arrayArgs.length
+    , has_index = proc.indexArgs.length>0
+    , code = []
+    , vars = []
+    , idx=0, pidx=0, i, j
+  for(i=0; i<dimension; ++i) { // Iteration variables
+    vars.push(["i",i,"=0"].join(""))
+  }
+  //Compute scan deltas
+  for(j=0; j<nargs; ++j) {
+    for(i=0; i<dimension; ++i) {
+      pidx = idx
+      idx = order[i]
+      if(i === 0) { // The innermost/fastest dimension's delta is simply its stride
+        vars.push(["d",j,"s",i,"=t",j,"p",idx].join(""))
+      } else { // For other dimensions the delta is basically the stride minus something which essentially "rewinds" the previous (more inner) dimension
+        vars.push(["d",j,"s",i,"=(t",j,"p",idx,"-s",pidx,"*t",j,"p",pidx,")"].join(""))
+      }
+    }
+  }
+  code.push("var " + vars.join(","))
+  //Scan loop
+  for(i=dimension-1; i>=0; --i) { // Start at largest stride and work your way inwards
+    idx = order[i]
+    code.push(["for(i",i,"=0;i",i,"<s",idx,";++i",i,"){"].join(""))
+  }
+  //Push body of inner loop
+  code.push(body)
+  //Advance scan pointers
+  for(i=0; i<dimension; ++i) {
+    pidx = idx
+    idx = order[i]
+    for(j=0; j<nargs; ++j) {
+      code.push(["p",j,"+=d",j,"s",i].join(""))
+    }
+    if(has_index) {
+      if(i > 0) {
+        code.push(["index[",pidx,"]-=s",pidx].join(""))
+      }
+      code.push(["++index[",idx,"]"].join(""))
+    }
+    code.push("}")
+  }
+  return code.join("\n")
+}
+
+// Generate "outer" loops that loop over blocks of data, applying "inner" loops to the blocks by manipulating the local variables in such a way that the inner loop only "sees" the current block.
+// TODO: If this is used, then the previous declaration (done by generateCwiseOp) of s* is essentially unnecessary.
+//       I believe the s* are not used elsewhere (in particular, I don't think they're used in the pre/post parts and "shape" is defined independently), so it would be possible to make defining the s* dependent on what loop method is being used.
+function outerFill(matched, order, proc, body) {
+  var dimension = order.length
+    , nargs = proc.arrayArgs.length
+    , blockSize = proc.blockSize
+    , has_index = proc.indexArgs.length > 0
+    , code = []
+  for(var i=0; i<nargs; ++i) {
+    code.push(["var offset",i,"=p",i].join(""))
+  }
+  //Generate loops for unmatched dimensions
+  // The order in which these dimensions are traversed is fairly arbitrary (from small stride to large stride, for the first argument)
+  // TODO: It would be nice if the order in which these loops are placed would also be somehow "optimal" (at the very least we should check that it really doesn't hurt us if they're not).
+  for(var i=matched; i<dimension; ++i) {
+    code.push(["for(var j"+i+"=SS[", order[i], "]|0;j", i, ">0;){"].join("")) // Iterate back to front
+    code.push(["if(j",i,"<",blockSize,"){"].join("")) // Either decrease j by blockSize (s = blockSize), or set it to zero (after setting s = j).
+    code.push(["s",order[i],"=j",i].join(""))
+    code.push(["j",i,"=0"].join(""))
+    code.push(["}else{s",order[i],"=",blockSize].join(""))
+    code.push(["j",i,"-=",blockSize,"}"].join(""))
+    if(has_index) {
+      code.push(["index[",order[i],"]=j",i].join(""))
+    }
+  }
+  for(var i=0; i<nargs; ++i) {
+    var indexStr = ["offset"+i]
+    for(var j=matched; j<dimension; ++j) {
+      indexStr.push(["j",j,"*t",i,"p",order[j]].join(""))
+    }
+    code.push(["p",i,"=(",indexStr.join("+"),")"].join(""))
+  }
+  code.push(innerFill(order, proc, body))
+  for(var i=matched; i<dimension; ++i) {
+    code.push("}")
+  }
+  return code.join("\n")
+}
+
+//Count the number of compatible inner orders
+// This is the length of the longest common prefix of the arrays in orders.
+// Each array in orders lists the dimensions of the correspond ndarray in order of increasing stride.
+// This is thus the maximum number of dimensions that can be efficiently traversed by simple nested loops for all arrays.
+function countMatches(orders) {
+  var matched = 0, dimension = orders[0].length
+  while(matched < dimension) {
+    for(var j=1; j<orders.length; ++j) {
+      if(orders[j][matched] !== orders[0][matched]) {
+        return matched
+      }
+    }
+    ++matched
+  }
+  return matched
+}
+
+//Processes a block according to the given data types
+// Replaces variable names by different ones, either "local" ones (that are then ferried in and out of the given array) or ones matching the arguments that the function performing the ultimate loop will accept.
+function processBlock(block, proc, dtypes) {
+  var code = block.body
+  var pre = []
+  var post = []
+  for(var i=0; i<block.args.length; ++i) {
+    var carg = block.args[i]
+    if(carg.count <= 0) {
+      continue
+    }
+    var re = new RegExp(carg.name, "g")
+    var ptrStr = ""
+    var arrNum = proc.arrayArgs.indexOf(i)
+    switch(proc.argTypes[i]) {
+      case "offset":
+        var offArgIndex = proc.offsetArgIndex.indexOf(i)
+        var offArg = proc.offsetArgs[offArgIndex]
+        arrNum = offArg.array
+        ptrStr = "+q" + offArgIndex // Adds offset to the "pointer" in the array
+      case "array":
+        ptrStr = "p" + arrNum + ptrStr
+        var localStr = "l" + i
+        var arrStr = "a" + arrNum
+        if (proc.arrayBlockIndices[arrNum] === 0) { // Argument to body is just a single value from this array
+          if(carg.count === 1) { // Argument/array used only once(?)
+            if(dtypes[arrNum] === "generic") {
+              if(carg.lvalue) {
+                pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join("")) // Is this necessary if the argument is ONLY used as an lvalue? (keep in mind that we can have a += something, so we would actually need to check carg.rvalue)
+                code = code.replace(re, localStr)
+                post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
+              } else {
+                code = code.replace(re, [arrStr, ".get(", ptrStr, ")"].join(""))
+              }
+            } else {
+              code = code.replace(re, [arrStr, "[", ptrStr, "]"].join(""))
+            }
+          } else if(dtypes[arrNum] === "generic") {
+            pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join("")) // TODO: Could we optimize by checking for carg.rvalue?
+            code = code.replace(re, localStr)
+            if(carg.lvalue) {
+              post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
+            }
+          } else {
+            pre.push(["var ", localStr, "=", arrStr, "[", ptrStr, "]"].join("")) // TODO: Could we optimize by checking for carg.rvalue?
+            code = code.replace(re, localStr)
+            if(carg.lvalue) {
+              post.push([arrStr, "[", ptrStr, "]=", localStr].join(""))
+            }
+          }
+        } else { // Argument to body is a "block"
+          var reStrArr = [carg.name], ptrStrArr = [ptrStr]
+          for(var j=0; j<Math.abs(proc.arrayBlockIndices[arrNum]); j++) {
+            reStrArr.push("\\s*\\[([^\\]]+)\\]")
+            ptrStrArr.push("$" + (j+1) + "*t" + arrNum + "b" + j) // Matched index times stride
+          }
+          re = new RegExp(reStrArr.join(""), "g")
+          ptrStr = ptrStrArr.join("+")
+          if(dtypes[arrNum] === "generic") {
+            /*if(carg.lvalue) {
+              pre.push(["var ", localStr, "=", arrStr, ".get(", ptrStr, ")"].join("")) // Is this necessary if the argument is ONLY used as an lvalue? (keep in mind that we can have a += something, so we would actually need to check carg.rvalue)
+              code = code.replace(re, localStr)
+              post.push([arrStr, ".set(", ptrStr, ",", localStr,")"].join(""))
+            } else {
+              code = code.replace(re, [arrStr, ".get(", ptrStr, ")"].join(""))
+            }*/
+            throw new Error("cwise: Generic arrays not supported in combination with blocks!")
+          } else {
+            // This does not produce any local variables, even if variables are used multiple times. It would be possible to do so, but it would complicate things quite a bit.
+            code = code.replace(re, [arrStr, "[", ptrStr, "]"].join(""))
+          }
+        }
+      break
+      case "scalar":
+        code = code.replace(re, "Y" + proc.scalarArgs.indexOf(i))
+      break
+      case "index":
+        code = code.replace(re, "index")
+      break
+      case "shape":
+        code = code.replace(re, "shape")
+      break
+    }
+  }
+  return [pre.join("\n"), code, post.join("\n")].join("\n").trim()
+}
+
+function typeSummary(dtypes) {
+  var summary = new Array(dtypes.length)
+  var allEqual = true
+  for(var i=0; i<dtypes.length; ++i) {
+    var t = dtypes[i]
+    var digits = t.match(/\d+/)
+    if(!digits) {
+      digits = ""
+    } else {
+      digits = digits[0]
+    }
+    if(t.charAt(0) === 0) {
+      summary[i] = "u" + t.charAt(1) + digits
+    } else {
+      summary[i] = t.charAt(0) + digits
+    }
+    if(i > 0) {
+      allEqual = allEqual && summary[i] === summary[i-1]
+    }
+  }
+  if(allEqual) {
+    return summary[0]
+  }
+  return summary.join("")
+}
+
+//Generates a cwise operator
+function generateCWiseOp(proc, typesig) {
+
+  //Compute dimension
+  // Arrays get put first in typesig, and there are two entries per array (dtype and order), so this gets the number of dimensions in the first array arg.
+  var dimension = (typesig[1].length - Math.abs(proc.arrayBlockIndices[0]))|0
+  var orders = new Array(proc.arrayArgs.length)
+  var dtypes = new Array(proc.arrayArgs.length)
+  for(var i=0; i<proc.arrayArgs.length; ++i) {
+    dtypes[i] = typesig[2*i]
+    orders[i] = typesig[2*i+1]
+  }
+  
+  //Determine where block and loop indices start and end
+  var blockBegin = [], blockEnd = [] // These indices are exposed as blocks
+  var loopBegin = [], loopEnd = [] // These indices are iterated over
+  var loopOrders = [] // orders restricted to the loop indices
+  for(var i=0; i<proc.arrayArgs.length; ++i) {
+    if (proc.arrayBlockIndices[i]<0) {
+      loopBegin.push(0)
+      loopEnd.push(dimension)
+      blockBegin.push(dimension)
+      blockEnd.push(dimension+proc.arrayBlockIndices[i])
+    } else {
+      loopBegin.push(proc.arrayBlockIndices[i]) // Non-negative
+      loopEnd.push(proc.arrayBlockIndices[i]+dimension)
+      blockBegin.push(0)
+      blockEnd.push(proc.arrayBlockIndices[i])
+    }
+    var newOrder = []
+    for(var j=0; j<orders[i].length; j++) {
+      if (loopBegin[i]<=orders[i][j] && orders[i][j]<loopEnd[i]) {
+        newOrder.push(orders[i][j]-loopBegin[i]) // If this is a loop index, put it in newOrder, subtracting loopBegin, to make sure that all loopOrders are using a common set of indices.
+      }
+    }
+    loopOrders.push(newOrder)
+  }
+
+  //First create arguments for procedure
+  var arglist = ["SS"] // SS is the overall shape over which we iterate
+  var code = ["'use strict'"]
+  var vars = []
+  
+  for(var j=0; j<dimension; ++j) {
+    vars.push(["s", j, "=SS[", j, "]"].join("")) // The limits for each dimension.
+  }
+  for(var i=0; i<proc.arrayArgs.length; ++i) {
+    arglist.push("a"+i) // Actual data array
+    arglist.push("t"+i) // Strides
+    arglist.push("p"+i) // Offset in the array at which the data starts (also used for iterating over the data)
+    
+    for(var j=0; j<dimension; ++j) { // Unpack the strides into vars for looping
+      vars.push(["t",i,"p",j,"=t",i,"[",loopBegin[i]+j,"]"].join(""))
+    }
+    
+    for(var j=0; j<Math.abs(proc.arrayBlockIndices[i]); ++j) { // Unpack the strides into vars for block iteration
+      vars.push(["t",i,"b",j,"=t",i,"[",blockBegin[i]+j,"]"].join(""))
+    }
+  }
+  for(var i=0; i<proc.scalarArgs.length; ++i) {
+    arglist.push("Y" + i)
+  }
+  if(proc.shapeArgs.length > 0) {
+    vars.push("shape=SS.slice(0)") // Makes the shape over which we iterate available to the user defined functions (so you can use width/height for example)
+  }
+  if(proc.indexArgs.length > 0) {
+    // Prepare an array to keep track of the (logical) indices, initialized to dimension zeroes.
+    var zeros = new Array(dimension)
+    for(var i=0; i<dimension; ++i) {
+      zeros[i] = "0"
+    }
+    vars.push(["index=[", zeros.join(","), "]"].join(""))
+  }
+  for(var i=0; i<proc.offsetArgs.length; ++i) { // Offset arguments used for stencil operations
+    var off_arg = proc.offsetArgs[i]
+    var init_string = []
+    for(var j=0; j<off_arg.offset.length; ++j) {
+      if(off_arg.offset[j] === 0) {
+        continue
+      } else if(off_arg.offset[j] === 1) {
+        init_string.push(["t", off_arg.array, "p", j].join(""))      
+      } else {
+        init_string.push([off_arg.offset[j], "*t", off_arg.array, "p", j].join(""))
+      }
+    }
+    if(init_string.length === 0) {
+      vars.push("q" + i + "=0")
+    } else {
+      vars.push(["q", i, "=", init_string.join("+")].join(""))
+    }
+  }
+
+  //Prepare this variables
+  var thisVars = uniq([].concat(proc.pre.thisVars)
+                      .concat(proc.body.thisVars)
+                      .concat(proc.post.thisVars))
+  vars = vars.concat(thisVars)
+  code.push("var " + vars.join(","))
+  for(var i=0; i<proc.arrayArgs.length; ++i) {
+    code.push("p"+i+"|=0")
+  }
+  
+  //Inline prelude
+  if(proc.pre.body.length > 3) {
+    code.push(processBlock(proc.pre, proc, dtypes))
+  }
+
+  //Process body
+  var body = processBlock(proc.body, proc, dtypes)
+  var matched = countMatches(loopOrders)
+  if(matched < dimension) {
+    code.push(outerFill(matched, loopOrders[0], proc, body)) // TODO: Rather than passing loopOrders[0], it might be interesting to look at passing an order that represents the majority of the arguments for example.
+  } else {
+    code.push(innerFill(loopOrders[0], proc, body))
+  }
+
+  //Inline epilog
+  if(proc.post.body.length > 3) {
+    code.push(processBlock(proc.post, proc, dtypes))
+  }
+  
+  if(proc.debug) {
+    console.log("-----Generated cwise routine for ", typesig, ":\n" + code.join("\n") + "\n----------")
+  }
+  
+  var loopName = [(proc.funcName||"unnamed"), "_cwise_loop_", orders[0].join("s"),"m",matched,typeSummary(dtypes)].join("")
+  var f = new Function(["function ",loopName,"(", arglist.join(","),"){", code.join("\n"),"} return ", loopName].join(""))
+  return f()
+}
+module.exports = generateCWiseOp
+
+},{"uniq":234}],68:[function(require,module,exports){
+"use strict"
+
+// The function below is called when constructing a cwise function object, and does the following:
+// A function object is constructed which accepts as argument a compilation function and returns another function.
+// It is this other function that is eventually returned by createThunk, and this function is the one that actually
+// checks whether a certain pattern of arguments has already been used before and compiles new loops as needed.
+// The compilation passed to the first function object is used for compiling new functions.
+// Once this function object is created, it is called with compile as argument, where the first argument of compile
+// is bound to "proc" (essentially containing a preprocessed version of the user arguments to cwise).
+// So createThunk roughly works like this:
+// function createThunk(proc) {
+//   var thunk = function(compileBound) {
+//     var CACHED = {}
+//     return function(arrays and scalars) {
+//       if (dtype and order of arrays in CACHED) {
+//         var func = CACHED[dtype and order of arrays]
+//       } else {
+//         var func = CACHED[dtype and order of arrays] = compileBound(dtype and order of arrays)
+//       }
+//       return func(arrays and scalars)
+//     }
+//   }
+//   return thunk(compile.bind1(proc))
+// }
+
+var compile = require("./compile.js")
+
+function createThunk(proc) {
+  var code = ["'use strict'", "var CACHED={}"]
+  var vars = []
+  var thunkName = proc.funcName + "_cwise_thunk"
+  
+  //Build thunk
+  code.push(["return function ", thunkName, "(", proc.shimArgs.join(","), "){"].join(""))
+  var typesig = []
+  var string_typesig = []
+  var proc_args = [["array",proc.arrayArgs[0],".shape.slice(", // Slice shape so that we only retain the shape over which we iterate (which gets passed to the cwise operator as SS).
+                    Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?(","+proc.arrayBlockIndices[0]+")"):")"].join("")]
+  var shapeLengthConditions = [], shapeConditions = []
+  // Process array arguments
+  for(var i=0; i<proc.arrayArgs.length; ++i) {
+    var j = proc.arrayArgs[i]
+    vars.push(["t", j, "=array", j, ".dtype,",
+               "r", j, "=array", j, ".order"].join(""))
+    typesig.push("t" + j)
+    typesig.push("r" + j)
+    string_typesig.push("t"+j)
+    string_typesig.push("r"+j+".join()")
+    proc_args.push("array" + j + ".data")
+    proc_args.push("array" + j + ".stride")
+    proc_args.push("array" + j + ".offset|0")
+    if (i>0) { // Gather conditions to check for shape equality (ignoring block indices)
+      shapeLengthConditions.push("array" + proc.arrayArgs[0] + ".shape.length===array" + j + ".shape.length+" + (Math.abs(proc.arrayBlockIndices[0])-Math.abs(proc.arrayBlockIndices[i])))
+      shapeConditions.push("array" + proc.arrayArgs[0] + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[0]) + "]===array" + j + ".shape[shapeIndex+" + Math.max(0,proc.arrayBlockIndices[i]) + "]")
+    }
+  }
+  // Check for shape equality
+  if (proc.arrayArgs.length > 1) {
+    code.push("if (!(" + shapeLengthConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')")
+    code.push("for(var shapeIndex=array" + proc.arrayArgs[0] + ".shape.length-" + Math.abs(proc.arrayBlockIndices[0]) + "; shapeIndex-->0;) {")
+    code.push("if (!(" + shapeConditions.join(" && ") + ")) throw new Error('cwise: Arrays do not all have the same shape!')")
+    code.push("}")
+  }
+  // Process scalar arguments
+  for(var i=0; i<proc.scalarArgs.length; ++i) {
+    proc_args.push("scalar" + proc.scalarArgs[i])
+  }
+  // Check for cached function (and if not present, generate it)
+  vars.push(["type=[", string_typesig.join(","), "].join()"].join(""))
+  vars.push("proc=CACHED[type]")
+  code.push("var " + vars.join(","))
+  
+  code.push(["if(!proc){",
+             "CACHED[type]=proc=compile([", typesig.join(","), "])}",
+             "return proc(", proc_args.join(","), ")}"].join(""))
+
+  if(proc.debug) {
+    console.log("-----Generated thunk:\n" + code.join("\n") + "\n----------")
+  }
+  
+  //Compile thunk
+  var thunk = new Function("compile", code.join("\n"))
+  return thunk(compile.bind(undefined, proc))
+}
+
+module.exports = createThunk
+
+},{"./compile.js":67}],69:[function(require,module,exports){
+module.exports = require("cwise-compiler")
+},{"cwise-compiler":66}],70:[function(require,module,exports){
+!function() {
+  var d3 = {
+    version: "3.5.13"
+  };
+  var d3_arraySlice = [].slice, d3_array = function(list) {
+    return d3_arraySlice.call(list);
+  };
+  var d3_document = this.document;
+  function d3_documentElement(node) {
+    return node && (node.ownerDocument || node.document || node).documentElement;
+  }
+  function d3_window(node) {
+    return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView);
+  }
+  if (d3_document) {
+    try {
+      d3_array(d3_document.documentElement.childNodes)[0].nodeType;
+    } catch (e) {
+      d3_array = function(list) {
+        var i = list.length, array = new Array(i);
+        while (i--) array[i] = list[i];
+        return array;
+      };
+    }
+  }
+  if (!Date.now) Date.now = function() {
+    return +new Date();
+  };
+  if (d3_document) {
+    try {
+      d3_document.createElement("DIV").style.setProperty("opacity", 0, "");
+    } catch (error) {
+      var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty;
+      d3_element_prototype.setAttribute = function(name, value) {
+        d3_element_setAttribute.call(this, name, value + "");
+      };
+      d3_element_prototype.setAttributeNS = function(space, local, value) {
+        d3_element_setAttributeNS.call(this, space, local, value + "");
+      };
+      d3_style_prototype.setProperty = function(name, value, priority) {
+        d3_style_setProperty.call(this, name, value + "", priority);
+      };
+    }
+  }
+  d3.ascending = d3_ascending;
+  function d3_ascending(a, b) {
+    return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
+  }
+  d3.descending = function(a, b) {
+    return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
+  };
+  d3.min = function(array, f) {
+    var i = -1, n = array.length, a, b;
+    if (arguments.length === 1) {
+      while (++i < n) if ((b = array[i]) != null && b >= b) {
+        a = b;
+        break;
+      }
+      while (++i < n) if ((b = array[i]) != null && a > b) a = b;
+    } else {
+      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
+        a = b;
+        break;
+      }
+      while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
+    }
+    return a;
+  };
+  d3.max = function(array, f) {
+    var i = -1, n = array.length, a, b;
+    if (arguments.length === 1) {
+      while (++i < n) if ((b = array[i]) != null && b >= b) {
+        a = b;
+        break;
+      }
+      while (++i < n) if ((b = array[i]) != null && b > a) a = b;
+    } else {
+      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
+        a = b;
+        break;
+      }
+      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
+    }
+    return a;
+  };
+  d3.extent = function(array, f) {
+    var i = -1, n = array.length, a, b, c;
+    if (arguments.length === 1) {
+      while (++i < n) if ((b = array[i]) != null && b >= b) {
+        a = c = b;
+        break;
+      }
+      while (++i < n) if ((b = array[i]) != null) {
+        if (a > b) a = b;
+        if (c < b) c = b;
+      }
+    } else {
+      while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
+        a = c = b;
+        break;
+      }
+      while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
+        if (a > b) a = b;
+        if (c < b) c = b;
+      }
+    }
+    return [ a, c ];
+  };
+  function d3_number(x) {
+    return x === null ? NaN : +x;
+  }
+  function d3_numeric(x) {
+    return !isNaN(x);
+  }
+  d3.sum = function(array, f) {
+    var s = 0, n = array.length, a, i = -1;
+    if (arguments.length === 1) {
+      while (++i < n) if (d3_numeric(a = +array[i])) s += a;
+    } else {
+      while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a;
+    }
+    return s;
+  };
+  d3.mean = function(array, f) {
+    var s = 0, n = array.length, a, i = -1, j = n;
+    if (arguments.length === 1) {
+      while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j;
+    } else {
+      while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j;
+    }
+    if (j) return s / j;
+  };
+  d3.quantile = function(values, p) {
+    var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h;
+    return e ? v + e * (values[h] - v) : v;
+  };
+  d3.median = function(array, f) {
+    var numbers = [], n = array.length, a, i = -1;
+    if (arguments.length === 1) {
+      while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a);
+    } else {
+      while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a);
+    }
+    if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5);
+  };
+  d3.variance = function(array, f) {
+    var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0;
+    if (arguments.length === 1) {
+      while (++i < n) {
+        if (d3_numeric(a = d3_number(array[i]))) {
+          d = a - m;
+          m += d / ++j;
+          s += d * (a - m);
+        }
+      }
+    } else {
+      while (++i < n) {
+        if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) {
+          d = a - m;
+          m += d / ++j;
+          s += d * (a - m);
+        }
+      }
+    }
+    if (j > 1) return s / (j - 1);
+  };
+  d3.deviation = function() {
+    var v = d3.variance.apply(this, arguments);
+    return v ? Math.sqrt(v) : v;
+  };
+  function d3_bisector(compare) {
+    return {
+      left: function(a, x, lo, hi) {
+        if (arguments.length < 3) lo = 0;
+        if (arguments.length < 4) hi = a.length;
+        while (lo < hi) {
+          var mid = lo + hi >>> 1;
+          if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid;
+        }
+        return lo;
+      },
+      right: function(a, x, lo, hi) {
+        if (arguments.length < 3) lo = 0;
+        if (arguments.length < 4) hi = a.length;
+        while (lo < hi) {
+          var mid = lo + hi >>> 1;
+          if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1;
+        }
+        return lo;
+      }
+    };
+  }
+  var d3_bisect = d3_bisector(d3_ascending);
+  d3.bisectLeft = d3_bisect.left;
+  d3.bisect = d3.bisectRight = d3_bisect.right;
+  d3.bisector = function(f) {
+    return d3_bisector(f.length === 1 ? function(d, x) {
+      return d3_ascending(f(d), x);
+    } : f);
+  };
+  d3.shuffle = function(array, i0, i1) {
+    if ((m = arguments.length) < 3) {
+      i1 = array.length;
+      if (m < 2) i0 = 0;
+    }
+    var m = i1 - i0, t, i;
+    while (m) {
+      i = Math.random() * m-- | 0;
+      t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t;
+    }
+    return array;
+  };
+  d3.permute = function(array, indexes) {
+    var i = indexes.length, permutes = new Array(i);
+    while (i--) permutes[i] = array[indexes[i]];
+    return permutes;
+  };
+  d3.pairs = function(array) {
+    var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n);
+    while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ];
+    return pairs;
+  };
+  d3.zip = function() {
+    if (!(n = arguments.length)) return [];
+    for (var i = -1, m = d3.min(arguments, d3_zipLength), zips = new Array(m); ++i < m; ) {
+      for (var j = -1, n, zip = zips[i] = new Array(n); ++j < n; ) {
+        zip[j] = arguments[j][i];
+      }
+    }
+    return zips;
+  };
+  function d3_zipLength(d) {
+    return d.length;
+  }
+  d3.transpose = function(matrix) {
+    return d3.zip.apply(d3, matrix);
+  };
+  d3.keys = function(map) {
+    var keys = [];
+    for (var key in map) keys.push(key);
+    return keys;
+  };
+  d3.values = function(map) {
+    var values = [];
+    for (var key in map) values.push(map[key]);
+    return values;
+  };
+  d3.entries = function(map) {
+    var entries = [];
+    for (var key in map) entries.push({
+      key: key,
+      value: map[key]
+    });
+    return entries;
+  };
+  d3.merge = function(arrays) {
+    var n = arrays.length, m, i = -1, j = 0, merged, array;
+    while (++i < n) j += arrays[i].length;
+    merged = new Array(j);
+    while (--n >= 0) {
+      array = arrays[n];
+      m = array.length;
+      while (--m >= 0) {
+        merged[--j] = array[m];
+      }
+    }
+    return merged;
+  };
+  var abs = Math.abs;
+  d3.range = function(start, stop, step) {
+    if (arguments.length < 3) {
+      step = 1;
+      if (arguments.length < 2) {
+        stop = start;
+        start = 0;
+      }
+    }
+    if ((stop - start) / step === Infinity) throw new Error("infinite range");
+    var range = [], k = d3_range_integerScale(abs(step)), i = -1, j;
+    start *= k, stop *= k, step *= k;
+    if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k);
+    return range;
+  };
+  function d3_range_integerScale(x) {
+    var k = 1;
+    while (x * k % 1) k *= 10;
+    return k;
+  }
+  function d3_class(ctor, properties) {
+    for (var key in properties) {
+      Object.defineProperty(ctor.prototype, key, {
+        value: properties[key],
+        enumerable: false
+      });
+    }
+  }
+  d3.map = function(object, f) {
+    var map = new d3_Map();
+    if (object instanceof d3_Map) {
+      object.forEach(function(key, value) {
+        map.set(key, value);
+      });
+    } else if (Array.isArray(object)) {
+      var i = -1, n = object.length, o;
+      if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o);
+    } else {
+      for (var key in object) map.set(key, object[key]);
+    }
+    return map;
+  };
+  function d3_Map() {
+    this._ = Object.create(null);
+  }
+  var d3_map_proto = "__proto__", d3_map_zero = "\x00";
+  d3_class(d3_Map, {
+    has: d3_map_has,
+    get: function(key) {
+      return this._[d3_map_escape(key)];
+    },
+    set: function(key, value) {
+      return this._[d3_map_escape(key)] = value;
+    },
+    remove: d3_map_remove,
+    keys: d3_map_keys,
+    values: function() {
+      var values = [];
+      for (var key in this._) values.push(this._[key]);
+      return values;
+    },
+    entries: function() {
+      var entries = [];
+      for (var key in this._) entries.push({
+        key: d3_map_unescape(key),
+        value: this._[key]
+      });
+      return entries;
+    },
+    size: d3_map_size,
+    empty: d3_map_empty,
+    forEach: function(f) {
+      for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]);
+    }
+  });
+  function d3_map_escape(key) {
+    return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key;
+  }
+  function d3_map_unescape(key) {
+    return (key += "")[0] === d3_map_zero ? key.slice(1) : key;
+  }
+  function d3_map_has(key) {
+    return d3_map_escape(key) in this._;
+  }
+  function d3_map_remove(key) {
+    return (key = d3_map_escape(key)) in this._ && delete this._[key];
+  }
+  function d3_map_keys() {
+    var keys = [];
+    for (var key in this._) keys.push(d3_map_unescape(key));
+    return keys;
+  }
+  function d3_map_size() {
+    var size = 0;
+    for (var key in this._) ++size;
+    return size;
+  }
+  function d3_map_empty() {
+    for (var key in this._) return false;
+    return true;
+  }
+  d3.nest = function() {
+    var nest = {}, keys = [], sortKeys = [], sortValues, rollup;
+    function map(mapType, array, depth) {
+      if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array;
+      var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values;
+      while (++i < n) {
+        if (values = valuesByKey.get(keyValue = key(object = array[i]))) {
+          values.push(object);
+        } else {
+          valuesByKey.set(keyValue, [ object ]);
+        }
+      }
+      if (mapType) {
+        object = mapType();
+        setter = function(keyValue, values) {
+          object.set(keyValue, map(mapType, values, depth));
+        };
+      } else {
+        object = {};
+        setter = function(keyValue, values) {
+          object[keyValue] = map(mapType, values, depth);
+        };
+      }
+      valuesByKey.forEach(setter);
+      return object;
+    }
+    function entries(map, depth) {
+      if (depth >= keys.length) return map;
+      var array = [], sortKey = sortKeys[depth++];
+      map.forEach(function(key, keyMap) {
+        array.push({
+          key: key,
+          values: entries(keyMap, depth)
+        });
+      });
+      return sortKey ? array.sort(function(a, b) {
+        return sortKey(a.key, b.key);
+      }) : array;
+    }
+    nest.map = function(array, mapType) {
+      return map(mapType, array, 0);
+    };
+    nest.entries = function(array) {
+      return entries(map(d3.map, array, 0), 0);
+    };
+    nest.key = function(d) {
+      keys.push(d);
+      return nest;
+    };
+    nest.sortKeys = function(order) {
+      sortKeys[keys.length - 1] = order;
+      return nest;
+    };
+    nest.sortValues = function(order) {
+      sortValues = order;
+      return nest;
+    };
+    nest.rollup = function(f) {
+      rollup = f;
+      return nest;
+    };
+    return nest;
+  };
+  d3.set = function(array) {
+    var set = new d3_Set();
+    if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]);
+    return set;
+  };
+  function d3_Set() {
+    this._ = Object.create(null);
+  }
+  d3_class(d3_Set, {
+    has: d3_map_has,
+    add: function(key) {
+      this._[d3_map_escape(key += "")] = true;
+      return key;
+    },
+    remove: d3_map_remove,
+    values: d3_map_keys,
+    size: d3_map_size,
+    empty: d3_map_empty,
+    forEach: function(f) {
+      for (var key in this._) f.call(this, d3_map_unescape(key));
+    }
+  });
+  d3.behavior = {};
+  function d3_identity(d) {
+    return d;
+  }
+  d3.rebind = function(target, source) {
+    var i = 1, n = arguments.length, method;
+    while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
+    return target;
+  };
+  function d3_rebind(target, source, method) {
+    return function() {
+      var value = method.apply(source, arguments);
+      return value === source ? target : value;
+    };
+  }
+  function d3_vendorSymbol(object, name) {
+    if (name in object) return name;
+    name = name.charAt(0).toUpperCase() + name.slice(1);
+    for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) {
+      var prefixName = d3_vendorPrefixes[i] + name;
+      if (prefixName in object) return prefixName;
+    }
+  }
+  var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ];
+  function d3_noop() {}
+  d3.dispatch = function() {
+    var dispatch = new d3_dispatch(), i = -1, n = arguments.length;
+    while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
+    return dispatch;
+  };
+  function d3_dispatch() {}
+  d3_dispatch.prototype.on = function(type, listener) {
+    var i = type.indexOf("."), name = "";
+    if (i >= 0) {
+      name = type.slice(i + 1);
+      type = type.slice(0, i);
+    }
+    if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener);
+    if (arguments.length === 2) {
+      if (listener == null) for (type in this) {
+        if (this.hasOwnProperty(type)) this[type].on(name, null);
+      }
+      return this;
+    }
+  };
+  function d3_dispatch_event(dispatch) {
+    var listeners = [], listenerByName = new d3_Map();
+    function event() {
+      var z = listeners, i = -1, n = z.length, l;
+      while (++i < n) if (l = z[i].on) l.apply(this, arguments);
+      return dispatch;
+    }
+    event.on = function(name, listener) {
+      var l = listenerByName.get(name), i;
+      if (arguments.length < 2) return l && l.on;
+      if (l) {
+        l.on = null;
+        listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1));
+        listenerByName.remove(name);
+      }
+      if (listener) listeners.push(listenerByName.set(name, {
+        on: listener
+      }));
+      return dispatch;
+    };
+    return event;
+  }
+  d3.event = null;
+  function d3_eventPreventDefault() {
+    d3.event.preventDefault();
+  }
+  function d3_eventSource() {
+    var e = d3.event, s;
+    while (s = e.sourceEvent) e = s;
+    return e;
+  }
+  function d3_eventDispatch(target) {
+    var dispatch = new d3_dispatch(), i = 0, n = arguments.length;
+    while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
+    dispatch.of = function(thiz, argumentz) {
+      return function(e1) {
+        try {
+          var e0 = e1.sourceEvent = d3.event;
+          e1.target = target;
+          d3.event = e1;
+          dispatch[e1.type].apply(thiz, argumentz);
+        } finally {
+          d3.event = e0;
+        }
+      };
+    };
+    return dispatch;
+  }
+  d3.requote = function(s) {
+    return s.replace(d3_requote_re, "\\$&");
+  };
+  var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
+  var d3_subclass = {}.__proto__ ? function(object, prototype) {
+    object.__proto__ = prototype;
+  } : function(object, prototype) {
+    for (var property in prototype) object[property] = prototype[property];
+  };
+  function d3_selection(groups) {
+    d3_subclass(groups, d3_selectionPrototype);
+    return groups;
+  }
+  var d3_select = function(s, n) {
+    return n.querySelector(s);
+  }, d3_selectAll = function(s, n) {
+    return n.querySelectorAll(s);
+  }, d3_selectMatches = function(n, s) {
+    var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")];
+    d3_selectMatches = function(n, s) {
+      return d3_selectMatcher.call(n, s);
+    };
+    return d3_selectMatches(n, s);
+  };
+  if (typeof Sizzle === "function") {
+    d3_select = function(s, n) {
+      return Sizzle(s, n)[0] || null;
+    };
+    d3_selectAll = Sizzle;
+    d3_selectMatches = Sizzle.matchesSelector;
+  }
+  d3.selection = function() {
+    return d3.select(d3_document.documentElement);
+  };
+  var d3_selectionPrototype = d3.selection.prototype = [];
+  d3_selectionPrototype.select = function(selector) {
+    var subgroups = [], subgroup, subnode, group, node;
+    selector = d3_selection_selector(selector);
+    for (var j = -1, m = this.length; ++j < m; ) {
+      subgroups.push(subgroup = []);
+      subgroup.parentNode = (group = this[j]).parentNode;
+      for (var i = -1, n = group.length; ++i < n; ) {
+        if (node = group[i]) {
+          subgroup.push(subnode = selector.call(node, node.__data__, i, j));
+          if (subnode && "__data__" in node) subnode.__data__ = node.__data__;
+        } else {
+          subgroup.push(null);
+        }
+      }
+    }
+    return d3_selection(subgroups);
+  };
+  function d3_selection_selector(selector) {
+    return typeof selector === "function" ? selector : function() {
+      return d3_select(selector, this);
+    };
+  }
+  d3_selectionPrototype.selectAll = function(selector) {
+    var subgroups = [], subgroup, node;
+    selector = d3_selection_selectorAll(selector);
+    for (var j = -1, m = this.length; ++j < m; ) {
+      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
+        if (node = group[i]) {
+          subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j)));
+          subgroup.parentNode = node;
+        }
+      }
+    }
+    return d3_selection(subgroups);
+  };
+  function d3_selection_selectorAll(selector) {
+    return typeof selector === "function" ? selector : function() {
+      return d3_selectAll(selector, this);
+    };
+  }
+  var d3_nsPrefix = {
+    svg: "http://www.w3.org/2000/svg",
+    xhtml: "http://www.w3.org/1999/xhtml",
+    xlink: "http://www.w3.org/1999/xlink",
+    xml: "http://www.w3.org/XML/1998/namespace",
+    xmlns: "http://www.w3.org/2000/xmlns/"
+  };
+  d3.ns = {
+    prefix: d3_nsPrefix,
+    qualify: function(name) {
+      var i = name.indexOf(":"), prefix = name;
+      if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
+      return d3_nsPrefix.hasOwnProperty(prefix) ? {
+        space: d3_nsPrefix[prefix],
+        local: name
+      } : name;
+    }
+  };
+  d3_selectionPrototype.attr = function(name, value) {
+    if (arguments.length < 2) {
+      if (typeof name === "string") {
+        var node = this.node();
+        name = d3.ns.qualify(name);
+        return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name);
+      }
+      for (value in name) this.each(d3_selection_attr(value, name[value]));
+      return this;
+    }
+    return this.each(d3_selection_attr(name, value));
+  };
+  function d3_selection_attr(name, value) {
+    name = d3.ns.qualify(name);
+    function attrNull() {
+      this.removeAttribute(name);
+    }
+    function attrNullNS() {
+      this.removeAttributeNS(name.space, name.local);
+    }
+    function attrConstant() {
+      this.setAttribute(name, value);
+    }
+    function attrConstantNS() {
+      this.setAttributeNS(name.space, name.local, value);
+    }
+    function attrFunction() {
+      var x = value.apply(this, arguments);
+      if (x == null) this.removeAttribute(name); else this.setAttribute(name, x);
+    }
+    function attrFunctionNS() {
+      var x = value.apply(this, arguments);
+      if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x);
+    }
+    return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant;
+  }
+  function d3_collapse(s) {
+    return s.trim().replace(/\s+/g, " ");
+  }
+  d3_selectionPrototype.classed = function(name, value) {
+    if (arguments.length < 2) {
+      if (typeof name === "string") {
+        var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1;
+        if (value = node.classList) {
+          while (++i < n) if (!value.contains(name[i])) return false;
+        } else {
+          value = node.getAttribute("class");
+          while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false;
+        }
+        return true;
+      }
+      for (value in name) this.each(d3_selection_classed(value, name[value]));
+      return this;
+    }
+    return this.each(d3_selection_classed(name, value));
+  };
+  function d3_selection_classedRe(name) {
+    return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g");
+  }
+  function d3_selection_classes(name) {
+    return (name + "").trim().split(/^|\s+/);
+  }
+  function d3_selection_classed(name, value) {
+    name = d3_selection_classes(name).map(d3_selection_classedName);
+    var n = name.length;
+    function classedConstant() {
+      var i = -1;
+      while (++i < n) name[i](this, value);
+    }
+    function classedFunction() {
+      var i = -1, x = value.apply(this, arguments);
+      while (++i < n) name[i](this, x);
+    }
+    return typeof value === "function" ? classedFunction : classedConstant;
+  }
+  function d3_selection_classedName(name) {
+    var re = d3_selection_classedRe(name);
+    return function(node, value) {
+      if (c = node.classList) return value ? c.add(name) : c.remove(name);
+      var c = node.getAttribute("class") || "";
+      if (value) {
+        re.lastIndex = 0;
+        if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name));
+      } else {
+        node.setAttribute("class", d3_collapse(c.replace(re, " ")));
+      }
+    };
+  }
+  d3_selectionPrototype.style = function(name, value, priority) {
+    var n = arguments.length;
+    if (n < 3) {
+      if (typeof name !== "string") {
+        if (n < 2) value = "";
+        for (priority in name) this.each(d3_selection_style(priority, name[priority], value));
+        return this;
+      }
+      if (n < 2) {
+        var node = this.node();
+        return d3_window(node).getComputedStyle(node, null).getPropertyValue(name);
+      }
+      priority = "";
+    }
+    return this.each(d3_selection_style(name, value, priority));
+  };
+  function d3_selection_style(name, value, priority) {
+    function styleNull() {
+      this.style.removeProperty(name);
+    }
+    function styleConstant() {
+      this.style.setProperty(name, value, priority);
+    }
+    function styleFunction() {
+      var x = value.apply(this, arguments);
+      if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority);
+    }
+    return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant;
+  }
+  d3_selectionPrototype.property = function(name, value) {
+    if (arguments.length < 2) {
+      if (typeof name === "string") return this.node()[name];
+      for (value in name) this.each(d3_selection_property(value, name[value]));
+      return this;
+    }
+    return this.each(d3_selection_property(name, value));
+  };
+  function d3_selection_property(name, value) {
+    function propertyNull() {
+      delete this[name];
+    }
+    function propertyConstant() {
+      this[name] = value;
+    }
+    function propertyFunction() {
+      var x = value.apply(this, arguments);
+      if (x == null) delete this[name]; else this[name] = x;
+    }
+    return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant;
+  }
+  d3_selectionPrototype.text = function(value) {
+    return arguments.length ? this.each(typeof value === "function" ? function() {
+      var v = value.apply(this, arguments);
+      this.textContent = v == null ? "" : v;
+    } : value == null ? function() {
+      this.textContent = "";
+    } : function() {
+      this.textContent = value;
+    }) : this.node().textContent;
+  };
+  d3_selectionPrototype.html = function(value) {
+    return arguments.length ? this.each(typeof value === "function" ? function() {
+      var v = value.apply(this, arguments);
+      this.innerHTML = v == null ? "" : v;
+    } : value == null ? function() {
+      this.innerHTML = "";
+    } : function() {
+      this.innerHTML = value;
+    }) : this.node().innerHTML;
+  };
+  d3_selectionPrototype.append = function(name) {
+    name = d3_selection_creator(name);
+    return this.select(function() {
+      return this.appendChild(name.apply(this, arguments));
+    });
+  };
+  function d3_selection_creator(name) {
+    function create() {
+      var document = this.ownerDocument, namespace = this.namespaceURI;
+      return namespace ? document.createElementNS(namespace, name) : document.createElement(name);
+    }
+    function createNS() {
+      return this.ownerDocument.createElementNS(name.space, name.local);
+    }
+    return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create;
+  }
+  d3_selectionPrototype.insert = function(name, before) {
+    name = d3_selection_creator(name);
+    before = d3_selection_selector(before);
+    return this.select(function() {
+      return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null);
+    });
+  };
+  d3_selectionPrototype.remove = function() {
+    return this.each(d3_selectionRemove);
+  };
+  function d3_selectionRemove() {
+    var parent = this.parentNode;
+    if (parent) parent.removeChild(this);
+  }
+  d3_selectionPrototype.data = function(value, key) {
+    var i = -1, n = this.length, group, node;
+    if (!arguments.length) {
+      value = new Array(n = (group = this[0]).length);
+      while (++i < n) {
+        if (node = group[i]) {
+          value[i] = node.__data__;
+        }
+      }
+      return value;
+    }
+    function bind(group, groupData) {
+      var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData;
+      if (key) {
+        var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue;
+        for (i = -1; ++i < n; ) {
+          if (node = group[i]) {
+            if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) {
+              exitNodes[i] = node;
+            } else {
+              nodeByKeyValue.set(keyValue, node);
+            }
+            keyValues[i] = keyValue;
+          }
+        }
+        for (i = -1; ++i < m; ) {
+          if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) {
+            enterNodes[i] = d3_selection_dataNode(nodeData);
+          } else if (node !== true) {
+            updateNodes[i] = node;
+            node.__data__ = nodeData;
+          }
+          nodeByKeyValue.set(keyValue, true);
+        }
+        for (i = -1; ++i < n; ) {
+          if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) {
+            exitNodes[i] = group[i];
+          }
+        }
+      } else {
+        for (i = -1; ++i < n0; ) {
+          node = group[i];
+          nodeData = groupData[i];
+          if (node) {
+            node.__data__ = nodeData;
+            updateNodes[i] = node;
+          } else {
+            enterNodes[i] = d3_selection_dataNode(nodeData);
+          }
+        }
+        for (;i < m; ++i) {
+          enterNodes[i] = d3_selection_dataNode(groupData[i]);
+        }
+        for (;i < n; ++i) {
+          exitNodes[i] = group[i];
+        }
+      }
+      enterNodes.update = updateNodes;
+      enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode;
+      enter.push(enterNodes);
+      update.push(updateNodes);
+      exit.push(exitNodes);
+    }
+    var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]);
+    if (typeof value === "function") {
+      while (++i < n) {
+        bind(group = this[i], value.call(group, group.parentNode.__data__, i));
+      }
+    } else {
+      while (++i < n) {
+        bind(group = this[i], value);
+      }
+    }
+    update.enter = function() {
+      return enter;
+    };
+    update.exit = function() {
+      return exit;
+    };
+    return update;
+  };
+  function d3_selection_dataNode(data) {
+    return {
+      __data__: data
+    };
+  }
+  d3_selectionPrototype.datum = function(value) {
+    return arguments.length ? this.property("__data__", value) : this.property("__data__");
+  };
+  d3_selectionPrototype.filter = function(filter) {
+    var subgroups = [], subgroup, group, node;
+    if (typeof filter !== "function") filter = d3_selection_filter(filter);
+    for (var j = 0, m = this.length; j < m; j++) {
+      subgroups.push(subgroup = []);
+      subgroup.parentNode = (group = this[j]).parentNode;
+      for (var i = 0, n = group.length; i < n; i++) {
+        if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
+          subgroup.push(node);
+        }
+      }
+    }
+    return d3_selection(subgroups);
+  };
+  function d3_selection_filter(selector) {
+    return function() {
+      return d3_selectMatches(this, selector);
+    };
+  }
+  d3_selectionPrototype.order = function() {
+    for (var j = -1, m = this.length; ++j < m; ) {
+      for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
+        if (node = group[i]) {
+          if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
+          next = node;
+        }
+      }
+    }
+    return this;
+  };
+  d3_selectionPrototype.sort = function(comparator) {
+    comparator = d3_selection_sortComparator.apply(this, arguments);
+    for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator);
+    return this.order();
+  };
+  function d3_selection_sortComparator(comparator) {
+    if (!arguments.length) comparator = d3_ascending;
+    return function(a, b) {
+      return a && b ? comparator(a.__data__, b.__data__) : !a - !b;
+    };
+  }
+  d3_selectionPrototype.each = function(callback) {
+    return d3_selection_each(this, function(node, i, j) {
+      callback.call(node, node.__data__, i, j);
+    });
+  };
+  function d3_selection_each(groups, callback) {
+    for (var j = 0, m = groups.length; j < m; j++) {
+      for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) {
+        if (node = group[i]) callback(node, i, j);
+      }
+    }
+    return groups;
+  }
+  d3_selectionPrototype.call = function(callback) {
+    var args = d3_array(arguments);
+    callback.apply(args[0] = this, args);
+    return this;
+  };
+  d3_selectionPrototype.empty = function() {
+    return !this.node();
+  };
+  d3_selectionPrototype.node = function() {
+    for (var j = 0, m = this.length; j < m; j++) {
+      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
+        var node = group[i];
+        if (node) return node;
+      }
+    }
+    return null;
+  };
+  d3_selectionPrototype.size = function() {
+    var n = 0;
+    d3_selection_each(this, function() {
+      ++n;
+    });
+    return n;
+  };
+  function d3_selection_enter(selection) {
+    d3_subclass(selection, d3_selection_enterPrototype);
+    return selection;
+  }
+  var d3_selection_enterPrototype = [];
+  d3.selection.enter = d3_selection_enter;
+  d3.selection.enter.prototype = d3_selection_enterPrototype;
+  d3_selection_enterPrototype.append = d3_selectionPrototype.append;
+  d3_selection_enterPrototype.empty = d3_selectionPrototype.empty;
+  d3_selection_enterPrototype.node = d3_selectionPrototype.node;
+  d3_selection_enterPrototype.call = d3_selectionPrototype.call;
+  d3_selection_enterPrototype.size = d3_selectionPrototype.size;
+  d3_selection_enterPrototype.select = function(selector) {
+    var subgroups = [], subgroup, subnode, upgroup, group, node;
+    for (var j = -1, m = this.length; ++j < m; ) {
+      upgroup = (group = this[j]).update;
+      subgroups.push(subgroup = []);
+      subgroup.parentNode = group.parentNode;
+      for (var i = -1, n = group.length; ++i < n; ) {
+        if (node = group[i]) {
+          subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j));
+          subnode.__data__ = node.__data__;
+        } else {
+          subgroup.push(null);
+        }
+      }
+    }
+    return d3_selection(subgroups);
+  };
+  d3_selection_enterPrototype.insert = function(name, before) {
+    if (arguments.length < 2) before = d3_selection_enterInsertBefore(this);
+    return d3_selectionPrototype.insert.call(this, name, before);
+  };
+  function d3_selection_enterInsertBefore(enter) {
+    var i0, j0;
+    return function(d, i, j) {
+      var group = enter[j].update, n = group.length, node;
+      if (j != j0) j0 = j, i0 = 0;
+      if (i >= i0) i0 = i + 1;
+      while (!(node = group[i0]) && ++i0 < n) ;
+      return node;
+    };
+  }
+  d3.select = function(node) {
+    var group;
+    if (typeof node === "string") {
+      group = [ d3_select(node, d3_document) ];
+      group.parentNode = d3_document.documentElement;
+    } else {
+      group = [ node ];
+      group.parentNode = d3_documentElement(node);
+    }
+    return d3_selection([ group ]);
+  };
+  d3.selectAll = function(nodes) {
+    var group;
+    if (typeof nodes === "string") {
+      group = d3_array(d3_selectAll(nodes, d3_document));
+      group.parentNode = d3_document.documentElement;
+    } else {
+      group = d3_array(nodes);
+      group.parentNode = null;
+    }
+    return d3_selection([ group ]);
+  };
+  d3_selectionPrototype.on = function(type, listener, capture) {
+    var n = arguments.length;
+    if (n < 3) {
+      if (typeof type !== "string") {
+        if (n < 2) listener = false;
+        for (capture in type) this.each(d3_selection_on(capture, type[capture], listener));
+        return this;
+      }
+      if (n < 2) return (n = this.node()["__on" + type]) && n._;
+      capture = false;
+    }
+    return this.each(d3_selection_on(type, listener, capture));
+  };
+  function d3_selection_on(type, listener, capture) {
+    var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener;
+    if (i > 0) type = type.slice(0, i);
+    var filter = d3_selection_onFilters.get(type);
+    if (filter) type = filter, wrap = d3_selection_onFilter;
+    function onRemove() {
+      var l = this[name];
+      if (l) {
+        this.removeEventListener(type, l, l.$);
+        delete this[name];
+      }
+    }
+    function onAdd() {
+      var l = wrap(listener, d3_array(arguments));
+      onRemove.call(this);
+      this.addEventListener(type, this[name] = l, l.$ = capture);
+      l._ = listener;
+    }
+    function removeAll() {
+      var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match;
+      for (var name in this) {
+        if (match = name.match(re)) {
+          var l = this[name];
+          this.removeEventListener(match[1], l, l.$);
+          delete this[name];
+        }
+      }
+    }
+    return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll;
+  }
+  var d3_selection_onFilters = d3.map({
+    mouseenter: "mouseover",
+    mouseleave: "mouseout"
+  });
+  if (d3_document) {
+    d3_selection_onFilters.forEach(function(k) {
+      if ("on" + k in d3_document) d3_selection_onFilters.remove(k);
+    });
+  }
+  function d3_selection_onListener(listener, argumentz) {
+    return function(e) {
+      var o = d3.event;
+      d3.event = e;
+      argumentz[0] = this.__data__;
+      try {
+        listener.apply(this, argumentz);
+      } finally {
+        d3.event = o;
+      }
+    };
+  }
+  function d3_selection_onFilter(listener, argumentz) {
+    var l = d3_selection_onListener(listener, argumentz);
+    return function(e) {
+      var target = this, related = e.relatedTarget;
+      if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) {
+        l.call(target, e);
+      }
+    };
+  }
+  var d3_event_dragSelect, d3_event_dragId = 0;
+  function d3_event_dragSuppress(node) {
+    var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault);
+    if (d3_event_dragSelect == null) {
+      d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect");
+    }
+    if (d3_event_dragSelect) {
+      var style = d3_documentElement(node).style, select = style[d3_event_dragSelect];
+      style[d3_event_dragSelect] = "none";
+    }
+    return function(suppressClick) {
+      w.on(name, null);
+      if (d3_event_dragSelect) style[d3_event_dragSelect] = select;
+      if (suppressClick) {
+        var off = function() {
+          w.on(click, null);
+        };
+        w.on(click, function() {
+          d3_eventPreventDefault();
+          off();
+        }, true);
+        setTimeout(off, 0);
+      }
+    };
+  }
+  d3.mouse = function(container) {
+    return d3_mousePoint(container, d3_eventSource());
+  };
+  var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0;
+  function d3_mousePoint(container, e) {
+    if (e.changedTouches) e = e.changedTouches[0];
+    var svg = container.ownerSVGElement || container;
+    if (svg.createSVGPoint) {
+      var point = svg.createSVGPoint();
+      if (d3_mouse_bug44083 < 0) {
+        var window = d3_window(container);
+        if (window.scrollX || window.scrollY) {
+          svg = d3.select("body").append("svg").style({
+            position: "absolute",
+            top: 0,
+            left: 0,
+            margin: 0,
+            padding: 0,
+            border: "none"
+          }, "important");
+          var ctm = svg[0][0].getScreenCTM();
+          d3_mouse_bug44083 = !(ctm.f || ctm.e);
+          svg.remove();
+        }
+      }
+      if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX, 
+      point.y = e.clientY;
+      point = point.matrixTransform(container.getScreenCTM().inverse());
+      return [ point.x, point.y ];
+    }
+    var rect = container.getBoundingClientRect();
+    return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ];
+  }
+  d3.touch = function(container, touches, identifier) {
+    if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches;
+    if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) {
+      if ((touch = touches[i]).identifier === identifier) {
+        return d3_mousePoint(container, touch);
+      }
+    }
+  };
+  d3.behavior.drag = function() {
+    var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend");
+    function drag() {
+      this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart);
+    }
+    function dragstart(id, position, subject, move, end) {
+      return function() {
+        var that = this, target = d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId);
+        if (origin) {
+          dragOffset = origin.apply(that, arguments);
+          dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ];
+        } else {
+          dragOffset = [ 0, 0 ];
+        }
+        dispatch({
+          type: "dragstart"
+        });
+        function moved() {
+          var position1 = position(parent, dragId), dx, dy;
+          if (!position1) return;
+          dx = position1[0] - position0[0];
+          dy = position1[1] - position0[1];
+          dragged |= dx | dy;
+          position0 = position1;
+          dispatch({
+            type: "drag",
+            x: position1[0] + dragOffset[0],
+            y: position1[1] + dragOffset[1],
+            dx: dx,
+            dy: dy
+          });
+        }
+        function ended() {
+          if (!position(parent, dragId)) return;
+          dragSubject.on(move + dragName, null).on(end + dragName, null);
+          dragRestore(dragged);
+          dispatch({
+            type: "dragend"
+          });
+        }
+      };
+    }
+    drag.origin = function(x) {
+      if (!arguments.length) return origin;
+      origin = x;
+      return drag;
+    };
+    return d3.rebind(drag, event, "on");
+  };
+  function d3_behavior_dragTouchId() {
+    return d3.event.changedTouches[0].identifier;
+  }
+  d3.touches = function(container, touches) {
+    if (arguments.length < 2) touches = d3_eventSource().touches;
+    return touches ? d3_array(touches).map(function(touch) {
+      var point = d3_mousePoint(container, touch);
+      point.identifier = touch.identifier;
+      return point;
+    }) : [];
+  };
+  var Îµ = 1e-6, Îµ2 = Îµ * Îµ, Ï = Math.PI, Ï = 2 * Ï, ÏÎµ = Ï - Îµ, halfÏ = Ï / 2, d3_radians = Ï / 180, d3_degrees = 180 / Ï;
+  function d3_sgn(x) {
+    return x > 0 ? 1 : x < 0 ? -1 : 0;
+  }
+  function d3_cross2d(a, b, c) {
+    return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
+  }
+  function d3_acos(x) {
+    return x > 1 ? 0 : x < -1 ? Ï : Math.acos(x);
+  }
+  function d3_asin(x) {
+    return x > 1 ? halfÏ : x < -1 ? -halfÏ : Math.asin(x);
+  }
+  function d3_sinh(x) {
+    return ((x = Math.exp(x)) - 1 / x) / 2;
+  }
+  function d3_cosh(x) {
+    return ((x = Math.exp(x)) + 1 / x) / 2;
+  }
+  function d3_tanh(x) {
+    return ((x = Math.exp(2 * x)) - 1) / (x + 1);
+  }
+  function d3_haversin(x) {
+    return (x = Math.sin(x / 2)) * x;
+  }
+  var Ï = Math.SQRT2, Ï2 = 2, Ï4 = 4;
+  d3.interpolateZoom = function(p0, p1) {
+    var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S;
+    if (d2 < Îµ2) {
+      S = Math.log(w1 / w0) / Ï;
+      i = function(t) {
+        return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(Ï * t * S) ];
+      };
+    } else {
+      var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + Ï4 * d2) / (2 * w0 * Ï2 * d1), b1 = (w1 * w1 - w0 * w0 - Ï4 * d2) / (2 * w1 * Ï2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
+      S = (r1 - r0) / Ï;
+      i = function(t) {
+        var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (Ï2 * d1) * (coshr0 * d3_tanh(Ï * s + r0) - d3_sinh(r0));
+        return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(Ï * s + r0) ];
+      };
+    }
+    i.duration = S * 1e3;
+    return i;
+  };
+  d3.behavior.zoom = function() {
+    var view = {
+      x: 0,
+      y: 0,
+      k: 1
+    }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1;
+    if (!d3_behavior_zoomWheel) {
+      d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() {
+        return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1);
+      }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() {
+        return d3.event.wheelDelta;
+      }, "mousewheel") : (d3_behavior_zoomDelta = function() {
+        return -d3.event.detail;
+      }, "MozMousePixelScroll");
+    }
+    function zoom(g) {
+      g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted);
+    }
+    zoom.event = function(g) {
+      g.each(function() {
+        var dispatch = event.of(this, arguments), view1 = view;
+        if (d3_transitionInheritId) {
+          d3.select(this).transition().each("start.zoom", function() {
+            view = this.__chart__ || {
+              x: 0,
+              y: 0,
+              k: 1
+            };
+            zoomstarted(dispatch);
+          }).tween("zoom:zoom", function() {
+            var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]);
+            return function(t) {
+              var l = i(t), k = dx / l[2];
+              this.__chart__ = view = {
+                x: cx - l[0] * k,
+                y: cy - l[1] * k,
+                k: k
+              };
+              zoomed(dispatch);
+            };
+          }).each("interrupt.zoom", function() {
+            zoomended(dispatch);
+          }).each("end.zoom", function() {
+            zoomended(dispatch);
+          });
+        } else {
+          this.__chart__ = view;
+          zoomstarted(dispatch);
+          zoomed(dispatch);
+          zoomended(dispatch);
+        }
+      });
+    };
+    zoom.translate = function(_) {
+      if (!arguments.length) return [ view.x, view.y ];
+      view = {
+        x: +_[0],
+        y: +_[1],
+        k: view.k
+      };
+      rescale();
+      return zoom;
+    };
+    zoom.scale = function(_) {
+      if (!arguments.length) return view.k;
+      view = {
+        x: view.x,
+        y: view.y,
+        k: null
+      };
+      scaleTo(+_);
+      rescale();
+      return zoom;
+    };
+    zoom.scaleExtent = function(_) {
+      if (!arguments.length) return scaleExtent;
+      scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ];
+      return zoom;
+    };
+    zoom.center = function(_) {
+      if (!arguments.length) return center;
+      center = _ && [ +_[0], +_[1] ];
+      return zoom;
+    };
+    zoom.size = function(_) {
+      if (!arguments.length) return size;
+      size = _ && [ +_[0], +_[1] ];
+      return zoom;
+    };
+    zoom.duration = function(_) {
+      if (!arguments.length) return duration;
+      duration = +_;
+      return zoom;
+    };
+    zoom.x = function(z) {
+      if (!arguments.length) return x1;
+      x1 = z;
+      x0 = z.copy();
+      view = {
+        x: 0,
+        y: 0,
+        k: 1
+      };
+      return zoom;
+    };
+    zoom.y = function(z) {
+      if (!arguments.length) return y1;
+      y1 = z;
+      y0 = z.copy();
+      view = {
+        x: 0,
+        y: 0,
+        k: 1
+      };
+      return zoom;
+    };
+    function location(p) {
+      return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ];
+    }
+    function point(l) {
+      return [ l[0] * view.k + view.x, l[1] * view.k + view.y ];
+    }
+    function scaleTo(s) {
+      view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s));
+    }
+    function translateTo(p, l) {
+      l = point(l);
+      view.x += p[0] - l[0];
+      view.y += p[1] - l[1];
+    }
+    function zoomTo(that, p, l, k) {
+      that.__chart__ = {
+        x: view.x,
+        y: view.y,
+        k: view.k
+      };
+      scaleTo(Math.pow(2, k));
+      translateTo(center0 = p, l);
+      that = d3.select(that);
+      if (duration > 0) that = that.transition().duration(duration);
+      that.call(zoom.event);
+    }
+    function rescale() {
+      if (x1) x1.domain(x0.range().map(function(x) {
+        return (x - view.x) / view.k;
+      }).map(x0.invert));
+      if (y1) y1.domain(y0.range().map(function(y) {
+        return (y - view.y) / view.k;
+      }).map(y0.invert));
+    }
+    function zoomstarted(dispatch) {
+      if (!zooming++) dispatch({
+        type: "zoomstart"
+      });
+    }
+    function zoomed(dispatch) {
+      rescale();
+      dispatch({
+        type: "zoom",
+        scale: view.k,
+        translate: [ view.x, view.y ]
+      });
+    }
+    function zoomended(dispatch) {
+      if (!--zooming) dispatch({
+        type: "zoomend"
+      }), center0 = null;
+    }
+    function mousedowned() {
+      var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that);
+      d3_selection_interrupt.call(that);
+      zoomstarted(dispatch);
+      function moved() {
+        dragged = 1;
+        translateTo(d3.mouse(that), location0);
+        zoomed(dispatch);
+      }
+      function ended() {
+        subject.on(mousemove, null).on(mouseup, null);
+        dragRestore(dragged);
+        zoomended(dispatch);
+      }
+    }
+    function touchstarted() {
+      var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that);
+      started();
+      zoomstarted(dispatch);
+      subject.on(mousedown, null).on(touchstart, started);
+      function relocate() {
+        var touches = d3.touches(that);
+        scale0 = view.k;
+        touches.forEach(function(t) {
+          if (t.identifier in locations0) locations0[t.identifier] = location(t);
+        });
+        return touches;
+      }
+      function started() {
+        var target = d3.event.target;
+        d3.select(target).on(touchmove, moved).on(touchend, ended);
+        targets.push(target);
+        var changed = d3.event.changedTouches;
+        for (var i = 0, n = changed.length; i < n; ++i) {
+          locations0[changed[i].identifier] = null;
+        }
+        var touches = relocate(), now = Date.now();
+        if (touches.length === 1) {
+          if (now - touchtime < 500) {
+            var p = touches[0];
+            zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1);
+            d3_eventPreventDefault();
+          }
+          touchtime = now;
+        } else if (touches.length > 1) {
+          var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1];
+          distance0 = dx * dx + dy * dy;
+        }
+      }
+      function moved() {
+        var touches = d3.touches(that), p0, l0, p1, l1;
+        d3_selection_interrupt.call(that);
+        for (var i = 0, n = touches.length; i < n; ++i, l1 = null) {
+          p1 = touches[i];
+          if (l1 = locations0[p1.identifier]) {
+            if (l0) break;
+            p0 = p1, l0 = l1;
+          }
+        }
+        if (l1) {
+          var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0);
+          p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ];
+          l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ];
+          scaleTo(scale1 * scale0);
+        }
+        touchtime = null;
+        translateTo(p0, l0);
+        zoomed(dispatch);
+      }
+      function ended() {
+        if (d3.event.touches.length) {
+          var changed = d3.event.changedTouches;
+          for (var i = 0, n = changed.length; i < n; ++i) {
+            delete locations0[changed[i].identifier];
+          }
+          for (var identifier in locations0) {
+            return void relocate();
+          }
+        }
+        d3.selectAll(targets).on(zoomName, null);
+        subject.on(mousedown, mousedowned).on(touchstart, touchstarted);
+        dragRestore();
+        zoomended(dispatch);
+      }
+    }
+    function mousewheeled() {
+      var dispatch = event.of(this, arguments);
+      if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this), 
+      translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch);
+      mousewheelTimer = setTimeout(function() {
+        mousewheelTimer = null;
+        zoomended(dispatch);
+      }, 50);
+      d3_eventPreventDefault();
+      scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k);
+      translateTo(center0, translate0);
+      zoomed(dispatch);
+    }
+    function dblclicked() {
+      var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2;
+      zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1);
+    }
+    return d3.rebind(zoom, event, "on");
+  };
+  var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel;
+  d3.color = d3_color;
+  function d3_color() {}
+  d3_color.prototype.toString = function() {
+    return this.rgb() + "";
+  };
+  d3.hsl = d3_hsl;
+  function d3_hsl(h, s, l) {
+    return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l);
+  }
+  var d3_hslPrototype = d3_hsl.prototype = new d3_color();
+  d3_hslPrototype.brighter = function(k) {
+    k = Math.pow(.7, arguments.length ? k : 1);
+    return new d3_hsl(this.h, this.s, this.l / k);
+  };
+  d3_hslPrototype.darker = function(k) {
+    k = Math.pow(.7, arguments.length ? k : 1);
+    return new d3_hsl(this.h, this.s, k * this.l);
+  };
+  d3_hslPrototype.rgb = function() {
+    return d3_hsl_rgb(this.h, this.s, this.l);
+  };
+  function d3_hsl_rgb(h, s, l) {
+    var m1, m2;
+    h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h;
+    s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s;
+    l = l < 0 ? 0 : l > 1 ? 1 : l;
+    m2 = l <= .5 ? l * (1 + s) : l + s - l * s;
+    m1 = 2 * l - m2;
+    function v(h) {
+      if (h > 360) h -= 360; else if (h < 0) h += 360;
+      if (h < 60) return m1 + (m2 - m1) * h / 60;
+      if (h < 180) return m2;
+      if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
+      return m1;
+    }
+    function vv(h) {
+      return Math.round(v(h) * 255);
+    }
+    return new d3_rgb(vv(h + 120), vv(h), vv(h - 120));
+  }
+  d3.hcl = d3_hcl;
+  function d3_hcl(h, c, l) {
+    return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l);
+  }
+  var d3_hclPrototype = d3_hcl.prototype = new d3_color();
+  d3_hclPrototype.brighter = function(k) {
+    return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)));
+  };
+  d3_hclPrototype.darker = function(k) {
+    return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)));
+  };
+  d3_hclPrototype.rgb = function() {
+    return d3_hcl_lab(this.h, this.c, this.l).rgb();
+  };
+  function d3_hcl_lab(h, c, l) {
+    if (isNaN(h)) h = 0;
+    if (isNaN(c)) c = 0;
+    return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c);
+  }
+  d3.lab = d3_lab;
+  function d3_lab(l, a, b) {
+    return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b);
+  }
+  var d3_lab_K = 18;
+  var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883;
+  var d3_labPrototype = d3_lab.prototype = new d3_color();
+  d3_labPrototype.brighter = function(k) {
+    return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
+  };
+  d3_labPrototype.darker = function(k) {
+    return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
+  };
+  d3_labPrototype.rgb = function() {
+    return d3_lab_rgb(this.l, this.a, this.b);
+  };
+  function d3_lab_rgb(l, a, b) {
+    var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200;
+    x = d3_lab_xyz(x) * d3_lab_X;
+    y = d3_lab_xyz(y) * d3_lab_Y;
+    z = d3_lab_xyz(z) * d3_lab_Z;
+    return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z));
+  }
+  function d3_lab_hcl(l, a, b) {
+    return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l);
+  }
+  function d3_lab_xyz(x) {
+    return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037;
+  }
+  function d3_xyz_lab(x) {
+    return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29;
+  }
+  function d3_xyz_rgb(r) {
+    return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055));
+  }
+  d3.rgb = d3_rgb;
+  function d3_rgb(r, g, b) {
+    return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b);
+  }
+  function d3_rgbNumber(value) {
+    return new d3_rgb(value >> 16, value >> 8 & 255, value & 255);
+  }
+  function d3_rgbString(value) {
+    return d3_rgbNumber(value) + "";
+  }
+  var d3_rgbPrototype = d3_rgb.prototype = new d3_color();
+  d3_rgbPrototype.brighter = function(k) {
+    k = Math.pow(.7, arguments.length ? k : 1);
+    var r = this.r, g = this.g, b = this.b, i = 30;
+    if (!r && !g && !b) return new d3_rgb(i, i, i);
+    if (r && r < i) r = i;
+    if (g && g < i) g = i;
+    if (b && b < i) b = i;
+    return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k));
+  };
+  d3_rgbPrototype.darker = function(k) {
+    k = Math.pow(.7, arguments.length ? k : 1);
+    return new d3_rgb(k * this.r, k * this.g, k * this.b);
+  };
+  d3_rgbPrototype.hsl = function() {
+    return d3_rgb_hsl(this.r, this.g, this.b);
+  };
+  d3_rgbPrototype.toString = function() {
+    return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b);
+  };
+  function d3_rgb_hex(v) {
+    return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16);
+  }
+  function d3_rgb_parse(format, rgb, hsl) {
+    var r = 0, g = 0, b = 0, m1, m2, color;
+    m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase());
+    if (m1) {
+      m2 = m1[2].split(",");
+      switch (m1[1]) {
+       case "hsl":
+        {
+          return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100);
+        }
+
+       case "rgb":
+        {
+          return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2]));
+        }
+      }
+    }
+    if (color = d3_rgb_names.get(format)) {
+      return rgb(color.r, color.g, color.b);
+    }
+    if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) {
+      if (format.length === 4) {
+        r = (color & 3840) >> 4;
+        r = r >> 4 | r;
+        g = color & 240;
+        g = g >> 4 | g;
+        b = color & 15;
+        b = b << 4 | b;
+      } else if (format.length === 7) {
+        r = (color & 16711680) >> 16;
+        g = (color & 65280) >> 8;
+        b = color & 255;
+      }
+    }
+    return rgb(r, g, b);
+  }
+  function d3_rgb_hsl(r, g, b) {
+    var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2;
+    if (d) {
+      s = l < .5 ? d / (max + min) : d / (2 - max - min);
+      if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4;
+      h *= 60;
+    } else {
+      h = NaN;
+      s = l > 0 && l < 1 ? 0 : h;
+    }
+    return new d3_hsl(h, s, l);
+  }
+  function d3_rgb_lab(r, g, b) {
+    r = d3_rgb_xyz(r);
+    g = d3_rgb_xyz(g);
+    b = d3_rgb_xyz(b);
+    var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z);
+    return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z));
+  }
+  function d3_rgb_xyz(r) {
+    return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4);
+  }
+  function d3_rgb_parseNumber(c) {
+    var f = parseFloat(c);
+    return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
+  }
+  var d3_rgb_names = d3.map({
+    aliceblue: 15792383,
+    antiquewhite: 16444375,
+    aqua: 65535,
+    aquamarine: 8388564,
+    azure: 15794175,
+    beige: 16119260,
+    bisque: 16770244,
+    black: 0,
+    blanchedalmond: 16772045,
+    blue: 255,
+    blueviolet: 9055202,
+    brown: 10824234,
+    burlywood: 14596231,
+    cadetblue: 6266528,
+    chartreuse: 8388352,
+    chocolate: 13789470,
+    coral: 16744272,
+    cornflowerblue: 6591981,
+    cornsilk: 16775388,
+    crimson: 14423100,
+    cyan: 65535,
+    darkblue: 139,
+    darkcyan: 35723,
+    darkgoldenrod: 12092939,
+    darkgray: 11119017,
+    darkgreen: 25600,
+    darkgrey: 11119017,
+    darkkhaki: 12433259,
+    darkmagenta: 9109643,
+    darkolivegreen: 5597999,
+    darkorange: 16747520,
+    darkorchid: 10040012,
+    darkred: 9109504,
+    darksalmon: 15308410,
+    darkseagreen: 9419919,
+    darkslateblue: 4734347,
+    darkslategray: 3100495,
+    darkslategrey: 3100495,
+    darkturquoise: 52945,
+    darkviolet: 9699539,
+    deeppink: 16716947,
+    deepskyblue: 49151,
+    dimgray: 6908265,
+    dimgrey: 6908265,
+    dodgerblue: 2003199,
+    firebrick: 11674146,
+    floralwhite: 16775920,
+    forestgreen: 2263842,
+    fuchsia: 16711935,
+    gainsboro: 14474460,
+    ghostwhite: 16316671,
+    gold: 16766720,
+    goldenrod: 14329120,
+    gray: 8421504,
+    green: 32768,
+    greenyellow: 11403055,
+    grey: 8421504,
+    honeydew: 15794160,
+    hotpink: 16738740,
+    indianred: 13458524,
+    indigo: 4915330,
+    ivory: 16777200,
+    khaki: 15787660,
+    lavender: 15132410,
+    lavenderblush: 16773365,
+    lawngreen: 8190976,
+    lemonchiffon: 16775885,
+    lightblue: 11393254,
+    lightcoral: 15761536,
+    lightcyan: 14745599,
+    lightgoldenrodyellow: 16448210,
+    lightgray: 13882323,
+    lightgreen: 9498256,
+    lightgrey: 13882323,
+    lightpink: 16758465,
+    lightsalmon: 16752762,
+    lightseagreen: 2142890,
+    lightskyblue: 8900346,
+    lightslategray: 7833753,
+    lightslategrey: 7833753,
+    lightsteelblue: 11584734,
+    lightyellow: 16777184,
+    lime: 65280,
+    limegreen: 3329330,
+    linen: 16445670,
+    magenta: 16711935,
+    maroon: 8388608,
+    mediumaquamarine: 6737322,
+    mediumblue: 205,
+    mediumorchid: 12211667,
+    mediumpurple: 9662683,
+    mediumseagreen: 3978097,
+    mediumslateblue: 8087790,
+    mediumspringgreen: 64154,
+    mediumturquoise: 4772300,
+    mediumvioletred: 13047173,
+    midnightblue: 1644912,
+    mintcream: 16121850,
+    mistyrose: 16770273,
+    moccasin: 16770229,
+    navajowhite: 16768685,
+    navy: 128,
+    oldlace: 16643558,
+    olive: 8421376,
+    olivedrab: 7048739,
+    orange: 16753920,
+    orangered: 16729344,
+    orchid: 14315734,
+    palegoldenrod: 15657130,
+    palegreen: 10025880,
+    paleturquoise: 11529966,
+    palevioletred: 14381203,
+    papayawhip: 16773077,
+    peachpuff: 16767673,
+    peru: 13468991,
+    pink: 16761035,
+    plum: 14524637,
+    powderblue: 11591910,
+    purple: 8388736,
+    rebeccapurple: 6697881,
+    red: 16711680,
+    rosybrown: 12357519,
+    royalblue: 4286945,
+    saddlebrown: 9127187,
+    salmon: 16416882,
+    sandybrown: 16032864,
+    seagreen: 3050327,
+    seashell: 16774638,
+    sienna: 10506797,
+    silver: 12632256,
+    skyblue: 8900331,
+    slateblue: 6970061,
+    slategray: 7372944,
+    slategrey: 7372944,
+    snow: 16775930,
+    springgreen: 65407,
+    steelblue: 4620980,
+    tan: 13808780,
+    teal: 32896,
+    thistle: 14204888,
+    tomato: 16737095,
+    turquoise: 4251856,
+    violet: 15631086,
+    wheat: 16113331,
+    white: 16777215,
+    whitesmoke: 16119285,
+    yellow: 16776960,
+    yellowgreen: 10145074
+  });
+  d3_rgb_names.forEach(function(key, value) {
+    d3_rgb_names.set(key, d3_rgbNumber(value));
+  });
+  function d3_functor(v) {
+    return typeof v === "function" ? v : function() {
+      return v;
+    };
+  }
+  d3.functor = d3_functor;
+  d3.xhr = d3_xhrType(d3_identity);
+  function d3_xhrType(response) {
+    return function(url, mimeType, callback) {
+      if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, 
+      mimeType = null;
+      return d3_xhr(url, mimeType, response, callback);
+    };
+  }
+  function d3_xhr(url, mimeType, response, callback) {
+    var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null;
+    if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest();
+    "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() {
+      request.readyState > 3 && respond();
+    };
+    function respond() {
+      var status = request.status, result;
+      if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) {
+        try {
+          result = response.call(xhr, request);
+        } catch (e) {
+          dispatch.error.call(xhr, e);
+          return;
+        }
+        dispatch.load.call(xhr, result);
+      } else {
+        dispatch.error.call(xhr, request);
+      }
+    }
+    request.onprogress = function(event) {
+      var o = d3.event;
+      d3.event = event;
+      try {
+        dispatch.progress.call(xhr, request);
+      } finally {
+        d3.event = o;
+      }
+    };
+    xhr.header = function(name, value) {
+      name = (name + "").toLowerCase();
+      if (arguments.length < 2) return headers[name];
+      if (value == null) delete headers[name]; else headers[name] = value + "";
+      return xhr;
+    };
+    xhr.mimeType = function(value) {
+      if (!arguments.length) return mimeType;
+      mimeType = value == null ? null : value + "";
+      return xhr;
+    };
+    xhr.responseType = function(value) {
+      if (!arguments.length) return responseType;
+      responseType = value;
+      return xhr;
+    };
+    xhr.response = function(value) {
+      response = value;
+      return xhr;
+    };
+    [ "get", "post" ].forEach(function(method) {
+      xhr[method] = function() {
+        return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments)));
+      };
+    });
+    xhr.send = function(method, data, callback) {
+      if (arguments.length === 2 && typeof data === "function") callback = data, data = null;
+      request.open(method, url, true);
+      if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*";
+      if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]);
+      if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType);
+      if (responseType != null) request.responseType = responseType;
+      if (callback != null) xhr.on("error", callback).on("load", function(request) {
+        callback(null, request);
+      });
+      dispatch.beforesend.call(xhr, request);
+      request.send(data == null ? null : data);
+      return xhr;
+    };
+    xhr.abort = function() {
+      request.abort();
+      return xhr;
+    };
+    d3.rebind(xhr, dispatch, "on");
+    return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback));
+  }
+  function d3_xhr_fixCallback(callback) {
+    return callback.length === 1 ? function(error, request) {
+      callback(error == null ? request : null);
+    } : callback;
+  }
+  function d3_xhrHasResponse(request) {
+    var type = request.responseType;
+    return type && type !== "text" ? request.response : request.responseText;
+  }
+  d3.dsv = function(delimiter, mimeType) {
+    var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0);
+    function dsv(url, row, callback) {
+      if (arguments.length < 3) callback = row, row = null;
+      var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback);
+      xhr.row = function(_) {
+        return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row;
+      };
+      return xhr;
+    }
+    function response(request) {
+      return dsv.parse(request.responseText);
+    }
+    function typedResponse(f) {
+      return function(request) {
+        return dsv.parse(request.responseText, f);
+      };
+    }
+    dsv.parse = function(text, f) {
+      var o;
+      return dsv.parseRows(text, function(row, i) {
+        if (o) return o(row, i - 1);
+        var a = new Function("d", "return {" + row.map(function(name, i) {
+          return JSON.stringify(name) + ": d[" + i + "]";
+        }).join(",") + "}");
+        o = f ? function(row, i) {
+          return f(a(row), i);
+        } : a;
+      });
+    };
+    dsv.parseRows = function(text, f) {
+      var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol;
+      function token() {
+        if (I >= N) return EOF;
+        if (eol) return eol = false, EOL;
+        var j = I;
+        if (text.charCodeAt(j) === 34) {
+          var i = j;
+          while (i++ < N) {
+            if (text.charCodeAt(i) === 34) {
+              if (text.charCodeAt(i + 1) !== 34) break;
+              ++i;
+            }
+          }
+          I = i + 2;
+          var c = text.charCodeAt(i + 1);
+          if (c === 13) {
+            eol = true;
+            if (text.charCodeAt(i + 2) === 10) ++I;
+          } else if (c === 10) {
+            eol = true;
+          }
+          return text.slice(j + 1, i).replace(/""/g, '"');
+        }
+        while (I < N) {
+          var c = text.charCodeAt(I++), k = 1;
+          if (c === 10) eol = true; else if (c === 13) {
+            eol = true;
+            if (text.charCodeAt(I) === 10) ++I, ++k;
+          } else if (c !== delimiterCode) continue;
+          return text.slice(j, I - k);
+        }
+        return text.slice(j);
+      }
+      while ((t = token()) !== EOF) {
+        var a = [];
+        while (t !== EOL && t !== EOF) {
+          a.push(t);
+          t = token();
+        }
+        if (f && (a = f(a, n++)) == null) continue;
+        rows.push(a);
+      }
+      return rows;
+    };
+    dsv.format = function(rows) {
+      if (Array.isArray(rows[0])) return dsv.formatRows(rows);
+      var fieldSet = new d3_Set(), fields = [];
+      rows.forEach(function(row) {
+        for (var field in row) {
+          if (!fieldSet.has(field)) {
+            fields.push(fieldSet.add(field));
+          }
+        }
+      });
+      return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) {
+        return fields.map(function(field) {
+          return formatValue(row[field]);
+        }).join(delimiter);
+      })).join("\n");
+    };
+    dsv.formatRows = function(rows) {
+      return rows.map(formatRow).join("\n");
+    };
+    function formatRow(row) {
+      return row.map(formatValue).join(delimiter);
+    }
+    function formatValue(text) {
+      return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text;
+    }
+    return dsv;
+  };
+  d3.csv = d3.dsv(",", "text/csv");
+  d3.tsv = d3.dsv("	", "text/tab-separated-values");
+  var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) {
+    setTimeout(callback, 17);
+  };
+  d3.timer = function() {
+    d3_timer.apply(this, arguments);
+  };
+  function d3_timer(callback, delay, then) {
+    var n = arguments.length;
+    if (n < 2) delay = 0;
+    if (n < 3) then = Date.now();
+    var time = then + delay, timer = {
+      c: callback,
+      t: time,
+      n: null
+    };
+    if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer;
+    d3_timer_queueTail = timer;
+    if (!d3_timer_interval) {
+      d3_timer_timeout = clearTimeout(d3_timer_timeout);
+      d3_timer_interval = 1;
+      d3_timer_frame(d3_timer_step);
+    }
+    return timer;
+  }
+  function d3_timer_step() {
+    var now = d3_timer_mark(), delay = d3_timer_sweep() - now;
+    if (delay > 24) {
+      if (isFinite(delay)) {
+        clearTimeout(d3_timer_timeout);
+        d3_timer_timeout = setTimeout(d3_timer_step, delay);
+      }
+      d3_timer_interval = 0;
+    } else {
+      d3_timer_interval = 1;
+      d3_timer_frame(d3_timer_step);
+    }
+  }
+  d3.timer.flush = function() {
+    d3_timer_mark();
+    d3_timer_sweep();
+  };
+  function d3_timer_mark() {
+    var now = Date.now(), timer = d3_timer_queueHead;
+    while (timer) {
+      if (now >= timer.t && timer.c(now - timer.t)) timer.c = null;
+      timer = timer.n;
+    }
+    return now;
+  }
+  function d3_timer_sweep() {
+    var t0, t1 = d3_timer_queueHead, time = Infinity;
+    while (t1) {
+      if (t1.c) {
+        if (t1.t < time) time = t1.t;
+        t1 = (t0 = t1).n;
+      } else {
+        t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n;
+      }
+    }
+    d3_timer_queueTail = t0;
+    return time;
+  }
+  function d3_format_precision(x, p) {
+    return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1);
+  }
+  d3.round = function(x, n) {
+    return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x);
+  };
+  var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "Âµ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix);
+  d3.formatPrefix = function(value, precision) {
+    var i = 0;
+    if (value = +value) {
+      if (value < 0) value *= -1;
+      if (precision) value = d3.round(value, d3_format_precision(value, precision));
+      i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
+      i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3));
+    }
+    return d3_formatPrefixes[8 + i / 3];
+  };
+  function d3_formatPrefix(d, i) {
+    var k = Math.pow(10, abs(8 - i) * 3);
+    return {
+      scale: i > 8 ? function(d) {
+        return d / k;
+      } : function(d) {
+        return d * k;
+      },
+      symbol: d
+    };
+  }
+  function d3_locale_numberFormat(locale) {
+    var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) {
+      var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0;
+      while (i > 0 && g > 0) {
+        if (length + g + 1 > width) g = Math.max(1, width - length);
+        t.push(value.substring(i -= g, i + g));
+        if ((length += g + 1) > width) break;
+        g = locale_grouping[j = (j + 1) % locale_grouping.length];
+      }
+      return t.reverse().join(locale_thousands);
+    } : d3_identity;
+    return function(specifier) {
+      var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true;
+      if (precision) precision = +precision.substring(1);
+      if (zfill || fill === "0" && align === "=") {
+        zfill = fill = "0";
+        align = "=";
+      }
+      switch (type) {
+       case "n":
+        comma = true;
+        type = "g";
+        break;
+
+       case "%":
+        scale = 100;
+        suffix = "%";
+        type = "f";
+        break;
+
+       case "p":
+        scale = 100;
+        suffix = "%";
+        type = "r";
+        break;
+
+       case "b":
+       case "o":
+       case "x":
+       case "X":
+        if (symbol === "#") prefix = "0" + type.toLowerCase();
+
+       case "c":
+        exponent = false;
+
+       case "d":
+        integer = true;
+        precision = 0;
+        break;
+
+       case "s":
+        scale = -1;
+        type = "r";
+        break;
+      }
+      if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1];
+      if (type == "r" && !precision) type = "g";
+      if (precision != null) {
+        if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision));
+      }
+      type = d3_format_types.get(type) || d3_format_typeDefault;
+      var zcomma = zfill && comma;
+      return function(value) {
+        var fullSuffix = suffix;
+        if (integer && value % 1) return "";
+        var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign;
+        if (scale < 0) {
+          var unit = d3.formatPrefix(value, precision);
+          value = unit.scale(value);
+          fullSuffix = unit.symbol + suffix;
+        } else {
+          value *= scale;
+        }
+        value = type(value, precision);
+        var i = value.lastIndexOf("."), before, after;
+        if (i < 0) {
+          var j = exponent ? value.lastIndexOf("e") : -1;
+          if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j);
+        } else {
+          before = value.substring(0, i);
+          after = locale_decimal + value.substring(i + 1);
+        }
+        if (!zfill && comma) before = formatGroup(before, Infinity);
+        var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : "";
+        if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity);
+        negative += prefix;
+        value = before + after;
+        return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix;
+      };
+    };
+  }
+  var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;
+  var d3_format_types = d3.map({
+    b: function(x) {
+      return x.toString(2);
+    },
+    c: function(x) {
+      return String.fromCharCode(x);
+    },
+    o: function(x) {
+      return x.toString(8);
+    },
+    x: function(x) {
+      return x.toString(16);
+    },
+    X: function(x) {
+      return x.toString(16).toUpperCase();
+    },
+    g: function(x, p) {
+      return x.toPrecision(p);
+    },
+    e: function(x, p) {
+      return x.toExponential(p);
+    },
+    f: function(x, p) {
+      return x.toFixed(p);
+    },
+    r: function(x, p) {
+      return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p))));
+    }
+  });
+  function d3_format_typeDefault(x) {
+    return x + "";
+  }
+  var d3_time = d3.time = {}, d3_date = Date;
+  function d3_date_utc() {
+    this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]);
+  }
+  d3_date_utc.prototype = {
+    getDate: function() {
+      return this._.getUTCDate();
+    },
+    getDay: function() {
+      return this._.getUTCDay();
+    },
+    getFullYear: function() {
+      return this._.getUTCFullYear();
+    },
+    getHours: function() {
+      return this._.getUTCHours();
+    },
+    getMilliseconds: function() {
+      return this._.getUTCMilliseconds();
+    },
+    getMinutes: function() {
+      return this._.getUTCMinutes();
+    },
+    getMonth: function() {
+      return this._.getUTCMonth();
+    },
+    getSeconds: function() {
+      return this._.getUTCSeconds();
+    },
+    getTime: function() {
+      return this._.getTime();
+    },
+    getTimezoneOffset: function() {
+      return 0;
+    },
+    valueOf: function() {
+      return this._.valueOf();
+    },
+    setDate: function() {
+      d3_time_prototype.setUTCDate.apply(this._, arguments);
+    },
+    setDay: function() {
+      d3_time_prototype.setUTCDay.apply(this._, arguments);
+    },
+    setFullYear: function() {
+      d3_time_prototype.setUTCFullYear.apply(this._, arguments);
+    },
+    setHours: function() {
+      d3_time_prototype.setUTCHours.apply(this._, arguments);
+    },
+    setMilliseconds: function() {
+      d3_time_prototype.setUTCMilliseconds.apply(this._, arguments);
+    },
+    setMinutes: function() {
+      d3_time_prototype.setUTCMinutes.apply(this._, arguments);
+    },
+    setMonth: function() {
+      d3_time_prototype.setUTCMonth.apply(this._, arguments);
+    },
+    setSeconds: function() {
+      d3_time_prototype.setUTCSeconds.apply(this._, arguments);
+    },
+    setTime: function() {
+      d3_time_prototype.setTime.apply(this._, arguments);
+    }
+  };
+  var d3_time_prototype = Date.prototype;
+  function d3_time_interval(local, step, number) {
+    function round(date) {
+      var d0 = local(date), d1 = offset(d0, 1);
+      return date - d0 < d1 - date ? d0 : d1;
+    }
+    function ceil(date) {
+      step(date = local(new d3_date(date - 1)), 1);
+      return date;
+    }
+    function offset(date, k) {
+      step(date = new d3_date(+date), k);
+      return date;
+    }
+    function range(t0, t1, dt) {
+      var time = ceil(t0), times = [];
+      if (dt > 1) {
+        while (time < t1) {
+          if (!(number(time) % dt)) times.push(new Date(+time));
+          step(time, 1);
+        }
+      } else {
+        while (time < t1) times.push(new Date(+time)), step(time, 1);
+      }
+      return times;
+    }
+    function range_utc(t0, t1, dt) {
+      try {
+        d3_date = d3_date_utc;
+        var utc = new d3_date_utc();
+        utc._ = t0;
+        return range(utc, t1, dt);
+      } finally {
+        d3_date = Date;
+      }
+    }
+    local.floor = local;
+    local.round = round;
+    local.ceil = ceil;
+    local.offset = offset;
+    local.range = range;
+    var utc = local.utc = d3_time_interval_utc(local);
+    utc.floor = utc;
+    utc.round = d3_time_interval_utc(round);
+    utc.ceil = d3_time_interval_utc(ceil);
+    utc.offset = d3_time_interval_utc(offset);
+    utc.range = range_utc;
+    return local;
+  }
+  function d3_time_interval_utc(method) {
+    return function(date, k) {
+      try {
+        d3_date = d3_date_utc;
+        var utc = new d3_date_utc();
+        utc._ = date;
+        return method(utc, k)._;
+      } finally {
+        d3_date = Date;
+      }
+    };
+  }
+  d3_time.year = d3_time_interval(function(date) {
+    date = d3_time.day(date);
+    date.setMonth(0, 1);
+    return date;
+  }, function(date, offset) {
+    date.setFullYear(date.getFullYear() + offset);
+  }, function(date) {
+    return date.getFullYear();
+  });
+  d3_time.years = d3_time.year.range;
+  d3_time.years.utc = d3_time.year.utc.range;
+  d3_time.day = d3_time_interval(function(date) {
+    var day = new d3_date(2e3, 0);
+    day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
+    return day;
+  }, function(date, offset) {
+    date.setDate(date.getDate() + offset);
+  }, function(date) {
+    return date.getDate() - 1;
+  });
+  d3_time.days = d3_time.day.range;
+  d3_time.days.utc = d3_time.day.utc.range;
+  d3_time.dayOfYear = function(date) {
+    var year = d3_time.year(date);
+    return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5);
+  };
+  [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) {
+    i = 7 - i;
+    var interval = d3_time[day] = d3_time_interval(function(date) {
+      (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7);
+      return date;
+    }, function(date, offset) {
+      date.setDate(date.getDate() + Math.floor(offset) * 7);
+    }, function(date) {
+      var day = d3_time.year(date).getDay();
+      return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i);
+    });
+    d3_time[day + "s"] = interval.range;
+    d3_time[day + "s"].utc = interval.utc.range;
+    d3_time[day + "OfYear"] = function(date) {
+      var day = d3_time.year(date).getDay();
+      return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7);
+    };
+  });
+  d3_time.week = d3_time.sunday;
+  d3_time.weeks = d3_time.sunday.range;
+  d3_time.weeks.utc = d3_time.sunday.utc.range;
+  d3_time.weekOfYear = d3_time.sundayOfYear;
+  function d3_locale_timeFormat(locale) {
+    var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths;
+    function d3_time_format(template) {
+      var n = template.length;
+      function format(date) {
+        var string = [], i = -1, j = 0, c, p, f;
+        while (++i < n) {
+          if (template.charCodeAt(i) === 37) {
+            string.push(template.slice(j, i));
+            if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i);
+            if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p);
+            string.push(c);
+            j = i + 1;
+          }
+        }
+        string.push(template.slice(j, i));
+        return string.join("");
+      }
+      format.parse = function(string) {
+        var d = {
+          y: 1900,
+          m: 0,
+          d: 1,
+          H: 0,
+          M: 0,
+          S: 0,
+          L: 0,
+          Z: null
+        }, i = d3_time_parse(d, template, string, 0);
+        if (i != string.length) return null;
+        if ("p" in d) d.H = d.H % 12 + d.p * 12;
+        var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)();
+        if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) {
+          if (!("w" in d)) d.w = "W" in d ? 1 : 0;
+          date.setFullYear(d.y, 0, 1);
+          date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7);
+        } else date.setFullYear(d.y, d.m, d.d);
+        date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L);
+        return localZ ? date._ : date;
+      };
+      format.toString = function() {
+        return template;
+      };
+      return format;
+    }
+    function d3_time_parse(date, template, string, j) {
+      var c, p, t, i = 0, n = template.length, m = string.length;
+      while (i < n) {
+        if (j >= m) return -1;
+        c = template.charCodeAt(i++);
+        if (c === 37) {
+          t = template.charAt(i++);
+          p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t];
+          if (!p || (j = p(date, string, j)) < 0) return -1;
+        } else if (c != string.charCodeAt(j++)) {
+          return -1;
+        }
+      }
+      return j;
+    }
+    d3_time_format.utc = function(template) {
+      var local = d3_time_format(template);
+      function format(date) {
+        try {
+          d3_date = d3_date_utc;
+          var utc = new d3_date();
+          utc._ = date;
+          return local(utc);
+        } finally {
+          d3_date = Date;
+        }
+      }
+      format.parse = function(string) {
+        try {
+          d3_date = d3_date_utc;
+          var date = local.parse(string);
+          return date && date._;
+        } finally {
+          d3_date = Date;
+        }
+      };
+      format.toString = local.toString;
+      return format;
+    };
+    d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti;
+    var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths);
+    locale_periods.forEach(function(p, i) {
+      d3_time_periodLookup.set(p.toLowerCase(), i);
+    });
+    var d3_time_formats = {
+      a: function(d) {
+        return locale_shortDays[d.getDay()];
+      },
+      A: function(d) {
+        return locale_days[d.getDay()];
+      },
+      b: function(d) {
+        return locale_shortMonths[d.getMonth()];
+      },
+      B: function(d) {
+        return locale_months[d.getMonth()];
+      },
+      c: d3_time_format(locale_dateTime),
+      d: function(d, p) {
+        return d3_time_formatPad(d.getDate(), p, 2);
+      },
+      e: function(d, p) {
+        return d3_time_formatPad(d.getDate(), p, 2);
+      },
+      H: function(d, p) {
+        return d3_time_formatPad(d.getHours(), p, 2);
+      },
+      I: function(d, p) {
+        return d3_time_formatPad(d.getHours() % 12 || 12, p, 2);
+      },
+      j: function(d, p) {
+        return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3);
+      },
+      L: function(d, p) {
+        return d3_time_formatPad(d.getMilliseconds(), p, 3);
+      },
+      m: function(d, p) {
+        return d3_time_formatPad(d.getMonth() + 1, p, 2);
+      },
+      M: function(d, p) {
+        return d3_time_formatPad(d.getMinutes(), p, 2);
+      },
+      p: function(d) {
+        return locale_periods[+(d.getHours() >= 12)];
+      },
+      S: function(d, p) {
+        return d3_time_formatPad(d.getSeconds(), p, 2);
+      },
+      U: function(d, p) {
+        return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2);
+      },
+      w: function(d) {
+        return d.getDay();
+      },
+      W: function(d, p) {
+        return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2);
+      },
+      x: d3_time_format(locale_date),
+      X: d3_time_format(locale_time),
+      y: function(d, p) {
+        return d3_time_formatPad(d.getFullYear() % 100, p, 2);
+      },
+      Y: function(d, p) {
+        return d3_time_formatPad(d.getFullYear() % 1e4, p, 4);
+      },
+      Z: d3_time_zone,
+      "%": function() {
+        return "%";
+      }
+    };
+    var d3_time_parsers = {
+      a: d3_time_parseWeekdayAbbrev,
+      A: d3_time_parseWeekday,
+      b: d3_time_parseMonthAbbrev,
+      B: d3_time_parseMonth,
+      c: d3_time_parseLocaleFull,
+      d: d3_time_parseDay,
+      e: d3_time_parseDay,
+      H: d3_time_parseHour24,
+      I: d3_time_parseHour24,
+      j: d3_time_parseDayOfYear,
+      L: d3_time_parseMilliseconds,
+      m: d3_time_parseMonthNumber,
+      M: d3_time_parseMinutes,
+      p: d3_time_parseAmPm,
+      S: d3_time_parseSeconds,
+      U: d3_time_parseWeekNumberSunday,
+      w: d3_time_parseWeekdayNumber,
+      W: d3_time_parseWeekNumberMonday,
+      x: d3_time_parseLocaleDate,
+      X: d3_time_parseLocaleTime,
+      y: d3_time_parseYear,
+      Y: d3_time_parseFullYear,
+      Z: d3_time_parseZone,
+      "%": d3_time_parseLiteralPercent
+    };
+    function d3_time_parseWeekdayAbbrev(date, string, i) {
+      d3_time_dayAbbrevRe.lastIndex = 0;
+      var n = d3_time_dayAbbrevRe.exec(string.slice(i));
+      return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
+    }
+    function d3_time_parseWeekday(date, string, i) {
+      d3_time_dayRe.lastIndex = 0;
+      var n = d3_time_dayRe.exec(string.slice(i));
+      return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
+    }
+    function d3_time_parseMonthAbbrev(date, string, i) {
+      d3_time_monthAbbrevRe.lastIndex = 0;
+      var n = d3_time_monthAbbrevRe.exec(string.slice(i));
+      return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
+    }
+    function d3_time_parseMonth(date, string, i) {
+      d3_time_monthRe.lastIndex = 0;
+      var n = d3_time_monthRe.exec(string.slice(i));
+      return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
+    }
+    function d3_time_parseLocaleFull(date, string, i) {
+      return d3_time_parse(date, d3_time_formats.c.toString(), string, i);
+    }
+    function d3_time_parseLocaleDate(date, string, i) {
+      return d3_time_parse(date, d3_time_formats.x.toString(), string, i);
+    }
+    function d3_time_parseLocaleTime(date, string, i) {
+      return d3_time_parse(date, d3_time_formats.X.toString(), string, i);
+    }
+    function d3_time_parseAmPm(date, string, i) {
+      var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase());
+      return n == null ? -1 : (date.p = n, i);
+    }
+    return d3_time_format;
+  }
+  var d3_time_formatPads = {
+    "-": "",
+    _: " ",
+    "0": "0"
+  }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/;
+  function d3_time_formatPad(value, fill, width) {
+    var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length;
+    return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
+  }
+  function d3_time_formatRe(names) {
+    return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i");
+  }
+  function d3_time_formatLookup(names) {
+    var map = new d3_Map(), i = -1, n = names.length;
+    while (++i < n) map.set(names[i].toLowerCase(), i);
+    return map;
+  }
+  function d3_time_parseWeekdayNumber(date, string, i) {
+    d3_time_numberRe.lastIndex = 0;
+    var n = d3_time_numberRe.exec(string.slice(i, i + 1));
+    return n ? (date.w = +n[0], i + n[0].length) : -1;
+  }
+  function d3_time_parseWeekNumberSunday(date, string, i) {
+    d3_time_numberRe.lastIndex = 0;
+    var n = d3_time_numberRe.exec(string.slice(i));
+    return n ? (date.U = +n[0], i + n[0].length) : -1;
+  }
+  function d3_time_parseWeekNumberMonday(date, string, i) {
+    d3_time_numberRe.lastIndex = 0;
+    var n = d3_time_numberRe.exec(string.slice(i));
+    return n ? (date.W = +n[0], i + n[0].length) : -1;
+  }
+  function d3_time_parseFullYear(date, string, i) {
+    d3_time_numberRe.lastIndex = 0;
+    var n = d3_time_numberRe.exec(string.slice(i, i + 4));
+    return n ? (date.y = +n[0], i + n[0].length) : -1;
+  }
+  function d3_time_parseYear(date, string, i) {
+    d3_time_numberRe.lastIndex = 0;
+    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
+    return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1;
+  }
+  function d3_time_parseZone(date, string, i) {
+    return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string, 
+    i + 5) : -1;
+  }
+  function d3_time_expandYear(d) {
+    return d + (d > 68 ? 1900 : 2e3);
+  }
+  function d3_time_parseMonthNumber(date, string, i) {
+    d3_time_numberRe.lastIndex = 0;
+    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
+    return n ? (date.m = n[0] - 1, i + n[0].length) : -1;
+  }
+  function d3_time_parseDay(date, string, i) {
+    d3_time_numberRe.lastIndex = 0;
+    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
+    return n ? (date.d = +n[0], i + n[0].length) : -1;
+  }
+  function d3_time_parseDayOfYear(date, string, i) {
+    d3_time_numberRe.lastIndex = 0;
+    var n = d3_time_numberRe.exec(string.slice(i, i + 3));
+    return n ? (date.j = +n[0], i + n[0].length) : -1;
+  }
+  function d3_time_parseHour24(date, string, i) {
+    d3_time_numberRe.lastIndex = 0;
+    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
+    return n ? (date.H = +n[0], i + n[0].length) : -1;
+  }
+  function d3_time_parseMinutes(date, string, i) {
+    d3_time_numberRe.lastIndex = 0;
+    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
+    return n ? (date.M = +n[0], i + n[0].length) : -1;
+  }
+  function d3_time_parseSeconds(date, string, i) {
+    d3_time_numberRe.lastIndex = 0;
+    var n = d3_time_numberRe.exec(string.slice(i, i + 2));
+    return n ? (date.S = +n[0], i + n[0].length) : -1;
+  }
+  function d3_time_parseMilliseconds(date, string, i) {
+    d3_time_numberRe.lastIndex = 0;
+    var n = d3_time_numberRe.exec(string.slice(i, i + 3));
+    return n ? (date.L = +n[0], i + n[0].length) : -1;
+  }
+  function d3_time_zone(d) {
+    var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60;
+    return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2);
+  }
+  function d3_time_parseLiteralPercent(date, string, i) {
+    d3_time_percentRe.lastIndex = 0;
+    var n = d3_time_percentRe.exec(string.slice(i, i + 1));
+    return n ? i + n[0].length : -1;
+  }
+  function d3_time_formatMulti(formats) {
+    var n = formats.length, i = -1;
+    while (++i < n) formats[i][0] = this(formats[i][0]);
+    return function(date) {
+      var i = 0, f = formats[i];
+      while (!f[1](date)) f = formats[++i];
+      return f[0](date);
+    };
+  }
+  d3.locale = function(locale) {
+    return {
+      numberFormat: d3_locale_numberFormat(locale),
+      timeFormat: d3_locale_timeFormat(locale)
+    };
+  };
+  var d3_locale_enUS = d3.locale({
+    decimal: ".",
+    thousands: ",",
+    grouping: [ 3 ],
+    currency: [ "$", "" ],
+    dateTime: "%a %b %e %X %Y",
+    date: "%m/%d/%Y",
+    time: "%H:%M:%S",
+    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" ]
+  });
+  d3.format = d3_locale_enUS.numberFormat;
+  d3.geo = {};
+  function d3_adder() {}
+  d3_adder.prototype = {
+    s: 0,
+    t: 0,
+    add: function(y) {
+      d3_adderSum(y, this.t, d3_adderTemp);
+      d3_adderSum(d3_adderTemp.s, this.s, this);
+      if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t;
+    },
+    reset: function() {
+      this.s = this.t = 0;
+    },
+    valueOf: function() {
+      return this.s;
+    }
+  };
+  var d3_adderTemp = new d3_adder();
+  function d3_adderSum(a, b, o) {
+    var x = o.s = a + b, bv = x - a, av = x - bv;
+    o.t = a - av + (b - bv);
+  }
+  d3.geo.stream = function(object, listener) {
+    if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) {
+      d3_geo_streamObjectType[object.type](object, listener);
+    } else {
+      d3_geo_streamGeometry(object, listener);
+    }
+  };
+  function d3_geo_streamGeometry(geometry, listener) {
+    if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) {
+      d3_geo_streamGeometryType[geometry.type](geometry, listener);
+    }
+  }
+  var d3_geo_streamObjectType = {
+    Feature: function(feature, listener) {
+      d3_geo_streamGeometry(feature.geometry, listener);
+    },
+    FeatureCollection: function(object, listener) {
+      var features = object.features, i = -1, n = features.length;
+      while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener);
+    }
+  };
+  var d3_geo_streamGeometryType = {
+    Sphere: function(object, listener) {
+      listener.sphere();
+    },
+    Point: function(object, listener) {
+      object = object.coordinates;
+      listener.point(object[0], object[1], object[2]);
+    },
+    MultiPoint: function(object, listener) {
+      var coordinates = object.coordinates, i = -1, n = coordinates.length;
+      while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]);
+    },
+    LineString: function(object, listener) {
+      d3_geo_streamLine(object.coordinates, listener, 0);
+    },
+    MultiLineString: function(object, listener) {
+      var coordinates = object.coordinates, i = -1, n = coordinates.length;
+      while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0);
+    },
+    Polygon: function(object, listener) {
+      d3_geo_streamPolygon(object.coordinates, listener);
+    },
+    MultiPolygon: function(object, listener) {
+      var coordinates = object.coordinates, i = -1, n = coordinates.length;
+      while (++i < n) d3_geo_streamPolygon(coordinates[i], listener);
+    },
+    GeometryCollection: function(object, listener) {
+      var geometries = object.geometries, i = -1, n = geometries.length;
+      while (++i < n) d3_geo_streamGeometry(geometries[i], listener);
+    }
+  };
+  function d3_geo_streamLine(coordinates, listener, closed) {
+    var i = -1, n = coordinates.length - closed, coordinate;
+    listener.lineStart();
+    while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]);
+    listener.lineEnd();
+  }
+  function d3_geo_streamPolygon(coordinates, listener) {
+    var i = -1, n = coordinates.length;
+    listener.polygonStart();
+    while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1);
+    listener.polygonEnd();
+  }
+  d3.geo.area = function(object) {
+    d3_geo_areaSum = 0;
+    d3.geo.stream(object, d3_geo_area);
+    return d3_geo_areaSum;
+  };
+  var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder();
+  var d3_geo_area = {
+    sphere: function() {
+      d3_geo_areaSum += 4 * Ï;
+    },
+    point: d3_noop,
+    lineStart: d3_noop,
+    lineEnd: d3_noop,
+    polygonStart: function() {
+      d3_geo_areaRingSum.reset();
+      d3_geo_area.lineStart = d3_geo_areaRingStart;
+    },
+    polygonEnd: function() {
+      var area = 2 * d3_geo_areaRingSum;
+      d3_geo_areaSum += area < 0 ? 4 * Ï + area : area;
+      d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop;
+    }
+  };
+  function d3_geo_areaRingStart() {
+    var Î»00, Ï00, Î»0, cosÏ0, sinÏ0;
+    d3_geo_area.point = function(Î», Ï) {
+      d3_geo_area.point = nextPoint;
+      Î»0 = (Î»00 = Î») * d3_radians, cosÏ0 = Math.cos(Ï = (Ï00 = Ï) * d3_radians / 2 + Ï / 4), 
+      sinÏ0 = Math.sin(Ï);
+    };
+    function nextPoint(Î», Ï) {
+      Î» *= d3_radians;
+      Ï = Ï * d3_radians / 2 + Ï / 4;
+      var dÎ» = Î» - Î»0, sdÎ» = dÎ» >= 0 ? 1 : -1, adÎ» = sdÎ» * dÎ», cosÏ = Math.cos(Ï), sinÏ = Math.sin(Ï), k = sinÏ0 * sinÏ, u = cosÏ0 * cosÏ + k * Math.cos(adÎ»), v = k * sdÎ» * Math.sin(adÎ»);
+      d3_geo_areaRingSum.add(Math.atan2(v, u));
+      Î»0 = Î», cosÏ0 = cosÏ, sinÏ0 = sinÏ;
+    }
+    d3_geo_area.lineEnd = function() {
+      nextPoint(Î»00, Ï00);
+    };
+  }
+  function d3_geo_cartesian(spherical) {
+    var Î» = spherical[0], Ï = spherical[1], cosÏ = Math.cos(Ï);
+    return [ cosÏ * Math.cos(Î»), cosÏ * Math.sin(Î»), Math.sin(Ï) ];
+  }
+  function d3_geo_cartesianDot(a, b) {
+    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+  }
+  function d3_geo_cartesianCross(a, b) {
+    return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ];
+  }
+  function d3_geo_cartesianAdd(a, b) {
+    a[0] += b[0];
+    a[1] += b[1];
+    a[2] += b[2];
+  }
+  function d3_geo_cartesianScale(vector, k) {
+    return [ vector[0] * k, vector[1] * k, vector[2] * k ];
+  }
+  function d3_geo_cartesianNormalize(d) {
+    var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
+    d[0] /= l;
+    d[1] /= l;
+    d[2] /= l;
+  }
+  function d3_geo_spherical(cartesian) {
+    return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ];
+  }
+  function d3_geo_sphericalEqual(a, b) {
+    return abs(a[0] - b[0]) < Îµ && abs(a[1] - b[1]) < Îµ;
+  }
+  d3.geo.bounds = function() {
+    var Î»0, Ï0, Î»1, Ï1, Î»_, Î»__, Ï__, p0, dÎ»Sum, ranges, range;
+    var bound = {
+      point: point,
+      lineStart: lineStart,
+      lineEnd: lineEnd,
+      polygonStart: function() {
+        bound.point = ringPoint;
+        bound.lineStart = ringStart;
+        bound.lineEnd = ringEnd;
+        dÎ»Sum = 0;
+        d3_geo_area.polygonStart();
+      },
+      polygonEnd: function() {
+        d3_geo_area.polygonEnd();
+        bound.point = point;
+        bound.lineStart = lineStart;
+        bound.lineEnd = lineEnd;
+        if (d3_geo_areaRingSum < 0) Î»0 = -(Î»1 = 180), Ï0 = -(Ï1 = 90); else if (dÎ»Sum > Îµ) Ï1 = 90; else if (dÎ»Sum < -Îµ) Ï0 = -90;
+        range[0] = Î»0, range[1] = Î»1;
+      }
+    };
+    function point(Î», Ï) {
+      ranges.push(range = [ Î»0 = Î», Î»1 = Î» ]);
+      if (Ï < Ï0) Ï0 = Ï;
+      if (Ï > Ï1) Ï1 = Ï;
+    }
+    function linePoint(Î», Ï) {
+      var p = d3_geo_cartesian([ Î» * d3_radians, Ï * d3_radians ]);
+      if (p0) {
+        var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal);
+        d3_geo_cartesianNormalize(inflection);
+        inflection = d3_geo_spherical(inflection);
+        var dÎ» = Î» - Î»_, s = dÎ» > 0 ? 1 : -1, Î»i = inflection[0] * d3_degrees * s, antimeridian = abs(dÎ») > 180;
+        if (antimeridian ^ (s * Î»_ < Î»i && Î»i < s * Î»)) {
+          var Ïi = inflection[1] * d3_degrees;
+          if (Ïi > Ï1) Ï1 = Ïi;
+        } else if (Î»i = (Î»i + 360) % 360 - 180, antimeridian ^ (s * Î»_ < Î»i && Î»i < s * Î»)) {
+          var Ïi = -inflection[1] * d3_degrees;
+          if (Ïi < Ï0) Ï0 = Ïi;
+        } else {
+          if (Ï < Ï0) Ï0 = Ï;
+          if (Ï > Ï1) Ï1 = Ï;
+        }
+        if (antimeridian) {
+          if (Î» < Î»_) {
+            if (angle(Î»0, Î») > angle(Î»0, Î»1)) Î»1 = Î»;
+          } else {
+            if (angle(Î», Î»1) > angle(Î»0, Î»1)) Î»0 = Î»;
+          }
+        } else {
+          if (Î»1 >= Î»0) {
+            if (Î» < Î»0) Î»0 = Î»;
+            if (Î» > Î»1) Î»1 = Î»;
+          } else {
+            if (Î» > Î»_) {
+              if (angle(Î»0, Î») > angle(Î»0, Î»1)) Î»1 = Î»;
+            } else {
+              if (angle(Î», Î»1) > angle(Î»0, Î»1)) Î»0 = Î»;
+            }
+          }
+        }
+      } else {
+        point(Î», Ï);
+      }
+      p0 = p, Î»_ = Î»;
+    }
+    function lineStart() {
+      bound.point = linePoint;
+    }
+    function lineEnd() {
+      range[0] = Î»0, range[1] = Î»1;
+      bound.point = point;
+      p0 = null;
+    }
+    function ringPoint(Î», Ï) {
+      if (p0) {
+        var dÎ» = Î» - Î»_;
+        dÎ»Sum += abs(dÎ») > 180 ? dÎ» + (dÎ» > 0 ? 360 : -360) : dÎ»;
+      } else Î»__ = Î», Ï__ = Ï;
+      d3_geo_area.point(Î», Ï);
+      linePoint(Î», Ï);
+    }
+    function ringStart() {
+      d3_geo_area.lineStart();
+    }
+    function ringEnd() {
+      ringPoint(Î»__, Ï__);
+      d3_geo_area.lineEnd();
+      if (abs(dÎ»Sum) > Îµ) Î»0 = -(Î»1 = 180);
+      range[0] = Î»0, range[1] = Î»1;
+      p0 = null;
+    }
+    function angle(Î»0, Î»1) {
+      return (Î»1 -= Î»0) < 0 ? Î»1 + 360 : Î»1;
+    }
+    function compareRanges(a, b) {
+      return a[0] - b[0];
+    }
+    function withinRange(x, range) {
+      return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
+    }
+    return function(feature) {
+      Ï1 = Î»1 = -(Î»0 = Ï0 = Infinity);
+      ranges = [];
+      d3.geo.stream(feature, bound);
+      var n = ranges.length;
+      if (n) {
+        ranges.sort(compareRanges);
+        for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) {
+          b = ranges[i];
+          if (withinRange(b[0], a) || withinRange(b[1], a)) {
+            if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];
+            if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];
+          } else {
+            merged.push(a = b);
+          }
+        }
+        var best = -Infinity, dÎ»;
+        for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) {
+          b = merged[i];
+          if ((dÎ» = angle(a[1], b[0])) > best) best = dÎ», Î»0 = b[0], Î»1 = a[1];
+        }
+      }
+      ranges = range = null;
+      return Î»0 === Infinity || Ï0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ Î»0, Ï0 ], [ Î»1, Ï1 ] ];
+    };
+  }();
+  d3.geo.centroid = function(object) {
+    d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
+    d3.geo.stream(object, d3_geo_centroid);
+    var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z;
+    if (m < Îµ2) {
+      x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1;
+      if (d3_geo_centroidW1 < Îµ) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0;
+      m = x * x + y * y + z * z;
+      if (m < Îµ2) return [ NaN, NaN ];
+    }
+    return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ];
+  };
+  var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2;
+  var d3_geo_centroid = {
+    sphere: d3_noop,
+    point: d3_geo_centroidPoint,
+    lineStart: d3_geo_centroidLineStart,
+    lineEnd: d3_geo_centroidLineEnd,
+    polygonStart: function() {
+      d3_geo_centroid.lineStart = d3_geo_centroidRingStart;
+    },
+    polygonEnd: function() {
+      d3_geo_centroid.lineStart = d3_geo_centroidLineStart;
+    }
+  };
+  function d3_geo_centroidPoint(Î», Ï) {
+    Î» *= d3_radians;
+    var cosÏ = Math.cos(Ï *= d3_radians);
+    d3_geo_centroidPointXYZ(cosÏ * Math.cos(Î»), cosÏ * Math.sin(Î»), Math.sin(Ï));
+  }
+  function d3_geo_centroidPointXYZ(x, y, z) {
+    ++d3_geo_centroidW0;
+    d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0;
+    d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0;
+    d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0;
+  }
+  function d3_geo_centroidLineStart() {
+    var x0, y0, z0;
+    d3_geo_centroid.point = function(Î», Ï) {
+      Î» *= d3_radians;
+      var cosÏ = Math.cos(Ï *= d3_radians);
+      x0 = cosÏ * Math.cos(Î»);
+      y0 = cosÏ * Math.sin(Î»);
+      z0 = Math.sin(Ï);
+      d3_geo_centroid.point = nextPoint;
+      d3_geo_centroidPointXYZ(x0, y0, z0);
+    };
+    function nextPoint(Î», Ï) {
+      Î» *= d3_radians;
+      var cosÏ = Math.cos(Ï *= d3_radians), x = cosÏ * Math.cos(Î»), y = cosÏ * Math.sin(Î»), z = Math.sin(Ï), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);
+      d3_geo_centroidW1 += w;
+      d3_geo_centroidX1 += w * (x0 + (x0 = x));
+      d3_geo_centroidY1 += w * (y0 + (y0 = y));
+      d3_geo_centroidZ1 += w * (z0 + (z0 = z));
+      d3_geo_centroidPointXYZ(x0, y0, z0);
+    }
+  }
+  function d3_geo_centroidLineEnd() {
+    d3_geo_centroid.point = d3_geo_centroidPoint;
+  }
+  function d3_geo_centroidRingStart() {
+    var Î»00, Ï00, x0, y0, z0;
+    d3_geo_centroid.point = function(Î», Ï) {
+      Î»00 = Î», Ï00 = Ï;
+      d3_geo_centroid.point = nextPoint;
+      Î» *= d3_radians;
+      var cosÏ = Math.cos(Ï *= d3_radians);
+      x0 = cosÏ * Math.cos(Î»);
+      y0 = cosÏ * Math.sin(Î»);
+      z0 = Math.sin(Ï);
+      d3_geo_centroidPointXYZ(x0, y0, z0);
+    };
+    d3_geo_centroid.lineEnd = function() {
+      nextPoint(Î»00, Ï00);
+      d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd;
+      d3_geo_centroid.point = d3_geo_centroidPoint;
+    };
+    function nextPoint(Î», Ï) {
+      Î» *= d3_radians;
+      var cosÏ = Math.cos(Ï *= d3_radians), x = cosÏ * Math.cos(Î»), y = cosÏ * Math.sin(Î»), z = Math.sin(Ï), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u);
+      d3_geo_centroidX2 += v * cx;
+      d3_geo_centroidY2 += v * cy;
+      d3_geo_centroidZ2 += v * cz;
+      d3_geo_centroidW1 += w;
+      d3_geo_centroidX1 += w * (x0 + (x0 = x));
+      d3_geo_centroidY1 += w * (y0 + (y0 = y));
+      d3_geo_centroidZ1 += w * (z0 + (z0 = z));
+      d3_geo_centroidPointXYZ(x0, y0, z0);
+    }
+  }
+  function d3_geo_compose(a, b) {
+    function compose(x, y) {
+      return x = a(x, y), b(x[0], x[1]);
+    }
+    if (a.invert && b.invert) compose.invert = function(x, y) {
+      return x = b.invert(x, y), x && a.invert(x[0], x[1]);
+    };
+    return compose;
+  }
+  function d3_true() {
+    return true;
+  }
+  function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) {
+    var subject = [], clip = [];
+    segments.forEach(function(segment) {
+      if ((n = segment.length - 1) <= 0) return;
+      var n, p0 = segment[0], p1 = segment[n];
+      if (d3_geo_sphericalEqual(p0, p1)) {
+        listener.lineStart();
+        for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]);
+        listener.lineEnd();
+        return;
+      }
+      var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false);
+      a.o = b;
+      subject.push(a);
+      clip.push(b);
+      a = new d3_geo_clipPolygonIntersection(p1, segment, null, false);
+      b = new d3_geo_clipPolygonIntersection(p1, null, a, true);
+      a.o = b;
+      subject.push(a);
+      clip.push(b);
+    });
+    clip.sort(compare);
+    d3_geo_clipPolygonLinkCircular(subject);
+    d3_geo_clipPolygonLinkCircular(clip);
+    if (!subject.length) return;
+    for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) {
+      clip[i].e = entry = !entry;
+    }
+    var start = subject[0], points, point;
+    while (1) {
+      var current = start, isSubject = true;
+      while (current.v) if ((current = current.n) === start) return;
+      points = current.z;
+      listener.lineStart();
+      do {
+        current.v = current.o.v = true;
+        if (current.e) {
+          if (isSubject) {
+            for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]);
+          } else {
+            interpolate(current.x, current.n.x, 1, listener);
+          }
+          current = current.n;
+        } else {
+          if (isSubject) {
+            points = current.p.z;
+            for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]);
+          } else {
+            interpolate(current.x, current.p.x, -1, listener);
+          }
+          current = current.p;
+        }
+        current = current.o;
+        points = current.z;
+        isSubject = !isSubject;
+      } while (!current.v);
+      listener.lineEnd();
+    }
+  }
+  function d3_geo_clipPolygonLinkCircular(array) {
+    if (!(n = array.length)) return;
+    var n, i = 0, a = array[0], b;
+    while (++i < n) {
+      a.n = b = array[i];
+      b.p = a;
+      a = b;
+    }
+    a.n = b = array[0];
+    b.p = a;
+  }
+  function d3_geo_clipPolygonIntersection(point, points, other, entry) {
+    this.x = point;
+    this.z = points;
+    this.o = other;
+    this.e = entry;
+    this.v = false;
+    this.n = this.p = null;
+  }
+  function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) {
+    return function(rotate, listener) {
+      var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]);
+      var clip = {
+        point: point,
+        lineStart: lineStart,
+        lineEnd: lineEnd,
+        polygonStart: function() {
+          clip.point = pointRing;
+          clip.lineStart = ringStart;
+          clip.lineEnd = ringEnd;
+          segments = [];
+          polygon = [];
+        },
+        polygonEnd: function() {
+          clip.point = point;
+          clip.lineStart = lineStart;
+          clip.lineEnd = lineEnd;
+          segments = d3.merge(segments);
+          var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon);
+          if (segments.length) {
+            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
+            d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener);
+          } else if (clipStartInside) {
+            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
+            listener.lineStart();
+            interpolate(null, null, 1, listener);
+            listener.lineEnd();
+          }
+          if (polygonStarted) listener.polygonEnd(), polygonStarted = false;
+          segments = polygon = null;
+        },
+        sphere: function() {
+          listener.polygonStart();
+          listener.lineStart();
+          interpolate(null, null, 1, listener);
+          listener.lineEnd();
+          listener.polygonEnd();
+        }
+      };
+      function point(Î», Ï) {
+        var point = rotate(Î», Ï);
+        if (pointVisible(Î» = point[0], Ï = point[1])) listener.point(Î», Ï);
+      }
+      function pointLine(Î», Ï) {
+        var point = rotate(Î», Ï);
+        line.point(point[0], point[1]);
+      }
+      function lineStart() {
+        clip.point = pointLine;
+        line.lineStart();
+      }
+      function lineEnd() {
+        clip.point = point;
+        line.lineEnd();
+      }
+      var segments;
+      var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring;
+      function pointRing(Î», Ï) {
+        ring.push([ Î», Ï ]);
+        var point = rotate(Î», Ï);
+        ringListener.point(point[0], point[1]);
+      }
+      function ringStart() {
+        ringListener.lineStart();
+        ring = [];
+      }
+      function ringEnd() {
+        pointRing(ring[0][0], ring[0][1]);
+        ringListener.lineEnd();
+        var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length;
+        ring.pop();
+        polygon.push(ring);
+        ring = null;
+        if (!n) return;
+        if (clean & 1) {
+          segment = ringSegments[0];
+          var n = segment.length - 1, i = -1, point;
+          if (n > 0) {
+            if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
+            listener.lineStart();
+            while (++i < n) listener.point((point = segment[i])[0], point[1]);
+            listener.lineEnd();
+          }
+          return;
+        }
+        if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
+        segments.push(ringSegments.filter(d3_geo_clipSegmentLength1));
+      }
+      return clip;
+    };
+  }
+  function d3_geo_clipSegmentLength1(segment) {
+    return segment.length > 1;
+  }
+  function d3_geo_clipBufferListener() {
+    var lines = [], line;
+    return {
+      lineStart: function() {
+        lines.push(line = []);
+      },
+      point: function(Î», Ï) {
+        line.push([ Î», Ï ]);
+      },
+      lineEnd: d3_noop,
+      buffer: function() {
+        var buffer = lines;
+        lines = [];
+        line = null;
+        return buffer;
+      },
+      rejoin: function() {
+        if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
+      }
+    };
+  }
+  function d3_geo_clipSort(a, b) {
+    return ((a = a.x)[0] < 0 ? a[1] - halfÏ - Îµ : halfÏ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfÏ - Îµ : halfÏ - b[1]);
+  }
+  var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -Ï, -Ï / 2 ]);
+  function d3_geo_clipAntimeridianLine(listener) {
+    var Î»0 = NaN, Ï0 = NaN, sÎ»0 = NaN, clean;
+    return {
+      lineStart: function() {
+        listener.lineStart();
+        clean = 1;
+      },
+      point: function(Î»1, Ï1) {
+        var sÎ»1 = Î»1 > 0 ? Ï : -Ï, dÎ» = abs(Î»1 - Î»0);
+        if (abs(dÎ» - Ï) < Îµ) {
+          listener.point(Î»0, Ï0 = (Ï0 + Ï1) / 2 > 0 ? halfÏ : -halfÏ);
+          listener.point(sÎ»0, Ï0);
+          listener.lineEnd();
+          listener.lineStart();
+          listener.point(sÎ»1, Ï0);
+          listener.point(Î»1, Ï0);
+          clean = 0;
+        } else if (sÎ»0 !== sÎ»1 && dÎ» >= Ï) {
+          if (abs(Î»0 - sÎ»0) < Îµ) Î»0 -= sÎ»0 * Îµ;
+          if (abs(Î»1 - sÎ»1) < Îµ) Î»1 -= sÎ»1 * Îµ;
+          Ï0 = d3_geo_clipAntimeridianIntersect(Î»0, Ï0, Î»1, Ï1);
+          listener.point(sÎ»0, Ï0);
+          listener.lineEnd();
+          listener.lineStart();
+          listener.point(sÎ»1, Ï0);
+          clean = 0;
+        }
+        listener.point(Î»0 = Î»1, Ï0 = Ï1);
+        sÎ»0 = sÎ»1;
+      },
+      lineEnd: function() {
+        listener.lineEnd();
+        Î»0 = Ï0 = NaN;
+      },
+      clean: function() {
+        return 2 - clean;
+      }
+    };
+  }
+  function d3_geo_clipAntimeridianIntersect(Î»0, Ï0, Î»1, Ï1) {
+    var cosÏ0, cosÏ1, sinÎ»0_Î»1 = Math.sin(Î»0 - Î»1);
+    return abs(sinÎ»0_Î»1) > Îµ ? Math.atan((Math.sin(Ï0) * (cosÏ1 = Math.cos(Ï1)) * Math.sin(Î»1) - Math.sin(Ï1) * (cosÏ0 = Math.cos(Ï0)) * Math.sin(Î»0)) / (cosÏ0 * cosÏ1 * sinÎ»0_Î»1)) : (Ï0 + Ï1) / 2;
+  }
+  function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) {
+    var Ï;
+    if (from == null) {
+      Ï = direction * halfÏ;
+      listener.point(-Ï, Ï);
+      listener.point(0, Ï);
+      listener.point(Ï, Ï);
+      listener.point(Ï, 0);
+      listener.point(Ï, -Ï);
+      listener.point(0, -Ï);
+      listener.point(-Ï, -Ï);
+      listener.point(-Ï, 0);
+      listener.point(-Ï, Ï);
+    } else if (abs(from[0] - to[0]) > Îµ) {
+      var s = from[0] < to[0] ? Ï : -Ï;
+      Ï = direction * s / 2;
+      listener.point(-s, Ï);
+      listener.point(0, Ï);
+      listener.point(s, Ï);
+    } else {
+      listener.point(to[0], to[1]);
+    }
+  }
+  function d3_geo_pointInPolygon(point, polygon) {
+    var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0;
+    d3_geo_areaRingSum.reset();
+    for (var i = 0, n = polygon.length; i < n; ++i) {
+      var ring = polygon[i], m = ring.length;
+      if (!m) continue;
+      var point0 = ring[0], Î»0 = point0[0], Ï0 = point0[1] / 2 + Ï / 4, sinÏ0 = Math.sin(Ï0), cosÏ0 = Math.cos(Ï0), j = 1;
+      while (true) {
+        if (j === m) j = 0;
+        point = ring[j];
+        var Î» = point[0], Ï = point[1] / 2 + Ï / 4, sinÏ = Math.sin(Ï), cosÏ = Math.cos(Ï), dÎ» = Î» - Î»0, sdÎ» = dÎ» >= 0 ? 1 : -1, adÎ» = sdÎ» * dÎ», antimeridian = adÎ» > Ï, k = sinÏ0 * sinÏ;
+        d3_geo_areaRingSum.add(Math.atan2(k * sdÎ» * Math.sin(adÎ»), cosÏ0 * cosÏ + k * Math.cos(adÎ»)));
+        polarAngle += antimeridian ? dÎ» + sdÎ» * Ï : dÎ»;
+        if (antimeridian ^ Î»0 >= meridian ^ Î» >= meridian) {
+          var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point));
+          d3_geo_cartesianNormalize(arc);
+          var intersection = d3_geo_cartesianCross(meridianNormal, arc);
+          d3_geo_cartesianNormalize(intersection);
+          var Ïarc = (antimeridian ^ dÎ» >= 0 ? -1 : 1) * d3_asin(intersection[2]);
+          if (parallel > Ïarc || parallel === Ïarc && (arc[0] || arc[1])) {
+            winding += antimeridian ^ dÎ» >= 0 ? 1 : -1;
+          }
+        }
+        if (!j++) break;
+        Î»0 = Î», sinÏ0 = sinÏ, cosÏ0 = cosÏ, point0 = point;
+      }
+    }
+    return (polarAngle < -Îµ || polarAngle < Îµ && d3_geo_areaRingSum < 0) ^ winding & 1;
+  }
+  function d3_geo_clipCircle(radius) {
+    var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > Îµ, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians);
+    return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -Ï, radius - Ï ]);
+    function visible(Î», Ï) {
+      return Math.cos(Î») * Math.cos(Ï) > cr;
+    }
+    function clipLine(listener) {
+      var point0, c0, v0, v00, clean;
+      return {
+        lineStart: function() {
+          v00 = v0 = false;
+          clean = 1;
+        },
+        point: function(Î», Ï) {
+          var point1 = [ Î», Ï ], point2, v = visible(Î», Ï), c = smallRadius ? v ? 0 : code(Î», Ï) : v ? code(Î» + (Î» < 0 ? Ï : -Ï), Ï) : 0;
+          if (!point0 && (v00 = v0 = v)) listener.lineStart();
+          if (v !== v0) {
+            point2 = intersect(point0, point1);
+            if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) {
+              point1[0] += Îµ;
+              point1[1] += Îµ;
+              v = visible(point1[0], point1[1]);
+            }
+          }
+          if (v !== v0) {
+            clean = 0;
+            if (v) {
+              listener.lineStart();
+              point2 = intersect(point1, point0);
+              listener.point(point2[0], point2[1]);
+            } else {
+              point2 = intersect(point0, point1);
+              listener.point(point2[0], point2[1]);
+              listener.lineEnd();
+            }
+            point0 = point2;
+          } else if (notHemisphere && point0 && smallRadius ^ v) {
+            var t;
+            if (!(c & c0) && (t = intersect(point1, point0, true))) {
+              clean = 0;
+              if (smallRadius) {
+                listener.lineStart();
+                listener.point(t[0][0], t[0][1]);
+                listener.point(t[1][0], t[1][1]);
+                listener.lineEnd();
+              } else {
+                listener.point(t[1][0], t[1][1]);
+                listener.lineEnd();
+                listener.lineStart();
+                listener.point(t[0][0], t[0][1]);
+              }
+            }
+          }
+          if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) {
+            listener.point(point1[0], point1[1]);
+          }
+          point0 = point1, v0 = v, c0 = c;
+        },
+        lineEnd: function() {
+          if (v0) listener.lineEnd();
+          point0 = null;
+        },
+        clean: function() {
+          return clean | (v00 && v0) << 1;
+        }
+      };
+    }
+    function intersect(a, b, two) {
+      var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b);
+      var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2;
+      if (!determinant) return !two && a;
+      var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2);
+      d3_geo_cartesianAdd(A, B);
+      var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1);
+      if (t2 < 0) return;
+      var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu);
+      d3_geo_cartesianAdd(q, A);
+      q = d3_geo_spherical(q);
+      if (!two) return q;
+      var Î»0 = a[0], Î»1 = b[0], Ï0 = a[1], Ï1 = b[1], z;
+      if (Î»1 < Î»0) z = Î»0, Î»0 = Î»1, Î»1 = z;
+      var ÎŽÎ» = Î»1 - Î»0, polar = abs(ÎŽÎ» - Ï) < Îµ, meridian = polar || ÎŽÎ» < Îµ;
+      if (!polar && Ï1 < Ï0) z = Ï0, Ï0 = Ï1, Ï1 = z;
+      if (meridian ? polar ? Ï0 + Ï1 > 0 ^ q[1] < (abs(q[0] - Î»0) < Îµ ? Ï0 : Ï1) : Ï0 <= q[1] && q[1] <= Ï1 : ÎŽÎ» > Ï ^ (Î»0 <= q[0] && q[0] <= Î»1)) {
+        var q1 = d3_geo_cartesianScale(u, (-w + t) / uu);
+        d3_geo_cartesianAdd(q1, A);
+        return [ q, d3_geo_spherical(q1) ];
+      }
+    }
+    function code(Î», Ï) {
+      var r = smallRadius ? radius : Ï - radius, code = 0;
+      if (Î» < -r) code |= 1; else if (Î» > r) code |= 2;
+      if (Ï < -r) code |= 4; else if (Ï > r) code |= 8;
+      return code;
+    }
+  }
+  function d3_geom_clipLine(x0, y0, x1, y1) {
+    return function(line) {
+      var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r;
+      r = x0 - ax;
+      if (!dx && r > 0) return;
+      r /= dx;
+      if (dx < 0) {
+        if (r < t0) return;
+        if (r < t1) t1 = r;
+      } else if (dx > 0) {
+        if (r > t1) return;
+        if (r > t0) t0 = r;
+      }
+      r = x1 - ax;
+      if (!dx && r < 0) return;
+      r /= dx;
+      if (dx < 0) {
+        if (r > t1) return;
+        if (r > t0) t0 = r;
+      } else if (dx > 0) {
+        if (r < t0) return;
+        if (r < t1) t1 = r;
+      }
+      r = y0 - ay;
+      if (!dy && r > 0) return;
+      r /= dy;
+      if (dy < 0) {
+        if (r < t0) return;
+        if (r < t1) t1 = r;
+      } else if (dy > 0) {
+        if (r > t1) return;
+        if (r > t0) t0 = r;
+      }
+      r = y1 - ay;
+      if (!dy && r < 0) return;
+      r /= dy;
+      if (dy < 0) {
+        if (r > t1) return;
+        if (r > t0) t0 = r;
+      } else if (dy > 0) {
+        if (r < t0) return;
+        if (r < t1) t1 = r;
+      }
+      if (t0 > 0) line.a = {
+        x: ax + t0 * dx,
+        y: ay + t0 * dy
+      };
+      if (t1 < 1) line.b = {
+        x: ax + t1 * dx,
+        y: ay + t1 * dy
+      };
+      return line;
+    };
+  }
+  var d3_geo_clipExtentMAX = 1e9;
+  d3.geo.clipExtent = function() {
+    var x0, y0, x1, y1, stream, clip, clipExtent = {
+      stream: function(output) {
+        if (stream) stream.valid = false;
+        stream = clip(output);
+        stream.valid = true;
+        return stream;
+      },
+      extent: function(_) {
+        if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
+        clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]);
+        if (stream) stream.valid = false, stream = null;
+        return clipExtent;
+      }
+    };
+    return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]);
+  };
+  function d3_geo_clipExtent(x0, y0, x1, y1) {
+    return function(listener) {
+      var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring;
+      var clip = {
+        point: point,
+        lineStart: lineStart,
+        lineEnd: lineEnd,
+        polygonStart: function() {
+          listener = bufferListener;
+          segments = [];
+          polygon = [];
+          clean = true;
+        },
+        polygonEnd: function() {
+          listener = listener_;
+          segments = d3.merge(segments);
+          var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length;
+          if (inside || visible) {
+            listener.polygonStart();
+            if (inside) {
+              listener.lineStart();
+              interpolate(null, null, 1, listener);
+              listener.lineEnd();
+            }
+            if (visible) {
+              d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener);
+            }
+            listener.polygonEnd();
+          }
+          segments = polygon = ring = null;
+        }
+      };
+      function insidePolygon(p) {
+        var wn = 0, n = polygon.length, y = p[1];
+        for (var i = 0; i < n; ++i) {
+          for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) {
+            b = v[j];
+            if (a[1] <= y) {
+              if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn;
+            } else {
+              if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn;
+            }
+            a = b;
+          }
+        }
+        return wn !== 0;
+      }
+      function interpolate(from, to, direction, listener) {
+        var a = 0, a1 = 0;
+        if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) {
+          do {
+            listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);
+          } while ((a = (a + direction + 4) % 4) !== a1);
+        } else {
+          listener.point(to[0], to[1]);
+        }
+      }
+      function pointVisible(x, y) {
+        return x0 <= x && x <= x1 && y0 <= y && y <= y1;
+      }
+      function point(x, y) {
+        if (pointVisible(x, y)) listener.point(x, y);
+      }
+      var x__, y__, v__, x_, y_, v_, first, clean;
+      function lineStart() {
+        clip.point = linePoint;
+        if (polygon) polygon.push(ring = []);
+        first = true;
+        v_ = false;
+        x_ = y_ = NaN;
+      }
+      function lineEnd() {
+        if (segments) {
+          linePoint(x__, y__);
+          if (v__ && v_) bufferListener.rejoin();
+          segments.push(bufferListener.buffer());
+        }
+        clip.point = point;
+        if (v_) listener.lineEnd();
+      }
+      function linePoint(x, y) {
+        x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x));
+        y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y));
+        var v = pointVisible(x, y);
+        if (polygon) ring.push([ x, y ]);
+        if (first) {
+          x__ = x, y__ = y, v__ = v;
+          first = false;
+          if (v) {
+            listener.lineStart();
+            listener.point(x, y);
+          }
+        } else {
+          if (v && v_) listener.point(x, y); else {
+            var l = {
+              a: {
+                x: x_,
+                y: y_
+              },
+              b: {
+                x: x,
+                y: y
+              }
+            };
+            if (clipLine(l)) {
+              if (!v_) {
+                listener.lineStart();
+                listener.point(l.a.x, l.a.y);
+              }
+              listener.point(l.b.x, l.b.y);
+              if (!v) listener.lineEnd();
+              clean = false;
+            } else if (v) {
+              listener.lineStart();
+              listener.point(x, y);
+              clean = false;
+            }
+          }
+        }
+        x_ = x, y_ = y, v_ = v;
+      }
+      return clip;
+    };
+    function corner(p, direction) {
+      return abs(p[0] - x0) < Îµ ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < Îµ ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < Îµ ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2;
+    }
+    function compare(a, b) {
+      return comparePoints(a.x, b.x);
+    }
+    function comparePoints(a, b) {
+      var ca = corner(a, 1), cb = corner(b, 1);
+      return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0];
+    }
+  }
+  function d3_geo_conic(projectAt) {
+    var Ï0 = 0, Ï1 = Ï / 3, m = d3_geo_projectionMutator(projectAt), p = m(Ï0, Ï1);
+    p.parallels = function(_) {
+      if (!arguments.length) return [ Ï0 / Ï * 180, Ï1 / Ï * 180 ];
+      return m(Ï0 = _[0] * Ï / 180, Ï1 = _[1] * Ï / 180);
+    };
+    return p;
+  }
+  function d3_geo_conicEqualArea(Ï0, Ï1) {
+    var sinÏ0 = Math.sin(Ï0), n = (sinÏ0 + Math.sin(Ï1)) / 2, C = 1 + sinÏ0 * (2 * n - sinÏ0), Ï0 = Math.sqrt(C) / n;
+    function forward(Î», Ï) {
+      var Ï = Math.sqrt(C - 2 * n * Math.sin(Ï)) / n;
+      return [ Ï * Math.sin(Î» *= n), Ï0 - Ï * Math.cos(Î») ];
+    }
+    forward.invert = function(x, y) {
+      var Ï0_y = Ï0 - y;
+      return [ Math.atan2(x, Ï0_y) / n, d3_asin((C - (x * x + Ï0_y * Ï0_y) * n * n) / (2 * n)) ];
+    };
+    return forward;
+  }
+  (d3.geo.conicEqualArea = function() {
+    return d3_geo_conic(d3_geo_conicEqualArea);
+  }).raw = d3_geo_conicEqualArea;
+  d3.geo.albers = function() {
+    return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070);
+  };
+  d3.geo.albersUsa = function() {
+    var lower48 = d3.geo.albers();
+    var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]);
+    var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]);
+    var point, pointStream = {
+      point: function(x, y) {
+        point = [ x, y ];
+      }
+    }, lower48Point, alaskaPoint, hawaiiPoint;
+    function albersUsa(coordinates) {
+      var x = coordinates[0], y = coordinates[1];
+      point = null;
+      (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y);
+      return point;
+    }
+    albersUsa.invert = function(coordinates) {
+      var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k;
+      return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates);
+    };
+    albersUsa.stream = function(stream) {
+      var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream);
+      return {
+        point: function(x, y) {
+          lower48Stream.point(x, y);
+          alaskaStream.point(x, y);
+          hawaiiStream.point(x, y);
+        },
+        sphere: function() {
+          lower48Stream.sphere();
+          alaskaStream.sphere();
+          hawaiiStream.sphere();
+        },
+        lineStart: function() {
+          lower48Stream.lineStart();
+          alaskaStream.lineStart();
+          hawaiiStream.lineStart();
+        },
+        lineEnd: function() {
+          lower48Stream.lineEnd();
+          alaskaStream.lineEnd();
+          hawaiiStream.lineEnd();
+        },
+        polygonStart: function() {
+          lower48Stream.polygonStart();
+          alaskaStream.polygonStart();
+          hawaiiStream.polygonStart();
+        },
+        polygonEnd: function() {
+          lower48Stream.polygonEnd();
+          alaskaStream.polygonEnd();
+          hawaiiStream.polygonEnd();
+        }
+      };
+    };
+    albersUsa.precision = function(_) {
+      if (!arguments.length) return lower48.precision();
+      lower48.precision(_);
+      alaska.precision(_);
+      hawaii.precision(_);
+      return albersUsa;
+    };
+    albersUsa.scale = function(_) {
+      if (!arguments.length) return lower48.scale();
+      lower48.scale(_);
+      alaska.scale(_ * .35);
+      hawaii.scale(_);
+      return albersUsa.translate(lower48.translate());
+    };
+    albersUsa.translate = function(_) {
+      if (!arguments.length) return lower48.translate();
+      var k = lower48.scale(), x = +_[0], y = +_[1];
+      lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point;
+      alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + Îµ, y + .12 * k + Îµ ], [ x - .214 * k - Îµ, y + .234 * k - Îµ ] ]).stream(pointStream).point;
+      hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + Îµ, y + .166 * k + Îµ ], [ x - .115 * k - Îµ, y + .234 * k - Îµ ] ]).stream(pointStream).point;
+      return albersUsa;
+    };
+    return albersUsa.scale(1070);
+  };
+  var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = {
+    point: d3_noop,
+    lineStart: d3_noop,
+    lineEnd: d3_noop,
+    polygonStart: function() {
+      d3_geo_pathAreaPolygon = 0;
+      d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart;
+    },
+    polygonEnd: function() {
+      d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop;
+      d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2);
+    }
+  };
+  function d3_geo_pathAreaRingStart() {
+    var x00, y00, x0, y0;
+    d3_geo_pathArea.point = function(x, y) {
+      d3_geo_pathArea.point = nextPoint;
+      x00 = x0 = x, y00 = y0 = y;
+    };
+    function nextPoint(x, y) {
+      d3_geo_pathAreaPolygon += y0 * x - x0 * y;
+      x0 = x, y0 = y;
+    }
+    d3_geo_pathArea.lineEnd = function() {
+      nextPoint(x00, y00);
+    };
+  }
+  var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1;
+  var d3_geo_pathBounds = {
+    point: d3_geo_pathBoundsPoint,
+    lineStart: d3_noop,
+    lineEnd: d3_noop,
+    polygonStart: d3_noop,
+    polygonEnd: d3_noop
+  };
+  function d3_geo_pathBoundsPoint(x, y) {
+    if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x;
+    if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x;
+    if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y;
+    if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y;
+  }
+  function d3_geo_pathBuffer() {
+    var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = [];
+    var stream = {
+      point: point,
+      lineStart: function() {
+        stream.point = pointLineStart;
+      },
+      lineEnd: lineEnd,
+      polygonStart: function() {
+        stream.lineEnd = lineEndPolygon;
+      },
+      polygonEnd: function() {
+        stream.lineEnd = lineEnd;
+        stream.point = point;
+      },
+      pointRadius: function(_) {
+        pointCircle = d3_geo_pathBufferCircle(_);
+        return stream;
+      },
+      result: function() {
+        if (buffer.length) {
+          var result = buffer.join("");
+          buffer = [];
+          return result;
+        }
+      }
+    };
+    function point(x, y) {
+      buffer.push("M", x, ",", y, pointCircle);
+    }
+    function pointLineStart(x, y) {
+      buffer.push("M", x, ",", y);
+      stream.point = pointLine;
+    }
+    function pointLine(x, y) {
+      buffer.push("L", x, ",", y);
+    }
+    function lineEnd() {
+      stream.point = point;
+    }
+    function lineEndPolygon() {
+      buffer.push("Z");
+    }
+    return stream;
+  }
+  function d3_geo_pathBufferCircle(radius) {
+    return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z";
+  }
+  var d3_geo_pathCentroid = {
+    point: d3_geo_pathCentroidPoint,
+    lineStart: d3_geo_pathCentroidLineStart,
+    lineEnd: d3_geo_pathCentroidLineEnd,
+    polygonStart: function() {
+      d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart;
+    },
+    polygonEnd: function() {
+      d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
+      d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart;
+      d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd;
+    }
+  };
+  function d3_geo_pathCentroidPoint(x, y) {
+    d3_geo_centroidX0 += x;
+    d3_geo_centroidY0 += y;
+    ++d3_geo_centroidZ0;
+  }
+  function d3_geo_pathCentroidLineStart() {
+    var x0, y0;
+    d3_geo_pathCentroid.point = function(x, y) {
+      d3_geo_pathCentroid.point = nextPoint;
+      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
+    };
+    function nextPoint(x, y) {
+      var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
+      d3_geo_centroidX1 += z * (x0 + x) / 2;
+      d3_geo_centroidY1 += z * (y0 + y) / 2;
+      d3_geo_centroidZ1 += z;
+      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
+    }
+  }
+  function d3_geo_pathCentroidLineEnd() {
+    d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
+  }
+  function d3_geo_pathCentroidRingStart() {
+    var x00, y00, x0, y0;
+    d3_geo_pathCentroid.point = function(x, y) {
+      d3_geo_pathCentroid.point = nextPoint;
+      d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y);
+    };
+    function nextPoint(x, y) {
+      var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
+      d3_geo_centroidX1 += z * (x0 + x) / 2;
+      d3_geo_centroidY1 += z * (y0 + y) / 2;
+      d3_geo_centroidZ1 += z;
+      z = y0 * x - x0 * y;
+      d3_geo_centroidX2 += z * (x0 + x);
+      d3_geo_centroidY2 += z * (y0 + y);
+      d3_geo_centroidZ2 += z * 3;
+      d3_geo_pathCentroidPoint(x0 = x, y0 = y);
+    }
+    d3_geo_pathCentroid.lineEnd = function() {
+      nextPoint(x00, y00);
+    };
+  }
+  function d3_geo_pathContext(context) {
+    var pointRadius = 4.5;
+    var stream = {
+      point: point,
+      lineStart: function() {
+        stream.point = pointLineStart;
+      },
+      lineEnd: lineEnd,
+      polygonStart: function() {
+        stream.lineEnd = lineEndPolygon;
+      },
+      polygonEnd: function() {
+        stream.lineEnd = lineEnd;
+        stream.point = point;
+      },
+      pointRadius: function(_) {
+        pointRadius = _;
+        return stream;
+      },
+      result: d3_noop
+    };
+    function point(x, y) {
+      context.moveTo(x + pointRadius, y);
+      context.arc(x, y, pointRadius, 0, Ï);
+    }
+    function pointLineStart(x, y) {
+      context.moveTo(x, y);
+      stream.point = pointLine;
+    }
+    function pointLine(x, y) {
+      context.lineTo(x, y);
+    }
+    function lineEnd() {
+      stream.point = point;
+    }
+    function lineEndPolygon() {
+      context.closePath();
+    }
+    return stream;
+  }
+  function d3_geo_resample(project) {
+    var ÎŽ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16;
+    function resample(stream) {
+      return (maxDepth ? resampleRecursive : resampleNone)(stream);
+    }
+    function resampleNone(stream) {
+      return d3_geo_transformPoint(stream, function(x, y) {
+        x = project(x, y);
+        stream.point(x[0], x[1]);
+      });
+    }
+    function resampleRecursive(stream) {
+      var Î»00, Ï00, x00, y00, a00, b00, c00, Î»0, x0, y0, a0, b0, c0;
+      var resample = {
+        point: point,
+        lineStart: lineStart,
+        lineEnd: lineEnd,
+        polygonStart: function() {
+          stream.polygonStart();
+          resample.lineStart = ringStart;
+        },
+        polygonEnd: function() {
+          stream.polygonEnd();
+          resample.lineStart = lineStart;
+        }
+      };
+      function point(x, y) {
+        x = project(x, y);
+        stream.point(x[0], x[1]);
+      }
+      function lineStart() {
+        x0 = NaN;
+        resample.point = linePoint;
+        stream.lineStart();
+      }
+      function linePoint(Î», Ï) {
+        var c = d3_geo_cartesian([ Î», Ï ]), p = project(Î», Ï);
+        resampleLineTo(x0, y0, Î»0, a0, b0, c0, x0 = p[0], y0 = p[1], Î»0 = Î», a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);
+        stream.point(x0, y0);
+      }
+      function lineEnd() {
+        resample.point = point;
+        stream.lineEnd();
+      }
+      function ringStart() {
+        lineStart();
+        resample.point = ringPoint;
+        resample.lineEnd = ringEnd;
+      }
+      function ringPoint(Î», Ï) {
+        linePoint(Î»00 = Î», Ï00 = Ï), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;
+        resample.point = linePoint;
+      }
+      function ringEnd() {
+        resampleLineTo(x0, y0, Î»0, a0, b0, c0, x00, y00, Î»00, a00, b00, c00, maxDepth, stream);
+        resample.lineEnd = lineEnd;
+        lineEnd();
+      }
+      return resample;
+    }
+    function resampleLineTo(x0, y0, Î»0, a0, b0, c0, x1, y1, Î»1, a1, b1, c1, depth, stream) {
+      var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy;
+      if (d2 > 4 * ÎŽ2 && depth--) {
+        var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), Ï2 = Math.asin(c /= m), Î»2 = abs(abs(c) - 1) < Îµ || abs(Î»0 - Î»1) < Îµ ? (Î»0 + Î»1) / 2 : Math.atan2(b, a), p = project(Î»2, Ï2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2;
+        if (dz * dz / d2 > ÎŽ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) {
+          resampleLineTo(x0, y0, Î»0, a0, b0, c0, x2, y2, Î»2, a /= m, b /= m, c, depth, stream);
+          stream.point(x2, y2);
+          resampleLineTo(x2, y2, Î»2, a, b, c, x1, y1, Î»1, a1, b1, c1, depth, stream);
+        }
+      }
+    }
+    resample.precision = function(_) {
+      if (!arguments.length) return Math.sqrt(ÎŽ2);
+      maxDepth = (ÎŽ2 = _ * _) > 0 && 16;
+      return resample;
+    };
+    return resample;
+  }
+  d3.geo.path = function() {
+    var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream;
+    function path(object) {
+      if (object) {
+        if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
+        if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream);
+        d3.geo.stream(object, cacheStream);
+      }
+      return contextStream.result();
+    }
+    path.area = function(object) {
+      d3_geo_pathAreaSum = 0;
+      d3.geo.stream(object, projectStream(d3_geo_pathArea));
+      return d3_geo_pathAreaSum;
+    };
+    path.centroid = function(object) {
+      d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
+      d3.geo.stream(object, projectStream(d3_geo_pathCentroid));
+      return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ];
+    };
+    path.bounds = function(object) {
+      d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity);
+      d3.geo.stream(object, projectStream(d3_geo_pathBounds));
+      return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ];
+    };
+    path.projection = function(_) {
+      if (!arguments.length) return projection;
+      projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity;
+      return reset();
+    };
+    path.context = function(_) {
+      if (!arguments.length) return context;
+      contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_);
+      if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
+      return reset();
+    };
+    path.pointRadius = function(_) {
+      if (!arguments.length) return pointRadius;
+      pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
+      return path;
+    };
+    function reset() {
+      cacheStream = null;
+      return path;
+    }
+    return path.projection(d3.geo.albersUsa()).context(null);
+  };
+  function d3_geo_pathProjectStream(project) {
+    var resample = d3_geo_resample(function(x, y) {
+      return project([ x * d3_degrees, y * d3_degrees ]);
+    });
+    return function(stream) {
+      return d3_geo_projectionRadians(resample(stream));
+    };
+  }
+  d3.geo.transform = function(methods) {
+    return {
+      stream: function(stream) {
+        var transform = new d3_geo_transform(stream);
+        for (var k in methods) transform[k] = methods[k];
+        return transform;
+      }
+    };
+  };
+  function d3_geo_transform(stream) {
+    this.stream = stream;
+  }
+  d3_geo_transform.prototype = {
+    point: function(x, y) {
+      this.stream.point(x, y);
+    },
+    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();
+    }
+  };
+  function d3_geo_transformPoint(stream, point) {
+    return {
+      point: point,
+      sphere: function() {
+        stream.sphere();
+      },
+      lineStart: function() {
+        stream.lineStart();
+      },
+      lineEnd: function() {
+        stream.lineEnd();
+      },
+      polygonStart: function() {
+        stream.polygonStart();
+      },
+      polygonEnd: function() {
+        stream.polygonEnd();
+      }
+    };
+  }
+  d3.geo.projection = d3_geo_projection;
+  d3.geo.projectionMutator = d3_geo_projectionMutator;
+  function d3_geo_projection(project) {
+    return d3_geo_projectionMutator(function() {
+      return project;
+    })();
+  }
+  function d3_geo_projectionMutator(projectAt) {
+    var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) {
+      x = project(x, y);
+      return [ x[0] * k + ÎŽx, ÎŽy - x[1] * k ];
+    }), k = 150, x = 480, y = 250, Î» = 0, Ï = 0, ÎŽÎ» = 0, ÎŽÏ = 0, ÎŽÎ³ = 0, ÎŽx, ÎŽy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream;
+    function projection(point) {
+      point = projectRotate(point[0] * d3_radians, point[1] * d3_radians);
+      return [ point[0] * k + ÎŽx, ÎŽy - point[1] * k ];
+    }
+    function invert(point) {
+      point = projectRotate.invert((point[0] - ÎŽx) / k, (ÎŽy - point[1]) / k);
+      return point && [ point[0] * d3_degrees, point[1] * d3_degrees ];
+    }
+    projection.stream = function(output) {
+      if (stream) stream.valid = false;
+      stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output))));
+      stream.valid = true;
+      return stream;
+    };
+    projection.clipAngle = function(_) {
+      if (!arguments.length) return clipAngle;
+      preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians);
+      return invalidate();
+    };
+    projection.clipExtent = function(_) {
+      if (!arguments.length) return clipExtent;
+      clipExtent = _;
+      postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity;
+      return invalidate();
+    };
+    projection.scale = function(_) {
+      if (!arguments.length) return k;
+      k = +_;
+      return reset();
+    };
+    projection.translate = function(_) {
+      if (!arguments.length) return [ x, y ];
+      x = +_[0];
+      y = +_[1];
+      return reset();
+    };
+    projection.center = function(_) {
+      if (!arguments.length) return [ Î» * d3_degrees, Ï * d3_degrees ];
+      Î» = _[0] % 360 * d3_radians;
+      Ï = _[1] % 360 * d3_radians;
+      return reset();
+    };
+    projection.rotate = function(_) {
+      if (!arguments.length) return [ ÎŽÎ» * d3_degrees, ÎŽÏ * d3_degrees, ÎŽÎ³ * d3_degrees ];
+      ÎŽÎ» = _[0] % 360 * d3_radians;
+      ÎŽÏ = _[1] % 360 * d3_radians;
+      ÎŽÎ³ = _.length > 2 ? _[2] % 360 * d3_radians : 0;
+      return reset();
+    };
+    d3.rebind(projection, projectResample, "precision");
+    function reset() {
+      projectRotate = d3_geo_compose(rotate = d3_geo_rotation(ÎŽÎ», ÎŽÏ, ÎŽÎ³), project);
+      var center = project(Î», Ï);
+      ÎŽx = x - center[0] * k;
+      ÎŽy = y + center[1] * k;
+      return invalidate();
+    }
+    function invalidate() {
+      if (stream) stream.valid = false, stream = null;
+      return projection;
+    }
+    return function() {
+      project = projectAt.apply(this, arguments);
+      projection.invert = project.invert && invert;
+      return reset();
+    };
+  }
+  function d3_geo_projectionRadians(stream) {
+    return d3_geo_transformPoint(stream, function(x, y) {
+      stream.point(x * d3_radians, y * d3_radians);
+    });
+  }
+  function d3_geo_equirectangular(Î», Ï) {
+    return [ Î», Ï ];
+  }
+  (d3.geo.equirectangular = function() {
+    return d3_geo_projection(d3_geo_equirectangular);
+  }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular;
+  d3.geo.rotation = function(rotate) {
+    rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0);
+    function forward(coordinates) {
+      coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
+      return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
+    }
+    forward.invert = function(coordinates) {
+      coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
+      return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
+    };
+    return forward;
+  };
+  function d3_geo_identityRotation(Î», Ï) {
+    return [ Î» > Ï ? Î» - Ï : Î» < -Ï ? Î» + Ï : Î», Ï ];
+  }
+  d3_geo_identityRotation.invert = d3_geo_equirectangular;
+  function d3_geo_rotation(ÎŽÎ», ÎŽÏ, ÎŽÎ³) {
+    return ÎŽÎ» ? ÎŽÏ || ÎŽÎ³ ? d3_geo_compose(d3_geo_rotationÎ»(ÎŽÎ»), d3_geo_rotationÏÎ³(ÎŽÏ, ÎŽÎ³)) : d3_geo_rotationÎ»(ÎŽÎ») : ÎŽÏ || ÎŽÎ³ ? d3_geo_rotationÏÎ³(ÎŽÏ, ÎŽÎ³) : d3_geo_identityRotation;
+  }
+  function d3_geo_forwardRotationÎ»(ÎŽÎ») {
+    return function(Î», Ï) {
+      return Î» += ÎŽÎ», [ Î» > Ï ? Î» - Ï : Î» < -Ï ? Î» + Ï : Î», Ï ];
+    };
+  }
+  function d3_geo_rotationÎ»(ÎŽÎ») {
+    var rotation = d3_geo_forwardRotationÎ»(ÎŽÎ»);
+    rotation.invert = d3_geo_forwardRotationÎ»(-ÎŽÎ»);
+    return rotation;
+  }
+  function d3_geo_rotationÏÎ³(ÎŽÏ, ÎŽÎ³) {
+    var cosÎŽÏ = Math.cos(ÎŽÏ), sinÎŽÏ = Math.sin(ÎŽÏ), cosÎŽÎ³ = Math.cos(ÎŽÎ³), sinÎŽÎ³ = Math.sin(ÎŽÎ³);
+    function rotation(Î», Ï) {
+      var cosÏ = Math.cos(Ï), x = Math.cos(Î») * cosÏ, y = Math.sin(Î») * cosÏ, z = Math.sin(Ï), k = z * cosÎŽÏ + x * sinÎŽÏ;
+      return [ Math.atan2(y * cosÎŽÎ³ - k * sinÎŽÎ³, x * cosÎŽÏ - z * sinÎŽÏ), d3_asin(k * cosÎŽÎ³ + y * sinÎŽÎ³) ];
+    }
+    rotation.invert = function(Î», Ï) {
+      var cosÏ = Math.cos(Ï), x = Math.cos(Î») * cosÏ, y = Math.sin(Î») * cosÏ, z = Math.sin(Ï), k = z * cosÎŽÎ³ - y * sinÎŽÎ³;
+      return [ Math.atan2(y * cosÎŽÎ³ + z * sinÎŽÎ³, x * cosÎŽÏ + k * sinÎŽÏ), d3_asin(k * cosÎŽÏ - x * sinÎŽÏ) ];
+    };
+    return rotation;
+  }
+  d3.geo.circle = function() {
+    var origin = [ 0, 0 ], angle, precision = 6, interpolate;
+    function circle() {
+      var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = [];
+      interpolate(null, null, 1, {
+        point: function(x, y) {
+          ring.push(x = rotate(x, y));
+          x[0] *= d3_degrees, x[1] *= d3_degrees;
+        }
+      });
+      return {
+        type: "Polygon",
+        coordinates: [ ring ]
+      };
+    }
+    circle.origin = function(x) {
+      if (!arguments.length) return origin;
+      origin = x;
+      return circle;
+    };
+    circle.angle = function(x) {
+      if (!arguments.length) return angle;
+      interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians);
+      return circle;
+    };
+    circle.precision = function(_) {
+      if (!arguments.length) return precision;
+      interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians);
+      return circle;
+    };
+    return circle.angle(90);
+  };
+  function d3_geo_circleInterpolate(radius, precision) {
+    var cr = Math.cos(radius), sr = Math.sin(radius);
+    return function(from, to, direction, listener) {
+      var step = direction * precision;
+      if (from != null) {
+        from = d3_geo_circleAngle(cr, from);
+        to = d3_geo_circleAngle(cr, to);
+        if (direction > 0 ? from < to : from > to) from += direction * Ï;
+      } else {
+        from = radius + direction * Ï;
+        to = radius - .5 * step;
+      }
+      for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) {
+        listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]);
+      }
+    };
+  }
+  function d3_geo_circleAngle(cr, point) {
+    var a = d3_geo_cartesian(point);
+    a[0] -= cr;
+    d3_geo_cartesianNormalize(a);
+    var angle = d3_acos(-a[1]);
+    return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - Îµ) % (2 * Math.PI);
+  }
+  d3.geo.distance = function(a, b) {
+    var ÎÎ» = (b[0] - a[0]) * d3_radians, Ï0 = a[1] * d3_radians, Ï1 = b[1] * d3_radians, sinÎÎ» = Math.sin(ÎÎ»), cosÎÎ» = Math.cos(ÎÎ»), sinÏ0 = Math.sin(Ï0), cosÏ0 = Math.cos(Ï0), sinÏ1 = Math.sin(Ï1), cosÏ1 = Math.cos(Ï1), t;
+    return Math.atan2(Math.sqrt((t = cosÏ1 * sinÎÎ») * t + (t = cosÏ0 * sinÏ1 - sinÏ0 * cosÏ1 * cosÎÎ») * t), sinÏ0 * sinÏ1 + cosÏ0 * cosÏ1 * cosÎÎ»);
+  };
+  d3.geo.graticule = function() {
+    var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5;
+    function graticule() {
+      return {
+        type: "MultiLineString",
+        coordinates: lines()
+      };
+    }
+    function lines() {
+      return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) {
+        return abs(x % DX) > Îµ;
+      }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) {
+        return abs(y % DY) > Îµ;
+      }).map(y));
+    }
+    graticule.lines = function() {
+      return lines().map(function(coordinates) {
+        return {
+          type: "LineString",
+          coordinates: coordinates
+        };
+      });
+    };
+    graticule.outline = function() {
+      return {
+        type: "Polygon",
+        coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ]
+      };
+    };
+    graticule.extent = function(_) {
+      if (!arguments.length) return graticule.minorExtent();
+      return graticule.majorExtent(_).minorExtent(_);
+    };
+    graticule.majorExtent = function(_) {
+      if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ];
+      X0 = +_[0][0], X1 = +_[1][0];
+      Y0 = +_[0][1], Y1 = +_[1][1];
+      if (X0 > X1) _ = X0, X0 = X1, X1 = _;
+      if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;
+      return graticule.precision(precision);
+    };
+    graticule.minorExtent = function(_) {
+      if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
+      x0 = +_[0][0], x1 = +_[1][0];
+      y0 = +_[0][1], y1 = +_[1][1];
+      if (x0 > x1) _ = x0, x0 = x1, x1 = _;
+      if (y0 > y1) _ = y0, y0 = y1, y1 = _;
+      return graticule.precision(precision);
+    };
+    graticule.step = function(_) {
+      if (!arguments.length) return graticule.minorStep();
+      return graticule.majorStep(_).minorStep(_);
+    };
+    graticule.majorStep = function(_) {
+      if (!arguments.length) return [ DX, DY ];
+      DX = +_[0], DY = +_[1];
+      return graticule;
+    };
+    graticule.minorStep = function(_) {
+      if (!arguments.length) return [ dx, dy ];
+      dx = +_[0], dy = +_[1];
+      return graticule;
+    };
+    graticule.precision = function(_) {
+      if (!arguments.length) return precision;
+      precision = +_;
+      x = d3_geo_graticuleX(y0, y1, 90);
+      y = d3_geo_graticuleY(x0, x1, precision);
+      X = d3_geo_graticuleX(Y0, Y1, 90);
+      Y = d3_geo_graticuleY(X0, X1, precision);
+      return graticule;
+    };
+    return graticule.majorExtent([ [ -180, -90 + Îµ ], [ 180, 90 - Îµ ] ]).minorExtent([ [ -180, -80 - Îµ ], [ 180, 80 + Îµ ] ]);
+  };
+  function d3_geo_graticuleX(y0, y1, dy) {
+    var y = d3.range(y0, y1 - Îµ, dy).concat(y1);
+    return function(x) {
+      return y.map(function(y) {
+        return [ x, y ];
+      });
+    };
+  }
+  function d3_geo_graticuleY(x0, x1, dx) {
+    var x = d3.range(x0, x1 - Îµ, dx).concat(x1);
+    return function(y) {
+      return x.map(function(x) {
+        return [ x, y ];
+      });
+    };
+  }
+  function d3_source(d) {
+    return d.source;
+  }
+  function d3_target(d) {
+    return d.target;
+  }
+  d3.geo.greatArc = function() {
+    var source = d3_source, source_, target = d3_target, target_;
+    function greatArc() {
+      return {
+        type: "LineString",
+        coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ]
+      };
+    }
+    greatArc.distance = function() {
+      return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments));
+    };
+    greatArc.source = function(_) {
+      if (!arguments.length) return source;
+      source = _, source_ = typeof _ === "function" ? null : _;
+      return greatArc;
+    };
+    greatArc.target = function(_) {
+      if (!arguments.length) return target;
+      target = _, target_ = typeof _ === "function" ? null : _;
+      return greatArc;
+    };
+    greatArc.precision = function() {
+      return arguments.length ? greatArc : 0;
+    };
+    return greatArc;
+  };
+  d3.geo.interpolate = function(source, target) {
+    return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians);
+  };
+  function d3_geo_interpolate(x0, y0, x1, y1) {
+    var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d);
+    var interpolate = d ? function(t) {
+      var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1;
+      return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ];
+    } : function() {
+      return [ x0 * d3_degrees, y0 * d3_degrees ];
+    };
+    interpolate.distance = d;
+    return interpolate;
+  }
+  d3.geo.length = function(object) {
+    d3_geo_lengthSum = 0;
+    d3.geo.stream(object, d3_geo_length);
+    return d3_geo_lengthSum;
+  };
+  var d3_geo_lengthSum;
+  var d3_geo_length = {
+    sphere: d3_noop,
+    point: d3_noop,
+    lineStart: d3_geo_lengthLineStart,
+    lineEnd: d3_noop,
+    polygonStart: d3_noop,
+    polygonEnd: d3_noop
+  };
+  function d3_geo_lengthLineStart() {
+    var Î»0, sinÏ0, cosÏ0;
+    d3_geo_length.point = function(Î», Ï) {
+      Î»0 = Î» * d3_radians, sinÏ0 = Math.sin(Ï *= d3_radians), cosÏ0 = Math.cos(Ï);
+      d3_geo_length.point = nextPoint;
+    };
+    d3_geo_length.lineEnd = function() {
+      d3_geo_length.point = d3_geo_length.lineEnd = d3_noop;
+    };
+    function nextPoint(Î», Ï) {
+      var sinÏ = Math.sin(Ï *= d3_radians), cosÏ = Math.cos(Ï), t = abs((Î» *= d3_radians) - Î»0), cosÎÎ» = Math.cos(t);
+      d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosÏ * Math.sin(t)) * t + (t = cosÏ0 * sinÏ - sinÏ0 * cosÏ * cosÎÎ») * t), sinÏ0 * sinÏ + cosÏ0 * cosÏ * cosÎÎ»);
+      Î»0 = Î», sinÏ0 = sinÏ, cosÏ0 = cosÏ;
+    }
+  }
+  function d3_geo_azimuthal(scale, angle) {
+    function azimuthal(Î», Ï) {
+      var cosÎ» = Math.cos(Î»), cosÏ = Math.cos(Ï), k = scale(cosÎ» * cosÏ);
+      return [ k * cosÏ * Math.sin(Î»), k * Math.sin(Ï) ];
+    }
+    azimuthal.invert = function(x, y) {
+      var Ï = Math.sqrt(x * x + y * y), c = angle(Ï), sinc = Math.sin(c), cosc = Math.cos(c);
+      return [ Math.atan2(x * sinc, Ï * cosc), Math.asin(Ï && y * sinc / Ï) ];
+    };
+    return azimuthal;
+  }
+  var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosÎ»cosÏ) {
+    return Math.sqrt(2 / (1 + cosÎ»cosÏ));
+  }, function(Ï) {
+    return 2 * Math.asin(Ï / 2);
+  });
+  (d3.geo.azimuthalEqualArea = function() {
+    return d3_geo_projection(d3_geo_azimuthalEqualArea);
+  }).raw = d3_geo_azimuthalEqualArea;
+  var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosÎ»cosÏ) {
+    var c = Math.acos(cosÎ»cosÏ);
+    return c && c / Math.sin(c);
+  }, d3_identity);
+  (d3.geo.azimuthalEquidistant = function() {
+    return d3_geo_projection(d3_geo_azimuthalEquidistant);
+  }).raw = d3_geo_azimuthalEquidistant;
+  function d3_geo_conicConformal(Ï0, Ï1) {
+    var cosÏ0 = Math.cos(Ï0), t = function(Ï) {
+      return Math.tan(Ï / 4 + Ï / 2);
+    }, n = Ï0 === Ï1 ? Math.sin(Ï0) : Math.log(cosÏ0 / Math.cos(Ï1)) / Math.log(t(Ï1) / t(Ï0)), F = cosÏ0 * Math.pow(t(Ï0), n) / n;
+    if (!n) return d3_geo_mercator;
+    function forward(Î», Ï) {
+      if (F > 0) {
+        if (Ï < -halfÏ + Îµ) Ï = -halfÏ + Îµ;
+      } else {
+        if (Ï > halfÏ - Îµ) Ï = halfÏ - Îµ;
+      }
+      var Ï = F / Math.pow(t(Ï), n);
+      return [ Ï * Math.sin(n * Î»), F - Ï * Math.cos(n * Î») ];
+    }
+    forward.invert = function(x, y) {
+      var Ï0_y = F - y, Ï = d3_sgn(n) * Math.sqrt(x * x + Ï0_y * Ï0_y);
+      return [ Math.atan2(x, Ï0_y) / n, 2 * Math.atan(Math.pow(F / Ï, 1 / n)) - halfÏ ];
+    };
+    return forward;
+  }
+  (d3.geo.conicConformal = function() {
+    return d3_geo_conic(d3_geo_conicConformal);
+  }).raw = d3_geo_conicConformal;
+  function d3_geo_conicEquidistant(Ï0, Ï1) {
+    var cosÏ0 = Math.cos(Ï0), n = Ï0 === Ï1 ? Math.sin(Ï0) : (cosÏ0 - Math.cos(Ï1)) / (Ï1 - Ï0), G = cosÏ0 / n + Ï0;
+    if (abs(n) < Îµ) return d3_geo_equirectangular;
+    function forward(Î», Ï) {
+      var Ï = G - Ï;
+      return [ Ï * Math.sin(n * Î»), G - Ï * Math.cos(n * Î») ];
+    }
+    forward.invert = function(x, y) {
+      var Ï0_y = G - y;
+      return [ Math.atan2(x, Ï0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + Ï0_y * Ï0_y) ];
+    };
+    return forward;
+  }
+  (d3.geo.conicEquidistant = function() {
+    return d3_geo_conic(d3_geo_conicEquidistant);
+  }).raw = d3_geo_conicEquidistant;
+  var d3_geo_gnomonic = d3_geo_azimuthal(function(cosÎ»cosÏ) {
+    return 1 / cosÎ»cosÏ;
+  }, Math.atan);
+  (d3.geo.gnomonic = function() {
+    return d3_geo_projection(d3_geo_gnomonic);
+  }).raw = d3_geo_gnomonic;
+  function d3_geo_mercator(Î», Ï) {
+    return [ Î», Math.log(Math.tan(Ï / 4 + Ï / 2)) ];
+  }
+  d3_geo_mercator.invert = function(x, y) {
+    return [ x, 2 * Math.atan(Math.exp(y)) - halfÏ ];
+  };
+  function d3_geo_mercatorProjection(project) {
+    var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto;
+    m.scale = function() {
+      var v = scale.apply(m, arguments);
+      return v === m ? clipAuto ? m.clipExtent(null) : m : v;
+    };
+    m.translate = function() {
+      var v = translate.apply(m, arguments);
+      return v === m ? clipAuto ? m.clipExtent(null) : m : v;
+    };
+    m.clipExtent = function(_) {
+      var v = clipExtent.apply(m, arguments);
+      if (v === m) {
+        if (clipAuto = _ == null) {
+          var k = Ï * scale(), t = translate();
+          clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]);
+        }
+      } else if (clipAuto) {
+        v = null;
+      }
+      return v;
+    };
+    return m.clipExtent(null);
+  }
+  (d3.geo.mercator = function() {
+    return d3_geo_mercatorProjection(d3_geo_mercator);
+  }).raw = d3_geo_mercator;
+  var d3_geo_orthographic = d3_geo_azimuthal(function() {
+    return 1;
+  }, Math.asin);
+  (d3.geo.orthographic = function() {
+    return d3_geo_projection(d3_geo_orthographic);
+  }).raw = d3_geo_orthographic;
+  var d3_geo_stereographic = d3_geo_azimuthal(function(cosÎ»cosÏ) {
+    return 1 / (1 + cosÎ»cosÏ);
+  }, function(Ï) {
+    return 2 * Math.atan(Ï);
+  });
+  (d3.geo.stereographic = function() {
+    return d3_geo_projection(d3_geo_stereographic);
+  }).raw = d3_geo_stereographic;
+  function d3_geo_transverseMercator(Î», Ï) {
+    return [ Math.log(Math.tan(Ï / 4 + Ï / 2)), -Î» ];
+  }
+  d3_geo_transverseMercator.invert = function(x, y) {
+    return [ -y, 2 * Math.atan(Math.exp(x)) - halfÏ ];
+  };
+  (d3.geo.transverseMercator = function() {
+    var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate;
+    projection.center = function(_) {
+      return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]);
+    };
+    projection.rotate = function(_) {
+      return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(), 
+      [ _[0], _[1], _[2] - 90 ]);
+    };
+    return rotate([ 0, 0, 90 ]);
+  }).raw = d3_geo_transverseMercator;
+  d3.geom = {};
+  function d3_geom_pointX(d) {
+    return d[0];
+  }
+  function d3_geom_pointY(d) {
+    return d[1];
+  }
+  d3.geom.hull = function(vertices) {
+    var x = d3_geom_pointX, y = d3_geom_pointY;
+    if (arguments.length) return hull(vertices);
+    function hull(data) {
+      if (data.length < 3) return [];
+      var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = [];
+      for (i = 0; i < n; i++) {
+        points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]);
+      }
+      points.sort(d3_geom_hullOrder);
+      for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]);
+      var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints);
+      var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = [];
+      for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]);
+      for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]);
+      return polygon;
+    }
+    hull.x = function(_) {
+      return arguments.length ? (x = _, hull) : x;
+    };
+    hull.y = function(_) {
+      return arguments.length ? (y = _, hull) : y;
+    };
+    return hull;
+  };
+  function d3_geom_hullUpper(points) {
+    var n = points.length, hull = [ 0, 1 ], hs = 2;
+    for (var i = 2; i < n; i++) {
+      while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs;
+      hull[hs++] = i;
+    }
+    return hull.slice(0, hs);
+  }
+  function d3_geom_hullOrder(a, b) {
+    return a[0] - b[0] || a[1] - b[1];
+  }
+  d3.geom.polygon = function(coordinates) {
+    d3_subclass(coordinates, d3_geom_polygonPrototype);
+    return coordinates;
+  };
+  var d3_geom_polygonPrototype = d3.geom.polygon.prototype = [];
+  d3_geom_polygonPrototype.area = function() {
+    var i = -1, n = this.length, a, b = this[n - 1], area = 0;
+    while (++i < n) {
+      a = b;
+      b = this[i];
+      area += a[1] * b[0] - a[0] * b[1];
+    }
+    return area * .5;
+  };
+  d3_geom_polygonPrototype.centroid = function(k) {
+    var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c;
+    if (!arguments.length) k = -1 / (6 * this.area());
+    while (++i < n) {
+      a = b;
+      b = this[i];
+      c = a[0] * b[1] - b[0] * a[1];
+      x += (a[0] + b[0]) * c;
+      y += (a[1] + b[1]) * c;
+    }
+    return [ x * k, y * k ];
+  };
+  d3_geom_polygonPrototype.clip = function(subject) {
+    var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d;
+    while (++i < n) {
+      input = subject.slice();
+      subject.length = 0;
+      b = this[i];
+      c = input[(m = input.length - closed) - 1];
+      j = -1;
+      while (++j < m) {
+        d = input[j];
+        if (d3_geom_polygonInside(d, a, b)) {
+          if (!d3_geom_polygonInside(c, a, b)) {
+            subject.push(d3_geom_polygonIntersect(c, d, a, b));
+          }
+          subject.push(d);
+        } else if (d3_geom_polygonInside(c, a, b)) {
+          subject.push(d3_geom_polygonIntersect(c, d, a, b));
+        }
+        c = d;
+      }
+      if (closed) subject.push(subject[0]);
+      a = b;
+    }
+    return subject;
+  };
+  function d3_geom_polygonInside(p, a, b) {
+    return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
+  }
+  function d3_geom_polygonIntersect(c, d, a, b) {
+    var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
+    return [ x1 + ua * x21, y1 + ua * y21 ];
+  }
+  function d3_geom_polygonClosed(coordinates) {
+    var a = coordinates[0], b = coordinates[coordinates.length - 1];
+    return !(a[0] - b[0] || a[1] - b[1]);
+  }
+  var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = [];
+  function d3_geom_voronoiBeach() {
+    d3_geom_voronoiRedBlackNode(this);
+    this.edge = this.site = this.circle = null;
+  }
+  function d3_geom_voronoiCreateBeach(site) {
+    var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach();
+    beach.site = site;
+    return beach;
+  }
+  function d3_geom_voronoiDetachBeach(beach) {
+    d3_geom_voronoiDetachCircle(beach);
+    d3_geom_voronoiBeaches.remove(beach);
+    d3_geom_voronoiBeachPool.push(beach);
+    d3_geom_voronoiRedBlackNode(beach);
+  }
+  function d3_geom_voronoiRemoveBeach(beach) {
+    var circle = beach.circle, x = circle.x, y = circle.cy, vertex = {
+      x: x,
+      y: y
+    }, previous = beach.P, next = beach.N, disappearing = [ beach ];
+    d3_geom_voronoiDetachBeach(beach);
+    var lArc = previous;
+    while (lArc.circle && abs(x - lArc.circle.x) < Îµ && abs(y - lArc.circle.cy) < Îµ) {
+      previous = lArc.P;
+      disappearing.unshift(lArc);
+      d3_geom_voronoiDetachBeach(lArc);
+      lArc = previous;
+    }
+    disappearing.unshift(lArc);
+    d3_geom_voronoiDetachCircle(lArc);
+    var rArc = next;
+    while (rArc.circle && abs(x - rArc.circle.x) < Îµ && abs(y - rArc.circle.cy) < Îµ) {
+      next = rArc.N;
+      disappearing.push(rArc);
+      d3_geom_voronoiDetachBeach(rArc);
+      rArc = next;
+    }
+    disappearing.push(rArc);
+    d3_geom_voronoiDetachCircle(rArc);
+    var nArcs = disappearing.length, iArc;
+    for (iArc = 1; iArc < nArcs; ++iArc) {
+      rArc = disappearing[iArc];
+      lArc = disappearing[iArc - 1];
+      d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex);
+    }
+    lArc = disappearing[0];
+    rArc = disappearing[nArcs - 1];
+    rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex);
+    d3_geom_voronoiAttachCircle(lArc);
+    d3_geom_voronoiAttachCircle(rArc);
+  }
+  function d3_geom_voronoiAddBeach(site) {
+    var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._;
+    while (node) {
+      dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x;
+      if (dxl > Îµ) node = node.L; else {
+        dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix);
+        if (dxr > Îµ) {
+          if (!node.R) {
+            lArc = node;
+            break;
+          }
+          node = node.R;
+        } else {
+          if (dxl > -Îµ) {
+            lArc = node.P;
+            rArc = node;
+          } else if (dxr > -Îµ) {
+            lArc = node;
+            rArc = node.N;
+          } else {
+            lArc = rArc = node;
+          }
+          break;
+        }
+      }
+    }
+    var newArc = d3_geom_voronoiCreateBeach(site);
+    d3_geom_voronoiBeaches.insert(lArc, newArc);
+    if (!lArc && !rArc) return;
+    if (lArc === rArc) {
+      d3_geom_voronoiDetachCircle(lArc);
+      rArc = d3_geom_voronoiCreateBeach(lArc.site);
+      d3_geom_voronoiBeaches.insert(newArc, rArc);
+      newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
+      d3_geom_voronoiAttachCircle(lArc);
+      d3_geom_voronoiAttachCircle(rArc);
+      return;
+    }
+    if (!rArc) {
+      newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
+      return;
+    }
+    d3_geom_voronoiDetachCircle(lArc);
+    d3_geom_voronoiDetachCircle(rArc);
+    var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = {
+      x: (cy * hb - by * hc) / d + ax,
+      y: (bx * hc - cx * hb) / d + ay
+    };
+    d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex);
+    newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex);
+    rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex);
+    d3_geom_voronoiAttachCircle(lArc);
+    d3_geom_voronoiAttachCircle(rArc);
+  }
+  function d3_geom_voronoiLeftBreakPoint(arc, directrix) {
+    var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix;
+    if (!pby2) return rfocx;
+    var lArc = arc.P;
+    if (!lArc) return -Infinity;
+    site = lArc.site;
+    var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix;
+    if (!plby2) return lfocx;
+    var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2;
+    if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx;
+    return (rfocx + lfocx) / 2;
+  }
+  function d3_geom_voronoiRightBreakPoint(arc, directrix) {
+    var rArc = arc.N;
+    if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix);
+    var site = arc.site;
+    return site.y === directrix ? site.x : Infinity;
+  }
+  function d3_geom_voronoiCell(site) {
+    this.site = site;
+    this.edges = [];
+  }
+  d3_geom_voronoiCell.prototype.prepare = function() {
+    var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge;
+    while (iHalfEdge--) {
+      edge = halfEdges[iHalfEdge].edge;
+      if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1);
+    }
+    halfEdges.sort(d3_geom_voronoiHalfEdgeOrder);
+    return halfEdges.length;
+  };
+  function d3_geom_voronoiCloseCells(extent) {
+    var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end;
+    while (iCell--) {
+      cell = cells[iCell];
+      if (!cell || !cell.prepare()) continue;
+      halfEdges = cell.edges;
+      nHalfEdges = halfEdges.length;
+      iHalfEdge = 0;
+      while (iHalfEdge < nHalfEdges) {
+        end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y;
+        start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y;
+        if (abs(x3 - x2) > Îµ || abs(y3 - y2) > Îµ) {
+          halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < Îµ && y1 - y3 > Îµ ? {
+            x: x0,
+            y: abs(x2 - x0) < Îµ ? y2 : y1
+          } : abs(y3 - y1) < Îµ && x1 - x3 > Îµ ? {
+            x: abs(y2 - y1) < Îµ ? x2 : x1,
+            y: y1
+          } : abs(x3 - x1) < Îµ && y3 - y0 > Îµ ? {
+            x: x1,
+            y: abs(x2 - x1) < Îµ ? y2 : y0
+          } : abs(y3 - y0) < Îµ && x3 - x0 > Îµ ? {
+            x: abs(y2 - y0) < Îµ ? x2 : x0,
+            y: y0
+          } : null), cell.site, null));
+          ++nHalfEdges;
+        }
+      }
+    }
+  }
+  function d3_geom_voronoiHalfEdgeOrder(a, b) {
+    return b.angle - a.angle;
+  }
+  function d3_geom_voronoiCircle() {
+    d3_geom_voronoiRedBlackNode(this);
+    this.x = this.y = this.arc = this.site = this.cy = null;
+  }
+  function d3_geom_voronoiAttachCircle(arc) {
+    var lArc = arc.P, rArc = arc.N;
+    if (!lArc || !rArc) return;
+    var lSite = lArc.site, cSite = arc.site, rSite = rArc.site;
+    if (lSite === rSite) return;
+    var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by;
+    var d = 2 * (ax * cy - ay * cx);
+    if (d >= -Îµ2) return;
+    var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by;
+    var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle();
+    circle.arc = arc;
+    circle.site = cSite;
+    circle.x = x + bx;
+    circle.y = cy + Math.sqrt(x * x + y * y);
+    circle.cy = cy;
+    arc.circle = circle;
+    var before = null, node = d3_geom_voronoiCircles._;
+    while (node) {
+      if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) {
+        if (node.L) node = node.L; else {
+          before = node.P;
+          break;
+        }
+      } else {
+        if (node.R) node = node.R; else {
+          before = node;
+          break;
+        }
+      }
+    }
+    d3_geom_voronoiCircles.insert(before, circle);
+    if (!before) d3_geom_voronoiFirstCircle = circle;
+  }
+  function d3_geom_voronoiDetachCircle(arc) {
+    var circle = arc.circle;
+    if (circle) {
+      if (!circle.P) d3_geom_voronoiFirstCircle = circle.N;
+      d3_geom_voronoiCircles.remove(circle);
+      d3_geom_voronoiCirclePool.push(circle);
+      d3_geom_voronoiRedBlackNode(circle);
+      arc.circle = null;
+    }
+  }
+  function d3_geom_voronoiClipEdges(extent) {
+    var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e;
+    while (i--) {
+      e = edges[i];
+      if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < Îµ && abs(e.a.y - e.b.y) < Îµ) {
+        e.a = e.b = null;
+        edges.splice(i, 1);
+      }
+    }
+  }
+  function d3_geom_voronoiConnectEdge(edge, extent) {
+    var vb = edge.b;
+    if (vb) return true;
+    var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb;
+    if (ry === ly) {
+      if (fx < x0 || fx >= x1) return;
+      if (lx > rx) {
+        if (!va) va = {
+          x: fx,
+          y: y0
+        }; else if (va.y >= y1) return;
+        vb = {
+          x: fx,
+          y: y1
+        };
+      } else {
+        if (!va) va = {
+          x: fx,
+          y: y1
+        }; else if (va.y < y0) return;
+        vb = {
+          x: fx,
+          y: y0
+        };
+      }
+    } else {
+      fm = (lx - rx) / (ry - ly);
+      fb = fy - fm * fx;
+      if (fm < -1 || fm > 1) {
+        if (lx > rx) {
+          if (!va) va = {
+            x: (y0 - fb) / fm,
+            y: y0
+          }; else if (va.y >= y1) return;
+          vb = {
+            x: (y1 - fb) / fm,
+            y: y1
+          };
+        } else {
+          if (!va) va = {
+            x: (y1 - fb) / fm,
+            y: y1
+          }; else if (va.y < y0) return;
+          vb = {
+            x: (y0 - fb) / fm,
+            y: y0
+          };
+        }
+      } else {
+        if (ly < ry) {
+          if (!va) va = {
+            x: x0,
+            y: fm * x0 + fb
+          }; else if (va.x >= x1) return;
+          vb = {
+            x: x1,
+            y: fm * x1 + fb
+          };
+        } else {
+          if (!va) va = {
+            x: x1,
+            y: fm * x1 + fb
+          }; else if (va.x < x0) return;
+          vb = {
+            x: x0,
+            y: fm * x0 + fb
+          };
+        }
+      }
+    }
+    edge.a = va;
+    edge.b = vb;
+    return true;
+  }
+  function d3_geom_voronoiEdge(lSite, rSite) {
+    this.l = lSite;
+    this.r = rSite;
+    this.a = this.b = null;
+  }
+  function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) {
+    var edge = new d3_geom_voronoiEdge(lSite, rSite);
+    d3_geom_voronoiEdges.push(edge);
+    if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va);
+    if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb);
+    d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite));
+    d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite));
+    return edge;
+  }
+  function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) {
+    var edge = new d3_geom_voronoiEdge(lSite, null);
+    edge.a = va;
+    edge.b = vb;
+    d3_geom_voronoiEdges.push(edge);
+    return edge;
+  }
+  function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) {
+    if (!edge.a && !edge.b) {
+      edge.a = vertex;
+      edge.l = lSite;
+      edge.r = rSite;
+    } else if (edge.l === rSite) {
+      edge.b = vertex;
+    } else {
+      edge.a = vertex;
+    }
+  }
+  function d3_geom_voronoiHalfEdge(edge, lSite, rSite) {
+    var va = edge.a, vb = edge.b;
+    this.edge = edge;
+    this.site = lSite;
+    this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y);
+  }
+  d3_geom_voronoiHalfEdge.prototype = {
+    start: function() {
+      return this.edge.l === this.site ? this.edge.a : this.edge.b;
+    },
+    end: function() {
+      return this.edge.l === this.site ? this.edge.b : this.edge.a;
+    }
+  };
+  function d3_geom_voronoiRedBlackTree() {
+    this._ = null;
+  }
+  function d3_geom_voronoiRedBlackNode(node) {
+    node.U = node.C = node.L = node.R = node.P = node.N = null;
+  }
+  d3_geom_voronoiRedBlackTree.prototype = {
+    insert: function(after, node) {
+      var parent, grandpa, uncle;
+      if (after) {
+        node.P = after;
+        node.N = after.N;
+        if (after.N) after.N.P = node;
+        after.N = node;
+        if (after.R) {
+          after = after.R;
+          while (after.L) after = after.L;
+          after.L = node;
+        } else {
+          after.R = node;
+        }
+        parent = after;
+      } else if (this._) {
+        after = d3_geom_voronoiRedBlackFirst(this._);
+        node.P = null;
+        node.N = after;
+        after.P = after.L = node;
+        parent = after;
+      } else {
+        node.P = node.N = null;
+        this._ = node;
+        parent = null;
+      }
+      node.L = node.R = null;
+      node.U = parent;
+      node.C = true;
+      after = node;
+      while (parent && parent.C) {
+        grandpa = parent.U;
+        if (parent === grandpa.L) {
+          uncle = grandpa.R;
+          if (uncle && uncle.C) {
+            parent.C = uncle.C = false;
+            grandpa.C = true;
+            after = grandpa;
+          } else {
+            if (after === parent.R) {
+              d3_geom_voronoiRedBlackRotateLeft(this, parent);
+              after = parent;
+              parent = after.U;
+            }
+            parent.C = false;
+            grandpa.C = true;
+            d3_geom_voronoiRedBlackRotateRight(this, grandpa);
+          }
+        } else {
+          uncle = grandpa.L;
+          if (uncle && uncle.C) {
+            parent.C = uncle.C = false;
+            grandpa.C = true;
+            after = grandpa;
+          } else {
+            if (after === parent.L) {
+              d3_geom_voronoiRedBlackRotateRight(this, parent);
+              after = parent;
+              parent = after.U;
+            }
+            parent.C = false;
+            grandpa.C = true;
+            d3_geom_voronoiRedBlackRotateLeft(this, grandpa);
+          }
+        }
+        parent = after.U;
+      }
+      this._.C = false;
+    },
+    remove: function(node) {
+      if (node.N) node.N.P = node.P;
+      if (node.P) node.P.N = node.N;
+      node.N = node.P = null;
+      var parent = node.U, sibling, left = node.L, right = node.R, next, red;
+      if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right);
+      if (parent) {
+        if (parent.L === node) parent.L = next; else parent.R = next;
+      } else {
+        this._ = next;
+      }
+      if (left && right) {
+        red = next.C;
+        next.C = node.C;
+        next.L = left;
+        left.U = next;
+        if (next !== right) {
+          parent = next.U;
+          next.U = node.U;
+          node = next.R;
+          parent.L = node;
+          next.R = right;
+          right.U = next;
+        } else {
+          next.U = parent;
+          parent = next;
+          node = next.R;
+        }
+      } else {
+        red = node.C;
+        node = next;
+      }
+      if (node) node.U = parent;
+      if (red) return;
+      if (node && node.C) {
+        node.C = false;
+        return;
+      }
+      do {
+        if (node === this._) break;
+        if (node === parent.L) {
+          sibling = parent.R;
+          if (sibling.C) {
+            sibling.C = false;
+            parent.C = true;
+            d3_geom_voronoiRedBlackRotateLeft(this, parent);
+            sibling = parent.R;
+          }
+          if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
+            if (!sibling.R || !sibling.R.C) {
+              sibling.L.C = false;
+              sibling.C = true;
+              d3_geom_voronoiRedBlackRotateRight(this, sibling);
+              sibling = parent.R;
+            }
+            sibling.C = parent.C;
+            parent.C = sibling.R.C = false;
+            d3_geom_voronoiRedBlackRotateLeft(this, parent);
+            node = this._;
+            break;
+          }
+        } else {
+          sibling = parent.L;
+          if (sibling.C) {
+            sibling.C = false;
+            parent.C = true;
+            d3_geom_voronoiRedBlackRotateRight(this, parent);
+            sibling = parent.L;
+          }
+          if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
+            if (!sibling.L || !sibling.L.C) {
+              sibling.R.C = false;
+              sibling.C = true;
+              d3_geom_voronoiRedBlackRotateLeft(this, sibling);
+              sibling = parent.L;
+            }
+            sibling.C = parent.C;
+            parent.C = sibling.L.C = false;
+            d3_geom_voronoiRedBlackRotateRight(this, parent);
+            node = this._;
+            break;
+          }
+        }
+        sibling.C = true;
+        node = parent;
+        parent = parent.U;
+      } while (!node.C);
+      if (node) node.C = false;
+    }
+  };
+  function d3_geom_voronoiRedBlackRotateLeft(tree, node) {
+    var p = node, q = node.R, parent = p.U;
+    if (parent) {
+      if (parent.L === p) parent.L = q; else parent.R = q;
+    } else {
+      tree._ = q;
+    }
+    q.U = parent;
+    p.U = q;
+    p.R = q.L;
+    if (p.R) p.R.U = p;
+    q.L = p;
+  }
+  function d3_geom_voronoiRedBlackRotateRight(tree, node) {
+    var p = node, q = node.L, parent = p.U;
+    if (parent) {
+      if (parent.L === p) parent.L = q; else parent.R = q;
+    } else {
+      tree._ = q;
+    }
+    q.U = parent;
+    p.U = q;
+    p.L = q.R;
+    if (p.L) p.L.U = p;
+    q.R = p;
+  }
+  function d3_geom_voronoiRedBlackFirst(node) {
+    while (node.L) node = node.L;
+    return node;
+  }
+  function d3_geom_voronoi(sites, bbox) {
+    var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle;
+    d3_geom_voronoiEdges = [];
+    d3_geom_voronoiCells = new Array(sites.length);
+    d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree();
+    d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree();
+    while (true) {
+      circle = d3_geom_voronoiFirstCircle;
+      if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) {
+        if (site.x !== x0 || site.y !== y0) {
+          d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site);
+          d3_geom_voronoiAddBeach(site);
+          x0 = site.x, y0 = site.y;
+        }
+        site = sites.pop();
+      } else if (circle) {
+        d3_geom_voronoiRemoveBeach(circle.arc);
+      } else {
+        break;
+      }
+    }
+    if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox);
+    var diagram = {
+      cells: d3_geom_voronoiCells,
+      edges: d3_geom_voronoiEdges
+    };
+    d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null;
+    return diagram;
+  }
+  function d3_geom_voronoiVertexOrder(a, b) {
+    return b.y - a.y || b.x - a.x;
+  }
+  d3.geom.voronoi = function(points) {
+    var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent;
+    if (points) return voronoi(points);
+    function voronoi(data) {
+      var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1];
+      d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) {
+        var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) {
+          var s = e.start();
+          return [ s.x, s.y ];
+        }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : [];
+        polygon.point = data[i];
+      });
+      return polygons;
+    }
+    function sites(data) {
+      return data.map(function(d, i) {
+        return {
+          x: Math.round(fx(d, i) / Îµ) * Îµ,
+          y: Math.round(fy(d, i) / Îµ) * Îµ,
+          i: i
+        };
+      });
+    }
+    voronoi.links = function(data) {
+      return d3_geom_voronoi(sites(data)).edges.filter(function(edge) {
+        return edge.l && edge.r;
+      }).map(function(edge) {
+        return {
+          source: data[edge.l.i],
+          target: data[edge.r.i]
+        };
+      });
+    };
+    voronoi.triangles = function(data) {
+      var triangles = [];
+      d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) {
+        var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l;
+        while (++j < m) {
+          e0 = e1;
+          s0 = s1;
+          e1 = edges[j].edge;
+          s1 = e1.l === site ? e1.r : e1.l;
+          if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) {
+            triangles.push([ data[i], data[s0.i], data[s1.i] ]);
+          }
+        }
+      });
+      return triangles;
+    };
+    voronoi.x = function(_) {
+      return arguments.length ? (fx = d3_functor(x = _), voronoi) : x;
+    };
+    voronoi.y = function(_) {
+      return arguments.length ? (fy = d3_functor(y = _), voronoi) : y;
+    };
+    voronoi.clipExtent = function(_) {
+      if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent;
+      clipExtent = _ == null ? d3_geom_voronoiClipExtent : _;
+      return voronoi;
+    };
+    voronoi.size = function(_) {
+      if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1];
+      return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]);
+    };
+    return voronoi;
+  };
+  var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ];
+  function d3_geom_voronoiTriangleArea(a, b, c) {
+    return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y);
+  }
+  d3.geom.delaunay = function(vertices) {
+    return d3.geom.voronoi().triangles(vertices);
+  };
+  d3.geom.quadtree = function(points, x1, y1, x2, y2) {
+    var x = d3_geom_pointX, y = d3_geom_pointY, compat;
+    if (compat = arguments.length) {
+      x = d3_geom_quadtreeCompatX;
+      y = d3_geom_quadtreeCompatY;
+      if (compat === 3) {
+        y2 = y1;
+        x2 = x1;
+        y1 = x1 = 0;
+      }
+      return quadtree(points);
+    }
+    function quadtree(data) {
+      var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_;
+      if (x1 != null) {
+        x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2;
+      } else {
+        x2_ = y2_ = -(x1_ = y1_ = Infinity);
+        xs = [], ys = [];
+        n = data.length;
+        if (compat) for (i = 0; i < n; ++i) {
+          d = data[i];
+          if (d.x < x1_) x1_ = d.x;
+          if (d.y < y1_) y1_ = d.y;
+          if (d.x > x2_) x2_ = d.x;
+          if (d.y > y2_) y2_ = d.y;
+          xs.push(d.x);
+          ys.push(d.y);
+        } else for (i = 0; i < n; ++i) {
+          var x_ = +fx(d = data[i], i), y_ = +fy(d, i);
+          if (x_ < x1_) x1_ = x_;
+          if (y_ < y1_) y1_ = y_;
+          if (x_ > x2_) x2_ = x_;
+          if (y_ > y2_) y2_ = y_;
+          xs.push(x_);
+          ys.push(y_);
+        }
+      }
+      var dx = x2_ - x1_, dy = y2_ - y1_;
+      if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy;
+      function insert(n, d, x, y, x1, y1, x2, y2) {
+        if (isNaN(x) || isNaN(y)) return;
+        if (n.leaf) {
+          var nx = n.x, ny = n.y;
+          if (nx != null) {
+            if (abs(nx - x) + abs(ny - y) < .01) {
+              insertChild(n, d, x, y, x1, y1, x2, y2);
+            } else {
+              var nPoint = n.point;
+              n.x = n.y = n.point = null;
+              insertChild(n, nPoint, nx, ny, x1, y1, x2, y2);
+              insertChild(n, d, x, y, x1, y1, x2, y2);
+            }
+          } else {
+            n.x = x, n.y = y, n.point = d;
+          }
+        } else {
+          insertChild(n, d, x, y, x1, y1, x2, y2);
+        }
+      }
+      function insertChild(n, d, x, y, x1, y1, x2, y2) {
+        var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right;
+        n.leaf = false;
+        n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode());
+        if (right) x1 = xm; else x2 = xm;
+        if (below) y1 = ym; else y2 = ym;
+        insert(n, d, x, y, x1, y1, x2, y2);
+      }
+      var root = d3_geom_quadtreeNode();
+      root.add = function(d) {
+        insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_);
+      };
+      root.visit = function(f) {
+        d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_);
+      };
+      root.find = function(point) {
+        return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_);
+      };
+      i = -1;
+      if (x1 == null) {
+        while (++i < n) {
+          insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_);
+        }
+        --i;
+      } else data.forEach(root.add);
+      xs = ys = data = d = null;
+      return root;
+    }
+    quadtree.x = function(_) {
+      return arguments.length ? (x = _, quadtree) : x;
+    };
+    quadtree.y = function(_) {
+      return arguments.length ? (y = _, quadtree) : y;
+    };
+    quadtree.extent = function(_) {
+      if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ];
+      if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0], 
+      y2 = +_[1][1];
+      return quadtree;
+    };
+    quadtree.size = function(_) {
+      if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ];
+      if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1];
+      return quadtree;
+    };
+    return quadtree;
+  };
+  function d3_geom_quadtreeCompatX(d) {
+    return d.x;
+  }
+  function d3_geom_quadtreeCompatY(d) {
+    return d.y;
+  }
+  function d3_geom_quadtreeNode() {
+    return {
+      leaf: true,
+      nodes: [],
+      point: null,
+      x: null,
+      y: null
+    };
+  }
+  function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) {
+    if (!f(node, x1, y1, x2, y2)) {
+      var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes;
+      if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy);
+      if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy);
+      if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2);
+      if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2);
+    }
+  }
+  function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) {
+    var minDistance2 = Infinity, closestPoint;
+    (function find(node, x1, y1, x2, y2) {
+      if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return;
+      if (point = node.point) {
+        var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy;
+        if (distance2 < minDistance2) {
+          var distance = Math.sqrt(minDistance2 = distance2);
+          x0 = x - distance, y0 = y - distance;
+          x3 = x + distance, y3 = y + distance;
+          closestPoint = point;
+        }
+      }
+      var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym;
+      for (var i = below << 1 | right, j = i + 4; i < j; ++i) {
+        if (node = children[i & 3]) switch (i & 3) {
+         case 0:
+          find(node, x1, y1, xm, ym);
+          break;
+
+         case 1:
+          find(node, xm, y1, x2, ym);
+          break;
+
+         case 2:
+          find(node, x1, ym, xm, y2);
+          break;
+
+         case 3:
+          find(node, xm, ym, x2, y2);
+          break;
+        }
+      }
+    })(root, x0, y0, x3, y3);
+    return closestPoint;
+  }
+  d3.interpolateRgb = d3_interpolateRgb;
+  function d3_interpolateRgb(a, b) {
+    a = d3.rgb(a);
+    b = d3.rgb(b);
+    var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab;
+    return function(t) {
+      return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t));
+    };
+  }
+  d3.interpolateObject = d3_interpolateObject;
+  function d3_interpolateObject(a, b) {
+    var i = {}, c = {}, k;
+    for (k in a) {
+      if (k in b) {
+        i[k] = d3_interpolate(a[k], b[k]);
+      } else {
+        c[k] = a[k];
+      }
+    }
+    for (k in b) {
+      if (!(k in a)) {
+        c[k] = b[k];
+      }
+    }
+    return function(t) {
+      for (k in i) c[k] = i[k](t);
+      return c;
+    };
+  }
+  d3.interpolateNumber = d3_interpolateNumber;
+  function d3_interpolateNumber(a, b) {
+    a = +a, b = +b;
+    return function(t) {
+      return a * (1 - t) + b * t;
+    };
+  }
+  d3.interpolateString = d3_interpolateString;
+  function d3_interpolateString(a, b) {
+    var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
+    a = a + "", b = b + "";
+    while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) {
+      if ((bs = bm.index) > bi) {
+        bs = b.slice(bi, bs);
+        if (s[i]) s[i] += bs; else s[++i] = bs;
+      }
+      if ((am = am[0]) === (bm = bm[0])) {
+        if (s[i]) s[i] += bm; else s[++i] = bm;
+      } else {
+        s[++i] = null;
+        q.push({
+          i: i,
+          x: d3_interpolateNumber(am, bm)
+        });
+      }
+      bi = d3_interpolate_numberB.lastIndex;
+    }
+    if (bi < b.length) {
+      bs = b.slice(bi);
+      if (s[i]) s[i] += bs; else s[++i] = bs;
+    }
+    return s.length < 2 ? q[0] ? (b = q[0].x, function(t) {
+      return b(t) + "";
+    }) : function() {
+      return b;
+    } : (b = q.length, function(t) {
+      for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
+      return s.join("");
+    });
+  }
+  var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g");
+  d3.interpolate = d3_interpolate;
+  function d3_interpolate(a, b) {
+    var i = d3.interpolators.length, f;
+    while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ;
+    return f;
+  }
+  d3.interpolators = [ function(a, b) {
+    var t = typeof b;
+    return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b);
+  } ];
+  d3.interpolateArray = d3_interpolateArray;
+  function d3_interpolateArray(a, b) {
+    var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i;
+    for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i]));
+    for (;i < na; ++i) c[i] = a[i];
+    for (;i < nb; ++i) c[i] = b[i];
+    return function(t) {
+      for (i = 0; i < n0; ++i) c[i] = x[i](t);
+      return c;
+    };
+  }
+  var d3_ease_default = function() {
+    return d3_identity;
+  };
+  var d3_ease = d3.map({
+    linear: d3_ease_default,
+    poly: d3_ease_poly,
+    quad: function() {
+      return d3_ease_quad;
+    },
+    cubic: function() {
+      return d3_ease_cubic;
+    },
+    sin: function() {
+      return d3_ease_sin;
+    },
+    exp: function() {
+      return d3_ease_exp;
+    },
+    circle: function() {
+      return d3_ease_circle;
+    },
+    elastic: d3_ease_elastic,
+    back: d3_ease_back,
+    bounce: function() {
+      return d3_ease_bounce;
+    }
+  });
+  var d3_ease_mode = d3.map({
+    "in": d3_identity,
+    out: d3_ease_reverse,
+    "in-out": d3_ease_reflect,
+    "out-in": function(f) {
+      return d3_ease_reflect(d3_ease_reverse(f));
+    }
+  });
+  d3.ease = function(name) {
+    var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in";
+    t = d3_ease.get(t) || d3_ease_default;
+    m = d3_ease_mode.get(m) || d3_identity;
+    return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1))));
+  };
+  function d3_ease_clamp(f) {
+    return function(t) {
+      return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
+    };
+  }
+  function d3_ease_reverse(f) {
+    return function(t) {
+      return 1 - f(1 - t);
+    };
+  }
+  function d3_ease_reflect(f) {
+    return function(t) {
+      return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t));
+    };
+  }
+  function d3_ease_quad(t) {
+    return t * t;
+  }
+  function d3_ease_cubic(t) {
+    return t * t * t;
+  }
+  function d3_ease_cubicInOut(t) {
+    if (t <= 0) return 0;
+    if (t >= 1) return 1;
+    var t2 = t * t, t3 = t2 * t;
+    return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
+  }
+  function d3_ease_poly(e) {
+    return function(t) {
+      return Math.pow(t, e);
+    };
+  }
+  function d3_ease_sin(t) {
+    return 1 - Math.cos(t * halfÏ);
+  }
+  function d3_ease_exp(t) {
+    return Math.pow(2, 10 * (t - 1));
+  }
+  function d3_ease_circle(t) {
+    return 1 - Math.sqrt(1 - t * t);
+  }
+  function d3_ease_elastic(a, p) {
+    var s;
+    if (arguments.length < 2) p = .45;
+    if (arguments.length) s = p / Ï * Math.asin(1 / a); else a = 1, s = p / 4;
+    return function(t) {
+      return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * Ï / p);
+    };
+  }
+  function d3_ease_back(s) {
+    if (!s) s = 1.70158;
+    return function(t) {
+      return t * t * ((s + 1) * t - s);
+    };
+  }
+  function d3_ease_bounce(t) {
+    return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
+  }
+  d3.interpolateHcl = d3_interpolateHcl;
+  function d3_interpolateHcl(a, b) {
+    a = d3.hcl(a);
+    b = d3.hcl(b);
+    var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al;
+    if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac;
+    if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
+    return function(t) {
+      return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + "";
+    };
+  }
+  d3.interpolateHsl = d3_interpolateHsl;
+  function d3_interpolateHsl(a, b) {
+    a = d3.hsl(a);
+    b = d3.hsl(b);
+    var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al;
+    if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as;
+    if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
+    return function(t) {
+      return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + "";
+    };
+  }
+  d3.interpolateLab = d3_interpolateLab;
+  function d3_interpolateLab(a, b) {
+    a = d3.lab(a);
+    b = d3.lab(b);
+    var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab;
+    return function(t) {
+      return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + "";
+    };
+  }
+  d3.interpolateRound = d3_interpolateRound;
+  function d3_interpolateRound(a, b) {
+    b -= a;
+    return function(t) {
+      return Math.round(a + b * t);
+    };
+  }
+  d3.transform = function(string) {
+    var g = d3_document.createElementNS(d3.ns.prefix.svg, "g");
+    return (d3.transform = function(string) {
+      if (string != null) {
+        g.setAttribute("transform", string);
+        var t = g.transform.baseVal.consolidate();
+      }
+      return new d3_transform(t ? t.matrix : d3_transformIdentity);
+    })(string);
+  };
+  function d3_transform(m) {
+    var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0;
+    if (r0[0] * r1[1] < r1[0] * r0[1]) {
+      r0[0] *= -1;
+      r0[1] *= -1;
+      kx *= -1;
+      kz *= -1;
+    }
+    this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees;
+    this.translate = [ m.e, m.f ];
+    this.scale = [ kx, ky ];
+    this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0;
+  }
+  d3_transform.prototype.toString = function() {
+    return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")";
+  };
+  function d3_transformDot(a, b) {
+    return a[0] * b[0] + a[1] * b[1];
+  }
+  function d3_transformNormalize(a) {
+    var k = Math.sqrt(d3_transformDot(a, a));
+    if (k) {
+      a[0] /= k;
+      a[1] /= k;
+    }
+    return k;
+  }
+  function d3_transformCombine(a, b, k) {
+    a[0] += k * b[0];
+    a[1] += k * b[1];
+    return a;
+  }
+  var d3_transformIdentity = {
+    a: 1,
+    b: 0,
+    c: 0,
+    d: 1,
+    e: 0,
+    f: 0
+  };
+  d3.interpolateTransform = d3_interpolateTransform;
+  function d3_interpolateTransformPop(s) {
+    return s.length ? s.pop() + "," : "";
+  }
+  function d3_interpolateTranslate(ta, tb, s, q) {
+    if (ta[0] !== tb[0] || ta[1] !== tb[1]) {
+      var i = s.push("translate(", null, ",", null, ")");
+      q.push({
+        i: i - 4,
+        x: d3_interpolateNumber(ta[0], tb[0])
+      }, {
+        i: i - 2,
+        x: d3_interpolateNumber(ta[1], tb[1])
+      });
+    } else if (tb[0] || tb[1]) {
+      s.push("translate(" + tb + ")");
+    }
+  }
+  function d3_interpolateRotate(ra, rb, s, q) {
+    if (ra !== rb) {
+      if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360;
+      q.push({
+        i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2,
+        x: d3_interpolateNumber(ra, rb)
+      });
+    } else if (rb) {
+      s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")");
+    }
+  }
+  function d3_interpolateSkew(wa, wb, s, q) {
+    if (wa !== wb) {
+      q.push({
+        i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2,
+        x: d3_interpolateNumber(wa, wb)
+      });
+    } else if (wb) {
+      s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")");
+    }
+  }
+  function d3_interpolateScale(ka, kb, s, q) {
+    if (ka[0] !== kb[0] || ka[1] !== kb[1]) {
+      var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")");
+      q.push({
+        i: i - 4,
+        x: d3_interpolateNumber(ka[0], kb[0])
+      }, {
+        i: i - 2,
+        x: d3_interpolateNumber(ka[1], kb[1])
+      });
+    } else if (kb[0] !== 1 || kb[1] !== 1) {
+      s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")");
+    }
+  }
+  function d3_interpolateTransform(a, b) {
+    var s = [], q = [];
+    a = d3.transform(a), b = d3.transform(b);
+    d3_interpolateTranslate(a.translate, b.translate, s, q);
+    d3_interpolateRotate(a.rotate, b.rotate, s, q);
+    d3_interpolateSkew(a.skew, b.skew, s, q);
+    d3_interpolateScale(a.scale, b.scale, s, q);
+    a = b = null;
+    return function(t) {
+      var i = -1, n = q.length, o;
+      while (++i < n) s[(o = q[i]).i] = o.x(t);
+      return s.join("");
+    };
+  }
+  function d3_uninterpolateNumber(a, b) {
+    b = (b -= a = +a) || 1 / b;
+    return function(x) {
+      return (x - a) / b;
+    };
+  }
+  function d3_uninterpolateClamp(a, b) {
+    b = (b -= a = +a) || 1 / b;
+    return function(x) {
+      return Math.max(0, Math.min(1, (x - a) / b));
+    };
+  }
+  d3.layout = {};
+  d3.layout.bundle = function() {
+    return function(links) {
+      var paths = [], i = -1, n = links.length;
+      while (++i < n) paths.push(d3_layout_bundlePath(links[i]));
+      return paths;
+    };
+  };
+  function d3_layout_bundlePath(link) {
+    var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ];
+    while (start !== lca) {
+      start = start.parent;
+      points.push(start);
+    }
+    var k = points.length;
+    while (end !== lca) {
+      points.splice(k, 0, end);
+      end = end.parent;
+    }
+    return points;
+  }
+  function d3_layout_bundleAncestors(node) {
+    var ancestors = [], parent = node.parent;
+    while (parent != null) {
+      ancestors.push(node);
+      node = parent;
+      parent = parent.parent;
+    }
+    ancestors.push(node);
+    return ancestors;
+  }
+  function d3_layout_bundleLeastCommonAncestor(a, b) {
+    if (a === b) return a;
+    var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null;
+    while (aNode === bNode) {
+      sharedNode = aNode;
+      aNode = aNodes.pop();
+      bNode = bNodes.pop();
+    }
+    return sharedNode;
+  }
+  d3.layout.chord = function() {
+    var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords;
+    function relayout() {
+      var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j;
+      chords = [];
+      groups = [];
+      k = 0, i = -1;
+      while (++i < n) {
+        x = 0, j = -1;
+        while (++j < n) {
+          x += matrix[i][j];
+        }
+        groupSums.push(x);
+        subgroupIndex.push(d3.range(n));
+        k += x;
+      }
+      if (sortGroups) {
+        groupIndex.sort(function(a, b) {
+          return sortGroups(groupSums[a], groupSums[b]);
+        });
+      }
+      if (sortSubgroups) {
+        subgroupIndex.forEach(function(d, i) {
+          d.sort(function(a, b) {
+            return sortSubgroups(matrix[i][a], matrix[i][b]);
+          });
+        });
+      }
+      k = (Ï - padding * n) / k;
+      x = 0, i = -1;
+      while (++i < n) {
+        x0 = x, j = -1;
+        while (++j < n) {
+          var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k;
+          subgroups[di + "-" + dj] = {
+            index: di,
+            subindex: dj,
+            startAngle: a0,
+            endAngle: a1,
+            value: v
+          };
+        }
+        groups[di] = {
+          index: di,
+          startAngle: x0,
+          endAngle: x,
+          value: groupSums[di]
+        };
+        x += padding;
+      }
+      i = -1;
+      while (++i < n) {
+        j = i - 1;
+        while (++j < n) {
+          var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i];
+          if (source.value || target.value) {
+            chords.push(source.value < target.value ? {
+              source: target,
+              target: source
+            } : {
+              source: source,
+              target: target
+            });
+          }
+        }
+      }
+      if (sortChords) resort();
+    }
+    function resort() {
+      chords.sort(function(a, b) {
+        return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2);
+      });
+    }
+    chord.matrix = function(x) {
+      if (!arguments.length) return matrix;
+      n = (matrix = x) && matrix.length;
+      chords = groups = null;
+      return chord;
+    };
+    chord.padding = function(x) {
+      if (!arguments.length) return padding;
+      padding = x;
+      chords = groups = null;
+      return chord;
+    };
+    chord.sortGroups = function(x) {
+      if (!arguments.length) return sortGroups;
+      sortGroups = x;
+      chords = groups = null;
+      return chord;
+    };
+    chord.sortSubgroups = function(x) {
+      if (!arguments.length) return sortSubgroups;
+      sortSubgroups = x;
+      chords = null;
+      return chord;
+    };
+    chord.sortChords = function(x) {
+      if (!arguments.length) return sortChords;
+      sortChords = x;
+      if (chords) resort();
+      return chord;
+    };
+    chord.chords = function() {
+      if (!chords) relayout();
+      return chords;
+    };
+    chord.groups = function() {
+      if (!groups) relayout();
+      return groups;
+    };
+    return chord;
+  };
+  d3.layout.force = function() {
+    var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges;
+    function repulse(node) {
+      return function(quad, x1, _, x2) {
+        if (quad.point !== node) {
+          var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy;
+          if (dw * dw / theta2 < dn) {
+            if (dn < chargeDistance2) {
+              var k = quad.charge / dn;
+              node.px -= dx * k;
+              node.py -= dy * k;
+            }
+            return true;
+          }
+          if (quad.point && dn && dn < chargeDistance2) {
+            var k = quad.pointCharge / dn;
+            node.px -= dx * k;
+            node.py -= dy * k;
+          }
+        }
+        return !quad.charge;
+      };
+    }
+    force.tick = function() {
+      if ((alpha *= .99) < .005) {
+        timer = null;
+        event.end({
+          type: "end",
+          alpha: alpha = 0
+        });
+        return true;
+      }
+      var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y;
+      for (i = 0; i < m; ++i) {
+        o = links[i];
+        s = o.source;
+        t = o.target;
+        x = t.x - s.x;
+        y = t.y - s.y;
+        if (l = x * x + y * y) {
+          l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
+          x *= l;
+          y *= l;
+          t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5);
+          t.y -= y * k;
+          s.x += x * (k = 1 - k);
+          s.y += y * k;
+        }
+      }
+      if (k = alpha * gravity) {
+        x = size[0] / 2;
+        y = size[1] / 2;
+        i = -1;
+        if (k) while (++i < n) {
+          o = nodes[i];
+          o.x += (x - o.x) * k;
+          o.y += (y - o.y) * k;
+        }
+      }
+      if (charge) {
+        d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
+        i = -1;
+        while (++i < n) {
+          if (!(o = nodes[i]).fixed) {
+            q.visit(repulse(o));
+          }
+        }
+      }
+      i = -1;
+      while (++i < n) {
+        o = nodes[i];
+        if (o.fixed) {
+          o.x = o.px;
+          o.y = o.py;
+        } else {
+          o.x -= (o.px - (o.px = o.x)) * friction;
+          o.y -= (o.py - (o.py = o.y)) * friction;
+        }
+      }
+      event.tick({
+        type: "tick",
+        alpha: alpha
+      });
+    };
+    force.nodes = function(x) {
+      if (!arguments.length) return nodes;
+      nodes = x;
+      return force;
+    };
+    force.links = function(x) {
+      if (!arguments.length) return links;
+      links = x;
+      return force;
+    };
+    force.size = function(x) {
+      if (!arguments.length) return size;
+      size = x;
+      return force;
+    };
+    force.linkDistance = function(x) {
+      if (!arguments.length) return linkDistance;
+      linkDistance = typeof x === "function" ? x : +x;
+      return force;
+    };
+    force.distance = force.linkDistance;
+    force.linkStrength = function(x) {
+      if (!arguments.length) return linkStrength;
+      linkStrength = typeof x === "function" ? x : +x;
+      return force;
+    };
+    force.friction = function(x) {
+      if (!arguments.length) return friction;
+      friction = +x;
+      return force;
+    };
+    force.charge = function(x) {
+      if (!arguments.length) return charge;
+      charge = typeof x === "function" ? x : +x;
+      return force;
+    };
+    force.chargeDistance = function(x) {
+      if (!arguments.length) return Math.sqrt(chargeDistance2);
+      chargeDistance2 = x * x;
+      return force;
+    };
+    force.gravity = function(x) {
+      if (!arguments.length) return gravity;
+      gravity = +x;
+      return force;
+    };
+    force.theta = function(x) {
+      if (!arguments.length) return Math.sqrt(theta2);
+      theta2 = x * x;
+      return force;
+    };
+    force.alpha = function(x) {
+      if (!arguments.length) return alpha;
+      x = +x;
+      if (alpha) {
+        if (x > 0) {
+          alpha = x;
+        } else {
+          timer.c = null, timer.t = NaN, timer = null;
+          event.end({
+            type: "end",
+            alpha: alpha = 0
+          });
+        }
+      } else if (x > 0) {
+        event.start({
+          type: "start",
+          alpha: alpha = x
+        });
+        timer = d3_timer(force.tick);
+      }
+      return force;
+    };
+    force.start = function() {
+      var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o;
+      for (i = 0; i < n; ++i) {
+        (o = nodes[i]).index = i;
+        o.weight = 0;
+      }
+      for (i = 0; i < m; ++i) {
+        o = links[i];
+        if (typeof o.source == "number") o.source = nodes[o.source];
+        if (typeof o.target == "number") o.target = nodes[o.target];
+        ++o.source.weight;
+        ++o.target.weight;
+      }
+      for (i = 0; i < n; ++i) {
+        o = nodes[i];
+        if (isNaN(o.x)) o.x = position("x", w);
+        if (isNaN(o.y)) o.y = position("y", h);
+        if (isNaN(o.px)) o.px = o.x;
+        if (isNaN(o.py)) o.py = o.y;
+      }
+      distances = [];
+      if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance;
+      strengths = [];
+      if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength;
+      charges = [];
+      if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge;
+      function position(dimension, size) {
+        if (!neighbors) {
+          neighbors = new Array(n);
+          for (j = 0; j < n; ++j) {
+            neighbors[j] = [];
+          }
+          for (j = 0; j < m; ++j) {
+            var o = links[j];
+            neighbors[o.source.index].push(o.target);
+            neighbors[o.target.index].push(o.source);
+          }
+        }
+        var candidates = neighbors[i], j = -1, l = candidates.length, x;
+        while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x;
+        return Math.random() * size;
+      }
+      return force.resume();
+    };
+    force.resume = function() {
+      return force.alpha(.1);
+    };
+    force.stop = function() {
+      return force.alpha(0);
+    };
+    force.drag = function() {
+      if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend);
+      if (!arguments.length) return drag;
+      this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag);
+    };
+    function dragmove(d) {
+      d.px = d3.event.x, d.py = d3.event.y;
+      force.resume();
+    }
+    return d3.rebind(force, event, "on");
+  };
+  function d3_layout_forceDragstart(d) {
+    d.fixed |= 2;
+  }
+  function d3_layout_forceDragend(d) {
+    d.fixed &= ~6;
+  }
+  function d3_layout_forceMouseover(d) {
+    d.fixed |= 4;
+    d.px = d.x, d.py = d.y;
+  }
+  function d3_layout_forceMouseout(d) {
+    d.fixed &= ~4;
+  }
+  function d3_layout_forceAccumulate(quad, alpha, charges) {
+    var cx = 0, cy = 0;
+    quad.charge = 0;
+    if (!quad.leaf) {
+      var nodes = quad.nodes, n = nodes.length, i = -1, c;
+      while (++i < n) {
+        c = nodes[i];
+        if (c == null) continue;
+        d3_layout_forceAccumulate(c, alpha, charges);
+        quad.charge += c.charge;
+        cx += c.charge * c.cx;
+        cy += c.charge * c.cy;
+      }
+    }
+    if (quad.point) {
+      if (!quad.leaf) {
+        quad.point.x += Math.random() - .5;
+        quad.point.y += Math.random() - .5;
+      }
+      var k = alpha * charges[quad.point.index];
+      quad.charge += quad.pointCharge = k;
+      cx += k * quad.point.x;
+      cy += k * quad.point.y;
+    }
+    quad.cx = cx / quad.charge;
+    quad.cy = cy / quad.charge;
+  }
+  var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity;
+  d3.layout.hierarchy = function() {
+    var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue;
+    function hierarchy(root) {
+      var stack = [ root ], nodes = [], node;
+      root.depth = 0;
+      while ((node = stack.pop()) != null) {
+        nodes.push(node);
+        if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) {
+          var n, childs, child;
+          while (--n >= 0) {
+            stack.push(child = childs[n]);
+            child.parent = node;
+            child.depth = node.depth + 1;
+          }
+          if (value) node.value = 0;
+          node.children = childs;
+        } else {
+          if (value) node.value = +value.call(hierarchy, node, node.depth) || 0;
+          delete node.children;
+        }
+      }
+      d3_layout_hierarchyVisitAfter(root, function(node) {
+        var childs, parent;
+        if (sort && (childs = node.children)) childs.sort(sort);
+        if (value && (parent = node.parent)) parent.value += node.value;
+      });
+      return nodes;
+    }
+    hierarchy.sort = function(x) {
+      if (!arguments.length) return sort;
+      sort = x;
+      return hierarchy;
+    };
+    hierarchy.children = function(x) {
+      if (!arguments.length) return children;
+      children = x;
+      return hierarchy;
+    };
+    hierarchy.value = function(x) {
+      if (!arguments.length) return value;
+      value = x;
+      return hierarchy;
+    };
+    hierarchy.revalue = function(root) {
+      if (value) {
+        d3_layout_hierarchyVisitBefore(root, function(node) {
+          if (node.children) node.value = 0;
+        });
+        d3_layout_hierarchyVisitAfter(root, function(node) {
+          var parent;
+          if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0;
+          if (parent = node.parent) parent.value += node.value;
+        });
+      }
+      return root;
+    };
+    return hierarchy;
+  };
+  function d3_layout_hierarchyRebind(object, hierarchy) {
+    d3.rebind(object, hierarchy, "sort", "children", "value");
+    object.nodes = object;
+    object.links = d3_layout_hierarchyLinks;
+    return object;
+  }
+  function d3_layout_hierarchyVisitBefore(node, callback) {
+    var nodes = [ node ];
+    while ((node = nodes.pop()) != null) {
+      callback(node);
+      if ((children = node.children) && (n = children.length)) {
+        var n, children;
+        while (--n >= 0) nodes.push(children[n]);
+      }
+    }
+  }
+  function d3_layout_hierarchyVisitAfter(node, callback) {
+    var nodes = [ node ], nodes2 = [];
+    while ((node = nodes.pop()) != null) {
+      nodes2.push(node);
+      if ((children = node.children) && (n = children.length)) {
+        var i = -1, n, children;
+        while (++i < n) nodes.push(children[i]);
+      }
+    }
+    while ((node = nodes2.pop()) != null) {
+      callback(node);
+    }
+  }
+  function d3_layout_hierarchyChildren(d) {
+    return d.children;
+  }
+  function d3_layout_hierarchyValue(d) {
+    return d.value;
+  }
+  function d3_layout_hierarchySort(a, b) {
+    return b.value - a.value;
+  }
+  function d3_layout_hierarchyLinks(nodes) {
+    return d3.merge(nodes.map(function(parent) {
+      return (parent.children || []).map(function(child) {
+        return {
+          source: parent,
+          target: child
+        };
+      });
+    }));
+  }
+  d3.layout.partition = function() {
+    var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ];
+    function position(node, x, dx, dy) {
+      var children = node.children;
+      node.x = x;
+      node.y = node.depth * dy;
+      node.dx = dx;
+      node.dy = dy;
+      if (children && (n = children.length)) {
+        var i = -1, n, c, d;
+        dx = node.value ? dx / node.value : 0;
+        while (++i < n) {
+          position(c = children[i], x, d = c.value * dx, dy);
+          x += d;
+        }
+      }
+    }
+    function depth(node) {
+      var children = node.children, d = 0;
+      if (children && (n = children.length)) {
+        var i = -1, n;
+        while (++i < n) d = Math.max(d, depth(children[i]));
+      }
+      return 1 + d;
+    }
+    function partition(d, i) {
+      var nodes = hierarchy.call(this, d, i);
+      position(nodes[0], 0, size[0], size[1] / depth(nodes[0]));
+      return nodes;
+    }
+    partition.size = function(x) {
+      if (!arguments.length) return size;
+      size = x;
+      return partition;
+    };
+    return d3_layout_hierarchyRebind(partition, hierarchy);
+  };
+  d3.layout.pie = function() {
+    var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = Ï, padAngle = 0;
+    function pie(data) {
+      var n = data.length, values = data.map(function(d, i) {
+        return +value.call(pie, d, i);
+      }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v;
+      if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) {
+        return values[j] - values[i];
+      } : function(i, j) {
+        return sort(data[i], data[j]);
+      });
+      index.forEach(function(i) {
+        arcs[i] = {
+          data: data[i],
+          value: v = values[i],
+          startAngle: a,
+          endAngle: a += v * k + pa,
+          padAngle: p
+        };
+      });
+      return arcs;
+    }
+    pie.value = function(_) {
+      if (!arguments.length) return value;
+      value = _;
+      return pie;
+    };
+    pie.sort = function(_) {
+      if (!arguments.length) return sort;
+      sort = _;
+      return pie;
+    };
+    pie.startAngle = function(_) {
+      if (!arguments.length) return startAngle;
+      startAngle = _;
+      return pie;
+    };
+    pie.endAngle = function(_) {
+      if (!arguments.length) return endAngle;
+      endAngle = _;
+      return pie;
+    };
+    pie.padAngle = function(_) {
+      if (!arguments.length) return padAngle;
+      padAngle = _;
+      return pie;
+    };
+    return pie;
+  };
+  var d3_layout_pieSortByValue = {};
+  d3.layout.stack = function() {
+    var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY;
+    function stack(data, index) {
+      if (!(n = data.length)) return data;
+      var series = data.map(function(d, i) {
+        return values.call(stack, d, i);
+      });
+      var points = series.map(function(d) {
+        return d.map(function(v, i) {
+          return [ x.call(stack, v, i), y.call(stack, v, i) ];
+        });
+      });
+      var orders = order.call(stack, points, index);
+      series = d3.permute(series, orders);
+      points = d3.permute(points, orders);
+      var offsets = offset.call(stack, points, index);
+      var m = series[0].length, n, i, j, o;
+      for (j = 0; j < m; ++j) {
+        out.call(stack, series[0][j], o = offsets[j], points[0][j][1]);
+        for (i = 1; i < n; ++i) {
+          out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]);
+        }
+      }
+      return data;
+    }
+    stack.values = function(x) {
+      if (!arguments.length) return values;
+      values = x;
+      return stack;
+    };
+    stack.order = function(x) {
+      if (!arguments.length) return order;
+      order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault;
+      return stack;
+    };
+    stack.offset = function(x) {
+      if (!arguments.length) return offset;
+      offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero;
+      return stack;
+    };
+    stack.x = function(z) {
+      if (!arguments.length) return x;
+      x = z;
+      return stack;
+    };
+    stack.y = function(z) {
+      if (!arguments.length) return y;
+      y = z;
+      return stack;
+    };
+    stack.out = function(z) {
+      if (!arguments.length) return out;
+      out = z;
+      return stack;
+    };
+    return stack;
+  };
+  function d3_layout_stackX(d) {
+    return d.x;
+  }
+  function d3_layout_stackY(d) {
+    return d.y;
+  }
+  function d3_layout_stackOut(d, y0, y) {
+    d.y0 = y0;
+    d.y = y;
+  }
+  var d3_layout_stackOrders = d3.map({
+    "inside-out": function(data) {
+      var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) {
+        return max[a] - max[b];
+      }), top = 0, bottom = 0, tops = [], bottoms = [];
+      for (i = 0; i < n; ++i) {
+        j = index[i];
+        if (top < bottom) {
+          top += sums[j];
+          tops.push(j);
+        } else {
+          bottom += sums[j];
+          bottoms.push(j);
+        }
+      }
+      return bottoms.reverse().concat(tops);
+    },
+    reverse: function(data) {
+      return d3.range(data.length).reverse();
+    },
+    "default": d3_layout_stackOrderDefault
+  });
+  var d3_layout_stackOffsets = d3.map({
+    silhouette: function(data) {
+      var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = [];
+      for (j = 0; j < m; ++j) {
+        for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
+        if (o > max) max = o;
+        sums.push(o);
+      }
+      for (j = 0; j < m; ++j) {
+        y0[j] = (max - sums[j]) / 2;
+      }
+      return y0;
+    },
+    wiggle: function(data) {
+      var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = [];
+      y0[0] = o = o0 = 0;
+      for (j = 1; j < m; ++j) {
+        for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1];
+        for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) {
+          for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) {
+            s3 += (data[k][j][1] - data[k][j - 1][1]) / dx;
+          }
+          s2 += s3 * data[i][j][1];
+        }
+        y0[j] = o -= s1 ? s2 / s1 * dx : 0;
+        if (o < o0) o0 = o;
+      }
+      for (j = 0; j < m; ++j) y0[j] -= o0;
+      return y0;
+    },
+    expand: function(data) {
+      var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = [];
+      for (j = 0; j < m; ++j) {
+        for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
+        if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k;
+      }
+      for (j = 0; j < m; ++j) y0[j] = 0;
+      return y0;
+    },
+    zero: d3_layout_stackOffsetZero
+  });
+  function d3_layout_stackOrderDefault(data) {
+    return d3.range(data.length);
+  }
+  function d3_layout_stackOffsetZero(data) {
+    var j = -1, m = data[0].length, y0 = [];
+    while (++j < m) y0[j] = 0;
+    return y0;
+  }
+  function d3_layout_stackMaxIndex(array) {
+    var i = 1, j = 0, v = array[0][1], k, n = array.length;
+    for (;i < n; ++i) {
+      if ((k = array[i][1]) > v) {
+        j = i;
+        v = k;
+      }
+    }
+    return j;
+  }
+  function d3_layout_stackReduceSum(d) {
+    return d.reduce(d3_layout_stackSum, 0);
+  }
+  function d3_layout_stackSum(p, d) {
+    return p + d[1];
+  }
+  d3.layout.histogram = function() {
+    var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges;
+    function histogram(data, i) {
+      var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x;
+      while (++i < m) {
+        bin = bins[i] = [];
+        bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]);
+        bin.y = 0;
+      }
+      if (m > 0) {
+        i = -1;
+        while (++i < n) {
+          x = values[i];
+          if (x >= range[0] && x <= range[1]) {
+            bin = bins[d3.bisect(thresholds, x, 1, m) - 1];
+            bin.y += k;
+            bin.push(data[i]);
+          }
+        }
+      }
+      return bins;
+    }
+    histogram.value = function(x) {
+      if (!arguments.length) return valuer;
+      valuer = x;
+      return histogram;
+    };
+    histogram.range = function(x) {
+      if (!arguments.length) return ranger;
+      ranger = d3_functor(x);
+      return histogram;
+    };
+    histogram.bins = function(x) {
+      if (!arguments.length) return binner;
+      binner = typeof x === "number" ? function(range) {
+        return d3_layout_histogramBinFixed(range, x);
+      } : d3_functor(x);
+      return histogram;
+    };
+    histogram.frequency = function(x) {
+      if (!arguments.length) return frequency;
+      frequency = !!x;
+      return histogram;
+    };
+    return histogram;
+  };
+  function d3_layout_histogramBinSturges(range, values) {
+    return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
+  }
+  function d3_layout_histogramBinFixed(range, n) {
+    var x = -1, b = +range[0], m = (range[1] - b) / n, f = [];
+    while (++x <= n) f[x] = m * x + b;
+    return f;
+  }
+  function d3_layout_histogramRange(values) {
+    return [ d3.min(values), d3.max(values) ];
+  }
+  d3.layout.pack = function() {
+    var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius;
+    function pack(d, i) {
+      var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() {
+        return radius;
+      };
+      root.x = root.y = 0;
+      d3_layout_hierarchyVisitAfter(root, function(d) {
+        d.r = +r(d.value);
+      });
+      d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
+      if (padding) {
+        var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2;
+        d3_layout_hierarchyVisitAfter(root, function(d) {
+          d.r += dr;
+        });
+        d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
+        d3_layout_hierarchyVisitAfter(root, function(d) {
+          d.r -= dr;
+        });
+      }
+      d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h));
+      return nodes;
+    }
+    pack.size = function(_) {
+      if (!arguments.length) return size;
+      size = _;
+      return pack;
+    };
+    pack.radius = function(_) {
+      if (!arguments.length) return radius;
+      radius = _ == null || typeof _ === "function" ? _ : +_;
+      return pack;
+    };
+    pack.padding = function(_) {
+      if (!arguments.length) return padding;
+      padding = +_;
+      return pack;
+    };
+    return d3_layout_hierarchyRebind(pack, hierarchy);
+  };
+  function d3_layout_packSort(a, b) {
+    return a.value - b.value;
+  }
+  function d3_layout_packInsert(a, b) {
+    var c = a._pack_next;
+    a._pack_next = b;
+    b._pack_prev = a;
+    b._pack_next = c;
+    c._pack_prev = b;
+  }
+  function d3_layout_packSplice(a, b) {
+    a._pack_next = b;
+    b._pack_prev = a;
+  }
+  function d3_layout_packIntersects(a, b) {
+    var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r;
+    return .999 * dr * dr > dx * dx + dy * dy;
+  }
+  function d3_layout_packSiblings(node) {
+    if (!(nodes = node.children) || !(n = nodes.length)) return;
+    var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n;
+    function bound(node) {
+      xMin = Math.min(node.x - node.r, xMin);
+      xMax = Math.max(node.x + node.r, xMax);
+      yMin = Math.min(node.y - node.r, yMin);
+      yMax = Math.max(node.y + node.r, yMax);
+    }
+    nodes.forEach(d3_layout_packLink);
+    a = nodes[0];
+    a.x = -a.r;
+    a.y = 0;
+    bound(a);
+    if (n > 1) {
+      b = nodes[1];
+      b.x = b.r;
+      b.y = 0;
+      bound(b);
+      if (n > 2) {
+        c = nodes[2];
+        d3_layout_packPlace(a, b, c);
+        bound(c);
+        d3_layout_packInsert(a, c);
+        a._pack_prev = c;
+        d3_layout_packInsert(c, b);
+        b = a._pack_next;
+        for (i = 3; i < n; i++) {
+          d3_layout_packPlace(a, b, c = nodes[i]);
+          var isect = 0, s1 = 1, s2 = 1;
+          for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
+            if (d3_layout_packIntersects(j, c)) {
+              isect = 1;
+              break;
+            }
+          }
+          if (isect == 1) {
+            for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
+              if (d3_layout_packIntersects(k, c)) {
+                break;
+              }
+            }
+          }
+          if (isect) {
+            if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b);
+            i--;
+          } else {
+            d3_layout_packInsert(a, c);
+            b = c;
+            bound(c);
+          }
+        }
+      }
+    }
+    var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0;
+    for (i = 0; i < n; i++) {
+      c = nodes[i];
+      c.x -= cx;
+      c.y -= cy;
+      cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y));
+    }
+    node.r = cr;
+    nodes.forEach(d3_layout_packUnlink);
+  }
+  function d3_layout_packLink(node) {
+    node._pack_next = node._pack_prev = node;
+  }
+  function d3_layout_packUnlink(node) {
+    delete node._pack_next;
+    delete node._pack_prev;
+  }
+  function d3_layout_packTransform(node, x, y, k) {
+    var children = node.children;
+    node.x = x += k * node.x;
+    node.y = y += k * node.y;
+    node.r *= k;
+    if (children) {
+      var i = -1, n = children.length;
+      while (++i < n) d3_layout_packTransform(children[i], x, y, k);
+    }
+  }
+  function d3_layout_packPlace(a, b, c) {
+    var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y;
+    if (db && (dx || dy)) {
+      var da = b.r + c.r, dc = dx * dx + dy * dy;
+      da *= da;
+      db *= db;
+      var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
+      c.x = a.x + x * dx + y * dy;
+      c.y = a.y + x * dy - y * dx;
+    } else {
+      c.x = a.x + db;
+      c.y = a.y;
+    }
+  }
+  d3.layout.tree = function() {
+    var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null;
+    function tree(d, i) {
+      var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0);
+      d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z;
+      d3_layout_hierarchyVisitBefore(root1, secondWalk);
+      if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else {
+        var left = root0, right = root0, bottom = root0;
+        d3_layout_hierarchyVisitBefore(root0, function(node) {
+          if (node.x < left.x) left = node;
+          if (node.x > right.x) right = node;
+          if (node.depth > bottom.depth) bottom = node;
+        });
+        var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1);
+        d3_layout_hierarchyVisitBefore(root0, function(node) {
+          node.x = (node.x + tx) * kx;
+          node.y = node.depth * ky;
+        });
+      }
+      return nodes;
+    }
+    function wrapTree(root0) {
+      var root1 = {
+        A: null,
+        children: [ root0 ]
+      }, queue = [ root1 ], node1;
+      while ((node1 = queue.pop()) != null) {
+        for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) {
+          queue.push((children[i] = child = {
+            _: children[i],
+            parent: node1,
+            children: (child = children[i].children) && child.slice() || [],
+            A: null,
+            a: null,
+            z: 0,
+            m: 0,
+            c: 0,
+            s: 0,
+            t: null,
+            i: i
+          }).a = child);
+        }
+      }
+      return root1.children[0];
+    }
+    function firstWalk(v) {
+      var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null;
+      if (children.length) {
+        d3_layout_treeShift(v);
+        var midpoint = (children[0].z + children[children.length - 1].z) / 2;
+        if (w) {
+          v.z = w.z + separation(v._, w._);
+          v.m = v.z - midpoint;
+        } else {
+          v.z = midpoint;
+        }
+      } else if (w) {
+        v.z = w.z + separation(v._, w._);
+      }
+      v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
+    }
+    function secondWalk(v) {
+      v._.x = v.z + v.parent.m;
+      v.m += v.parent.m;
+    }
+    function apportion(v, w, ancestor) {
+      if (w) {
+        var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift;
+        while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) {
+          vom = d3_layout_treeLeft(vom);
+          vop = d3_layout_treeRight(vop);
+          vop.a = v;
+          shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
+          if (shift > 0) {
+            d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift);
+            sip += shift;
+            sop += shift;
+          }
+          sim += vim.m;
+          sip += vip.m;
+          som += vom.m;
+          sop += vop.m;
+        }
+        if (vim && !d3_layout_treeRight(vop)) {
+          vop.t = vim;
+          vop.m += sim - sop;
+        }
+        if (vip && !d3_layout_treeLeft(vom)) {
+          vom.t = vip;
+          vom.m += sip - som;
+          ancestor = v;
+        }
+      }
+      return ancestor;
+    }
+    function sizeNode(node) {
+      node.x *= size[0];
+      node.y = node.depth * size[1];
+    }
+    tree.separation = function(x) {
+      if (!arguments.length) return separation;
+      separation = x;
+      return tree;
+    };
+    tree.size = function(x) {
+      if (!arguments.length) return nodeSize ? null : size;
+      nodeSize = (size = x) == null ? sizeNode : null;
+      return tree;
+    };
+    tree.nodeSize = function(x) {
+      if (!arguments.length) return nodeSize ? size : null;
+      nodeSize = (size = x) == null ? null : sizeNode;
+      return tree;
+    };
+    return d3_layout_hierarchyRebind(tree, hierarchy);
+  };
+  function d3_layout_treeSeparation(a, b) {
+    return a.parent == b.parent ? 1 : 2;
+  }
+  function d3_layout_treeLeft(v) {
+    var children = v.children;
+    return children.length ? children[0] : v.t;
+  }
+  function d3_layout_treeRight(v) {
+    var children = v.children, n;
+    return (n = children.length) ? children[n - 1] : v.t;
+  }
+  function d3_layout_treeMove(wm, wp, shift) {
+    var change = shift / (wp.i - wm.i);
+    wp.c -= change;
+    wp.s += shift;
+    wm.c += change;
+    wp.z += shift;
+    wp.m += shift;
+  }
+  function d3_layout_treeShift(v) {
+    var shift = 0, change = 0, children = v.children, i = children.length, w;
+    while (--i >= 0) {
+      w = children[i];
+      w.z += shift;
+      w.m += shift;
+      shift += w.s + (change += w.c);
+    }
+  }
+  function d3_layout_treeAncestor(vim, v, ancestor) {
+    return vim.a.parent === v.parent ? vim.a : ancestor;
+  }
+  d3.layout.cluster = function() {
+    var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false;
+    function cluster(d, i) {
+      var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0;
+      d3_layout_hierarchyVisitAfter(root, function(node) {
+        var children = node.children;
+        if (children && children.length) {
+          node.x = d3_layout_clusterX(children);
+          node.y = d3_layout_clusterY(children);
+        } else {
+          node.x = previousNode ? x += separation(node, previousNode) : 0;
+          node.y = 0;
+          previousNode = node;
+        }
+      });
+      var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
+      d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) {
+        node.x = (node.x - root.x) * size[0];
+        node.y = (root.y - node.y) * size[1];
+      } : function(node) {
+        node.x = (node.x - x0) / (x1 - x0) * size[0];
+        node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1];
+      });
+      return nodes;
+    }
+    cluster.separation = function(x) {
+      if (!arguments.length) return separation;
+      separation = x;
+      return cluster;
+    };
+    cluster.size = function(x) {
+      if (!arguments.length) return nodeSize ? null : size;
+      nodeSize = (size = x) == null;
+      return cluster;
+    };
+    cluster.nodeSize = function(x) {
+      if (!arguments.length) return nodeSize ? size : null;
+      nodeSize = (size = x) != null;
+      return cluster;
+    };
+    return d3_layout_hierarchyRebind(cluster, hierarchy);
+  };
+  function d3_layout_clusterY(children) {
+    return 1 + d3.max(children, function(child) {
+      return child.y;
+    });
+  }
+  function d3_layout_clusterX(children) {
+    return children.reduce(function(x, child) {
+      return x + child.x;
+    }, 0) / children.length;
+  }
+  function d3_layout_clusterLeft(node) {
+    var children = node.children;
+    return children && children.length ? d3_layout_clusterLeft(children[0]) : node;
+  }
+  function d3_layout_clusterRight(node) {
+    var children = node.children, n;
+    return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node;
+  }
+  d3.layout.treemap = function() {
+    var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5));
+    function scale(children, k) {
+      var i = -1, n = children.length, child, area;
+      while (++i < n) {
+        area = (child = children[i]).value * (k < 0 ? 0 : k);
+        child.area = isNaN(area) || area <= 0 ? 0 : area;
+      }
+    }
+    function squarify(node) {
+      var children = node.children;
+      if (children && children.length) {
+        var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n;
+        scale(remaining, rect.dx * rect.dy / node.value);
+        row.area = 0;
+        while ((n = remaining.length) > 0) {
+          row.push(child = remaining[n - 1]);
+          row.area += child.area;
+          if (mode !== "squarify" || (score = worst(row, u)) <= best) {
+            remaining.pop();
+            best = score;
+          } else {
+            row.area -= row.pop().area;
+            position(row, u, rect, false);
+            u = Math.min(rect.dx, rect.dy);
+            row.length = row.area = 0;
+            best = Infinity;
+          }
+        }
+        if (row.length) {
+          position(row, u, rect, true);
+          row.length = row.area = 0;
+        }
+        children.forEach(squarify);
+      }
+    }
+    function stickify(node) {
+      var children = node.children;
+      if (children && children.length) {
+        var rect = pad(node), remaining = children.slice(), child, row = [];
+        scale(remaining, rect.dx * rect.dy / node.value);
+        row.area = 0;
+        while (child = remaining.pop()) {
+          row.push(child);
+          row.area += child.area;
+          if (child.z != null) {
+            position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
+            row.length = row.area = 0;
+          }
+        }
+        children.forEach(stickify);
+      }
+    }
+    function worst(row, u) {
+      var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length;
+      while (++i < n) {
+        if (!(r = row[i].area)) continue;
+        if (r < rmin) rmin = r;
+        if (r > rmax) rmax = r;
+      }
+      s *= s;
+      u *= u;
+      return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity;
+    }
+    function position(row, u, rect, flush) {
+      var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o;
+      if (u == rect.dx) {
+        if (flush || v > rect.dy) v = rect.dy;
+        while (++i < n) {
+          o = row[i];
+          o.x = x;
+          o.y = y;
+          o.dy = v;
+          x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
+        }
+        o.z = true;
+        o.dx += rect.x + rect.dx - x;
+        rect.y += v;
+        rect.dy -= v;
+      } else {
+        if (flush || v > rect.dx) v = rect.dx;
+        while (++i < n) {
+          o = row[i];
+          o.x = x;
+          o.y = y;
+          o.dx = v;
+          y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
+        }
+        o.z = false;
+        o.dy += rect.y + rect.dy - y;
+        rect.x += v;
+        rect.dx -= v;
+      }
+    }
+    function treemap(d) {
+      var nodes = stickies || hierarchy(d), root = nodes[0];
+      root.x = root.y = 0;
+      if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0;
+      if (stickies) hierarchy.revalue(root);
+      scale([ root ], root.dx * root.dy / root.value);
+      (stickies ? stickify : squarify)(root);
+      if (sticky) stickies = nodes;
+      return nodes;
+    }
+    treemap.size = function(x) {
+      if (!arguments.length) return size;
+      size = x;
+      return treemap;
+    };
+    treemap.padding = function(x) {
+      if (!arguments.length) return padding;
+      function padFunction(node) {
+        var p = x.call(treemap, node, node.depth);
+        return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p);
+      }
+      function padConstant(node) {
+        return d3_layout_treemapPad(node, x);
+      }
+      var type;
+      pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ], 
+      padConstant) : padConstant;
+      return treemap;
+    };
+    treemap.round = function(x) {
+      if (!arguments.length) return round != Number;
+      round = x ? Math.round : Number;
+      return treemap;
+    };
+    treemap.sticky = function(x) {
+      if (!arguments.length) return sticky;
+      sticky = x;
+      stickies = null;
+      return treemap;
+    };
+    treemap.ratio = function(x) {
+      if (!arguments.length) return ratio;
+      ratio = x;
+      return treemap;
+    };
+    treemap.mode = function(x) {
+      if (!arguments.length) return mode;
+      mode = x + "";
+      return treemap;
+    };
+    return d3_layout_hierarchyRebind(treemap, hierarchy);
+  };
+  function d3_layout_treemapPadNull(node) {
+    return {
+      x: node.x,
+      y: node.y,
+      dx: node.dx,
+      dy: node.dy
+    };
+  }
+  function d3_layout_treemapPad(node, padding) {
+    var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2];
+    if (dx < 0) {
+      x += dx / 2;
+      dx = 0;
+    }
+    if (dy < 0) {
+      y += dy / 2;
+      dy = 0;
+    }
+    return {
+      x: x,
+      y: y,
+      dx: dx,
+      dy: dy
+    };
+  }
+  d3.random = {
+    normal: function(Âµ, Ï) {
+      var n = arguments.length;
+      if (n < 2) Ï = 1;
+      if (n < 1) Âµ = 0;
+      return function() {
+        var x, y, r;
+        do {
+          x = Math.random() * 2 - 1;
+          y = Math.random() * 2 - 1;
+          r = x * x + y * y;
+        } while (!r || r > 1);
+        return Âµ + Ï * x * Math.sqrt(-2 * Math.log(r) / r);
+      };
+    },
+    logNormal: function() {
+      var random = d3.random.normal.apply(d3, arguments);
+      return function() {
+        return Math.exp(random());
+      };
+    },
+    bates: function(m) {
+      var random = d3.random.irwinHall(m);
+      return function() {
+        return random() / m;
+      };
+    },
+    irwinHall: function(m) {
+      return function() {
+        for (var s = 0, j = 0; j < m; j++) s += Math.random();
+        return s;
+      };
+    }
+  };
+  d3.scale = {};
+  function d3_scaleExtent(domain) {
+    var start = domain[0], stop = domain[domain.length - 1];
+    return start < stop ? [ start, stop ] : [ stop, start ];
+  }
+  function d3_scaleRange(scale) {
+    return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range());
+  }
+  function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
+    var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]);
+    return function(x) {
+      return i(u(x));
+    };
+  }
+  function d3_scale_nice(domain, nice) {
+    var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx;
+    if (x1 < x0) {
+      dx = i0, i0 = i1, i1 = dx;
+      dx = x0, x0 = x1, x1 = dx;
+    }
+    domain[i0] = nice.floor(x0);
+    domain[i1] = nice.ceil(x1);
+    return domain;
+  }
+  function d3_scale_niceStep(step) {
+    return step ? {
+      floor: function(x) {
+        return Math.floor(x / step) * step;
+      },
+      ceil: function(x) {
+        return Math.ceil(x / step) * step;
+      }
+    } : d3_scale_niceIdentity;
+  }
+  var d3_scale_niceIdentity = {
+    floor: d3_identity,
+    ceil: d3_identity
+  };
+  function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
+    var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1;
+    if (domain[k] < domain[0]) {
+      domain = domain.slice().reverse();
+      range = range.slice().reverse();
+    }
+    while (++j <= k) {
+      u.push(uninterpolate(domain[j - 1], domain[j]));
+      i.push(interpolate(range[j - 1], range[j]));
+    }
+    return function(x) {
+      var j = d3.bisect(domain, x, 1, k) - 1;
+      return i[j](u[j](x));
+    };
+  }
+  d3.scale.linear = function() {
+    return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false);
+  };
+  function d3_scale_linear(domain, range, interpolate, clamp) {
+    var output, input;
+    function rescale() {
+      var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
+      output = linear(domain, range, uninterpolate, interpolate);
+      input = linear(range, domain, uninterpolate, d3_interpolate);
+      return scale;
+    }
+    function scale(x) {
+      return output(x);
+    }
+    scale.invert = function(y) {
+      return input(y);
+    };
+    scale.domain = function(x) {
+      if (!arguments.length) return domain;
+      domain = x.map(Number);
+      return rescale();
+    };
+    scale.range = function(x) {
+      if (!arguments.length) return range;
+      range = x;
+      return rescale();
+    };
+    scale.rangeRound = function(x) {
+      return scale.range(x).interpolate(d3_interpolateRound);
+    };
+    scale.clamp = function(x) {
+      if (!arguments.length) return clamp;
+      clamp = x;
+      return rescale();
+    };
+    scale.interpolate = function(x) {
+      if (!arguments.length) return interpolate;
+      interpolate = x;
+      return rescale();
+    };
+    scale.ticks = function(m) {
+      return d3_scale_linearTicks(domain, m);
+    };
+    scale.tickFormat = function(m, format) {
+      return d3_scale_linearTickFormat(domain, m, format);
+    };
+    scale.nice = function(m) {
+      d3_scale_linearNice(domain, m);
+      return rescale();
+    };
+    scale.copy = function() {
+      return d3_scale_linear(domain, range, interpolate, clamp);
+    };
+    return rescale();
+  }
+  function d3_scale_linearRebind(scale, linear) {
+    return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
+  }
+  function d3_scale_linearNice(domain, m) {
+    d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
+    d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
+    return domain;
+  }
+  function d3_scale_linearTickRange(domain, m) {
+    if (m == null) m = 10;
+    var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step;
+    if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2;
+    extent[0] = Math.ceil(extent[0] / step) * step;
+    extent[1] = Math.floor(extent[1] / step) * step + step * .5;
+    extent[2] = step;
+    return extent;
+  }
+  function d3_scale_linearTicks(domain, m) {
+    return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
+  }
+  function d3_scale_linearTickFormat(domain, m, format) {
+    var range = d3_scale_linearTickRange(domain, m);
+    if (format) {
+      var match = d3_format_re.exec(format);
+      match.shift();
+      if (match[8] === "s") {
+        var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1])));
+        if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2]));
+        match[8] = "f";
+        format = d3.format(match.join(""));
+        return function(d) {
+          return format(prefix.scale(d)) + prefix.symbol;
+        };
+      }
+      if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range);
+      format = match.join("");
+    } else {
+      format = ",." + d3_scale_linearPrecision(range[2]) + "f";
+    }
+    return d3.format(format);
+  }
+  var d3_scale_linearFormatSignificant = {
+    s: 1,
+    g: 1,
+    p: 1,
+    r: 1,
+    e: 1
+  };
+  function d3_scale_linearPrecision(value) {
+    return -Math.floor(Math.log(value) / Math.LN10 + .01);
+  }
+  function d3_scale_linearFormatPrecision(type, range) {
+    var p = d3_scale_linearPrecision(range[2]);
+    return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2;
+  }
+  d3.scale.log = function() {
+    return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]);
+  };
+  function d3_scale_log(linear, base, positive, domain) {
+    function log(x) {
+      return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base);
+    }
+    function pow(x) {
+      return positive ? Math.pow(base, x) : -Math.pow(base, -x);
+    }
+    function scale(x) {
+      return linear(log(x));
+    }
+    scale.invert = function(x) {
+      return pow(linear.invert(x));
+    };
+    scale.domain = function(x) {
+      if (!arguments.length) return domain;
+      positive = x[0] >= 0;
+      linear.domain((domain = x.map(Number)).map(log));
+      return scale;
+    };
+    scale.base = function(_) {
+      if (!arguments.length) return base;
+      base = +_;
+      linear.domain(domain.map(log));
+      return scale;
+    };
+    scale.nice = function() {
+      var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative);
+      linear.domain(niced);
+      domain = niced.map(pow);
+      return scale;
+    };
+    scale.ticks = function() {
+      var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base;
+      if (isFinite(j - i)) {
+        if (positive) {
+          for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k);
+          ticks.push(pow(i));
+        } else {
+          ticks.push(pow(i));
+          for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k);
+        }
+        for (i = 0; ticks[i] < u; i++) {}
+        for (j = ticks.length; ticks[j - 1] > v; j--) {}
+        ticks = ticks.slice(i, j);
+      }
+      return ticks;
+    };
+    scale.tickFormat = function(n, format) {
+      if (!arguments.length) return d3_scale_logFormat;
+      if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format);
+      var k = Math.max(1, base * n / scale.ticks().length);
+      return function(d) {
+        var i = d / pow(Math.round(log(d)));
+        if (i * base < base - .5) i *= base;
+        return i <= k ? format(d) : "";
+      };
+    };
+    scale.copy = function() {
+      return d3_scale_log(linear.copy(), base, positive, domain);
+    };
+    return d3_scale_linearRebind(scale, linear);
+  }
+  var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = {
+    floor: function(x) {
+      return -Math.ceil(-x);
+    },
+    ceil: function(x) {
+      return -Math.floor(-x);
+    }
+  };
+  d3.scale.pow = function() {
+    return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]);
+  };
+  function d3_scale_pow(linear, exponent, domain) {
+    var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent);
+    function scale(x) {
+      return linear(powp(x));
+    }
+    scale.invert = function(x) {
+      return powb(linear.invert(x));
+    };
+    scale.domain = function(x) {
+      if (!arguments.length) return domain;
+      linear.domain((domain = x.map(Number)).map(powp));
+      return scale;
+    };
+    scale.ticks = function(m) {
+      return d3_scale_linearTicks(domain, m);
+    };
+    scale.tickFormat = function(m, format) {
+      return d3_scale_linearTickFormat(domain, m, format);
+    };
+    scale.nice = function(m) {
+      return scale.domain(d3_scale_linearNice(domain, m));
+    };
+    scale.exponent = function(x) {
+      if (!arguments.length) return exponent;
+      powp = d3_scale_powPow(exponent = x);
+      powb = d3_scale_powPow(1 / exponent);
+      linear.domain(domain.map(powp));
+      return scale;
+    };
+    scale.copy = function() {
+      return d3_scale_pow(linear.copy(), exponent, domain);
+    };
+    return d3_scale_linearRebind(scale, linear);
+  }
+  function d3_scale_powPow(e) {
+    return function(x) {
+      return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
+    };
+  }
+  d3.scale.sqrt = function() {
+    return d3.scale.pow().exponent(.5);
+  };
+  d3.scale.ordinal = function() {
+    return d3_scale_ordinal([], {
+      t: "range",
+      a: [ [] ]
+    });
+  };
+  function d3_scale_ordinal(domain, ranger) {
+    var index, range, rangeBand;
+    function scale(x) {
+      return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length];
+    }
+    function steps(start, step) {
+      return d3.range(domain.length).map(function(i) {
+        return start + step * i;
+      });
+    }
+    scale.domain = function(x) {
+      if (!arguments.length) return domain;
+      domain = [];
+      index = new d3_Map();
+      var i = -1, n = x.length, xi;
+      while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
+      return scale[ranger.t].apply(scale, ranger.a);
+    };
+    scale.range = function(x) {
+      if (!arguments.length) return range;
+      range = x;
+      rangeBand = 0;
+      ranger = {
+        t: "range",
+        a: arguments
+      };
+      return scale;
+    };
+    scale.rangePoints = function(x, padding) {
+      if (arguments.length < 2) padding = 0;
+      var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2, 
+      0) : (stop - start) / (domain.length - 1 + padding);
+      range = steps(start + step * padding / 2, step);
+      rangeBand = 0;
+      ranger = {
+        t: "rangePoints",
+        a: arguments
+      };
+      return scale;
+    };
+    scale.rangeRoundPoints = function(x, padding) {
+      if (arguments.length < 2) padding = 0;
+      var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2), 
+      0) : (stop - start) / (domain.length - 1 + padding) | 0;
+      range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step);
+      rangeBand = 0;
+      ranger = {
+        t: "rangeRoundPoints",
+        a: arguments
+      };
+      return scale;
+    };
+    scale.rangeBands = function(x, padding, outerPadding) {
+      if (arguments.length < 2) padding = 0;
+      if (arguments.length < 3) outerPadding = padding;
+      var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding);
+      range = steps(start + step * outerPadding, step);
+      if (reverse) range.reverse();
+      rangeBand = step * (1 - padding);
+      ranger = {
+        t: "rangeBands",
+        a: arguments
+      };
+      return scale;
+    };
+    scale.rangeRoundBands = function(x, padding, outerPadding) {
+      if (arguments.length < 2) padding = 0;
+      if (arguments.length < 3) outerPadding = padding;
+      var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding));
+      range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step);
+      if (reverse) range.reverse();
+      rangeBand = Math.round(step * (1 - padding));
+      ranger = {
+        t: "rangeRoundBands",
+        a: arguments
+      };
+      return scale;
+    };
+    scale.rangeBand = function() {
+      return rangeBand;
+    };
+    scale.rangeExtent = function() {
+      return d3_scaleExtent(ranger.a[0]);
+    };
+    scale.copy = function() {
+      return d3_scale_ordinal(domain, ranger);
+    };
+    return scale.domain(domain);
+  }
+  d3.scale.category10 = function() {
+    return d3.scale.ordinal().range(d3_category10);
+  };
+  d3.scale.category20 = function() {
+    return d3.scale.ordinal().range(d3_category20);
+  };
+  d3.scale.category20b = function() {
+    return d3.scale.ordinal().range(d3_category20b);
+  };
+  d3.scale.category20c = function() {
+    return d3.scale.ordinal().range(d3_category20c);
+  };
+  var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString);
+  var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString);
+  var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString);
+  var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString);
+  d3.scale.quantile = function() {
+    return d3_scale_quantile([], []);
+  };
+  function d3_scale_quantile(domain, range) {
+    var thresholds;
+    function rescale() {
+      var k = 0, q = range.length;
+      thresholds = [];
+      while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
+      return scale;
+    }
+    function scale(x) {
+      if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)];
+    }
+    scale.domain = function(x) {
+      if (!arguments.length) return domain;
+      domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending);
+      return rescale();
+    };
+    scale.range = function(x) {
+      if (!arguments.length) return range;
+      range = x;
+      return rescale();
+    };
+    scale.quantiles = function() {
+      return thresholds;
+    };
+    scale.invertExtent = function(y) {
+      y = range.indexOf(y);
+      return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ];
+    };
+    scale.copy = function() {
+      return d3_scale_quantile(domain, range);
+    };
+    return rescale();
+  }
+  d3.scale.quantize = function() {
+    return d3_scale_quantize(0, 1, [ 0, 1 ]);
+  };
+  function d3_scale_quantize(x0, x1, range) {
+    var kx, i;
+    function scale(x) {
+      return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
+    }
+    function rescale() {
+      kx = range.length / (x1 - x0);
+      i = range.length - 1;
+      return scale;
+    }
+    scale.domain = function(x) {
+      if (!arguments.length) return [ x0, x1 ];
+      x0 = +x[0];
+      x1 = +x[x.length - 1];
+      return rescale();
+    };
+    scale.range = function(x) {
+      if (!arguments.length) return range;
+      range = x;
+      return rescale();
+    };
+    scale.invertExtent = function(y) {
+      y = range.indexOf(y);
+      y = y < 0 ? NaN : y / kx + x0;
+      return [ y, y + 1 / kx ];
+    };
+    scale.copy = function() {
+      return d3_scale_quantize(x0, x1, range);
+    };
+    return rescale();
+  }
+  d3.scale.threshold = function() {
+    return d3_scale_threshold([ .5 ], [ 0, 1 ]);
+  };
+  function d3_scale_threshold(domain, range) {
+    function scale(x) {
+      if (x <= x) return range[d3.bisect(domain, x)];
+    }
+    scale.domain = function(_) {
+      if (!arguments.length) return domain;
+      domain = _;
+      return scale;
+    };
+    scale.range = function(_) {
+      if (!arguments.length) return range;
+      range = _;
+      return scale;
+    };
+    scale.invertExtent = function(y) {
+      y = range.indexOf(y);
+      return [ domain[y - 1], domain[y] ];
+    };
+    scale.copy = function() {
+      return d3_scale_threshold(domain, range);
+    };
+    return scale;
+  }
+  d3.scale.identity = function() {
+    return d3_scale_identity([ 0, 1 ]);
+  };
+  function d3_scale_identity(domain) {
+    function identity(x) {
+      return +x;
+    }
+    identity.invert = identity;
+    identity.domain = identity.range = function(x) {
+      if (!arguments.length) return domain;
+      domain = x.map(identity);
+      return identity;
+    };
+    identity.ticks = function(m) {
+      return d3_scale_linearTicks(domain, m);
+    };
+    identity.tickFormat = function(m, format) {
+      return d3_scale_linearTickFormat(domain, m, format);
+    };
+    identity.copy = function() {
+      return d3_scale_identity(domain);
+    };
+    return identity;
+  }
+  d3.svg = {};
+  function d3_zero() {
+    return 0;
+  }
+  d3.svg.arc = function() {
+    var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle;
+    function arc() {
+      var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfÏ, a1 = endAngle.apply(this, arguments) - halfÏ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1;
+      if (r1 < r0) rc = r1, r1 = r0, r0 = rc;
+      if (da >= ÏÎµ) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z";
+      var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = [];
+      if (ap = (+padAngle.apply(this, arguments) || 0) / 2) {
+        rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments);
+        if (!cw) p1 *= -1;
+        if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap));
+        if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap));
+      }
+      if (r1) {
+        x0 = r1 * Math.cos(a0 + p1);
+        y0 = r1 * Math.sin(a0 + p1);
+        x1 = r1 * Math.cos(a1 - p1);
+        y1 = r1 * Math.sin(a1 - p1);
+        var l1 = Math.abs(a1 - a0 - 2 * p1) <= Ï ? 0 : 1;
+        if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) {
+          var h1 = (a0 + a1) / 2;
+          x0 = r1 * Math.cos(h1);
+          y0 = r1 * Math.sin(h1);
+          x1 = y1 = null;
+        }
+      } else {
+        x0 = y0 = 0;
+      }
+      if (r0) {
+        x2 = r0 * Math.cos(a1 - p0);
+        y2 = r0 * Math.sin(a1 - p0);
+        x3 = r0 * Math.cos(a0 + p0);
+        y3 = r0 * Math.sin(a0 + p0);
+        var l0 = Math.abs(a0 - a1 + 2 * p0) <= Ï ? 0 : 1;
+        if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) {
+          var h0 = (a0 + a1) / 2;
+          x2 = r0 * Math.cos(h0);
+          y2 = r0 * Math.sin(h0);
+          x3 = y3 = null;
+        }
+      } else {
+        x2 = y2 = 0;
+      }
+      if (da > Îµ && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) {
+        cr = r0 < r1 ^ cw ? 0 : 1;
+        var rc1 = rc, rc0 = rc;
+        if (da < Ï) {
+          var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
+          rc0 = Math.min(rc, (r0 - lc) / (kc - 1));
+          rc1 = Math.min(rc, (r1 - lc) / (kc + 1));
+        }
+        if (x1 != null) {
+          var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw);
+          if (rc === rc1) {
+            path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]);
+          } else {
+            path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]);
+          }
+        } else {
+          path.push("M", x0, ",", y0);
+        }
+        if (x3 != null) {
+          var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw);
+          if (rc === rc0) {
+            path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
+          } else {
+            path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
+          }
+        } else {
+          path.push("L", x2, ",", y2);
+        }
+      } else {
+        path.push("M", x0, ",", y0);
+        if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1);
+        path.push("L", x2, ",", y2);
+        if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3);
+      }
+      path.push("Z");
+      return path.join("");
+    }
+    function circleSegment(r1, cw) {
+      return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1;
+    }
+    arc.innerRadius = function(v) {
+      if (!arguments.length) return innerRadius;
+      innerRadius = d3_functor(v);
+      return arc;
+    };
+    arc.outerRadius = function(v) {
+      if (!arguments.length) return outerRadius;
+      outerRadius = d3_functor(v);
+      return arc;
+    };
+    arc.cornerRadius = function(v) {
+      if (!arguments.length) return cornerRadius;
+      cornerRadius = d3_functor(v);
+      return arc;
+    };
+    arc.padRadius = function(v) {
+      if (!arguments.length) return padRadius;
+      padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v);
+      return arc;
+    };
+    arc.startAngle = function(v) {
+      if (!arguments.length) return startAngle;
+      startAngle = d3_functor(v);
+      return arc;
+    };
+    arc.endAngle = function(v) {
+      if (!arguments.length) return endAngle;
+      endAngle = d3_functor(v);
+      return arc;
+    };
+    arc.padAngle = function(v) {
+      if (!arguments.length) return padAngle;
+      padAngle = d3_functor(v);
+      return arc;
+    };
+    arc.centroid = function() {
+      var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfÏ;
+      return [ Math.cos(a) * r, Math.sin(a) * r ];
+    };
+    return arc;
+  };
+  var d3_svg_arcAuto = "auto";
+  function d3_svg_arcInnerRadius(d) {
+    return d.innerRadius;
+  }
+  function d3_svg_arcOuterRadius(d) {
+    return d.outerRadius;
+  }
+  function d3_svg_arcStartAngle(d) {
+    return d.startAngle;
+  }
+  function d3_svg_arcEndAngle(d) {
+    return d.endAngle;
+  }
+  function d3_svg_arcPadAngle(d) {
+    return d && d.padAngle;
+  }
+  function d3_svg_arcSweep(x0, y0, x1, y1) {
+    return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1;
+  }
+  function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) {
+    var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3;
+    if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
+    return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ];
+  }
+  function d3_svg_line(projection) {
+    var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7;
+    function line(data) {
+      var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y);
+      function segment() {
+        segments.push("M", interpolate(projection(points), tension));
+      }
+      while (++i < n) {
+        if (defined.call(this, d = data[i], i)) {
+          points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]);
+        } else if (points.length) {
+          segment();
+          points = [];
+        }
+      }
+      if (points.length) segment();
+      return segments.length ? segments.join("") : null;
+    }
+    line.x = function(_) {
+      if (!arguments.length) return x;
+      x = _;
+      return line;
+    };
+    line.y = function(_) {
+      if (!arguments.length) return y;
+      y = _;
+      return line;
+    };
+    line.defined = function(_) {
+      if (!arguments.length) return defined;
+      defined = _;
+      return line;
+    };
+    line.interpolate = function(_) {
+      if (!arguments.length) return interpolateKey;
+      if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
+      return line;
+    };
+    line.tension = function(_) {
+      if (!arguments.length) return tension;
+      tension = _;
+      return line;
+    };
+    return line;
+  }
+  d3.svg.line = function() {
+    return d3_svg_line(d3_identity);
+  };
+  var d3_svg_lineInterpolators = d3.map({
+    linear: d3_svg_lineLinear,
+    "linear-closed": d3_svg_lineLinearClosed,
+    step: d3_svg_lineStep,
+    "step-before": d3_svg_lineStepBefore,
+    "step-after": d3_svg_lineStepAfter,
+    basis: d3_svg_lineBasis,
+    "basis-open": d3_svg_lineBasisOpen,
+    "basis-closed": d3_svg_lineBasisClosed,
+    bundle: d3_svg_lineBundle,
+    cardinal: d3_svg_lineCardinal,
+    "cardinal-open": d3_svg_lineCardinalOpen,
+    "cardinal-closed": d3_svg_lineCardinalClosed,
+    monotone: d3_svg_lineMonotone
+  });
+  d3_svg_lineInterpolators.forEach(function(key, value) {
+    value.key = key;
+    value.closed = /-closed$/.test(key);
+  });
+  function d3_svg_lineLinear(points) {
+    return points.length > 1 ? points.join("L") : points + "Z";
+  }
+  function d3_svg_lineLinearClosed(points) {
+    return points.join("L") + "Z";
+  }
+  function d3_svg_lineStep(points) {
+    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
+    while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]);
+    if (n > 1) path.push("H", p[0]);
+    return path.join("");
+  }
+  function d3_svg_lineStepBefore(points) {
+    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
+    while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
+    return path.join("");
+  }
+  function d3_svg_lineStepAfter(points) {
+    var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
+    while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
+    return path.join("");
+  }
+  function d3_svg_lineCardinalOpen(points, tension) {
+    return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension));
+  }
+  function d3_svg_lineCardinalClosed(points, tension) {
+    return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), 
+    points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension));
+  }
+  function d3_svg_lineCardinal(points, tension) {
+    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension));
+  }
+  function d3_svg_lineHermite(points, tangents) {
+    if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) {
+      return d3_svg_lineLinear(points);
+    }
+    var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1;
+    if (quad) {
+      path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1];
+      p0 = points[1];
+      pi = 2;
+    }
+    if (tangents.length > 1) {
+      t = tangents[1];
+      p = points[pi];
+      pi++;
+      path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
+      for (var i = 2; i < tangents.length; i++, pi++) {
+        p = points[pi];
+        t = tangents[i];
+        path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
+      }
+    }
+    if (quad) {
+      var lp = points[pi];
+      path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1];
+    }
+    return path;
+  }
+  function d3_svg_lineCardinalTangents(points, tension) {
+    var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length;
+    while (++i < n) {
+      p0 = p1;
+      p1 = p2;
+      p2 = points[i];
+      tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]);
+    }
+    return tangents;
+  }
+  function d3_svg_lineBasis(points) {
+    if (points.length < 3) return d3_svg_lineLinear(points);
+    var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
+    points.push(points[n - 1]);
+    while (++i <= n) {
+      pi = points[i];
+      px.shift();
+      px.push(pi[0]);
+      py.shift();
+      py.push(pi[1]);
+      d3_svg_lineBasisBezier(path, px, py);
+    }
+    points.pop();
+    path.push("L", pi);
+    return path.join("");
+  }
+  function d3_svg_lineBasisOpen(points) {
+    if (points.length < 4) return d3_svg_lineLinear(points);
+    var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ];
+    while (++i < 3) {
+      pi = points[i];
+      px.push(pi[0]);
+      py.push(pi[1]);
+    }
+    path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
+    --i;
+    while (++i < n) {
+      pi = points[i];
+      px.shift();
+      px.push(pi[0]);
+      py.shift();
+      py.push(pi[1]);
+      d3_svg_lineBasisBezier(path, px, py);
+    }
+    return path.join("");
+  }
+  function d3_svg_lineBasisClosed(points) {
+    var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = [];
+    while (++i < 4) {
+      pi = points[i % n];
+      px.push(pi[0]);
+      py.push(pi[1]);
+    }
+    path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
+    --i;
+    while (++i < m) {
+      pi = points[i % n];
+      px.shift();
+      px.push(pi[0]);
+      py.shift();
+      py.push(pi[1]);
+      d3_svg_lineBasisBezier(path, px, py);
+    }
+    return path.join("");
+  }
+  function d3_svg_lineBundle(points, tension) {
+    var n = points.length - 1;
+    if (n) {
+      var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t;
+      while (++i <= n) {
+        p = points[i];
+        t = i / n;
+        p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
+        p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
+      }
+    }
+    return d3_svg_lineBasis(points);
+  }
+  function d3_svg_lineDot4(a, b) {
+    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
+  }
+  var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ];
+  function d3_svg_lineBasisBezier(path, x, y) {
+    path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
+  }
+  function d3_svg_lineSlope(p0, p1) {
+    return (p1[1] - p0[1]) / (p1[0] - p0[0]);
+  }
+  function d3_svg_lineFiniteDifferences(points) {
+    var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1);
+    while (++i < j) {
+      m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2;
+    }
+    m[i] = d;
+    return m;
+  }
+  function d3_svg_lineMonotoneTangents(points) {
+    var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1;
+    while (++i < j) {
+      d = d3_svg_lineSlope(points[i], points[i + 1]);
+      if (abs(d) < Îµ) {
+        m[i] = m[i + 1] = 0;
+      } else {
+        a = m[i] / d;
+        b = m[i + 1] / d;
+        s = a * a + b * b;
+        if (s > 9) {
+          s = d * 3 / Math.sqrt(s);
+          m[i] = s * a;
+          m[i + 1] = s * b;
+        }
+      }
+    }
+    i = -1;
+    while (++i <= j) {
+      s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i]));
+      tangents.push([ s || 0, m[i] * s || 0 ]);
+    }
+    return tangents;
+  }
+  function d3_svg_lineMonotone(points) {
+    return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
+  }
+  d3.svg.line.radial = function() {
+    var line = d3_svg_line(d3_svg_lineRadial);
+    line.radius = line.x, delete line.x;
+    line.angle = line.y, delete line.y;
+    return line;
+  };
+  function d3_svg_lineRadial(points) {
+    var point, i = -1, n = points.length, r, a;
+    while (++i < n) {
+      point = points[i];
+      r = point[0];
+      a = point[1] - halfÏ;
+      point[0] = r * Math.cos(a);
+      point[1] = r * Math.sin(a);
+    }
+    return points;
+  }
+  function d3_svg_area(projection) {
+    var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7;
+    function area(data) {
+      var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() {
+        return x;
+      } : d3_functor(x1), fy1 = y0 === y1 ? function() {
+        return y;
+      } : d3_functor(y1), x, y;
+      function segment() {
+        segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z");
+      }
+      while (++i < n) {
+        if (defined.call(this, d = data[i], i)) {
+          points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]);
+          points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]);
+        } else if (points0.length) {
+          segment();
+          points0 = [];
+          points1 = [];
+        }
+      }
+      if (points0.length) segment();
+      return segments.length ? segments.join("") : null;
+    }
+    area.x = function(_) {
+      if (!arguments.length) return x1;
+      x0 = x1 = _;
+      return area;
+    };
+    area.x0 = function(_) {
+      if (!arguments.length) return x0;
+      x0 = _;
+      return area;
+    };
+    area.x1 = function(_) {
+      if (!arguments.length) return x1;
+      x1 = _;
+      return area;
+    };
+    area.y = function(_) {
+      if (!arguments.length) return y1;
+      y0 = y1 = _;
+      return area;
+    };
+    area.y0 = function(_) {
+      if (!arguments.length) return y0;
+      y0 = _;
+      return area;
+    };
+    area.y1 = function(_) {
+      if (!arguments.length) return y1;
+      y1 = _;
+      return area;
+    };
+    area.defined = function(_) {
+      if (!arguments.length) return defined;
+      defined = _;
+      return area;
+    };
+    area.interpolate = function(_) {
+      if (!arguments.length) return interpolateKey;
+      if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
+      interpolateReverse = interpolate.reverse || interpolate;
+      L = interpolate.closed ? "M" : "L";
+      return area;
+    };
+    area.tension = function(_) {
+      if (!arguments.length) return tension;
+      tension = _;
+      return area;
+    };
+    return area;
+  }
+  d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter;
+  d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore;
+  d3.svg.area = function() {
+    return d3_svg_area(d3_identity);
+  };
+  d3.svg.area.radial = function() {
+    var area = d3_svg_area(d3_svg_lineRadial);
+    area.radius = area.x, delete area.x;
+    area.innerRadius = area.x0, delete area.x0;
+    area.outerRadius = area.x1, delete area.x1;
+    area.angle = area.y, delete area.y;
+    area.startAngle = area.y0, delete area.y0;
+    area.endAngle = area.y1, delete area.y1;
+    return area;
+  };
+  d3.svg.chord = function() {
+    var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
+    function chord(d, i) {
+      var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i);
+      return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z";
+    }
+    function subgroup(self, f, d, i) {
+      var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfÏ, a1 = endAngle.call(self, subgroup, i) - halfÏ;
+      return {
+        r: r,
+        a0: a0,
+        a1: a1,
+        p0: [ r * Math.cos(a0), r * Math.sin(a0) ],
+        p1: [ r * Math.cos(a1), r * Math.sin(a1) ]
+      };
+    }
+    function equals(a, b) {
+      return a.a0 == b.a0 && a.a1 == b.a1;
+    }
+    function arc(r, p, a) {
+      return "A" + r + "," + r + " 0 " + +(a > Ï) + ",1 " + p;
+    }
+    function curve(r0, p0, r1, p1) {
+      return "Q 0,0 " + p1;
+    }
+    chord.radius = function(v) {
+      if (!arguments.length) return radius;
+      radius = d3_functor(v);
+      return chord;
+    };
+    chord.source = function(v) {
+      if (!arguments.length) return source;
+      source = d3_functor(v);
+      return chord;
+    };
+    chord.target = function(v) {
+      if (!arguments.length) return target;
+      target = d3_functor(v);
+      return chord;
+    };
+    chord.startAngle = function(v) {
+      if (!arguments.length) return startAngle;
+      startAngle = d3_functor(v);
+      return chord;
+    };
+    chord.endAngle = function(v) {
+      if (!arguments.length) return endAngle;
+      endAngle = d3_functor(v);
+      return chord;
+    };
+    return chord;
+  };
+  function d3_svg_chordRadius(d) {
+    return d.radius;
+  }
+  d3.svg.diagonal = function() {
+    var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection;
+    function diagonal(d, i) {
+      var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, {
+        x: p0.x,
+        y: m
+      }, {
+        x: p3.x,
+        y: m
+      }, p3 ];
+      p = p.map(projection);
+      return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3];
+    }
+    diagonal.source = function(x) {
+      if (!arguments.length) return source;
+      source = d3_functor(x);
+      return diagonal;
+    };
+    diagonal.target = function(x) {
+      if (!arguments.length) return target;
+      target = d3_functor(x);
+      return diagonal;
+    };
+    diagonal.projection = function(x) {
+      if (!arguments.length) return projection;
+      projection = x;
+      return diagonal;
+    };
+    return diagonal;
+  };
+  function d3_svg_diagonalProjection(d) {
+    return [ d.x, d.y ];
+  }
+  d3.svg.diagonal.radial = function() {
+    var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection;
+    diagonal.projection = function(x) {
+      return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection;
+    };
+    return diagonal;
+  };
+  function d3_svg_diagonalRadialProjection(projection) {
+    return function() {
+      var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfÏ;
+      return [ r * Math.cos(a), r * Math.sin(a) ];
+    };
+  }
+  d3.svg.symbol = function() {
+    var type = d3_svg_symbolType, size = d3_svg_symbolSize;
+    function symbol(d, i) {
+      return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i));
+    }
+    symbol.type = function(x) {
+      if (!arguments.length) return type;
+      type = d3_functor(x);
+      return symbol;
+    };
+    symbol.size = function(x) {
+      if (!arguments.length) return size;
+      size = d3_functor(x);
+      return symbol;
+    };
+    return symbol;
+  };
+  function d3_svg_symbolSize() {
+    return 64;
+  }
+  function d3_svg_symbolType() {
+    return "circle";
+  }
+  function d3_svg_symbolCircle(size) {
+    var r = Math.sqrt(size / Ï);
+    return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z";
+  }
+  var d3_svg_symbols = d3.map({
+    circle: d3_svg_symbolCircle,
+    cross: function(size) {
+      var r = Math.sqrt(size / 5) / 2;
+      return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z";
+    },
+    diamond: function(size) {
+      var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30;
+      return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z";
+    },
+    square: function(size) {
+      var r = Math.sqrt(size) / 2;
+      return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z";
+    },
+    "triangle-down": function(size) {
+      var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
+      return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z";
+    },
+    "triangle-up": function(size) {
+      var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
+      return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z";
+    }
+  });
+  d3.svg.symbolTypes = d3_svg_symbols.keys();
+  var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians);
+  d3_selectionPrototype.transition = function(name) {
+    var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || {
+      time: Date.now(),
+      ease: d3_ease_cubicInOut,
+      delay: 0,
+      duration: 250
+    };
+    for (var j = -1, m = this.length; ++j < m; ) {
+      subgroups.push(subgroup = []);
+      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
+        if (node = group[i]) d3_transitionNode(node, i, ns, id, transition);
+        subgroup.push(node);
+      }
+    }
+    return d3_transition(subgroups, ns, id);
+  };
+  d3_selectionPrototype.interrupt = function(name) {
+    return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name)));
+  };
+  var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace());
+  function d3_selection_interruptNS(ns) {
+    return function() {
+      var lock, activeId, active;
+      if ((lock = this[ns]) && (active = lock[activeId = lock.active])) {
+        active.timer.c = null;
+        active.timer.t = NaN;
+        if (--lock.count) delete lock[activeId]; else delete this[ns];
+        lock.active += .5;
+        active.event && active.event.interrupt.call(this, this.__data__, active.index);
+      }
+    };
+  }
+  function d3_transition(groups, ns, id) {
+    d3_subclass(groups, d3_transitionPrototype);
+    groups.namespace = ns;
+    groups.id = id;
+    return groups;
+  }
+  var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit;
+  d3_transitionPrototype.call = d3_selectionPrototype.call;
+  d3_transitionPrototype.empty = d3_selectionPrototype.empty;
+  d3_transitionPrototype.node = d3_selectionPrototype.node;
+  d3_transitionPrototype.size = d3_selectionPrototype.size;
+  d3.transition = function(selection, name) {
+    return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection);
+  };
+  d3.transition.prototype = d3_transitionPrototype;
+  d3_transitionPrototype.select = function(selector) {
+    var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node;
+    selector = d3_selection_selector(selector);
+    for (var j = -1, m = this.length; ++j < m; ) {
+      subgroups.push(subgroup = []);
+      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
+        if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) {
+          if ("__data__" in node) subnode.__data__ = node.__data__;
+          d3_transitionNode(subnode, i, ns, id, node[ns][id]);
+          subgroup.push(subnode);
+        } else {
+          subgroup.push(null);
+        }
+      }
+    }
+    return d3_transition(subgroups, ns, id);
+  };
+  d3_transitionPrototype.selectAll = function(selector) {
+    var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition;
+    selector = d3_selection_selectorAll(selector);
+    for (var j = -1, m = this.length; ++j < m; ) {
+      for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
+        if (node = group[i]) {
+          transition = node[ns][id];
+          subnodes = selector.call(node, node.__data__, i, j);
+          subgroups.push(subgroup = []);
+          for (var k = -1, o = subnodes.length; ++k < o; ) {
+            if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition);
+            subgroup.push(subnode);
+          }
+        }
+      }
+    }
+    return d3_transition(subgroups, ns, id);
+  };
+  d3_transitionPrototype.filter = function(filter) {
+    var subgroups = [], subgroup, group, node;
+    if (typeof filter !== "function") filter = d3_selection_filter(filter);
+    for (var j = 0, m = this.length; j < m; j++) {
+      subgroups.push(subgroup = []);
+      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
+        if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
+          subgroup.push(node);
+        }
+      }
+    }
+    return d3_transition(subgroups, this.namespace, this.id);
+  };
+  d3_transitionPrototype.tween = function(name, tween) {
+    var id = this.id, ns = this.namespace;
+    if (arguments.length < 2) return this.node()[ns][id].tween.get(name);
+    return d3_selection_each(this, tween == null ? function(node) {
+      node[ns][id].tween.remove(name);
+    } : function(node) {
+      node[ns][id].tween.set(name, tween);
+    });
+  };
+  function d3_transition_tween(groups, name, value, tween) {
+    var id = groups.id, ns = groups.namespace;
+    return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) {
+      node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j)));
+    } : (value = tween(value), function(node) {
+      node[ns][id].tween.set(name, value);
+    }));
+  }
+  d3_transitionPrototype.attr = function(nameNS, value) {
+    if (arguments.length < 2) {
+      for (value in nameNS) this.attr(value, nameNS[value]);
+      return this;
+    }
+    var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS);
+    function attrNull() {
+      this.removeAttribute(name);
+    }
+    function attrNullNS() {
+      this.removeAttributeNS(name.space, name.local);
+    }
+    function attrTween(b) {
+      return b == null ? attrNull : (b += "", function() {
+        var a = this.getAttribute(name), i;
+        return a !== b && (i = interpolate(a, b), function(t) {
+          this.setAttribute(name, i(t));
+        });
+      });
+    }
+    function attrTweenNS(b) {
+      return b == null ? attrNullNS : (b += "", function() {
+        var a = this.getAttributeNS(name.space, name.local), i;
+        return a !== b && (i = interpolate(a, b), function(t) {
+          this.setAttributeNS(name.space, name.local, i(t));
+        });
+      });
+    }
+    return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween);
+  };
+  d3_transitionPrototype.attrTween = function(nameNS, tween) {
+    var name = d3.ns.qualify(nameNS);
+    function attrTween(d, i) {
+      var f = tween.call(this, d, i, this.getAttribute(name));
+      return f && function(t) {
+        this.setAttribute(name, f(t));
+      };
+    }
+    function attrTweenNS(d, i) {
+      var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local));
+      return f && function(t) {
+        this.setAttributeNS(name.space, name.local, f(t));
+      };
+    }
+    return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween);
+  };
+  d3_transitionPrototype.style = function(name, value, priority) {
+    var n = arguments.length;
+    if (n < 3) {
+      if (typeof name !== "string") {
+        if (n < 2) value = "";
+        for (priority in name) this.style(priority, name[priority], value);
+        return this;
+      }
+      priority = "";
+    }
+    function styleNull() {
+      this.style.removeProperty(name);
+    }
+    function styleString(b) {
+      return b == null ? styleNull : (b += "", function() {
+        var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i;
+        return a !== b && (i = d3_interpolate(a, b), function(t) {
+          this.style.setProperty(name, i(t), priority);
+        });
+      });
+    }
+    return d3_transition_tween(this, "style." + name, value, styleString);
+  };
+  d3_transitionPrototype.styleTween = function(name, tween, priority) {
+    if (arguments.length < 3) priority = "";
+    function styleTween(d, i) {
+      var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name));
+      return f && function(t) {
+        this.style.setProperty(name, f(t), priority);
+      };
+    }
+    return this.tween("style." + name, styleTween);
+  };
+  d3_transitionPrototype.text = function(value) {
+    return d3_transition_tween(this, "text", value, d3_transition_text);
+  };
+  function d3_transition_text(b) {
+    if (b == null) b = "";
+    return function() {
+      this.textContent = b;
+    };
+  }
+  d3_transitionPrototype.remove = function() {
+    var ns = this.namespace;
+    return this.each("end.transition", function() {
+      var p;
+      if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this);
+    });
+  };
+  d3_transitionPrototype.ease = function(value) {
+    var id = this.id, ns = this.namespace;
+    if (arguments.length < 1) return this.node()[ns][id].ease;
+    if (typeof value !== "function") value = d3.ease.apply(d3, arguments);
+    return d3_selection_each(this, function(node) {
+      node[ns][id].ease = value;
+    });
+  };
+  d3_transitionPrototype.delay = function(value) {
+    var id = this.id, ns = this.namespace;
+    if (arguments.length < 1) return this.node()[ns][id].delay;
+    return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
+      node[ns][id].delay = +value.call(node, node.__data__, i, j);
+    } : (value = +value, function(node) {
+      node[ns][id].delay = value;
+    }));
+  };
+  d3_transitionPrototype.duration = function(value) {
+    var id = this.id, ns = this.namespace;
+    if (arguments.length < 1) return this.node()[ns][id].duration;
+    return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
+      node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j));
+    } : (value = Math.max(1, value), function(node) {
+      node[ns][id].duration = value;
+    }));
+  };
+  d3_transitionPrototype.each = function(type, listener) {
+    var id = this.id, ns = this.namespace;
+    if (arguments.length < 2) {
+      var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId;
+      try {
+        d3_transitionInheritId = id;
+        d3_selection_each(this, function(node, i, j) {
+          d3_transitionInherit = node[ns][id];
+          type.call(node, node.__data__, i, j);
+        });
+      } finally {
+        d3_transitionInherit = inherit;
+        d3_transitionInheritId = inheritId;
+      }
+    } else {
+      d3_selection_each(this, function(node) {
+        var transition = node[ns][id];
+        (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener);
+      });
+    }
+    return this;
+  };
+  d3_transitionPrototype.transition = function() {
+    var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition;
+    for (var j = 0, m = this.length; j < m; j++) {
+      subgroups.push(subgroup = []);
+      for (var group = this[j], i = 0, n = group.length; i < n; i++) {
+        if (node = group[i]) {
+          transition = node[ns][id0];
+          d3_transitionNode(node, i, ns, id1, {
+            time: transition.time,
+            ease: transition.ease,
+            delay: transition.delay + transition.duration,
+            duration: transition.duration
+          });
+        }
+        subgroup.push(node);
+      }
+    }
+    return d3_transition(subgroups, ns, id1);
+  };
+  function d3_transitionNamespace(name) {
+    return name == null ? "__transition__" : "__transition_" + name + "__";
+  }
+  function d3_transitionNode(node, i, ns, id, inherit) {
+    var lock = node[ns] || (node[ns] = {
+      active: 0,
+      count: 0
+    }), transition = lock[id], time, timer, duration, ease, tweens;
+    function schedule(elapsed) {
+      var delay = transition.delay;
+      timer.t = delay + time;
+      if (delay <= elapsed) return start(elapsed - delay);
+      timer.c = start;
+    }
+    function start(elapsed) {
+      var activeId = lock.active, active = lock[activeId];
+      if (active) {
+        active.timer.c = null;
+        active.timer.t = NaN;
+        --lock.count;
+        delete lock[activeId];
+        active.event && active.event.interrupt.call(node, node.__data__, active.index);
+      }
+      for (var cancelId in lock) {
+        if (+cancelId < id) {
+          var cancel = lock[cancelId];
+          cancel.timer.c = null;
+          cancel.timer.t = NaN;
+          --lock.count;
+          delete lock[cancelId];
+        }
+      }
+      timer.c = tick;
+      d3_timer(function() {
+        if (timer.c && tick(elapsed || 1)) {
+          timer.c = null;
+          timer.t = NaN;
+        }
+        return 1;
+      }, 0, time);
+      lock.active = id;
+      transition.event && transition.event.start.call(node, node.__data__, i);
+      tweens = [];
+      transition.tween.forEach(function(key, value) {
+        if (value = value.call(node, node.__data__, i)) {
+          tweens.push(value);
+        }
+      });
+      ease = transition.ease;
+      duration = transition.duration;
+    }
+    function tick(elapsed) {
+      var t = elapsed / duration, e = ease(t), n = tweens.length;
+      while (n > 0) {
+        tweens[--n].call(node, e);
+      }
+      if (t >= 1) {
+        transition.event && transition.event.end.call(node, node.__data__, i);
+        if (--lock.count) delete lock[id]; else delete node[ns];
+        return 1;
+      }
+    }
+    if (!transition) {
+      time = inherit.time;
+      timer = d3_timer(schedule, 0, time);
+      transition = lock[id] = {
+        tween: new d3_Map(),
+        time: time,
+        timer: timer,
+        delay: inherit.delay,
+        duration: inherit.duration,
+        ease: inherit.ease,
+        index: i
+      };
+      inherit = null;
+      ++lock.count;
+    }
+  }
+  d3.svg.axis = function() {
+    var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_;
+    function axis(g) {
+      g.each(function() {
+        var g = d3.select(this);
+        var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy();
+        var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", Îµ), tickExit = d3.transition(tick.exit()).style("opacity", Îµ).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform;
+        var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"), 
+        d3.transition(path));
+        tickEnter.append("line");
+        tickEnter.append("text");
+        var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2;
+        if (orient === "bottom" || orient === "top") {
+          tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2";
+          text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle");
+          pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize);
+        } else {
+          tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2";
+          text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start");
+          pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize);
+        }
+        lineEnter.attr(y2, sign * innerTickSize);
+        textEnter.attr(y1, sign * tickSpacing);
+        lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize);
+        textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing);
+        if (scale1.rangeBand) {
+          var x = scale1, dx = x.rangeBand() / 2;
+          scale0 = scale1 = function(d) {
+            return x(d) + dx;
+          };
+        } else if (scale0.rangeBand) {
+          scale0 = scale1;
+        } else {
+          tickExit.call(tickTransform, scale1, scale0);
+        }
+        tickEnter.call(tickTransform, scale0, scale1);
+        tickUpdate.call(tickTransform, scale1, scale1);
+      });
+    }
+    axis.scale = function(x) {
+      if (!arguments.length) return scale;
+      scale = x;
+      return axis;
+    };
+    axis.orient = function(x) {
+      if (!arguments.length) return orient;
+      orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient;
+      return axis;
+    };
+    axis.ticks = function() {
+      if (!arguments.length) return tickArguments_;
+      tickArguments_ = d3_array(arguments);
+      return axis;
+    };
+    axis.tickValues = function(x) {
+      if (!arguments.length) return tickValues;
+      tickValues = x;
+      return axis;
+    };
+    axis.tickFormat = function(x) {
+      if (!arguments.length) return tickFormat_;
+      tickFormat_ = x;
+      return axis;
+    };
+    axis.tickSize = function(x) {
+      var n = arguments.length;
+      if (!n) return innerTickSize;
+      innerTickSize = +x;
+      outerTickSize = +arguments[n - 1];
+      return axis;
+    };
+    axis.innerTickSize = function(x) {
+      if (!arguments.length) return innerTickSize;
+      innerTickSize = +x;
+      return axis;
+    };
+    axis.outerTickSize = function(x) {
+      if (!arguments.length) return outerTickSize;
+      outerTickSize = +x;
+      return axis;
+    };
+    axis.tickPadding = function(x) {
+      if (!arguments.length) return tickPadding;
+      tickPadding = +x;
+      return axis;
+    };
+    axis.tickSubdivide = function() {
+      return arguments.length && axis;
+    };
+    return axis;
+  };
+  var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = {
+    top: 1,
+    right: 1,
+    bottom: 1,
+    left: 1
+  };
+  function d3_svg_axisX(selection, x0, x1) {
+    selection.attr("transform", function(d) {
+      var v0 = x0(d);
+      return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)";
+    });
+  }
+  function d3_svg_axisY(selection, y0, y1) {
+    selection.attr("transform", function(d) {
+      var v0 = y0(d);
+      return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")";
+    });
+  }
+  d3.svg.brush = function() {
+    var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0];
+    function brush(g) {
+      g.each(function() {
+        var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart);
+        var background = g.selectAll(".background").data([ 0 ]);
+        background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair");
+        g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move");
+        var resize = g.selectAll(".resize").data(resizes, d3_identity);
+        resize.exit().remove();
+        resize.enter().append("g").attr("class", function(d) {
+          return "resize " + d;
+        }).style("cursor", function(d) {
+          return d3_svg_brushCursor[d];
+        }).append("rect").attr("x", function(d) {
+          return /[ew]$/.test(d) ? -3 : null;
+        }).attr("y", function(d) {
+          return /^[ns]/.test(d) ? -3 : null;
+        }).attr("width", 6).attr("height", 6).style("visibility", "hidden");
+        resize.style("display", brush.empty() ? "none" : null);
+        var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range;
+        if (x) {
+          range = d3_scaleRange(x);
+          backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]);
+          redrawX(gUpdate);
+        }
+        if (y) {
+          range = d3_scaleRange(y);
+          backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]);
+          redrawY(gUpdate);
+        }
+        redraw(gUpdate);
+      });
+    }
+    brush.event = function(g) {
+      g.each(function() {
+        var event_ = event.of(this, arguments), extent1 = {
+          x: xExtent,
+          y: yExtent,
+          i: xExtentDomain,
+          j: yExtentDomain
+        }, extent0 = this.__chart__ || extent1;
+        this.__chart__ = extent1;
+        if (d3_transitionInheritId) {
+          d3.select(this).transition().each("start.brush", function() {
+            xExtentDomain = extent0.i;
+            yExtentDomain = extent0.j;
+            xExtent = extent0.x;
+            yExtent = extent0.y;
+            event_({
+              type: "brushstart"
+            });
+          }).tween("brush:brush", function() {
+            var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y);
+            xExtentDomain = yExtentDomain = null;
+            return function(t) {
+              xExtent = extent1.x = xi(t);
+              yExtent = extent1.y = yi(t);
+              event_({
+                type: "brush",
+                mode: "resize"
+              });
+            };
+          }).each("end.brush", function() {
+            xExtentDomain = extent1.i;
+            yExtentDomain = extent1.j;
+            event_({
+              type: "brush",
+              mode: "resize"
+            });
+            event_({
+              type: "brushend"
+            });
+          });
+        } else {
+          event_({
+            type: "brushstart"
+          });
+          event_({
+            type: "brush",
+            mode: "resize"
+          });
+          event_({
+            type: "brushend"
+          });
+        }
+      });
+    };
+    function redraw(g) {
+      g.selectAll(".resize").attr("transform", function(d) {
+        return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")";
+      });
+    }
+    function redrawX(g) {
+      g.select(".extent").attr("x", xExtent[0]);
+      g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]);
+    }
+    function redrawY(g) {
+      g.select(".extent").attr("y", yExtent[0]);
+      g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]);
+    }
+    function brushstart() {
+      var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset;
+      var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup);
+      if (d3.event.changedTouches) {
+        w.on("touchmove.brush", brushmove).on("touchend.brush", brushend);
+      } else {
+        w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend);
+      }
+      g.interrupt().selectAll("*").interrupt();
+      if (dragging) {
+        origin[0] = xExtent[0] - origin[0];
+        origin[1] = yExtent[0] - origin[1];
+      } else if (resizing) {
+        var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing);
+        offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ];
+        origin[0] = xExtent[ex];
+        origin[1] = yExtent[ey];
+      } else if (d3.event.altKey) center = origin.slice();
+      g.style("pointer-events", "none").selectAll(".resize").style("display", null);
+      d3.select("body").style("cursor", eventTarget.style("cursor"));
+      event_({
+        type: "brushstart"
+      });
+      brushmove();
+      function keydown() {
+        if (d3.event.keyCode == 32) {
+          if (!dragging) {
+            center = null;
+            origin[0] -= xExtent[1];
+            origin[1] -= yExtent[1];
+            dragging = 2;
+          }
+          d3_eventPreventDefault();
+        }
+      }
+      function keyup() {
+        if (d3.event.keyCode == 32 && dragging == 2) {
+          origin[0] += xExtent[1];
+          origin[1] += yExtent[1];
+          dragging = 0;
+          d3_eventPreventDefault();
+        }
+      }
+      function brushmove() {
+        var point = d3.mouse(target), moved = false;
+        if (offset) {
+          point[0] += offset[0];
+          point[1] += offset[1];
+        }
+        if (!dragging) {
+          if (d3.event.altKey) {
+            if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ];
+            origin[0] = xExtent[+(point[0] < center[0])];
+            origin[1] = yExtent[+(point[1] < center[1])];
+          } else center = null;
+        }
+        if (resizingX && move1(point, x, 0)) {
+          redrawX(g);
+          moved = true;
+        }
+        if (resizingY && move1(point, y, 1)) {
+          redrawY(g);
+          moved = true;
+        }
+        if (moved) {
+          redraw(g);
+          event_({
+            type: "brush",
+            mode: dragging ? "move" : "resize"
+          });
+        }
+      }
+      function move1(point, scale, i) {
+        var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max;
+        if (dragging) {
+          r0 -= position;
+          r1 -= size + position;
+        }
+        min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i];
+        if (dragging) {
+          max = (min += position) + size;
+        } else {
+          if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min));
+          if (position < min) {
+            max = min;
+            min = position;
+          } else {
+            max = position;
+          }
+        }
+        if (extent[0] != min || extent[1] != max) {
+          if (i) yExtentDomain = null; else xExtentDomain = null;
+          extent[0] = min;
+          extent[1] = max;
+          return true;
+        }
+      }
+      function brushend() {
+        brushmove();
+        g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null);
+        d3.select("body").style("cursor", null);
+        w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null);
+        dragRestore();
+        event_({
+          type: "brushend"
+        });
+      }
+    }
+    brush.x = function(z) {
+      if (!arguments.length) return x;
+      x = z;
+      resizes = d3_svg_brushResizes[!x << 1 | !y];
+      return brush;
+    };
+    brush.y = function(z) {
+      if (!arguments.length) return y;
+      y = z;
+      resizes = d3_svg_brushResizes[!x << 1 | !y];
+      return brush;
+    };
+    brush.clamp = function(z) {
+      if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null;
+      if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z;
+      return brush;
+    };
+    brush.extent = function(z) {
+      var x0, x1, y0, y1, t;
+      if (!arguments.length) {
+        if (x) {
+          if (xExtentDomain) {
+            x0 = xExtentDomain[0], x1 = xExtentDomain[1];
+          } else {
+            x0 = xExtent[0], x1 = xExtent[1];
+            if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1);
+            if (x1 < x0) t = x0, x0 = x1, x1 = t;
+          }
+        }
+        if (y) {
+          if (yExtentDomain) {
+            y0 = yExtentDomain[0], y1 = yExtentDomain[1];
+          } else {
+            y0 = yExtent[0], y1 = yExtent[1];
+            if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1);
+            if (y1 < y0) t = y0, y0 = y1, y1 = t;
+          }
+        }
+        return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ];
+      }
+      if (x) {
+        x0 = z[0], x1 = z[1];
+        if (y) x0 = x0[0], x1 = x1[0];
+        xExtentDomain = [ x0, x1 ];
+        if (x.invert) x0 = x(x0), x1 = x(x1);
+        if (x1 < x0) t = x0, x0 = x1, x1 = t;
+        if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ];
+      }
+      if (y) {
+        y0 = z[0], y1 = z[1];
+        if (x) y0 = y0[1], y1 = y1[1];
+        yExtentDomain = [ y0, y1 ];
+        if (y.invert) y0 = y(y0), y1 = y(y1);
+        if (y1 < y0) t = y0, y0 = y1, y1 = t;
+        if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ];
+      }
+      return brush;
+    };
+    brush.clear = function() {
+      if (!brush.empty()) {
+        xExtent = [ 0, 0 ], yExtent = [ 0, 0 ];
+        xExtentDomain = yExtentDomain = null;
+      }
+      return brush;
+    };
+    brush.empty = function() {
+      return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1];
+    };
+    return d3.rebind(brush, event, "on");
+  };
+  var d3_svg_brushCursor = {
+    n: "ns-resize",
+    e: "ew-resize",
+    s: "ns-resize",
+    w: "ew-resize",
+    nw: "nwse-resize",
+    ne: "nesw-resize",
+    se: "nwse-resize",
+    sw: "nesw-resize"
+  };
+  var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ];
+  var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat;
+  var d3_time_formatUtc = d3_time_format.utc;
+  var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ");
+  d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso;
+  function d3_time_formatIsoNative(date) {
+    return date.toISOString();
+  }
+  d3_time_formatIsoNative.parse = function(string) {
+    var date = new Date(string);
+    return isNaN(date) ? null : date;
+  };
+  d3_time_formatIsoNative.toString = d3_time_formatIso.toString;
+  d3_time.second = d3_time_interval(function(date) {
+    return new d3_date(Math.floor(date / 1e3) * 1e3);
+  }, function(date, offset) {
+    date.setTime(date.getTime() + Math.floor(offset) * 1e3);
+  }, function(date) {
+    return date.getSeconds();
+  });
+  d3_time.seconds = d3_time.second.range;
+  d3_time.seconds.utc = d3_time.second.utc.range;
+  d3_time.minute = d3_time_interval(function(date) {
+    return new d3_date(Math.floor(date / 6e4) * 6e4);
+  }, function(date, offset) {
+    date.setTime(date.getTime() + Math.floor(offset) * 6e4);
+  }, function(date) {
+    return date.getMinutes();
+  });
+  d3_time.minutes = d3_time.minute.range;
+  d3_time.minutes.utc = d3_time.minute.utc.range;
+  d3_time.hour = d3_time_interval(function(date) {
+    var timezone = date.getTimezoneOffset() / 60;
+    return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5);
+  }, function(date, offset) {
+    date.setTime(date.getTime() + Math.floor(offset) * 36e5);
+  }, function(date) {
+    return date.getHours();
+  });
+  d3_time.hours = d3_time.hour.range;
+  d3_time.hours.utc = d3_time.hour.utc.range;
+  d3_time.month = d3_time_interval(function(date) {
+    date = d3_time.day(date);
+    date.setDate(1);
+    return date;
+  }, function(date, offset) {
+    date.setMonth(date.getMonth() + offset);
+  }, function(date) {
+    return date.getMonth();
+  });
+  d3_time.months = d3_time.month.range;
+  d3_time.months.utc = d3_time.month.utc.range;
+  function d3_time_scale(linear, methods, format) {
+    function scale(x) {
+      return linear(x);
+    }
+    scale.invert = function(x) {
+      return d3_time_scaleDate(linear.invert(x));
+    };
+    scale.domain = function(x) {
+      if (!arguments.length) return linear.domain().map(d3_time_scaleDate);
+      linear.domain(x);
+      return scale;
+    };
+    function tickMethod(extent, count) {
+      var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target);
+      return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) {
+        return d / 31536e6;
+      }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i];
+    }
+    scale.nice = function(interval, skip) {
+      var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval);
+      if (method) interval = method[0], skip = method[1];
+      function skipped(date) {
+        return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length;
+      }
+      return scale.domain(d3_scale_nice(domain, skip > 1 ? {
+        floor: function(date) {
+          while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1);
+          return date;
+        },
+        ceil: function(date) {
+          while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1);
+          return date;
+        }
+      } : interval));
+    };
+    scale.ticks = function(interval, skip) {
+      var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ {
+        range: interval
+      }, skip ];
+      if (method) interval = method[0], skip = method[1];
+      return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip);
+    };
+    scale.tickFormat = function() {
+      return format;
+    };
+    scale.copy = function() {
+      return d3_time_scale(linear.copy(), methods, format);
+    };
+    return d3_scale_linearRebind(scale, linear);
+  }
+  function d3_time_scaleDate(t) {
+    return new Date(t);
+  }
+  var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ];
+  var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ];
+  var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) {
+    return d.getMilliseconds();
+  } ], [ ":%S", function(d) {
+    return d.getSeconds();
+  } ], [ "%I:%M", function(d) {
+    return d.getMinutes();
+  } ], [ "%I %p", function(d) {
+    return d.getHours();
+  } ], [ "%a %d", function(d) {
+    return d.getDay() && d.getDate() != 1;
+  } ], [ "%b %d", function(d) {
+    return d.getDate() != 1;
+  } ], [ "%B", function(d) {
+    return d.getMonth();
+  } ], [ "%Y", d3_true ] ]);
+  var d3_time_scaleMilliseconds = {
+    range: function(start, stop, step) {
+      return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate);
+    },
+    floor: d3_identity,
+    ceil: d3_identity
+  };
+  d3_time_scaleLocalMethods.year = d3_time.year;
+  d3_time.scale = function() {
+    return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat);
+  };
+  var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) {
+    return [ m[0].utc, m[1] ];
+  });
+  var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) {
+    return d.getUTCMilliseconds();
+  } ], [ ":%S", function(d) {
+    return d.getUTCSeconds();
+  } ], [ "%I:%M", function(d) {
+    return d.getUTCMinutes();
+  } ], [ "%I %p", function(d) {
+    return d.getUTCHours();
+  } ], [ "%a %d", function(d) {
+    return d.getUTCDay() && d.getUTCDate() != 1;
+  } ], [ "%b %d", function(d) {
+    return d.getUTCDate() != 1;
+  } ], [ "%B", function(d) {
+    return d.getUTCMonth();
+  } ], [ "%Y", d3_true ] ]);
+  d3_time_scaleUtcMethods.year = d3_time.year.utc;
+  d3_time.scale.utc = function() {
+    return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat);
+  };
+  d3.text = d3_xhrType(function(request) {
+    return request.responseText;
+  });
+  d3.json = function(url, callback) {
+    return d3_xhr(url, "application/json", d3_json, callback);
+  };
+  function d3_json(request) {
+    return JSON.parse(request.responseText);
+  }
+  d3.html = function(url, callback) {
+    return d3_xhr(url, "text/html", d3_html, callback);
+  };
+  function d3_html(request) {
+    var range = d3_document.createRange();
+    range.selectNode(d3_document.body);
+    return range.createContextualFragment(request.responseText);
+  }
+  d3.xml = d3_xhrType(function(request) {
+    return request.responseXML;
+  });
+  if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3;
+}();
+},{}],71:[function(require,module,exports){
+"use strict"
+
+var ch = require("incremental-convex-hull")
+var uniq = require("uniq")
+
+module.exports = triangulate
+
+function LiftedPoint(p, i) {
+  this.point = p
+  this.index = i
+}
+
+function compareLifted(a, b) {
+  var ap = a.point
+  var bp = b.point
+  var d = ap.length
+  for(var i=0; i<d; ++i) {
+    var s = bp[i] - ap[i]
+    if(s) {
+      return s
+    }
+  }
+  return 0
+}
+
+function triangulate1D(n, points, includePointAtInfinity) {
+  if(n === 1) {
+    if(includePointAtInfinity) {
+      return [ [-1, 0] ]
+    } else {
+      return []
+    }
+  }
+  var lifted = points.map(function(p, i) {
+    return [ p[0], i ]
+  })
+  lifted.sort(function(a,b) {
+    return a[0] - b[0]
+  })
+  var cells = new Array(n - 1)
+  for(var i=1; i<n; ++i) {
+    var a = lifted[i-1]
+    var b = lifted[i]
+    cells[i-1] = [ a[1], b[1] ]
+  }
+  if(includePointAtInfinity) {
+    cells.push(
+      [ -1, cells[0][1], ],
+      [ cells[n-1][1], -1 ])
+  }
+  return cells
+}
+
+function triangulate(points, includePointAtInfinity) {
+  var n = points.length
+  if(n === 0) {
+    return []
+  }
+  
+  var d = points[0].length
+  if(d < 1) {
+    return []
+  }
+
+  //Special case:  For 1D we can just sort the points
+  if(d === 1) {
+    return triangulate1D(n, points, includePointAtInfinity)
+  }
+  
+  //Lift points, sort
+  var lifted = new Array(n)
+  var upper = 1.0
+  for(var i=0; i<n; ++i) {
+    var p = points[i]
+    var x = new Array(d+1)
+    var l = 0.0
+    for(var j=0; j<d; ++j) {
+      var v = p[j]
+      x[j] = v
+      l += v * v
+    }
+    x[d] = l
+    lifted[i] = new LiftedPoint(x, i)
+    upper = Math.max(l, upper)
+  }
+  uniq(lifted, compareLifted)
+  
+  //Double points
+  n = lifted.length
+
+  //Create new list of points
+  var dpoints = new Array(n + d + 1)
+  var dindex = new Array(n + d + 1)
+
+  //Add steiner points at top
+  var u = (d+1) * (d+1) * upper
+  var y = new Array(d+1)
+  for(var i=0; i<=d; ++i) {
+    y[i] = 0.0
+  }
+  y[d] = u
+
+  dpoints[0] = y.slice()
+  dindex[0] = -1
+
+  for(var i=0; i<=d; ++i) {
+    var x = y.slice()
+    x[i] = 1
+    dpoints[i+1] = x
+    dindex[i+1] = -1
+  }
+
+  //Copy rest of the points over
+  for(var i=0; i<n; ++i) {
+    var h = lifted[i]
+    dpoints[i + d + 1] = h.point
+    dindex[i + d + 1] =  h.index
+  }
+
+  //Construct convex hull
+  var hull = ch(dpoints, false)
+  if(includePointAtInfinity) {
+    hull = hull.filter(function(cell) {
+      var count = 0
+      for(var j=0; j<=d; ++j) {
+        var v = dindex[cell[j]]
+        if(v < 0) {
+          if(++count >= 2) {
+            return false
+          }
+        }
+        cell[j] = v
+      }
+      return true
+    })
+  } else {
+    hull = hull.filter(function(cell) {
+      for(var i=0; i<=d; ++i) {
+        var v = dindex[cell[i]]
+        if(v < 0) {
+          return false
+        }
+        cell[i] = v
+      }
+      return true
+    })
+  }
+
+  if(d & 1) {
+    for(var i=0; i<hull.length; ++i) {
+      var h = hull[i]
+      var x = h[0]
+      h[0] = h[1]
+      h[1] = x
+    }
+  }
+
+  return hull
+}
+},{"incremental-convex-hull":191,"uniq":234}],72:[function(require,module,exports){
+"use strict"
+
+function dupe_array(count, value, i) {
+  var c = count[i]|0
+  if(c <= 0) {
+    return []
+  }
+  var result = new Array(c), j
+  if(i === count.length-1) {
+    for(j=0; j<c; ++j) {
+      result[j] = value
+    }
+  } else {
+    for(j=0; j<c; ++j) {
+      result[j] = dupe_array(count, value, i+1)
+    }
+  }
+  return result
+}
+
+function dupe_number(count, value) {
+  var result, i
+  result = new Array(count)
+  for(i=0; i<count; ++i) {
+    result[i] = value
+  }
+  return result
+}
+
+function dupe(count, value) {
+  if(typeof value === "undefined") {
+    value = 0
+  }
+  switch(typeof count) {
+    case "number":
+      if(count > 0) {
+        return dupe_number(count|0, value)
+      }
+    break
+    case "object":
+      if(typeof (count.length) === "number") {
+        return dupe_array(count, value, 0)
+      }
+    break
+  }
+  return []
+}
+
+module.exports = dupe
+},{}],73:[function(require,module,exports){
+(function (process,global){
+/*!
+ * @overview es6-promise - a tiny implementation of Promises/A+.
+ * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
+ * @license   Licensed under MIT license
+ *            See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
+ * @version   3.0.2
+ */
+
+(function() {
+    "use strict";
+    function lib$es6$promise$utils$$objectOrFunction(x) {
+      return typeof x === 'function' || (typeof x === 'object' && x !== null);
+    }
+
+    function lib$es6$promise$utils$$isFunction(x) {
+      return typeof x === 'function';
+    }
+
+    function lib$es6$promise$utils$$isMaybeThenable(x) {
+      return typeof x === 'object' && x !== null;
+    }
+
+    var lib$es6$promise$utils$$_isArray;
+    if (!Array.isArray) {
+      lib$es6$promise$utils$$_isArray = function (x) {
+        return Object.prototype.toString.call(x) === '[object Array]';
+      };
+    } else {
+      lib$es6$promise$utils$$_isArray = Array.isArray;
+    }
+
+    var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
+    var lib$es6$promise$asap$$len = 0;
+    var lib$es6$promise$asap$$toString = {}.toString;
+    var lib$es6$promise$asap$$vertxNext;
+    var lib$es6$promise$asap$$customSchedulerFn;
+
+    var lib$es6$promise$asap$$asap = function asap(callback, arg) {
+      lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
+      lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
+      lib$es6$promise$asap$$len += 2;
+      if (lib$es6$promise$asap$$len === 2) {
+        // If len is 2, that means that we need to schedule an async flush.
+        // If additional callbacks are queued before the queue is flushed, they
+        // will be processed by this flush that we are scheduling.
+        if (lib$es6$promise$asap$$customSchedulerFn) {
+          lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
+        } else {
+          lib$es6$promise$asap$$scheduleFlush();
+        }
+      }
+    }
+
+    function lib$es6$promise$asap$$setScheduler(scheduleFn) {
+      lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
+    }
+
+    function lib$es6$promise$asap$$setAsap(asapFn) {
+      lib$es6$promise$asap$$asap = asapFn;
+    }
+
+    var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
+    var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
+    var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
+    var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
+
+    // test for web worker but not in IE10
+    var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
+      typeof importScripts !== 'undefined' &&
+      typeof MessageChannel !== 'undefined';
+
+    // node
+    function lib$es6$promise$asap$$useNextTick() {
+      // node version 0.10.x displays a deprecation warning when nextTick is used recursively
+      // see https://github.com/cujojs/when/issues/410 for details
+      return function() {
+        process.nextTick(lib$es6$promise$asap$$flush);
+      };
+    }
+
+    // vertx
+    function lib$es6$promise$asap$$useVertxTimer() {
+      return function() {
+        lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
+      };
+    }
+
+    function lib$es6$promise$asap$$useMutationObserver() {
+      var iterations = 0;
+      var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
+      var node = document.createTextNode('');
+      observer.observe(node, { characterData: true });
+
+      return function() {
+        node.data = (iterations = ++iterations % 2);
+      };
+    }
+
+    // web worker
+    function lib$es6$promise$asap$$useMessageChannel() {
+      var channel = new MessageChannel();
+      channel.port1.onmessage = lib$es6$promise$asap$$flush;
+      return function () {
+        channel.port2.postMessage(0);
+      };
+    }
+
+    function lib$es6$promise$asap$$useSetTimeout() {
+      return function() {
+        setTimeout(lib$es6$promise$asap$$flush, 1);
+      };
+    }
+
+    var lib$es6$promise$asap$$queue = new Array(1000);
+    function lib$es6$promise$asap$$flush() {
+      for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
+        var callback = lib$es6$promise$asap$$queue[i];
+        var arg = lib$es6$promise$asap$$queue[i+1];
+
+        callback(arg);
+
+        lib$es6$promise$asap$$queue[i] = undefined;
+        lib$es6$promise$asap$$queue[i+1] = undefined;
+      }
+
+      lib$es6$promise$asap$$len = 0;
+    }
+
+    function lib$es6$promise$asap$$attemptVertx() {
+      try {
+        var r = require;
+        var vertx = r('vertx');
+        lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
+        return lib$es6$promise$asap$$useVertxTimer();
+      } catch(e) {
+        return lib$es6$promise$asap$$useSetTimeout();
+      }
+    }
+
+    var lib$es6$promise$asap$$scheduleFlush;
+    // Decide what async method to use to triggering processing of queued callbacks:
+    if (lib$es6$promise$asap$$isNode) {
+      lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
+    } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
+      lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
+    } else if (lib$es6$promise$asap$$isWorker) {
+      lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
+    } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
+      lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
+    } else {
+      lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
+    }
+
+    function lib$es6$promise$$internal$$noop() {}
+
+    var lib$es6$promise$$internal$$PENDING   = void 0;
+    var lib$es6$promise$$internal$$FULFILLED = 1;
+    var lib$es6$promise$$internal$$REJECTED  = 2;
+
+    var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
+
+    function lib$es6$promise$$internal$$selfFulfillment() {
+      return new TypeError("You cannot resolve a promise with itself");
+    }
+
+    function lib$es6$promise$$internal$$cannotReturnOwn() {
+      return new TypeError('A promises callback cannot return that same promise.');
+    }
+
+    function lib$es6$promise$$internal$$getThen(promise) {
+      try {
+        return promise.then;
+      } catch(error) {
+        lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
+        return lib$es6$promise$$internal$$GET_THEN_ERROR;
+      }
+    }
+
+    function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
+      try {
+        then.call(value, fulfillmentHandler, rejectionHandler);
+      } catch(e) {
+        return e;
+      }
+    }
+
+    function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
+       lib$es6$promise$asap$$asap(function(promise) {
+        var sealed = false;
+        var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
+          if (sealed) { return; }
+          sealed = true;
+          if (thenable !== value) {
+            lib$es6$promise$$internal$$resolve(promise, value);
+          } else {
+            lib$es6$promise$$internal$$fulfill(promise, value);
+          }
+        }, function(reason) {
+          if (sealed) { return; }
+          sealed = true;
+
+          lib$es6$promise$$internal$$reject(promise, reason);
+        }, 'Settle: ' + (promise._label || ' unknown promise'));
+
+        if (!sealed && error) {
+          sealed = true;
+          lib$es6$promise$$internal$$reject(promise, error);
+        }
+      }, promise);
+    }
+
+    function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
+      if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
+        lib$es6$promise$$internal$$fulfill(promise, thenable._result);
+      } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
+        lib$es6$promise$$internal$$reject(promise, thenable._result);
+      } else {
+        lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
+          lib$es6$promise$$internal$$resolve(promise, value);
+        }, function(reason) {
+          lib$es6$promise$$internal$$reject(promise, reason);
+        });
+      }
+    }
+
+    function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
+      if (maybeThenable.constructor === promise.constructor) {
+        lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
+      } else {
+        var then = lib$es6$promise$$internal$$getThen(maybeThenable);
+
+        if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
+          lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
+        } else if (then === undefined) {
+          lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
+        } else if (lib$es6$promise$utils$$isFunction(then)) {
+          lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
+        } else {
+          lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
+        }
+      }
+    }
+
+    function lib$es6$promise$$internal$$resolve(promise, value) {
+      if (promise === value) {
+        lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
+      } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
+        lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
+      } else {
+        lib$es6$promise$$internal$$fulfill(promise, value);
+      }
+    }
+
+    function lib$es6$promise$$internal$$publishRejection(promise) {
+      if (promise._onerror) {
+        promise._onerror(promise._result);
+      }
+
+      lib$es6$promise$$internal$$publish(promise);
+    }
+
+    function lib$es6$promise$$internal$$fulfill(promise, value) {
+      if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
+
+      promise._result = value;
+      promise._state = lib$es6$promise$$internal$$FULFILLED;
+
+      if (promise._subscribers.length !== 0) {
+        lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
+      }
+    }
+
+    function lib$es6$promise$$internal$$reject(promise, reason) {
+      if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
+      promise._state = lib$es6$promise$$internal$$REJECTED;
+      promise._result = reason;
+
+      lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
+    }
+
+    function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
+      var subscribers = parent._subscribers;
+      var length = subscribers.length;
+
+      parent._onerror = null;
+
+      subscribers[length] = child;
+      subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
+      subscribers[length + lib$es6$promise$$internal$$REJECTED]  = onRejection;
+
+      if (length === 0 && parent._state) {
+        lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
+      }
+    }
+
+    function lib$es6$promise$$internal$$publish(promise) {
+      var subscribers = promise._subscribers;
+      var settled = promise._state;
+
+      if (subscribers.length === 0) { return; }
+
+      var child, callback, detail = promise._result;
+
+      for (var i = 0; i < subscribers.length; i += 3) {
+        child = subscribers[i];
+        callback = subscribers[i + settled];
+
+        if (child) {
+          lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
+        } else {
+          callback(detail);
+        }
+      }
+
+      promise._subscribers.length = 0;
+    }
+
+    function lib$es6$promise$$internal$$ErrorObject() {
+      this.error = null;
+    }
+
+    var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
+
+    function lib$es6$promise$$internal$$tryCatch(callback, detail) {
+      try {
+        return callback(detail);
+      } catch(e) {
+        lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
+        return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
+      }
+    }
+
+    function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
+      var hasCallback = lib$es6$promise$utils$$isFunction(callback),
+          value, error, succeeded, failed;
+
+      if (hasCallback) {
+        value = lib$es6$promise$$internal$$tryCatch(callback, detail);
+
+        if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
+          failed = true;
+          error = value.error;
+          value = null;
+        } else {
+          succeeded = true;
+        }
+
+        if (promise === value) {
+          lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
+          return;
+        }
+
+      } else {
+        value = detail;
+        succeeded = true;
+      }
+
+      if (promise._state !== lib$es6$promise$$internal$$PENDING) {
+        // noop
+      } else if (hasCallback && succeeded) {
+        lib$es6$promise$$internal$$resolve(promise, value);
+      } else if (failed) {
+        lib$es6$promise$$internal$$reject(promise, error);
+      } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
+        lib$es6$promise$$internal$$fulfill(promise, value);
+      } else if (settled === lib$es6$promise$$internal$$REJECTED) {
+        lib$es6$promise$$internal$$reject(promise, value);
+      }
+    }
+
+    function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
+      try {
+        resolver(function resolvePromise(value){
+          lib$es6$promise$$internal$$resolve(promise, value);
+        }, function rejectPromise(reason) {
+          lib$es6$promise$$internal$$reject(promise, reason);
+        });
+      } catch(e) {
+        lib$es6$promise$$internal$$reject(promise, e);
+      }
+    }
+
+    function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
+      var enumerator = this;
+
+      enumerator._instanceConstructor = Constructor;
+      enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
+
+      if (enumerator._validateInput(input)) {
+        enumerator._input     = input;
+        enumerator.length     = input.length;
+        enumerator._remaining = input.length;
+
+        enumerator._init();
+
+        if (enumerator.length === 0) {
+          lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
+        } else {
+          enumerator.length = enumerator.length || 0;
+          enumerator._enumerate();
+          if (enumerator._remaining === 0) {
+            lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
+          }
+        }
+      } else {
+        lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
+      }
+    }
+
+    lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
+      return lib$es6$promise$utils$$isArray(input);
+    };
+
+    lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
+      return new Error('Array Methods must be provided an Array');
+    };
+
+    lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
+      this._result = new Array(this.length);
+    };
+
+    var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
+
+    lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
+      var enumerator = this;
+
+      var length  = enumerator.length;
+      var promise = enumerator.promise;
+      var input   = enumerator._input;
+
+      for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
+        enumerator._eachEntry(input[i], i);
+      }
+    };
+
+    lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
+      var enumerator = this;
+      var c = enumerator._instanceConstructor;
+
+      if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
+        if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
+          entry._onerror = null;
+          enumerator._settledAt(entry._state, i, entry._result);
+        } else {
+          enumerator._willSettleAt(c.resolve(entry), i);
+        }
+      } else {
+        enumerator._remaining--;
+        enumerator._result[i] = entry;
+      }
+    };
+
+    lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
+      var enumerator = this;
+      var promise = enumerator.promise;
+
+      if (promise._state === lib$es6$promise$$internal$$PENDING) {
+        enumerator._remaining--;
+
+        if (state === lib$es6$promise$$internal$$REJECTED) {
+          lib$es6$promise$$internal$$reject(promise, value);
+        } else {
+          enumerator._result[i] = value;
+        }
+      }
+
+      if (enumerator._remaining === 0) {
+        lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
+      }
+    };
+
+    lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
+      var enumerator = this;
+
+      lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
+        enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
+      }, function(reason) {
+        enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
+      });
+    };
+    function lib$es6$promise$promise$all$$all(entries) {
+      return new lib$es6$promise$enumerator$$default(this, entries).promise;
+    }
+    var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
+    function lib$es6$promise$promise$race$$race(entries) {
+      /*jshint validthis:true */
+      var Constructor = this;
+
+      var promise = new Constructor(lib$es6$promise$$internal$$noop);
+
+      if (!lib$es6$promise$utils$$isArray(entries)) {
+        lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
+        return promise;
+      }
+
+      var length = entries.length;
+
+      function onFulfillment(value) {
+        lib$es6$promise$$internal$$resolve(promise, value);
+      }
+
+      function onRejection(reason) {
+        lib$es6$promise$$internal$$reject(promise, reason);
+      }
+
+      for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
+        lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
+      }
+
+      return promise;
+    }
+    var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
+    function lib$es6$promise$promise$resolve$$resolve(object) {
+      /*jshint validthis:true */
+      var Constructor = this;
+
+      if (object && typeof object === 'object' && object.constructor === Constructor) {
+        return object;
+      }
+
+      var promise = new Constructor(lib$es6$promise$$internal$$noop);
+      lib$es6$promise$$internal$$resolve(promise, object);
+      return promise;
+    }
+    var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
+    function lib$es6$promise$promise$reject$$reject(reason) {
+      /*jshint validthis:true */
+      var Constructor = this;
+      var promise = new Constructor(lib$es6$promise$$internal$$noop);
+      lib$es6$promise$$internal$$reject(promise, reason);
+      return promise;
+    }
+    var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
+
+    var lib$es6$promise$promise$$counter = 0;
+
+    function lib$es6$promise$promise$$needsResolver() {
+      throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
+    }
+
+    function lib$es6$promise$promise$$needsNew() {
+      throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
+    }
+
+    var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
+    /**
+      Promise objects represent the eventual result of an asynchronous operation. The
+      primary way of interacting with a promise is through its `then` method, which
+      registers callbacks to receive either a promise's eventual value or the reason
+      why the promise cannot be fulfilled.
+
+      Terminology
+      -----------
+
+      - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
+      - `thenable` is an object or function that defines a `then` method.
+      - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
+      - `exception` is a value that is thrown using the throw statement.
+      - `reason` is a value that indicates why a promise was rejected.
+      - `settled` the final resting state of a promise, fulfilled or rejected.
+
+      A promise can be in one of three states: pending, fulfilled, or rejected.
+
+      Promises that are fulfilled have a fulfillment value and are in the fulfilled
+      state.  Promises that are rejected have a rejection reason and are in the
+      rejected state.  A fulfillment value is never a thenable.
+
+      Promises can also be said to *resolve* a value.  If this value is also a
+      promise, then the original promise's settled state will match the value's
+      settled state.  So a promise that *resolves* a promise that rejects will
+      itself reject, and a promise that *resolves* a promise that fulfills will
+      itself fulfill.
+
+
+      Basic Usage:
+      ------------
+
+      ```js
+      var promise = new Promise(function(resolve, reject) {
+        // on success
+        resolve(value);
+
+        // on failure
+        reject(reason);
+      });
+
+      promise.then(function(value) {
+        // on fulfillment
+      }, function(reason) {
+        // on rejection
+      });
+      ```
+
+      Advanced Usage:
+      ---------------
+
+      Promises shine when abstracting away asynchronous interactions such as
+      `XMLHttpRequest`s.
+
+      ```js
+      function getJSON(url) {
+        return new Promise(function(resolve, reject){
+          var xhr = new XMLHttpRequest();
+
+          xhr.open('GET', url);
+          xhr.onreadystatechange = handler;
+          xhr.responseType = 'json';
+          xhr.setRequestHeader('Accept', 'application/json');
+          xhr.send();
+
+          function handler() {
+            if (this.readyState === this.DONE) {
+              if (this.status === 200) {
+                resolve(this.response);
+              } else {
+                reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
+              }
+            }
+          };
+        });
+      }
+
+      getJSON('/posts.json').then(function(json) {
+        // on fulfillment
+      }, function(reason) {
+        // on rejection
+      });
+      ```
+
+      Unlike callbacks, promises are great composable primitives.
+
+      ```js
+      Promise.all([
+        getJSON('/posts'),
+        getJSON('/comments')
+      ]).then(function(values){
+        values[0] // => postsJSON
+        values[1] // => commentsJSON
+
+        return values;
+      });
+      ```
+
+      @class Promise
+      @param {function} resolver
+      Useful for tooling.
+      @constructor
+    */
+    function lib$es6$promise$promise$$Promise(resolver) {
+      this._id = lib$es6$promise$promise$$counter++;
+      this._state = undefined;
+      this._result = undefined;
+      this._subscribers = [];
+
+      if (lib$es6$promise$$internal$$noop !== resolver) {
+        if (!lib$es6$promise$utils$$isFunction(resolver)) {
+          lib$es6$promise$promise$$needsResolver();
+        }
+
+        if (!(this instanceof lib$es6$promise$promise$$Promise)) {
+          lib$es6$promise$promise$$needsNew();
+        }
+
+        lib$es6$promise$$internal$$initializePromise(this, resolver);
+      }
+    }
+
+    lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
+    lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
+    lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
+    lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
+    lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
+    lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
+    lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
+
+    lib$es6$promise$promise$$Promise.prototype = {
+      constructor: lib$es6$promise$promise$$Promise,
+
+    /**
+      The primary way of interacting with a promise is through its `then` method,
+      which registers callbacks to receive either a promise's eventual value or the
+      reason why the promise cannot be fulfilled.
+
+      ```js
+      findUser().then(function(user){
+        // user is available
+      }, function(reason){
+        // user is unavailable, and you are given the reason why
+      });
+      ```
+
+      Chaining
+      --------
+
+      The return value of `then` is itself a promise.  This second, 'downstream'
+      promise is resolved with the return value of the first promise's fulfillment
+      or rejection handler, or rejected if the handler throws an exception.
+
+      ```js
+      findUser().then(function (user) {
+        return user.name;
+      }, function (reason) {
+        return 'default name';
+      }).then(function (userName) {
+        // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
+        // will be `'default name'`
+      });
+
+      findUser().then(function (user) {
+        throw new Error('Found user, but still unhappy');
+      }, function (reason) {
+        throw new Error('`findUser` rejected and we're unhappy');
+      }).then(function (value) {
+        // never reached
+      }, function (reason) {
+        // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
+        // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
+      });
+      ```
+      If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
+
+      ```js
+      findUser().then(function (user) {
+        throw new PedagogicalException('Upstream error');
+      }).then(function (value) {
+        // never reached
+      }).then(function (value) {
+        // never reached
+      }, function (reason) {
+        // The `PedgagocialException` is propagated all the way down to here
+      });
+      ```
+
+      Assimilation
+      ------------
+
+      Sometimes the value you want to propagate to a downstream promise can only be
+      retrieved asynchronously. This can be achieved by returning a promise in the
+      fulfillment or rejection handler. The downstream promise will then be pending
+      until the returned promise is settled. This is called *assimilation*.
+
+      ```js
+      findUser().then(function (user) {
+        return findCommentsByAuthor(user);
+      }).then(function (comments) {
+        // The user's comments are now available
+      });
+      ```
+
+      If the assimliated promise rejects, then the downstream promise will also reject.
+
+      ```js
+      findUser().then(function (user) {
+        return findCommentsByAuthor(user);
+      }).then(function (comments) {
+        // If `findCommentsByAuthor` fulfills, we'll have the value here
+      }, function (reason) {
+        // If `findCommentsByAuthor` rejects, we'll have the reason here
+      });
+      ```
+
+      Simple Example
+      --------------
+
+      Synchronous Example
+
+      ```javascript
+      var result;
+
+      try {
+        result = findResult();
+        // success
+      } catch(reason) {
+        // failure
+      }
+      ```
+
+      Errback Example
+
+      ```js
+      findResult(function(result, err){
+        if (err) {
+          // failure
+        } else {
+          // success
+        }
+      });
+      ```
+
+      Promise Example;
+
+      ```javascript
+      findResult().then(function(result){
+        // success
+      }, function(reason){
+        // failure
+      });
+      ```
+
+      Advanced Example
+      --------------
+
+      Synchronous Example
+
+      ```javascript
+      var author, books;
+
+      try {
+        author = findAuthor();
+        books  = findBooksByAuthor(author);
+        // success
+      } catch(reason) {
+        // failure
+      }
+      ```
+
+      Errback Example
+
+      ```js
+
+      function foundBooks(books) {
+
+      }
+
+      function failure(reason) {
+
+      }
+
+      findAuthor(function(author, err){
+        if (err) {
+          failure(err);
+          // failure
+        } else {
+          try {
+            findBoooksByAuthor(author, function(books, err) {
+              if (err) {
+                failure(err);
+              } else {
+                try {
+                  foundBooks(books);
+                } catch(reason) {
+                  failure(reason);
+                }
+              }
+            });
+          } catch(error) {
+            failure(err);
+          }
+          // success
+        }
+      });
+      ```
+
+      Promise Example;
+
+      ```javascript
+      findAuthor().
+        then(findBooksByAuthor).
+        then(function(books){
+          // found books
+      }).catch(function(reason){
+        // something went wrong
+      });
+      ```
+
+      @method then
+      @param {Function} onFulfilled
+      @param {Function} onRejected
+      Useful for tooling.
+      @return {Promise}
+    */
+      then: function(onFulfillment, onRejection) {
+        var parent = this;
+        var state = parent._state;
+
+        if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
+          return this;
+        }
+
+        var child = new this.constructor(lib$es6$promise$$internal$$noop);
+        var result = parent._result;
+
+        if (state) {
+          var callback = arguments[state - 1];
+          lib$es6$promise$asap$$asap(function(){
+            lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
+          });
+        } else {
+          lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
+        }
+
+        return child;
+      },
+
+    /**
+      `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
+      as the catch block of a try/catch statement.
+
+      ```js
+      function findAuthor(){
+        throw new Error('couldn't find that author');
+      }
+
+      // synchronous
+      try {
+        findAuthor();
+      } catch(reason) {
+        // something went wrong
+      }
+
+      // async with promises
+      findAuthor().catch(function(reason){
+        // something went wrong
+      });
+      ```
+
+      @method catch
+      @param {Function} onRejection
+      Useful for tooling.
+      @return {Promise}
+    */
+      'catch': function(onRejection) {
+        return this.then(null, onRejection);
+      }
+    };
+    function lib$es6$promise$polyfill$$polyfill() {
+      var local;
+
+      if (typeof global !== 'undefined') {
+          local = global;
+      } else if (typeof self !== 'undefined') {
+          local = self;
+      } else {
+          try {
+              local = Function('return this')();
+          } catch (e) {
+              throw new Error('polyfill failed because global object is unavailable in this environment');
+          }
+      }
+
+      var P = local.Promise;
+
+      if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
+        return;
+      }
+
+      local.Promise = lib$es6$promise$promise$$default;
+    }
+    var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
+
+    var lib$es6$promise$umd$$ES6Promise = {
+      'Promise': lib$es6$promise$promise$$default,
+      'polyfill': lib$es6$promise$polyfill$$default
+    };
+
+    /* global define:true module:true window: true */
+    if (typeof define === 'function' && define['amd']) {
+      define(function() { return lib$es6$promise$umd$$ES6Promise; });
+    } else if (typeof module !== 'undefined' && module['exports']) {
+      module['exports'] = lib$es6$promise$umd$$ES6Promise;
+    } else if (typeof this !== 'undefined') {
+      this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
+    }
+
+    lib$es6$promise$polyfill$$default();
+}).call(this);
+
+
+}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"_process":55}],74:[function(require,module,exports){
+/**
+ * inspired by is-number <https://github.com/jonschlinkert/is-number>
+ * but significantly simplified and sped up by ignoring number and string constructors
+ * ie these return false:
+ *   new Number(1)
+ *   new String('1')
+ */
+
+'use strict';
+
+/**
+ * Is this string all whitespace?
+ * This solution kind of makes my brain hurt, but it's significantly faster
+ * than !str.trim() or any other solution I could find.
+ *
+ * whitespace codes from: http://en.wikipedia.org/wiki/Whitespace_character
+ * and verified with:
+ *
+ *  for(var i = 0; i < 65536; i++) {
+ *      var s = String.fromCharCode(i);
+ *      if(+s===0 && !s.trim()) console.log(i, s);
+ *  }
+ *
+ * which counts a couple of these as *not* whitespace, but finds nothing else
+ * that *is* whitespace. Note that charCodeAt stops at 16 bits, but it appears
+ * that there are no whitespace characters above this, and code points above
+ * this do not map onto white space characters.
+ */
+function allBlankCharCodes(str){
+    var l = str.length,
+        a;
+    for(var i = 0; i < l; i++) {
+        a = str.charCodeAt(i);
+        if((a < 9 || a > 13) && (a !== 32) && (a !== 133) && (a !== 160) &&
+            (a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) &&
+            (a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) &&
+            (a !== 8288) && (a !== 12288) && (a !== 65279)) {
+                return false;
+        }
+    }
+    return true;
+}
+
+module.exports = function(n) {
+    var type = typeof n;
+    if(type === 'string') {
+        var original = n;
+        n = +n;
+        // whitespace strings cast to zero - filter them out
+        if(n===0 && allBlankCharCodes(original)) return false;
+    }
+    else if(type !== 'number') return false;
+
+    return n - n < 1;
+};
+
+},{}],75:[function(require,module,exports){
+"use strict"
+
+var pool = require("typedarray-pool")
+var ops = require("ndarray-ops")
+var ndarray = require("ndarray")
+
+var SUPPORTED_TYPES = [
+  "uint8",
+  "uint8_clamped",
+  "uint16",
+  "uint32",
+  "int8",
+  "int16",
+  "int32",
+  "float32" ]
+
+function GLBuffer(gl, type, handle, length, usage) {
+  this.gl = gl
+  this.type = type
+  this.handle = handle
+  this.length = length
+  this.usage = usage
+}
+
+var proto = GLBuffer.prototype
+
+proto.bind = function() {
+  this.gl.bindBuffer(this.type, this.handle)
+}
+
+proto.unbind = function() {
+  this.gl.bindBuffer(this.type, null)
+}
+
+proto.dispose = function() {
+  this.gl.deleteBuffer(this.handle)
+}
+
+function updateTypeArray(gl, type, len, usage, data, offset) {
+  var dataLen = data.length * data.BYTES_PER_ELEMENT
+  if(offset < 0) {
+    gl.bufferData(type, data, usage)
+    return dataLen
+  }
+  if(dataLen + offset > len) {
+    throw new Error("gl-buffer: If resizing buffer, must not specify offset")
+  }
+  gl.bufferSubData(type, offset, data)
+  return len
+}
+
+function makeScratchTypeArray(array, dtype) {
+  var res = pool.malloc(array.length, dtype)
+  var n = array.length
+  for(var i=0; i<n; ++i) {
+    res[i] = array[i]
+  }
+  return res
+}
+
+function isPacked(shape, stride) {
+  var n = 1
+  for(var i=stride.length-1; i>=0; --i) {
+    if(stride[i] !== n) {
+      return false
+    }
+    n *= shape[i]
+  }
+  return true
+}
+
+proto.update = function(array, offset) {
+  if(typeof offset !== "number") {
+    offset = -1
+  }
+  this.bind()
+  if(typeof array === "object" && typeof array.shape !== "undefined") { //ndarray
+    var dtype = array.dtype
+    if(SUPPORTED_TYPES.indexOf(dtype) < 0) {
+      dtype = "float32"
+    }
+    if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
+      var ext = gl.getExtension('OES_element_index_uint')
+      if(ext && dtype !== "uint16") {
+        dtype = "uint32"
+      } else {
+        dtype = "uint16"
+      }
+    }
+    if(dtype === array.dtype && isPacked(array.shape, array.stride)) {
+      if(array.offset === 0 && array.data.length === array.shape[0]) {
+        this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data, offset)
+      } else {
+        this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array.data.subarray(array.offset, array.shape[0]), offset)
+      }
+    } else {
+      var tmp = pool.malloc(array.size, dtype)
+      var ndt = ndarray(tmp, array.shape)
+      ops.assign(ndt, array)
+      if(offset < 0) {
+        this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp, offset)
+      } else {
+        this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, tmp.subarray(0, array.size), offset)
+      }
+      pool.free(tmp)
+    }
+  } else if(Array.isArray(array)) { //Vanilla array
+    var t
+    if(this.type === this.gl.ELEMENT_ARRAY_BUFFER) {
+      t = makeScratchTypeArray(array, "uint16")
+    } else {
+      t = makeScratchTypeArray(array, "float32")
+    }
+    if(offset < 0) {
+      this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t, offset)
+    } else {
+      this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, t.subarray(0, array.length), offset)
+    }
+    pool.free(t)
+  } else if(typeof array === "object" && typeof array.length === "number") { //Typed array
+    this.length = updateTypeArray(this.gl, this.type, this.length, this.usage, array, offset)
+  } else if(typeof array === "number" || array === undefined) { //Number/default
+    if(offset >= 0) {
+      throw new Error("gl-buffer: Cannot specify offset when resizing buffer")
+    }
+    array = array | 0
+    if(array <= 0) {
+      array = 1
+    }
+    this.gl.bufferData(this.type, array|0, this.usage)
+    this.length = array
+  } else { //Error, case should not happen
+    throw new Error("gl-buffer: Invalid data type")
+  }
+}
+
+function createBuffer(gl, data, type, usage) {
+  type = type || gl.ARRAY_BUFFER
+  usage = usage || gl.DYNAMIC_DRAW
+  if(type !== gl.ARRAY_BUFFER && type !== gl.ELEMENT_ARRAY_BUFFER) {
+    throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER")
+  }
+  if(usage !== gl.DYNAMIC_DRAW && usage !== gl.STATIC_DRAW && usage !== gl.STREAM_DRAW) {
+    throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW")
+  }
+  var handle = gl.createBuffer()
+  var result = new GLBuffer(gl, type, handle, 0, usage)
+  result.update(data)
+  return result
+}
+
+module.exports = createBuffer
+
+},{"ndarray":208,"ndarray-ops":207,"typedarray-pool":233}],76:[function(require,module,exports){
+'use strict'
+
+var createShader = require('gl-shader')
+var createBuffer = require('gl-buffer')
+var pool = require('typedarray-pool')
+var shaders = require('./lib/shaders')
+
+module.exports = createError2D
+
+var WEIGHTS = [
+  //x-error bar
+  [ 1, 0, 0, 1, 0, 0],
+  [ 1, 0, 0,-1, 0, 0],
+  [-1, 0, 0,-1, 0, 0],
+
+  [-1, 0, 0,-1, 0, 0],
+  [-1, 0, 0, 1, 0, 0],
+  [ 1, 0, 0, 1, 0, 0],
+
+  //x-error right cap
+  [ 1, 0, -1, 0, 0, 1],
+  [ 1, 0, -1, 0, 0,-1],
+  [ 1, 0,  1, 0, 0,-1],
+
+  [ 1, 0,  1, 0, 0,-1],
+  [ 1, 0,  1, 0, 0, 1],
+  [ 1, 0, -1, 0, 0, 1],
+
+  //x-error left cap
+  [-1, 0, -1, 0, 0, 1],
+  [-1, 0, -1, 0, 0,-1],
+  [-1, 0,  1, 0, 0,-1],
+
+  [-1, 0,  1, 0, 0,-1],
+  [-1, 0,  1, 0, 0, 1],
+  [-1, 0, -1, 0, 0, 1],
+
+  //y-error bar
+  [0, 1, 1, 0, 0, 0],
+  [0, 1,-1, 0, 0, 0],
+  [0,-1,-1, 0, 0, 0],
+
+  [0,-1,-1, 0, 0, 0],
+  [0, 1, 1, 0, 0, 0],
+  [0,-1, 1, 0, 0, 0],
+
+  //y-error top cap
+  [ 0, 1, 0,-1, 1, 0],
+  [ 0, 1, 0,-1,-1, 0],
+  [ 0, 1, 0, 1,-1, 0],
+
+  [ 0, 1, 0, 1, 1, 0],
+  [ 0, 1, 0,-1, 1, 0],
+  [ 0, 1, 0, 1,-1, 0],
+
+  //y-error bottom cap
+  [ 0,-1, 0,-1, 1, 0],
+  [ 0,-1, 0,-1,-1, 0],
+  [ 0,-1, 0, 1,-1, 0],
+
+  [ 0,-1, 0, 1, 1, 0],
+  [ 0,-1, 0,-1, 1, 0],
+  [ 0,-1, 0, 1,-1, 0]
+]
+
+function GLError2D(plot, shader, buffer) {
+  this.plot = plot
+
+  this.shader = shader
+  this.buffer = buffer
+
+  this.bounds = [Infinity, Infinity, -Infinity, -Infinity]
+
+  this.numPoints = 0
+
+  this.color     = [0,0,0,1]
+}
+
+var proto = GLError2D.prototype
+
+proto.draw = (function() {
+
+  var MATRIX      = [
+    1, 0, 0,
+    0, 1, 0,
+    0, 0, 1
+  ]
+
+  var PIXEL_SCALE = [1,1]
+
+  return function() {
+    var plot      = this.plot
+    var shader    = this.shader
+    var buffer    = this.buffer
+    var bounds    = this.bounds
+    var numPoints = this.numPoints
+    var color     = this.color
+
+    var gl          = plot.gl
+    var dataBox     = plot.dataBox
+    var viewBox     = plot.viewBox
+    var pixelRatio  = plot.pixelRatio
+
+    var boundX  = bounds[2]  - bounds[0]
+    var boundY  = bounds[3]  - bounds[1]
+    var dataX   = dataBox[2] - dataBox[0]
+    var dataY   = dataBox[3] - dataBox[1]
+
+    MATRIX[0] = 2.0 * boundX / dataX
+    MATRIX[4] = 2.0 * boundY / dataY
+    MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0
+    MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0
+
+    var screenX = viewBox[2] - viewBox[0]
+    var screenY = viewBox[3] - viewBox[1]
+
+    PIXEL_SCALE[0] = 2.0 * pixelRatio / screenX
+    PIXEL_SCALE[1] = 2.0 * pixelRatio / screenY
+
+    buffer.bind()
+    shader.bind()
+
+    shader.uniforms.viewTransform = MATRIX
+    shader.uniforms.pixelScale    = PIXEL_SCALE
+    shader.uniforms.color         = this.color
+
+    shader.attributes.position.pointer(
+      gl.FLOAT,
+      false,
+      16,
+      0)
+
+    shader.attributes.pixelOffset.pointer(
+      gl.FLOAT,
+      false,
+      16,
+      8)
+
+    gl.drawArrays(gl.TRIANGLES, 0, numPoints * WEIGHTS.length)
+  }
+})()
+
+proto.drawPick = function(offset) { return offset }
+proto.pick = function(x, y) {
+  return null
+}
+
+proto.update = function(options) {
+  options = options || {}
+
+  var positions = options.positions || []
+  var errors    = options.errors    || []
+
+  var lineWidth = 1
+  if('lineWidth' in options) {
+    lineWidth = +options.lineWidth
+  }
+
+  var capSize = 5
+  if('capSize' in options) {
+    capSize = +options.capSize
+  }
+
+  this.color     = (options.color || [0,0,0,1]).slice()
+
+  var bounds    = this.bounds = [Infinity, Infinity, -Infinity, -Infinity]
+
+  var numPoints = this.numPoints = positions.length>>1
+  for(var i=0; i<numPoints; ++i) {
+    var x = positions[i*2]
+    var y = positions[i*2+1]
+
+    bounds[0] = Math.min(x, bounds[0])
+    bounds[1] = Math.min(y, bounds[1])
+    bounds[2] = Math.max(x, bounds[2])
+    bounds[3] = Math.max(y, bounds[3])
+  }
+  if(bounds[2] === bounds[0]) {
+    bounds[2] += 1
+  }
+  if(bounds[3] === bounds[1]) {
+    bounds[3] += 1
+  }
+  var sx = 1.0 / (bounds[2] - bounds[0])
+  var sy = 1.0 / (bounds[3] - bounds[1])
+  var tx = bounds[0]
+  var ty = bounds[1]
+
+  var bufferData = pool.mallocFloat32(numPoints * WEIGHTS.length * 4)
+  var ptr = 0
+  for(var i=0; i<numPoints; ++i) {
+    var x   = positions[2*i]
+    var y   = positions[2*i+1]
+    var ex0 = errors[4*i]
+    var ex1 = errors[4*i+1]
+    var ey0 = errors[4*i+2]
+    var ey1 = errors[4*i+3]
+
+    for(var j=0; j<WEIGHTS.length; ++j) {
+      var w = WEIGHTS[j]
+
+      var dx = w[0]
+      var dy = w[1]
+
+      if(dx < 0) {
+        dx *= ex0
+      } else if(dx > 0) {
+        dx *= ex1
+      }
+
+      if(dy < 0) {
+        dy *= ey0
+      } else if(dy > 0) {
+        dy *= ey1
+      }
+
+      bufferData[ptr++] = sx * ((x - tx) + dx)
+      bufferData[ptr++] = sy * ((y - ty) + dy)
+      bufferData[ptr++] = lineWidth * w[2] + (capSize + lineWidth) * w[4]
+      bufferData[ptr++] = lineWidth * w[3] + (capSize + lineWidth) * w[5]
+    }
+  }
+  this.buffer.update(bufferData)
+  pool.free(bufferData)
+}
+
+proto.dispose = function() {
+  this.plot.removeObject(this)
+  this.shader.dispose()
+  this.buffer.dispose()
+}
+
+function createError2D(plot, options) {
+  var shader = createShader(plot.gl, shaders.vertex, shaders.fragment)
+  var buffer = createBuffer(plot.gl)
+
+  var errorbars = new GLError2D(plot, shader, buffer)
+
+  errorbars.update(options)
+
+  plot.addObject(errorbars)
+
+  return errorbars
+}
+
+},{"./lib/shaders":77,"gl-buffer":75,"gl-shader":154,"typedarray-pool":233}],77:[function(require,module,exports){
+
+
+module.exports = {
+  vertex:   "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 position;\nattribute vec2 pixelOffset;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvoid main() {\n  vec3 scrPosition = viewTransform * vec3(position, 1);\n  gl_Position = vec4(\n    scrPosition.xy + scrPosition.z * pixelScale * pixelOffset,\n    0,\n    scrPosition.z);\n}\n",
+  fragment: "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 color;\n\nvoid main() {\n  gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n"
+}
+
+},{}],78:[function(require,module,exports){
+'use strict'
+
+module.exports = createErrorBars
+
+var createBuffer  = require('gl-buffer')
+var createVAO     = require('gl-vao')
+var createShader  = require('./shaders/index')
+
+var IDENTITY = [1,0,0,0,
+                0,1,0,0,
+                0,0,1,0,
+                0,0,0,1]
+
+function ErrorBars(gl, buffer, vao, shader) {
+  this.gl           = gl
+  this.shader       = shader
+  this.buffer       = buffer
+  this.vao          = vao
+  this.pixelRatio   = 1
+  this.bounds       = [[ Infinity, Infinity, Infinity], [-Infinity,-Infinity,-Infinity]]
+  this.clipBounds   = [[-Infinity,-Infinity,-Infinity], [ Infinity, Infinity, Infinity]]
+  this.lineWidth    = [1,1,1]
+  this.capSize      = [10,10,10]
+  this.lineCount    = [0,0,0]
+  this.lineOffset   = [0,0,0]
+  this.opacity      = 1
+}
+
+var proto = ErrorBars.prototype
+
+proto.isOpaque = function() {
+  return this.opacity >= 1
+}
+
+proto.isTransparent = function() {
+  return this.opacity < 1
+}
+
+proto.drawTransparent = proto.draw = function(cameraParams) {
+  var gl = this.gl
+  var uniforms        = this.shader.uniforms
+
+  this.shader.bind()
+  var view       = uniforms.view       = cameraParams.view       || IDENTITY
+  var projection = uniforms.projection = cameraParams.projection || IDENTITY
+  uniforms.model      = cameraParams.model      || IDENTITY
+  uniforms.clipBounds = this.clipBounds
+  uniforms.opacity    = this.opacity
+
+
+  var cx = view[12]
+  var cy = view[13]
+  var cz = view[14]
+  var cw = view[15]
+  var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight
+
+
+  this.vao.bind()
+  for(var i=0; i<3; ++i) {
+    gl.lineWidth(this.lineWidth[i])
+    uniforms.capSize = this.capSize[i] * pixelScaleF
+    gl.drawArrays(gl.LINES, this.lineOffset[i], this.lineCount[i])
+  }
+  this.vao.unbind()
+}
+
+function updateBounds(bounds, point) {
+  for(var i=0; i<3; ++i) {
+    bounds[0][i] = Math.min(bounds[0][i], point[i])
+    bounds[1][i] = Math.max(bounds[1][i], point[i])
+  }
+}
+
+var FACE_TABLE = (function(){
+  var table = new Array(3)
+  for(var d=0; d<3; ++d) {
+    var row = []
+    for(var j=1; j<=2; ++j) {
+      for(var s=-1; s<=1; s+=2) {
+        var u = (j+d) % 3
+        var y = [0,0,0]
+        y[u] = s
+        row.push(y)
+      }
+    }
+    table[d] = row
+  }
+  return table
+})()
+
+
+function emitFace(verts, x, c, d) {
+  var offsets = FACE_TABLE[d]
+  for(var i=0; i<offsets.length; ++i) {
+    var o = offsets[i]
+    verts.push(x[0], x[1], x[2],
+               c[0], c[1], c[2], c[3],
+               o[0], o[1], o[2])
+  }
+  return offsets.length
+}
+
+proto.update = function(options) {
+  options = options || {}
+
+  if('lineWidth' in options) {
+    this.lineWidth = options.lineWidth
+    if(!Array.isArray(this.lineWidth)) {
+      this.lineWidth = [this.lineWidth, this.lineWidth, this.lineWidth]
+    }
+  }
+  if('capSize' in options) {
+    this.capSize = options.capSize
+    if(!Array.isArray(this.capSize)) {
+      this.capSize = [this.capSize, this.capSize, this.capSize]
+    }
+  }
+  if('opacity' in options) {
+    this.opacity = options.opacity
+  }
+
+  var color    = options.color || [[0,0,0],[0,0,0],[0,0,0]]
+  var position = options.position
+  var error    = options.error
+  if(!Array.isArray(color[0])) {
+    color = [color,color,color]
+  }
+
+  if(position && error) {
+
+    var verts       = []
+    var n           = position.length
+    var vertexCount = 0
+    this.bounds     = [[ Infinity, Infinity, Infinity],
+                       [-Infinity,-Infinity,-Infinity]]
+    this.lineCount  = [0,0,0]
+
+    //Build geometry for lines
+    for(var j=0; j<3; ++j) {
+      this.lineOffset[j] = vertexCount
+
+i_loop:
+      for(var i=0; i<n; ++i) {
+        var p = position[i]
+
+        for(var k=0; k<3; ++k) {
+          if(isNaN(p[k]) || !isFinite(p[k])) {
+            continue i_loop
+          }
+        }
+
+        var e = error[i]
+        var c = color[j]
+        if(Array.isArray(c[0])) {
+          c = color[i]
+        }
+        if(c.length === 3) {
+          c = [c[0], c[1], c[2], 1]
+        }
+        if(isNaN(e[0][j]) || isNaN(e[1][j])) {
+          continue
+        }
+        if(e[0][j] < 0) {
+          var x = p.slice()
+          x[j] += e[0][j]
+          verts.push(p[0], p[1], p[2],
+                     c[0], c[1], c[2], c[3],
+                        0,    0,    0,
+                     x[0], x[1], x[2],
+                     c[0], c[1], c[2], c[3],
+                        0,    0,    0)
+          updateBounds(this.bounds, x)
+          vertexCount += 2 + emitFace(verts, x, c, j)
+        }
+        if(e[1][j] > 0) {
+          var x = p.slice()
+          x[j] += e[1][j]
+          verts.push(p[0], p[1], p[2],
+                     c[0], c[1], c[2], c[3],
+                        0,    0,    0,
+                     x[0], x[1], x[2],
+                     c[0], c[1], c[2], c[3],
+                        0,    0,    0)
+          updateBounds(this.bounds, x)
+          vertexCount += 2 + emitFace(verts, x, c, j)
+        }
+      }
+      this.lineCount[j] = vertexCount - this.lineOffset[j]
+    }
+    this.buffer.update(verts)
+  }
+}
+
+proto.dispose = function() {
+  this.shader.dispose()
+  this.buffer.dispose()
+  this.vao.dispose()
+}
+
+function createErrorBars(options) {
+  var gl = options.gl
+  var buffer = createBuffer(gl)
+  var vao = createVAO(gl, [
+      {
+        buffer: buffer,
+        type:   gl.FLOAT,
+        size:   3,
+        offset: 0,
+        stride: 40
+      },
+      {
+        buffer: buffer,
+        type:   gl.FLOAT,
+        size:   4,
+        offset: 12,
+        stride: 40
+      },
+      {
+        buffer: buffer,
+        type:   gl.FLOAT,
+        size:   3,
+        offset: 28,
+        stride: 40
+      }
+    ])
+
+  var shader = createShader(gl)
+  shader.attributes.position.location = 0
+  shader.attributes.color.location    = 1
+  shader.attributes.offset.location   = 2
+
+  var result = new ErrorBars(gl, buffer, vao, shader)
+  result.update(options)
+  return result
+}
+
+},{"./shaders/index":79,"gl-buffer":75,"gl-vao":189}],79:[function(require,module,exports){
+'use strict'
+
+
+var createShader = require('gl-shader')
+
+var vertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n  vec4 worldPosition  = model * vec4(position, 1.0);\n  worldPosition       = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n  gl_Position         = projection * view * worldPosition;\n  fragColor           = color;\n  fragPosition        = position;\n}"
+var fragSrc = "#define GLSLIFY 1\nprecision mediump float;\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n  if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n    discard;\n  }\n  gl_FragColor = opacity * fragColor;\n}"
+
+module.exports = function(gl) {
+  return createShader(gl, vertSrc, fragSrc, null, [
+    {name: 'position', type: 'vec3'},
+    {name: 'offset', type: 'vec3'},
+    {name: 'color', type: 'vec4'}
+  ])
+}
+
+},{"gl-shader":154}],80:[function(require,module,exports){
+'use strict'
+
+var createTexture = require('gl-texture2d')
+
+module.exports = createFBO
+
+var colorAttachmentArrays = null
+var FRAMEBUFFER_UNSUPPORTED
+var FRAMEBUFFER_INCOMPLETE_ATTACHMENT
+var FRAMEBUFFER_INCOMPLETE_DIMENSIONS
+var FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT
+
+function saveFBOState(gl) {
+  var fbo = gl.getParameter(gl.FRAMEBUFFER_BINDING)
+  var rbo = gl.getParameter(gl.RENDERBUFFER_BINDING)
+  var tex = gl.getParameter(gl.TEXTURE_BINDING_2D)
+  return [fbo, rbo, tex]
+}
+
+function restoreFBOState(gl, data) {
+  gl.bindFramebuffer(gl.FRAMEBUFFER, data[0])
+  gl.bindRenderbuffer(gl.RENDERBUFFER, data[1])
+  gl.bindTexture(gl.TEXTURE_2D, data[2])
+}
+
+function lazyInitColorAttachments(gl, ext) {
+  var maxColorAttachments = gl.getParameter(ext.MAX_COLOR_ATTACHMENTS_WEBGL)
+  colorAttachmentArrays = new Array(maxColorAttachments + 1)
+  for(var i=0; i<=maxColorAttachments; ++i) {
+    var x = new Array(maxColorAttachments)
+    for(var j=0; j<i; ++j) {
+      x[j] = gl.COLOR_ATTACHMENT0 + j
+    }
+    for(var j=i; j<maxColorAttachments; ++j) {
+      x[j] = gl.NONE
+    }
+    colorAttachmentArrays[i] = x
+  }
+}
+
+//Throw an appropriate error
+function throwFBOError(status) {
+  switch(status){
+    case FRAMEBUFFER_UNSUPPORTED:
+      throw new Error('gl-fbo: Framebuffer unsupported')
+    case FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
+      throw new Error('gl-fbo: Framebuffer incomplete attachment')
+    case FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
+      throw new Error('gl-fbo: Framebuffer incomplete dimensions')
+    case FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
+      throw new Error('gl-fbo: Framebuffer incomplete missing attachment')
+    default:
+      throw new Error('gl-fbo: Framebuffer failed for unspecified reason')
+  }
+}
+
+//Initialize a texture object
+function initTexture(gl, width, height, type, format, attachment) {
+  if(!type) {
+    return null
+  }
+  var result = createTexture(gl, width, height, format, type)
+  result.magFilter = gl.NEAREST
+  result.minFilter = gl.NEAREST
+  result.mipSamples = 1
+  result.bind()
+  gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, result.handle, 0)
+  return result
+}
+
+//Initialize a render buffer object
+function initRenderBuffer(gl, width, height, component, attachment) {
+  var result = gl.createRenderbuffer()
+  gl.bindRenderbuffer(gl.RENDERBUFFER, result)
+  gl.renderbufferStorage(gl.RENDERBUFFER, component, width, height)
+  gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, result)
+  return result
+}
+
+//Rebuild the frame buffer
+function rebuildFBO(fbo) {
+
+  //Save FBO state
+  var state = saveFBOState(fbo.gl)
+
+  var gl = fbo.gl
+  var handle = fbo.handle = gl.createFramebuffer()
+  var width = fbo._shape[0]
+  var height = fbo._shape[1]
+  var numColors = fbo.color.length
+  var ext = fbo._ext
+  var useStencil = fbo._useStencil
+  var useDepth = fbo._useDepth
+  var colorType = fbo._colorType
+
+  //Bind the fbo
+  gl.bindFramebuffer(gl.FRAMEBUFFER, handle)
+
+  //Allocate color buffers
+  for(var i=0; i<numColors; ++i) {
+    fbo.color[i] = initTexture(gl, width, height, colorType, gl.RGBA, gl.COLOR_ATTACHMENT0 + i)
+  }
+  if(numColors === 0) {
+    fbo._color_rb = initRenderBuffer(gl, width, height, gl.RGBA4, gl.COLOR_ATTACHMENT0)
+    if(ext) {
+      ext.drawBuffersWEBGL(colorAttachmentArrays[0])
+    }
+  } else if(numColors > 1) {
+    ext.drawBuffersWEBGL(colorAttachmentArrays[numColors])
+  }
+
+  //Allocate depth/stencil buffers
+  var WEBGL_depth_texture = gl.getExtension('WEBGL_depth_texture')
+  if(WEBGL_depth_texture) {
+    if(useStencil) {
+      fbo.depth = initTexture(gl, width, height,
+                          WEBGL_depth_texture.UNSIGNED_INT_24_8_WEBGL,
+                          gl.DEPTH_STENCIL,
+                          gl.DEPTH_STENCIL_ATTACHMENT)
+    } else if(useDepth) {
+      fbo.depth = initTexture(gl, width, height,
+                          gl.UNSIGNED_SHORT,
+                          gl.DEPTH_COMPONENT,
+                          gl.DEPTH_ATTACHMENT)
+    }
+  } else {
+    if(useDepth && useStencil) {
+      fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_STENCIL, gl.DEPTH_STENCIL_ATTACHMENT)
+    } else if(useDepth) {
+      fbo._depth_rb = initRenderBuffer(gl, width, height, gl.DEPTH_COMPONENT16, gl.DEPTH_ATTACHMENT)
+    } else if(useStencil) {
+      fbo._depth_rb = initRenderBuffer(gl, width, height, gl.STENCIL_INDEX, gl.STENCIL_ATTACHMENT)
+    }
+  }
+
+  //Check frame buffer state
+  var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER)
+  if(status !== gl.FRAMEBUFFER_COMPLETE) {
+
+    //Release all partially allocated resources
+    fbo._destroyed = true
+
+    //Release all resources
+    gl.bindFramebuffer(gl.FRAMEBUFFER, null)
+    gl.deleteFramebuffer(fbo.handle)
+    fbo.handle = null
+    if(fbo.depth) {
+      fbo.depth.dispose()
+      fbo.depth = null
+    }
+    if(fbo._depth_rb) {
+      gl.deleteRenderbuffer(fbo._depth_rb)
+      fbo._depth_rb = null
+    }
+    for(var i=0; i<fbo.color.length; ++i) {
+      fbo.color[i].dispose()
+      fbo.color[i] = null
+    }
+    if(fbo._color_rb) {
+      gl.deleteRenderbuffer(fbo._color_rb)
+      fbo._color_rb = null
+    }
+
+    restoreFBOState(gl, state)
+
+    //Throw the frame buffer error
+    throwFBOError(status)
+  }
+
+  //Everything ok, let's get on with life
+  restoreFBOState(gl, state)
+}
+
+function Framebuffer(gl, width, height, colorType, numColors, useDepth, useStencil, ext) {
+
+  //Handle and set properties
+  this.gl = gl
+  this._shape = [width|0, height|0]
+  this._destroyed = false
+  this._ext = ext
+
+  //Allocate buffers
+  this.color = new Array(numColors)
+  for(var i=0; i<numColors; ++i) {
+    this.color[i] = null
+  }
+  this._color_rb = null
+  this.depth = null
+  this._depth_rb = null
+
+  //Save depth and stencil flags
+  this._colorType = colorType
+  this._useDepth = useDepth
+  this._useStencil = useStencil
+
+  //Shape vector for resizing
+  var parent = this
+  var shapeVector = [width|0, height|0]
+  Object.defineProperties(shapeVector, {
+    0: {
+      get: function() {
+        return parent._shape[0]
+      },
+      set: function(w) {
+        return parent.width = w
+      }
+    },
+    1: {
+      get: function() {
+        return parent._shape[1]
+      },
+      set: function(h) {
+        return parent.height = h
+      }
+    }
+  })
+  this._shapeVector = shapeVector
+
+  //Initialize all attachments
+  rebuildFBO(this)
+}
+
+var proto = Framebuffer.prototype
+
+function reshapeFBO(fbo, w, h) {
+  //If fbo is invalid, just skip this
+  if(fbo._destroyed) {
+    throw new Error('gl-fbo: Can\'t resize destroyed FBO')
+  }
+
+  //Don't resize if no change in shape
+  if( (fbo._shape[0] === w) &&
+      (fbo._shape[1] === h) ) {
+    return
+  }
+
+  var gl = fbo.gl
+
+  //Check parameter ranges
+  var maxFBOSize = gl.getParameter(gl.MAX_RENDERBUFFER_SIZE)
+  if( w < 0 || w > maxFBOSize ||
+      h < 0 || h > maxFBOSize) {
+    throw new Error('gl-fbo: Can\'t resize FBO, invalid dimensions')
+  }
+
+  //Update shape
+  fbo._shape[0] = w
+  fbo._shape[1] = h
+
+  //Save framebuffer state
+  var state = saveFBOState(gl)
+
+  //Resize framebuffer attachments
+  for(var i=0; i<fbo.color.length; ++i) {
+    fbo.color[i].shape = fbo._shape
+  }
+  if(fbo._color_rb) {
+    gl.bindRenderbuffer(gl.RENDERBUFFER, fbo._color_rb)
+    gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA4, fbo._shape[0], fbo._shape[1])
+  }
+  if(fbo.depth) {
+    fbo.depth.shape = fbo._shape
+  }
+  if(fbo._depth_rb) {
+    gl.bindRenderbuffer(gl.RENDERBUFFER, fbo._depth_rb)
+    if(fbo._useDepth && fbo._useStencil) {
+      gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, fbo._shape[0], fbo._shape[1])
+    } else if(fbo._useDepth) {
+      gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, fbo._shape[0], fbo._shape[1])
+    } else if(fbo._useStencil) {
+      gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX, fbo._shape[0], fbo._shape[1])
+    }
+  }
+
+  //Check FBO status after resize, if something broke then die in a fire
+  gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.handle)
+  var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER)
+  if(status !== gl.FRAMEBUFFER_COMPLETE) {
+    fbo.dispose()
+    restoreFBOState(gl, state)
+    throwFBOError(status)
+  }
+
+  //Restore framebuffer state
+  restoreFBOState(gl, state)
+}
+
+Object.defineProperties(proto, {
+  'shape': {
+    get: function() {
+      if(this._destroyed) {
+        return [0,0]
+      }
+      return this._shapeVector
+    },
+    set: function(x) {
+      if(!Array.isArray(x)) {
+        x = [x|0, x|0]
+      }
+      if(x.length !== 2) {
+        throw new Error('gl-fbo: Shape vector must be length 2')
+      }
+
+      var w = x[0]|0
+      var h = x[1]|0
+      reshapeFBO(this, w, h)
+
+      return [w, h]
+    },
+    enumerable: false
+  },
+  'width': {
+    get: function() {
+      if(this._destroyed) {
+        return 0
+      }
+      return this._shape[0]
+    },
+    set: function(w) {
+      w = w|0
+      reshapeFBO(this, w, this._shape[1])
+      return w
+    },
+    enumerable: false
+  },
+  'height': {
+    get: function() {
+      if(this._destroyed) {
+        return 0
+      }
+      return this._shape[1]
+    },
+    set: function(h) {
+      h = h|0
+      reshapeFBO(this, this._shape[0], h)
+      return h
+    },
+    enumerable: false
+  }
+})
+
+proto.bind = function() {
+  if(this._destroyed) {
+    return
+  }
+  var gl = this.gl
+  gl.bindFramebuffer(gl.FRAMEBUFFER, this.handle)
+  gl.viewport(0, 0, this._shape[0], this._shape[1])
+}
+
+proto.dispose = function() {
+  if(this._destroyed) {
+    return
+  }
+  this._destroyed = true
+  var gl = this.gl
+  gl.deleteFramebuffer(this.handle)
+  this.handle = null
+  if(this.depth) {
+    this.depth.dispose()
+    this.depth = null
+  }
+  if(this._depth_rb) {
+    gl.deleteRenderbuffer(this._depth_rb)
+    this._depth_rb = null
+  }
+  for(var i=0; i<this.color.length; ++i) {
+    this.color[i].dispose()
+    this.color[i] = null
+  }
+  if(this._color_rb) {
+    gl.deleteRenderbuffer(this._color_rb)
+    this._color_rb = null
+  }
+}
+
+function createFBO(gl, width, height, options) {
+
+  //Update frame buffer error code values
+  if(!FRAMEBUFFER_UNSUPPORTED) {
+    FRAMEBUFFER_UNSUPPORTED = gl.FRAMEBUFFER_UNSUPPORTED
+    FRAMEBUFFER_INCOMPLETE_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT
+    FRAMEBUFFER_INCOMPLETE_DIMENSIONS = gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS
+    FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT
+  }
+
+  //Lazily initialize color attachment arrays
+  var WEBGL_draw_buffers = gl.getExtension('WEBGL_draw_buffers')
+  if(!colorAttachmentArrays && WEBGL_draw_buffers) {
+    lazyInitColorAttachments(gl, WEBGL_draw_buffers)
+  }
+
+  //Special case: Can accept an array as argument
+  if(Array.isArray(width)) {
+    options = height
+    height = width[1]|0
+    width = width[0]|0
+  }
+
+  if(typeof width !== 'number') {
+    throw new Error('gl-fbo: Missing shape parameter')
+  }
+
+  //Validate width/height properties
+  var maxFBOSize = gl.getParameter(gl.MAX_RENDERBUFFER_SIZE)
+  if(width < 0 || width > maxFBOSize || height < 0 || height > maxFBOSize) {
+    throw new Error('gl-fbo: Parameters are too large for FBO')
+  }
+
+  //Handle each option type
+  options = options || {}
+
+  //Figure out number of color buffers to use
+  var numColors = 1
+  if('color' in options) {
+    numColors = Math.max(options.color|0, 0)
+    if(numColors < 0) {
+      throw new Error('gl-fbo: Must specify a nonnegative number of colors')
+    }
+    if(numColors > 1) {
+      //Check if multiple render targets supported
+      if(!WEBGL_draw_buffers) {
+        throw new Error('gl-fbo: Multiple draw buffer extension not supported')
+      } else if(numColors > gl.getParameter(WEBGL_draw_buffers.MAX_COLOR_ATTACHMENTS_WEBGL)) {
+        throw new Error('gl-fbo: Context does not support ' + numColors + ' draw buffers')
+      }
+    }
+  }
+
+  //Determine whether to use floating point textures
+  var colorType = gl.UNSIGNED_BYTE
+  var OES_texture_float = gl.getExtension('OES_texture_float')
+  if(options.float && numColors > 0) {
+    if(!OES_texture_float) {
+      throw new Error('gl-fbo: Context does not support floating point textures')
+    }
+    colorType = gl.FLOAT
+  } else if(options.preferFloat && numColors > 0) {
+    if(OES_texture_float) {
+      colorType = gl.FLOAT
+    }
+  }
+
+  //Check if we should use depth buffer
+  var useDepth = true
+  if('depth' in options) {
+    useDepth = !!options.depth
+  }
+
+  //Check if we should use a stencil buffer
+  var useStencil = false
+  if('stencil' in options) {
+    useStencil = !!options.stencil
+  }
+
+  return new Framebuffer(
+    gl,
+    width,
+    height,
+    colorType,
+    numColors,
+    useDepth,
+    useStencil,
+    WEBGL_draw_buffers)
+}
+
+},{"gl-texture2d":185}],81:[function(require,module,exports){
+
+
+exports.lineVertex    = "#define GLSLIFY 1\nprecision mediump float;\n\nfloat inverse_1_0(float m) {\n  return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n  return mat2(m[1][1],-m[0][1],\n             -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n  float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n  float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n  float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n  float b01 = a22 * a11 - a12 * a21;\n  float b11 = -a22 * a10 + a12 * a20;\n  float b21 = a21 * a10 - a11 * a20;\n\n  float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n  return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n              b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n              b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n  float\n      a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n      a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n      a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n      a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n      b00 = a00 * a11 - a01 * a10,\n      b01 = a00 * a12 - a02 * a10,\n      b02 = a00 * a13 - a03 * a10,\n      b03 = a01 * a12 - a02 * a11,\n      b04 = a01 * a13 - a03 * a11,\n      b05 = a02 * a13 - a03 * a12,\n      b06 = a20 * a31 - a21 * a30,\n      b07 = a20 * a32 - a22 * a30,\n      b08 = a20 * a33 - a23 * a30,\n      b09 = a21 * a32 - a22 * a31,\n      b10 = a21 * a33 - a23 * a31,\n      b11 = a22 * a33 - a23 * a32,\n\n      det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n  return mat4(\n      a11 * b11 - a12 * b10 + a13 * b09,\n      a02 * b10 - a01 * b11 - a03 * b09,\n      a31 * b05 - a32 * b04 + a33 * b03,\n      a22 * b04 - a21 * b05 - a23 * b03,\n      a12 * b08 - a10 * b11 - a13 * b07,\n      a00 * b11 - a02 * b08 + a03 * b07,\n      a32 * b02 - a30 * b05 - a33 * b01,\n      a20 * b05 - a22 * b02 + a23 * b01,\n      a10 * b10 - a11 * b08 + a13 * b06,\n      a01 * b08 - a00 * b10 - a03 * b06,\n      a30 * b04 - a31 * b02 + a33 * b00,\n      a21 * b02 - a20 * b04 - a23 * b00,\n      a11 * b07 - a10 * b09 - a12 * b06,\n      a00 * b09 - a01 * b07 + a02 * b06,\n      a31 * b01 - a30 * b03 - a32 * b00,\n      a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec2 direction;\n\nvoid main() {\n  vec2 dir = (matrix * vec3(d, 0)).xy;\n  vec3 base = matrix * vec3(a, 1);\n  vec2 n = 0.5 * width *\n    normalize(screenShape.yx * vec2(dir.y, -dir.x)) / screenShape.xy;\n  vec2 tangent = normalize(screenShape.xy * dir);\n  if(dir.x < 0.0 || (dir.x == 0.0 && dir.y < 0.0)) {\n    direction = -tangent;\n  } else {\n    direction = tangent;\n  }\n  gl_Position = vec4(base.xy/base.z + n, 0, 1);\n}\n"
+exports.lineFragment  = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 color;\nuniform vec2 screenShape;\nuniform sampler2D dashPattern;\nuniform float dashLength;\n\nvarying vec2 direction;\n\nvoid main() {\n  float t = fract(dot(direction, gl_FragCoord.xy) / dashLength);\n  vec4 pcolor = color * texture2D(dashPattern, vec2(t, 0.0)).r;\n  gl_FragColor = vec4(pcolor.rgb * pcolor.a, pcolor.a);\n}\n"
+exports.mitreVertex   = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 p;\n\nuniform mat3  matrix;\nuniform vec2 screenShape;\nuniform float radius;\n\nvoid main() {\n  vec3 pp = matrix * vec3(p, 1);\n  gl_Position  = vec4(pp.xy, 0, pp.z);\n  gl_PointSize = radius;\n}\n"
+exports.mitreFragment = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 color;\n\nvoid main() {\n  if(length(gl_PointCoord.xy - 0.5) > 0.25) {\n    discard;\n  }\n  gl_FragColor = vec4(color.rgb, color.a);\n}\n"
+exports.pickVertex    = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 a, d;\nattribute vec4 pick0, pick1;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec4 pickA, pickB;\n\nfloat inverse_1_0(float m) {\n  return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n  return mat2(m[1][1],-m[0][1],\n             -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n  float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n  float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n  float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n  float b01 = a22 * a11 - a12 * a21;\n  float b11 = -a22 * a10 + a12 * a20;\n  float b21 = a21 * a10 - a11 * a20;\n\n  float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n  return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n              b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n              b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n  float\n      a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n      a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n      a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n      a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n      b00 = a00 * a11 - a01 * a10,\n      b01 = a00 * a12 - a02 * a10,\n      b02 = a00 * a13 - a03 * a10,\n      b03 = a01 * a12 - a02 * a11,\n      b04 = a01 * a13 - a03 * a11,\n      b05 = a02 * a13 - a03 * a12,\n      b06 = a20 * a31 - a21 * a30,\n      b07 = a20 * a32 - a22 * a30,\n      b08 = a20 * a33 - a23 * a30,\n      b09 = a21 * a32 - a22 * a31,\n      b10 = a21 * a33 - a23 * a31,\n      b11 = a22 * a33 - a23 * a32,\n\n      det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n  return mat4(\n      a11 * b11 - a12 * b10 + a13 * b09,\n      a02 * b10 - a01 * b11 - a03 * b09,\n      a31 * b05 - a32 * b04 + a33 * b03,\n      a22 * b04 - a21 * b05 - a23 * b03,\n      a12 * b08 - a10 * b11 - a13 * b07,\n      a00 * b11 - a02 * b08 + a03 * b07,\n      a32 * b02 - a30 * b05 - a33 * b01,\n      a20 * b05 - a22 * b02 + a23 * b01,\n      a10 * b10 - a11 * b08 + a13 * b06,\n      a01 * b08 - a00 * b10 - a03 * b06,\n      a30 * b04 - a31 * b02 + a33 * b00,\n      a21 * b02 - a20 * b04 - a23 * b00,\n      a11 * b07 - a10 * b09 - a12 * b06,\n      a00 * b09 - a01 * b07 + a02 * b06,\n      a31 * b01 - a30 * b03 - a32 * b00,\n      a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nvoid main() {\n  vec3 base = matrix * vec3(a, 1);\n  vec2 n = width *\n    normalize(screenShape.yx * vec2(d.y, -d.x)) / screenShape.xy;\n  gl_Position = vec4(base.xy/base.z + n, 0, 1);\n  pickA = pick0;\n  pickB = pick1;\n}\n"
+exports.pickFragment  = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 pickOffset;\n\nvarying vec4 pickA, pickB;\n\nvoid main() {\n  vec4 fragId = vec4(pickA.xyz, 0.0);\n  if(pickB.w > pickA.w) {\n    fragId.xyz = pickB.xyz;\n  }\n\n  fragId += pickOffset;\n\n  fragId.y += floor(fragId.x / 256.0);\n  fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n  fragId.z += floor(fragId.y / 256.0);\n  fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n  fragId.w += floor(fragId.z / 256.0);\n  fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n  gl_FragColor = fragId / 255.0;\n}\n"
+exports.fillVertex    = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 projectAxis;\nuniform float projectValue;\nuniform float depth;\n\nvoid main() {\n  vec3 base = matrix * vec3(a, 1);\n  vec2 p = base.xy / base.z;\n  if(d.y < 0.0 || (d.y == 0.0 && d.x < 0.0)) {\n    if(dot(p, projectAxis) < projectValue) {\n      p = p * (1.0 - abs(projectAxis)) + projectAxis * projectValue;\n    }\n  }\n  gl_Position = vec4(p, depth, 1);\n}\n"
+exports.fillFragment  = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 color;\n\nvoid main() {\n  gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n"
+
+},{}],82:[function(require,module,exports){
+'use strict'
+
+module.exports = createLinePlot
+
+var createShader = require('gl-shader')
+var createBuffer = require('gl-buffer')
+var createTexture = require('gl-texture2d')
+var ndarray = require('ndarray')
+var pool = require('typedarray-pool')
+
+var SHADERS = require('./lib/shaders')
+
+function GLLine2D(
+  plot,
+  dashPattern,
+  lineBuffer,
+  pickBuffer,
+  lineShader,
+  mitreShader,
+  fillShader,
+  pickShader) {
+
+  this.plot         = plot
+  this.dashPattern  = dashPattern
+  this.lineBuffer   = lineBuffer
+  this.pickBuffer   = pickBuffer
+  this.lineShader   = lineShader
+  this.mitreShader  = mitreShader
+  this.fillShader   = fillShader
+  this.pickShader   = pickShader
+  this.usingDashes  = false
+
+  this.bounds     = [Infinity, Infinity, -Infinity, -Infinity]
+
+  this.width      = 1
+  this.color      = [0,0,1,1]
+
+  //Fill to axes
+  this.fill       = [false, false, false, false]
+  this.fillColor  = [[0,0,0,1],
+                     [0,0,0,1],
+                     [0,0,0,1],
+                     [0,0,0,1]]
+
+  this.data       = null
+  this.numPoints  = 0
+  this.vertCount  = 0
+
+  this.pickOffset = 0
+
+  this.lodBuffer = []
+}
+
+var proto = GLLine2D.prototype
+
+proto.draw = (function() {
+var MATRIX = [1, 0, 0,
+              0, 1, 0,
+              0, 0, 1]
+var SCREEN_SHAPE = [0,0]
+var PX_AXIS = [1,0]
+var NX_AXIS = [-1,0]
+var PY_AXIS = [0,1]
+var NY_AXIS = [0,-1]
+return function() {
+  var plot      = this.plot
+  var color     = this.color
+  var width     = this.width
+  var numPoints = this.numPoints
+  var bounds    = this.bounds
+  var count     = this.vertCount
+
+  var gl        = plot.gl
+  var viewBox   = plot.viewBox
+  var dataBox   = plot.dataBox
+  var pixelRatio = plot.pixelRatio
+
+  var boundX  = bounds[2] - bounds[0]
+  var boundY  = bounds[3] - bounds[1]
+  var dataX   = dataBox[2] - dataBox[0]
+  var dataY   = dataBox[3] - dataBox[1]
+  var screenX = viewBox[2] - viewBox[0]
+  var screenY = viewBox[3] - viewBox[1]
+
+  MATRIX[0] = 2.0 * boundX / dataX
+  MATRIX[4] = 2.0 * boundY / dataY
+  MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0
+  MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0
+
+  SCREEN_SHAPE[0] = screenX
+  SCREEN_SHAPE[1] = screenY
+
+  var buffer    = this.lineBuffer
+  buffer.bind()
+
+  var fill = this.fill
+
+  if(fill[0] || fill[1] || fill[2] || fill[3]) {
+
+    var fillShader = this.fillShader
+    fillShader.bind()
+
+    var fillUniforms = fillShader.uniforms
+    fillUniforms.matrix = MATRIX
+    fillUniforms.depth = plot.nextDepthValue()
+
+    var fillAttributes = fillShader.attributes
+    fillAttributes.a.pointer(gl.FLOAT, false, 16, 0)
+    fillAttributes.d.pointer(gl.FLOAT, false, 16, 8)
+
+    gl.depthMask(true)
+    gl.enable(gl.DEPTH_TEST)
+
+    var fillColor = this.fillColor
+    if(fill[0]) {
+      fillUniforms.color        = fillColor[0]
+      fillUniforms.projectAxis  = NX_AXIS
+      fillUniforms.projectValue = 1
+      gl.drawArrays(gl.TRIANGLES, 0, count)
+    }
+
+    if(fill[1]) {
+      fillUniforms.color        = fillColor[1]
+      fillUniforms.projectAxis  = NY_AXIS
+      fillUniforms.projectValue = 1
+      gl.drawArrays(gl.TRIANGLES, 0, count)
+    }
+
+    if(fill[2]) {
+      fillUniforms.color        = fillColor[2]
+      fillUniforms.projectAxis  = PX_AXIS
+      fillUniforms.projectValue = 1
+      gl.drawArrays(gl.TRIANGLES, 0, count)
+    }
+
+    if(fill[3]) {
+      fillUniforms.color        = fillColor[3]
+      fillUniforms.projectAxis  = PY_AXIS
+      fillUniforms.projectValue = 1
+      gl.drawArrays(gl.TRIANGLES, 0, count)
+    }
+
+    gl.depthMask(false)
+    gl.disable(gl.DEPTH_TEST)
+  }
+
+  var shader    = this.lineShader
+  shader.bind()
+
+  var uniforms = shader.uniforms
+  uniforms.matrix = MATRIX
+  uniforms.color  = color
+  uniforms.width  = width * pixelRatio
+  uniforms.screenShape = SCREEN_SHAPE
+  uniforms.dashPattern = this.dashPattern.bind()
+  uniforms.dashLength = this.dashLength * pixelRatio
+
+  var attributes = shader.attributes
+  attributes.a.pointer(gl.FLOAT, false, 16, 0)
+  attributes.d.pointer(gl.FLOAT, false, 16, 8)
+
+  gl.drawArrays(gl.TRIANGLES, 0, count)
+
+  //Draw mitres
+  if(width > 2 && !this.usingDashes) {
+    var mshader = this.mitreShader
+    mshader.bind()
+
+    var muniforms = mshader.uniforms
+    muniforms.matrix = MATRIX
+    muniforms.color  = color
+    muniforms.screenShape = SCREEN_SHAPE
+    muniforms.radius = width * pixelRatio
+
+    mshader.attributes.p.pointer(gl.FLOAT, false, 48, 0)
+    gl.drawArrays(gl.POINTS, 0, (count/3)|0)
+  }
+}
+})()
+
+proto.drawPick = (function() {
+  var MATRIX = [1, 0, 0,
+                0, 1, 0,
+                0, 0, 1]
+  var SCREEN_SHAPE = [0,0]
+  var PICK_OFFSET = [0,0,0,0]
+  return function(pickOffset) {
+    var plot      = this.plot
+    var shader    = this.pickShader
+    var buffer    = this.lineBuffer
+    var pickBuffer= this.pickBuffer
+    var width     = this.width
+    var numPoints = this.numPoints
+    var bounds    = this.bounds
+    var count     = this.vertCount
+
+    var gl        = plot.gl
+    var viewBox   = plot.viewBox
+    var dataBox   = plot.dataBox
+    var pixelRatio = plot.pickPixelRatio
+
+    var boundX  = bounds[2]  - bounds[0]
+    var boundY  = bounds[3]  - bounds[1]
+    var dataX   = dataBox[2] - dataBox[0]
+    var dataY   = dataBox[3] - dataBox[1]
+    var screenX = viewBox[2] - viewBox[0]
+    var screenY = viewBox[3] - viewBox[1]
+
+    this.pickOffset = pickOffset
+
+    MATRIX[0] = 2.0 * boundX / dataX
+    MATRIX[4] = 2.0 * boundY / dataY
+    MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0
+    MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0
+
+    SCREEN_SHAPE[0] = screenX
+    SCREEN_SHAPE[1] = screenY
+
+    PICK_OFFSET[0] =  pickOffset       & 0xff
+    PICK_OFFSET[1] = (pickOffset>>>8)  & 0xff
+    PICK_OFFSET[2] = (pickOffset>>>16) & 0xff
+    PICK_OFFSET[3] =  pickOffset>>>24
+
+    shader.bind()
+
+    var uniforms = shader.uniforms
+    uniforms.matrix      = MATRIX
+    uniforms.width       = width * pixelRatio
+    uniforms.pickOffset  = PICK_OFFSET
+    uniforms.screenShape = SCREEN_SHAPE
+
+    var attributes = shader.attributes
+
+    buffer.bind()
+    attributes.a.pointer(gl.FLOAT, false, 16, 0)
+    attributes.d.pointer(gl.FLOAT, false, 16, 8)
+
+    pickBuffer.bind()
+    attributes.pick0.pointer(gl.UNSIGNED_BYTE, false, 8, 0)
+    attributes.pick1.pointer(gl.UNSIGNED_BYTE, false, 8, 4)
+
+    gl.drawArrays(gl.TRIANGLES, 0, count)
+
+    return pickOffset + numPoints
+  }
+})()
+
+proto.pick = function(x, y, value) {
+  var pickOffset = this.pickOffset
+  var pointCount = this.numPoints
+  if(value < pickOffset || value >= pickOffset + pointCount) {
+    return null
+  }
+  var pointId = value - pickOffset
+  var points = this.data
+  return {
+    object:    this,
+    pointId:   pointId,
+    dataCoord: [ points[2*pointId], points[2*pointId+1] ]
+  }
+}
+
+function deepCopy(arr) {
+  return arr.map(function(x) {
+    return x.slice()
+  })
+}
+
+proto.update = function(options) {
+  options = options || {}
+
+  var gl = this.plot.gl
+
+  this.color = (options.color || [0,0,1,1]).slice()
+  this.width = +(options.width || 1)
+
+  this.fill      = (options.fill || [false,false,false,false]).slice()
+  this.fillColor = deepCopy(options.fillColor || [[0,0,0,1],
+                     [0,0,0,1],
+                     [0,0,0,1],
+                     [0,0,0,1]])
+
+  var dashes = options.dashes || [1]
+  var dashLength = 0
+  for(var i=0; i<dashes.length; ++i) {
+    dashLength += dashes[i]
+  }
+  var dashData = pool.mallocUint8(dashLength)
+  var ptr = 0
+  var fillColor = 255
+  for(var i=0; i<dashes.length; ++i) {
+    for(var j=0; j<dashes[i]; ++j) {
+      dashData[ptr++] = fillColor
+    }
+    fillColor ^= 255
+  }
+  this.dashPattern.dispose()
+  this.usingDashes = dashes.length > 1
+
+  this.dashPattern = createTexture(gl,
+    ndarray(dashData, [dashLength, 1, 4], [1, 0, 0]))
+  this.dashPattern.minFilter = gl.NEAREST
+  this.dashPattern.magFilter = gl.NEAREST
+  this.dashLength = dashLength
+  pool.free(dashData)
+
+  var data = options.positions
+  this.data = data
+
+  var bounds = this.bounds
+  bounds[0] = bounds[1] = Infinity
+  bounds[2] = bounds[3] = -Infinity
+
+  var numPoints = this.numPoints = data.length>>>1
+  if(numPoints === 0) {
+    return
+  }
+
+  for(var i=0; i<numPoints; ++i) {
+    var ax = data[2*i]
+    var ay = data[2*i+1]
+    bounds[0] = Math.min(bounds[0], ax)
+    bounds[1] = Math.min(bounds[1], ay)
+    bounds[2] = Math.max(bounds[2], ax)
+    bounds[3] = Math.max(bounds[3], ay)
+  }
+
+  if(bounds[0] === bounds[2]) {
+    bounds[2] += 1
+  }
+  if(bounds[3] === bounds[1]) {
+    bounds[3] += 1
+  }
+
+  //Generate line data
+  var lineData    = pool.mallocFloat32(24*(numPoints-1))
+  var pickData    = pool.mallocUint32(12*(numPoints-1))
+  var lineDataPtr = lineData.length
+  var pickDataPtr = pickData.length
+  var ptr = numPoints
+
+  this.vertCount = 6 * (numPoints - 1)
+
+  while(ptr > 1) {
+    var id = --ptr
+    var ax = data[2*ptr]
+    var ay = data[2*ptr+1]
+
+    ax = (ax - bounds[0]) / (bounds[2] - bounds[0])
+    ay = (ay - bounds[1]) / (bounds[3] - bounds[1])
+
+    var next = id-1
+    var bx = data[2*next]
+    var by = data[2*next+1]
+
+    bx = (bx - bounds[0]) / (bounds[2] - bounds[0])
+    by = (by - bounds[1]) / (bounds[3] - bounds[1])
+
+    var dx = bx - ax
+    var dy = by - ay
+
+    var akey0 = id     | (1<<24)
+    var akey1 = (id-1)
+    var bkey0 = id
+    var bkey1 = (id-1) | (1<<24)
+
+    lineData[--lineDataPtr] = -dy
+    lineData[--lineDataPtr] = -dx
+    lineData[--lineDataPtr] = ay
+    lineData[--lineDataPtr] = ax
+    pickData[--pickDataPtr] = akey0
+    pickData[--pickDataPtr] = akey1
+
+    lineData[--lineDataPtr] = dy
+    lineData[--lineDataPtr] = dx
+    lineData[--lineDataPtr] = by
+    lineData[--lineDataPtr] = bx
+    pickData[--pickDataPtr] = bkey0
+    pickData[--pickDataPtr] = bkey1
+
+    lineData[--lineDataPtr] = -dy
+    lineData[--lineDataPtr] = -dx
+    lineData[--lineDataPtr] = by
+    lineData[--lineDataPtr] = bx
+    pickData[--pickDataPtr] = bkey0
+    pickData[--pickDataPtr] = bkey1
+
+    lineData[--lineDataPtr] = dy
+    lineData[--lineDataPtr] = dx
+    lineData[--lineDataPtr] = by
+    lineData[--lineDataPtr] = bx
+    pickData[--pickDataPtr] = bkey0
+    pickData[--pickDataPtr] = bkey1
+
+    lineData[--lineDataPtr] = -dy
+    lineData[--lineDataPtr] = -dx
+    lineData[--lineDataPtr] = ay
+    lineData[--lineDataPtr] = ax
+    pickData[--pickDataPtr] = akey0
+    pickData[--pickDataPtr] = akey1
+
+    lineData[--lineDataPtr] = dy
+    lineData[--lineDataPtr] = dx
+    lineData[--lineDataPtr] = ay
+    lineData[--lineDataPtr] = ax
+    pickData[--pickDataPtr] = akey0
+    pickData[--pickDataPtr] = akey1
+  }
+
+  this.lineBuffer.update(lineData)
+  this.pickBuffer.update(pickData)
+
+  pool.free(lineData)
+  pool.free(pickData)
+}
+
+proto.dispose = function() {
+  this.plot.removeObject(this)
+  this.lineBuffer.dispose()
+  this.pickBuffer.dispose()
+  this.lineShader.dispose()
+  this.mitreShader.dispose()
+  this.fillShader.dispose()
+  this.pickShader.dispose()
+  this.dashPattern.dispose()
+}
+
+function createLinePlot(plot, options) {
+  var gl = plot.gl
+  var lineBuffer  = createBuffer(gl)
+  var pickBuffer  = createBuffer(gl)
+  var dashPattern = createTexture(gl, [1,1])
+  var lineShader  = createShader(gl, SHADERS.lineVertex,  SHADERS.lineFragment)
+  var mitreShader = createShader(gl, SHADERS.mitreVertex, SHADERS.mitreFragment)
+  var fillShader  = createShader(gl, SHADERS.fillVertex,  SHADERS.fillFragment)
+  var pickShader  = createShader(gl, SHADERS.pickVertex,  SHADERS.pickFragment)
+  var linePlot    = new GLLine2D(
+    plot,
+    dashPattern,
+    lineBuffer,
+    pickBuffer,
+    lineShader,
+    mitreShader,
+    fillShader,
+    pickShader)
+  plot.addObject(linePlot)
+  linePlot.update(options)
+  return linePlot
+}
+
+},{"./lib/shaders":81,"gl-buffer":75,"gl-shader":154,"gl-texture2d":185,"ndarray":208,"typedarray-pool":233}],83:[function(require,module,exports){
+
+var createShader  = require('gl-shader')
+
+var vertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n  vec4 projected = projection * view * model * vec4(position, 1.0);\n  vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n  vec2 tangent = normalize(screenShape * tangentClip.xy);\n  vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n  gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n  worldPosition = position;\n  pixelArcLength = arcLength;\n  fragColor = color;\n}\n"
+var forwardFrag = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec3      clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float     dashScale;\nuniform float     opacity;\n\nvarying vec3    worldPosition;\nvarying float   pixelArcLength;\nvarying vec4    fragColor;\n\nvoid main() {\n  if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n    discard;\n  }\n  float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n  if(dashWeight < 0.5) {\n    discard;\n  }\n  gl_FragColor = fragColor * opacity;\n}\n"
+var pickFrag = "#define GLSLIFY 1\nprecision mediump float;\n\n#define FLOAT_MAX  1.70141184e38\n#define FLOAT_MIN  1.17549435e-38\n\nlowp vec4 encode_float_1_0(highp float v) {\n  highp float av = abs(v);\n\n  //Handle special cases\n  if(av < FLOAT_MIN) {\n    return vec4(0.0, 0.0, 0.0, 0.0);\n  } else if(v > FLOAT_MAX) {\n    return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n  } else if(v < -FLOAT_MAX) {\n    return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n  }\n\n  highp vec4 c = vec4(0,0,0,0);\n\n  //Compute exponent and mantissa\n  highp float e = floor(log2(av));\n  highp float m = av * pow(2.0, -e) - 1.0;\n  \n  //Unpack mantissa\n  c[1] = floor(128.0 * m);\n  m -= c[1] / 128.0;\n  c[2] = floor(32768.0 * m);\n  m -= c[2] / 32768.0;\n  c[3] = floor(8388608.0 * m);\n  \n  //Unpack exponent\n  highp float ebias = e + 127.0;\n  c[0] = floor(ebias / 2.0);\n  ebias -= c[0] * 2.0;\n  c[1] += floor(ebias) * 128.0; \n\n  //Unpack sign bit\n  c[0] += 128.0 * step(0.0, -v);\n\n  //Scale back to range\n  return c / 255.0;\n}\n\n\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n  if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n    discard;\n  }\n  gl_FragColor = vec4(pickId/255.0, encode_float_1_0(pixelArcLength).xyz);\n}"
+
+var ATTRIBUTES = [
+  {name: 'position', type: 'vec3'},
+  {name: 'nextPosition', type: 'vec3'},
+  {name: 'arcLength', type: 'float'},
+  {name: 'lineWidth', type: 'float'},
+  {name: 'color', type: 'vec4'}
+]
+
+exports.createShader = function(gl) {
+  return createShader(gl, vertSrc, forwardFrag, null, ATTRIBUTES)
+}
+
+exports.createPickShader = function(gl) {
+  return createShader(gl, vertSrc, pickFrag, null, ATTRIBUTES)
+}
+
+},{"gl-shader":154}],84:[function(require,module,exports){
+'use strict'
+
+module.exports = createLinePlot
+
+var createBuffer  = require('gl-buffer')
+var createVAO     = require('gl-vao')
+var createTexture = require('gl-texture2d')
+var unpackFloat   = require('glsl-read-float')
+var bsearch       = require('binary-search-bounds')
+var ndarray       = require('ndarray')
+var shaders       = require('./lib/shaders')
+
+var createShader      = shaders.createShader
+var createPickShader  = shaders.createPickShader
+
+var identity = [1,0,0,0,
+                0,1,0,0,
+                0,0,1,0,
+                0,0,0,1]
+
+function distance(a, b) {
+  var s = 0.0
+  for(var i=0; i<3; ++i) {
+    var d = a[i] - b[i]
+    s += d*d
+  }
+  return Math.sqrt(s)
+}
+
+function filterClipBounds(bounds) {
+  var result = [[-1e6,-1e6,-1e6], [1e6,1e6,1e6]]
+  for(var i=0; i<3; ++i) {
+    result[0][i] = Math.max(bounds[0][i], result[0][i])
+    result[1][i] = Math.min(bounds[1][i], result[1][i])
+  }
+  return result
+}
+
+function PickResult(tau, position, index, dataCoordinate) {
+  this.arcLength = tau
+  this.position  = position
+  this.index     = index
+  this.dataCoordinate = dataCoordinate
+}
+
+function LinePlot(gl, shader, pickShader, buffer, vao, texture) {
+  this.gl           = gl
+  this.shader       = shader
+  this.pickShader   = pickShader
+  this.buffer       = buffer
+  this.vao          = vao
+  this.clipBounds   = [[-Infinity,-Infinity,-Infinity],
+                       [ Infinity, Infinity, Infinity]]
+  this.points       = []
+  this.arcLength    = []
+  this.vertexCount  = 0
+  this.bounds       = [[0,0,0],[0,0,0]]
+  this.pickId       = 0
+  this.lineWidth    = 1
+  this.texture      = texture
+  this.dashScale    = 1
+  this.opacity      = 1
+  this.dirty        = true
+  this.pixelRatio   = 1
+}
+
+var proto = LinePlot.prototype
+
+proto.isTransparent = function() {
+  return this.opacity < 1
+}
+
+proto.isOpaque = function() {
+  return this.opacity >= 1
+}
+
+proto.pickSlots = 1
+
+proto.setPickBase = function(id) {
+  this.pickId = id
+}
+
+proto.drawTransparent = proto.draw = function(camera) {
+  var gl      = this.gl
+  var shader  = this.shader
+  var vao     = this.vao
+  shader.bind()
+  shader.uniforms = {
+    model:        camera.model      || identity,
+    view:         camera.view       || identity,
+    projection:   camera.projection || identity,
+    clipBounds:   filterClipBounds(this.clipBounds),
+    dashTexture:  this.texture.bind(),
+    dashScale:    this.dashScale / this.arcLength[this.arcLength.length-1],
+    opacity:      this.opacity,
+    screenShape:  [gl.drawingBufferWidth, gl.drawingBufferHeight],
+    pixelRatio:   this.pixelRatio
+  }
+  vao.bind()
+  vao.draw(gl.TRIANGLE_STRIP, this.vertexCount)
+}
+
+proto.drawPick = function(camera) {
+  var gl      = this.gl
+  var shader  = this.pickShader
+  var vao     = this.vao
+  shader.bind()
+  shader.uniforms = {
+    model:      camera.model      || identity,
+    view:       camera.view       || identity,
+    projection: camera.projection || identity,
+    pickId:     this.pickId,
+    clipBounds: filterClipBounds(this.clipBounds),
+    screenShape:  [gl.drawingBufferWidth, gl.drawingBufferHeight],
+    pixelRatio:   this.pixelRatio
+  }
+  vao.bind()
+  vao.draw(gl.TRIANGLE_STRIP, this.vertexCount)
+}
+
+proto.update = function(options) {
+  this.dirty = true
+
+  if('dashScale' in options) {
+    this.dashScale = options.dashScale
+  }
+  if('opacity' in options) {
+    this.opacity = +options.opacity
+  }
+
+  var positions = options.position || options.positions
+  if(!positions) {
+    return
+  }
+
+  //Default color
+  var colors = options.color || options.colors || [0,0,0,1]
+
+  var lineWidth = options.lineWidth || 1
+
+  //Recalculate buffer data
+  var buffer          = []
+  var arcLengthArray  = []
+  var pointArray      = []
+  var arcLength       = 0.0
+  var vertexCount     = 0
+  var bounds = [[ Infinity, Infinity, Infinity],
+                [-Infinity,-Infinity,-Infinity]]
+
+fill_loop:
+  for(var i=1; i<positions.length; ++i) {
+    var a = positions[i-1]
+    var b = positions[i]
+
+    arcLengthArray.push(arcLength)
+    pointArray.push(a.slice())
+
+    for(var j=0; j<3; ++j) {
+      if(isNaN(a[j]) || isNaN(b[j]) ||
+        !isFinite(a[j]) || !isFinite(b[j])) {
+        continue fill_loop
+      }
+      bounds[0][j] = Math.min(bounds[0][j], a[j], b[j])
+      bounds[1][j] = Math.max(bounds[1][j], a[j], b[j])
+    }
+
+    var acolor, bcolor
+    if(Array.isArray(colors[0])) {
+      acolor = colors[i-1]
+      bcolor = colors[i]
+    } else {
+      acolor = bcolor = colors
+    }
+    if(acolor.length === 3) {
+      acolor = [acolor[0], acolor[1], acolor[2], 1]
+    }
+    if(bcolor.length === 3) {
+      bcolor = [bcolor[0], bcolor[1], bcolor[2], 1]
+    }
+
+    var w0, w1
+    if(Array.isArray(lineWidth)) {
+      w0 = lineWidth[i-1]
+      w1 = lineWidht[i]
+    } else {
+      w0 = w1 = lineWidth
+    }
+
+    var t0 = arcLength
+    arcLength += distance(a, b)
+
+    buffer.push(
+      a[0], a[1], a[2], b[0], b[1], b[2], t0, w0, acolor[0], acolor[1], acolor[2], acolor[3],
+      a[0], a[1], a[2], b[0], b[1], b[2], t0,-w0, acolor[0], acolor[1], acolor[2], acolor[3],
+      b[0], b[1], b[2], a[0], a[1], a[2], arcLength,-w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3],
+      b[0], b[1], b[2], a[0], a[1], a[2], arcLength, w0, bcolor[0], bcolor[1], bcolor[2], bcolor[3])
+
+    vertexCount += 4
+  }
+  this.buffer.update(buffer)
+
+  arcLengthArray.push(arcLength)
+  pointArray.push(positions[positions.length-1].slice())
+
+  this.bounds = bounds
+
+  this.vertexCount = vertexCount
+
+  this.points = pointArray
+  this.arcLength = arcLengthArray
+
+  if('dashes' in options) {
+    var dashArray = options.dashes
+
+    //Calculate prefix sum
+    var prefixSum = dashArray.slice()
+    prefixSum.unshift(0)
+    for(var i=1; i<prefixSum.length; ++i) {
+      prefixSum[i] = prefixSum[i-1] + prefixSum[i]
+    }
+
+    var dashTexture = ndarray(new Array(256*4), [256, 1, 4])
+    for(var i=0; i<256; ++i) {
+      for(var j=0; j<4; ++j) {
+        dashTexture.set(i,0,j, 0)
+      }
+      if(bsearch.le(prefixSum, prefixSum[prefixSum.length-1]*i/255.0) & 1) {
+        dashTexture.set(i,0,0, 0)
+      } else {
+        dashTexture.set(i,0,0, 255)
+      }
+    }
+
+    this.texture.setPixels(dashTexture)
+  }
+}
+
+proto.dispose = function() {
+  this.shader.dispose()
+  this.vao.dispose()
+  this.buffer.dispose()
+}
+
+proto.pick = function(selection) {
+  if(!selection) {
+    return null
+  }
+  if(selection.id !== this.pickId) {
+    return null
+  }
+  var tau = unpackFloat(
+    selection.value[0],
+    selection.value[1],
+    selection.value[2],
+    0)
+  var index = bsearch.le(this.arcLength, tau)
+  if(index < 0) {
+    return null
+  }
+  if(index === this.arcLength.length-1) {
+    return new PickResult(
+      this.arcLength[this.arcLength.length-1],
+      this.points[this.points.length-1].slice(),
+      index)
+  }
+  var a = this.points[index]
+  var b = this.points[Math.min(index+1, this.points.length-1)]
+  var t = (tau - this.arcLength[index]) / (this.arcLength[index+1] - this.arcLength[index])
+  var ti = 1.0 - t
+  var x = [0,0,0]
+  for(var i=0; i<3; ++i) {
+    x[i] = ti * a[i] + t * b[i]
+  }
+  var dataIndex = Math.min((t < 0.5) ? index : (index+1), this.points.length-1)
+  return new PickResult(
+    tau,
+    x,
+    dataIndex,
+    this.points[dataIndex])
+}
+
+function createLinePlot(options) {
+  var gl = options.gl || (options.scene && options.scene.gl)
+
+  var shader = createShader(gl)
+  shader.attributes.position.location     = 0
+  shader.attributes.nextPosition.location = 1
+  shader.attributes.arcLength.location    = 2
+  shader.attributes.lineWidth.location    = 3
+  shader.attributes.color.location        = 4
+
+  var pickShader = createPickShader(gl)
+  pickShader.attributes.position.location     = 0
+  pickShader.attributes.nextPosition.location = 1
+  pickShader.attributes.arcLength.location    = 2
+  pickShader.attributes.lineWidth.location    = 3
+  pickShader.attributes.color.location        = 4
+
+  var buffer = createBuffer(gl)
+  var vao = createVAO(gl, [
+      {
+        'buffer': buffer,
+        'size': 3,
+        'offset': 0,
+        'stride': 48
+      },
+      {
+        'buffer': buffer,
+        'size': 3,
+        'offset': 12,
+        'stride': 48
+      },
+      {
+        'buffer': buffer,
+        'size': 1,
+        'offset': 24,
+        'stride': 48
+      },
+      {
+        'buffer': buffer,
+        'size': 1,
+        'offset': 28,
+        'stride': 48
+      },
+      {
+        'buffer': buffer,
+        'size': 4,
+        'offset': 32,
+        'stride': 48
+      }
+    ])
+
+  //Create texture for dash pattern
+  var defaultTexture = ndarray(new Array(256*4), [256,1,4])
+  for(var i=0; i<256*4; ++i) {
+    defaultTexture.data[i] = 255
+  }
+  var texture = createTexture(gl, defaultTexture)
+  texture.wrap = gl.REPEAT
+
+  var linePlot = new LinePlot(gl, shader, pickShader, buffer, vao, texture)
+  linePlot.update(options)
+  return linePlot
+}
+
+},{"./lib/shaders":83,"binary-search-bounds":85,"gl-buffer":75,"gl-texture2d":185,"gl-vao":189,"glsl-read-float":86,"ndarray":208}],85:[function(require,module,exports){
+arguments[4][20][0].apply(exports,arguments)
+},{"dup":20}],86:[function(require,module,exports){
+module.exports = decodeFloat
+
+var UINT8_VIEW = new Uint8Array(4)
+var FLOAT_VIEW = new Float32Array(UINT8_VIEW.buffer)
+
+function decodeFloat(x, y, z, w) {
+  UINT8_VIEW[0] = w
+  UINT8_VIEW[1] = z
+  UINT8_VIEW[2] = y
+  UINT8_VIEW[3] = x
+  return FLOAT_VIEW[0]
+}
+
+},{}],87:[function(require,module,exports){
+module.exports = invert
+
+/**
+ * Inverts a mat3
+ *
+ * @alias mat3.invert
+ * @param {mat3} out the receiving matrix
+ * @param {mat3} a the source matrix
+ * @returns {mat3} out
+ */
+function invert(out, a) {
+  var a00 = a[0], a01 = a[1], a02 = a[2]
+  var a10 = a[3], a11 = a[4], a12 = a[5]
+  var a20 = a[6], a21 = a[7], a22 = a[8]
+
+  var b01 = a22 * a11 - a12 * a21
+  var b11 = -a22 * a10 + a12 * a20
+  var b21 = a21 * a10 - a11 * a20
+
+  // Calculate the determinant
+  var det = a00 * b01 + a01 * b11 + a02 * b21
+
+  if (!det) return null
+  det = 1.0 / det
+
+  out[0] = b01 * det
+  out[1] = (-a22 * a01 + a02 * a21) * det
+  out[2] = (a12 * a01 - a02 * a11) * det
+  out[3] = b11 * det
+  out[4] = (a22 * a00 - a02 * a20) * det
+  out[5] = (-a12 * a00 + a02 * a10) * det
+  out[6] = b21 * det
+  out[7] = (-a21 * a00 + a01 * a20) * det
+  out[8] = (a11 * a00 - a01 * a10) * det
+
+  return out
+}
+
+},{}],88:[function(require,module,exports){
+module.exports = clone;
+
+/**
+ * Creates a new mat4 initialized with values from an existing matrix
+ *
+ * @param {mat4} a matrix to clone
+ * @returns {mat4} a new 4x4 matrix
+ */
+function clone(a) {
+    var out = new Float32Array(16);
+    out[0] = a[0];
+    out[1] = a[1];
+    out[2] = a[2];
+    out[3] = a[3];
+    out[4] = a[4];
+    out[5] = a[5];
+    out[6] = a[6];
+    out[7] = a[7];
+    out[8] = a[8];
+    out[9] = a[9];
+    out[10] = a[10];
+    out[11] = a[11];
+    out[12] = a[12];
+    out[13] = a[13];
+    out[14] = a[14];
+    out[15] = a[15];
+    return out;
+};
+},{}],89:[function(require,module,exports){
+module.exports = create;
+
+/**
+ * Creates a new identity mat4
+ *
+ * @returns {mat4} a new 4x4 matrix
+ */
+function create() {
+    var out = new Float32Array(16);
+    out[0] = 1;
+    out[1] = 0;
+    out[2] = 0;
+    out[3] = 0;
+    out[4] = 0;
+    out[5] = 1;
+    out[6] = 0;
+    out[7] = 0;
+    out[8] = 0;
+    out[9] = 0;
+    out[10] = 1;
+    out[11] = 0;
+    out[12] = 0;
+    out[13] = 0;
+    out[14] = 0;
+    out[15] = 1;
+    return out;
+};
+},{}],90:[function(require,module,exports){
+module.exports = determinant;
+
+/**
+ * Calculates the determinant of a mat4
+ *
+ * @param {mat4} a the source matrix
+ * @returns {Number} determinant of a
+ */
+function determinant(a) {
+    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
+        a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
+        a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
+        a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
+
+        b00 = a00 * a11 - a01 * a10,
+        b01 = a00 * a12 - a02 * a10,
+        b02 = a00 * a13 - a03 * a10,
+        b03 = a01 * a12 - a02 * a11,
+        b04 = a01 * a13 - a03 * a11,
+        b05 = a02 * a13 - a03 * a12,
+        b06 = a20 * a31 - a21 * a30,
+        b07 = a20 * a32 - a22 * a30,
+        b08 = a20 * a33 - a23 * a30,
+        b09 = a21 * a32 - a22 * a31,
+        b10 = a21 * a33 - a23 * a31,
+        b11 = a22 * a33 - a23 * a32;
+
+    // Calculate the determinant
+    return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
+};
+},{}],91:[function(require,module,exports){
+module.exports = fromQuat;
+
+/**
+ * Creates a matrix from a quaternion rotation.
+ *
+ * @param {mat4} out mat4 receiving operation result
+ * @param {quat4} q Rotation quaternion
+ * @returns {mat4} out
+ */
+function fromQuat(out, q) {
+    var x = q[0], y = q[1], z = q[2], w = q[3],
+        x2 = x + x,
+        y2 = y + y,
+        z2 = z + z,
+
+        xx = x * x2,
+        yx = y * x2,
+        yy = y * y2,
+        zx = z * x2,
+        zy = z * y2,
+        zz = z * z2,
+        wx = w * x2,
+        wy = w * y2,
+        wz = w * z2;
+
+    out[0] = 1 - yy - zz;
+    out[1] = yx + wz;
+    out[2] = zx - wy;
+    out[3] = 0;
+
+    out[4] = yx - wz;
+    out[5] = 1 - xx - zz;
+    out[6] = zy + wx;
+    out[7] = 0;
+
+    out[8] = zx + wy;
+    out[9] = zy - wx;
+    out[10] = 1 - xx - yy;
+    out[11] = 0;
+
+    out[12] = 0;
+    out[13] = 0;
+    out[14] = 0;
+    out[15] = 1;
+
+    return out;
+};
+},{}],92:[function(require,module,exports){
+module.exports = fromRotationTranslation;
+
+/**
+ * Creates a matrix from a quaternion rotation and vector translation
+ * This is equivalent to (but much faster than):
+ *
+ *     mat4.identity(dest);
+ *     mat4.translate(dest, vec);
+ *     var quatMat = mat4.create();
+ *     quat4.toMat4(quat, quatMat);
+ *     mat4.multiply(dest, quatMat);
+ *
+ * @param {mat4} out mat4 receiving operation result
+ * @param {quat4} q Rotation quaternion
+ * @param {vec3} v Translation vector
+ * @returns {mat4} out
+ */
+function fromRotationTranslation(out, q, v) {
+    // Quaternion math
+    var x = q[0], y = q[1], z = q[2], w = q[3],
+        x2 = x + x,
+        y2 = y + y,
+        z2 = z + z,
+
+        xx = x * x2,
+        xy = x * y2,
+        xz = x * z2,
+        yy = y * y2,
+        yz = y * z2,
+        zz = z * z2,
+        wx = w * x2,
+        wy = w * y2,
+        wz = w * z2;
+
+    out[0] = 1 - (yy + zz);
+    out[1] = xy + wz;
+    out[2] = xz - wy;
+    out[3] = 0;
+    out[4] = xy - wz;
+    out[5] = 1 - (xx + zz);
+    out[6] = yz + wx;
+    out[7] = 0;
+    out[8] = xz + wy;
+    out[9] = yz - wx;
+    out[10] = 1 - (xx + yy);
+    out[11] = 0;
+    out[12] = v[0];
+    out[13] = v[1];
+    out[14] = v[2];
+    out[15] = 1;
+    
+    return out;
+};
+},{}],93:[function(require,module,exports){
+module.exports = identity;
+
+/**
+ * Set a mat4 to the identity matrix
+ *
+ * @param {mat4} out the receiving matrix
+ * @returns {mat4} out
+ */
+function identity(out) {
+    out[0] = 1;
+    out[1] = 0;
+    out[2] = 0;
+    out[3] = 0;
+    out[4] = 0;
+    out[5] = 1;
+    out[6] = 0;
+    out[7] = 0;
+    out[8] = 0;
+    out[9] = 0;
+    out[10] = 1;
+    out[11] = 0;
+    out[12] = 0;
+    out[13] = 0;
+    out[14] = 0;
+    out[15] = 1;
+    return out;
+};
+},{}],94:[function(require,module,exports){
+module.exports = invert;
+
+/**
+ * Inverts a mat4
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the source matrix
+ * @returns {mat4} out
+ */
+function invert(out, a) {
+    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
+        a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
+        a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
+        a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
+
+        b00 = a00 * a11 - a01 * a10,
+        b01 = a00 * a12 - a02 * a10,
+        b02 = a00 * a13 - a03 * a10,
+        b03 = a01 * a12 - a02 * a11,
+        b04 = a01 * a13 - a03 * a11,
+        b05 = a02 * a13 - a03 * a12,
+        b06 = a20 * a31 - a21 * a30,
+        b07 = a20 * a32 - a22 * a30,
+        b08 = a20 * a33 - a23 * a30,
+        b09 = a21 * a32 - a22 * a31,
+        b10 = a21 * a33 - a23 * a31,
+        b11 = a22 * a33 - a23 * a32,
+
+        // Calculate the determinant
+        det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
+
+    if (!det) { 
+        return null; 
+    }
+    det = 1.0 / det;
+
+    out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
+    out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
+    out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
+    out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
+    out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
+    out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
+    out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
+    out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
+    out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
+    out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
+    out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
+    out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
+    out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
+    out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
+    out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
+    out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
+
+    return out;
+};
+},{}],95:[function(require,module,exports){
+var identity = require('./identity');
+
+module.exports = lookAt;
+
+/**
+ * Generates a look-at matrix with the given eye position, focal point, and up axis
+ *
+ * @param {mat4} out mat4 frustum matrix will be written into
+ * @param {vec3} eye Position of the viewer
+ * @param {vec3} center Point the viewer is looking at
+ * @param {vec3} up vec3 pointing up
+ * @returns {mat4} out
+ */
+function lookAt(out, eye, center, up) {
+    var x0, x1, x2, y0, y1, y2, z0, z1, z2, len,
+        eyex = eye[0],
+        eyey = eye[1],
+        eyez = eye[2],
+        upx = up[0],
+        upy = up[1],
+        upz = up[2],
+        centerx = center[0],
+        centery = center[1],
+        centerz = center[2];
+
+    if (Math.abs(eyex - centerx) < 0.000001 &&
+        Math.abs(eyey - centery) < 0.000001 &&
+        Math.abs(eyez - centerz) < 0.000001) {
+        return identity(out);
+    }
+
+    z0 = eyex - centerx;
+    z1 = eyey - centery;
+    z2 = eyez - centerz;
+
+    len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
+    z0 *= len;
+    z1 *= len;
+    z2 *= len;
+
+    x0 = upy * z2 - upz * z1;
+    x1 = upz * z0 - upx * z2;
+    x2 = upx * z1 - upy * z0;
+    len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
+    if (!len) {
+        x0 = 0;
+        x1 = 0;
+        x2 = 0;
+    } else {
+        len = 1 / len;
+        x0 *= len;
+        x1 *= len;
+        x2 *= len;
+    }
+
+    y0 = z1 * x2 - z2 * x1;
+    y1 = z2 * x0 - z0 * x2;
+    y2 = z0 * x1 - z1 * x0;
+
+    len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
+    if (!len) {
+        y0 = 0;
+        y1 = 0;
+        y2 = 0;
+    } else {
+        len = 1 / len;
+        y0 *= len;
+        y1 *= len;
+        y2 *= len;
+    }
+
+    out[0] = x0;
+    out[1] = y0;
+    out[2] = z0;
+    out[3] = 0;
+    out[4] = x1;
+    out[5] = y1;
+    out[6] = z1;
+    out[7] = 0;
+    out[8] = x2;
+    out[9] = y2;
+    out[10] = z2;
+    out[11] = 0;
+    out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
+    out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
+    out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
+    out[15] = 1;
+
+    return out;
+};
+},{"./identity":93}],96:[function(require,module,exports){
+module.exports = multiply;
+
+/**
+ * Multiplies two mat4's
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the first operand
+ * @param {mat4} b the second operand
+ * @returns {mat4} out
+ */
+function multiply(out, a, b) {
+    var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
+        a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
+        a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
+        a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
+
+    // Cache only the current line of the second matrix
+    var b0  = b[0], b1 = b[1], b2 = b[2], b3 = b[3];  
+    out[0] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+    out[1] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+    out[2] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+    out[3] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+    b0 = b[4]; b1 = b[5]; b2 = b[6]; b3 = b[7];
+    out[4] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+    out[5] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+    out[6] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+    out[7] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+    b0 = b[8]; b1 = b[9]; b2 = b[10]; b3 = b[11];
+    out[8] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+    out[9] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+    out[10] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+    out[11] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+
+    b0 = b[12]; b1 = b[13]; b2 = b[14]; b3 = b[15];
+    out[12] = b0*a00 + b1*a10 + b2*a20 + b3*a30;
+    out[13] = b0*a01 + b1*a11 + b2*a21 + b3*a31;
+    out[14] = b0*a02 + b1*a12 + b2*a22 + b3*a32;
+    out[15] = b0*a03 + b1*a13 + b2*a23 + b3*a33;
+    return out;
+};
+},{}],97:[function(require,module,exports){
+module.exports = perspective;
+
+/**
+ * Generates a perspective projection matrix with the given bounds
+ *
+ * @param {mat4} out mat4 frustum matrix will be written into
+ * @param {number} fovy Vertical field of view in radians
+ * @param {number} aspect Aspect ratio. typically viewport width/height
+ * @param {number} near Near bound of the frustum
+ * @param {number} far Far bound of the frustum
+ * @returns {mat4} out
+ */
+function perspective(out, fovy, aspect, near, far) {
+    var f = 1.0 / Math.tan(fovy / 2),
+        nf = 1 / (near - far);
+    out[0] = f / aspect;
+    out[1] = 0;
+    out[2] = 0;
+    out[3] = 0;
+    out[4] = 0;
+    out[5] = f;
+    out[6] = 0;
+    out[7] = 0;
+    out[8] = 0;
+    out[9] = 0;
+    out[10] = (far + near) * nf;
+    out[11] = -1;
+    out[12] = 0;
+    out[13] = 0;
+    out[14] = (2 * far * near) * nf;
+    out[15] = 0;
+    return out;
+};
+},{}],98:[function(require,module,exports){
+module.exports = rotate;
+
+/**
+ * Rotates a mat4 by the given angle
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @param {vec3} axis the axis to rotate around
+ * @returns {mat4} out
+ */
+function rotate(out, a, rad, axis) {
+    var x = axis[0], y = axis[1], z = axis[2],
+        len = Math.sqrt(x * x + y * y + z * z),
+        s, c, t,
+        a00, a01, a02, a03,
+        a10, a11, a12, a13,
+        a20, a21, a22, a23,
+        b00, b01, b02,
+        b10, b11, b12,
+        b20, b21, b22;
+
+    if (Math.abs(len) < 0.000001) { return null; }
+    
+    len = 1 / len;
+    x *= len;
+    y *= len;
+    z *= len;
+
+    s = Math.sin(rad);
+    c = Math.cos(rad);
+    t = 1 - c;
+
+    a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
+    a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
+    a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
+
+    // Construct the elements of the rotation matrix
+    b00 = x * x * t + c; b01 = y * x * t + z * s; b02 = z * x * t - y * s;
+    b10 = x * y * t - z * s; b11 = y * y * t + c; b12 = z * y * t + x * s;
+    b20 = x * z * t + y * s; b21 = y * z * t - x * s; b22 = z * z * t + c;
+
+    // Perform rotation-specific matrix multiplication
+    out[0] = a00 * b00 + a10 * b01 + a20 * b02;
+    out[1] = a01 * b00 + a11 * b01 + a21 * b02;
+    out[2] = a02 * b00 + a12 * b01 + a22 * b02;
+    out[3] = a03 * b00 + a13 * b01 + a23 * b02;
+    out[4] = a00 * b10 + a10 * b11 + a20 * b12;
+    out[5] = a01 * b10 + a11 * b11 + a21 * b12;
+    out[6] = a02 * b10 + a12 * b11 + a22 * b12;
+    out[7] = a03 * b10 + a13 * b11 + a23 * b12;
+    out[8] = a00 * b20 + a10 * b21 + a20 * b22;
+    out[9] = a01 * b20 + a11 * b21 + a21 * b22;
+    out[10] = a02 * b20 + a12 * b21 + a22 * b22;
+    out[11] = a03 * b20 + a13 * b21 + a23 * b22;
+
+    if (a !== out) { // If the source and destination differ, copy the unchanged last row
+        out[12] = a[12];
+        out[13] = a[13];
+        out[14] = a[14];
+        out[15] = a[15];
+    }
+    return out;
+};
+},{}],99:[function(require,module,exports){
+module.exports = rotateX;
+
+/**
+ * Rotates a matrix by the given angle around the X axis
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat4} out
+ */
+function rotateX(out, a, rad) {
+    var s = Math.sin(rad),
+        c = Math.cos(rad),
+        a10 = a[4],
+        a11 = a[5],
+        a12 = a[6],
+        a13 = a[7],
+        a20 = a[8],
+        a21 = a[9],
+        a22 = a[10],
+        a23 = a[11];
+
+    if (a !== out) { // If the source and destination differ, copy the unchanged rows
+        out[0]  = a[0];
+        out[1]  = a[1];
+        out[2]  = a[2];
+        out[3]  = a[3];
+        out[12] = a[12];
+        out[13] = a[13];
+        out[14] = a[14];
+        out[15] = a[15];
+    }
+
+    // Perform axis-specific matrix multiplication
+    out[4] = a10 * c + a20 * s;
+    out[5] = a11 * c + a21 * s;
+    out[6] = a12 * c + a22 * s;
+    out[7] = a13 * c + a23 * s;
+    out[8] = a20 * c - a10 * s;
+    out[9] = a21 * c - a11 * s;
+    out[10] = a22 * c - a12 * s;
+    out[11] = a23 * c - a13 * s;
+    return out;
+};
+},{}],100:[function(require,module,exports){
+module.exports = rotateY;
+
+/**
+ * Rotates a matrix by the given angle around the Y axis
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat4} out
+ */
+function rotateY(out, a, rad) {
+    var s = Math.sin(rad),
+        c = Math.cos(rad),
+        a00 = a[0],
+        a01 = a[1],
+        a02 = a[2],
+        a03 = a[3],
+        a20 = a[8],
+        a21 = a[9],
+        a22 = a[10],
+        a23 = a[11];
+
+    if (a !== out) { // If the source and destination differ, copy the unchanged rows
+        out[4]  = a[4];
+        out[5]  = a[5];
+        out[6]  = a[6];
+        out[7]  = a[7];
+        out[12] = a[12];
+        out[13] = a[13];
+        out[14] = a[14];
+        out[15] = a[15];
+    }
+
+    // Perform axis-specific matrix multiplication
+    out[0] = a00 * c - a20 * s;
+    out[1] = a01 * c - a21 * s;
+    out[2] = a02 * c - a22 * s;
+    out[3] = a03 * c - a23 * s;
+    out[8] = a00 * s + a20 * c;
+    out[9] = a01 * s + a21 * c;
+    out[10] = a02 * s + a22 * c;
+    out[11] = a03 * s + a23 * c;
+    return out;
+};
+},{}],101:[function(require,module,exports){
+module.exports = rotateZ;
+
+/**
+ * Rotates a matrix by the given angle around the Z axis
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to rotate
+ * @param {Number} rad the angle to rotate the matrix by
+ * @returns {mat4} out
+ */
+function rotateZ(out, a, rad) {
+    var s = Math.sin(rad),
+        c = Math.cos(rad),
+        a00 = a[0],
+        a01 = a[1],
+        a02 = a[2],
+        a03 = a[3],
+        a10 = a[4],
+        a11 = a[5],
+        a12 = a[6],
+        a13 = a[7];
+
+    if (a !== out) { // If the source and destination differ, copy the unchanged last row
+        out[8]  = a[8];
+        out[9]  = a[9];
+        out[10] = a[10];
+        out[11] = a[11];
+        out[12] = a[12];
+        out[13] = a[13];
+        out[14] = a[14];
+        out[15] = a[15];
+    }
+
+    // Perform axis-specific matrix multiplication
+    out[0] = a00 * c + a10 * s;
+    out[1] = a01 * c + a11 * s;
+    out[2] = a02 * c + a12 * s;
+    out[3] = a03 * c + a13 * s;
+    out[4] = a10 * c - a00 * s;
+    out[5] = a11 * c - a01 * s;
+    out[6] = a12 * c - a02 * s;
+    out[7] = a13 * c - a03 * s;
+    return out;
+};
+},{}],102:[function(require,module,exports){
+module.exports = scale;
+
+/**
+ * Scales the mat4 by the dimensions in the given vec3
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to scale
+ * @param {vec3} v the vec3 to scale the matrix by
+ * @returns {mat4} out
+ **/
+function scale(out, a, v) {
+    var x = v[0], y = v[1], z = v[2];
+
+    out[0] = a[0] * x;
+    out[1] = a[1] * x;
+    out[2] = a[2] * x;
+    out[3] = a[3] * x;
+    out[4] = a[4] * y;
+    out[5] = a[5] * y;
+    out[6] = a[6] * y;
+    out[7] = a[7] * y;
+    out[8] = a[8] * z;
+    out[9] = a[9] * z;
+    out[10] = a[10] * z;
+    out[11] = a[11] * z;
+    out[12] = a[12];
+    out[13] = a[13];
+    out[14] = a[14];
+    out[15] = a[15];
+    return out;
+};
+},{}],103:[function(require,module,exports){
+module.exports = translate;
+
+/**
+ * Translate a mat4 by the given vector
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the matrix to translate
+ * @param {vec3} v vector to translate by
+ * @returns {mat4} out
+ */
+function translate(out, a, v) {
+    var x = v[0], y = v[1], z = v[2],
+        a00, a01, a02, a03,
+        a10, a11, a12, a13,
+        a20, a21, a22, a23;
+
+    if (a === out) {
+        out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
+        out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
+        out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
+        out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
+    } else {
+        a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
+        a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
+        a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
+
+        out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
+        out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
+        out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;
+
+        out[12] = a00 * x + a10 * y + a20 * z + a[12];
+        out[13] = a01 * x + a11 * y + a21 * z + a[13];
+        out[14] = a02 * x + a12 * y + a22 * z + a[14];
+        out[15] = a03 * x + a13 * y + a23 * z + a[15];
+    }
+
+    return out;
+};
+},{}],104:[function(require,module,exports){
+module.exports = transpose;
+
+/**
+ * Transpose the values of a mat4
+ *
+ * @param {mat4} out the receiving matrix
+ * @param {mat4} a the source matrix
+ * @returns {mat4} out
+ */
+function transpose(out, a) {
+    // If we are transposing ourselves we can skip a few steps but have to cache some values
+    if (out === a) {
+        var a01 = a[1], a02 = a[2], a03 = a[3],
+            a12 = a[6], a13 = a[7],
+            a23 = a[11];
+
+        out[1] = a[4];
+        out[2] = a[8];
+        out[3] = a[12];
+        out[4] = a01;
+        out[6] = a[9];
+        out[7] = a[13];
+        out[8] = a02;
+        out[9] = a12;
+        out[11] = a[14];
+        out[12] = a03;
+        out[13] = a13;
+        out[14] = a23;
+    } else {
+        out[0] = a[0];
+        out[1] = a[4];
+        out[2] = a[8];
+        out[3] = a[12];
+        out[4] = a[1];
+        out[5] = a[5];
+        out[6] = a[9];
+        out[7] = a[13];
+        out[8] = a[2];
+        out[9] = a[6];
+        out[10] = a[10];
+        out[11] = a[14];
+        out[12] = a[3];
+        out[13] = a[7];
+        out[14] = a[11];
+        out[15] = a[15];
+    }
+    
+    return out;
+};
+},{}],105:[function(require,module,exports){
+'use strict'
+
+var barycentric            = require('barycentric')
+var closestPointToTriangle = require('polytope-closest-point/lib/closest_point_2d.js')
+
+module.exports = closestPointToPickLocation
+
+function xformMatrix(m, v) {
+  var out = [0,0,0,0]
+  for(var i=0; i<4; ++i) {
+    for(var j=0; j<4; ++j) {
+      out[j] += m[4*i + j] * v[i]
+    }
+  }
+  return out
+}
+
+function projectVertex(v, model, view, projection, resolution) {
+  var p = xformMatrix(projection,
+            xformMatrix(view,
+              xformMatrix(model, [v[0], v[1], v[2], 1])))
+  for(var i=0; i<3; ++i) {
+    p[i] /= p[3]
+  }
+  return [ 0.5 * resolution[0] * (1.0+p[0]), 0.5 * resolution[1] * (1.0-p[1]) ]
+}
+
+function barycentricCoord(simplex, point) {
+  if(simplex.length === 2) {
+    var d0 = 0.0
+    var d1 = 0.0
+    for(var i=0; i<2; ++i) {
+      d0 += Math.pow(point[i] - simplex[0][i], 2)
+      d1 += Math.pow(point[i] - simplex[1][i], 2)
+    }
+    d0 = Math.sqrt(d0)
+    d1 = Math.sqrt(d1)
+    if(d0+d1 < 1e-6) {
+      return [1,0]
+    }
+    return [d1/(d0+d1),d0/(d1+d0)]
+  } else if(simplex.length === 3) {
+    var closestPoint = [0,0]
+    closestPointToTriangle(simplex[0], simplex[1], simplex[2], point, closestPoint)
+    return barycentric(simplex, closestPoint)
+  }
+  return []
+}
+
+function interpolate(simplex, weights) {
+  var result = [0,0,0]
+  for(var i=0; i<simplex.length; ++i) {
+    var p = simplex[i]
+    var w = weights[i]
+    for(var j=0; j<3; ++j) {
+      result[j] += w * p[j]
+    }
+  }
+  return result
+}
+
+function closestPointToPickLocation(simplex, pixelCoord, model, view, projection, resolution) {
+  if(simplex.length === 1) {
+    return [0, simplex[0].slice()]
+  }
+  var simplex2D = new Array(simplex.length)
+  for(var i=0; i<simplex.length; ++i) {
+    simplex2D[i] = projectVertex(simplex[i], model, view, projection, resolution);
+  }
+
+  var closestIndex = 0
+  var closestDist  = Infinity
+  for(var i=0; i<simplex2D.length; ++i) {
+    var d2 = 0.0
+    for(var j=0; j<2; ++j) {
+      d2 += Math.pow(simplex2D[i][j] - pixelCoord[j], 2)
+    }
+    if(d2 < closestDist) {
+      closestDist  = d2
+      closestIndex = i
+    }
+  }
+
+  var weights = barycentricCoord(simplex2D, pixelCoord)
+  var s = 0.0
+  for(var i=0; i<3; ++i) {
+    if(weights[i] < -0.001 ||
+       weights[i] > 1.0001) {
+      return null
+    }
+    s += weights[i]
+  }
+  if(Math.abs(s - 1.0) > 0.001) {
+    return null
+  }
+  return [closestIndex, interpolate(simplex, weights), weights]
+}
+},{"barycentric":108,"polytope-closest-point/lib/closest_point_2d.js":110}],106:[function(require,module,exports){
+
+
+var triVertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n           , view\n           , projection;\nuniform vec3 eyePosition\n           , lightPosition;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  vec4 m_position  = model * vec4(position, 1.0);\n  vec4 t_position  = view * m_position;\n  gl_Position      = projection * t_position;\n  f_color          = color;\n  f_normal         = normal;\n  f_data           = position;\n  f_eyeDirection   = eyePosition   - position;\n  f_lightDirection = lightPosition - position;\n  f_uv             = uv;\n}"
+var triFragSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat cookTorranceSpecular_1_1(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution_2_0(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n            , fresnel\n            , kambient\n            , kdiffuse\n            , kspecular\n            , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if(any(lessThan(f_data, clipBounds[0])) || \n     any(greaterThan(f_data, clipBounds[1]))) {\n    discard;\n  }\n\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n  \n  if(!gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = cookTorranceSpecular_1_1(L, V, N, roughness, fresnel);\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}"
+var edgeVertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n  f_color = color;\n  f_data  = position;\n  f_uv    = uv;\n}"
+var edgeFragSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n  if(any(lessThan(f_data, clipBounds[0])) || \n     any(greaterThan(f_data, clipBounds[1]))) {\n    discard;\n  }\n\n  gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"
+var pointVertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if(any(lessThan(position, clipBounds[0])) || \n     any(greaterThan(position, clipBounds[1]))) {\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    gl_Position = projection * view * model * vec4(position, 1.0);\n  }\n  gl_PointSize = pointSize;\n  f_color = color;\n  f_uv = uv;\n}"
+var pointFragSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n  if(dot(pointR, pointR) > 0.25) {\n    discard;\n  }\n  gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"
+var pickVertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n  f_id        = id;\n  f_position  = position;\n}"
+var pickFragSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if(any(lessThan(f_position, clipBounds[0])) || \n     any(greaterThan(f_position, clipBounds[1]))) {\n    discard;\n  }\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}"
+var pickPointVertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3  position;\nattribute float pointSize;\nattribute vec4  id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if(any(lessThan(position, clipBounds[0])) || \n     any(greaterThan(position, clipBounds[1]))) {\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    gl_Position  = projection * view * model * vec4(position, 1.0);\n    gl_PointSize = pointSize;\n  }\n  f_id         = id;\n  f_position   = position;\n}"
+var contourVertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n}"
+var contourFragSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec3 contourColor;\n\nvoid main() {\n  gl_FragColor = vec4(contourColor,1);\n}\n"
+
+exports.meshShader = {
+  vertex:   triVertSrc,
+  fragment: triFragSrc,
+  attributes: [
+    {name: 'position', type: 'vec3'},
+    {name: 'normal', type: 'vec3'},
+    {name: 'color', type: 'vec4'},
+    {name: 'uv', type: 'vec2'}
+  ]
+}
+exports.wireShader = {
+  vertex:   edgeVertSrc,
+  fragment: edgeFragSrc,
+  attributes: [
+    {name: 'position', type: 'vec3'},
+    {name: 'color', type: 'vec4'},
+    {name: 'uv', type: 'vec2'}
+  ]
+}
+exports.pointShader = {
+  vertex:   pointVertSrc,
+  fragment: pointFragSrc,
+  attributes: [
+    {name: 'position', type: 'vec3'},
+    {name: 'color', type: 'vec4'},
+    {name: 'uv', type: 'vec2'},
+    {name: 'pointSize', type: 'float'}
+  ]
+}
+exports.pickShader = {
+  vertex:   pickVertSrc,
+  fragment: pickFragSrc,
+  attributes: [
+    {name: 'position', type: 'vec3'},
+    {name: 'id', type: 'vec4'}
+  ]
+}
+exports.pointPickShader = {
+  vertex:   pickPointVertSrc,
+  fragment: pickFragSrc,
+  attributes: [
+    {name: 'position', type: 'vec3'},
+    {name: 'pointSize', type: 'float'},
+    {name: 'id', type: 'vec4'}
+  ]
+}
+exports.contourShader = {
+  vertex:   contourVertSrc,
+  fragment: contourFragSrc,
+  attributes: [
+    {name: 'position', type: 'vec3'}
+  ]
+}
+
+},{}],107:[function(require,module,exports){
+'use strict'
+
+var createShader  = require('gl-shader')
+var createBuffer  = require('gl-buffer')
+var createVAO     = require('gl-vao')
+var createTexture = require('gl-texture2d')
+var normals       = require('normals')
+var multiply      = require('gl-mat4/multiply')
+var invert        = require('gl-mat4/invert')
+var ndarray       = require('ndarray')
+var colormap      = require('colormap')
+var getContour    = require('simplicial-complex-contour')
+var pool          = require('typedarray-pool')
+var shaders       = require('./lib/shaders')
+var closestPoint  = require('./lib/closest-point')
+
+var meshShader    = shaders.meshShader
+var wireShader    = shaders.wireShader
+var pointShader   = shaders.pointShader
+var pickShader    = shaders.pickShader
+var pointPickShader = shaders.pointPickShader
+var contourShader = shaders.contourShader
+
+var identityMatrix = [
+  1,0,0,0,
+  0,1,0,0,
+  0,0,1,0,
+  0,0,0,1]
+
+function SimplicialMesh(gl
+  , texture
+  , triShader
+  , lineShader
+  , pointShader
+  , pickShader
+  , pointPickShader
+  , contourShader
+  , trianglePositions
+  , triangleIds
+  , triangleColors
+  , triangleUVs
+  , triangleNormals
+  , triangleVAO
+  , edgePositions
+  , edgeIds
+  , edgeColors
+  , edgeUVs
+  , edgeVAO
+  , pointPositions
+  , pointIds
+  , pointColors
+  , pointUVs
+  , pointSizes
+  , pointVAO
+  , contourPositions
+  , contourVAO) {
+
+  this.gl                = gl
+  this.cells             = []
+  this.positions         = []
+  this.intensity         = []
+  this.texture           = texture
+  this.dirty             = true
+
+  this.triShader         = triShader
+  this.lineShader        = lineShader
+  this.pointShader       = pointShader
+  this.pickShader        = pickShader
+  this.pointPickShader   = pointPickShader
+  this.contourShader     = contourShader
+
+  this.trianglePositions = trianglePositions
+  this.triangleColors    = triangleColors
+  this.triangleNormals   = triangleNormals
+  this.triangleUVs       = triangleUVs
+  this.triangleIds       = triangleIds
+  this.triangleVAO       = triangleVAO
+  this.triangleCount     = 0
+
+  this.lineWidth         = 1
+  this.edgePositions     = edgePositions
+  this.edgeColors        = edgeColors
+  this.edgeUVs           = edgeUVs
+  this.edgeIds           = edgeIds
+  this.edgeVAO           = edgeVAO
+  this.edgeCount         = 0
+
+  this.pointPositions    = pointPositions
+  this.pointColors       = pointColors
+  this.pointUVs          = pointUVs
+  this.pointSizes        = pointSizes
+  this.pointIds          = pointIds
+  this.pointVAO          = pointVAO
+  this.pointCount        = 0
+
+  this.contourLineWidth  = 1
+  this.contourPositions  = contourPositions
+  this.contourVAO        = contourVAO
+  this.contourCount      = 0
+  this.contourColor      = [0,0,0]
+  this.contourEnable     = true
+
+  this.pickId            = 1
+  this.bounds            = [
+    [ Infinity, Infinity, Infinity],
+    [-Infinity,-Infinity,-Infinity] ]
+  this.clipBounds        = [
+    [-Infinity,-Infinity,-Infinity],
+    [ Infinity, Infinity, Infinity] ]
+
+  this.lightPosition = [1e5, 1e5, 0]
+  this.ambientLight  = 0.8
+  this.diffuseLight  = 0.8
+  this.specularLight = 2.0
+  this.roughness     = 0.5
+  this.fresnel       = 1.5
+
+  this.opacity       = 1.0
+
+  this._model       = identityMatrix
+  this._view        = identityMatrix
+  this._projection  = identityMatrix
+  this._resolution  = [1,1]
+}
+
+var proto = SimplicialMesh.prototype
+
+proto.isOpaque = function() {
+  return this.opacity >= 1
+}
+
+proto.isTransparent = function() {
+  return this.opacity < 1
+}
+
+proto.pickSlots = 1
+
+proto.setPickBase = function(id) {
+  this.pickId = id
+}
+
+function genColormap(param) {
+  var colors = colormap({
+      colormap: param
+    , nshades:  256
+    , format:  'rgba'
+  })
+
+  var result = new Uint8Array(256*4)
+  for(var i=0; i<256; ++i) {
+    var c = colors[i]
+    for(var j=0; j<3; ++j) {
+      result[4*i+j] = c[j]
+    }
+    result[4*i+3] = c[3]*255
+  }
+
+  return ndarray(result, [256,256,4], [4,0,1])
+}
+
+function unpackIntensity(cells, numVerts, cellIntensity) {
+  var result = new Array(numVerts)
+  for(var i=0; i<numVerts; ++i) {
+    result[i] = 0
+  }
+  var numCells = cells.length
+  for(var i=0; i<numCells; ++i) {
+    var c = cells[i]
+    for(var j=0; j<c.length; ++j) {
+      result[c[j]] = cellIntensity[i]
+    }
+  }
+  return result
+}
+
+function takeZComponent(array) {
+  var n = array.length
+  var result = new Array(n)
+  for(var i=0; i<n; ++i) {
+    result[i] = array[i][2]
+  }
+  return result
+}
+
+proto.highlight = function(selection) {
+  if(!selection || !this.contourEnable) {
+    this.contourCount = 0
+    return
+  }
+  var level = getContour(this.cells, this.intensity, selection.intensity)
+  var cells         = level.cells
+  var vertexIds     = level.vertexIds
+  var vertexWeights = level.vertexWeights
+  var numCells = cells.length
+  var result = pool.mallocFloat32(2 * 3 * numCells)
+  var ptr = 0
+  for(var i=0; i<numCells; ++i) {
+    var c = cells[i]
+    for(var j=0; j<2; ++j) {
+      var v = c[0]
+      if(c.length === 2) {
+        v = c[j]
+      }
+      var a = vertexIds[v][0]
+      var b = vertexIds[v][1]
+      var w = vertexWeights[v]
+      var wi = 1.0 - w
+      var pa = this.positions[a]
+      var pb = this.positions[b]
+      for(var k=0; k<3; ++k) {
+        result[ptr++] = w * pa[k] + wi * pb[k]
+      }
+    }
+  }
+  this.contourCount = (ptr / 3)|0
+  this.contourPositions.update(result.subarray(0, ptr))
+  pool.free(result)
+}
+
+proto.update = function(params) {
+  params = params || {}
+  var gl = this.gl
+
+  this.dirty = true
+
+  if('contourEnable' in params) {
+    this.contourEnable = params.contourEnable
+  }
+  if('contourColor' in params) {
+    this.contourColor = params.contourColor
+  }
+  if('lineWidth' in params) {
+    this.lineWidth = params.lineWidth
+  }
+  if('opacity' in params) {
+    this.opacity = params.opacity
+  }
+
+  if(params.texture) {
+    this.texture.dispose()
+    this.texture = createTexture(gl, params.texture)
+  } else if (params.colormap) {
+    this.texture.shape = [256,256]
+    this.texture.minFilter = gl.LINEAR_MIPMAP_LINEAR
+    this.texture.magFilter = gl.LINEAR
+    this.texture.setPixels(genColormap(params.colormap))
+    this.texture.generateMipmap()
+  }
+
+  var cells = params.cells
+  var positions = params.positions
+
+  if(!positions || !cells) {
+    return
+  }
+
+  var tPos = []
+  var tCol = []
+  var tNor = []
+  var tUVs = []
+  var tIds = []
+
+  var ePos = []
+  var eCol = []
+  var eUVs = []
+  var eIds = []
+
+  var pPos = []
+  var pCol = []
+  var pUVs = []
+  var pSiz = []
+  var pIds = []
+
+  //Save geometry data for picking calculations
+  this.cells     = cells
+  this.positions = positions
+
+  //Compute normals
+  var vertexNormals = params.vertexNormals
+  var cellNormals   = params.cellNormals
+  if(params.useFacetNormals && !cellNormals) {
+    cellNormals = normals.faceNormals(cells, positions)
+  }
+  if(!cellNormals && !vertexNormals) {
+    vertexNormals = normals.vertexNormals(cells, positions)
+  }
+
+  //Compute colors
+  var vertexColors    = params.vertexColors
+  var cellColors      = params.cellColors
+  var meshColor       = params.meshColor || [1,1,1,1]
+
+  //UVs
+  var vertexUVs       = params.vertexUVs
+  var vertexIntensity = params.vertexIntensity
+  var cellUVs         = params.cellUVs
+  var cellIntensity   = params.cellIntensity
+
+  var intensityLo     = Infinity
+  var intensityHi     = -Infinity
+  if(!vertexUVs && !cellUVs) {
+    if(vertexIntensity) {
+      for(var i=0; i<vertexIntensity.length; ++i) {
+        var f = vertexIntensity[i]
+        intensityLo = Math.min(intensityLo, f)
+        intensityHi = Math.max(intensityHi, f)
+      }
+    } else if(cellIntensity) {
+      for(var i=0; i<cellIntensity.length; ++i) {
+        var f = cellIntensity[i]
+        intensityLo = Math.min(intensityLo, f)
+        intensityHi = Math.max(intensityHi, f)
+      }
+    } else {
+      for(var i=0; i<positions.length; ++i) {
+        var f = positions[i][2]
+        intensityLo = Math.min(intensityLo, f)
+        intensityHi = Math.max(intensityHi, f)
+      }
+    }
+  }
+
+  if(vertexIntensity) {
+    this.intensity = vertexIntensity
+  } else if(cellIntensity) {
+    this.intensity = unpackIntensity(cells, positions.length, cellIntensity)
+  } else {
+    this.intensity = takeZComponent(positions)
+  }
+
+  //Point size
+  var pointSizes      = params.pointSizes
+  var meshPointSize   = params.pointSize || 1.0
+
+  //Update bounds
+  this.bounds       = [[Infinity,Infinity,Infinity], [-Infinity,-Infinity,-Infinity]]
+  for(var i=0; i<positions.length; ++i) {
+    var p = positions[i]
+    for(var j=0; j<3; ++j) {
+      if(isNaN(p[j]) || !isFinite(p[j])) {
+        continue
+      }
+      this.bounds[0][j] = Math.min(this.bounds[0][j], p[j])
+      this.bounds[1][j] = Math.max(this.bounds[1][j], p[j])
+    }
+  }
+
+  //Pack cells into buffers
+  var triangleCount = 0
+  var edgeCount = 0
+  var pointCount = 0
+
+fill_loop:
+  for(var i=0; i<cells.length; ++i) {
+    var cell = cells[i]
+    switch(cell.length) {
+      case 1:
+
+        var v = cell[0]
+        var p = positions[v]
+
+        //Check NaNs
+        for(var j=0; j<3; ++j) {
+          if(isNaN(p[j]) || !isFinite(p[j])) {
+            continue fill_loop
+          }
+        }
+
+        pPos.push(p[0], p[1], p[2])
+
+        var c
+        if(vertexColors) {
+          c = vertexColors[v]
+        } else if(cellColors) {
+          c = cellColors[i]
+        } else {
+          c = meshColor
+        }
+        if(c.length === 3) {
+          pCol.push(c[0], c[1], c[2], 1)
+        } else {
+          pCol.push(c[0], c[1], c[2], c[3])
+        }
+
+        var uv
+        if(vertexUVs) {
+          uv = vertexUVs[v]
+        } else if(vertexIntensity) {
+          uv = [
+            (vertexIntensity[v] - intensityLo) /
+            (intensityHi - intensityLo), 0]
+        } else if(cellUVs) {
+          uv = cellUVs[i]
+        } else if(cellIntensity) {
+          uv = [
+            (cellIntensity[i] - intensityLo) /
+            (intensityHi - intensityLo), 0]
+        } else {
+          uv = [
+            (p[2] - intensityLo) /
+            (intensityHi - intensityLo), 0]
+        }
+        pUVs.push(uv[0], uv[1])
+
+        if(pointSizes) {
+          pSiz.push(pointSizes[v])
+        } else {
+          pSiz.push(meshPointSize)
+        }
+
+        pIds.push(i)
+
+        pointCount += 1
+      break
+
+      case 2:
+
+        //Check NaNs
+        for(var j=0; j<2; ++j) {
+          var v = cell[j]
+          var p = positions[v]
+          for(var k=0; k<3; ++k) {
+            if(isNaN(p[k]) || !isFinite(p[k])) {
+              continue fill_loop
+            }
+          }
+        }
+
+        for(var j=0; j<2; ++j) {
+          var v = cell[j]
+          var p = positions[v]
+
+          ePos.push(p[0], p[1], p[2])
+
+          var c
+          if(vertexColors) {
+            c = vertexColors[v]
+          } else if(cellColors) {
+            c = cellColors[i]
+          } else {
+            c = meshColor
+          }
+          if(c.length === 3) {
+            eCol.push(c[0], c[1], c[2], 1)
+          } else {
+            eCol.push(c[0], c[1], c[2], c[3])
+          }
+
+          var uv
+          if(vertexUVs) {
+            uv = vertexUVs[v]
+          } else if(vertexIntensity) {
+            uv = [
+              (vertexIntensity[v] - intensityLo) /
+              (intensityHi - intensityLo), 0]
+          } else if(cellUVs) {
+            uv = cellUVs[i]
+          } else if(cellIntensity) {
+            uv = [
+              (cellIntensity[i] - intensityLo) /
+              (intensityHi - intensityLo), 0]
+          } else {
+            uv = [
+              (p[2] - intensityLo) /
+              (intensityHi - intensityLo), 0]
+          }
+          eUVs.push(uv[0], uv[1])
+
+          eIds.push(i)
+        }
+        edgeCount += 1
+      break
+
+      case 3:
+        //Check NaNs
+        for(var j=0; j<3; ++j) {
+          var v = cell[j]
+          var p = positions[v]
+          for(var k=0; k<3; ++k) {
+            if(isNaN(p[k]) || !isFinite(p[k])) {
+              continue fill_loop
+            }
+          }
+        }
+
+        for(var j=0; j<3; ++j) {
+          var v = cell[j]
+
+          var p = positions[v]
+          tPos.push(p[0], p[1], p[2])
+
+          var c
+          if(vertexColors) {
+            c = vertexColors[v]
+          } else if(cellColors) {
+            c = cellColors[i]
+          } else {
+            c = meshColor
+          }
+          if(c.length === 3) {
+            tCol.push(c[0], c[1], c[2], 1)
+          } else {
+            tCol.push(c[0], c[1], c[2], c[3])
+          }
+
+          var uv
+          if(vertexUVs) {
+            uv = vertexUVs[v]
+          } else if(vertexIntensity) {
+            uv = [
+              (vertexIntensity[v] - intensityLo) /
+              (intensityHi - intensityLo), 0]
+          } else if(cellUVs) {
+            uv = cellUVs[i]
+          } else if(cellIntensity) {
+            uv = [
+              (cellIntensity[i] - intensityLo) /
+              (intensityHi - intensityLo), 0]
+          } else {
+            uv = [
+              (p[2] - intensityLo) /
+              (intensityHi - intensityLo), 0]
+          }
+          tUVs.push(uv[0], uv[1])
+
+          var q
+          if(vertexNormals) {
+            q = vertexNormals[v]
+          } else {
+            q = cellNormals[i]
+          }
+          tNor.push(q[0], q[1], q[2])
+
+          tIds.push(i)
+        }
+        triangleCount += 1
+      break
+
+      default:
+      break
+    }
+  }
+
+  this.pointCount     = pointCount
+  this.edgeCount      = edgeCount
+  this.triangleCount  = triangleCount
+
+  this.pointPositions.update(pPos)
+  this.pointColors.update(pCol)
+  this.pointUVs.update(pUVs)
+  this.pointSizes.update(pSiz)
+  this.pointIds.update(new Uint32Array(pIds))
+
+  this.edgePositions.update(ePos)
+  this.edgeColors.update(eCol)
+  this.edgeUVs.update(eUVs)
+  this.edgeIds.update(new Uint32Array(eIds))
+
+  this.trianglePositions.update(tPos)
+  this.triangleColors.update(tCol)
+  this.triangleUVs.update(tUVs)
+  this.triangleNormals.update(tNor)
+  this.triangleIds.update(new Uint32Array(tIds))
+}
+
+proto.drawTransparent = proto.draw = function(params) {
+  params = params || {}
+  var gl          = this.gl
+  var model       = params.model      || identityMatrix
+  var view        = params.view       || identityMatrix
+  var projection  = params.projection || identityMatrix
+
+  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
+  for(var i=0; i<3; ++i) {
+    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
+    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
+  }
+
+  var uniforms = {
+    model:      model,
+    view:       view,
+    projection: projection,
+
+    clipBounds: clipBounds,
+
+    kambient:   this.ambientLight,
+    kdiffuse:   this.diffuseLight,
+    kspecular:  this.specularLight,
+    roughness:  this.roughness,
+    fresnel:    this.fresnel,
+
+    eyePosition:   [0,0,0],
+    lightPosition: [0,0,0],
+
+    opacity:  this.opacity,
+
+    contourColor: this.contourColor,
+
+    texture:    0
+  }
+
+  this.texture.bind(0)
+
+  var invCameraMatrix = new Array(16)
+  multiply(invCameraMatrix, uniforms.view, uniforms.model)
+  multiply(invCameraMatrix, uniforms.projection, invCameraMatrix)
+  invert(invCameraMatrix, invCameraMatrix)
+
+  for(var i=0; i<3; ++i) {
+    uniforms.eyePosition[i] = invCameraMatrix[12+i] / invCameraMatrix[15]
+  }
+
+  var w = invCameraMatrix[15]
+  for(var i=0; i<3; ++i) {
+    w += this.lightPosition[i] * invCameraMatrix[4*i+3]
+  }
+  for(var i=0; i<3; ++i) {
+    var s = invCameraMatrix[12+i]
+    for(var j=0; j<3; ++j) {
+      s += invCameraMatrix[4*j+i] * this.lightPosition[j]
+    }
+    uniforms.lightPosition[i] = s / w
+  }
+
+  if(this.triangleCount > 0) {
+    var shader = this.triShader
+    shader.bind()
+    shader.uniforms = uniforms
+
+    this.triangleVAO.bind()
+    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
+    this.triangleVAO.unbind()
+  }
+
+  if(this.edgeCount > 0 && this.lineWidth > 0) {
+    var shader = this.lineShader
+    shader.bind()
+    shader.uniforms = uniforms
+
+    this.edgeVAO.bind()
+    gl.lineWidth(this.lineWidth)
+    gl.drawArrays(gl.LINES, 0, this.edgeCount*2)
+    this.edgeVAO.unbind()
+  }
+
+  if(this.pointCount > 0) {
+    var shader = this.pointShader
+    shader.bind()
+    shader.uniforms = uniforms
+
+    this.pointVAO.bind()
+    gl.drawArrays(gl.POINTS, 0, this.pointCount)
+    this.pointVAO.unbind()
+  }
+
+  if(this.contourEnable && this.contourCount > 0 && this.contourLineWidth > 0) {
+    var shader = this.contourShader
+    shader.bind()
+    shader.uniforms = uniforms
+
+    this.contourVAO.bind()
+    gl.drawArrays(gl.LINES, 0, this.contourCount)
+    this.contourVAO.unbind()
+  }
+}
+
+proto.drawPick = function(params) {
+  params = params || {}
+
+  var gl         = this.gl
+
+  var model      = params.model      || identityMatrix
+  var view       = params.view       || identityMatrix
+  var projection = params.projection || identityMatrix
+
+  var clipBounds = [[-1e6,-1e6,-1e6],[1e6,1e6,1e6]]
+  for(var i=0; i<3; ++i) {
+    clipBounds[0][i] = Math.max(clipBounds[0][i], this.clipBounds[0][i])
+    clipBounds[1][i] = Math.min(clipBounds[1][i], this.clipBounds[1][i])
+  }
+
+  //Save camera parameters
+  this._model      = [].slice.call(model)
+  this._view       = [].slice.call(view)
+  this._projection = [].slice.call(projection)
+  this._resolution = [gl.drawingBufferWidth, gl.drawingBufferHeight]
+
+  var uniforms = {
+    model:      model,
+    view:       view,
+    projection: projection,
+    clipBounds: clipBounds,
+    pickId:     this.pickId / 255.0,
+  }
+
+  var shader = this.pickShader
+  shader.bind()
+  shader.uniforms = uniforms
+
+  if(this.triangleCount > 0) {
+    this.triangleVAO.bind()
+    gl.drawArrays(gl.TRIANGLES, 0, this.triangleCount*3)
+    this.triangleVAO.unbind()
+  }
+
+  if(this.edgeCount > 0) {
+    this.edgeVAO.bind()
+    gl.lineWidth(this.lineWidth)
+    gl.drawArrays(gl.LINES, 0, this.edgeCount*2)
+    this.edgeVAO.unbind()
+  }
+
+  if(this.pointCount > 0) {
+    var shader = this.pointPickShader
+    shader.bind()
+    shader.uniforms = uniforms
+
+    this.pointVAO.bind()
+    gl.drawArrays(gl.POINTS, 0, this.pointCount)
+    this.pointVAO.unbind()
+  }
+}
+
+
+proto.pick = function(pickData) {
+  if(!pickData) {
+    return null
+  }
+  if(pickData.id !== this.pickId) {
+    return null
+  }
+
+  var cellId    = pickData.value[0] + 256*pickData.value[1] + 65536*pickData.value[2]
+  var cell      = this.cells[cellId]
+  var positions = this.positions
+
+  var simplex   = new Array(cell.length)
+  for(var i=0; i<cell.length; ++i) {
+    simplex[i] = positions[cell[i]]
+  }
+
+  var data = closestPoint(
+    simplex,
+    [pickData.coord[0], this._resolution[1]-pickData.coord[1]],
+    this._model,
+    this._view,
+    this._projection,
+    this._resolution)
+
+  if(!data) {
+    return null
+  }
+
+  var weights = data[2]
+  var interpIntensity = 0.0
+  for(var i=0; i<cell.length; ++i) {
+    interpIntensity += weights[i] * this.intensity[cell[i]]
+  }
+
+  return {
+    position: data[1],
+    index:    cell[data[0]],
+    cell:     cell,
+    cellId:   cellId,
+    intensity:  interpIntensity,
+    dataCoordinate: this.positions[cell[data[0]]]
+  }
+}
+
+
+proto.dispose = function() {
+  this.texture.dispose()
+
+  this.triShader.dispose()
+  this.lineShader.dispose()
+  this.pointShader.dispose()
+  this.pickShader.dispose()
+  this.pointPickShader.dispose()
+
+  this.triangleVAO.dispose()
+  this.trianglePositions.dispose()
+  this.triangleColors.dispose()
+  this.triangleUVs.dispose()
+  this.triangleNormals.dispose()
+  this.triangleIds.dispose()
+
+  this.edgeVAO.dispose()
+  this.edgePositions.dispose()
+  this.edgeColors.dispose()
+  this.edgeUVs.dispose()
+  this.edgeIds.dispose()
+
+  this.pointVAO.dispose()
+  this.pointPositions.dispose()
+  this.pointColors.dispose()
+  this.pointUVs.dispose()
+  this.pointSizes.dispose()
+  this.pointIds.dispose()
+
+  this.contourVAO.dispose()
+  this.contourPositions.dispose()
+  this.contourShader.dispose()
+}
+
+function createMeshShader(gl) {
+  var shader = createShader(gl, meshShader)
+  shader.attributes.position.location = 0
+  shader.attributes.color.location    = 2
+  shader.attributes.uv.location       = 3
+  shader.attributes.normal.location   = 4
+  return shader
+}
+
+function createWireShader(gl) {
+  var shader = createShader(gl, wireShader)
+  shader.attributes.position.location = 0
+  shader.attributes.color.location    = 2
+  shader.attributes.uv.location       = 3
+  return shader
+}
+
+function createPointShader(gl) {
+  var shader = createShader(gl, pointShader)
+  shader.attributes.position.location  = 0
+  shader.attributes.color.location     = 2
+  shader.attributes.uv.location        = 3
+  shader.attributes.pointSize.location = 4
+  return shader
+}
+
+function createPickShader(gl) {
+  var shader = createShader(gl, pickShader)
+  shader.attributes.position.location = 0
+  shader.attributes.id.location       = 1
+  return shader
+}
+
+function createPointPickShader(gl) {
+  var shader = createShader(gl, pointPickShader)
+  shader.attributes.position.location  = 0
+  shader.attributes.id.location        = 1
+  shader.attributes.pointSize.location = 4
+  return shader
+}
+
+function createContourShader(gl) {
+  var shader = createShader(gl, contourShader)
+  shader.attributes.position.location = 0
+  return shader
+}
+
+function createSimplicialMesh(params) {
+  var gl = params.gl
+
+  var triShader       = createMeshShader(gl)
+  var lineShader      = createWireShader(gl)
+  var pointShader     = createPointShader(gl)
+  var pickShader      = createPickShader(gl)
+  var pointPickShader = createPointPickShader(gl)
+  var contourShader   = createContourShader(gl)
+
+  var meshTexture       = createTexture(gl,
+    ndarray(new Uint8Array([255,255,255,255]), [1,1,4]))
+  meshTexture.generateMipmap()
+  meshTexture.minFilter = gl.LINEAR_MIPMAP_LINEAR
+  meshTexture.magFilter = gl.LINEAR
+
+  var trianglePositions = createBuffer(gl)
+  var triangleColors    = createBuffer(gl)
+  var triangleUVs       = createBuffer(gl)
+  var triangleNormals   = createBuffer(gl)
+  var triangleIds       = createBuffer(gl)
+  var triangleVAO       = createVAO(gl, [
+    { buffer: trianglePositions,
+      type: gl.FLOAT,
+      size: 3
+    },
+    { buffer: triangleIds,
+      type: gl.UNSIGNED_BYTE,
+      size: 4,
+      normalized: true
+    },
+    { buffer: triangleColors,
+      type: gl.FLOAT,
+      size: 4
+    },
+    { buffer: triangleUVs,
+      type: gl.FLOAT,
+      size: 2
+    },
+    { buffer: triangleNormals,
+      type: gl.FLOAT,
+      size: 3
+    }
+  ])
+
+  var edgePositions = createBuffer(gl)
+  var edgeColors    = createBuffer(gl)
+  var edgeUVs       = createBuffer(gl)
+  var edgeIds       = createBuffer(gl)
+  var edgeVAO       = createVAO(gl, [
+    { buffer: edgePositions,
+      type: gl.FLOAT,
+      size: 3
+    },
+    { buffer: edgeIds,
+      type: gl.UNSIGNED_BYTE,
+      size: 4,
+      normalized: true
+    },
+    { buffer: edgeColors,
+      type: gl.FLOAT,
+      size: 4
+    },
+    { buffer: edgeUVs,
+      type: gl.FLOAT,
+      size: 2
+    }
+  ])
+
+  var pointPositions  = createBuffer(gl)
+  var pointColors     = createBuffer(gl)
+  var pointUVs        = createBuffer(gl)
+  var pointSizes      = createBuffer(gl)
+  var pointIds        = createBuffer(gl)
+  var pointVAO        = createVAO(gl, [
+    { buffer: pointPositions,
+      type: gl.FLOAT,
+      size: 3
+    },
+    { buffer: pointIds,
+      type: gl.UNSIGNED_BYTE,
+      size: 4,
+      normalized: true
+    },
+    { buffer: pointColors,
+      type: gl.FLOAT,
+      size: 4
+    },
+    { buffer: pointUVs,
+      type: gl.FLOAT,
+      size: 2
+    },
+    { buffer: pointSizes,
+      type: gl.FLOAT,
+      size: 1
+    }
+  ])
+
+  var contourPositions = createBuffer(gl)
+  var contourVAO       = createVAO(gl, [
+    { buffer: contourPositions,
+      type:   gl.FLOAT,
+      size:   3
+    }])
+
+  var mesh = new SimplicialMesh(gl
+    , meshTexture
+    , triShader
+    , lineShader
+    , pointShader
+    , pickShader
+    , pointPickShader
+    , contourShader
+    , trianglePositions
+    , triangleIds
+    , triangleColors
+    , triangleUVs
+    , triangleNormals
+    , triangleVAO
+    , edgePositions
+    , edgeIds
+    , edgeColors
+    , edgeUVs
+    , edgeVAO
+    , pointPositions
+    , pointIds
+    , pointColors
+    , pointUVs
+    , pointSizes
+    , pointVAO
+    , contourPositions
+    , contourVAO)
+
+  mesh.update(params)
+
+  return mesh
+}
+
+module.exports = createSimplicialMesh
+
+},{"./lib/closest-point":105,"./lib/shaders":106,"colormap":57,"gl-buffer":75,"gl-mat4/invert":94,"gl-mat4/multiply":96,"gl-shader":154,"gl-texture2d":185,"gl-vao":189,"ndarray":208,"normals":109,"simplicial-complex-contour":111,"typedarray-pool":233}],108:[function(require,module,exports){
+'use strict'
+
+module.exports = barycentric
+
+var solve = require('robust-linear-solve')
+
+function reduce(x) {
+  var r = 0
+  for(var i=0; i<x.length; ++i) {
+    r += x[i]
+  }
+  return r
+}
+
+function barycentric(simplex, point) {
+  var d = point.length
+  var A = new Array(d+1)
+  for(var i=0; i<d; ++i) {
+    var row = new Array(d+1)
+    for(var j=0; j<=d; ++j) {
+      row[j] = simplex[j][i]
+    }
+    A[i] = row
+  }
+  A[d] = new Array(d+1)
+  for(var i=0; i<=d; ++i) {
+    A[d][i] = 1
+  }
+
+  var b = new Array(d+1)
+  for(var i=0; i<d; ++i) {
+    b[i] = point[i]
+  }
+  b[d] = 1.0
+
+  var x = solve(A, b)
+  var w = reduce(x[d+1])
+  
+  if(w === 0) {
+    w = 1.0
+  }
+  var y = new Array(d+1)
+  for(var i=0; i<=d; ++i) {
+    y[i] = reduce(x[i]) / w
+  }
+  return y
+}
+},{"robust-linear-solve":211}],109:[function(require,module,exports){
+var EPSILON = 1e-6;
+
+//Estimate the vertex normals of a mesh
+exports.vertexNormals = function(faces, positions) {
+  
+  var N         = positions.length;
+  var normals   = new Array(N);
+  
+  //Initialize normal array
+  for(var i=0; i<N; ++i) {
+    normals[i] = [0.0, 0.0, 0.0];
+  }
+  
+  //Walk over all the faces and add per-vertex contribution to normal weights
+  for(var i=0; i<faces.length; ++i) {
+    var f = faces[i];
+    var p = 0;
+    var c = f[f.length-1];
+    var n = f[0];
+    for(var j=0; j<f.length; ++j) {
+    
+      //Shift indices back
+      p = c;
+      c = n;
+      n = f[(j+1) % f.length];
+    
+      var v0 = positions[p];
+      var v1 = positions[c];
+      var v2 = positions[n];
+      
+      //Compute infineteismal arcs
+      var d01 = new Array(3);
+      var m01 = 0.0;
+      var d21 = new Array(3);
+      var m21 = 0.0;
+      for(var k=0; k<3; ++k) {
+        d01[k] = v0[k]  - v1[k];
+        m01   += d01[k] * d01[k];
+        d21[k] = v2[k]  - v1[k];
+        m21   += d21[k] * d21[k];
+      }
+
+      //Accumulate values in normal
+      if(m01 * m21 > EPSILON) {
+        var norm = normals[c];
+        var w = 1.0 / Math.sqrt(m01 * m21);
+        for(var k=0; k<3; ++k) {
+          var u = (k+1)%3;
+          var v = (k+2)%3;
+          norm[k] += w * (d21[u] * d01[v] - d21[v] * d01[u]);
+        }
+      }
+    }
+  }
+  
+  //Scale all normals to unit length
+  for(var i=0; i<N; ++i) {
+    var norm = normals[i];
+    var m = 0.0;
+    for(var k=0; k<3; ++k) {
+      m += norm[k] * norm[k];
+    }
+    if(m > EPSILON) {
+      var w = 1.0 / Math.sqrt(m);
+      for(var k=0; k<3; ++k) {
+        norm[k] *= w;
+      }
+    } else {
+      for(var k=0; k<3; ++k) {
+        norm[k] = 0.0;
+      }
+    }
+  }
+
+  //Return the resulting set of patches
+  return normals;
+}
+
+//Compute face normals of a mesh
+exports.faceNormals = function(faces, positions) {
+  var N         = faces.length;
+  var normals   = new Array(N);
+  
+  for(var i=0; i<N; ++i) {
+    var f = faces[i];
+    var pos = new Array(3);
+    for(var j=0; j<3; ++j) {
+      pos[j] = positions[f[j]];
+    }
+    
+    var d01 = new Array(3);
+    var d21 = new Array(3);
+    for(var j=0; j<3; ++j) {
+      d01[j] = pos[1][j] - pos[0][j];
+      d21[j] = pos[2][j] - pos[0][j];
+    }
+    
+    var n = new Array(3);
+    var l = 0.0;
+    for(var j=0; j<3; ++j) {
+      var u = (j+1)%3;
+      var v = (j+2)%3;
+      n[j] = d01[u] * d21[v] - d01[v] * d21[u];
+      l += n[j] * n[j];
+    }
+    if(l > EPSILON) {
+      l = 1.0 / Math.sqrt(l);
+    } else {
+      l = 0.0;
+    }
+    for(var j=0; j<3; ++j) {
+      n[j] *= l;
+    }
+    normals[i] = n;
+  }
+  return normals;
+}
+
+
+
+},{}],110:[function(require,module,exports){
+//Optimized version for triangle closest point
+// Based on Eberly's WildMagick codes
+// http://www.geometrictools.com/LibMathematics/Distance/Distance.html
+"use strict";
+
+var diff = new Float64Array(4);
+var edge0 = new Float64Array(4);
+var edge1 = new Float64Array(4);
+
+function closestPoint2d(V0, V1, V2, point, result) {
+  //Reallocate buffers if necessary
+  if(diff.length < point.length) {
+    diff = new Float64Array(point.length);
+    edge0 = new Float64Array(point.length);
+    edge1 = new Float64Array(point.length);
+  }
+  //Compute edges
+  for(var i=0; i<point.length; ++i) {
+    diff[i]  = V0[i] - point[i];
+    edge0[i] = V1[i] - V0[i];
+    edge1[i] = V2[i] - V0[i];
+  }
+  //Compute coefficients for quadratic func
+  var a00 = 0.0
+    , a01 = 0.0
+    , a11 = 0.0
+    , b0  = 0.0
+    , b1  = 0.0
+    , c   = 0.0;
+  for(var i=0; i<point.length; ++i) {
+    var e0 = edge0[i]
+      , e1 = edge1[i]
+      , d  = diff[i];
+    a00 += e0 * e0;
+    a01 += e0 * e1;
+    a11 += e1 * e1;
+    b0  += d * e0;
+    b1  += d * e1;
+    c   += d * d;
+  }
+  //Compute determinant/coeffs
+  var det = Math.abs(a00*a11 - a01*a01);
+  var s   = a01*b1 - a11*b0;
+  var t   = a01*b0 - a00*b1;
+  var sqrDistance;
+  //Hardcoded Voronoi diagram classification
+  if (s + t <= det) {
+    if (s < 0) {
+      if (t < 0) { // region 4
+        if (b0 < 0) {
+          t = 0;
+          if (-b0 >= a00) {
+            s = 1.0;
+            sqrDistance = a00 + 2.0*b0 + c;
+          } else {
+            s = -b0/a00;
+            sqrDistance = b0*s + c;
+          }
+        } else {
+          s = 0;
+          if (b1 >= 0) {
+            t = 0;
+            sqrDistance = c;
+          } else if (-b1 >= a11) {
+            t = 1;
+            sqrDistance = a11 + 2.0*b1 + c;
+          } else {
+            t = -b1/a11;
+            sqrDistance = b1*t + c;
+          }
+        }
+      } else {  // region 3
+        s = 0;
+        if (b1 >= 0) {
+          t = 0;
+          sqrDistance = c;
+        } else if (-b1 >= a11) {
+          t = 1;
+          sqrDistance = a11 + 2.0*b1 + c;
+        } else {
+          t = -b1/a11;
+          sqrDistance = b1*t + c;
+        }
+      }
+    } else if (t < 0) { // region 5
+      t = 0;
+      if (b0 >= 0) {
+        s = 0;
+        sqrDistance = c;
+      } else if (-b0 >= a00) {
+        s = 1;
+        sqrDistance = a00 + 2.0*b0 + c;
+      } else {
+        s = -b0/a00;
+        sqrDistance = b0*s + c;
+      }
+    } else {  // region 0
+      // minimum at interior point
+      var invDet = 1.0 / det;
+      s *= invDet;
+      t *= invDet;
+      sqrDistance = s*(a00*s + a01*t + 2.0*b0) + t*(a01*s + a11*t + 2.0*b1) + c;
+    }
+  } else {
+    var tmp0, tmp1, numer, denom;
+    
+    if (s < 0) {  // region 2
+      tmp0 = a01 + b0;
+      tmp1 = a11 + b1;
+      if (tmp1 > tmp0) {
+        numer = tmp1 - tmp0;
+        denom = a00 - 2.0*a01 + a11;
+        if (numer >= denom) {
+          s = 1;
+          t = 0;
+          sqrDistance = a00 + 2.0*b0 + c;
+        } else {
+          s = numer/denom;
+          t = 1 - s;
+          sqrDistance = s*(a00*s + a01*t + 2.0*b0) +
+          t*(a01*s + a11*t + 2.0*b1) + c;
+        }
+      } else {
+        s = 0;
+        if (tmp1 <= 0) {
+          t = 1;
+          sqrDistance = a11 + 2.0*b1 + c;
+        } else if (b1 >= 0) {
+          t = 0;
+          sqrDistance = c;
+        } else {
+          t = -b1/a11;
+          sqrDistance = b1*t + c;
+        }
+      }
+    } else if (t < 0) {  // region 6
+      tmp0 = a01 + b1;
+      tmp1 = a00 + b0;
+      if (tmp1 > tmp0) {
+        numer = tmp1 - tmp0;
+        denom = a00 - 2.0*a01 + a11;
+        if (numer >= denom) {
+          t = 1;
+          s = 0;
+          sqrDistance = a11 + 2.0*b1 + c;
+        } else {
+          t = numer/denom;
+          s = 1 - t;
+          sqrDistance = s*(a00*s + a01*t + 2.0*b0) +
+          t*(a01*s + a11*t + 2.0*b1) + c;
+        }
+      } else {
+        t = 0;
+        if (tmp1 <= 0) {
+          s = 1;
+          sqrDistance = a00 + 2.0*b0 + c;
+        } else if (b0 >= 0) {
+          s = 0;
+          sqrDistance = c;
+        } else {
+          s = -b0/a00;
+          sqrDistance = b0*s + c;
+        }
+      }
+    } else {  // region 1
+      numer = a11 + b1 - a01 - b0;
+      if (numer <= 0) {
+        s = 0;
+        t = 1;
+        sqrDistance = a11 + 2.0*b1 + c;
+      } else {
+        denom = a00 - 2.0*a01 + a11;
+        if (numer >= denom) {
+          s = 1;
+          t = 0;
+          sqrDistance = a00 + 2.0*b0 + c;
+        } else {
+          s = numer/denom;
+          t = 1 - s;
+          sqrDistance = s*(a00*s + a01*t + 2.0*b0) +
+          t*(a01*s + a11*t + 2.0*b1) + c;
+        }
+      }
+    }
+  }
+  var u = 1.0 - s - t;
+  for(var i=0; i<point.length; ++i) {
+    result[i] = u * V0[i] + s * V1[i] + t * V2[i];
+  }
+  if(sqrDistance < 0) {
+    return 0;
+  }
+  return sqrDistance;
+}
+
+module.exports = closestPoint2d;
+
+},{}],111:[function(require,module,exports){
+'use strict'
+
+module.exports = extractContour
+
+var ndarray = require('ndarray')
+var pool    = require('typedarray-pool')
+var ndsort  = require('ndarray-sort')
+
+var contourAlgorithm = require('./lib/codegen')
+
+function getDimension(cells) {
+  var numCells = cells.length
+  var d = 0
+  for(var i=0; i<numCells; ++i) {
+    d = Math.max(d, cells[i].length)|0
+  }
+  return d-1
+}
+
+function getSigns(values, level) {
+  var numVerts    = values.length
+  var vertexSigns = pool.mallocUint8(numVerts)
+  for(var i=0; i<numVerts; ++i) {
+    vertexSigns[i] = (values[i] < level)|0
+  }
+  return vertexSigns
+}
+
+function getEdges(cells, d) {
+  var numCells = cells.length
+  var maxEdges = ((d * (d+1)/2) * numCells)|0
+  var edges    = pool.mallocUint32(maxEdges*2)
+  var ePtr     = 0
+  for(var i=0; i<numCells; ++i) {
+    var c = cells[i]
+    var d = c.length
+    for(var j=0; j<d; ++j) {
+      for(var k=0; k<j; ++k) {
+        var a = c[k]
+        var b = c[j]
+        edges[ePtr++] = Math.min(a,b)|0
+        edges[ePtr++] = Math.max(a,b)|0
+      }
+    }
+  }
+  var nedges = (ePtr/2)|0
+  ndsort(ndarray(edges, [nedges,2])) 
+  var ptr = 2
+  for(var i=2; i<ePtr; i+=2) {
+    if(edges[i-2] === edges[i] &&
+       edges[i-1] === edges[i+1]) {
+      continue
+    }
+    edges[ptr++] = edges[i]
+    edges[ptr++] = edges[i+1]
+  }
+
+  return ndarray(edges, [(ptr/2)|0, 2])
+}
+
+function getCrossingWeights(edges, values, signs, level) {
+  var edata     = edges.data
+  var numEdges  = edges.shape[0]
+  var weights   = pool.mallocDouble(numEdges)
+  var ptr       = 0
+  for(var i=0; i<numEdges; ++i) {
+    var a  = edata[2*i]
+    var b  = edata[2*i+1]
+    if(signs[a] === signs[b]) {
+      continue
+    }
+    var va = values[a]
+    var vb = values[b]
+    edata[2*ptr]     = a
+    edata[2*ptr+1]   = b
+    weights[ptr++]   = (vb - level) / (vb - va)
+  }
+  edges.shape[0] = ptr
+  return ndarray(weights, [ptr])
+}
+
+function getCascade(edges, numVerts) {
+  var result   = pool.mallocInt32(numVerts*2)
+  var numEdges = edges.shape[0]
+  var edata    = edges.data
+  result[0]    = 0
+  var lastV    = 0
+  for(var i=0; i<numEdges; ++i) {
+    var a = edata[2*i]
+    if(a !== lastV) {
+      result[2*lastV+1] = i
+      while(++lastV < a) {
+        result[2*lastV] = i
+        result[2*lastV+1] = i
+      }
+      result[2*lastV] = i
+    }
+  }
+  result[2*lastV+1] = numEdges
+  while(++lastV < numVerts) {
+    result[2*lastV] = result[2*lastV+1] = numEdges
+  }
+  return result
+}
+
+function unpackEdges(edges) {
+  var ne = edges.shape[0]|0
+  var edata = edges.data
+  var result = new Array(ne)
+  for(var i=0; i<ne; ++i) {
+    result[i] = [edata[2*i], edata[2*i+1]]
+  }
+  return result
+}
+
+function extractContour(cells, values, level, d) {
+  level = level||0.0
+
+  //If user didn't specify `d`, use brute force scan
+  if(typeof d === 'undefined') {
+    d = getDimension(cells)
+  }
+
+  //Count number of cells
+  var numCells = cells.length
+  if(numCells === 0 || d < 1) {
+    return {
+      cells:         [],
+      vertexIds:     [],
+      vertexWeights: []
+    }
+  }
+
+  //Read in vertex signs
+  var vertexSigns = getSigns(values, +level)
+
+  //First get 1-skeleton, find all crossings
+  var edges   = getEdges(cells, d)
+  var weights = getCrossingWeights(edges, values, vertexSigns, +level)
+
+  //Build vertex cascade to speed up binary search
+  var vcascade = getCascade(edges, values.length|0)
+
+  //Then construct cells
+  var faces = contourAlgorithm(d)(cells, edges.data, vcascade, vertexSigns)
+
+  //Unpack data into pretty format
+  var uedges   = unpackEdges(edges)
+  var uweights = [].slice.call(weights.data, 0, weights.shape[0])
+
+  //Release data
+  pool.free(vertexSigns)
+  pool.free(edges.data)
+  pool.free(weights.data)
+  pool.free(vcascade)
+  
+  return {
+    cells:         faces,
+    vertexIds:     uedges,
+    vertexWeights: uweights
+  }
+}
+},{"./lib/codegen":112,"ndarray":208,"ndarray-sort":115,"typedarray-pool":233}],112:[function(require,module,exports){
+'use strict'
+
+module.exports = getPolygonizer
+
+var pool = require('typedarray-pool')
+var createMSTable = require('marching-simplex-table')
+
+var CACHE = {}
+
+function createCellPolygonizer(d) {
+  var maxCellSize = 0
+  var tables = new Array(d+1)
+  tables[0] = [ [] ]
+  for(var i=1; i<=d; ++i) {
+    var tab = tables[i] = createMSTable(i)
+    for(var j=0; j<tab.length; ++j) {
+      maxCellSize = Math.max(maxCellSize, tab[i].length)
+    }
+  }
+
+  var code  = [
+  'function B(C,E,i,j){',
+    'var a=Math.min(i,j)|0,b=Math.max(i,j)|0,l=C[2*a],h=C[2*a+1];',
+    'while(l<h){',
+      'var m=(l+h)>>1,v=E[2*m+1];',
+      'if(v===b){return m}',
+      'if(b<v){h=m}else{l=m+1}',
+    '}',
+    'return l;',
+  '};',
+  'function getContour', d, 'd(F,E,C,S){',
+    'var n=F.length,R=[];',
+    'for(var i=0;i<n;++i){var c=F[i],l=c.length;'
+  ]
+
+  function generateCase(facets) {
+    if(facets.length <= 0) {
+      return
+    }
+    code.push('R.push(')
+    for(var i=0; i<facets.length; ++i) {
+      var facet = facets[i]
+      if(i > 0) {
+        code.push(',')
+      }
+      code.push('[')
+      for(var j=0; j<facet.length; ++j) {
+        var f = facet[j]
+        if(j > 0) {
+          code.push(',')
+        }
+        code.push('B(C,E,c[', f[0], '],c[', f[1], '])')
+      }
+      code.push(']')
+    }
+    code.push(');')
+  }
+
+  for(var i=d+1; i>1; --i) {
+    if(i < d+1) {
+      code.push('else ')
+    }
+    code.push('if(l===', i, '){')
+
+    //Generate mask
+    var maskStr = []
+    for(var j=0; j<i; ++j) {
+      maskStr.push('(S[c['+j+']]<<'+j+')')
+    }
+
+    //Perform table look up
+    code.push('var M=', maskStr.join('+'), 
+      ';if(M===0||M===', (1<<i)-1, 
+        '){continue}switch(M){')
+
+    var tab = tables[i-1]
+    for(var j=0; j<tab.length; ++j) {
+      code.push('case ', j, ':')
+      generateCase(tab[j])
+      code.push('break;')
+    }
+    code.push('}}')
+  }
+  code.push('}return R;};return getContour', d, 'd')
+
+  var proc = new Function('pool', code.join(''))
+  return proc(pool)
+}
+
+function getPolygonizer(d) {
+  var alg = CACHE[d]
+  if(!alg) {
+    alg = CACHE[d] = createCellPolygonizer(d) 
+  }
+  return alg
+}
+},{"marching-simplex-table":113,"typedarray-pool":233}],113:[function(require,module,exports){
+'use strict'
+
+module.exports = createTable
+
+var chull = require('convex-hull')
+
+function constructVertex(d, a, b) {
+  var x = new Array(d)
+  for(var i=0; i<d; ++i) {
+    x[i] = 0.0
+    if(i === a) {
+      x[i] += 0.5
+    }
+    if(i === b) {
+      x[i] += 0.5
+    }
+  }
+  return x
+}
+
+function constructCell(dimension, mask) {
+  if(mask === 0 || mask === (1<<(dimension+1))-1) {
+    return []
+  }
+  var points = []
+  var index  = []
+  for(var i=0; i<=dimension; ++i) {
+    if(mask & (1<<i)) {
+      points.push(constructVertex(dimension, i-1, i-1))
+      index.push(null)
+      for(var j=0; j<=dimension; ++j) {
+        if(~mask & (1<<j)) {
+          points.push(constructVertex(dimension, i-1, j-1))
+          index.push([i,j])
+        }
+      }
+    }
+  }
+  
+  //Preprocess points so first d+1 points are linearly independent
+  var hull = chull(points)
+  var faces = []
+i_loop:
+  for(var i=0; i<hull.length; ++i) {
+    var face = hull[i]
+    var nface = []
+    for(var j=0; j<face.length; ++j) {
+      if(!index[face[j]]) {
+        continue i_loop
+      }
+      nface.push(index[face[j]].slice())
+    }
+    faces.push(nface)
+  }
+  return faces
+}
+
+function createTable(dimension) {
+  var numCells = 1<<(dimension+1)
+  var result = new Array(numCells)
+  for(var i=0; i<numCells; ++i) {
+    result[i] = constructCell(dimension, i)
+  }
+  return result
+}
+},{"convex-hull":60}],114:[function(require,module,exports){
+"use strict"
+
+var pool = require("typedarray-pool")
+
+var INSERTION_SORT_THRESHOLD = 32
+
+function getMallocFree(dtype) {
+  switch(dtype) {
+    case "uint8":
+      return [pool.mallocUint8, pool.freeUint8]
+    case "uint16":
+      return [pool.mallocUint16, pool.freeUint16]
+    case "uint32":
+      return [pool.mallocUint32, pool.freeUint32]
+    case "int8":
+      return [pool.mallocInt8, pool.freeInt8]
+    case "int16":
+      return [pool.mallocInt16, pool.freeInt16]
+    case "int32":
+      return [pool.mallocInt32, pool.freeInt32]
+    case "float32":
+      return [pool.mallocFloat, pool.freeFloat]
+    case "float64":
+      return [pool.mallocDouble, pool.freeDouble]
+    default:
+      return null
+  }
+}
+
+function shapeArgs(dimension) {
+  var args = []
+  for(var i=0; i<dimension; ++i) {
+    args.push("s"+i)
+  }
+  for(var i=0; i<dimension; ++i) {
+    args.push("n"+i)
+  }
+  for(var i=1; i<dimension; ++i) {
+    args.push("d"+i)
+  }
+  for(var i=1; i<dimension; ++i) {
+    args.push("e"+i)
+  }
+  for(var i=1; i<dimension; ++i) {
+    args.push("f"+i)
+  }
+  return args
+}
+
+function createInsertionSort(order, dtype) {
+
+  var code = ["'use strict'"]
+  var funcName = ["ndarrayInsertionSort", order.join("d"), dtype].join("")
+  var funcArgs = ["left", "right", "data", "offset" ].concat(shapeArgs(order.length))
+  var allocator = getMallocFree(dtype)
+  
+  var vars = [ "i,j,cptr,ptr=left*s0+offset" ]
+  
+  if(order.length > 1) {
+    var scratch_shape = []
+    for(var i=1; i<order.length; ++i) {
+      vars.push("i"+i)
+      scratch_shape.push("n"+i)
+    }
+    if(allocator) {
+      vars.push("scratch=malloc(" + scratch_shape.join("*") + ")")
+    } else {
+      vars.push("scratch=new Array("+scratch_shape.join("*") + ")")
+    }
+    vars.push("dptr","sptr","a","b")
+  } else {
+    vars.push("scratch")
+  }
+  
+  function dataRead(ptr) {
+    if(dtype === "generic") {
+      return ["data.get(", ptr, ")"].join("")
+    }
+    return ["data[",ptr,"]"].join("")
+  }
+  
+  function dataWrite(ptr, v) {
+    if(dtype === "generic") {
+      return ["data.set(", ptr, ",", v, ")"].join("")
+    }
+    return ["data[",ptr,"]=",v].join("")
+  }
+  
+  //Create function header
+  code.push(
+    ["function ", funcName, "(", funcArgs.join(","), "){var ", vars.join(",")].join(""),
+      "for(i=left+1;i<=right;++i){",
+        "j=i;ptr+=s0",
+        "cptr=ptr")
+  
+  
+  if(order.length > 1) {
+  
+    //Copy data into scratch
+    code.push("dptr=0;sptr=ptr")
+    for(var i=order.length-1; i>=0; --i) {
+      var j = order[i]
+      if(j === 0) {
+        continue
+      }
+      code.push(["for(i",j,"=0;i",j,"<n",j,";++i",j,"){"].join(""))
+    }
+    code.push("scratch[dptr++]=",dataRead("sptr"))
+    for(var i=0; i<order.length; ++i) {
+      var j = order[i]
+      if(j === 0) {
+        continue
+      }
+      code.push("sptr+=d"+j,"}")
+    }
+
+    
+    //Compare items in outer loop
+    code.push("__g:while(j-->left){",
+              "dptr=0",
+              "sptr=cptr-s0")
+    for(var i=1; i<order.length; ++i) {
+      if(i === 1) {
+        code.push("__l:")
+      }
+      code.push(["for(i",i,"=0;i",i,"<n",i,";++i",i,"){"].join(""))
+    }
+    code.push(["a=", dataRead("sptr"),"\nb=scratch[dptr]\nif(a<b){break __g}\nif(a>b){break __l}"].join(""))
+    for(var i=order.length-1; i>=1; --i) {
+      code.push(
+        "sptr+=e"+i,
+        "dptr+=f"+i,
+        "}")
+    }
+    
+    //Copy data back
+    code.push("dptr=cptr;sptr=cptr-s0")
+    for(var i=order.length-1; i>=0; --i) {
+      var j = order[i]
+      if(j === 0) {
+        continue
+      }
+      code.push(["for(i",j,"=0;i",j,"<n",j,";++i",j,"){"].join(""))
+    }
+    code.push(dataWrite("dptr", dataRead("sptr")))
+    for(var i=0; i<order.length; ++i) {
+      var j = order[i]
+      if(j === 0) {
+        continue
+      }
+      code.push(["dptr+=d",j,";sptr+=d",j].join(""),"}")
+    }
+    
+    //Close while loop
+    code.push("cptr-=s0\n}")
+
+    //Copy scratch into cptr
+    code.push("dptr=cptr;sptr=0")
+    for(var i=order.length-1; i>=0; --i) {
+      var j = order[i]
+      if(j === 0) {
+        continue
+      }
+      code.push(["for(i",j,"=0;i",j,"<n",j,";++i",j,"){"].join(""))
+    }
+    code.push(dataWrite("dptr", "scratch[sptr++]"))
+    for(var i=0; i<order.length; ++i) {
+      var j = order[i]
+      if(j === 0) {
+        continue
+      }
+      code.push("dptr+=d"+j,"}")
+    }
+  } else {
+    code.push("scratch=" + dataRead("ptr"),
+              "while((j-->left)&&("+dataRead("cptr-s0")+">scratch)){",
+                dataWrite("cptr", dataRead("cptr-s0")),
+                "cptr-=s0",
+              "}",
+              dataWrite("cptr", "scratch"))
+  }
+  
+  //Close outer loop body
+  code.push("}")
+  if(order.length > 1 && allocator) {
+    code.push("free(scratch)")
+  }
+  code.push("} return " + funcName)
+  
+  //Compile and link function
+  if(allocator) {
+    var result = new Function("malloc", "free", code.join("\n"))
+    return result(allocator[0], allocator[1])
+  } else {
+    var result = new Function(code.join("\n"))
+    return result()
+  }
+}
+
+function createQuickSort(order, dtype, insertionSort) {
+  var code = [ "'use strict'" ]
+  var funcName = ["ndarrayQuickSort", order.join("d"), dtype].join("")
+  var funcArgs = ["left", "right", "data", "offset" ].concat(shapeArgs(order.length))
+  var allocator = getMallocFree(dtype)
+  var labelCounter=0
+  
+  code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join(""))
+  
+  var vars = [
+    "sixth=((right-left+1)/6)|0",
+    "index1=left+sixth",
+    "index5=right-sixth",
+    "index3=(left+right)>>1",
+    "index2=index3-sixth",
+    "index4=index3+sixth",
+    "el1=index1",
+    "el2=index2",
+    "el3=index3",
+    "el4=index4",
+    "el5=index5",
+    "less=left+1",
+    "great=right-1",
+    "pivots_are_equal=true",
+    "tmp",
+    "tmp0",
+    "x",
+    "y",
+    "z",
+    "k",
+    "ptr0",
+    "ptr1",
+    "ptr2",
+    "comp_pivot1=0",
+    "comp_pivot2=0",
+    "comp=0"
+  ]
+  
+  if(order.length > 1) {
+    var ele_size = []
+    for(var i=1; i<order.length; ++i) {
+      ele_size.push("n"+i)
+      vars.push("i"+i)
+    }
+    for(var i=0; i<8; ++i) {
+      vars.push("b_ptr"+i)
+    }
+    vars.push(
+      "ptr3",
+      "ptr4",
+      "ptr5",
+      "ptr6",
+      "ptr7",
+      "pivot_ptr",
+      "ptr_shift",
+      "elementSize="+ele_size.join("*"))
+    if(allocator) {
+      vars.push("pivot1=malloc(elementSize)",
+                "pivot2=malloc(elementSize)")
+    } else {
+      vars.push("pivot1=new Array(elementSize),pivot2=new Array(elementSize)")
+    }
+  } else {
+    vars.push("pivot1", "pivot2")
+  }
+  
+  //Initialize local variables
+  code.push("var " + vars.join(","))
+  
+  function toPointer(v) {
+    return ["(offset+",v,"*s0)"].join("")
+  }
+  
+  function dataRead(ptr) {
+    if(dtype === "generic") {
+      return ["data.get(", ptr, ")"].join("")
+    }
+    return ["data[",ptr,"]"].join("")
+  }
+  
+  function dataWrite(ptr, v) {
+    if(dtype === "generic") {
+      return ["data.set(", ptr, ",", v, ")"].join("")
+    }
+    return ["data[",ptr,"]=",v].join("")
+  }
+  
+  function cacheLoop(ptrs, usePivot, body) {
+    if(ptrs.length === 1) {
+      code.push("ptr0="+toPointer(ptrs[0]))
+    } else {
+      for(var i=0; i<ptrs.length; ++i) {
+        code.push(["b_ptr",i,"=s0*",ptrs[i]].join(""))
+      }
+    }
+    if(usePivot) {
+      code.push("pivot_ptr=0")
+    }
+    code.push("ptr_shift=offset")
+    for(var i=order.length-1; i>=0; --i) {
+      var j = order[i]
+      if(j === 0) {
+        continue
+      }
+      code.push(["for(i",j,"=0;i",j,"<n",j,";++i",j,"){"].join(""))
+    }
+    if(ptrs.length > 1) {
+      for(var i=0; i<ptrs.length; ++i) {
+        code.push(["ptr",i,"=b_ptr",i,"+ptr_shift"].join(""))
+      }
+    }
+    code.push(body)
+    if(usePivot) {
+      code.push("++pivot_ptr")
+    }
+    for(var i=0; i<order.length; ++i) {
+      var j = order[i]
+      if(j === 0) {
+        continue
+      }
+      if(ptrs.length>1) {
+        code.push("ptr_shift+=d"+j)
+      } else {
+        code.push("ptr0+=d"+j)
+      }
+      code.push("}")
+    }
+  }
+  
+  function lexicoLoop(label, ptrs, usePivot, body) {
+    if(ptrs.length === 1) {
+      code.push("ptr0="+toPointer(ptrs[0]))
+    } else {
+      for(var i=0; i<ptrs.length; ++i) {
+        code.push(["b_ptr",i,"=s0*",ptrs[i]].join(""))
+      }
+      code.push("ptr_shift=offset")
+    }
+    if(usePivot) {
+      code.push("pivot_ptr=0")
+    }
+    if(label) {
+      code.push(label+":")
+    }
+    for(var i=1; i<order.length; ++i) {
+      code.push(["for(i",i,"=0;i",i,"<n",i,";++i",i,"){"].join(""))
+    }
+    if(ptrs.length > 1) {
+      for(var i=0; i<ptrs.length; ++i) {
+        code.push(["ptr",i,"=b_ptr",i,"+ptr_shift"].join(""))
+      }
+    }
+    code.push(body)
+    for(var i=order.length-1; i>=1; --i) {
+      if(usePivot) {
+        code.push("pivot_ptr+=f"+i)
+      }
+      if(ptrs.length > 1) {
+        code.push("ptr_shift+=e"+i)
+      } else {
+        code.push("ptr0+=e"+i)
+      }
+      code.push("}")
+    }
+  }
+  
+  function cleanUp() {
+    if(order.length > 1 && allocator) {
+      code.push("free(pivot1)", "free(pivot2)")
+    }
+  }
+  
+  function compareSwap(a_id, b_id) {
+    var a = "el"+a_id
+    var b = "el"+b_id
+    if(order.length > 1) {
+      var lbl = "__l" + (++labelCounter)
+      lexicoLoop(lbl, [a, b], false, [
+        "comp=",dataRead("ptr0"),"-",dataRead("ptr1"),"\n",
+        "if(comp>0){tmp0=", a, ";",a,"=",b,";", b,"=tmp0;break ", lbl,"}\n",
+        "if(comp<0){break ", lbl, "}"
+      ].join(""))
+    } else {
+      code.push(["if(", dataRead(toPointer(a)), ">", dataRead(toPointer(b)), "){tmp0=", a, ";",a,"=",b,";", b,"=tmp0}"].join(""))
+    }
+  }
+  
+  compareSwap(1, 2)
+  compareSwap(4, 5)
+  compareSwap(1, 3)
+  compareSwap(2, 3)
+  compareSwap(1, 4)
+  compareSwap(3, 4)
+  compareSwap(2, 5)
+  compareSwap(2, 3)
+  compareSwap(4, 5)
+  
+  if(order.length > 1) {
+    cacheLoop(["el1", "el2", "el3", "el4", "el5", "index1", "index3", "index5"], true, [
+      "pivot1[pivot_ptr]=",dataRead("ptr1"),"\n",
+      "pivot2[pivot_ptr]=",dataRead("ptr3"),"\n",
+      "pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n",
+      "x=",dataRead("ptr0"),"\n",
+      "y=",dataRead("ptr2"),"\n",
+      "z=",dataRead("ptr4"),"\n",
+      dataWrite("ptr5", "x"),"\n",
+      dataWrite("ptr6", "y"),"\n",
+      dataWrite("ptr7", "z")
+    ].join(""))
+  } else {
+    code.push([
+      "pivot1=", dataRead(toPointer("el2")), "\n",
+      "pivot2=", dataRead(toPointer("el4")), "\n",
+      "pivots_are_equal=pivot1===pivot2\n",
+      "x=", dataRead(toPointer("el1")), "\n",
+      "y=", dataRead(toPointer("el3")), "\n",
+      "z=", dataRead(toPointer("el5")), "\n",
+      dataWrite(toPointer("index1"), "x"), "\n",
+      dataWrite(toPointer("index3"), "y"), "\n",
+      dataWrite(toPointer("index5"), "z")
+    ].join(""))
+  }
+  
+
+  function moveElement(dst, src) {
+    if(order.length > 1) {
+      cacheLoop([dst, src], false,
+        dataWrite("ptr0", dataRead("ptr1"))
+      )
+    } else {
+      code.push(dataWrite(toPointer(dst), dataRead(toPointer(src))))
+    }
+  }
+  
+  moveElement("index2", "left")
+  moveElement("index4", "right")
+  
+  function comparePivot(result, ptr, n) {
+    if(order.length > 1) {
+      var lbl = "__l" + (++labelCounter)
+      lexicoLoop(lbl, [ptr], true, [
+        result,"=",dataRead("ptr0"),"-pivot",n,"[pivot_ptr]\n",
+        "if(",result,"!==0){break ", lbl, "}"
+      ].join(""))
+    } else {
+      code.push([result,"=", dataRead(toPointer(ptr)), "-pivot", n].join(""))
+    }
+  }
+  
+  function swapElements(a, b) {
+    if(order.length > 1) {
+      cacheLoop([a,b],false,[
+        "tmp=",dataRead("ptr0"),"\n",
+        dataWrite("ptr0", dataRead("ptr1")),"\n",
+        dataWrite("ptr1", "tmp")
+      ].join(""))
+    } else {
+      code.push([
+        "ptr0=",toPointer(a),"\n",
+        "ptr1=",toPointer(b),"\n",
+        "tmp=",dataRead("ptr0"),"\n",
+        dataWrite("ptr0", dataRead("ptr1")),"\n",
+        dataWrite("ptr1", "tmp")
+      ].join(""))
+    }
+  }
+  
+  function tripleSwap(k, less, great) {
+    if(order.length > 1) {
+      cacheLoop([k,less,great], false, [
+        "tmp=",dataRead("ptr0"),"\n",
+        dataWrite("ptr0", dataRead("ptr1")),"\n",
+        dataWrite("ptr1", dataRead("ptr2")),"\n",
+        dataWrite("ptr2", "tmp")
+      ].join(""))
+      code.push("++"+less, "--"+great)
+    } else {
+      code.push([
+        "ptr0=",toPointer(k),"\n",
+        "ptr1=",toPointer(less),"\n",
+        "ptr2=",toPointer(great),"\n",
+        "++",less,"\n",
+        "--",great,"\n",
+        "tmp=", dataRead("ptr0"), "\n",
+        dataWrite("ptr0", dataRead("ptr1")), "\n",
+        dataWrite("ptr1", dataRead("ptr2")), "\n",
+        dataWrite("ptr2", "tmp")
+      ].join(""))
+    }
+  }
+  
+  function swapAndDecrement(k, great) {
+    swapElements(k, great)
+    code.push("--"+great)
+  }
+    
+  code.push("if(pivots_are_equal){")
+    //Pivots are equal case
+    code.push("for(k=less;k<=great;++k){")
+      comparePivot("comp", "k", 1)
+      code.push("if(comp===0){continue}")
+      code.push("if(comp<0){")
+        code.push("if(k!==less){")
+          swapElements("k", "less")
+        code.push("}")
+        code.push("++less")
+      code.push("}else{")
+        code.push("while(true){")
+          comparePivot("comp", "great", 1)
+          code.push("if(comp>0){")
+            code.push("great--")
+          code.push("}else if(comp<0){")
+            tripleSwap("k", "less", "great")
+            code.push("break")
+          code.push("}else{")
+            swapAndDecrement("k", "great")
+            code.push("break")
+          code.push("}")
+        code.push("}")
+      code.push("}")
+    code.push("}")
+  code.push("}else{")
+    //Pivots not equal case
+    code.push("for(k=less;k<=great;++k){")
+      comparePivot("comp_pivot1", "k", 1)
+      code.push("if(comp_pivot1<0){")
+        code.push("if(k!==less){")
+          swapElements("k", "less")
+        code.push("}")
+        code.push("++less")
+      code.push("}else{")
+        comparePivot("comp_pivot2", "k", 2)
+        code.push("if(comp_pivot2>0){")
+          code.push("while(true){")
+            comparePivot("comp", "great", 2)
+            code.push("if(comp>0){")
+              code.push("if(--great<k){break}")
+              code.push("continue")
+            code.push("}else{")
+              comparePivot("comp", "great", 1)
+              code.push("if(comp<0){")
+                tripleSwap("k", "less", "great")
+              code.push("}else{")
+                swapAndDecrement("k", "great")
+              code.push("}")
+              code.push("break")
+            code.push("}")
+          code.push("}")
+        code.push("}")
+      code.push("}")
+    code.push("}")
+  code.push("}")
+  
+  //Move pivots to correct place
+  function storePivot(mem_dest, pivot_dest, pivot) {
+    if(order.length>1) {
+      cacheLoop([mem_dest, pivot_dest], true, [
+        dataWrite("ptr0", dataRead("ptr1")), "\n",
+        dataWrite("ptr1", ["pivot",pivot,"[pivot_ptr]"].join(""))
+      ].join(""))
+    } else {
+      code.push(
+          dataWrite(toPointer(mem_dest), dataRead(toPointer(pivot_dest))),
+          dataWrite(toPointer(pivot_dest), "pivot"+pivot))
+    }
+  }
+  
+  storePivot("left", "(less-1)", 1)
+  storePivot("right", "(great+1)", 2)
+
+  //Recursive sort call
+  function doSort(left, right) {
+    code.push([
+      "if((",right,"-",left,")<=",INSERTION_SORT_THRESHOLD,"){\n",
+        "insertionSort(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n",
+      "}else{\n",
+        funcName, "(", left, ",", right, ",data,offset,", shapeArgs(order.length).join(","), ")\n",
+      "}"
+    ].join(""))
+  }
+  doSort("left", "(less-2)")
+  doSort("(great+2)", "right")
+  
+  //If pivots are equal, then early out
+  code.push("if(pivots_are_equal){")
+    cleanUp()
+    code.push("return")
+  code.push("}")
+  
+  function walkPointer(ptr, pivot, body) {
+    if(order.length > 1) {
+      code.push(["__l",++labelCounter,":while(true){"].join(""))
+      cacheLoop([ptr], true, [
+        "if(", dataRead("ptr0"), "!==pivot", pivot, "[pivot_ptr]){break __l", labelCounter, "}"
+      ].join(""))
+      code.push(body, "}")
+    } else {
+      code.push(["while(", dataRead(toPointer(ptr)), "===pivot", pivot, "){", body, "}"].join(""))
+    }
+  }
+  
+  //Check bounds
+  code.push("if(less<index1&&great>index5){")
+  
+    walkPointer("less", 1, "++less")
+    walkPointer("great", 2, "--great")
+  
+    code.push("for(k=less;k<=great;++k){")
+      comparePivot("comp_pivot1", "k", 1)
+      code.push("if(comp_pivot1===0){")
+        code.push("if(k!==less){")
+          swapElements("k", "less")
+        code.push("}")
+        code.push("++less")
+      code.push("}else{")
+        comparePivot("comp_pivot2", "k", 2)
+        code.push("if(comp_pivot2===0){")
+          code.push("while(true){")
+            comparePivot("comp", "great", 2)
+            code.push("if(comp===0){")
+              code.push("if(--great<k){break}")
+              code.push("continue")
+            code.push("}else{")
+              comparePivot("comp", "great", 1)
+              code.push("if(comp<0){")
+                tripleSwap("k", "less", "great")
+              code.push("}else{")
+                swapAndDecrement("k", "great")
+              code.push("}")
+              code.push("break")
+            code.push("}")
+          code.push("}")
+        code.push("}")
+      code.push("}")
+    code.push("}")
+  code.push("}")
+  
+  //Clean up and do a final sorting pass
+  cleanUp()
+  doSort("less", "great")
+ 
+  //Close off main loop
+  code.push("}return " + funcName)
+  
+  //Compile and link
+  if(order.length > 1 && allocator) {
+    var compiled = new Function("insertionSort", "malloc", "free", code.join("\n"))
+    return compiled(insertionSort, allocator[0], allocator[1])
+  }
+  var compiled = new Function("insertionSort", code.join("\n"))
+  return compiled(insertionSort)
+}
+
+function compileSort(order, dtype) {
+  var code = ["'use strict'"]
+  var funcName = ["ndarraySortWrapper", order.join("d"), dtype].join("")
+  var funcArgs = [ "array" ]
+  
+  code.push(["function ", funcName, "(", funcArgs.join(","), "){"].join(""))
+  
+  //Unpack local variables from array
+  var vars = ["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"]
+  for(var i=0; i<order.length; ++i) {
+    vars.push(["s",i,"=stride[",i,"]|0,n",i,"=shape[",i,"]|0"].join(""))
+  }
+  
+  var scratch_stride = new Array(order.length)
+  var nprod = []
+  for(var i=0; i<order.length; ++i) {
+    var k = order[i]
+    if(k === 0) {
+      continue
+    }
+    if(nprod.length === 0) {
+      scratch_stride[k] = "1"
+    } else {
+      scratch_stride[k] = nprod.join("*")
+    }
+    nprod.push("n"+k)
+  }
+  
+  var p = -1, q = -1
+  for(var i=0; i<order.length; ++i) {
+    var j = order[i]
+    if(j !== 0) {
+      if(p > 0) {
+        vars.push(["d",j,"=s",j,"-d",p,"*n",p].join(""))
+      } else {
+        vars.push(["d",j,"=s",j].join(""))
+      }
+      p = j
+    }
+    var k = order.length-1-i
+    if(k !== 0) {
+      if(q > 0) {
+        vars.push(["e",k,"=s",k,"-e",q,"*n",q,
+                  ",f",k,"=",scratch_stride[k],"-f",q,"*n",q].join(""))
+      } else {
+        vars.push(["e",k,"=s",k,",f",k,"=",scratch_stride[k]].join(""))
+      }
+      q = k
+    }
+  }
+  
+  //Declare local variables
+  code.push("var " + vars.join(","))
+  
+  //Create arguments for subroutine
+  var sortArgs = ["0", "n0-1", "data", "offset"].concat(shapeArgs(order.length))
+  
+  //Call main sorting routine
+  code.push([
+    "if(n0<=",INSERTION_SORT_THRESHOLD,"){",
+      "insertionSort(", sortArgs.join(","), ")}else{",
+      "quickSort(", sortArgs.join(","),
+    ")}"
+  ].join(""))
+  
+  //Return
+  code.push("}return " + funcName)
+  
+  //Link everything together
+  var result = new Function("insertionSort", "quickSort", code.join("\n"))
+  var insertionSort = createInsertionSort(order, dtype)
+  var quickSort = createQuickSort(order, dtype, insertionSort)
+  return result(insertionSort, quickSort)
+}
+
+module.exports = compileSort
+},{"typedarray-pool":233}],115:[function(require,module,exports){
+"use strict"
+
+var compile = require("./lib/compile_sort.js")
+var CACHE = {}
+
+function sort(array) {
+  var order = array.order
+  var dtype = array.dtype
+  var typeSig = [order, dtype ]
+  var typeName = typeSig.join(":")
+  var compiled = CACHE[typeName]
+  if(!compiled) {
+    CACHE[typeName] = compiled = compile(order, dtype)
+  }
+  compiled(array)
+  return array
+}
+
+module.exports = sort
+},{"./lib/compile_sort.js":114}],116:[function(require,module,exports){
+'use strict'
+
+module.exports = createBoxes
+
+var createBuffer = require('gl-buffer')
+var createShader = require('gl-shader')
+
+var shaders = require('./shaders')
+
+function Boxes(plot, vbo, shader) {
+  this.plot   = plot
+  this.vbo    = vbo
+  this.shader = shader
+}
+
+var proto = Boxes.prototype
+
+proto.bind = function() {
+  var shader = this.shader
+  this.vbo.bind()
+  this.shader.bind()
+  shader.attributes.coord.pointer()
+  shader.uniforms.screenBox = this.plot.screenBox
+}
+
+proto.drawBox = (function() {
+  var lo = [0,0]
+  var hi = [0,0]
+  return function(loX, loY, hiX, hiY, color) {
+    var plot       = this.plot
+    var shader     = this.shader
+    var gl         = plot.gl
+
+    lo[0] = loX
+    lo[1] = loY
+    hi[0] = hiX
+    hi[1] = hiY
+
+    shader.uniforms.lo     = lo
+    shader.uniforms.hi     = hi
+    shader.uniforms.color  = color
+
+    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+  }
+}())
+
+proto.dispose = function() {
+  this.vbo.dispose()
+  this.shader.dispose()
+}
+
+function createBoxes(plot) {
+  var gl  = plot.gl
+  var vbo = createBuffer(gl, [
+    0,0,
+    0,1,
+    1,0,
+    1,1])
+  var shader  = createShader(gl, shaders.boxVert, shaders.lineFrag)
+  return new Boxes(plot, vbo, shader)
+}
+
+},{"./shaders":119,"gl-buffer":75,"gl-shader":154}],117:[function(require,module,exports){
+'use strict'
+
+module.exports = createGrid
+
+var createBuffer  = require('gl-buffer')
+var createShader  = require('gl-shader')
+var bsearch       = require('binary-search-bounds')
+var shaders       = require('./shaders')
+
+function Grid(plot, vbo, shader, tickShader) {
+  this.plot   = plot
+  this.vbo    = vbo
+  this.shader = shader
+  this.tickShader = tickShader
+  this.ticks  = [[], []]
+}
+
+function compareTickNum(a, b) {
+  return a - b
+}
+
+var proto = Grid.prototype
+
+proto.draw = (function() {
+
+  var DATA_SHIFT = [0,0]
+  var DATA_SCALE = [0,0]
+  var DATA_AXIS  = [0,0]
+
+  return function() {
+    var plot       = this.plot
+    var vbo        = this.vbo
+    var shader     = this.shader
+    var ticks      = this.ticks
+    var gl         = plot.gl
+    var bounds     = plot._tickBounds
+    var dataBox    = plot.dataBox
+    var viewPixels = plot.viewBox
+    var lineWidth  = plot.gridLineWidth
+    var gridColor  = plot.gridLineColor
+    var gridEnable = plot.gridLineEnable
+    var pixelRatio = plot.pixelRatio
+
+    for(var i=0; i<2; ++i) {
+      var lo = bounds[i]
+      var hi = bounds[i+2]
+      var boundScale = hi - lo
+      var dataCenter  = 0.5 * (dataBox[i+2] + dataBox[i])
+      var dataWidth   = dataBox[i+2] - dataBox[i]
+      DATA_SCALE[i] = 2.0 * boundScale / dataWidth
+      DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth
+    }
+
+    shader.bind()
+    vbo.bind()
+    shader.attributes.dataCoord.pointer()
+    shader.uniforms.dataShift = DATA_SHIFT
+    shader.uniforms.dataScale = DATA_SCALE
+
+    var offset = 0
+    for(var i=0; i<2; ++i) {
+      DATA_AXIS[0] = DATA_AXIS[1] = 0
+      DATA_AXIS[i] = 1
+      shader.uniforms.dataAxis  = DATA_AXIS
+      shader.uniforms.lineWidth = lineWidth[i] / (viewPixels[i+2] - viewPixels[i]) * pixelRatio
+      shader.uniforms.color     = gridColor[i]
+
+      var size = ticks[i].length * 6
+      if(gridEnable[i]) {
+        gl.drawArrays(gl.TRIANGLES, offset, size)
+      }
+      offset += size
+    }
+  }
+})()
+
+proto.drawTickMarks = (function() {
+  var DATA_SHIFT = [0,0]
+  var DATA_SCALE = [0,0]
+  var X_AXIS     = [1,0]
+  var Y_AXIS     = [0,1]
+  var SCR_OFFSET = [0,0]
+  var TICK_SCALE = [0,0]
+
+  return function() {
+    var plot       = this.plot
+    var vbo        = this.vbo
+    var shader     = this.tickShader
+    var ticks      = this.ticks
+    var gl         = plot.gl
+    var bounds     = plot._tickBounds
+    var dataBox    = plot.dataBox
+    var viewBox    = plot.viewBox
+    var pixelRatio = plot.pixelRatio
+    var screenBox  = plot.screenBox
+
+    var screenWidth  = screenBox[2] - screenBox[0]
+    var screenHeight = screenBox[3] - screenBox[1]
+    var viewWidth    = viewBox[2]   - viewBox[0]
+    var viewHeight   = viewBox[3]   - viewBox[1]
+
+    for(var i=0; i<2; ++i) {
+      var lo = bounds[i]
+      var hi = bounds[i+2]
+      var boundScale = hi - lo
+      var dataCenter  = 0.5 * (dataBox[i+2] + dataBox[i])
+      var dataWidth   = (dataBox[i+2] - dataBox[i])
+      DATA_SCALE[i] = 2.0 * boundScale / dataWidth
+      DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth
+    }
+
+    DATA_SCALE[0] *= viewWidth / screenWidth
+    DATA_SHIFT[0] *= viewWidth / screenWidth
+
+    DATA_SCALE[1] *= viewHeight / screenHeight
+    DATA_SHIFT[1] *= viewHeight / screenHeight
+
+    shader.bind()
+    vbo.bind()
+
+    shader.attributes.dataCoord.pointer()
+
+    var uniforms = shader.uniforms
+    uniforms.dataShift = DATA_SHIFT
+    uniforms.dataScale = DATA_SCALE
+
+    var tickMarkLength = plot.tickMarkLength
+    var tickMarkWidth  = plot.tickMarkWidth
+    var tickMarkColor  = plot.tickMarkColor
+
+    var xTicksOffset = 0
+    var yTicksOffset = ticks[0].length * 6
+
+    var xStart = Math.min(bsearch.ge(ticks[0], (dataBox[0] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length)
+    var xEnd   = Math.min(bsearch.gt(ticks[0], (dataBox[2] - bounds[0]) / (bounds[2] - bounds[0]), compareTickNum), ticks[0].length)
+    var xOffset = xTicksOffset + 6 * xStart
+    var xCount  = 6 * Math.max(0, xEnd - xStart)
+
+    var yStart = Math.min(bsearch.ge(ticks[1], (dataBox[1] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length)
+    var yEnd   = Math.min(bsearch.gt(ticks[1], (dataBox[3] - bounds[1]) / (bounds[3] - bounds[1]), compareTickNum), ticks[1].length)
+    var yOffset = yTicksOffset + 6 * yStart
+    var yCount  = 6 * Math.max(0, yEnd - yStart)
+
+    SCR_OFFSET[0]         = 2.0 * (viewBox[0] - tickMarkLength[1]) / screenWidth - 1.0
+    SCR_OFFSET[1]         = (viewBox[3] + viewBox[1]) / screenHeight - 1.0
+    TICK_SCALE[0]         = tickMarkLength[1] * pixelRatio / screenWidth
+    TICK_SCALE[1]         = tickMarkWidth[1]  * pixelRatio / screenHeight
+
+    uniforms.color        = tickMarkColor[1]
+    uniforms.tickScale    = TICK_SCALE
+    uniforms.dataAxis     = Y_AXIS
+    uniforms.screenOffset = SCR_OFFSET
+    gl.drawArrays(gl.TRIANGLES, yOffset, yCount)
+
+    SCR_OFFSET[0]         = (viewBox[2] + viewBox[0]) / screenWidth - 1.0
+    SCR_OFFSET[1]         = 2.0 * (viewBox[1] - tickMarkLength[0]) / screenHeight - 1.0
+    TICK_SCALE[0]         = tickMarkWidth[0]  * pixelRatio / screenWidth
+    TICK_SCALE[1]         = tickMarkLength[0] * pixelRatio / screenHeight
+
+    uniforms.color        = tickMarkColor[0]
+    uniforms.tickScale    = TICK_SCALE
+    uniforms.dataAxis     = X_AXIS
+    uniforms.screenOffset = SCR_OFFSET
+    gl.drawArrays(gl.TRIANGLES, xOffset, xCount)
+
+    SCR_OFFSET[0]         = 2.0 * (viewBox[2] + tickMarkLength[3]) / screenWidth - 1.0
+    SCR_OFFSET[1]         = (viewBox[3] + viewBox[1]) / screenHeight - 1.0
+    TICK_SCALE[0]         = tickMarkLength[3] * pixelRatio / screenWidth
+    TICK_SCALE[1]         = tickMarkWidth[3]  * pixelRatio / screenHeight
+
+    uniforms.color        = tickMarkColor[3]
+    uniforms.tickScale    = TICK_SCALE
+    uniforms.dataAxis     = Y_AXIS
+    uniforms.screenOffset = SCR_OFFSET
+    gl.drawArrays(gl.TRIANGLES, yOffset, yCount)
+
+    SCR_OFFSET[0]         = (viewBox[2] + viewBox[0]) / screenWidth - 1.0
+    SCR_OFFSET[1]         = 2.0 * (viewBox[3] + tickMarkLength[2]) / screenHeight - 1.0
+    TICK_SCALE[0]         = tickMarkWidth[2]  * pixelRatio / screenWidth
+    TICK_SCALE[1]         = tickMarkLength[2] * pixelRatio / screenHeight
+
+    uniforms.color        = tickMarkColor[2]
+    uniforms.tickScale    = TICK_SCALE
+    uniforms.dataAxis     = X_AXIS
+    uniforms.screenOffset = SCR_OFFSET
+    gl.drawArrays(gl.TRIANGLES, xOffset, xCount)
+  }
+})()
+
+proto.update = (function() {
+  var OFFSET_X = [1,  1, -1, -1,  1, -1]
+  var OFFSET_Y = [1, -1,  1,  1, -1, -1]
+
+  return function(options) {
+    var ticks  = options.ticks
+    var bounds = options.bounds
+    var data   = new Float32Array(6 * 3 * (ticks[0].length + ticks[1].length))
+
+    var zeroLineEnable = this.plot.zeroLineEnable
+
+    var ptr    = 0
+    var gridTicks = [[], []]
+    for(var dim=0; dim<2; ++dim) {
+      var localTicks = gridTicks[dim]
+      var axisTicks = ticks[dim]
+      var lo = bounds[dim]
+      var hi = bounds[dim+2]
+      for(var i=0; i<axisTicks.length; ++i) {
+        var x = (axisTicks[i].x - lo) / (hi - lo)
+        localTicks.push(x)
+        for(var j=0; j<6; ++j) {
+          data[ptr++] = x
+          data[ptr++] = OFFSET_X[j]
+          data[ptr++] = OFFSET_Y[j]
+        }
+      }
+    }
+
+    this.ticks = gridTicks
+    this.vbo.update(data)
+  }
+})()
+
+proto.dispose = function() {
+  this.vbo.dispose()
+  this.shader.dispose()
+  this.tickShader.dispose()
+}
+
+function createGrid(plot) {
+  var gl     = plot.gl
+  var vbo    = createBuffer(gl)
+  var shader = createShader(gl, shaders.gridVert, shaders.gridFrag)
+  var tickShader = createShader(gl, shaders.tickVert, shaders.gridFrag)
+  var grid   = new Grid(plot, vbo, shader, tickShader)
+  return grid
+}
+
+},{"./shaders":119,"binary-search-bounds":121,"gl-buffer":75,"gl-shader":154}],118:[function(require,module,exports){
+'use strict'
+
+module.exports = createLines
+
+var createBuffer = require('gl-buffer')
+var createShader = require('gl-shader')
+
+var shaders = require('./shaders')
+
+function Lines(plot, vbo, shader) {
+  this.plot   = plot
+  this.vbo    = vbo
+  this.shader = shader
+}
+
+var proto = Lines.prototype
+
+proto.bind = function() {
+  var shader = this.shader
+  this.vbo.bind()
+  this.shader.bind()
+  shader.attributes.coord.pointer()
+  shader.uniforms.screenBox = this.plot.screenBox
+}
+
+proto.drawLine = (function() {
+  var start = [0,0]
+  var end   = [0,0]
+  return function(startX, startY, endX, endY, width, color) {
+    var plot       = this.plot
+    var shader     = this.shader
+    var gl         = plot.gl
+
+    start[0] = startX
+    start[1] = startY
+    end[0]   = endX
+    end[1]   = endY
+
+    shader.uniforms.start  = start
+    shader.uniforms.end    = end
+    shader.uniforms.width  = width * plot.pixelRatio
+    shader.uniforms.color  = color
+
+    gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
+  }
+}())
+
+proto.dispose = function() {
+  this.vbo.dispose()
+  this.shader.dispose()
+}
+
+function createLines(plot) {
+  var gl  = plot.gl
+  var vbo = createBuffer(gl, [
+    -1,-1,
+    -1,1,
+    1,-1,
+    1,1])
+  var shader  = createShader(gl, shaders.lineVert, shaders.lineFrag)
+  var lines   = new Lines(plot, vbo, shader)
+  return lines
+}
+
+},{"./shaders":119,"gl-buffer":75,"gl-shader":154}],119:[function(require,module,exports){
+'use strict'
+
+
+
+var FRAGMENT = "#define GLSLIFY 1\nprecision lowp float;\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = vec4(color.xyz * color.w, color.w);\n}\n"
+
+module.exports = {
+  lineVert: "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n  return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n  return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n  vec2 delta = normalize(perp(start - end));\n  vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n  gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n",
+  lineFrag: FRAGMENT,
+  textVert: "#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n  float dataOffset  = textCoordinate.z;\n  vec2 glyphOffset  = textCoordinate.xy;\n  mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n  vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n    glyphMatrix * glyphOffset * textScale + screenOffset;\n  gl_Position = vec4(screenCoordinate, 0, 1);\n}\n",
+  textFrag: FRAGMENT,
+  gridVert: "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n  vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n  pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n  gl_Position = vec4(pos, 0, 1);\n}\n",
+  gridFrag: FRAGMENT,
+  boxVert:  "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n  return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n  gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n",
+  tickVert: "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n  vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n  gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n"
+}
+
+},{}],120:[function(require,module,exports){
+'use strict'
+
+module.exports = createTextElements
+
+var createBuffer = require('gl-buffer')
+var createShader = require('gl-shader')
+var getText      = require('text-cache')
+var bsearch      = require('binary-search-bounds')
+var shaders      = require('./shaders')
+
+function TextElements(plot, vbo, shader) {
+  this.plot         = plot
+  this.vbo          = vbo
+  this.shader       = shader
+  this.tickOffset   = [[],[]]
+  this.tickX        = [[],[]]
+  this.labelOffset  = [0,0]
+  this.labelCount   = [0,0]
+}
+
+var proto = TextElements.prototype
+
+proto.drawTicks = (function() {
+  var DATA_AXIS = [0,0]
+  var SCREEN_OFFSET = [0,0]
+  var ZERO_2 = [0,0]
+
+  return function(axis) {
+    var plot        = this.plot
+    var shader      = this.shader
+    var tickX       = this.tickX[axis]
+    var tickOffset  = this.tickOffset[axis]
+    var gl          = plot.gl
+    var viewBox     = plot.viewBox
+    var dataBox     = plot.dataBox
+    var screenBox   = plot.screenBox
+    var pixelRatio  = plot.pixelRatio
+    var tickEnable  = plot.tickEnable
+    var tickPad     = plot.tickPad
+    var textColor   = plot.tickColor
+    var textAngle   = plot.tickAngle
+    var tickLength  = plot.tickMarkLength
+
+    var labelEnable = plot.labelEnable
+    var labelPad    = plot.labelPad
+    var labelColor  = plot.labelColor
+    var labelAngle  = plot.labelAngle
+    var labelOffset = this.labelOffset[axis]
+    var labelCount  = this.labelCount[axis]
+
+    var start = bsearch.lt(tickX, dataBox[axis])
+    var end   = bsearch.le(tickX, dataBox[axis+2])
+
+    DATA_AXIS[0]    = DATA_AXIS[1] = 0
+    DATA_AXIS[axis] = 1
+
+    SCREEN_OFFSET[axis] = (viewBox[2+axis] + viewBox[axis]) / (screenBox[2+axis] - screenBox[axis]) - 1.0
+
+    var screenScale = 2.0 / screenBox[2+(axis^1)] - screenBox[axis^1]
+
+    SCREEN_OFFSET[axis^1] = screenScale * viewBox[axis^1] - 1.0
+    if(tickEnable[axis]) {
+      SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * tickPad[axis]
+      if(start < end) {
+        shader.uniforms.dataAxis     = DATA_AXIS
+        shader.uniforms.screenOffset = SCREEN_OFFSET
+        shader.uniforms.color        = textColor[axis]
+        shader.uniforms.angle        = textAngle[axis]
+        gl.drawArrays(
+          gl.TRIANGLES,
+          tickOffset[start],
+          tickOffset[end] - tickOffset[start])
+      }
+    }
+    if(labelEnable[axis]) {
+      SCREEN_OFFSET[axis^1] -= screenScale * pixelRatio * labelPad[axis]
+      shader.uniforms.dataAxis     = ZERO_2
+      shader.uniforms.screenOffset = SCREEN_OFFSET
+      shader.uniforms.color        = labelColor[axis]
+      shader.uniforms.angle        = labelAngle[axis]
+      gl.drawArrays(
+        gl.TRIANGLES,
+        labelOffset,
+        labelCount)
+    }
+
+    SCREEN_OFFSET[axis^1] = screenScale * viewBox[2+(axis^1)] - 1.0
+    if(tickEnable[axis+2]) {
+      SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * tickPad[axis+2]
+      if(start < end) {
+        shader.uniforms.dataAxis     = DATA_AXIS
+        shader.uniforms.screenOffset = SCREEN_OFFSET
+        shader.uniforms.color        = textColor[axis+2]
+        shader.uniforms.angle        = textAngle[axis+2]
+        gl.drawArrays(
+          gl.TRIANGLES,
+          tickOffset[start],
+          tickOffset[end] - tickOffset[start])
+      }
+    }
+    if(labelEnable[axis+2]) {
+      SCREEN_OFFSET[axis^1] += screenScale * pixelRatio * labelPad[axis+2]
+      shader.uniforms.dataAxis     = ZERO_2
+      shader.uniforms.screenOffset = SCREEN_OFFSET
+      shader.uniforms.color        = labelColor[axis+2]
+      shader.uniforms.angle        = labelAngle[axis+2]
+      gl.drawArrays(
+        gl.TRIANGLES,
+        labelOffset,
+        labelCount)
+    }
+
+  }
+})()
+
+proto.drawTitle = (function() {
+  var DATA_AXIS = [0,0]
+  var SCREEN_OFFSET = [0,0]
+
+  return function() {
+    var plot        = this.plot
+    var shader      = this.shader
+    var gl          = plot.gl
+    var screenBox   = plot.screenBox
+    var titleCenter = plot.titleCenter
+    var titleAngle  = plot.titleAngle
+    var titleColor  = plot.titleColor
+    var titleCenter = plot.titleCenter
+    var pixelRatio  = plot.pixelRatio
+
+    for(var i=0; i<2; ++i) {
+      SCREEN_OFFSET[i] = 2.0 * (titleCenter[i]*pixelRatio - screenBox[i]) /
+        (screenBox[2+i] - screenBox[i]) - 1
+    }
+
+    shader.bind()
+    shader.uniforms.dataAxis      = DATA_AXIS
+    shader.uniforms.screenOffset  = SCREEN_OFFSET
+    shader.uniforms.angle         = titleAngle
+    shader.uniforms.color         = titleColor
+
+    gl.drawArrays(gl.TRIANGLES, this.titleOffset, this.titleCount)
+  }
+})()
+
+proto.bind = (function() {
+  var DATA_SHIFT = [0,0]
+  var DATA_SCALE = [0,0]
+  var TEXT_SCALE = [0,0]
+
+  return function() {
+    var plot      = this.plot
+    var shader    = this.shader
+    var bounds    = plot._tickBounds
+    var dataBox   = plot.dataBox
+    var screenBox = plot.screenBox
+    var viewBox   = plot.viewBox
+
+    shader.bind()
+
+    //Set up coordinate scaling uniforms
+    for(var i=0; i<2; ++i) {
+
+      var lo = bounds[i]
+      var hi = bounds[i+2]
+      var boundScale = hi - lo
+      var dataCenter  = 0.5 * (dataBox[i+2] + dataBox[i])
+      var dataWidth   = (dataBox[i+2] - dataBox[i])
+
+      var viewLo = viewBox[i]
+      var viewHi = viewBox[i+2]
+      var viewScale = viewHi - viewLo
+      var screenLo = screenBox[i]
+      var screenHi = screenBox[i+2]
+      var screenScale = screenHi - screenLo
+
+      DATA_SCALE[i] = 2.0 * boundScale / dataWidth * viewScale / screenScale
+      DATA_SHIFT[i] = 2.0 * (lo - dataCenter) / dataWidth * viewScale / screenScale
+    }
+
+    TEXT_SCALE[1] = 2.0 * plot.pixelRatio / (screenBox[3] - screenBox[1])
+    TEXT_SCALE[0] = TEXT_SCALE[1] * (screenBox[3] - screenBox[1]) / (screenBox[2] - screenBox[0])
+
+    shader.uniforms.dataScale = DATA_SCALE
+    shader.uniforms.dataShift = DATA_SHIFT
+    shader.uniforms.textScale = TEXT_SCALE
+
+    //Set attributes
+    this.vbo.bind()
+    shader.attributes.textCoordinate.pointer()
+  }
+})()
+
+proto.update = function(options) {
+  var vertices  = []
+  var axesTicks = options.ticks
+  var bounds    = options.bounds
+
+  for(var dimension=0; dimension<2; ++dimension) {
+    var offsets = [Math.floor(vertices.length/3)], tickX = [-Infinity]
+
+    //Copy vertices over to buffer
+    var ticks = axesTicks[dimension]
+    for(var i=0; i<ticks.length; ++i) {
+      var tick  = ticks[i]
+      var x     = tick.x
+      var text  = tick.text
+      var font  = tick.font || 'sans-serif'
+      var scale = (tick.fontSize || 12)
+
+      var data = getText(font, text).data
+
+      var coordScale = 1.0 / (bounds[dimension+2] - bounds[dimension])
+      var coordShift = bounds[dimension]
+
+      for(var j=0; j<data.length; j+=2) {
+        vertices.push(
+           data[j]  *scale,
+          -data[j+1]*scale,
+          (x - coordShift) * coordScale)
+      }
+
+      offsets.push(Math.floor(vertices.length/3))
+      tickX.push(x)
+    }
+
+    this.tickOffset[dimension] = offsets
+    this.tickX[dimension] = tickX
+  }
+
+  //Add labels
+  for(var dimension=0; dimension<2; ++dimension) {
+    this.labelOffset[dimension] = Math.floor(vertices.length/3)
+
+    var data  = getText(options.labelFont[dimension], options.labels[dimension]).data
+    var scale = options.labelSize[dimension]
+    for(var i=0; i<data.length; i+=2) {
+      vertices.push(data[i]*scale, -data[i+1]*scale, 0)
+    }
+
+    this.labelCount[dimension] =
+      Math.floor(vertices.length/3) - this.labelOffset[dimension]
+  }
+
+  //Add title
+  this.titleOffset = Math.floor(vertices.length/3)
+  var data = getText(options.titleFont, options.title).data
+  var scale = options.titleSize
+  for(var i=0; i<data.length; i+=2) {
+    vertices.push(data[i]*scale, -data[i+1]*scale, 0)
+  }
+  this.titleCount = Math.floor(vertices.length/3) - this.titleOffset
+
+  //Upload new vertices
+  this.vbo.update(vertices)
+}
+
+proto.dispose = function() {
+  this.vbo.dispose()
+  this.shader.dispose()
+}
+
+function createTextElements(plot) {
+  var gl = plot.gl
+  var vbo = createBuffer(gl)
+  var shader = createShader(gl, shaders.textVert, shaders.textFrag)
+  var text = new TextElements(plot, vbo, shader)
+  return text
+}
+
+},{"./shaders":119,"binary-search-bounds":121,"gl-buffer":75,"gl-shader":154,"text-cache":228}],121:[function(require,module,exports){
+"use strict"
+
+function compileSearch(funcName, predicate, reversed, extraArgs, earlyOut) {
+  var code = [
+    "function ", funcName, "(a,l,h,", extraArgs.join(","),  "){",
+earlyOut ? "" : "var i=", (reversed ? "l-1" : "h+1"),
+";while(l<=h){\
+var m=(l+h)>>>1,x=a[m]"]
+  if(earlyOut) {
+    if(predicate.indexOf("c") < 0) {
+      code.push(";if(x===y){return m}else if(x<=y){")
+    } else {
+      code.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){")
+    }
+  } else {
+    code.push(";if(", predicate, "){i=m;")
+  }
+  if(reversed) {
+    code.push("l=m+1}else{h=m-1}")
+  } else {
+    code.push("h=m-1}else{l=m+1}")
+  }
+  code.push("}")
+  if(earlyOut) {
+    code.push("return -1};")
+  } else {
+    code.push("return i};")
+  }
+  return code.join("")
+}
+
+function compileBoundsSearch(predicate, reversed, suffix, earlyOut) {
+  var result = new Function([
+  compileSearch("A", "x" + predicate + "y", reversed, ["y"], earlyOut),
+  compileSearch("P", "c(x,y)" + predicate + "0", reversed, ["y", "c"], earlyOut),
+"function dispatchBsearch", suffix, "(a,y,c,l,h){\
+if(typeof(c)==='function'){\
+return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)\
+}else{\
+return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)\
+}}\
+return dispatchBsearch", suffix].join(""))
+  return result()
+}
+
+module.exports = {
+  ge: compileBoundsSearch(">=", false, "GE"),
+  gt: compileBoundsSearch(">", false, "GT"),
+  lt: compileBoundsSearch("<", true, "LT"),
+  le: compileBoundsSearch("<=", true, "LE"),
+  eq: compileBoundsSearch("-", true, "EQ", true)
+}
+
+},{}],122:[function(require,module,exports){
+'use strict'
+
+module.exports = createGLPlot2D
+
+var createPick = require('gl-select-static')
+
+var createGrid = require('./lib/grid')
+var createText = require('./lib/text')
+var createLine = require('./lib/line')
+var createBox  = require('./lib/box')
+
+function GLPlot2D(gl, pickBuffer) {
+  this.gl               = gl
+  this.pickBuffer       = pickBuffer
+
+  this.screenBox        = [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight]
+  this.viewBox          = [0, 0, 0, 0]
+  this.dataBox          = [-10, -10, 10, 10]
+
+  this.gridLineEnable   = [true,true]
+  this.gridLineWidth    = [1,1]
+  this.gridLineColor    = [[0,0,0,1],
+                           [0,0,0,1]]
+
+  this.pixelRatio       = 1
+
+  this.tickMarkLength   = [0,0,0,0]
+  this.tickMarkWidth    = [0,0,0,0]
+  this.tickMarkColor    = [[0,0,0,1],
+                           [0,0,0,1],
+                           [0,0,0,1],
+                           [0,0,0,1]]
+
+  this.tickPad          = [15,15,15,15]
+  this.tickAngle        = [0,0,0,0]
+  this.tickEnable       = [true,true,true,true]
+  this.tickColor        = [[0,0,0,1],
+                           [0,0,0,1],
+                           [0,0,0,1],
+                           [0,0,0,1]]
+
+  this.labelPad         = [15,15,15,15]
+  this.labelAngle       = [0,Math.PI/2,0,3.0*Math.PI/2]
+  this.labelEnable      = [true,true,true,true]
+  this.labelColor       = [[0,0,0,1],
+                           [0,0,0,1],
+                           [0,0,0,1],
+                           [0,0,0,1]]
+
+  this.titleCenter      = [0,0]
+  this.titleEnable      = true
+  this.titleAngle       = 0
+  this.titleColor       = [0,0,0,1]
+
+  this.borderColor      = [0,0,0,0]
+  this.backgroundColor  = [0,0,0,0]
+
+  this.zeroLineEnable   = [true, true]
+  this.zeroLineWidth    = [4, 4]
+  this.zeroLineColor    = [[0, 0, 0, 1],[0, 0, 0, 1]]
+
+  this.borderLineEnable = [true,true,true,true]
+  this.borderLineWidth  = [2,2,2,2]
+  this.borderLineColor  = [[0,0,0,1],
+                           [0,0,0,1],
+                           [0,0,0,1],
+                           [0,0,0,1]]
+
+  //Drawing parameters
+  this.grid             = null
+  this.text             = null
+  this.line             = null
+  this.box              = null
+  this.objects          = []
+  this.overlays         = []
+
+  this._tickBounds      = [Infinity, Infinity, -Infinity, -Infinity]
+
+  this.dirty        = false
+  this.pickDirty    = false
+  this.pickDelay    = 120
+  this.pickRadius   = 10
+  this._pickTimeout = null
+  this._drawPick    = this.drawPick.bind(this)
+
+  this._depthCounter = 0
+}
+
+var proto = GLPlot2D.prototype
+
+proto.setDirty = function() {
+  this.dirty = this.pickDirty = true
+}
+
+proto.setOverlayDirty = function() {
+  this.dirty = true
+}
+
+proto.nextDepthValue = function() {
+  return (this._depthCounter++) / 65536.0
+}
+
+function lerp(a, b, t) {
+  var s = 0.5 * (t + 1.0)
+  return Math.floor((1.0-s)*a + s*b)|0
+}
+
+proto.draw = (function() {
+var TICK_MARK_BOX = [0,0,0,0]
+return function() {
+  var gl         = this.gl
+  var screenBox  = this.screenBox
+  var viewPixels = this.viewBox
+  var dataBox    = this.dataBox
+  var pixelRatio = this.pixelRatio
+  var grid       = this.grid
+  var line       = this.line
+  var text       = this.text
+  var objects    = this.objects
+
+  this._depthCounter = 0
+
+  if(this.pickDirty) {
+    if(this._pickTimeout) {
+      clearTimeout(this._pickTimeout)
+    }
+    this.pickDirty = false
+    this._pickTimeout = setTimeout(this._drawPick, this.pickDelay)
+  }
+
+  if(!this.dirty) {
+    return
+  }
+  this.dirty = false
+
+  gl.bindFramebuffer(gl.FRAMEBUFFER, null)
+
+  //Turn on scissor
+  gl.enable(gl.SCISSOR_TEST)
+
+  //Turn off depth buffer
+  gl.disable(gl.DEPTH_TEST)
+  gl.depthFunc(gl.LESS)
+  gl.depthMask(false)
+
+  //Configure premultiplied alpha blending
+  gl.enable(gl.BLEND)
+  gl.blendEquation(gl.FUNC_ADD, gl.FUNC_ADD);
+  gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+
+  //Draw border
+  gl.scissor(
+    screenBox[0],
+    screenBox[1],
+    screenBox[2]-screenBox[0],
+    screenBox[3]-screenBox[1])
+  var borderColor = this.borderColor
+  gl.clearColor(
+    borderColor[0]*borderColor[3],
+    borderColor[1]*borderColor[3],
+    borderColor[2]*borderColor[3],
+    borderColor[3])
+  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
+
+  //Draw center pane
+  gl.scissor(
+    viewPixels[0],
+    viewPixels[1],
+    viewPixels[2]-viewPixels[0],
+    viewPixels[3]-viewPixels[1])
+  gl.viewport(
+    viewPixels[0],
+    viewPixels[1],
+    viewPixels[2]-viewPixels[0],
+    viewPixels[3]-viewPixels[1])
+  var backgroundColor = this.backgroundColor
+  gl.clearColor(
+    backgroundColor[0]*backgroundColor[3],
+    backgroundColor[1]*backgroundColor[3],
+    backgroundColor[2]*backgroundColor[3],
+    backgroundColor[3])
+  gl.clear(gl.COLOR_BUFFER_BIT)
+
+  //Draw grid
+  grid.draw()
+
+  //Draw zero lines separately
+  var zeroLineEnable = this.zeroLineEnable
+  var zeroLineColor  = this.zeroLineColor
+  var zeroLineWidth  = this.zeroLineWidth
+  if(zeroLineEnable[0] || zeroLineEnable[1]) {
+    line.bind()
+    for(var i=0; i<2; ++i) {
+      if(!zeroLineEnable[i] ||
+        !(dataBox[i] <= 0 && dataBox[i+2] >= 0)) {
+        continue
+      }
+
+      var zeroIntercept = screenBox[i] -
+        dataBox[i] * (screenBox[i+2] - screenBox[i]) / (dataBox[i+2] - dataBox[i])
+
+      if(i === 0) {
+        line.drawLine(
+          zeroIntercept, screenBox[1], zeroIntercept, screenBox[3],
+          zeroLineWidth[i],
+          zeroLineColor[i])
+      } else {
+        line.drawLine(
+          screenBox[0], zeroIntercept, screenBox[2], zeroIntercept,
+          zeroLineWidth[i],
+          zeroLineColor[i])
+      }
+    }
+  }
+
+  //Draw traces
+  for(var i=0; i<objects.length; ++i) {
+    objects[i].draw()
+  }
+
+  //Return viewport to default
+  gl.viewport(
+    screenBox[0],
+    screenBox[1],
+    screenBox[2]-screenBox[0],
+    screenBox[3]-screenBox[1])
+  gl.scissor(
+    screenBox[0],
+    screenBox[1],
+    screenBox[2]-screenBox[0],
+    screenBox[3]-screenBox[1])
+
+  //Draw tick marks
+  this.grid.drawTickMarks()
+
+  //Draw line elements
+  line.bind()
+
+  //Draw border lines
+  var borderLineEnable = this.borderLineEnable
+  var borderLineWidth  = this.borderLineWidth
+  var borderLineColor  = this.borderLineColor
+  if(borderLineEnable[1]) {
+    line.drawLine(
+      viewPixels[0], viewPixels[1] - 0.5*borderLineWidth[1]*pixelRatio,
+      viewPixels[0], viewPixels[3] + 0.5*borderLineWidth[3]*pixelRatio,
+      borderLineWidth[1], borderLineColor[1])
+  }
+  if(borderLineEnable[0]) {
+    line.drawLine(
+      viewPixels[0] - 0.5*borderLineWidth[0]*pixelRatio, viewPixels[1],
+      viewPixels[2] + 0.5*borderLineWidth[2]*pixelRatio, viewPixels[1],
+      borderLineWidth[0], borderLineColor[0])
+  }
+  if(borderLineEnable[3]) {
+    line.drawLine(
+      viewPixels[2], viewPixels[1] - 0.5*borderLineWidth[1]*pixelRatio,
+      viewPixels[2], viewPixels[3] + 0.5*borderLineWidth[3]*pixelRatio,
+      borderLineWidth[3], borderLineColor[3])
+  }
+  if(borderLineEnable[2]) {
+    line.drawLine(
+      viewPixels[0] - 0.5*borderLineWidth[0]*pixelRatio, viewPixels[3],
+      viewPixels[2] + 0.5*borderLineWidth[2]*pixelRatio, viewPixels[3],
+      borderLineWidth[2], borderLineColor[2])
+  }
+
+  //Draw text elements
+  text.bind()
+  for(var i=0; i<2; ++i) {
+    text.drawTicks(i)
+  }
+  if(this.titleEnable) {
+    text.drawTitle()
+  }
+
+  //Draw other overlay elements (select boxes, etc.)
+  var overlays = this.overlays
+  for(var i=0; i<overlays.length; ++i) {
+    overlays[i].draw()
+  }
+
+  //Turn off scissor test
+  gl.disable(gl.SCISSOR_TEST)
+  gl.disable(gl.BLEND)
+  gl.depthMask(true)
+}
+})()
+
+proto.drawPick = (function() {
+
+return function() {
+  var pickBuffer = this.pickBuffer
+  var gl = this.gl
+
+  this._pickTimeout = null
+  pickBuffer.begin()
+
+  var pickOffset = 1
+  var objects = this.objects
+  for(var i=0; i<objects.length; ++i) {
+    pickOffset = objects[i].drawPick(pickOffset)
+  }
+
+  pickBuffer.end()
+}
+})()
+
+proto.pick = (function() {
+return function(x, y) {
+  var pixelRatio     = this.pixelRatio
+  var pickPixelRatio = this.pickPixelRatio
+  var viewBox        = this.viewBox
+
+  var scrX = Math.round((x - viewBox[0] / pixelRatio) * pickPixelRatio)|0
+  var scrY = Math.round((y - viewBox[1] / pixelRatio) * pickPixelRatio)|0
+
+  var pickResult = this.pickBuffer.query(scrX, scrY, this.pickRadius)
+  if(!pickResult) {
+    return null
+  }
+
+  var pickValue = pickResult.id +
+    (pickResult.value[0]<<8)  +
+    (pickResult.value[1]<<16) +
+    (pickResult.value[2]<<24)
+
+  var objects = this.objects
+  for(var i=0; i<objects.length; ++i) {
+    var result = objects[i].pick(scrX, scrY, pickValue)
+    if(result) {
+      return result
+    }
+  }
+
+  return null
+}
+})()
+
+function deepClone(array) {
+  var result = array.slice()
+  for(var i=0; i<result.length; ++i) {
+    result[i] = result[i].slice()
+  }
+  return result
+}
+
+function compareTicks(a, b) {
+  return a.x - b.x
+}
+
+proto.setScreenBox = function(nbox) {
+  var screenBox = this.screenBox
+  var pixelRatio = this.pixelRatio
+
+  screenBox[0] = Math.round(nbox[0] * pixelRatio) | 0
+  screenBox[1] = Math.round(nbox[1] * pixelRatio) | 0
+  screenBox[2] = Math.round(nbox[2] * pixelRatio) | 0
+  screenBox[3] = Math.round(nbox[3] * pixelRatio) | 0
+
+  this.setDirty()
+}
+
+proto.setDataBox = function(nbox) {
+  var dataBox = this.dataBox
+
+  var different =
+    dataBox[0] !== nbox[0] ||
+    dataBox[1] !== nbox[1] ||
+    dataBox[2] !== nbox[2] ||
+    dataBox[3] !== nbox[3]
+
+  if(different) {
+    dataBox[0] = nbox[0]
+    dataBox[1] = nbox[1]
+    dataBox[2] = nbox[2]
+    dataBox[3] = nbox[3]
+
+    this.setDirty()
+  }
+}
+
+proto.setViewBox = function(nbox) {
+  var pixelRatio = this.pixelRatio
+  var viewBox = this.viewBox
+
+  viewBox[0] = Math.round(nbox[0] * pixelRatio)|0
+  viewBox[1] = Math.round(nbox[1] * pixelRatio)|0
+  viewBox[2] = Math.round(nbox[2] * pixelRatio)|0
+  viewBox[3] = Math.round(nbox[3] * pixelRatio)|0
+
+  var pickPixelRatio = this.pickPixelRatio
+  this.pickBuffer.shape = [
+    Math.round((nbox[2] - nbox[0]) * pickPixelRatio)|0,
+    Math.round((nbox[3] - nbox[1]) * pickPixelRatio)|0 ]
+
+  this.setDirty()
+}
+
+proto.update = function(options) {
+  options = options || {}
+
+  var gl = this.gl
+
+  this.pixelRatio      = options.pixelRatio || 1
+
+  var pixelRatio       = this.pixelRatio
+  this.pickPixelRatio  = Math.max(pixelRatio, 1)
+
+  this.setScreenBox(options.screenBox ||
+    [0, 0, gl.drawingBufferWidth/pixelRatio, gl.drawingBufferHeight/pixelRatio])
+
+  var screenBox = this.screenBox
+  this.setViewBox(options.viewBox ||
+    [0.125*(this.screenBox[2]-this.screenBox[0])/pixelRatio,
+     0.125*(this.screenBox[3]-this.screenBox[1])/pixelRatio,
+     0.875*(this.screenBox[2]-this.screenBox[0])/pixelRatio,
+     0.875*(this.screenBox[3]-this.screenBox[1])/pixelRatio])
+
+  var viewBox = this.viewBox
+  var aspectRatio = (viewBox[2] - viewBox[0]) / (viewBox[3] - viewBox[1])
+  this.setDataBox(options.dataBox || [-10, -10/aspectRatio, 10, 10/aspectRatio])
+
+  this.borderColor     = (options.borderColor     || [0,0,0,0]).slice()
+  this.backgroundColor = (options.backgroundColor || [0,0,0,0]).slice()
+
+  this.gridLineEnable  = (options.gridLineEnable || [true,true]).slice()
+  this.gridLineWidth   = (options.gridLineWidth || [1,1]).slice()
+  this.gridLineColor   = deepClone(options.gridLineColor ||
+    [[0.5,0.5,0.5,1],[0.5,0.5,0.5,1]])
+
+  this.zeroLineEnable   = (options.zeroLineEnable || [true, true]).slice()
+  this.zeroLineWidth    = (options.zeroLineWidth || [4, 4]).slice()
+  this.zeroLineColor    = deepClone(options.zeroLineColor ||
+    [[0, 0, 0, 1],[0, 0, 0, 1]])
+
+  this.tickMarkLength   = (options.tickMarkLength || [0,0,0,0]).slice()
+  this.tickMarkWidth    = (options.tickMarkWidth || [0,0,0,0]).slice()
+  this.tickMarkColor    = deepClone(options.tickMarkColor ||
+    [[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]])
+
+  this.titleCenter      = (options.titleCenter || [
+    0.5*(viewBox[0]+viewBox[2])/pixelRatio,(viewBox[3]+120)/pixelRatio]).slice()
+  this.titleEnable      = !('titleEnable' in options) || !!options.titleEnable
+  this.titleAngle       = options.titleAngle || 0
+  this.titleColor       = (options.titleColor || [0,0,0,1]).slice()
+
+  this.labelPad         = (options.labelPad || [15,15,15,15]).slice()
+  this.labelAngle       = (options.labelAngle ||
+    [0,Math.PI/2,0,3.0*Math.PI/2]).slice()
+  this.labelEnable      = (options.labelEnable || [true,true,true,true]).slice()
+  this.labelColor       = deepClone(options.labelColor ||
+    [[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]])
+
+  this.tickPad         = (options.tickPad || [15,15,15,15]).slice()
+  this.tickAngle       = (options.tickAngle || [0,0,0,0]).slice()
+  this.tickEnable      = (options.tickEnable || [true,true,true,true]).slice()
+  this.tickColor       = deepClone(options.tickColor ||
+    [[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]])
+
+  this.borderLineEnable = (options.borderLineEnable ||
+                            [true,true,true,true]).slice()
+  this.borderLineWidth  = (options.borderLineWidth || [2,2,2,2]).slice()
+  this.borderLineColor  = deepClone(options.borderLineColor ||
+                          [[0,0,0,1],
+                           [0,0,0,1],
+                           [0,0,0,1],
+                           [0,0,0,1]])
+
+  var ticks = options.ticks || [ [], [] ]
+
+  //Compute bounds on ticks
+  var bounds = this._tickBounds
+  bounds[0] = bounds[1] =  Infinity
+  bounds[2] = bounds[3] = -Infinity
+  for(var i=0; i<2; ++i) {
+    var axisTicks = ticks[i].slice(0)
+    if(axisTicks.length === 0) {
+      continue
+    }
+    axisTicks.sort(compareTicks)
+    bounds[i]   = Math.min(bounds[i], axisTicks[0].x)
+    bounds[i+2] = Math.max(bounds[i+2], axisTicks[axisTicks.length-1].x)
+  }
+
+  //Update grid
+  this.grid.update({
+    bounds: bounds,
+    ticks:  ticks
+  })
+
+  //Update text
+  this.text.update({
+    bounds:     bounds,
+    ticks:      ticks,
+    labels:     options.labels    || ['x', 'y'],
+    labelSize:  options.labelSize || [12,12],
+    labelFont:  options.labelFont || ['sans-serif', 'sans-serif'],
+    title:      options.title     || '',
+    titleSize:  options.titleSize || 18,
+    titleFont:  options.titleFont || 'sans-serif'
+  })
+
+  this.setDirty()
+}
+
+proto.dispose = function() {
+  this.box.dispose()
+  this.grid.dispose()
+  this.text.dispose()
+  this.line.dispose()
+  for(var i=this.objects.length-1; i>=0; --i) {
+    this.objects[i].dispose()
+  }
+  this.objects.length = 0
+  for(var i=this.overlays.length-1; i>=0; --i) {
+    this.overlays[i].dispose()
+  }
+  this.overlays.length = 0
+
+  this.gl = null
+}
+
+proto.addObject = function(object) {
+  if(this.objects.indexOf(object) < 0) {
+    this.objects.push(object)
+    this.setDirty()
+  }
+}
+
+proto.removeObject = function(object) {
+  var objects = this.objects
+  for(var i=0; i<objects.length; ++i) {
+    if(objects[i] === object) {
+      objects.splice(i,1)
+      this.setDirty()
+      break
+    }
+  }
+}
+
+proto.addOverlay = function(object) {
+  if(this.overlays.indexOf(object) < 0) {
+    this.overlays.push(object)
+    this.setOverlayDirty()
+  }
+}
+
+proto.removeOverlay = function(object) {
+  var objects = this.overlays
+  for(var i=0; i<objects.length; ++i) {
+    if(objects[i] === object) {
+      objects.splice(i,1)
+      this.setOverlayDirty()
+      break
+    }
+  }
+}
+
+function createGLPlot2D(options) {
+  var gl = options.gl
+  var pickBuffer = createPick(gl, [
+    gl.drawingBufferWidth, gl.drawingBufferHeight])
+  var plot = new GLPlot2D(gl, pickBuffer)
+  plot.grid = createGrid(plot)
+  plot.text = createText(plot)
+  plot.line = createLine(plot)
+  plot.box  = createBox(plot)
+  plot.update(options)
+  return plot
+}
+
+},{"./lib/box":116,"./lib/grid":117,"./lib/line":118,"./lib/text":120,"gl-select-static":153}],123:[function(require,module,exports){
+
+var createShader = require('gl-shader')
+
+var vertSrc = "precision mediump float;\n#define GLSLIFY 1\nattribute vec2 position;\nvarying vec2 uv;\nvoid main() {\n  uv = position;\n  gl_Position = vec4(position, 0, 1);\n}"
+var fragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D accumBuffer;\nvarying vec2 uv;\n\nvoid main() {\n  vec4 accum = texture2D(accumBuffer, 0.5 * (uv + 1.0));\n  gl_FragColor = min(vec4(1,1,1,1), accum);\n}"
+
+module.exports = function(gl) {
+  return createShader(gl, vertSrc, fragSrc, null, [ { name: 'position', type: 'vec2'}])
+}
+
+},{"gl-shader":154}],124:[function(require,module,exports){
+'use strict'
+
+module.exports = createCamera
+
+var now         = require('right-now')
+var createView  = require('3d-view')
+var mouseChange = require('mouse-change')
+var mouseWheel  = require('mouse-wheel')
+
+function createCamera(element, options) {
+  element = element || document.body
+  options = options || {}
+
+  var limits  = [ 0.01, Infinity ]
+  if('distanceLimits' in options) {
+    limits[0] = options.distanceLimits[0]
+    limits[1] = options.distanceLimits[1]
+  }
+  if('zoomMin' in options) {
+    limits[0] = options.zoomMin
+  }
+  if('zoomMax' in options) {
+    limits[1] = options.zoomMax
+  }
+
+  var view = createView({
+    center: options.center || [0,0,0],
+    up:     options.up     || [0,1,0],
+    eye:    options.eye    || [0,0,10],
+    mode:   options.mode   || 'orbit',
+    distanceLimits: limits
+  })
+
+  var pmatrix = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
+  var distance = 0.0
+  var width   = element.clientWidth
+  var height  = element.clientHeight
+
+  var camera = {
+    view:               view,
+    element:            element,
+    delay:              options.delay          || 16,
+    rotateSpeed:        options.rotateSpeed    || 1,
+    zoomSpeed:          options.zoomSpeed      || 1,
+    translateSpeed:     options.translateSpeed || 1,
+    flipX:              !!options.flipX,
+    flipY:              !!options.flipY,
+    modes:              view.modes,
+    tick: function() {
+      var t = now()
+      var delay = this.delay
+      view.idle(t-delay)
+      view.flush(t-(100+delay*2))
+      var ctime = t - 2 * delay
+      view.recalcMatrix(ctime)
+      var allEqual = true
+      var matrix = view.computedMatrix
+      for(var i=0; i<16; ++i) {
+        allEqual = allEqual && (pmatrix[i] === matrix[i])
+        pmatrix[i] = matrix[i]
+      }
+      var sizeChanged = 
+          element.clientWidth === width && 
+          element.clientHeight === height
+      width  = element.clientWidth
+      height = element.clientHeight
+      if(allEqual) {
+        return !sizeChanged
+      }
+      distance = Math.exp(view.computedRadius[0])
+      return true
+    },
+    lookAt: function(center, eye, up) {
+      view.lookAt(view.lastT(), center, eye, up)
+    },
+    rotate: function(pitch, yaw, roll) {
+      view.rotate(view.lastT(), pitch, yaw, roll)
+    },
+    pan: function(dx, dy, dz) {
+      view.pan(view.lastT(), dx, dy, dz)
+    },
+    translate: function(dx, dy, dz) {
+      view.translate(view.lastT(), dx, dy, dz)
+    }
+  }
+
+  Object.defineProperties(camera, {
+    matrix: {
+      get: function() {
+        return view.computedMatrix
+      },
+      set: function(mat) {
+        view.setMatrix(view.lastT(), mat)
+        return view.computedMatrix
+      },
+      enumerable: true
+    },
+    mode: {
+      get: function() {
+        return view.getMode()
+      },
+      set: function(mode) {
+        view.setMode(mode)
+        return view.getMode()
+      },
+      enumerable: true
+    },
+    center: {
+      get: function() {
+        return view.computedCenter
+      },
+      set: function(ncenter) {
+        view.lookAt(view.lastT(), ncenter)
+        return view.computedCenter
+      },
+      enumerable: true
+    },
+    eye: {
+      get: function() {
+        return view.computedEye
+      },
+      set: function(neye) {
+        view.lookAt(view.lastT(), null, neye)
+        return view.computedEye
+      },
+      enumerable: true
+    },
+    up: {
+      get: function() {
+        return view.computedUp
+      },
+      set: function(nup) {
+        view.lookAt(view.lastT(), null, null, nup)
+        return view.computedUp
+      },
+      enumerable: true
+    },
+    distance: {
+      get: function() {
+        return distance
+      },
+      set: function(d) {
+        view.setDistance(view.lastT(), d)
+        return d
+      },
+      enumerable: true
+    },
+    distanceLimits: {
+      get: function() {
+        return view.getDistanceLimits(limits)
+      },
+      set: function(v) {
+        view.setDistanceLimits(v)
+        return v
+      },
+      enumerable: true
+    }
+  })
+  
+  element.addEventListener('contextmenu', function(ev) {
+    ev.preventDefault()
+    return false
+  })
+
+  var lastX = 0, lastY = 0
+  mouseChange(element, function(buttons, x, y, mods) {
+    var scale = 1.0 / element.clientHeight
+    var dx    = scale * (x - lastX)
+    var dy    = scale * (y - lastY)
+
+    var flipX = camera.flipX ? 1 : -1
+    var flipY = camera.flipY ? 1 : -1
+
+    var drot  = Math.PI * camera.rotateSpeed
+
+    var t = now()
+
+    if(buttons & 1) {
+      if(mods.shift) {
+        view.rotate(t, 0, 0, -dx * drot)
+      } else {
+        view.rotate(t, flipX * drot * dx, -flipY * drot * dy, 0)
+      }
+    } else if(buttons & 2) {
+      view.pan(t, -camera.translateSpeed * dx * distance, camera.translateSpeed * dy * distance, 0)
+    } else if(buttons & 4) {
+      var kzoom = camera.zoomSpeed * dy / window.innerHeight * (t - view.lastT()) * 50.0
+      view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1))
+    }
+
+    lastX = x
+    lastY = y
+  })
+
+  mouseWheel(element, function(dx, dy, dz) {
+    var flipX = camera.flipX ? 1 : -1
+    var flipY = camera.flipY ? 1 : -1
+    var t = now()
+    if(Math.abs(dx) > Math.abs(dy)) {
+      view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth)
+    } else {
+      var kzoom = camera.zoomSpeed * flipY * dy / window.innerHeight * (t - view.lastT()) / 100.0
+      view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1))
+    }
+  }, true)
+
+  return camera
+}
+},{"3d-view":38,"mouse-change":196,"mouse-wheel":200,"right-now":210}],125:[function(require,module,exports){
+// Copyright (C) 2011 Google Inc.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+/**
+ * @fileoverview Install a leaky WeakMap emulation on platforms that
+ * don't provide a built-in one.
+ *
+ * <p>Assumes that an ES5 platform where, if {@code WeakMap} is
+ * already present, then it conforms to the anticipated ES6
+ * specification. To run this file on an ES5 or almost ES5
+ * implementation where the {@code WeakMap} specification does not
+ * quite conform, run <code>repairES5.js</code> first.
+ *
+ * <p>Even though WeakMapModule is not global, the linter thinks it
+ * is, which is why it is in the overrides list below.
+ *
+ * <p>NOTE: Before using this WeakMap emulation in a non-SES
+ * environment, see the note below about hiddenRecord.
+ *
+ * @author Mark S. Miller
+ * @requires crypto, ArrayBuffer, Uint8Array, navigator, console
+ * @overrides WeakMap, ses, Proxy
+ * @overrides WeakMapModule
+ */
+
+/**
+ * This {@code WeakMap} emulation is observably equivalent to the
+ * ES-Harmony WeakMap, but with leakier garbage collection properties.
+ *
+ * <p>As with true WeakMaps, in this emulation, a key does not
+ * retain maps indexed by that key and (crucially) a map does not
+ * retain the keys it indexes. A map by itself also does not retain
+ * the values associated with that map.
+ *
+ * <p>However, the values associated with a key in some map are
+ * retained so long as that key is retained and those associations are
+ * not overridden. For example, when used to support membranes, all
+ * values exported from a given membrane will live for the lifetime
+ * they would have had in the absence of an interposed membrane. Even
+ * when the membrane is revoked, all objects that would have been
+ * reachable in the absence of revocation will still be reachable, as
+ * far as the GC can tell, even though they will no longer be relevant
+ * to ongoing computation.
+ *
+ * <p>The API implemented here is approximately the API as implemented
+ * in FF6.0a1 and agreed to by MarkM, Andreas Gal, and Dave Herman,
+ * rather than the offially approved proposal page. TODO(erights):
+ * upgrade the ecmascript WeakMap proposal page to explain this API
+ * change and present to EcmaScript committee for their approval.
+ *
+ * <p>The first difference between the emulation here and that in
+ * FF6.0a1 is the presence of non enumerable {@code get___, has___,
+ * set___, and delete___} methods on WeakMap instances to represent
+ * what would be the hidden internal properties of a primitive
+ * implementation. Whereas the FF6.0a1 WeakMap.prototype methods
+ * require their {@code this} to be a genuine WeakMap instance (i.e.,
+ * an object of {@code [[Class]]} "WeakMap}), since there is nothing
+ * unforgeable about the pseudo-internal method names used here,
+ * nothing prevents these emulated prototype methods from being
+ * applied to non-WeakMaps with pseudo-internal methods of the same
+ * names.
+ *
+ * <p>Another difference is that our emulated {@code
+ * WeakMap.prototype} is not itself a WeakMap. A problem with the
+ * current FF6.0a1 API is that WeakMap.prototype is itself a WeakMap
+ * providing ambient mutability and an ambient communications
+ * channel. Thus, if a WeakMap is already present and has this
+ * problem, repairES5.js wraps it in a safe wrappper in order to
+ * prevent access to this channel. (See
+ * PATCH_MUTABLE_FROZEN_WEAKMAP_PROTO in repairES5.js).
+ */
+
+/**
+ * If this is a full <a href=
+ * "http://code.google.com/p/es-lab/wiki/SecureableES5"
+ * >secureable ES5</a> platform and the ES-Harmony {@code WeakMap} is
+ * absent, install an approximate emulation.
+ *
+ * <p>If WeakMap is present but cannot store some objects, use our approximate
+ * emulation as a wrapper.
+ *
+ * <p>If this is almost a secureable ES5 platform, then WeakMap.js
+ * should be run after repairES5.js.
+ *
+ * <p>See {@code WeakMap} for documentation of the garbage collection
+ * properties of this WeakMap emulation.
+ */
+(function WeakMapModule() {
+  "use strict";
+
+  if (typeof ses !== 'undefined' && ses.ok && !ses.ok()) {
+    // already too broken, so give up
+    return;
+  }
+
+  /**
+   * In some cases (current Firefox), we must make a choice betweeen a
+   * WeakMap which is capable of using all varieties of host objects as
+   * keys and one which is capable of safely using proxies as keys. See
+   * comments below about HostWeakMap and DoubleWeakMap for details.
+   *
+   * This function (which is a global, not exposed to guests) marks a
+   * WeakMap as permitted to do what is necessary to index all host
+   * objects, at the cost of making it unsafe for proxies.
+   *
+   * Do not apply this function to anything which is not a genuine
+   * fresh WeakMap.
+   */
+  function weakMapPermitHostObjects(map) {
+    // identity of function used as a secret -- good enough and cheap
+    if (map.permitHostObjects___) {
+      map.permitHostObjects___(weakMapPermitHostObjects);
+    }
+  }
+  if (typeof ses !== 'undefined') {
+    ses.weakMapPermitHostObjects = weakMapPermitHostObjects;
+  }
+
+  // IE 11 has no Proxy but has a broken WeakMap such that we need to patch
+  // it using DoubleWeakMap; this flag tells DoubleWeakMap so.
+  var doubleWeakMapCheckSilentFailure = false;
+
+  // Check if there is already a good-enough WeakMap implementation, and if so
+  // exit without replacing it.
+  if (typeof WeakMap === 'function') {
+    var HostWeakMap = WeakMap;
+    // There is a WeakMap -- is it good enough?
+    if (typeof navigator !== 'undefined' &&
+        /Firefox/.test(navigator.userAgent)) {
+      // We're now *assuming not*, because as of this writing (2013-05-06)
+      // Firefox's WeakMaps have a miscellany of objects they won't accept, and
+      // we don't want to make an exhaustive list, and testing for just one
+      // will be a problem if that one is fixed alone (as they did for Event).
+
+      // If there is a platform that we *can* reliably test on, here's how to
+      // do it:
+      //  var problematic = ... ;
+      //  var testHostMap = new HostWeakMap();
+      //  try {
+      //    testHostMap.set(problematic, 1);  // Firefox 20 will throw here
+      //    if (testHostMap.get(problematic) === 1) {
+      //      return;
+      //    }
+      //  } catch (e) {}
+
+    } else {
+      // IE 11 bug: WeakMaps silently fail to store frozen objects.
+      var testMap = new HostWeakMap();
+      var testObject = Object.freeze({});
+      testMap.set(testObject, 1);
+      if (testMap.get(testObject) !== 1) {
+        doubleWeakMapCheckSilentFailure = true;
+        // Fall through to installing our WeakMap.
+      } else {
+        module.exports = WeakMap;
+        return;
+      }
+    }
+  }
+
+  var hop = Object.prototype.hasOwnProperty;
+  var gopn = Object.getOwnPropertyNames;
+  var defProp = Object.defineProperty;
+  var isExtensible = Object.isExtensible;
+
+  /**
+   * Security depends on HIDDEN_NAME being both <i>unguessable</i> and
+   * <i>undiscoverable</i> by untrusted code.
+   *
+   * <p>Given the known weaknesses of Math.random() on existing
+   * browsers, it does not generate unguessability we can be confident
+   * of.
+   *
+   * <p>It is the monkey patching logic in this file that is intended
+   * to ensure undiscoverability. The basic idea is that there are
+   * three fundamental means of discovering properties of an object:
+   * The for/in loop, Object.keys(), and Object.getOwnPropertyNames(),
+   * as well as some proposed ES6 extensions that appear on our
+   * whitelist. The first two only discover enumerable properties, and
+   * we only use HIDDEN_NAME to name a non-enumerable property, so the
+   * only remaining threat should be getOwnPropertyNames and some
+   * proposed ES6 extensions that appear on our whitelist. We monkey
+   * patch them to remove HIDDEN_NAME from the list of properties they
+   * returns.
+   *
+   * <p>TODO(erights): On a platform with built-in Proxies, proxies
+   * could be used to trap and thereby discover the HIDDEN_NAME, so we
+   * need to monkey patch Proxy.create, Proxy.createFunction, etc, in
+   * order to wrap the provided handler with the real handler which
+   * filters out all traps using HIDDEN_NAME.
+   *
+   * <p>TODO(erights): Revisit Mike Stay's suggestion that we use an
+   * encapsulated function at a not-necessarily-secret name, which
+   * uses the Stiegler shared-state rights amplification pattern to
+   * reveal the associated value only to the WeakMap in which this key
+   * is associated with that value. Since only the key retains the
+   * function, the function can also remember the key without causing
+   * leakage of the key, so this doesn't violate our general gc
+   * goals. In addition, because the name need not be a guarded
+   * secret, we could efficiently handle cross-frame frozen keys.
+   */
+  var HIDDEN_NAME_PREFIX = 'weakmap:';
+  var HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'ident:' + Math.random() + '___';
+
+  if (typeof crypto !== 'undefined' &&
+      typeof crypto.getRandomValues === 'function' &&
+      typeof ArrayBuffer === 'function' &&
+      typeof Uint8Array === 'function') {
+    var ab = new ArrayBuffer(25);
+    var u8s = new Uint8Array(ab);
+    crypto.getRandomValues(u8s);
+    HIDDEN_NAME = HIDDEN_NAME_PREFIX + 'rand:' +
+      Array.prototype.map.call(u8s, function(u8) {
+        return (u8 % 36).toString(36);
+      }).join('') + '___';
+  }
+
+  function isNotHiddenName(name) {
+    return !(
+        name.substr(0, HIDDEN_NAME_PREFIX.length) == HIDDEN_NAME_PREFIX &&
+        name.substr(name.length - 3) === '___');
+  }
+
+  /**
+   * Monkey patch getOwnPropertyNames to avoid revealing the
+   * HIDDEN_NAME.
+   *
+   * <p>The ES5.1 spec requires each name to appear only once, but as
+   * of this writing, this requirement is controversial for ES6, so we
+   * made this code robust against this case. If the resulting extra
+   * search turns out to be expensive, we can probably relax this once
+   * ES6 is adequately supported on all major browsers, iff no browser
+   * versions we support at that time have relaxed this constraint
+   * without providing built-in ES6 WeakMaps.
+   */
+  defProp(Object, 'getOwnPropertyNames', {
+    value: function fakeGetOwnPropertyNames(obj) {
+      return gopn(obj).filter(isNotHiddenName);
+    }
+  });
+
+  /**
+   * getPropertyNames is not in ES5 but it is proposed for ES6 and
+   * does appear in our whitelist, so we need to clean it too.
+   */
+  if ('getPropertyNames' in Object) {
+    var originalGetPropertyNames = Object.getPropertyNames;
+    defProp(Object, 'getPropertyNames', {
+      value: function fakeGetPropertyNames(obj) {
+        return originalGetPropertyNames(obj).filter(isNotHiddenName);
+      }
+    });
+  }
+
+  /**
+   * <p>To treat objects as identity-keys with reasonable efficiency
+   * on ES5 by itself (i.e., without any object-keyed collections), we
+   * need to add a hidden property to such key objects when we
+   * can. This raises several issues:
+   * <ul>
+   * <li>Arranging to add this property to objects before we lose the
+   *     chance, and
+   * <li>Hiding the existence of this new property from most
+   *     JavaScript code.
+   * <li>Preventing <i>certification theft</i>, where one object is
+   *     created falsely claiming to be the key of an association
+   *     actually keyed by another object.
+   * <li>Preventing <i>value theft</i>, where untrusted code with
+   *     access to a key object but not a weak map nevertheless
+   *     obtains access to the value associated with that key in that
+   *     weak map.
+   * </ul>
+   * We do so by
+   * <ul>
+   * <li>Making the name of the hidden property unguessable, so "[]"
+   *     indexing, which we cannot intercept, cannot be used to access
+   *     a property without knowing the name.
+   * <li>Making the hidden property non-enumerable, so we need not
+   *     worry about for-in loops or {@code Object.keys},
+   * <li>monkey patching those reflective methods that would
+   *     prevent extensions, to add this hidden property first,
+   * <li>monkey patching those methods that would reveal this
+   *     hidden property.
+   * </ul>
+   * Unfortunately, because of same-origin iframes, we cannot reliably
+   * add this hidden property before an object becomes
+   * non-extensible. Instead, if we encounter a non-extensible object
+   * without a hidden record that we can detect (whether or not it has
+   * a hidden record stored under a name secret to us), then we just
+   * use the key object itself to represent its identity in a brute
+   * force leaky map stored in the weak map, losing all the advantages
+   * of weakness for these.
+   */
+  function getHiddenRecord(key) {
+    if (key !== Object(key)) {
+      throw new TypeError('Not an object: ' + key);
+    }
+    var hiddenRecord = key[HIDDEN_NAME];
+    if (hiddenRecord && hiddenRecord.key === key) { return hiddenRecord; }
+    if (!isExtensible(key)) {
+      // Weak map must brute force, as explained in doc-comment above.
+      return void 0;
+    }
+
+    // The hiddenRecord and the key point directly at each other, via
+    // the "key" and HIDDEN_NAME properties respectively. The key
+    // field is for quickly verifying that this hidden record is an
+    // own property, not a hidden record from up the prototype chain.
+    //
+    // NOTE: Because this WeakMap emulation is meant only for systems like
+    // SES where Object.prototype is frozen without any numeric
+    // properties, it is ok to use an object literal for the hiddenRecord.
+    // This has two advantages:
+    // * It is much faster in a performance critical place
+    // * It avoids relying on Object.create(null), which had been
+    //   problematic on Chrome 28.0.1480.0. See
+    //   https://code.google.com/p/google-caja/issues/detail?id=1687
+    hiddenRecord = { key: key };
+
+    // When using this WeakMap emulation on platforms where
+    // Object.prototype might not be frozen and Object.create(null) is
+    // reliable, use the following two commented out lines instead.
+    // hiddenRecord = Object.create(null);
+    // hiddenRecord.key = key;
+
+    // Please contact us if you need this to work on platforms where
+    // Object.prototype might not be frozen and
+    // Object.create(null) might not be reliable.
+
+    try {
+      defProp(key, HIDDEN_NAME, {
+        value: hiddenRecord,
+        writable: false,
+        enumerable: false,
+        configurable: false
+      });
+      return hiddenRecord;
+    } catch (error) {
+      // Under some circumstances, isExtensible seems to misreport whether
+      // the HIDDEN_NAME can be defined.
+      // The circumstances have not been isolated, but at least affect
+      // Node.js v0.10.26 on TravisCI / Linux, but not the same version of
+      // Node.js on OS X.
+      return void 0;
+    }
+  }
+
+  /**
+   * Monkey patch operations that would make their argument
+   * non-extensible.
+   *
+   * <p>The monkey patched versions throw a TypeError if their
+   * argument is not an object, so it should only be done to functions
+   * that should throw a TypeError anyway if their argument is not an
+   * object.
+   */
+  (function(){
+    var oldFreeze = Object.freeze;
+    defProp(Object, 'freeze', {
+      value: function identifyingFreeze(obj) {
+        getHiddenRecord(obj);
+        return oldFreeze(obj);
+      }
+    });
+    var oldSeal = Object.seal;
+    defProp(Object, 'seal', {
+      value: function identifyingSeal(obj) {
+        getHiddenRecord(obj);
+        return oldSeal(obj);
+      }
+    });
+    var oldPreventExtensions = Object.preventExtensions;
+    defProp(Object, 'preventExtensions', {
+      value: function identifyingPreventExtensions(obj) {
+        getHiddenRecord(obj);
+        return oldPreventExtensions(obj);
+      }
+    });
+  })();
+
+  function constFunc(func) {
+    func.prototype = null;
+    return Object.freeze(func);
+  }
+
+  var calledAsFunctionWarningDone = false;
+  function calledAsFunctionWarning() {
+    // Future ES6 WeakMap is currently (2013-09-10) expected to reject WeakMap()
+    // but we used to permit it and do it ourselves, so warn only.
+    if (!calledAsFunctionWarningDone && typeof console !== 'undefined') {
+      calledAsFunctionWarningDone = true;
+      console.warn('WeakMap should be invoked as new WeakMap(), not ' +
+          'WeakMap(). This will be an error in the future.');
+    }
+  }
+
+  var nextId = 0;
+
+  var OurWeakMap = function() {
+    if (!(this instanceof OurWeakMap)) {  // approximate test for new ...()
+      calledAsFunctionWarning();
+    }
+
+    // We are currently (12/25/2012) never encountering any prematurely
+    // non-extensible keys.
+    var keys = []; // brute force for prematurely non-extensible keys.
+    var values = []; // brute force for corresponding values.
+    var id = nextId++;
+
+    function get___(key, opt_default) {
+      var index;
+      var hiddenRecord = getHiddenRecord(key);
+      if (hiddenRecord) {
+        return id in hiddenRecord ? hiddenRecord[id] : opt_default;
+      } else {
+        index = keys.indexOf(key);
+        return index >= 0 ? values[index] : opt_default;
+      }
+    }
+
+    function has___(key) {
+      var hiddenRecord = getHiddenRecord(key);
+      if (hiddenRecord) {
+        return id in hiddenRecord;
+      } else {
+        return keys.indexOf(key) >= 0;
+      }
+    }
+
+    function set___(key, value) {
+      var index;
+      var hiddenRecord = getHiddenRecord(key);
+      if (hiddenRecord) {
+        hiddenRecord[id] = value;
+      } else {
+        index = keys.indexOf(key);
+        if (index >= 0) {
+          values[index] = value;
+        } else {
+          // Since some browsers preemptively terminate slow turns but
+          // then continue computing with presumably corrupted heap
+          // state, we here defensively get keys.length first and then
+          // use it to update both the values and keys arrays, keeping
+          // them in sync.
+          index = keys.length;
+          values[index] = value;
+          // If we crash here, values will be one longer than keys.
+          keys[index] = key;
+        }
+      }
+      return this;
+    }
+
+    function delete___(key) {
+      var hiddenRecord = getHiddenRecord(key);
+      var index, lastIndex;
+      if (hiddenRecord) {
+        return id in hiddenRecord && delete hiddenRecord[id];
+      } else {
+        index = keys.indexOf(key);
+        if (index < 0) {
+          return false;
+        }
+        // Since some browsers preemptively terminate slow turns but
+        // then continue computing with potentially corrupted heap
+        // state, we here defensively get keys.length first and then use
+        // it to update both the keys and the values array, keeping
+        // them in sync. We update the two with an order of assignments,
+        // such that any prefix of these assignments will preserve the
+        // key/value correspondence, either before or after the delete.
+        // Note that this needs to work correctly when index === lastIndex.
+        lastIndex = keys.length - 1;
+        keys[index] = void 0;
+        // If we crash here, there's a void 0 in the keys array, but
+        // no operation will cause a "keys.indexOf(void 0)", since
+        // getHiddenRecord(void 0) will always throw an error first.
+        values[index] = values[lastIndex];
+        // If we crash here, values[index] cannot be found here,
+        // because keys[index] is void 0.
+        keys[index] = keys[lastIndex];
+        // If index === lastIndex and we crash here, then keys[index]
+        // is still void 0, since the aliasing killed the previous key.
+        keys.length = lastIndex;
+        // If we crash here, keys will be one shorter than values.
+        values.length = lastIndex;
+        return true;
+      }
+    }
+
+    return Object.create(OurWeakMap.prototype, {
+      get___:    { value: constFunc(get___) },
+      has___:    { value: constFunc(has___) },
+      set___:    { value: constFunc(set___) },
+      delete___: { value: constFunc(delete___) }
+    });
+  };
+
+  OurWeakMap.prototype = Object.create(Object.prototype, {
+    get: {
+      /**
+       * Return the value most recently associated with key, or
+       * opt_default if none.
+       */
+      value: function get(key, opt_default) {
+        return this.get___(key, opt_default);
+      },
+      writable: true,
+      configurable: true
+    },
+
+    has: {
+      /**
+       * Is there a value associated with key in this WeakMap?
+       */
+      value: function has(key) {
+        return this.has___(key);
+      },
+      writable: true,
+      configurable: true
+    },
+
+    set: {
+      /**
+       * Associate value with key in this WeakMap, overwriting any
+       * previous association if present.
+       */
+      value: function set(key, value) {
+        return this.set___(key, value);
+      },
+      writable: true,
+      configurable: true
+    },
+
+    'delete': {
+      /**
+       * Remove any association for key in this WeakMap, returning
+       * whether there was one.
+       *
+       * <p>Note that the boolean return here does not work like the
+       * {@code delete} operator. The {@code delete} operator returns
+       * whether the deletion succeeds at bringing about a state in
+       * which the deleted property is absent. The {@code delete}
+       * operator therefore returns true if the property was already
+       * absent, whereas this {@code delete} method returns false if
+       * the association was already absent.
+       */
+      value: function remove(key) {
+        return this.delete___(key);
+      },
+      writable: true,
+      configurable: true
+    }
+  });
+
+  if (typeof HostWeakMap === 'function') {
+    (function() {
+      // If we got here, then the platform has a WeakMap but we are concerned
+      // that it may refuse to store some key types. Therefore, make a map
+      // implementation which makes use of both as possible.
+
+      // In this mode we are always using double maps, so we are not proxy-safe.
+      // This combination does not occur in any known browser, but we had best
+      // be safe.
+      if (doubleWeakMapCheckSilentFailure && typeof Proxy !== 'undefined') {
+        Proxy = undefined;
+      }
+
+      function DoubleWeakMap() {
+        if (!(this instanceof OurWeakMap)) {  // approximate test for new ...()
+          calledAsFunctionWarning();
+        }
+
+        // Preferable, truly weak map.
+        var hmap = new HostWeakMap();
+
+        // Our hidden-property-based pseudo-weak-map. Lazily initialized in the
+        // 'set' implementation; thus we can avoid performing extra lookups if
+        // we know all entries actually stored are entered in 'hmap'.
+        var omap = undefined;
+
+        // Hidden-property maps are not compatible with proxies because proxies
+        // can observe the hidden name and either accidentally expose it or fail
+        // to allow the hidden property to be set. Therefore, we do not allow
+        // arbitrary WeakMaps to switch to using hidden properties, but only
+        // those which need the ability, and unprivileged code is not allowed
+        // to set the flag.
+        //
+        // (Except in doubleWeakMapCheckSilentFailure mode in which case we
+        // disable proxies.)
+        var enableSwitching = false;
+
+        function dget(key, opt_default) {
+          if (omap) {
+            return hmap.has(key) ? hmap.get(key)
+                : omap.get___(key, opt_default);
+          } else {
+            return hmap.get(key, opt_default);
+          }
+        }
+
+        function dhas(key) {
+          return hmap.has(key) || (omap ? omap.has___(key) : false);
+        }
+
+        var dset;
+        if (doubleWeakMapCheckSilentFailure) {
+          dset = function(key, value) {
+            hmap.set(key, value);
+            if (!hmap.has(key)) {
+              if (!omap) { omap = new OurWeakMap(); }
+              omap.set(key, value);
+            }
+            return this;
+          };
+        } else {
+          dset = function(key, value) {
+            if (enableSwitching) {
+              try {
+                hmap.set(key, value);
+              } catch (e) {
+                if (!omap) { omap = new OurWeakMap(); }
+                omap.set___(key, value);
+              }
+            } else {
+              hmap.set(key, value);
+            }
+            return this;
+          };
+        }
+
+        function ddelete(key) {
+          var result = !!hmap['delete'](key);
+          if (omap) { return omap.delete___(key) || result; }
+          return result;
+        }
+
+        return Object.create(OurWeakMap.prototype, {
+          get___:    { value: constFunc(dget) },
+          has___:    { value: constFunc(dhas) },
+          set___:    { value: constFunc(dset) },
+          delete___: { value: constFunc(ddelete) },
+          permitHostObjects___: { value: constFunc(function(token) {
+            if (token === weakMapPermitHostObjects) {
+              enableSwitching = true;
+            } else {
+              throw new Error('bogus call to permitHostObjects___');
+            }
+          })}
+        });
+      }
+      DoubleWeakMap.prototype = OurWeakMap.prototype;
+      module.exports = DoubleWeakMap;
+
+      // define .constructor to hide OurWeakMap ctor
+      Object.defineProperty(WeakMap.prototype, 'constructor', {
+        value: WeakMap,
+        enumerable: false,  // as default .constructor is
+        configurable: true,
+        writable: true
+      });
+    })();
+  } else {
+    // There is no host WeakMap, so we must use the emulation.
+
+    // Emulated WeakMaps are incompatible with native proxies (because proxies
+    // can observe the hidden name), so we must disable Proxy usage (in
+    // ArrayLike and Domado, currently).
+    if (typeof Proxy !== 'undefined') {
+      Proxy = undefined;
+    }
+
+    module.exports = OurWeakMap;
+  }
+})();
+
+},{}],126:[function(require,module,exports){
+'use strict'
+
+var weakMap      = typeof WeakMap === 'undefined' ? require('weak-map') : WeakMap
+var createBuffer = require('gl-buffer')
+var createVAO    = require('gl-vao')
+
+var TriangleCache = new weakMap()
+
+function createABigTriangle(gl) {
+
+  var triangleVAO = TriangleCache.get(gl)
+  if(!triangleVAO || !gl.isBuffer(triangleVAO._triangleBuffer.buffer)) {
+    var buf = createBuffer(gl, new Float32Array([-1, -1, -1, 4, 4, -1]))
+    triangleVAO = createVAO(gl, [
+      { buffer: buf,
+        type: gl.FLOAT,
+        size: 2
+      }
+    ])
+    triangleVAO._triangleBuffer = buf
+    TriangleCache.set(gl, triangleVAO)
+  }
+  triangleVAO.bind()
+  gl.drawArrays(gl.TRIANGLES, 0, 3)
+  triangleVAO.unbind()
+}
+
+module.exports = createABigTriangle
+
+},{"gl-buffer":75,"gl-vao":189,"weak-map":125}],127:[function(require,module,exports){
+'use strict'
+
+module.exports = createAxes
+
+var createText        = require('./lib/text.js')
+var createLines       = require('./lib/lines.js')
+var createBackground  = require('./lib/background.js')
+var getCubeProperties = require('./lib/cube.js')
+var Ticks             = require('./lib/ticks.js')
+
+var identity = new Float32Array([
+  1, 0, 0, 0,
+  0, 1, 0, 0,
+  0, 0, 1, 0,
+  0, 0, 0, 1])
+
+function copyVec3(a, b) {
+  a[0] = b[0]
+  a[1] = b[1]
+  a[2] = b[2]
+  return a
+}
+
+function Axes(gl) {
+  this.gl             = gl
+
+  this.pixelRatio     = 1
+
+  this.bounds         = [ [-10, -10, -10],
+                          [ 10,  10,  10] ]
+  this.ticks          = [ [], [], [] ]
+  this.autoTicks      = true
+  this.tickSpacing    = [ 1, 1, 1 ]
+
+  this.tickEnable     = [ true, true, true ]
+  this.tickFont       = [ 'sans-serif', 'sans-serif', 'sans-serif' ]
+  this.tickSize       = [ 12, 12, 12 ]
+  this.tickAngle      = [ 0, 0, 0 ]
+  this.tickColor      = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]
+  this.tickPad        = [ 10, 10, 10 ]
+
+  this.lastCubeProps  = {
+    cubeEdges: [0,0,0],
+    axis:      [0,0,0]
+  }
+
+  this.labels         = [ 'x', 'y', 'z' ]
+  this.labelEnable    = [ true, true, true ]
+  this.labelFont      = 'sans-serif'
+  this.labelSize      = [ 20, 20, 20 ]
+  this.labelAngle     = [ 0, 0, 0 ]
+  this.labelColor     = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]
+  this.labelPad       = [ 10, 10, 10 ]
+
+  this.lineEnable     = [ true, true, true ]
+  this.lineMirror     = [ false, false, false ]
+  this.lineWidth      = [ 1, 1, 1 ]
+  this.lineColor      = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]
+
+  this.lineTickEnable = [ true, true, true ]
+  this.lineTickMirror = [ false, false, false ]
+  this.lineTickLength = [ 0, 0, 0 ]
+  this.lineTickWidth  = [ 1, 1, 1 ]
+  this.lineTickColor  = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]
+
+  this.gridEnable     = [ true, true, true ]
+  this.gridWidth      = [ 1, 1, 1 ]
+  this.gridColor      = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]
+
+  this.zeroEnable     = [ true, true, true ]
+  this.zeroLineColor  = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ]
+  this.zeroLineWidth  = [ 2, 2, 2 ]
+
+  this.backgroundEnable = [ false, false, false ]
+  this.backgroundColor  = [ [0.8, 0.8, 0.8, 0.5],
+                            [0.8, 0.8, 0.8, 0.5],
+                            [0.8, 0.8, 0.8, 0.5] ]
+
+  this._firstInit = true
+  this._text  = null
+  this._lines = null
+  this._background = createBackground(gl)
+}
+
+var proto = Axes.prototype
+
+proto.update = function(options) {
+  options = options || {}
+
+  //Option parsing helper functions
+  function parseOption(nest, cons, name) {
+    if(name in options) {
+      var opt = options[name]
+      var prev = this[name]
+      var next
+      if(nest ? (Array.isArray(opt) && Array.isArray(opt[0])) :
+                 Array.isArray(opt) ) {
+        this[name] = next = [ cons(opt[0]), cons(opt[1]), cons(opt[2]) ]
+      } else {
+        this[name] = next = [ cons(opt), cons(opt), cons(opt) ]
+      }
+      for(var i=0; i<3; ++i) {
+        if(next[i] !== prev[i]) {
+          return true
+        }
+      }
+    }
+    return false
+  }
+
+  var NUMBER  = parseOption.bind(this, false, Number)
+  var BOOLEAN = parseOption.bind(this, false, Boolean)
+  var STRING  = parseOption.bind(this, false, String)
+  var COLOR   = parseOption.bind(this, true, function(v) {
+    if(Array.isArray(v)) {
+      if(v.length === 3) {
+        return [ +v[0], +v[1], +v[2], 1.0 ]
+      } else if(v.length === 4) {
+        return [ +v[0], +v[1], +v[2], +v[3] ]
+      }
+    }
+    return [ 0, 0, 0, 1 ]
+  })
+
+  //Tick marks and bounds
+  var nextTicks
+  var ticksUpdate   = false
+  var boundsChanged = false
+  if('bounds' in options) {
+    var bounds = options.bounds
+i_loop:
+    for(var i=0; i<2; ++i) {
+      for(var j=0; j<3; ++j) {
+        if(bounds[i][j] !== this.bounds[i][j]) {
+          boundsChanged = true
+        }
+        this.bounds[i][j] = bounds[i][j]
+      }
+    }
+  }
+  if('ticks' in options) {
+    nextTicks      = options.ticks
+    ticksUpdate    = true
+    this.autoTicks = false
+    for(var i=0; i<3; ++i) {
+      this.tickSpacing[i] = 0.0
+    }
+  } else if(NUMBER('tickSpacing')) {
+    this.autoTicks  = true
+    boundsChanged   = true
+  }
+
+  if(this._firstInit) {
+    if(!('ticks' in options || 'tickSpacing' in options)) {
+      this.autoTicks = true
+    }
+
+    //Force tick recomputation on first update
+    boundsChanged   = true
+    ticksUpdate     = true
+    this._firstInit = false
+  }
+
+  if(boundsChanged && this.autoTicks) {
+    nextTicks = Ticks.create(this.bounds, this.tickSpacing)
+    ticksUpdate = true
+  }
+
+  //Compare next ticks to previous ticks, only update if needed
+  if(ticksUpdate) {
+    for(var i=0; i<3; ++i) {
+      nextTicks[i].sort(function(a,b) {
+        return a.x-b.x
+      })
+    }
+    if(Ticks.equal(nextTicks, this.ticks)) {
+      ticksUpdate = false
+    } else {
+      this.ticks = nextTicks
+    }
+  }
+
+  //Parse tick properties
+  BOOLEAN('tickEnable')
+  if(STRING('tickFont')) {
+    ticksUpdate = true  //If font changes, must rebuild vbo
+  }
+  NUMBER('tickSize')
+  NUMBER('tickAngle')
+  NUMBER('tickPad')
+  COLOR('tickColor')
+
+  //Axis labels
+  var labelUpdate = STRING('labels')
+  if(STRING('labelFont')) {
+    labelUpdate = true
+  }
+  BOOLEAN('labelEnable')
+  NUMBER('labelSize')
+  NUMBER('labelPad')
+  COLOR('labelColor')
+
+  //Axis lines
+  BOOLEAN('lineEnable')
+  BOOLEAN('lineMirror')
+  NUMBER('lineWidth')
+  COLOR('lineColor')
+
+  //Axis line ticks
+  BOOLEAN('lineTickEnable')
+  BOOLEAN('lineTickMirror')
+  NUMBER('lineTickLength')
+  NUMBER('lineTickWidth')
+  COLOR('lineTickColor')
+
+  //Grid lines
+  BOOLEAN('gridEnable')
+  NUMBER('gridWidth')
+  COLOR('gridColor')
+
+  //Zero line
+  BOOLEAN('zeroEnable')
+  COLOR('zeroLineColor')
+  NUMBER('zeroLineWidth')
+
+  //Background
+  BOOLEAN('backgroundEnable')
+  COLOR('backgroundColor')
+
+  //Update text if necessary
+  if(!this._text) {
+    this._text = createText(
+      this.gl,
+      this.bounds,
+      this.labels,
+      this.labelFont,
+      this.ticks,
+      this.tickFont)
+  } else if(this._text && (labelUpdate || ticksUpdate)) {
+    this._text.update(
+      this.bounds,
+      this.labels,
+      this.labelFont,
+      this.ticks,
+      this.tickFont)
+  }
+
+  //Update lines if necessary
+  if(this._lines && ticksUpdate) {
+    this._lines.dispose()
+    this._lines = null
+  }
+  if(!this._lines) {
+    this._lines = createLines(this.gl, this.bounds, this.ticks)
+  }
+}
+
+function OffsetInfo() {
+  this.primalOffset = [0,0,0]
+  this.primalMinor  = [0,0,0]
+  this.mirrorOffset = [0,0,0]
+  this.mirrorMinor  = [0,0,0]
+}
+
+var LINE_OFFSET = [ new OffsetInfo(), new OffsetInfo(), new OffsetInfo() ]
+
+function computeLineOffset(result, i, bounds, cubeEdges, cubeAxis) {
+  var primalOffset = result.primalOffset
+  var primalMinor  = result.primalMinor
+  var dualOffset   = result.mirrorOffset
+  var dualMinor    = result.mirrorMinor
+  var e = cubeEdges[i]
+
+  //Calculate offsets
+  for(var j=0; j<3; ++j) {
+    if(i === j) {
+      continue
+    }
+    var a = primalOffset,
+        b = dualOffset,
+        c = primalMinor,
+        d = dualMinor
+    if(e & (1<<j)) {
+      a = dualOffset
+      b = primalOffset
+      c = dualMinor
+      d = primalMinor
+    }
+    a[j] = bounds[0][j]
+    b[j] = bounds[1][j]
+    if(cubeAxis[j] > 0) {
+      c[j] = -1
+      d[j] = 0
+    } else {
+      c[j] = 0
+      d[j] = +1
+    }
+  }
+}
+
+var CUBE_ENABLE = [0,0,0]
+var DEFAULT_PARAMS = {
+  model:      identity,
+  view:       identity,
+  projection: identity
+}
+
+proto.isOpaque = function() {
+  return true
+}
+
+proto.isTransparent = function() {
+  return false
+}
+
+proto.drawTransparent = function(params) {}
+
+
+var PRIMAL_MINOR  = [0,0,0]
+var MIRROR_MINOR  = [0,0,0]
+var PRIMAL_OFFSET = [0,0,0]
+
+proto.draw = function(params) {
+  params = params || DEFAULT_PARAMS
+
+  var gl = this.gl
+
+  //Geometry for camera and axes
+  var model       = params.model || identity
+  var view        = params.view || identity
+  var projection  = params.projection || identity
+  var bounds      = this.bounds
+
+  //Unpack axis info
+  var cubeParams  = getCubeProperties(model, view, projection, bounds)
+  var cubeEdges   = cubeParams.cubeEdges
+  var cubeAxis    = cubeParams.axis
+
+  var cx = view[12]
+  var cy = view[13]
+  var cz = view[14]
+  var cw = view[15]
+
+  var pixelScaleF = this.pixelRatio * (projection[3]*cx + projection[7]*cy + projection[11]*cz + projection[15]*cw) / gl.drawingBufferHeight
+
+  for(var i=0; i<3; ++i) {
+    this.lastCubeProps.cubeEdges[i] = cubeEdges[i]
+    this.lastCubeProps.axis[i] = cubeAxis[i]
+  }
+
+  //Compute axis info
+  var lineOffset  = LINE_OFFSET
+  for(var i=0; i<3; ++i) {
+    computeLineOffset(
+      LINE_OFFSET[i],
+      i,
+      this.bounds,
+      cubeEdges,
+      cubeAxis)
+  }
+
+  //Set up state parameters
+  var gl = this.gl
+
+  //Draw background first
+  var cubeEnable = CUBE_ENABLE
+  for(var i=0; i<3; ++i) {
+    if(this.backgroundEnable[i]) {
+      cubeEnable[i] = cubeAxis[i]
+    } else {
+      cubeEnable[i] = 0
+    }
+  }
+
+  this._background.draw(
+    model,
+    view,
+    projection,
+    bounds,
+    cubeEnable,
+    this.backgroundColor)
+
+  //Draw lines
+  this._lines.bind(
+    model,
+    view,
+    projection,
+    this)
+
+  //First draw grid lines and zero lines
+  for(var i=0; i<3; ++i) {
+    var x = [0,0,0]
+    if(cubeAxis[i] > 0) {
+      x[i] = bounds[1][i]
+    } else {
+      x[i] = bounds[0][i]
+    }
+
+    //Draw grid lines
+    for(var j=0; j<2; ++j) {
+      var u = (i + 1 + j) % 3
+      var v = (i + 1 + (j^1)) % 3
+      if(this.gridEnable[u]) {
+        this._lines.drawGrid(u, v, this.bounds, x, this.gridColor[u], this.gridWidth[u]*this.pixelRatio)
+      }
+    }
+
+    //Draw zero lines (need to do this AFTER all grid lines are drawn)
+    for(var j=0; j<2; ++j) {
+      var u = (i + 1 + j) % 3
+      var v = (i + 1 + (j^1)) % 3
+      if(this.zeroEnable[v]) {
+        //Check if zero line in bounds
+        if(bounds[0][v] <= 0 && bounds[1][v] >= 0) {
+          this._lines.drawZero(u, v, this.bounds, x, this.zeroLineColor[v], this.zeroLineWidth[v]*this.pixelRatio)
+        }
+      }
+    }
+  }
+
+  //Then draw axis lines and tick marks
+  for(var i=0; i<3; ++i) {
+
+    //Draw axis lines
+    if(this.lineEnable[i]) {
+      this._lines.drawAxisLine(i, this.bounds, lineOffset[i].primalOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio)
+    }
+    if(this.lineMirror[i]) {
+      this._lines.drawAxisLine(i, this.bounds, lineOffset[i].mirrorOffset, this.lineColor[i], this.lineWidth[i]*this.pixelRatio)
+    }
+
+    //Compute minor axes
+    var primalMinor = copyVec3(PRIMAL_MINOR, lineOffset[i].primalMinor)
+    var mirrorMinor = copyVec3(MIRROR_MINOR, lineOffset[i].mirrorMinor)
+    var tickLength  = this.lineTickLength
+    var op = 0
+    for(var j=0; j<3; ++j) {
+      var scaleFactor = pixelScaleF / model[5*j]
+      primalMinor[j] *= tickLength[j] * scaleFactor
+      mirrorMinor[j] *= tickLength[j] * scaleFactor
+    }
+
+    //Draw axis line ticks
+    if(this.lineTickEnable[i]) {
+      this._lines.drawAxisTicks(i, lineOffset[i].primalOffset, primalMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio)
+    }
+    if(this.lineTickMirror[i]) {
+      this._lines.drawAxisTicks(i, lineOffset[i].mirrorOffset, mirrorMinor, this.lineTickColor[i], this.lineTickWidth[i]*this.pixelRatio)
+    }
+  }
+
+  //Draw text sprites
+  this._text.bind(
+    model,
+    view,
+    projection,
+    this.pixelRatio)
+
+  for(var i=0; i<3; ++i) {
+
+    var minor      = lineOffset[i].primalMinor
+    var offset     = copyVec3(PRIMAL_OFFSET, lineOffset[i].primalOffset)
+
+    for(var j=0; j<3; ++j) {
+      if(this.lineTickEnable[i]) {
+        offset[j] += pixelScaleF * minor[j] * Math.max(this.lineTickLength[j], 0)  / model[5*j]
+      }
+    }
+
+    //Draw tick text
+    if(this.tickEnable[i]) {
+
+      //Add tick padding
+      for(var j=0; j<3; ++j) {
+        offset[j] += pixelScaleF * minor[j] * this.tickPad[j] / model[5*j]
+      }
+
+      //Draw axis
+      this._text.drawTicks(
+        i,
+        this.tickSize[i],
+        this.tickAngle[i],
+        offset,
+        this.tickColor[i])
+    }
+
+    //Draw labels
+    if(this.labelEnable[i]) {
+
+      //Add label padding
+      for(var j=0; j<3; ++j) {
+        offset[j] += pixelScaleF * minor[j] * this.labelPad[j] / model[5*j]
+      }
+      offset[i] += 0.5 * (bounds[0][i] + bounds[1][i])
+
+      //Draw axis
+      this._text.drawLabel(
+        i,
+        this.labelSize[i],
+        this.labelAngle[i],
+        offset,
+        this.labelColor[i])
+    }
+  }
+}
+
+proto.dispose = function() {
+  this._text.dispose()
+  this._lines.dispose()
+  this._background.dispose()
+  this._lines = null
+  this._text = null
+  this._background = null
+  this.gl = null
+}
+
+function createAxes(gl, options) {
+  var axes = new Axes(gl)
+  axes.update(options)
+  return axes
+}
+
+},{"./lib/background.js":128,"./lib/cube.js":129,"./lib/lines.js":130,"./lib/text.js":132,"./lib/ticks.js":133}],128:[function(require,module,exports){
+'use strict'
+
+module.exports = createBackgroundCube
+
+var createBuffer = require('gl-buffer')
+var createVAO    = require('gl-vao')
+var createShader = require('./shaders').bg
+
+function BackgroundCube(gl, buffer, vao, shader) {
+  this.gl = gl
+  this.buffer = buffer
+  this.vao = vao
+  this.shader = shader
+}
+
+var proto = BackgroundCube.prototype
+
+proto.draw = function(model, view, projection, bounds, enable, colors) {
+  var needsBG = false
+  for(var i=0; i<3; ++i) {
+    needsBG = needsBG || enable[i]
+  }
+  if(!needsBG) {
+    return
+  }
+
+  var gl = this.gl
+
+  gl.enable(gl.POLYGON_OFFSET_FILL)
+  gl.polygonOffset(1, 2)
+
+  this.shader.bind()
+  this.shader.uniforms = {
+    model: model,
+    view: view,
+    projection: projection,
+    bounds: bounds,
+    enable: enable,
+    colors: colors
+  }
+  this.vao.bind()
+  this.vao.draw(this.gl.TRIANGLES, 36)
+
+  gl.disable(gl.POLYGON_OFFSET_FILL)
+}
+
+proto.dispose = function() {
+  this.vao.dispose()
+  this.buffer.dispose()
+  this.shader.dispose()
+}
+
+function createBackgroundCube(gl) {
+  //Create cube vertices
+  var vertices = []
+  var indices  = []
+  var ptr = 0
+  for(var d=0; d<3; ++d) {
+    var u = (d+1) % 3
+    var v = (d+2) % 3
+    var x = [0,0,0]
+    var c = [0,0,0]
+    for(var s=-1; s<=1; s+=2) {
+      indices.push(ptr,   ptr+2, ptr+1,
+                   ptr+1, ptr+2, ptr+3)
+      x[d] = s
+      c[d] = s
+      for(var i=-1; i<=1; i+=2) {
+        x[u] = i
+        for(var j=-1; j<=1; j+=2) {
+          x[v] = j
+          vertices.push(x[0], x[1], x[2],
+                        c[0], c[1], c[2])
+          ptr += 1
+        }
+      }
+      //Swap u and v
+      var tt = u
+      u = v
+      v = tt
+    }
+  }
+
+  //Allocate buffer and vertex array
+  var buffer = createBuffer(gl, new Float32Array(vertices))
+  var elements = createBuffer(gl, new Uint16Array(indices), gl.ELEMENT_ARRAY_BUFFER)
+  var vao = createVAO(gl, [
+      {
+        buffer: buffer,
+        type: gl.FLOAT,
+        size: 3,
+        offset: 0,
+        stride: 24
+      },
+      {
+        buffer: buffer,
+        type: gl.FLOAT,
+        size: 3,
+        offset: 12,
+        stride: 24
+      }
+    ], elements)
+
+  //Create shader object
+  var shader = createShader(gl)
+  shader.attributes.position.location = 0
+  shader.attributes.normal.location = 1
+
+  return new BackgroundCube(gl, buffer, vao, shader)
+}
+
+},{"./shaders":131,"gl-buffer":75,"gl-vao":189}],129:[function(require,module,exports){
+"use strict"
+
+module.exports = getCubeEdges
+
+var bits      = require('bit-twiddle')
+var multiply  = require('gl-mat4/multiply')
+var invert    = require('gl-mat4/invert')
+var splitPoly = require('split-polygon')
+var orient    = require('robust-orientation')
+
+var mvp        = new Array(16)
+var imvp       = new Array(16)
+var pCubeVerts = new Array(8)
+var cubeVerts  = new Array(8)
+var x          = new Array(3)
+var zero3      = [0,0,0]
+
+;(function() {
+  for(var i=0; i<8; ++i) {
+    pCubeVerts[i] =[1,1,1,1]
+    cubeVerts[i] = [1,1,1]
+  }
+})()
+
+
+function transformHg(result, x, mat) {
+  for(var i=0; i<4; ++i) {
+    result[i] = mat[12+i]
+    for(var j=0; j<3; ++j) {
+      result[i] += x[j]*mat[4*j+i]
+    }
+  }
+}
+
+var FRUSTUM_PLANES = [
+  [ 0, 0, 1, 0, 0],
+  [ 0, 0,-1, 1, 0],
+  [ 0,-1, 0, 1, 0],
+  [ 0, 1, 0, 1, 0],
+  [-1, 0, 0, 1, 0],
+  [ 1, 0, 0, 1, 0]
+]
+
+function polygonArea(p) {
+  for(var i=0; i<FRUSTUM_PLANES.length; ++i) {
+    p = splitPoly.positive(p, FRUSTUM_PLANES[i])
+    if(p.length < 3) {
+      return 0
+    }
+  }
+
+  var base = p[0]
+  var ax = base[0] / base[3]
+  var ay = base[1] / base[3]
+  var area = 0.0
+  for(var i=1; i+1<p.length; ++i) {
+    var b = p[i]
+    var c = p[i+1]
+
+    var bx = b[0]/b[3]
+    var by = b[1]/b[3]
+    var cx = c[0]/c[3]
+    var cy = c[1]/c[3]
+
+    var ux = bx - ax
+    var uy = by - ay
+
+    var vx = cx - ax
+    var vy = cy - ay
+
+    area += Math.abs(ux * vy - uy * vx)
+  }
+
+  return area
+}
+
+var CUBE_EDGES = [1,1,1]
+var CUBE_AXIS  = [0,0,0]
+var CUBE_RESULT = {
+  cubeEdges: CUBE_EDGES,
+  axis: CUBE_AXIS
+}
+
+function getCubeEdges(model, view, projection, bounds) {
+
+  //Concatenate matrices
+  multiply(mvp, view, model)
+  multiply(mvp, projection, mvp)
+  
+  //First project cube vertices
+  var ptr = 0
+  for(var i=0; i<2; ++i) {
+    x[2] = bounds[i][2]
+    for(var j=0; j<2; ++j) {
+      x[1] = bounds[j][1]
+      for(var k=0; k<2; ++k) {
+        x[0] = bounds[k][0]
+        transformHg(pCubeVerts[ptr], x, mvp)
+        ptr += 1
+      }
+    }
+  }
+
+  //Classify camera against cube faces
+  var closest = -1
+
+  for(var i=0; i<8; ++i) {
+    var w = pCubeVerts[i][3]
+    for(var l=0; l<3; ++l) {
+      cubeVerts[i][l] = pCubeVerts[i][l] / w
+    }
+    if(w < 0) {
+      if(closest < 0) {
+        closest = i
+      } else if(cubeVerts[i][2] < cubeVerts[closest][2]) {
+        closest = i
+      }
+    }    
+  }
+
+  if(closest < 0) {
+    closest = 0
+    for(var d=0; d<3; ++d) {
+      var u = (d+2) % 3
+      var v = (d+1) % 3
+      var o0 = -1
+      var o1 = -1
+      for(var s=0; s<2; ++s) {
+        var f0 = (s<<d)
+        var f1 = f0 + (s << u) + ((1-s) << v)
+        var f2 = f0 + ((1-s) << u) + (s << v)
+        if(orient(cubeVerts[f0], cubeVerts[f1], cubeVerts[f2], zero3) < 0) {
+          continue
+        }
+        if(s) {
+          o0 = 1
+        } else {
+          o1 = 1
+        }
+      }
+      if(o0 < 0 || o1 < 0) {
+        if(o1 > o0) {
+          closest |= 1<<d
+        }
+        continue
+      } 
+      for(var s=0; s<2; ++s) {
+        var f0 = (s<<d)
+        var f1 = f0 + (s << u) + ((1-s) << v)
+        var f2 = f0 + ((1-s) << u) + (s << v)    
+        var o = polygonArea([
+            pCubeVerts[f0], 
+            pCubeVerts[f1], 
+            pCubeVerts[f2], 
+            pCubeVerts[f0+(1<<u)+(1<<v)]])
+        if(s) {
+          o0 = o
+        } else {
+          o1 = o
+        }
+      }
+      if(o1 > o0) {
+        closest |= 1<<d
+        continue
+      }
+    }
+  }
+
+  var farthest = 7^closest
+
+  //Find lowest vertex which is not closest closest
+  var bottom = -1
+  for(var i=0; i<8; ++i) {
+    if(i === closest || i === farthest) {
+      continue
+    }
+    if(bottom < 0) {
+      bottom = i
+    } else if(cubeVerts[bottom][1] > cubeVerts[i][1]) {
+      bottom = i
+    }
+  }
+
+  //Find left/right neighbors of bottom vertex
+  var left = -1
+  for(var i=0; i<3; ++i) {
+    var idx = bottom ^ (1<<i)
+    if(idx === closest || idx === farthest) {
+      continue
+    }
+    if(left < 0) {
+      left = idx
+    }
+    var v = cubeVerts[idx]
+    if(v[0] < cubeVerts[left][0]) {
+      left = idx
+    }
+  }
+  var right = -1
+  for(var i=0; i<3; ++i) {
+    var idx = bottom ^ (1<<i)
+    if(idx === closest || idx === farthest || idx === left) {
+      continue
+    }
+    if(right < 0) {
+      right = idx
+    }
+    var v = cubeVerts[idx]
+    if(v[0] > cubeVerts[right][0]) {
+      right = idx
+    }
+  }
+
+  //Determine edge axis coordinates
+  var cubeEdges = CUBE_EDGES
+  cubeEdges[0] = cubeEdges[1] = cubeEdges[2] = 0
+  cubeEdges[bits.log2(left^bottom)] = bottom&left
+  cubeEdges[bits.log2(bottom^right)] = bottom&right
+  var top = right ^ 7
+  if(top === closest || top === farthest) {
+    top = left ^ 7
+    cubeEdges[bits.log2(right^top)] = top&right
+  } else {
+    cubeEdges[bits.log2(left^top)] = top&left
+  }
+
+  //Determine visible faces
+  var axis = CUBE_AXIS
+  var cutCorner = closest
+  for(var d=0; d<3; ++d) {
+    if(cutCorner & (1<<d)) {
+      axis[d] = -1
+    } else {
+      axis[d] = 1
+    }
+  }
+
+  //Return result
+  return CUBE_RESULT
+}
+},{"bit-twiddle":49,"gl-mat4/invert":94,"gl-mat4/multiply":96,"robust-orientation":214,"split-polygon":135}],130:[function(require,module,exports){
+'use strict'
+
+module.exports    = createLines
+
+var createBuffer  = require('gl-buffer')
+var createVAO     = require('gl-vao')
+var createShader  = require('./shaders').line
+
+var MAJOR_AXIS = [0,0,0]
+var MINOR_AXIS = [0,0,0]
+var SCREEN_AXIS = [0,0,0]
+var OFFSET_VEC = [0,0,0]
+var SHAPE = [1,1]
+
+function zeroVec(a) {
+  a[0] = a[1] = a[2] = 0
+  return a
+}
+
+function copyVec(a,b) {
+  a[0] = b[0]
+  a[1] = b[1]
+  a[2] = b[2]
+  return a
+}
+
+function Lines(gl, vertBuffer, vao, shader, tickCount, tickOffset, gridCount, gridOffset) {
+  this.gl         = gl
+  this.vertBuffer = vertBuffer
+  this.vao        = vao
+  this.shader     = shader
+  this.tickCount  = tickCount
+  this.tickOffset = tickOffset
+  this.gridCount  = gridCount
+  this.gridOffset = gridOffset
+}
+
+var proto = Lines.prototype
+
+proto.bind = function(model, view, projection) {
+  this.shader.bind()
+  this.shader.uniforms.model = model
+  this.shader.uniforms.view = view
+  this.shader.uniforms.projection = projection
+
+  SHAPE[0] = this.gl.drawingBufferWidth
+  SHAPE[1] = this.gl.drawingBufferHeight
+
+  this.shader.uniforms.screenShape = SHAPE
+  this.vao.bind()
+}
+
+proto.drawAxisLine = function(j, bounds, offset, color, lineWidth) {
+  var minorAxis = zeroVec(MINOR_AXIS)
+  this.shader.uniforms.majorAxis = MINOR_AXIS
+
+  minorAxis[j] = bounds[1][j] - bounds[0][j]
+  this.shader.uniforms.minorAxis = minorAxis
+
+  var noffset = copyVec(OFFSET_VEC, offset)
+  noffset[j] += bounds[0][j]
+  this.shader.uniforms.offset = noffset
+
+  this.shader.uniforms.lineWidth = lineWidth
+
+  this.shader.uniforms.color = color
+
+  var screenAxis = zeroVec(SCREEN_AXIS)
+  screenAxis[(j+2)%3] = 1
+  this.shader.uniforms.screenAxis = screenAxis
+  this.vao.draw(this.gl.TRIANGLES, 6)
+
+  var screenAxis = zeroVec(SCREEN_AXIS)
+  screenAxis[(j+1)%3] = 1
+  this.shader.uniforms.screenAxis = screenAxis
+  this.vao.draw(this.gl.TRIANGLES, 6)
+}
+
+proto.drawAxisTicks = function(j, offset, minorAxis, color, lineWidth) {
+  var majorAxis = zeroVec(MAJOR_AXIS)
+  majorAxis[j]  = 1
+  this.shader.uniforms.majorAxis = majorAxis
+  this.shader.uniforms.offset    = offset
+  this.shader.uniforms.minorAxis = minorAxis
+  this.shader.uniforms.color     = color
+  this.shader.uniforms.lineWidth = lineWidth
+
+  var screenAxis = zeroVec(SCREEN_AXIS)
+  screenAxis[j] = 1
+  this.shader.uniforms.screenAxis = screenAxis
+  this.vao.draw(this.gl.TRIANGLES, this.tickCount[j], this.tickOffset[j])
+}
+
+
+proto.drawGrid = function(i, j, bounds, offset, color, lineWidth) {
+  var minorAxis = zeroVec(MINOR_AXIS)
+  minorAxis[j]  = bounds[1][j] - bounds[0][j]
+  this.shader.uniforms.minorAxis = minorAxis
+
+  var noffset = copyVec(OFFSET_VEC, offset)
+  noffset[j] += bounds[0][j]
+  this.shader.uniforms.offset = noffset
+
+  var majorAxis = zeroVec(MAJOR_AXIS)
+  majorAxis[i]  = 1
+  this.shader.uniforms.majorAxis = majorAxis
+
+  var screenAxis = zeroVec(SCREEN_AXIS)
+  screenAxis[i] = 1
+  this.shader.uniforms.screenAxis = screenAxis
+  this.shader.uniforms.lineWidth = lineWidth
+
+  this.shader.uniforms.color = color
+  this.vao.draw(this.gl.TRIANGLES, this.gridCount[i], this.gridOffset[i])
+}
+
+proto.drawZero = function(j, i, bounds, offset, color, lineWidth) {
+  var minorAxis = zeroVec(MINOR_AXIS)
+  this.shader.uniforms.majorAxis = minorAxis
+
+  minorAxis[j] = bounds[1][j] - bounds[0][j]
+  this.shader.uniforms.minorAxis = minorAxis
+
+  var noffset = copyVec(OFFSET_VEC, offset)
+  noffset[j] += bounds[0][j]
+  this.shader.uniforms.offset = noffset
+
+  var screenAxis = zeroVec(SCREEN_AXIS)
+  screenAxis[i] = 1
+  this.shader.uniforms.screenAxis = screenAxis
+  this.shader.uniforms.lineWidth = lineWidth
+
+  this.shader.uniforms.color = color
+  this.vao.draw(this.gl.TRIANGLES, 6)
+}
+
+proto.dispose = function() {
+  this.vao.dispose()
+  this.vertBuffer.dispose()
+  this.shader.dispose()
+}
+
+function createLines(gl, bounds, ticks) {
+  var vertices    = []
+  var tickOffset  = [0,0,0]
+  var tickCount   = [0,0,0]
+
+  //Create grid lines for each axis/direction
+  var gridOffset = [0,0,0]
+  var gridCount  = [0,0,0]
+
+  //Add zero line
+  vertices.push(
+    0,0,1,   0,1,1,   0,0,-1,
+    0,0,-1,  0,1,1,   0,1,-1)
+
+  for(var i=0; i<3; ++i) {
+    //Axis tick marks
+    var start = ((vertices.length / 3)|0)
+    for(var j=0; j<ticks[i].length; ++j) {
+      var x = +ticks[i][j].x
+      vertices.push(
+        x,0,1,   x,1,1,   x,0,-1,
+        x,0,-1,  x,1,1,   x,1,-1)
+    }
+    var end = ((vertices.length / 3)|0)
+    tickOffset[i] = start
+    tickCount[i]  = end - start
+
+    //Grid lines
+    var start = ((vertices.length / 3)|0)
+    for(var k=0; k<ticks[i].length; ++k) {
+      var x = +ticks[i][k].x
+      vertices.push(
+        x,0,1,   x,1,1,   x,0,-1,
+        x,0,-1,  x,1,1,   x,1,-1)
+    }
+    var end = ((vertices.length / 3)|0)
+    gridOffset[i] = start
+    gridCount[i]  = end - start
+  }
+
+  //Create cube VAO
+  var vertBuf = createBuffer(gl, new Float32Array(vertices))
+  var vao = createVAO(gl, [
+    { "buffer": vertBuf,
+      "type": gl.FLOAT,
+      "size": 3,
+      "stride": 0,
+      "offset": 0
+    }
+  ])
+  var shader = createShader(gl)
+  shader.attributes.position.location = 0
+  return new Lines(gl, vertBuf, vao, shader, tickCount, tickOffset, gridCount, gridOffset)
+}
+
+},{"./shaders":131,"gl-buffer":75,"gl-vao":189}],131:[function(require,module,exports){
+'use strict'
+
+
+var createShader = require('gl-shader')
+
+var lineVert = "#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n  vec4 pp = projection * view * model * vec4(p, 1.0);\n  return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n  vec3 major = position.x * majorAxis;\n  vec3 minor = position.y * minorAxis;\n\n  vec3 vPosition = major + minor + offset;\n  vec3 pPosition = project(vPosition);\n  vec3 offset = project(vPosition + screenAxis * position.z);\n\n  vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n  gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n"
+var lineFrag = "precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}"
+exports.line = function(gl) {
+  return createShader(gl, lineVert, lineFrag, null, [
+    {name: 'position', type: 'vec3'}
+  ])
+}
+
+var textVert = "#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() {  \n  //Compute plane offset\n  vec2 planeCoord = position.xy * pixelScale;\n  mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n                                -sin(angle), cos(angle));\n  vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n  //Compute world offset\n  float axisDistance = position.z;\n  vec3 dataPosition = axisDistance * axis + offset;\n  vec4 worldPosition = model * vec4(dataPosition, 1);\n  \n  //Compute clip position\n  vec4 viewPosition = view * worldPosition;\n  vec4 clipPosition = projection * viewPosition;\n  clipPosition /= clipPosition.w;\n\n  //Apply text offset in clip coordinates\n  clipPosition += vec4(viewOffset, 0, 0);\n\n  //Done\n  gl_Position = clipPosition;\n}"
+var textFrag = "precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}"
+exports.text = function(gl) {
+  return createShader(gl, textVert, textFrag, null, [
+    {name: 'position', type: 'vec3'}
+  ])
+}
+
+var bgVert = "#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n  if(dot(normal, enable) > 0.0) {\n    vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n    gl_Position = projection * view * model * vec4(nPosition, 1.0);\n  } else {\n    gl_Position = vec4(0,0,0,0);\n  }\n  colorChannel = abs(normal);\n}"
+var bgFrag = "precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n  gl_FragColor = colorChannel.x * colors[0] + \n                 colorChannel.y * colors[1] +\n                 colorChannel.z * colors[2];\n}"
+exports.bg = function(gl) {
+  return createShader(gl, bgVert, bgFrag, null, [
+    {name: 'position', type: 'vec3'},
+    {name: 'normal', type: 'vec3'}
+  ])
+}
+
+},{"gl-shader":154}],132:[function(require,module,exports){
+(function (process){
+"use strict"
+
+module.exports = createTextSprites
+
+var createBuffer  = require('gl-buffer')
+var createVAO     = require('gl-vao')
+var vectorizeText = require('vectorize-text')
+var createShader  = require('./shaders').text
+
+var globals = window || process.global || {}
+var __TEXT_CACHE  = globals.__TEXT_CACHE || {}
+globals.__TEXT_CACHE = {}
+
+//Vertex buffer format for text is:
+//
+/// [x,y,z] = Spatial coordinate
+//
+
+var VERTEX_SIZE = 3
+var VERTEX_STRIDE = VERTEX_SIZE * 4
+
+function TextSprites(
+  gl,
+  shader,
+  buffer,
+  vao) {
+  this.gl           = gl
+  this.shader       = shader
+  this.buffer       = buffer
+  this.vao          = vao
+  this.tickOffset   =
+  this.tickCount    =
+  this.labelOffset  =
+  this.labelCount   = null
+}
+
+var proto = TextSprites.prototype
+
+//Bind textures for rendering
+var SHAPE = [0,0]
+proto.bind = function(model, view, projection, pixelScale) {
+  this.vao.bind()
+  this.shader.bind()
+  var uniforms = this.shader.uniforms
+  uniforms.model = model
+  uniforms.view = view
+  uniforms.projection = projection
+  uniforms.pixelScale = pixelScale
+  SHAPE[0] = this.gl.drawingBufferWidth
+  SHAPE[1] = this.gl.drawingBufferHeight
+  this.shader.uniforms.resolution = SHAPE
+}
+
+proto.update = function(bounds, labels, labelFont, ticks, tickFont) {
+  var gl = this.gl
+  var data = []
+
+  function addItem(t, text, font, size) {
+    var fontcache = __TEXT_CACHE[font]
+    if(!fontcache) {
+      fontcache = __TEXT_CACHE[font] = {}
+    }
+    var mesh = fontcache[text]
+    if(!mesh) {
+      mesh = fontcache[text] = tryVectorizeText(text, {
+        triangles: true,
+        font: font,
+        textAlign: 'center',
+        textBaseline: 'middle'
+      })
+    }
+    var scale = (size || 12) / 12
+    var positions = mesh.positions
+    var cells = mesh.cells
+    var lo = [ Infinity, Infinity]
+    var hi = [-Infinity,-Infinity]
+    for(var i=0, nc=cells.length; i<nc; ++i) {
+      var c = cells[i]
+      for(var j=2; j>=0; --j) {
+        var p = positions[c[j]]
+        data.push(scale*p[0], -scale*p[1], t)
+      }
+    }
+  }
+
+  //Generate sprites for all 3 axes, store data in texture atlases
+  var tickOffset  = [0,0,0]
+  var tickCount   = [0,0,0]
+  var labelOffset = [0,0,0]
+  var labelCount  = [0,0,0]
+  for(var d=0; d<3; ++d) {
+
+    //Generate label
+    labelOffset[d] = (data.length/VERTEX_SIZE)|0
+    addItem(0.5*(bounds[0][d]+bounds[1][d]), labels[d], labelFont)
+    labelCount[d] = ((data.length/VERTEX_SIZE)|0) - labelOffset[d]
+
+    //Generate sprites for tick marks
+    tickOffset[d] = (data.length/VERTEX_SIZE)|0
+    for(var i=0; i<ticks[d].length; ++i) {
+      if(!ticks[d][i].text) {
+        continue
+      }
+      addItem(
+        ticks[d][i].x,
+        ticks[d][i].text,
+        ticks[d][i].font || tickFont,
+        ticks[d][i].fontSize || 12)
+    }
+    tickCount[d] = ((data.length/VERTEX_SIZE)|0) - tickOffset[d]
+  }
+
+  this.buffer.update(data)
+  this.tickOffset = tickOffset
+  this.tickCount = tickCount
+  this.labelOffset = labelOffset
+  this.labelCount = labelCount
+}
+
+//Draws the tick marks for an axis
+var AXIS = [0,0,0]
+proto.drawTicks = function(d, scale, angle, offset, color) {
+  var v = AXIS
+  v[0] = v[1] = v[2] = 0
+  v[d] = 1
+  this.shader.uniforms.axis = v
+  this.shader.uniforms.color = color
+  this.shader.uniforms.angle = angle
+  this.shader.uniforms.scale = scale
+  this.shader.uniforms.offset = offset
+  this.vao.draw(this.gl.TRIANGLES, this.tickCount[d], this.tickOffset[d])
+}
+
+//Draws the text label for an axis
+var ZERO = [0,0,0]
+proto.drawLabel = function(d, scale, angle, offset, color) {
+  this.shader.uniforms.axis = ZERO
+  this.shader.uniforms.color = color
+  this.shader.uniforms.angle = angle
+  this.shader.uniforms.scale = scale
+  this.shader.uniforms.offset = offset
+  this.vao.draw(this.gl.TRIANGLES, this.labelCount[d], this.labelOffset[d])
+}
+
+//Releases all resources attached to this object
+proto.dispose = function() {
+  this.shader.dispose()
+  this.vao.dispose()
+  this.buffer.dispose()
+}
+
+function tryVectorizeText(text, options) {
+  try {
+    return vectorizeText(text, options)
+  } catch(e) {
+    console.warn('error vectorizing text:', e)
+    return {
+      cells: [],
+      positions: []
+    }
+  }
+}
+
+function createTextSprites(
+    gl,
+    bounds,
+    labels,
+    labelFont,
+    ticks,
+    tickFont) {
+
+  var buffer = createBuffer(gl)
+  var vao = createVAO(gl, [
+    { "buffer": buffer,
+      "size": 3
+    }
+  ])
+
+  var shader = createShader(gl)
+  shader.attributes.position.location = 0
+
+  var result = new TextSprites(
+    gl,
+    shader,
+    buffer,
+    vao)
+
+  result.update(bounds, labels, labelFont, ticks, tickFont)
+
+  return result
+}
+
+}).call(this,require('_process'))
+},{"./shaders":131,"_process":55,"gl-buffer":75,"gl-vao":189,"vectorize-text":235}],133:[function(require,module,exports){
+'use strict'
+
+exports.create   = defaultTicks
+exports.equal    = ticksEqual
+
+function prettyPrint(spacing, i) {
+  var stepStr = spacing + ""
+  var u = stepStr.indexOf(".")
+  var sigFigs = 0
+  if(u >= 0) {
+    sigFigs = stepStr.length - u - 1
+  }
+  var shift = Math.pow(10, sigFigs)
+  var x = Math.round(spacing * i * shift)
+  var xstr = x + ""
+  if(xstr.indexOf("e") >= 0) {
+    return xstr
+  }
+  var xi = x / shift, xf = x % shift
+  if(x < 0) {
+    xi = -Math.ceil(xi)|0
+    xf = (-xf)|0
+  } else {
+    xi = Math.floor(xi)|0
+    xf = xf|0
+  }
+  var xis = "" + xi 
+  if(x < 0) {
+    xis = "-" + xis
+  }
+  if(sigFigs) {
+    var xs = "" + xf
+    while(xs.length < sigFigs) {
+      xs = "0" + xs
+    }
+    return xis + "." + xs
+  } else {
+    return xis
+  }
+}
+
+function defaultTicks(bounds, tickSpacing) {
+  var array = []
+  for(var d=0; d<3; ++d) {
+    var ticks = []
+    var m = 0.5*(bounds[0][d]+bounds[1][d])
+    for(var t=0; t*tickSpacing[d]<=bounds[1][d]; ++t) {
+      ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)})
+    }
+    for(var t=-1; t*tickSpacing[d]>=bounds[0][d]; --t) {
+      ticks.push({x: t*tickSpacing[d], text: prettyPrint(tickSpacing[d], t)})
+    }
+    array.push(ticks)
+  }
+  return array
+}
+
+function ticksEqual(ticksA, ticksB) {
+  for(var i=0; i<3; ++i) {
+    if(ticksA[i].length !== ticksB[i].length) {
+      return false
+    }
+    for(var j=0; j<ticksA[i].length; ++j) {
+      var a = ticksA[i][j]
+      var b = ticksB[i][j]
+      if(a.x !== b.x || a.text !== b.text) {
+        return false
+      }
+    }
+  }
+  return true
+}
+},{}],134:[function(require,module,exports){
+"use strict"
+
+module.exports = extractPlanes
+
+function extractPlanes(M, zNear, zFar) {
+  var z  = zNear || 0.0
+  var zf = zFar || 1.0
+  return [
+    [ M[12] + M[0], M[13] + M[1], M[14] + M[2], M[15] + M[3] ],
+    [ M[12] - M[0], M[13] - M[1], M[14] - M[2], M[15] - M[3] ],
+    [ M[12] + M[4], M[13] + M[5], M[14] + M[6], M[15] + M[7] ],
+    [ M[12] - M[4], M[13] - M[5], M[14] - M[6], M[15] - M[7] ],
+    [ z*M[12] + M[8], z*M[13] + M[9], z*M[14] + M[10], z*M[15] + M[11] ],
+    [ zf*M[12] - M[8], zf*M[13] - M[9], zf*M[14] - M[10], zf*M[15] - M[11] ]
+  ]
+}
+},{}],135:[function(require,module,exports){
+"use strict"
+
+var robustDot = require("robust-dot-product")
+var robustSum = require("robust-sum")
+
+module.exports = splitPolygon
+module.exports.positive = positive
+module.exports.negative = negative
+
+function planeT(p, plane) {
+  var r = robustSum(robustDot(p, plane), [plane[plane.length-1]])
+  return r[r.length-1]
+}
+
+
+//Can't do this exactly and emit a floating point result
+function lerpW(a, wa, b, wb) {
+  var d = wb - wa
+  var t = -wa / d
+  if(t < 0.0) {
+    t = 0.0
+  } else if(t > 1.0) {
+    t = 1.0
+  }
+  var ti = 1.0 - t
+  var n = a.length
+  var r = new Array(n)
+  for(var i=0; i<n; ++i) {
+    r[i] = t * a[i] + ti * b[i]
+  }
+  return r
+}
+
+function splitPolygon(points, plane) {
+  var pos = []
+  var neg = []
+  var a = planeT(points[points.length-1], plane)
+  for(var s=points[points.length-1], t=points[0], i=0; i<points.length; ++i, s=t) {
+    t = points[i]
+    var b = planeT(t, plane)
+    if((a < 0 && b > 0) || (a > 0 && b < 0)) {
+      var p = lerpW(s, b, t, a)
+      pos.push(p)
+      neg.push(p.slice())
+    }
+    if(b < 0) {
+      neg.push(t.slice())
+    } else if(b > 0) {
+      pos.push(t.slice())
+    } else {
+      pos.push(t.slice())
+      neg.push(t.slice())
+    }
+    a = b
+  }
+  return { positive: pos, negative: neg }
+}
+
+function positive(points, plane) {
+  var pos = []
+  var a = planeT(points[points.length-1], plane)
+  for(var s=points[points.length-1], t=points[0], i=0; i<points.length; ++i, s=t) {
+    t = points[i]
+    var b = planeT(t, plane)
+    if((a < 0 && b > 0) || (a > 0 && b < 0)) {
+      pos.push(lerpW(s, b, t, a))
+    }
+    if(b >= 0) {
+      pos.push(t.slice())
+    }
+    a = b
+  }
+  return pos
+}
+
+function negative(points, plane) {
+  var neg = []
+  var a = planeT(points[points.length-1], plane)
+  for(var s=points[points.length-1], t=points[0], i=0; i<points.length; ++i, s=t) {
+    t = points[i]
+    var b = planeT(t, plane)
+    if((a < 0 && b > 0) || (a > 0 && b < 0)) {
+      neg.push(lerpW(s, b, t, a))
+    }
+    if(b <= 0) {
+      neg.push(t.slice())
+    }
+    a = b
+  }
+  return neg
+}
+},{"robust-dot-product":136,"robust-sum":217}],136:[function(require,module,exports){
+"use strict"
+
+var twoProduct = require("two-product")
+var robustSum = require("robust-sum")
+
+module.exports = robustDotProduct
+
+function robustDotProduct(a, b) {
+  var r = twoProduct(a[0], b[0])
+  for(var i=1; i<a.length; ++i) {
+    r = robustSum(r, twoProduct(a[i], b[i]))
+  }
+  return r
+}
+},{"robust-sum":217,"two-product":231}],137:[function(require,module,exports){
+"use strict"
+
+module.exports = axesProperties
+
+var getPlanes   = require("extract-frustum-planes")
+var splitPoly   = require("split-polygon")
+var cubeParams  = require("./lib/cube.js")
+var m4mul       = require("gl-mat4/multiply")
+var m4transpose = require("gl-mat4/transpose")
+var v4transformMat4 = require("gl-vec4/transformMat4")
+
+var identity    = new Float32Array([
+    1, 0, 0, 0,
+    0, 1, 0, 0,
+    0, 0, 1, 0,
+    0, 0, 0, 1
+  ])
+
+var mvp         = new Float32Array(16)
+
+function AxesRange3D(lo, hi, pixelsPerDataUnit) {
+  this.lo = lo
+  this.hi = hi
+  this.pixelsPerDataUnit = pixelsPerDataUnit
+}
+
+var SCRATCH_P = [0,0,0,1]
+var SCRATCH_Q = [0,0,0,1]
+
+function gradient(result, M, v, width, height) {
+  for(var i=0; i<3; ++i) {
+    var p = SCRATCH_P
+    var q = SCRATCH_Q
+    for(var j=0; j<3; ++j) {
+      q[j] = p[j] = v[j]
+    }
+    q[3] = p[3] = 1
+
+    q[i] += 1
+    v4transformMat4(q, q, M)
+    if(q[3] < 0) {
+      result[i] = Infinity
+    }
+
+    p[i] -= 1
+    v4transformMat4(p, p, M)
+    if(p[3] < 0) {
+      result[i] = Infinity
+    }
+
+    var dx = (p[0]/p[3] - q[0]/q[3]) * width
+    var dy = (p[1]/p[3] - q[1]/q[3]) * height
+
+    result[i] = 0.25 * Math.sqrt(dx*dx + dy*dy)
+  }
+  return result
+}
+
+var RANGES = [
+  new AxesRange3D(Infinity, -Infinity, Infinity),
+  new AxesRange3D(Infinity, -Infinity, Infinity),
+  new AxesRange3D(Infinity, -Infinity, Infinity)
+]
+
+var SCRATCH_X = [0,0,0]
+
+function axesProperties(axes, camera, width, height, params) {
+  var model       = camera.model || identity
+  var view        = camera.view || identity
+  var projection  = camera.projection || identity
+  var bounds      = axes.bounds
+  var params      = params || cubeParams(model, view, projection, bounds)
+  var axis        = params.axis
+  var edges       = params.edges
+
+  m4mul(mvp, view, model)
+  m4mul(mvp, projection, mvp)
+
+  //Calculate the following properties for each axis:
+  //
+  // * lo - start of visible range for each axis in tick coordinates
+  // * hi - end of visible range for each axis in tick coordinates
+  // * ticksPerPixel - pixel density of tick marks for the axis
+  //
+  var ranges = RANGES
+  for(var i=0; i<3; ++i) {
+    ranges[i].lo = Infinity
+    ranges[i].hi = -Infinity
+    ranges[i].pixelsPerDataUnit = Infinity
+  }
+
+  //Compute frustum planes, intersect with box
+  var frustum = getPlanes(m4transpose(mvp, mvp))
+  m4transpose(mvp, mvp)
+
+  //Loop over vertices of viewable box
+  for(var d=0; d<3; ++d) {
+    var u = (d+1)%3
+    var v = (d+2)%3
+    var x = SCRATCH_X
+i_loop:
+    for(var i=0; i<2; ++i) {
+      var poly = []
+
+      if((axis[d] < 0) === !!i) {
+        continue
+      }
+
+      x[d] = bounds[i][d]
+      for(var j=0; j<2; ++j) {
+        x[u] = bounds[j^i][u]
+        for(var k=0; k<2; ++k) {
+          x[v] = bounds[k^j^i][v]
+          poly.push(x.slice())
+        }
+      }
+      for(var j=0; j<frustum.length; ++j) {
+        if(poly.length === 0) {
+          continue i_loop
+        }
+        poly = splitPoly.positive(poly, frustum[j])
+      }
+
+      //Loop over vertices of polygon to find extremal points
+      for(var j=0; j<poly.length; ++j) {
+        var v = poly[j]
+        var grad = gradient(SCRATCH_X, mvp, v, width, height)
+        for(var k=0; k<3; ++k) {
+          ranges[k].lo = Math.min(ranges[k].lo, v[k])
+          ranges[k].hi = Math.max(ranges[k].hi, v[k])
+          if(k !== d) {
+            ranges[k].pixelsPerDataUnit = Math.min(ranges[k].pixelsPerDataUnit, Math.abs(grad[k]))
+          }
+        }
+      }
+    }
+  }
+
+  return ranges
+}
+
+},{"./lib/cube.js":129,"extract-frustum-planes":134,"gl-mat4/multiply":96,"gl-mat4/transpose":104,"gl-vec4/transformMat4":190,"split-polygon":135}],138:[function(require,module,exports){
+'use strict'
+
+
+var createShader = require('gl-shader')
+
+var vertSrc = "precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, color;\nattribute float weight;\n\nuniform mat4 model, view, projection;\nuniform vec3 coordinates[3];\nuniform vec4 colors[3];\nuniform vec2 screenShape;\nuniform float lineWidth;\n\nvarying vec4 fragColor;\n\nvoid main() {\n  vec3 vertexPosition = mix(coordinates[0],\n    mix(coordinates[2], coordinates[1], 0.5 * (position + 1.0)), abs(position));\n\n  vec4 clipPos = projection * view * model * vec4(vertexPosition, 1.0);\n  vec2 clipOffset = (projection * view * model * vec4(color, 0.0)).xy;\n  vec2 delta = weight * clipOffset * screenShape;\n  vec2 lineOffset = normalize(vec2(delta.y, -delta.x)) / screenShape;\n\n  gl_Position   = vec4(clipPos.xy + clipPos.w * 0.5 * lineWidth * lineOffset, clipPos.z, clipPos.w);\n  fragColor     = color.x * colors[0] + color.y * colors[1] + color.z * colors[2];\n}\n"
+var fragSrc = "precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n  gl_FragColor = fragColor;\n}"
+
+module.exports = function(gl) {
+  return createShader(gl, vertSrc, fragSrc, null, [
+    {name: 'position', type: 'vec3'},
+    {name: 'color', type: 'vec3'},
+    {name: 'weight', type: 'float'}
+  ])
+}
+
+},{"gl-shader":154}],139:[function(require,module,exports){
+'use strict'
+
+var createBuffer = require('gl-buffer')
+var createVAO = require('gl-vao')
+var createShader = require('./shaders/index')
+
+module.exports = createSpikes
+
+var identity = [1,0,0,0,
+                0,1,0,0,
+                0,0,1,0,
+                0,0,0,1]
+
+function AxisSpikes(gl, buffer, vao, shader) {
+  this.gl         = gl
+  this.buffer     = buffer
+  this.vao        = vao
+  this.shader     = shader
+  this.pixelRatio = 1
+  this.bounds     = [[-1000,-1000,-1000], [1000,1000,1000]]
+  this.position   = [0,0,0]
+  this.lineWidth  = [2,2,2]
+  this.colors     = [[0,0,0,1], [0,0,0,1], [0,0,0,1]]
+  this.enabled    = [true,true,true]
+  this.drawSides  = [true,true,true]
+  this.axes       = null
+}
+
+var proto = AxisSpikes.prototype
+
+var OUTER_FACE = [0,0,0]
+var INNER_FACE = [0,0,0]
+
+var SHAPE = [0,0]
+
+proto.isTransparent = function() {
+  return false
+}
+
+proto.drawTransparent = function(camera) {}
+
+proto.draw = function(camera) {
+  var gl = this.gl
+  var vao = this.vao
+  var shader = this.shader
+
+  vao.bind()
+  shader.bind()
+
+  var model      = camera.model || identity
+  var view       = camera.view || identity
+  var projection = camera.projection || identity
+
+  var axis
+  if(this.axes) {
+    axis = this.axes.lastCubeProps.axis
+  }
+
+  var outerFace = OUTER_FACE
+  var innerFace = INNER_FACE
+  for(var i=0; i<3; ++i) {
+    if(axis && axis[i] < 0) {
+      outerFace[i] = this.bounds[0][i]
+      innerFace[i] = this.bounds[1][i]
+    } else {
+      outerFace[i] = this.bounds[1][i]
+      innerFace[i] = this.bounds[0][i]
+    }
+  }
+
+  SHAPE[0] = gl.drawingBufferWidth
+  SHAPE[1] = gl.drawingBufferHeight
+
+  shader.uniforms.model       = model
+  shader.uniforms.view        = view
+  shader.uniforms.projection  = projection
+  shader.uniforms.coordinates = [this.position, outerFace, innerFace]
+  shader.uniforms.colors      = this.colors
+  shader.uniforms.screenShape = SHAPE
+
+  for(var i=0; i<3; ++i) {
+    shader.uniforms.lineWidth = this.lineWidth[i] * this.pixelRatio
+    if(this.enabled[i]) {
+      vao.draw(gl.TRIANGLES, 6, 6*i)
+      if(this.drawSides[i]) {
+        vao.draw(gl.TRIANGLES, 12, 18+12*i)
+      }
+    }
+  }
+
+  vao.unbind()
+}
+
+proto.update = function(options) {
+  if(!options) {
+    return
+  }
+  if("bounds" in options) {
+    this.bounds = options.bounds
+  }
+  if("position" in options) {
+    this.position = options.position
+  }
+  if("lineWidth" in options) {
+    this.lineWidth = options.lineWidth
+  }
+  if("colors" in options) {
+    this.colors = options.colors
+  }
+  if("enabled" in options) {
+    this.enabled = options.enabled
+  }
+  if("drawSides" in options) {
+    this.drawSides = options.drawSides
+  }
+}
+
+proto.dispose = function() {
+  this.vao.dispose()
+  this.buffer.dispose()
+  this.shader.dispose()
+}
+
+
+
+function createSpikes(gl, options) {
+  //Create buffers
+  var data = [ ]
+
+  function line(x,y,z,i,l,h) {
+    var row = [x,y,z,  0,0,0,  1]
+    row[i+3] = 1
+    row[i] = l
+    data.push.apply(data, row)
+    row[6] = -1
+    data.push.apply(data, row)
+    row[i] = h
+    data.push.apply(data, row)
+    data.push.apply(data, row)
+    row[6] = 1
+    data.push.apply(data, row)
+    row[i] = l
+    data.push.apply(data, row)
+  }
+
+  line(0,0,0, 0, 0, 1)
+  line(0,0,0, 1, 0, 1)
+  line(0,0,0, 2, 0, 1)
+
+  line(1,0,0,  1,  -1,1)
+  line(1,0,0,  2,  -1,1)
+
+  line(0,1,0,  0,  -1,1)
+  line(0,1,0,  2,  -1,1)
+
+  line(0,0,1,  0,  -1,1)
+  line(0,0,1,  1,  -1,1)
+
+  var buffer = createBuffer(gl, data)
+  var vao = createVAO(gl, [{
+    type: gl.FLOAT,
+    buffer: buffer,
+    size: 3,
+    offset: 0,
+    stride: 28
+  }, {
+    type: gl.FLOAT,
+    buffer: buffer,
+    size: 3,
+    offset: 12,
+    stride: 28
+  }, {
+    type: gl.FLOAT,
+    buffer: buffer,
+    size: 1,
+    offset: 24,
+    stride: 28
+  }])
+
+  //Create shader
+  var shader = createShader(gl)
+  shader.attributes.position.location = 0
+  shader.attributes.color.location = 1
+  shader.attributes.weight.location = 2
+
+  //Create spike object
+  var spikes = new AxisSpikes(gl, buffer, vao, shader)
+
+  //Set parameters
+  spikes.update(options)
+
+  //Return resulting object
+  return spikes
+}
+
+},{"./shaders/index":138,"gl-buffer":75,"gl-vao":189}],140:[function(require,module,exports){
+'use strict'
+
+module.exports = createScene
+
+var createCamera = require('3d-view-controls')
+var createAxes   = require('gl-axes3d')
+var axesRanges   = require('gl-axes3d/properties')
+var createSpikes = require('gl-spikes3d')
+var createSelect = require('gl-select-static')
+var createFBO    = require('gl-fbo')
+var drawTriangle = require('a-big-triangle')
+var mouseChange  = require('mouse-change')
+var perspective  = require('gl-mat4/perspective')
+var createShader = require('./lib/shader')
+
+function MouseSelect() {
+  this.mouse          = [-1,-1]
+  this.screen         = null
+  this.distance       = Infinity
+  this.index          = null
+  this.dataCoordinate = null
+  this.dataPosition   = null
+  this.object         = null
+  this.data           = null
+}
+
+function getContext(canvas, options) {
+  var gl = null
+  try {
+    gl = canvas.getContext('webgl', options)
+    if(!gl) {
+      gl = canvas.getContext('experimental-webgl', options)
+    }
+  } catch(e) {
+    return null
+  }
+  return gl
+}
+
+function roundUpPow10(x) {
+  var y = Math.round(Math.log(Math.abs(x)) / Math.log(10))
+  if(y < 0) {
+    var base = Math.round(Math.pow(10, -y))
+    return Math.ceil(x*base) / base
+  } else if(y > 0) {
+    var base = Math.round(Math.pow(10, y))
+    return Math.ceil(x/base) * base
+  }
+  return Math.ceil(x)
+}
+
+function defaultBool(x) {
+  if(typeof x === 'boolean') {
+    return x
+  }
+  return true
+}
+
+function createScene(options) {
+  options = options || {}
+
+  var stopped = false
+
+  var pixelRatio = options.pixelRatio || parseFloat(window.devicePixelRatio)
+
+  var canvas = options.canvas
+  if(!canvas) {
+    canvas = document.createElement('canvas')
+    if(options.container) {
+      var container = options.container
+      container.appendChild(canvas)
+    } else {
+      document.body.appendChild(canvas)
+    }
+  }
+
+  var gl = options.gl
+  if(!gl) {
+    gl = getContext(canvas,
+      options.glOptions || {
+        premultipliedAlpha: true,
+        antialias: true
+      })
+  }
+  if(!gl) {
+    throw new Error('webgl not supported')
+  }
+
+  //Initial bounds
+  var bounds = options.bounds || [[-10,-10,-10], [10,10,10]]
+
+  //Create selection
+  var selection = new MouseSelect()
+
+  //Accumulation buffer
+  var accumBuffer = createFBO(gl,
+    [gl.drawingBufferWidth, gl.drawingBufferHeight], {
+      preferFloat: true
+    })
+
+  var accumShader = createShader(gl)
+
+  //Create a camera
+  var cameraOptions = options.camera || {
+    eye:    [2,0,0],
+    center: [0,0,0],
+    up:     [0,1,0],
+    zoomMin: 0.1,
+    zoomMax: 100,
+    mode:    'turntable'
+  }
+
+  //Create axes
+  var axesOptions = options.axes || {}
+  var axes = createAxes(gl, axesOptions)
+  axes.enable = !axesOptions.disable
+
+  //Create spikes
+  var spikeOptions = options.spikes || {}
+  var spikes = createSpikes(gl, spikeOptions)
+
+  //Object list is empty initially
+  var objects         = []
+  var pickBufferIds   = []
+  var pickBufferCount = []
+  var pickBuffers     = []
+
+  //Dirty flag, skip redraw if scene static
+  var dirty       = true
+  var pickDirty   = true
+
+  var projection     = new Array(16)
+  var model          = new Array(16)
+
+  var cameraParams = {
+    view:         null,
+    projection:   projection,
+    model:        model
+  }
+
+  var pickDirty = true
+
+  var viewShape = [ gl.drawingBufferWidth, gl.drawingBufferHeight ]
+
+  //Create scene object
+  var scene = {
+    gl:           gl,
+    contextLost:  false,
+    pixelRatio:   options.pixelRatio || parseFloat(window.devicePixelRatio),
+    canvas:       canvas,
+    selection:    selection,
+    camera:       createCamera(canvas, cameraOptions),
+    axes:         axes,
+    axesPixels:   null,
+    spikes:       spikes,
+    bounds:       bounds,
+    objects:      objects,
+    shape:        viewShape,
+    aspect:       options.aspectRatio || [1,1,1],
+    pickRadius:   options.pickRadius || 10,
+    zNear:        options.zNear || 0.01,
+    zFar:         options.zFar  || 1000,
+    fovy:         options.fovy  || Math.PI/4,
+    clearColor:   options.clearColor || [0,0,0,0],
+    autoResize:   defaultBool(options.autoResize),
+    autoBounds:   defaultBool(options.autoBounds),
+    autoScale:    !!options.autoScale,
+    autoCenter:   defaultBool(options.autoCenter),
+    clipToBounds: defaultBool(options.clipToBounds),
+    snapToData:   !!options.snapToData,
+    onselect:     options.onselect || null,
+    onrender:     options.onrender || null,
+    onclick:      options.onclick  || null,
+    cameraParams: cameraParams,
+    oncontextloss: null,
+    mouseListener: null
+  }
+
+  var pickShape = [ (gl.drawingBufferWidth/scene.pixelRatio)|0, (gl.drawingBufferHeight/scene.pixelRatio)|0 ]
+
+  function resizeListener() {
+    if(stopped) {
+      return
+    }
+    if(!scene.autoResize) {
+      return
+    }
+    var parent = canvas.parentNode
+    var width  = 1
+    var height = 1
+    if(parent && parent !== document.body) {
+      width  = parent.clientWidth
+      height = parent.clientHeight
+    } else {
+      width  = window.innerWidth
+      height = window.innerHeight
+    }
+    var nextWidth  = Math.ceil(width  * scene.pixelRatio)|0
+    var nextHeight = Math.ceil(height * scene.pixelRatio)|0
+    if(nextWidth !== canvas.width || nextHeight !== canvas.height) {
+      canvas.width   = nextWidth
+      canvas.height  = nextHeight
+      var style = canvas.style
+      style.position = style.position || 'absolute'
+      style.left     = '0px'
+      style.top      = '0px'
+      style.width    = width  + 'px'
+      style.height   = height + 'px'
+      dirty = true
+    }
+  }
+  if(scene.autoResize) {
+    resizeListener()
+  }
+  window.addEventListener('resize', resizeListener)
+
+  function reallocPickIds() {
+    var numObjs = objects.length
+    var numPick = pickBuffers.length
+    for(var i=0; i<numPick; ++i) {
+      pickBufferCount[i] = 0
+    }
+    obj_loop:
+    for(var i=0; i<numObjs; ++i) {
+      var obj = objects[i]
+      var pickCount = obj.pickSlots
+      if(!pickCount) {
+        pickBufferIds[i] = -1
+        continue
+      }
+      for(var j=0; j<numPick; ++j) {
+        if(pickBufferCount[j] + pickCount < 255) {
+          pickBufferIds[i] = j
+          obj.setPickBase(pickBufferCount[j]+1)
+          pickBufferCount[j] += pickCount
+          continue obj_loop
+        }
+      }
+      //Create new pick buffer
+      var nbuffer = createSelect(gl, viewShape)
+      pickBufferIds[i] = numPick
+      pickBuffers.push(nbuffer)
+      pickBufferCount.push(pickCount)
+      obj.setPickBase(1)
+      numPick += 1
+    }
+    while(numPick > 0 && pickBufferCount[numPick-1] === 0) {
+      pickBufferCount.pop()
+      pickBuffers.pop().dispose()
+    }
+  }
+
+  scene.update = function(options) {
+    if(stopped) {
+      return
+    }
+    options = options || {}
+    dirty = true
+    pickDirty = true
+  }
+
+  scene.add = function(obj) {
+    if(stopped) {
+      return
+    }
+    obj.axes = axes
+    objects.push(obj)
+    pickBufferIds.push(-1)
+    dirty = true
+    pickDirty = true
+    reallocPickIds()
+  }
+
+  scene.remove = function(obj) {
+    if(stopped) {
+      return
+    }
+    var idx = objects.indexOf(obj)
+    if(idx < 0) {
+      return
+    }
+    objects.splice(idx, 1)
+    pickBufferIds.pop()
+    dirty = true
+    pickDirty = true
+    reallocPickIds()
+  }
+
+  scene.dispose = function() {
+    if(stopped) {
+      return
+    }
+
+    stopped = true
+
+    window.removeEventListener('resize', resizeListener)
+    canvas.removeEventListener('webglcontextlost', checkContextLoss)
+    scene.mouseListener.enabled = false
+
+    if(scene.contextLost) {
+      return
+    }
+
+    //Destroy objects
+    axes.dispose()
+    spikes.dispose()
+    for(var i=0; i<objects.length; ++i) {
+      objects[i].dispose()
+    }
+
+    //Clean up buffers
+    accumBuffer.dispose()
+    for(var i=0; i<pickBuffers.length; ++i) {
+      pickBuffers[i].dispose()
+    }
+
+    //Clean up shaders
+    accumShader.dispose()
+
+    //Release all references
+    gl = null
+    axes = null
+    spikes = null
+    objects = []
+  }
+
+  //Update mouse position
+  var mouseRotating = false
+
+  var prevButtons = 0
+
+  scene.mouseListener = mouseChange(canvas, function(buttons, x, y) {
+    if(stopped) {
+      return
+    }
+
+    var numPick = pickBuffers.length
+    var numObjs = objects.length
+    var prevObj = selection.object
+
+    selection.distance = Infinity
+    selection.mouse[0] = x
+    selection.mouse[1] = y
+    selection.object = null
+    selection.screen = null
+    selection.dataCoordinate = selection.dataPosition = null
+
+    var change = false
+
+    if(buttons && prevButtons) {
+      mouseRotating = true
+    } else {
+      if(mouseRotating) {
+        pickDirty = true
+      }
+      mouseRotating = false
+
+      for(var i=0; i<numPick; ++i) {
+        var result = pickBuffers[i].query(x, pickShape[1] - y - 1, scene.pickRadius)
+        if(result) {
+          if(result.distance > selection.distance) {
+            continue
+          }
+          for(var j=0; j<numObjs; ++j) {
+            var obj = objects[j]
+            if(pickBufferIds[j] !== i) {
+              continue
+            }
+            var objPick = obj.pick(result)
+            if(objPick) {
+              selection.buttons        = buttons
+              selection.screen         = result.coord
+              selection.distance       = result.distance
+              selection.object         = obj
+              selection.index          = objPick.distance
+              selection.dataPosition   = objPick.position
+              selection.dataCoordinate = objPick.dataCoordinate
+              selection.data           = objPick
+              change = true
+            }
+          }
+        }
+      }
+    }
+
+    if(prevObj && prevObj !== selection.object) {
+      if(prevObj.highlight) {
+        prevObj.highlight(null)
+      }
+      dirty = true
+    }
+    if(selection.object) {
+      if(selection.object.highlight) {
+        selection.object.highlight(selection.data)
+      }
+      dirty = true
+    }
+
+    change = change || (selection.object !== prevObj)
+    if(change && scene.onselect) {
+      scene.onselect(selection)
+    }
+
+    if((buttons & 1) && !(prevButtons & 1) && scene.onclick) {
+      scene.onclick(selection)
+    }
+    prevButtons = buttons
+  })
+
+  function checkContextLoss() {
+    if(scene.contextLost) {
+      return true
+    }
+    if(gl.isContextLost()) {
+      scene.contextLost = true
+      scene.mouseListener.enabled = false
+      scene.selection.object = null
+      if(scene.oncontextloss) {
+        scene.oncontextloss()
+      }
+    }
+  }
+
+  canvas.addEventListener('webglcontextlost', checkContextLoss)
+
+  //Render the scene for mouse picking
+  function renderPick() {
+    if(checkContextLoss()) {
+      return
+    }
+
+    gl.colorMask(true, true, true, true)
+    gl.depthMask(true)
+    gl.disable(gl.BLEND)
+    gl.enable(gl.DEPTH_TEST)
+
+    var numObjs = objects.length
+    var numPick = pickBuffers.length
+    for(var j=0; j<numPick; ++j) {
+      var buf = pickBuffers[j]
+      buf.shape = pickShape
+      buf.begin()
+      for(var i=0; i<numObjs; ++i) {
+        if(pickBufferIds[i] !== j) {
+          continue
+        }
+        var obj = objects[i]
+        if(obj.drawPick) {
+          obj.pixelRatio = 1
+          obj.drawPick(cameraParams)
+        }
+      }
+      buf.end()
+    }
+  }
+
+  var nBounds = [
+    [ Infinity, Infinity, Infinity],
+    [-Infinity,-Infinity,-Infinity]]
+
+  var prevBounds = [nBounds[0].slice(), nBounds[1].slice()]
+
+  function redraw() {
+    if(checkContextLoss()) {
+      return
+    }
+
+    resizeListener()
+
+    //Tick camera
+    var cameraMoved = scene.camera.tick()
+    cameraParams.view = scene.camera.matrix
+    dirty     = dirty || cameraMoved
+    pickDirty = pickDirty || cameraMoved
+
+      //Set pixel ratio
+    axes.pixelRatio   = scene.pixelRatio
+    spikes.pixelRatio = scene.pixelRatio
+
+    //Check if any objects changed, recalculate bounds
+    var numObjs = objects.length
+    var lo = nBounds[0]
+    var hi = nBounds[1]
+    lo[0] = lo[1] = lo[2] =  Infinity
+    hi[0] = hi[1] = hi[2] = -Infinity
+    for(var i=0; i<numObjs; ++i) {
+      var obj = objects[i]
+
+      //Set the axes properties for each object
+      obj.pixelRatio = scene.pixelRatio
+      obj.axes = scene.axes
+
+      dirty = dirty || !!obj.dirty
+      pickDirty = pickDirty || !!obj.dirty
+      var obb = obj.bounds
+      if(obb) {
+        var olo = obb[0]
+        var ohi = obb[1]
+        for(var j=0; j<3; ++j) {
+          lo[j] = Math.min(lo[j], olo[j])
+          hi[j] = Math.max(hi[j], ohi[j])
+        }
+      }
+    }
+
+    //Recalculate bounds
+    var bounds = scene.bounds
+    if(scene.autoBounds) {
+      for(var j=0; j<3; ++j) {
+        if(hi[j] < lo[j]) {
+          lo[j] = -1
+          hi[j] = 1
+        } else {
+          if(lo[j] === hi[j]) {
+            lo[j] -= 1
+            hi[j] += 1
+          }
+          var padding = 0.05 * (hi[j] - lo[j])
+          lo[j] = lo[j] - padding
+          hi[j] = hi[j] + padding
+        }
+        bounds[0][j] = lo[j]
+        bounds[1][j] = hi[j]
+      }
+    }
+
+    var boundsChanged = false
+    for(var j=0; j<3; ++j) {
+        boundsChanged = boundsChanged ||
+            (prevBounds[0][j] !== bounds[0][j])  ||
+            (prevBounds[1][j] !== bounds[1][j])
+        prevBounds[0][j] = bounds[0][j]
+        prevBounds[1][j] = bounds[1][j]
+    }
+
+    if(boundsChanged) {
+      var tickSpacing = [0,0,0]
+      for(var i=0; i<3; ++i) {
+        tickSpacing[i] = roundUpPow10((bounds[1][i]-bounds[0][i]) / 10.0)
+      }
+      if(axes.autoTicks) {
+        axes.update({
+          bounds: bounds,
+          tickSpacing: tickSpacing
+        })
+      } else {
+        axes.update({
+          bounds: bounds
+        })
+      }
+    }
+
+    //Recalculate bounds
+    pickDirty = pickDirty || boundsChanged
+    dirty = dirty || boundsChanged
+
+    //Get scene
+    var width  = gl.drawingBufferWidth
+    var height = gl.drawingBufferHeight
+    viewShape[0] = width
+    viewShape[1] = height
+    pickShape[0] = Math.max(width/scene.pixelRatio, 1)|0
+    pickShape[1] = Math.max(height/scene.pixelRatio, 1)|0
+
+    //Compute camera parameters
+    perspective(projection,
+      scene.fovy,
+      width/height,
+      scene.zNear,
+      scene.zFar)
+
+    //Compute model matrix
+    for(var i=0; i<16; ++i) {
+      model[i] = 0
+    }
+    model[15] = 1
+
+    var maxS = 0
+    for(var i=0; i<3; ++i) {
+      maxS = Math.max(maxS, bounds[1][i] - bounds[0][i])
+    }
+
+    for(var i=0; i<3; ++i) {
+      if(scene.autoScale) {
+        model[5*i] = scene.aspect[i] / (bounds[1][i] - bounds[0][i])
+      } else {
+        model[5*i] = 1  / maxS
+      }
+      if(scene.autoCenter) {
+        model[12+i] = -model[5*i] * 0.5 * (bounds[0][i] + bounds[1][i])
+      }
+    }
+
+    //Apply axes/clip bounds
+    for(var i=0; i<numObjs; ++i) {
+      var obj = objects[i]
+
+      //Set axes bounds
+      obj.axesBounds = bounds
+
+      //Set clip bounds
+      if(scene.clipToBounds) {
+        obj.clipBounds = bounds
+      }
+    }
+
+    //Set spike parameters
+    if(selection.object) {
+      if(scene.snapToData) {
+        spikes.position = selection.dataCoordinate
+      } else {
+        spikes.position = selection.dataPosition
+      }
+      spikes.bounds = bounds
+    }
+
+    //If state changed, then redraw pick buffers
+    if(pickDirty) {
+      pickDirty = false
+      renderPick()
+    }
+
+    if(!dirty) {
+      return
+    }
+
+    //Recalculate pixel data
+    scene.axesPixels = axesRanges(scene.axes, cameraParams, width, height)
+
+    //Call render callback
+    if(scene.onrender) {
+      scene.onrender()
+    }
+
+    //Read value
+    gl.bindFramebuffer(gl.FRAMEBUFFER, null)
+    gl.viewport(0, 0, width, height)
+
+    //General strategy: 3 steps
+    //  1. render non-transparent objects
+    //  2. accumulate transparent objects into separate fbo
+    //  3. composite final scene
+
+    //Clear FBO
+    var clearColor = scene.clearColor
+    gl.clearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3])
+    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
+    gl.depthMask(true)
+    gl.colorMask(true, true, true, true)
+    gl.enable(gl.DEPTH_TEST)
+    gl.depthFunc(gl.LEQUAL)
+    gl.disable(gl.BLEND)
+    gl.disable(gl.CULL_FACE)  //most visualization surfaces are 2 sided
+
+    //Render opaque pass
+    var hasTransparent = false
+    if(axes.enable) {
+      hasTransparent = hasTransparent || axes.isTransparent()
+      axes.draw(cameraParams)
+    }
+    spikes.axes = axes
+    if(selection.object) {
+      spikes.draw(cameraParams)
+    }
+
+    gl.disable(gl.CULL_FACE)  //most visualization surfaces are 2 sided
+
+    for(var i=0; i<numObjs; ++i) {
+      var obj = objects[i]
+      obj.axes = axes
+      obj.pixelRatio = scene.pixelRatio
+      if(obj.isOpaque && obj.isOpaque()) {
+        obj.draw(cameraParams)
+      }
+      if(obj.isTransparent && obj.isTransparent()) {
+        hasTransparent = true
+      }
+    }
+
+    if(hasTransparent) {
+      //Render transparent pass
+      accumBuffer.shape = viewShape
+      accumBuffer.bind()
+      gl.clear(gl.DEPTH_BUFFER_BIT)
+      gl.colorMask(false, false, false, false)
+      gl.depthMask(true)
+      gl.depthFunc(gl.LESS)
+
+      //Render forward facing objects
+      if(axes.enable && axes.isTransparent()) {
+        axes.drawTransparent(cameraParams)
+      }
+      for(var i=0; i<numObjs; ++i) {
+        var obj = objects[i]
+        if(obj.isOpaque && obj.isOpaque()) {
+          obj.draw(cameraParams)
+        }
+      }
+
+      //Render transparent pass
+      gl.enable(gl.BLEND)
+      gl.blendEquation(gl.FUNC_ADD)
+      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
+      gl.colorMask(true, true, true, true)
+      gl.depthMask(false)
+      gl.clearColor(0,0,0,0)
+      gl.clear(gl.COLOR_BUFFER_BIT)
+
+      if(axes.isTransparent()) {
+        axes.drawTransparent(cameraParams)
+      }
+
+      for(var i=0; i<numObjs; ++i) {
+        var obj = objects[i]
+        if(obj.isTransparent && obj.isTransparent()) {
+          obj.drawTransparent(cameraParams)
+        }
+      }
+
+      //Unbind framebuffer
+      gl.bindFramebuffer(gl.FRAMEBUFFER, null)
+
+      //Draw composite pass
+      gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
+      gl.disable(gl.DEPTH_TEST)
+      accumShader.bind()
+      accumBuffer.color[0].bind(0)
+      accumShader.uniforms.accumBuffer = 0
+      drawTriangle(gl)
+
+      //Turn off blending
+      gl.disable(gl.BLEND)
+    }
+
+    //Clear dirty flags
+    dirty = false
+    for(var i=0; i<numObjs; ++i) {
+      objects[i].dirty = false
+    }
+  }
+
+
+  //Draw the whole scene
+  function render() {
+    if(stopped || scene.contextLost) {
+      return
+    }
+    requestAnimationFrame(render)
+    redraw()
+  }
+  render()
+
+  //Force redraw of whole scene
+  scene.redraw = function() {
+    if(stopped) {
+      return
+    }
+    dirty = true
+    redraw()
+  }
+
+  return scene
+}
+
+},{"./lib/shader":123,"3d-view-controls":124,"a-big-triangle":126,"gl-axes3d":127,"gl-axes3d/properties":137,"gl-fbo":80,"gl-mat4/perspective":97,"gl-select-static":153,"gl-spikes3d":139,"mouse-change":196}],141:[function(require,module,exports){
+'use strict'
+
+
+
+module.exports = {
+  vertex:       "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n  vec3 xposition = view * vec3(position, 1.0);\n  return vec4(\n    xposition.xy + scale * offset * xposition.z,\n    0,\n    xposition.z);\n}\n\n\n\n\nvoid main() {\n  fragColor = color;\n\n  gl_Position = computePosition_1_0(\n    position,\n    offset,\n    viewTransform,\n    pixelScale);\n}\n",
+  fragment:     "#define GLSLIFY 1\nprecision lowp float;\nvarying vec4 fragColor;\nvoid main() {\n  gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n",
+  pickVertex:   "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 id;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\nuniform vec4 pickOffset;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n  vec3 xposition = view * vec3(position, 1.0);\n  return vec4(\n    xposition.xy + scale * offset * xposition.z,\n    0,\n    xposition.z);\n}\n\n\n\n\nvoid main() {\n  vec4 fragId = id + pickOffset;\n\n  fragId.y += floor(fragId.x / 256.0);\n  fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n  fragId.z += floor(fragId.y / 256.0);\n  fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n  fragId.w += floor(fragId.z / 256.0);\n  fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n  fragColor = fragId / 255.0;\n\n  gl_Position = computePosition_1_0(\n    position,\n    offset,\n    viewTransform,\n    pixelScale);\n}\n",
+  pickFragment: "#define GLSLIFY 1\nprecision lowp float;\nvarying vec4 fragColor;\nvoid main() {\n  gl_FragColor = fragColor;\n}\n"
+}
+
+},{}],142:[function(require,module,exports){
+'use strict'
+
+module.exports = createFancyScatter2D
+
+var createShader = require('gl-shader')
+var createBuffer = require('gl-buffer')
+var textCache = require('text-cache')
+var pool = require('typedarray-pool')
+var vectorizeText = require('vectorize-text')
+var shaders = require('./lib/shaders')
+
+var BOUNDARIES = {}
+
+function getBoundary(glyph) {
+  if(glyph in BOUNDARIES) {
+    return BOUNDARIES[glyph]
+  }
+
+  var polys = vectorizeText(glyph, {
+    polygons: true,
+    font: 'sans-serif',
+    textAlign: 'left',
+    textBaseline: 'alphabetic'
+  })
+
+  var coords  = []
+  var normals = []
+
+  polys.forEach(function(loops) {
+    loops.forEach(function(loop) {
+      for(var i=0; i<loop.length; ++i) {
+        var a = loop[(i + loop.length - 1) % loop.length]
+        var b = loop[i]
+        var c = loop[(i + 1) % loop.length]
+        var d = loop[(i + 2) % loop.length]
+
+        var dx = b[0] - a[0]
+        var dy = b[1] - a[1]
+        var dl = Math.sqrt(dx*dx + dy*dy)
+        dx /= dl
+        dy /= dl
+
+        coords.push(a[0], a[1] + 1.4)
+        normals.push(dy, -dx)
+        coords.push(a[0], a[1] + 1.4)
+        normals.push(-dy, dx)
+        coords.push(b[0], b[1] + 1.4)
+        normals.push(-dy, dx)
+
+        coords.push(b[0], b[1] + 1.4)
+        normals.push(-dy, dx)
+        coords.push(a[0], a[1] + 1.4)
+        normals.push(dy, -dx)
+        coords.push(b[0], b[1] + 1.4)
+        normals.push(dy, -dx)
+
+        var ex = d[0] - c[0]
+        var ey = d[1] - c[1]
+        var el = Math.sqrt(ex*ex + ey*ey)
+        ex /= el
+        ey /= el
+
+        coords.push(b[0], b[1]+1.4)
+        normals.push(dy, -dx)
+        coords.push(b[0], b[1]+1.4)
+        normals.push(-dy, dx)
+        coords.push(c[0], c[1]+1.4)
+        normals.push(-ey, ex)
+
+        coords.push(c[0], c[1]+1.4)
+        normals.push(-ey, ex)
+        coords.push(b[0], b[1]+1.4)
+        normals.push(ey, -ex)
+        coords.push(c[0], c[1]+1.4)
+        normals.push(ey, -ex)
+      }
+    })
+  })
+
+  var bounds = [Infinity, Infinity, -Infinity, -Infinity]
+  for(var i=0; i<coords.length; i+=2) {
+    for(var j=0; j<2; ++j) {
+      bounds[j]   = Math.min(bounds[j],   coords[i+j])
+      bounds[2+j] = Math.max(bounds[2+j], coords[i+j])
+    }
+  }
+
+  return BOUNDARIES[glyph] = {
+    coords:  coords,
+    normals: normals,
+    bounds:  bounds
+  }
+}
+
+
+var VERTEX_SIZE       = 9
+var VERTEX_SIZE_BYTES = VERTEX_SIZE * 4
+
+function GLScatterFancy(
+    plot,
+    shader,
+    pickShader,
+    positionBuffer,
+    offsetBuffer,
+    colorBuffer,
+    idBuffer) {
+  this.plot           = plot
+  this.shader         = shader
+  this.pickShader     = pickShader
+  this.positionBuffer = positionBuffer
+  this.offsetBuffer   = offsetBuffer
+  this.colorBuffer    = colorBuffer
+  this.idBuffer       = idBuffer
+  this.bounds         = [Infinity, Infinity, -Infinity, -Infinity]
+  this.numPoints      = 0
+  this.numVertices    = 0
+  this.pickOffset     = 0
+  this.points         = null
+}
+
+var proto = GLScatterFancy.prototype
+
+;(function() {
+  var MATRIX = [
+    1, 0, 0,
+    0, 1, 0,
+    0, 0, 1
+  ];
+
+  var PIXEL_SCALE = [1, 1]
+
+  function calcScales() {
+    var plot          = this.plot
+    var bounds        = this.bounds
+
+    var viewBox     = plot.viewBox
+    var dataBox     = plot.dataBox
+    var pixelRatio  = plot.pixelRatio
+
+    var boundX  = bounds[2] - bounds[0]
+    var boundY  = bounds[3] - bounds[1]
+    var dataX   = dataBox[2] - dataBox[0]
+    var dataY   = dataBox[3] - dataBox[1]
+
+    MATRIX[0] = 2.0 * boundX / dataX
+    MATRIX[4] = 2.0 * boundY / dataY
+    MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0
+    MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0
+
+    var screenX = (viewBox[2] - viewBox[0])
+    var screenY = (viewBox[3] - viewBox[1])
+
+    PIXEL_SCALE[0] = 2.0 * pixelRatio / screenX
+    PIXEL_SCALE[1] = 2.0 * pixelRatio / screenY
+  }
+
+  proto.draw = function() {
+    var plot          = this.plot
+    var shader        = this.shader
+    var numVertices   = this.numVertices
+
+    var gl          = plot.gl
+
+    calcScales.call(this)
+
+    shader.bind()
+
+    shader.uniforms.pixelScale = PIXEL_SCALE
+    shader.uniforms.viewTransform = MATRIX
+
+    this.positionBuffer.bind()
+    shader.attributes.position.pointer()
+
+    this.offsetBuffer.bind()
+    shader.attributes.offset.pointer()
+
+    this.colorBuffer.bind()
+    shader.attributes.color.pointer(gl.UNSIGNED_BYTE, true)
+
+    gl.drawArrays(gl.TRIANGLES, 0, numVertices)
+  }
+
+  var PICK_OFFSET = [0,0,0,0]
+
+  proto.drawPick = function(offset) {
+    var plot          = this.plot
+    var shader        = this.pickShader
+    var numVertices   = this.numVertices
+
+    var gl          = plot.gl
+
+    this.pickOffset = offset
+
+    for(var i=0; i<4; ++i) {
+      PICK_OFFSET[i] = ((offset>>(i*8)) & 0xff)
+    }
+
+    calcScales.call(this)
+
+    shader.bind()
+
+    shader.uniforms.pixelScale    = PIXEL_SCALE
+    shader.uniforms.viewTransform = MATRIX
+    shader.uniforms.pickOffset    = PICK_OFFSET
+
+    this.positionBuffer.bind()
+    shader.attributes.position.pointer()
+
+    this.offsetBuffer.bind()
+    shader.attributes.offset.pointer()
+
+    this.idBuffer.bind()
+    shader.attributes.id.pointer(gl.UNSIGNED_BYTE, false)
+
+    gl.drawArrays(gl.TRIANGLES, 0, numVertices)
+
+    return offset + this.numPoints
+  }
+})()
+
+proto.pick = function(x, y, value) {
+  var pickOffset = this.pickOffset
+  var pointCount = this.numPoints
+  if(value < pickOffset || value >= pickOffset + pointCount) {
+    return null
+  }
+  var pointId = value - pickOffset
+  var points   = this.points
+  return {
+    object:     this,
+    pointId:    pointId,
+    dataCoord: [ points[2*pointId], points[2*pointId+1] ]
+  }
+}
+
+proto.update = function(options) {
+  options = options || {}
+
+  var positions     = options.positions    || []
+  var colors        = options.colors       || []
+  var glyphs        = options.glyphs       || []
+  var sizes         = options.sizes        || []
+  var borderWidths  = options.borderWidths || []
+  var borderColors  = options.borderColors || []
+
+  this.points = positions
+
+  var bounds = this.bounds = [Infinity, Infinity, -Infinity, -Infinity]
+  var numVertices = 0
+  for(var i=0; i<glyphs.length; ++i) {
+    numVertices += (
+      textCache('sans-serif', glyphs[i]).data.length +
+      getBoundary(glyphs[i]).coords.length
+    )>> 1
+    for(var j=0; j<2; ++j) {
+      bounds[j]   = Math.min(bounds[j],   positions[2*i+j])
+      bounds[2+j] = Math.max(bounds[2+j], positions[2*i+j])
+    }
+  }
+
+  if(bounds[0] === bounds[2]) {
+    bounds[2] += 1
+  }
+  if(bounds[3] === bounds[1]) {
+    bounds[3] += 1
+  }
+
+  var sx = 1/(bounds[2] - bounds[0])
+  var sy = 1/(bounds[3] - bounds[1])
+  var tx = bounds[0]
+  var ty = bounds[1]
+
+  var v_position = pool.mallocFloat32(2 * numVertices)
+  var v_offset   = pool.mallocFloat32(2 * numVertices)
+  var v_color    = pool.mallocUint8(4 * numVertices)
+  var v_ids      = pool.mallocUint32(numVertices)
+  var ptr = 0
+
+  for(var i=0; i<glyphs.length; ++i) {
+    var glyph = textCache('sans-serif', glyphs[i])
+    var border = getBoundary(glyphs[i])
+    var x = sx * (positions[2*i]   - tx)
+    var y = sy * (positions[2*i+1] - ty)
+    var s = sizes[i]
+    var r = colors[4*i]   * 255.0
+    var g = colors[4*i+1] * 255.0
+    var b = colors[4*i+2] * 255.0
+    var a = colors[4*i+3] * 255.0
+
+    var gx = 0.5*(border.bounds[0] + border.bounds[2])
+    var gy = 0.5*(border.bounds[1] + border.bounds[3])
+
+    for(var j=0; j<glyph.data.length; j+=2) {
+      v_position[2*ptr]   = x
+      v_position[2*ptr+1] = y
+      v_offset[2*ptr]     = -s * (glyph.data[j]   - gx)
+      v_offset[2*ptr+1]   = -s * (glyph.data[j+1] - gy)
+      v_color[4*ptr]      = r
+      v_color[4*ptr+1]    = g
+      v_color[4*ptr+2]    = b
+      v_color[4*ptr+3]    = a
+      v_ids[ptr]          = i
+
+      ptr += 1
+    }
+
+    var w = borderWidths[i]
+    r = borderColors[4*i]   * 255.0
+    g = borderColors[4*i+1] * 255.0
+    b = borderColors[4*i+2] * 255.0
+    a = borderColors[4*i+3] * 255.0
+
+    for(var j=0; j<border.coords.length; j+=2) {
+      v_position[2*ptr]   = x
+      v_position[2*ptr+1] = y
+      v_offset[2*ptr]     = -(s*(border.coords[j]  -gx)+w*border.normals[j])
+      v_offset[2*ptr+1]   = -(s*(border.coords[j+1]-gy)+w*border.normals[j+1])
+      v_color[4*ptr]      = r
+      v_color[4*ptr+1]    = g
+      v_color[4*ptr+2]    = b
+      v_color[4*ptr+3]    = a
+      v_ids[ptr]          = i
+
+      ptr += 1
+    }
+  }
+
+  this.numPoints = glyphs.length
+  this.numVertices = numVertices
+
+  this.positionBuffer.update(v_position)
+  this.offsetBuffer.update(v_offset)
+  this.colorBuffer.update(v_color)
+  this.idBuffer.update(v_ids)
+
+  pool.free(v_position)
+  pool.free(v_offset)
+  pool.free(v_color)
+  pool.free(v_ids)
+}
+
+proto.dispose = function() {
+  this.shader.dispose()
+  this.pickShader.dispose()
+  this.positionBuffer.dispose()
+  this.offsetBuffer.dispose()
+  this.colorBuffer.dispose()
+  this.idBuffer.dispose()
+  this.plot.removeObject(this)
+}
+
+function createFancyScatter2D(plot, options) {
+  var gl = plot.gl
+
+  var shader      = createShader(gl, shaders.vertex,     shaders.fragment)
+  var pickShader  = createShader(gl, shaders.pickVertex, shaders.pickFragment)
+
+  var positionBuffer  = createBuffer(gl)
+  var offsetBuffer    = createBuffer(gl)
+  var colorBuffer     = createBuffer(gl)
+  var idBuffer        = createBuffer(gl)
+
+  var scatter = new GLScatterFancy(
+    plot,
+    shader,
+    pickShader,
+    positionBuffer,
+    offsetBuffer,
+    colorBuffer,
+    idBuffer)
+
+  scatter.update(options)
+
+  plot.addObject(scatter)
+
+  return scatter
+}
+
+},{"./lib/shaders":141,"gl-buffer":75,"gl-shader":154,"text-cache":228,"typedarray-pool":233,"vectorize-text":235}],143:[function(require,module,exports){
+
+
+exports.pointVertex       = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 position;\nattribute float weight;\n\nuniform mat3 matrix;\nuniform float pointSize, useWeight;\n\nvarying float fragWeight;\n\nvoid main() {\n  vec3 hgPosition = matrix * vec3(position, 1);\n  gl_Position  = vec4(hgPosition.xy, 0, hgPosition.z);\n  gl_PointSize = pointSize;\n  fragWeight = mix(1.0, weight, useWeight);\n}\n"
+exports.pointFragment     = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\n\nvarying float fragWeight;\n\nfloat smoothStep(float x, float y) {\n  return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n  float radius = length(2.0*gl_PointCoord.xy-1.0);\n  if(radius > 1.0) {\n    discard;\n  }\n  vec4 baseColor = mix(borderColor, color, smoothStep(radius, centerFraction));\n  float alpha = 1.0 - pow(1.0 - baseColor.a, fragWeight);\n  gl_FragColor = vec4(baseColor.rgb * alpha, alpha);\n}\n"
+exports.pickVertex        = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n  vec3 hgPosition = matrix * vec3(position, 1);\n  gl_Position  = vec4(hgPosition.xy, 0, hgPosition.z);\n  gl_PointSize = pointSize;\n\n  vec4 id = pickId + pickOffset;\n  id.y += floor(id.x / 256.0);\n  id.x -= floor(id.x / 256.0) * 256.0;\n\n  id.z += floor(id.y / 256.0);\n  id.y -= floor(id.y / 256.0) * 256.0;\n\n  id.w += floor(id.z / 256.0);\n  id.z -= floor(id.z / 256.0) * 256.0;\n\n  fragId = id;\n}\n"
+exports.pickFragment      = "#define GLSLIFY 1\nprecision mediump float;\n\nvarying vec4 fragId;\n\nvoid main() {\n  float radius = length(2.0*gl_PointCoord.xy-1.0);\n  if(radius > 1.0) {\n    discard;\n  }\n  gl_FragColor = fragId / 255.0;\n}\n"
+
+},{}],144:[function(require,module,exports){
+arguments[4][121][0].apply(exports,arguments)
+},{"dup":121}],145:[function(require,module,exports){
+'use strict'
+
+module.exports = sortLevels
+
+var INSERT_SORT_CUTOFF = 32
+
+function sortLevels(data_levels, data_points, data_ids, data_weights, n0) {
+  if (n0 <= 4*INSERT_SORT_CUTOFF) {
+    insertionSort(0, n0 - 1, data_levels, data_points, data_ids, data_weights)
+  } else {
+    quickSort(0, n0 - 1, data_levels, data_points, data_ids, data_weights)
+  }
+}
+
+function insertionSort(left, right, data_levels, data_points, data_ids, data_weights) {
+  for(var i=left+1; i<=right; ++i) {
+    var a_level  = data_levels[i]
+    var a_x      = data_points[2*i]
+    var a_y      = data_points[2*i+1]
+    var a_id     = data_ids[i]
+    var a_weight = data_weights[i]
+
+    var j = i
+    while(j > left) {
+      var b_level = data_levels[j-1]
+      var b_x     = data_points[2*(j-1)]
+      if(((b_level - a_level) || (a_x - b_x)) >= 0) {
+        break
+      }
+      data_levels[j]      = b_level
+      data_points[2*j]    = b_x
+      data_points[2*j+1]  = data_points[2*j-1]
+      data_ids[j]         = data_ids[j-1]
+      data_weights[j]     = data_weights[j-1]
+      j -= 1
+    }
+
+    data_levels[j]     = a_level
+    data_points[2*j]   = a_x
+    data_points[2*j+1] = a_y
+    data_ids[j]        = a_id
+    data_weights[j]    = a_weight
+  }
+}
+
+function swap(i, j, data_levels, data_points, data_ids, data_weights) {
+  var a_level = data_levels[i]
+  var a_x     = data_points[2*i]
+  var a_y     = data_points[2*i+1]
+  var a_id    = data_ids[i]
+  var a_weight = data_weights[i]
+
+  data_levels[i]     = data_levels[j]
+  data_points[2*i]   = data_points[2*j]
+  data_points[2*i+1] = data_points[2*j+1]
+  data_ids[i]        = data_ids[j]
+  data_weights[i]    = data_weights[j]
+
+  data_levels[j]     = a_level
+  data_points[2*j]   = a_x
+  data_points[2*j+1] = a_y
+  data_ids[j]        = a_id
+  data_weights[j]    = a_weight
+}
+
+function move(i, j, data_levels, data_points, data_ids, data_weights) {
+  data_levels[i]     = data_levels[j]
+  data_points[2*i]   = data_points[2*j]
+  data_points[2*i+1] = data_points[2*j+1]
+  data_ids[i]        = data_ids[j]
+  data_weights[i]    = data_weights[j]
+}
+
+function rotate(i, j, k, data_levels, data_points, data_ids, data_weights) {
+  var a_level = data_levels[i]
+  var a_x     = data_points[2*i]
+  var a_y     = data_points[2*i+1]
+  var a_id    = data_ids[i]
+  var a_weight = data_weights[i]
+
+  data_levels[i]     = data_levels[j]
+  data_points[2*i]   = data_points[2*j]
+  data_points[2*i+1] = data_points[2*j+1]
+  data_ids[i]        = data_ids[j]
+  data_weights[i]    = data_weights[j]
+
+  data_levels[j]     = data_levels[k]
+  data_points[2*j]   = data_points[2*k]
+  data_points[2*j+1] = data_points[2*k+1]
+  data_ids[j]        = data_ids[k]
+  data_weights[j]    = data_weights[k]
+
+  data_levels[k]     = a_level
+  data_points[2*k]   = a_x
+  data_points[2*k+1] = a_y
+  data_ids[k]        = a_id
+  data_weights[k]    = a_weight
+}
+
+function shufflePivot(
+  i, j,
+  a_level, a_x, a_y, a_id, a_weight,
+  data_levels, data_points, data_ids, data_weights) {
+
+  data_levels[i]     = data_levels[j]
+  data_points[2*i]   = data_points[2*j]
+  data_points[2*i+1] = data_points[2*j+1]
+  data_ids[i]        = data_ids[j]
+  data_weights[i]    = data_weights[j]
+
+  data_levels[j]     = a_level
+  data_points[2*j]   = a_x
+  data_points[2*j+1] = a_y
+  data_ids[j]        = a_id
+  data_weights[j]    = a_weight
+}
+
+function compare(i, j, data_levels, data_points, data_ids) {
+  return ((data_levels[i] - data_levels[j]) ||
+          (data_points[2*j] - data_points[2*i]) ||
+          (data_ids[i] - data_ids[j])) < 0
+}
+
+function comparePivot(i, level, x, y, id, data_levels, data_points, data_ids) {
+  return ((level - data_levels[i]) ||
+          (data_points[2*i] - x) ||
+          (id - data_ids[i])) < 0
+}
+
+function quickSort(left, right, data_levels, data_points, data_ids, data_weights) {
+  var sixth = (right - left + 1) / 6 | 0,
+      index1 = left + sixth,
+      index5 = right - sixth,
+      index3 = left + right >> 1,
+      index2 = index3 - sixth,
+      index4 = index3 + sixth,
+      el1 = index1,
+      el2 = index2,
+      el3 = index3,
+      el4 = index4,
+      el5 = index5,
+      less = left + 1,
+      great = right - 1,
+      tmp = 0
+  if(compare(el1, el2, data_levels, data_points, data_ids, data_weights)) {
+    tmp = el1
+    el1 = el2
+    el2 = tmp
+  }
+  if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) {
+    tmp = el4
+    el4 = el5
+    el5 = tmp
+  }
+  if(compare(el1, el3, data_levels, data_points, data_ids, data_weights)) {
+    tmp = el1
+    el1 = el3
+    el3 = tmp
+  }
+  if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) {
+    tmp = el2
+    el2 = el3
+    el3 = tmp
+  }
+  if(compare(el1, el4, data_levels, data_points, data_ids, data_weights)) {
+    tmp = el1
+    el1 = el4
+    el4 = tmp
+  }
+  if(compare(el3, el4, data_levels, data_points, data_ids, data_weights)) {
+    tmp = el3
+    el3 = el4
+    el4 = tmp
+  }
+  if(compare(el2, el5, data_levels, data_points, data_ids, data_weights)) {
+    tmp = el2
+    el2 = el5
+    el5 = tmp
+  }
+  if(compare(el2, el3, data_levels, data_points, data_ids, data_weights)) {
+    tmp = el2
+    el2 = el3
+    el3 = tmp
+  }
+  if(compare(el4, el5, data_levels, data_points, data_ids, data_weights)) {
+    tmp = el4
+    el4 = el5
+    el5 = tmp
+  }
+
+  var pivot1_level  = data_levels[el2]
+  var pivot1_x      = data_points[2*el2]
+  var pivot1_y      = data_points[2*el2+1]
+  var pivot1_id     = data_ids[el2]
+  var pivot1_weight = data_weights[el2]
+
+  var pivot2_level  = data_levels[el4]
+  var pivot2_x      = data_points[2*el4]
+  var pivot2_y      = data_points[2*el4+1]
+  var pivot2_id     = data_ids[el4]
+  var pivot2_weight = data_weights[el4]
+
+  var ptr0 = el1
+  var ptr2 = el3
+  var ptr4 = el5
+  var ptr5 = index1
+  var ptr6 = index3
+  var ptr7 = index5
+
+  var level_x = data_levels[ptr0]
+  var level_y = data_levels[ptr2]
+  var level_z = data_levels[ptr4]
+  data_levels[ptr5] = level_x
+  data_levels[ptr6] = level_y
+  data_levels[ptr7] = level_z
+
+  for (var i1 = 0; i1 < 2; ++i1) {
+    var x = data_points[2*ptr0+i1]
+    var y = data_points[2*ptr2+i1]
+    var z = data_points[2*ptr4+i1]
+    data_points[2*ptr5+i1] = x
+    data_points[2*ptr6+i1] = y
+    data_points[2*ptr7+i1] = z
+  }
+
+  var id_x = data_ids[ptr0]
+  var id_y = data_ids[ptr2]
+  var id_z = data_ids[ptr4]
+  data_ids[ptr5] = id_x
+  data_ids[ptr6] = id_y
+  data_ids[ptr7] = id_z
+
+  var weight_x = data_weights[ptr0]
+  var weight_y = data_weights[ptr2]
+  var weight_z = data_weights[ptr4]
+  data_weights[ptr5] = weight_x
+  data_weights[ptr6] = weight_y
+  data_weights[ptr7] = weight_z
+
+  move(index2, left,  data_levels, data_points, data_ids, data_weights)
+  move(index4, right, data_levels, data_points, data_ids, data_weights)
+  for (var k = less; k <= great; ++k) {
+    if (comparePivot(k,
+        pivot1_level, pivot1_x, pivot1_y, pivot1_id,
+        data_levels, data_points, data_ids)) {
+      if (k !== less) {
+        swap(k, less, data_levels, data_points, data_ids, data_weights)
+      }
+      ++less;
+    } else {
+      if (!comparePivot(k,
+          pivot2_level, pivot2_x, pivot2_y, pivot2_id,
+          data_levels, data_points, data_ids)) {
+        while (true) {
+          if (!comparePivot(great,
+              pivot2_level, pivot2_x, pivot2_y, pivot2_id,
+              data_levels, data_points, data_ids)) {
+            if (--great < k) {
+              break;
+            }
+            continue;
+          } else {
+            if (comparePivot(great,
+                pivot1_level, pivot1_x, pivot1_y, pivot1_id,
+                data_levels, data_points, data_ids)) {
+              rotate(k, less, great, data_levels, data_points, data_ids, data_weights)
+              ++less;
+              --great;
+            } else {
+              swap(k, great, data_levels, data_points, data_ids, data_weights)
+              --great;
+            }
+            break;
+          }
+        }
+      }
+    }
+  }
+  shufflePivot(left, less-1, pivot1_level, pivot1_x, pivot1_y, pivot1_id, pivot1_weight, data_levels, data_points, data_ids, data_weights)
+  shufflePivot(right, great+1, pivot2_level, pivot2_x, pivot2_y, pivot2_id, pivot2_weight, data_levels, data_points, data_ids, data_weights)
+  if (less - 2 - left <= INSERT_SORT_CUTOFF) {
+    insertionSort(left, less - 2, data_levels, data_points, data_ids, data_weights)
+  } else {
+    quickSort(left, less - 2, data_levels, data_points, data_ids, data_weights)
+  }
+  if (right - (great + 2) <= INSERT_SORT_CUTOFF) {
+    insertionSort(great + 2, right, data_levels, data_points, data_ids, data_weights)
+  } else {
+    quickSort(great + 2, right, data_levels, data_points, data_ids, data_weights)
+  }
+  if (great - less <= INSERT_SORT_CUTOFF) {
+    insertionSort(less, great, data_levels, data_points, data_ids, data_weights)
+  } else {
+    quickSort(less, great, data_levels, data_points, data_ids, data_weights)
+  }
+}
+
+},{}],146:[function(require,module,exports){
+'use strict'
+
+var pool = require('typedarray-pool')
+
+var sortLevels = require('./lib/sort')
+
+module.exports = snapPoints
+
+function partition(points, ids, start, end, lox, loy, hix, hiy) {
+  var mid = start
+  for(var i=start; i<end; ++i) {
+    var x  = points[2*i]
+    var y  = points[2*i+1]
+    var s  = ids[i]
+    if(lox <= x && x <= hix &&
+       loy <= y && y <= hiy) {
+      if(i === mid) {
+        mid += 1
+      } else {
+        points[2*i]     = points[2*mid]
+        points[2*i+1]   = points[2*mid+1]
+        ids[i]          = ids[mid]
+        points[2*mid]   = x
+        points[2*mid+1] = y
+        ids[mid]        = s
+        mid += 1
+      }
+    }
+  }
+  return mid
+}
+
+function SnapInterval(pixelSize, offset, count) {
+  this.pixelSize  = pixelSize
+  this.offset     = offset
+  this.count      = count
+}
+
+function snapPoints(points, ids, weights, bounds) {
+  var n    = points.length >>> 1
+  if(n < 1) {
+    return []
+  }
+
+  var lox =  Infinity, loy =  Infinity
+  var hix = -Infinity, hiy = -Infinity
+  for(var i=0; i<n; ++i) {
+    var x = points[2*i]
+    var y = points[2*i+1]
+    lox = Math.min(lox, x)
+    hix = Math.max(hix, x)
+    loy = Math.min(loy, y)
+    hiy = Math.max(hiy, y)
+    ids[i] = i
+  }
+
+  if(lox === hix) {
+    hix += 1 + Math.abs(hix)
+  }
+  if(loy === hiy) {
+    hiy += 1 + Math.abs(hix)
+  }
+
+  //Calculate diameter
+  var scaleX = 1.0 / (hix - lox)
+  var scaleY = 1.0 / (hiy - loy)
+  var diam = Math.max(hix - lox, hiy - loy)
+
+  bounds = bounds || [0,0,0,0]
+
+  bounds[0] = lox
+  bounds[1] = loy
+  bounds[2] = hix
+  bounds[3] = hiy
+
+  var levels = pool.mallocInt32(n)
+  var ptr = 0
+
+  function snapRec(x, y, diam, start, end, level) {
+    var diam_2 = diam * 0.5
+    var offset = start + 1
+    var count = end - start
+    weights[ptr] = count
+    levels[ptr++] = level
+    for(var i=0; i<2; ++i) {
+      for(var j=0; j<2; ++j) {
+        var nx = x+i*diam_2
+        var ny = y+j*diam_2
+        var nextOffset = partition(
+            points
+          , ids
+          , offset
+          , end
+          , nx, ny
+          , nx+diam_2, ny+diam_2)
+        if(nextOffset === offset) {
+          continue
+        }
+        if(nextOffset - offset >= Math.max(0.9 * count, 32)) {
+          var mid = (end + start)>>>1
+          snapRec(nx, ny, diam_2, offset, mid, level+1)
+          offset = mid
+        }
+        snapRec(nx, ny, diam_2, offset, nextOffset, level+1)
+        offset = nextOffset
+      }
+    }
+  }
+  snapRec(lox, loy, diam, 0, n, 0)
+  sortLevels(levels, points, ids, weights, n)
+
+  var lod         = []
+  var lastLevel   = 0
+  var prevOffset  = n
+  for(var ptr=n-1; ptr>=0; --ptr) {
+    points[2*ptr]   = (points[2*ptr]   - lox) * scaleX
+    points[2*ptr+1] = (points[2*ptr+1] - loy) * scaleY
+
+    var level = levels[ptr]
+    if(level === lastLevel) {
+      continue
+    }
+
+    lod.push(new SnapInterval(
+      diam * Math.pow(0.5, level),
+      ptr+1,
+      prevOffset - (ptr+1)
+    ))
+    prevOffset = ptr+1
+
+    lastLevel = level
+  }
+
+  lod.push(new SnapInterval(diam * Math.pow(0.5, level+1), 0, prevOffset))
+  pool.free(levels)
+
+  return lod
+}
+
+},{"./lib/sort":145,"typedarray-pool":233}],147:[function(require,module,exports){
+'use strict'
+
+var createShader = require('gl-shader')
+var createBuffer = require('gl-buffer')
+var bsearch = require('binary-search-bounds')
+var snapPoints = require('snap-points-2d')
+
+var pool = require('typedarray-pool')
+
+var SHADERS = require('./lib/shader')
+
+module.exports = createScatter2D
+
+function Scatter2D(plot, offsetBuffer, pickBuffer, weightBuffer, shader, pickShader) {
+  this.plot           = plot
+  this.offsetBuffer   = offsetBuffer
+  this.pickBuffer     = pickBuffer
+  this.weightBuffer   = weightBuffer
+  this.shader         = shader
+  this.pickShader     = pickShader
+  this.scales         = []
+  this.size           = 12.0
+  this.borderSize     = 1.0
+  this.pointCount     = 0
+  this.color          = [1,0,0,1]
+  this.borderColor    = [0,0,0,1]
+  this.bounds         = [Infinity,Infinity,-Infinity,-Infinity]
+  this.pickOffset     = 0
+  this.points         = null
+  this.xCoords        = null
+}
+
+var proto = Scatter2D.prototype
+
+proto.dispose = function() {
+  this.shader.dispose()
+  this.pickShader.dispose()
+  this.offsetBuffer.dispose()
+  this.pickBuffer.dispose()
+  if(this.xCoords) {
+    pool.free(this.xCoords)
+  }
+  this.plot.removeObject(this)
+}
+
+proto.update = function(options) {
+  options = options || {}
+
+  function dflt(opt, value) {
+    if(opt in options) {
+      return options[opt]
+    }
+    return value
+  }
+
+  this.size         = dflt('size', 12.0)
+  this.color        = dflt('color', [1,0,0,1]).slice()
+  this.borderSize   = dflt('borderSize', 1)
+  this.borderColor  = dflt('borderColor', [0,0,0,1]).slice()
+
+  //Update point data
+  if(this.xCoords) {
+    pool.free(this.xCoords)
+  }
+  var data          = options.positions
+  var packed        = pool.mallocFloat32(data.length)
+  var packedId      = pool.mallocInt32(data.length>>>1)
+  packed.set(data)
+  var packedW       = pool.mallocFloat32(data.length)
+  this.points       = data
+  this.scales       = snapPoints(packed, packedId, packedW, this.bounds)
+  this.offsetBuffer.update(packed)
+  this.pickBuffer.update(packedId)
+  this.weightBuffer.update(packedW)
+  var xCoords      = pool.mallocFloat32(data.length>>>1)
+  for(var i=0,j=0; i<data.length; i+=2,++j) {
+    xCoords[j] = packed[i]
+  }
+  pool.free(packedId)
+  pool.free(packed)
+  pool.free(packedW)
+
+  this.xCoords = xCoords
+
+  this.pointCount = data.length >>> 1
+  this.pickOffset = 0
+}
+
+proto.drawPick = (function() {
+  var MATRIX = [1,0,0,
+                0,1,0,
+                0,0,1]
+  var PICK_VEC4 = [0,0,0,0]
+return function(pickOffset) {
+  var plot          = this.plot
+  var shader        = this.pickShader
+  var scales        = this.scales
+  var offsetBuffer  = this.offsetBuffer
+  var pickBuffer    = this.pickBuffer
+  var bounds        = this.bounds
+  var size          = this.size
+  var borderSize    = this.borderSize
+  var gl            = plot.gl
+  var pixelRatio    = plot.pickPixelRatio
+  var viewBox       = plot.viewBox
+  var dataBox       = plot.dataBox
+
+  if(this.pointCount === 0) {
+    return pickOffset
+  }
+
+  var boundX  = bounds[2] - bounds[0]
+  var boundY  = bounds[3] - bounds[1]
+  var dataX   = dataBox[2] - dataBox[0]
+  var dataY   = dataBox[3] - dataBox[1]
+  var screenX = (viewBox[2] - viewBox[0]) * pixelRatio / plot.pixelRatio
+  var screenY = (viewBox[3] - viewBox[1]) * pixelRatio / plot.pixelRatio
+
+  var pixelSize   = Math.min(dataX / screenX, dataY / screenY)
+  var targetScale = pixelSize
+
+
+  MATRIX[0] = 2.0 * boundX / dataX
+  MATRIX[4] = 2.0 * boundY / dataY
+  MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0
+  MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0
+
+  this.pickOffset = pickOffset
+  PICK_VEC4[0] = ( pickOffset      & 0xff)
+  PICK_VEC4[1] = ((pickOffset>>8)  & 0xff)
+  PICK_VEC4[2] = ((pickOffset>>16) & 0xff)
+  PICK_VEC4[3] = ((pickOffset>>24) & 0xff)
+
+  shader.bind()
+  shader.uniforms.matrix      = MATRIX
+  shader.uniforms.color       = this.color
+  shader.uniforms.borderColor = this.borderColor
+  shader.uniforms.pointSize   = pixelRatio * (size + borderSize)
+  shader.uniforms.pickOffset  = PICK_VEC4
+
+  if(this.borderSize === 0) {
+    shader.uniforms.centerFraction = 2.0;
+  } else {
+    shader.uniforms.centerFraction = size / (size + borderSize + 1.25)
+  }
+
+  offsetBuffer.bind()
+  shader.attributes.position.pointer()
+  pickBuffer.bind()
+  shader.attributes.pickId.pointer(gl.UNSIGNED_BYTE)
+
+  var xCoords = this.xCoords
+  var xStart = (dataBox[0] - bounds[0] - pixelSize * size * pixelRatio) / boundX
+  var xEnd   = (dataBox[2] - bounds[0] + pixelSize * size * pixelRatio) / boundX
+
+  for(var scaleNum = scales.length-1; scaleNum >= 0; --scaleNum) {
+    var lod     = scales[scaleNum]
+    if(lod.pixelSize < pixelSize && scaleNum > 1) {
+      continue
+    }
+
+    var intervalStart = lod.offset
+    var intervalEnd   = lod.count + intervalStart
+
+    var startOffset = bsearch.ge(xCoords, xStart, intervalStart, intervalEnd-1)
+    var endOffset   = bsearch.lt(xCoords, xEnd, startOffset, intervalEnd-1)+1
+
+    gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset)
+  }
+
+  return pickOffset + this.pointCount
+}
+})()
+
+proto.draw = (function() {
+  var MATRIX = [1, 0, 0,
+                0, 1, 0,
+                0, 0, 1]
+
+  return function() {
+    var plot          = this.plot
+    var shader        = this.shader
+    var scales        = this.scales
+    var offsetBuffer  = this.offsetBuffer
+    var bounds        = this.bounds
+    var size          = this.size
+    var borderSize    = this.borderSize
+    var gl            = plot.gl
+    var pixelRatio    = plot.pixelRatio
+    var viewBox       = plot.viewBox
+    var dataBox       = plot.dataBox
+
+    if(this.pointCount === 0) {
+      return
+    }
+
+    var boundX  = bounds[2] - bounds[0]
+    var boundY  = bounds[3] - bounds[1]
+    var dataX   = dataBox[2] - dataBox[0]
+    var dataY   = dataBox[3] - dataBox[1]
+    var screenX = viewBox[2] - viewBox[0]
+    var screenY = viewBox[3] - viewBox[1]
+
+    var pixelSize   = Math.min(dataX / screenX, dataY / screenY)
+    var targetScale = pixelSize
+
+    MATRIX[0] = 2.0 * boundX / dataX
+    MATRIX[4] = 2.0 * boundY / dataY
+    MATRIX[6] = 2.0 * (bounds[0] - dataBox[0]) / dataX - 1.0
+    MATRIX[7] = 2.0 * (bounds[1] - dataBox[1]) / dataY - 1.0
+
+    shader.bind()
+    shader.uniforms.matrix      = MATRIX
+    shader.uniforms.color       = this.color
+    shader.uniforms.borderColor = this.borderColor
+    shader.uniforms.pointSize   = pixelRatio * (size + borderSize)
+    shader.uniforms.useWeight   = 1
+
+    if(this.borderSize === 0) {
+      shader.uniforms.centerFraction = 2.0;
+    } else {
+      shader.uniforms.centerFraction = size / (size + borderSize + 1.25)
+    }
+
+    offsetBuffer.bind()
+    shader.attributes.position.pointer()
+
+    this.weightBuffer.bind()
+    shader.attributes.weight.pointer()
+
+    var xCoords = this.xCoords
+    var xStart = (dataBox[0] - bounds[0] - pixelSize * size * pixelRatio) / boundX
+    var xEnd   = (dataBox[2] - bounds[0] + pixelSize * size * pixelRatio) / boundX
+
+    var firstLevel = true
+
+    for(var scaleNum = scales.length-1; scaleNum >= 0; --scaleNum) {
+      var lod     = scales[scaleNum]
+      if(lod.pixelSize < pixelSize && scaleNum > 1) {
+        continue
+      }
+
+      var intervalStart = lod.offset
+      var intervalEnd   = lod.count + intervalStart
+
+      var startOffset = bsearch.ge(xCoords, xStart, intervalStart, intervalEnd-1)
+      var endOffset   = bsearch.lt(xCoords, xEnd, startOffset, intervalEnd-1)+1
+
+      gl.drawArrays(gl.POINTS, startOffset, endOffset - startOffset)
+
+      if(firstLevel) {
+        firstLevel = false
+        shader.uniforms.useWeight = 0
+      }
+    }
+  }
+})()
+
+proto.pick = function(x, y, value) {
+  var pickOffset = this.pickOffset
+  var pointCount = this.pointCount
+  if(value < pickOffset || value >= pickOffset + pointCount) {
+    return null
+  }
+  var pointId = value - pickOffset
+  var points = this.points
+  return {
+    object:  this,
+    pointId: pointId,
+    dataCoord: [ points[2*pointId], points[2*pointId+1] ]
+  }
+}
+
+function createScatter2D(plot, options) {
+  var gl     = plot.gl
+  var buffer = createBuffer(gl)
+  var pickBuffer = createBuffer(gl)
+  var weightBuffer = createBuffer(gl)
+  var shader = createShader(gl, SHADERS.pointVertex, SHADERS.pointFragment)
+  var pickShader = createShader(gl, SHADERS.pickVertex, SHADERS.pickFragment)
+
+  var result = new Scatter2D(
+    plot, buffer, pickBuffer, weightBuffer, shader, pickShader)
+  result.update(options)
+
+  //Register with plot
+  plot.addObject(result)
+
+  return result
+}
+
+},{"./lib/shader":143,"binary-search-bounds":144,"gl-buffer":75,"gl-shader":154,"snap-points-2d":146,"typedarray-pool":233}],148:[function(require,module,exports){
+"use strict"
+
+var vectorizeText = require("vectorize-text")
+
+module.exports = getGlyph
+
+var GLYPH_CACHE = {}
+
+function getGlyph(symbol, font) {
+  var fontCache = GLYPH_CACHE[font]
+  if(!fontCache) {
+    fontCache = GLYPH_CACHE[font] = {}
+  }
+  if(symbol in fontCache) {
+    return fontCache[symbol]
+  }
+
+  //Get line and triangle meshes for glyph
+  var lineSymbol = vectorizeText(symbol, {
+      textAlign: "center",
+      textBaseline: "middle",
+      lineHeight: 1.0,
+      font: font
+    }) 
+  var triSymbol = vectorizeText(symbol, {
+      triangles: true,
+      textAlign: "center",
+      textBaseline: "middle",
+      lineHeight: 1.0,
+      font: font
+    })
+
+  //Calculate bounding box
+  var bounds = [[Infinity,Infinity], [-Infinity,-Infinity]]
+  for(var i=0; i<lineSymbol.positions.length; ++i) {
+    var p = lineSymbol.positions[i]
+    for(var j=0; j<2; ++j) {
+      bounds[0][j] = Math.min(bounds[0][j], p[j])
+      bounds[1][j] = Math.max(bounds[1][j], p[j])
+    }
+  }
+
+  //Save cached symbol
+  return fontCache[symbol] = [triSymbol, lineSymbol, bounds]
+}
+},{"vectorize-text":235}],149:[function(require,module,exports){
+var createShaderWrapper = require('gl-shader')
+
+
+var perspectiveVertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if(any(lessThan(position, clipBounds[0]))   || \n     any(greaterThan(position, clipBounds[1])) ) {\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float scale = 1.0;\n    if(distance(highlightId, id) < 0.0001) {\n      scale = highlightScale;\n    }\n\n    vec4 worldPosition = model * vec4(position, 1);\n    vec4 viewPosition = view * worldPosition;\n    viewPosition = viewPosition / viewPosition.w;\n    vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n    \n    gl_Position = clipPosition;\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = position;\n  }\n}"
+var orthographicVertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if(any(lessThan(position, clipBounds[0])) || any(greaterThan(position, clipBounds[1]))) {\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float scale = pixelRatio;\n    if(distance(highlightId.bgr, id.bgr) < 0.001) {\n      scale *= highlightScale;\n    }\n\n    vec4 worldPosition = model * vec4(position, 1.0);\n    vec4 viewPosition = view * worldPosition;\n    vec4 clipPosition = projection * viewPosition;\n    clipPosition /= clipPosition.w;\n    \n    gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = position;\n  }\n}"
+var projectionVertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if(any(lessThan(position, clipBounds[0]))   ||\n     any(greaterThan(position, clipBounds[1])) ) {\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float lscale = pixelRatio * scale;\n    if(distance(highlightId, id) < 0.0001) {\n      lscale *= highlightScale;\n    }\n\n    vec4 clipCenter   = projection * view * model * vec4(position, 1);\n    vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n    vec4 clipPosition = projection * view * model * vec4(dataPosition, 1);\n\n    gl_Position = clipPosition;\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = dataPosition;\n  }\n}\n"
+var drawFragSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if(any(lessThan(dataCoordinate, fragClipBounds[0]))   ||\n     any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n    discard;\n  } else {\n    gl_FragColor = interpColor * opacity;\n  }\n}\n"
+var pickFragSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if(any(lessThan(dataCoordinate, fragClipBounds[0]))   || \n     any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n    discard;\n  } else {\n    gl_FragColor = vec4(pickGroup, pickId.bgr);\n  }\n}"
+
+var ATTRIBUTES = [
+  {name: 'position', type: 'vec3'},
+  {name: 'color', type: 'vec4'},
+  {name: 'glyph', type: 'vec2'},
+  {name: 'id', type: 'vec4'}
+]
+
+var perspective = {
+    vertex: perspectiveVertSrc,
+    fragment: drawFragSrc,
+    attributes: ATTRIBUTES
+  },
+  ortho = {
+    vertex: orthographicVertSrc,
+    fragment: drawFragSrc,
+    attributes: ATTRIBUTES
+  },
+  project = {
+    vertex: projectionVertSrc,
+    fragment: drawFragSrc,
+    attributes: ATTRIBUTES
+  },
+  pickPerspective = {
+    vertex: perspectiveVertSrc,
+    fragment: pickFragSrc,
+    attributes: ATTRIBUTES
+  },
+  pickOrtho = {
+    vertex: orthographicVertSrc,
+    fragment: pickFragSrc,
+    attributes: ATTRIBUTES
+  },
+  pickProject = {
+    vertex: projectionVertSrc,
+    fragment: pickFragSrc,
+    attributes: ATTRIBUTES
+  }
+
+function createShader(gl, src) {
+  var shader = createShaderWrapper(gl, src)
+  var attr = shader.attributes
+  attr.position.location = 0
+  attr.color.location = 1
+  attr.glyph.location = 2
+  attr.id.location = 3
+  return shader
+}
+
+exports.createPerspective = function(gl) {
+  return createShader(gl, perspective)
+}
+exports.createOrtho = function(gl) {
+  return createShader(gl, ortho)
+}
+exports.createProject = function(gl) {
+  return createShader(gl, project)
+}
+exports.createPickPerspective = function(gl) {
+  return createShader(gl, pickPerspective)
+}
+exports.createPickOrtho = function(gl) {
+  return createShader(gl, pickOrtho)
+}
+exports.createPickProject = function(gl) {
+  return createShader(gl, pickProject)
+}
+
+},{"gl-shader":154}],150:[function(require,module,exports){
+'use strict'
+
+var createBuffer  = require('gl-buffer')
+var createVAO     = require('gl-vao')
+var pool          = require('typedarray-pool')
+var mat4mult      = require('gl-mat4/multiply')
+var shaders       = require('./lib/shaders')
+var getGlyph      = require('./lib/glyphs')
+
+var IDENTITY = [1,0,0,0,
+                0,1,0,0,
+                0,0,1,0,
+                0,0,0,1]
+
+module.exports = createPointCloud
+
+function transformMat4(x, m) {
+  var x0 = x[0]
+  var x1 = x[1]
+  var x2 = x[2]
+  var x3 = x[3]
+  x[0] = m[0] * x0 + m[4] * x1 + m[8]  * x2 + m[12] * x3
+  x[1] = m[1] * x0 + m[5] * x1 + m[9]  * x2 + m[13] * x3
+  x[2] = m[2] * x0 + m[6] * x1 + m[10] * x2 + m[14] * x3
+  x[3] = m[3] * x0 + m[7] * x1 + m[11] * x2 + m[15] * x3
+  return x
+}
+
+function project(p, v, m, x) {
+  transformMat4(x, x, m)
+  transformMat4(x, x, v)
+  return transformMat4(x, x, p)
+}
+
+function clampVec(v) {
+  var result = new Array(3)
+  for(var i=0; i<3; ++i) {
+    result[i] = Math.min(Math.max(v[i], -1e8), 1e8)
+  }
+  return result
+}
+
+function ScatterPlotPickResult(index, position) {
+  this.index = index
+  this.dataCoordinate = this.position = position
+}
+
+function PointCloud(
+  gl,
+  shader,
+  orthoShader,
+  projectShader,
+  pointBuffer,
+  colorBuffer,
+  glyphBuffer,
+  idBuffer,
+  vao,
+  pickPerspectiveShader,
+  pickOrthoShader,
+  pickProjectShader) {
+
+  this.gl              = gl
+
+  this.pixelRatio      = 1
+
+  this.shader          = shader
+  this.orthoShader     = orthoShader
+  this.projectShader   = projectShader
+
+  this.pointBuffer     = pointBuffer
+  this.colorBuffer     = colorBuffer
+  this.glyphBuffer     = glyphBuffer
+  this.idBuffer        = idBuffer
+  this.vao             = vao
+  this.vertexCount     = 0
+  this.lineVertexCount = 0
+
+  this.opacity         = 1.0
+
+  this.lineWidth       = 0
+  this.projectScale    = [2.0/3.0, 2.0/3.0, 2.0/3.0]
+  this.projectOpacity  = [1,1,1]
+
+  this.pickId                = 0
+  this.pickPerspectiveShader = pickPerspectiveShader
+  this.pickOrthoShader       = pickOrthoShader
+  this.pickProjectShader     = pickProjectShader
+  this.points                = []
+
+  this._selectResult = new ScatterPlotPickResult(0, [0,0,0])
+
+  this.useOrtho = true
+  this.bounds   = [[ Infinity,Infinity,Infinity],
+                   [-Infinity,-Infinity,-Infinity]]
+
+  //Axes projections
+  this.axesProject = [ true, true, true ]
+  this.axesBounds = [[-Infinity,-Infinity,-Infinity],
+                     [ Infinity, Infinity, Infinity]]
+
+  this.highlightId    = [1,1,1,1]
+  this.highlightScale = 2
+
+  this.clipBounds = [[-Infinity,-Infinity,-Infinity],
+                     [ Infinity, Infinity, Infinity]]
+
+  this.dirty = true
+}
+
+var proto = PointCloud.prototype
+
+proto.pickSlots = 1
+
+proto.setPickBase = function(pickBase) {
+  this.pickId = pickBase
+}
+
+proto.isTransparent = function() {
+  if(this.opacity < 1)  {
+    return true
+  }
+  for(var i=0; i<3; ++i) {
+    if(this.axesProject[i] && this.projectOpacity[i] < 1) {
+      return true
+    }
+  }
+  return false
+}
+
+proto.isOpaque = function() {
+  if(this.opacity >= 1)  {
+    return true
+  }
+  for(var i=0; i<3; ++i) {
+    if(this.axesProject[i] && this.projectOpacity[i] >= 1) {
+      return true
+    }
+  }
+  return false
+}
+
+var VIEW_SHAPE = [0,0]
+var U_VEC = [0,0,0]
+var V_VEC = [0,0,0]
+var MU_VEC = [0,0,0,1]
+var MV_VEC = [0,0,0,1]
+var SCRATCH_MATRIX = IDENTITY.slice()
+var SCRATCH_VEC = [0,0,0]
+var CLIP_BOUNDS = [[0,0,0], [0,0,0]]
+
+function zeroVec(a) {
+  a[0] = a[1] = a[2] = 0
+  return a
+}
+
+function augment(hg, af) {
+  hg[0] = af[0]
+  hg[1] = af[1]
+  hg[2] = af[2]
+  hg[3] = 1
+  return hg
+}
+
+function setComponent(out, v, i, x) {
+  out[0] = v[0]
+  out[1] = v[1]
+  out[2] = v[2]
+  out[i] = x
+  return out
+}
+
+function getClipBounds(bounds) {
+  var result = CLIP_BOUNDS
+  for(var i=0; i<2; ++i) {
+    for(var j=0; j<3; ++j) {
+      result[i][j] = Math.max(Math.min(bounds[i][j], 1e8), -1e8)
+    }
+  }
+  return result
+}
+
+function drawProject(shader, points, camera, transparent, forceDraw) {
+  var axesProject = points.axesProject
+
+  var gl         = points.gl
+  var uniforms   = shader.uniforms
+  var model      = camera.model      || IDENTITY
+  var view       = camera.view       || IDENTITY
+  var projection = camera.projection || IDENTITY
+  var bounds     = points.axesBounds
+  var clipBounds = getClipBounds(points.clipBounds)
+
+  var cubeAxis
+  if(points.axes) {
+    cubeAxis = points.axes.lastCubeProps.axis
+  } else {
+    cubeAxis = [1,1,1]
+  }
+
+  VIEW_SHAPE[0] = 2.0/gl.drawingBufferWidth
+  VIEW_SHAPE[1] = 2.0/gl.drawingBufferHeight
+
+  shader.bind()
+  uniforms.view           = view
+  uniforms.projection     = projection
+  uniforms.screenSize     = VIEW_SHAPE
+  uniforms.highlightId    = points.highlightId
+  uniforms.highlightScale = points.highlightScale
+  uniforms.clipBounds     = clipBounds
+  uniforms.pickGroup      = points.pickId / 255.0
+  uniforms.pixelRatio     = points.pixelRatio
+
+  for(var i=0; i<3; ++i) {
+    if(!axesProject[i]) {
+      continue
+    }
+    if((points.projectOpacity[i] < 1) !== transparent) {
+      continue
+    }
+
+    uniforms.scale          = points.projectScale[i]
+    uniforms.opacity        = points.projectOpacity[i]
+
+    //Project model matrix
+    var pmodel = SCRATCH_MATRIX
+    for(var j=0; j<16; ++j) {
+      pmodel[j] = 0
+    }
+    for(var j=0; j<4; ++j) {
+      pmodel[5*j] = 1
+    }
+    pmodel[5*i] = 0
+    if(cubeAxis[i] < 0) {
+      pmodel[12+i] = bounds[0][i]
+    } else {
+      pmodel[12+i] = bounds[1][i]
+    }
+    mat4mult(pmodel, model, pmodel)
+    uniforms.model = pmodel
+
+    //Compute initial axes
+    var u = (i+1)%3
+    var v = (i+2)%3
+    var du = zeroVec(U_VEC)
+    var dv = zeroVec(V_VEC)
+    du[u] = 1
+    dv[v] = 1
+
+    //Align orientation relative to viewer
+    var mdu = project(projection, view, model, augment(MU_VEC, du))
+    var mdv = project(projection, view, model, augment(MV_VEC, dv))
+    if(Math.abs(mdu[1]) > Math.abs(mdv[1])) {
+      var tmp = mdu
+      mdu = mdv
+      mdv = tmp
+      tmp = du
+      du = dv
+      dv = tmp
+      var t = u
+      u = v
+      v = t
+    }
+    if(mdu[0] < 0) {
+      du[u] = -1
+    }
+    if(mdv[1] > 0) {
+      dv[v] = -1
+    }
+    var su = 0.0
+    var sv = 0.0
+    for(var j=0; j<4; ++j) {
+      su += Math.pow(model[4*u+j], 2)
+      sv += Math.pow(model[4*v+j], 2)
+    }
+    du[u] /= Math.sqrt(su)
+    dv[v] /= Math.sqrt(sv)
+    uniforms.axes[0] = du
+    uniforms.axes[1] = dv
+
+    //Update fragment clip bounds
+    uniforms.fragClipBounds[0] = setComponent(SCRATCH_VEC, clipBounds[0], i, -1e8)
+    uniforms.fragClipBounds[1] = setComponent(SCRATCH_VEC, clipBounds[1], i, 1e8)
+
+    //Draw interior
+    points.vao.draw(gl.TRIANGLES, points.vertexCount)
+
+    //Draw edges
+    if(points.lineWidth > 0) {
+      gl.lineWidth(points.lineWidth)
+      points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount)
+    }
+  }
+}
+
+
+var NEG_INFINITY3 = [-1e8, -1e8, -1e8]
+var POS_INFINITY3 = [1e8, 1e8, 1e8]
+var CLIP_GROUP    = [NEG_INFINITY3, POS_INFINITY3]
+
+function drawFull(shader, pshader, points, camera, transparent, forceDraw) {
+  var gl = points.gl
+
+  points.vao.bind()
+
+  if(transparent === (points.opacity < 1) || forceDraw) {
+    shader.bind()
+    var uniforms = shader.uniforms
+
+    uniforms.model      = camera.model      || IDENTITY
+    uniforms.view       = camera.view       || IDENTITY
+    uniforms.projection = camera.projection || IDENTITY
+
+    VIEW_SHAPE[0]       = 2.0/gl.drawingBufferWidth
+    VIEW_SHAPE[1]       = 2.0/gl.drawingBufferHeight
+    uniforms.screenSize = VIEW_SHAPE
+
+    uniforms.highlightId    = points.highlightId
+    uniforms.highlightScale = points.highlightScale
+
+    uniforms.fragClipBounds = CLIP_GROUP
+    uniforms.clipBounds     = points.axes.bounds
+
+    uniforms.opacity    = points.opacity
+    uniforms.pickGroup  = points.pickId / 255.0
+
+    uniforms.pixelRatio = points.pixelRatio
+
+    //Draw interior
+    points.vao.draw(gl.TRIANGLES, points.vertexCount)
+
+    //Draw edges
+    if(points.lineWidth > 0) {
+      gl.lineWidth(points.lineWidth)
+      points.vao.draw(gl.LINES, points.lineVertexCount, points.vertexCount)
+    }
+  }
+
+  drawProject(pshader, points, camera, transparent, forceDraw)
+
+  points.vao.unbind()
+}
+
+proto.draw = function(camera) {
+  var shader = this.useOrtho ? this.orthoShader : this.shader
+  drawFull(shader, this.projectShader, this, camera, false, false)
+}
+
+proto.drawTransparent = function(camera) {
+  var shader = this.useOrtho ? this.orthoShader : this.shader
+  drawFull(shader, this.projectShader, this, camera, true, false)
+}
+
+proto.drawPick = function(camera) {
+  var shader = this.useOrtho ? this.pickOrthoShader : this.pickPerspectiveShader
+  drawFull(shader, this.pickProjectShader, this, camera, false, true)
+}
+
+proto.pick = function(selected) {
+  if(!selected) {
+    return null
+  }
+  if(selected.id !== this.pickId) {
+    return null
+  }
+  var x = selected.value[2] + (selected.value[1]<<8) + (selected.value[0]<<16)
+  if(x >= this.pointCount || x < 0) {
+    return null
+  }
+
+  //Unpack result
+  var coord = this.points[x]
+  var result = this._selectResult
+  result.index = x
+  for(var i=0; i<3; ++i) {
+    result.position[i] = result.dataCoordinate[i] = coord[i]
+  }
+  return result
+}
+
+proto.highlight = function(selection) {
+  if(!selection) {
+    this.highlightId = [1,1,1,1]
+  } else {
+    var pointId = selection.index
+    var a0 =  pointId     &0xff
+    var a1 = (pointId>>8) &0xff
+    var a2 = (pointId>>16)&0xff
+    this.highlightId = [a0/255.0, a1/255.0, a2/255.0, 0]
+  }
+}
+
+proto.update = function(options) {
+
+  options = options || {}
+
+  if('perspective' in options) {
+    this.useOrtho = !options.perspective
+  }
+  if('orthographic' in options) {
+    this.useOrtho = !!options.orthographic
+  }
+  if('lineWidth' in options) {
+    this.lineWidth = options.lineWidth
+  }
+  if('project' in options) {
+    if(Array.isArray(options.project)) {
+      this.axesProject = options.project
+    } else {
+      var v = !!options.project
+      this.axesProject = [v,v,v]
+    }
+  }
+  if('projectScale' in options) {
+    if(Array.isArray(options.projectScale)) {
+      this.projectScale = options.projectScale.slice()
+    } else {
+      var s = +options.projectScale
+      this.projectScale = [s,s,s]
+    }
+  }
+  if('projectOpacity' in options) {
+    if(Array.isArray(options.projectOpacity)) {
+      this.projectOpacity = options.projectOpacity.slice()
+    } else {
+      var s = +options.projectOpacity
+      this.projectOpacity = [s,s,s]
+    }
+  }
+  if('opacity' in options) {
+    this.opacity = options.opacity
+  }
+
+  //Set dirty flag
+  this.dirty = true
+
+  //Create new buffers
+  var points = options.position
+  if(!points) {
+    return
+  }
+
+  //Text font
+  var font      = options.font      || 'normal'
+  var alignment = options.alignment || [0,0]
+
+  //Bounds
+  var lowerBound = [ Infinity, Infinity, Infinity]
+  var upperBound = [-Infinity,-Infinity,-Infinity]
+
+  //Unpack options
+  var glyphs     = options.glyph
+  var colors     = options.color
+  var sizes      = options.size
+  var angles     = options.angle
+  var lineColors = options.lineColor
+
+  //Picking geometry
+  var pickCounter = 0
+
+  //First do pass to compute buffer sizes
+  var triVertexCount     = 0
+  var lineVertexCount = 0
+
+  //Count number of points and buffer size
+  var numPoints   = points.length
+
+count_loop:
+  for(var i=0; i<numPoints; ++i) {
+    var x = points[i]
+    for(var j=0; j<3; ++j) {
+      if(isNaN(x[j]) || !isFinite(x[j])) {
+        continue count_loop
+      }
+    }
+
+    var glyphData
+    if(Array.isArray(glyphs)) {
+      glyphData = getGlyph(glyphs[i], font)
+    } else if(glyphs) {
+      glyphData = getGlyph(glyphs, font)
+    } else {
+      glyphData = getGlyph('â', font)
+    }
+    var glyphMesh   = glyphData[0]
+    var glyphLines  = glyphData[1]
+    var glyphBounds = glyphData[2]
+
+    triVertexCount  += glyphMesh.cells.length * 3
+    lineVertexCount += glyphLines.edges.length * 2
+  }
+
+
+  //Preallocate data
+  var vertexCount   = triVertexCount + lineVertexCount
+  var positionArray = pool.mallocFloat(3*vertexCount)
+  var colorArray    = pool.mallocFloat(4*vertexCount)
+  var glyphArray    = pool.mallocFloat(2*vertexCount)
+  var idArray       = pool.mallocUint32(vertexCount)
+
+  var textOffset = [0,alignment[1]]
+
+  var triOffset  = 0
+  var lineOffset = triVertexCount
+  var color      = [0,0,0,1]
+  var lineColor  = [0,0,0,1]
+
+  var isColorArray      = Array.isArray(colors)     && Array.isArray(colors[0])
+  var isLineColorArray  = Array.isArray(lineColors) && Array.isArray(lineColors[0])
+
+fill_loop:
+  for(var i=0; i<numPoints; ++i) {
+    var x = points[i]
+    for(var j=0; j<3; ++j) {
+      if(isNaN(x[j]) || !isFinite(x[j])) {
+        pickCounter += 1
+        continue fill_loop
+      }
+
+      upperBound[j] = Math.max(upperBound[j], x[j])
+      lowerBound[j] = Math.min(lowerBound[j], x[j])
+    }
+
+    var glyphData
+    if(Array.isArray(glyphs)) {
+      glyphData = getGlyph(glyphs[i], font)
+    } else if(glyphs) {
+      glyphData = getGlyph(glyphs, font)
+    } else {
+      glyphData = getGlyph('â', font)
+    }
+    var glyphMesh   = glyphData[0]
+    var glyphLines  = glyphData[1]
+    var glyphBounds = glyphData[2]
+
+
+    //Get color
+    if(Array.isArray(colors)) {
+      var c
+      if(isColorArray) {
+        c = colors[i]
+      } else {
+        c = colors
+      }
+      if(c.length === 3) {
+        for(var j=0; j<3; ++j) {
+          color[j] = c[j]
+        }
+        color[3] = 1
+      } else if(c.length === 4) {
+        for(var j=0; j<4; ++j) {
+          color[j] = c[j]
+        }
+      }
+    } else {
+      color[0] = color[1] = color[2] = 0
+      color[3] = 1
+    }
+
+    //Get lineColor
+    if(Array.isArray(lineColors)) {
+      var c
+      if(isLineColorArray) {
+        c = lineColors[i]
+      } else {
+        c = lineColors
+      }
+      if(c.length === 3) {
+        for(var j=0; j<3; ++j) {
+          lineColor[j] = c[j]
+        }
+        lineColor[j] = 1
+      } else if(c.length === 4) {
+        for(var j=0; j<4; ++j) {
+          lineColor[j] = c[j]
+        }
+      }
+    } else {
+      lineColor[0] = lineColor[1] = lineColor[2] = 0
+      lineColor[3] = 1
+    }
+
+    var size = 0.5
+    if(Array.isArray(sizes)) {
+      size = +sizes[i]
+    } else if(sizes) {
+      size = +sizes
+    } else if(this.useOrtho) {
+      size = 12
+    }
+
+    var angle = 0
+    if(Array.isArray(angles)) {
+      angle = +angles[i]
+    } else if(angles) {
+      angle = +angles
+    }
+
+    //Loop through markers and append to buffers
+    var cos = Math.cos(angle)
+    var sin = Math.sin(angle)
+
+    var x = points[i]
+    for(var j=0; j<3; ++j) {
+      upperBound[j] = Math.max(upperBound[j], x[j])
+      lowerBound[j] = Math.min(lowerBound[j], x[j])
+    }
+
+    //Calculate text offset
+    if(alignment[0] < 0) {
+      textOffset[0] = alignment[0]  * (1+glyphBounds[1][0])
+    } else if(alignment[0] > 0) {
+      textOffset[0] = -alignment[0] * (1+glyphBounds[0][0])
+    }
+
+    //Write out inner marker
+    var cells = glyphMesh.cells
+    var verts = glyphMesh.positions
+
+    for(var j=0; j<cells.length; ++j) {
+      var cell = cells[j]
+      for(var k=0; k<3; ++k) {
+        for(var l=0; l<3; ++l) {
+          positionArray[3*triOffset+l] = x[l]
+        }
+        for(var l=0; l<4; ++l) {
+          colorArray[4*triOffset+l] = color[l]
+        }
+        idArray[triOffset] = pickCounter
+        var p = verts[cell[k]]
+        glyphArray[2*triOffset]   = size * (cos*p[0] - sin*p[1] + textOffset[0])
+        glyphArray[2*triOffset+1] = size * (sin*p[0] + cos*p[1] + textOffset[1])
+        triOffset += 1
+      }
+    }
+
+    var cells = glyphLines.edges
+    var verts = glyphLines.positions
+
+    for(var j=0; j<cells.length; ++j) {
+      var cell = cells[j]
+      for(var k=0; k<2; ++k) {
+        for(var l=0; l<3; ++l) {
+          positionArray[3*lineOffset+l] = x[l]
+        }
+        for(var l=0; l<4; ++l) {
+          colorArray[4*lineOffset+l] = lineColor[l]
+        }
+        idArray[lineOffset] = pickCounter
+        var p = verts[cell[k]]
+        glyphArray[2*lineOffset]   = size * (cos*p[0] - sin*p[1] + textOffset[0])
+        glyphArray[2*lineOffset+1] = size * (sin*p[0] + cos*p[1] + textOffset[1])
+        lineOffset += 1
+      }
+    }
+
+    //Increment pickCounter
+    pickCounter += 1
+  }
+
+
+  //Update vertex counts
+  this.vertexCount      = triVertexCount
+  this.lineVertexCount  = lineVertexCount
+
+  //Update buffers
+  this.pointBuffer.update(positionArray)
+  this.colorBuffer.update(colorArray)
+  this.glyphBuffer.update(glyphArray)
+  this.idBuffer.update(new Uint32Array(idArray))
+
+  pool.free(positionArray)
+  pool.free(colorArray)
+  pool.free(glyphArray)
+  pool.free(idArray)
+
+  //Update bounds
+  this.bounds = [lowerBound, upperBound]
+
+  //Save points
+  this.points = points
+
+  //Save number of points
+  this.pointCount = points.length
+}
+
+proto.dispose = function() {
+  //Shaders
+  this.shader.dispose()
+  this.orthoShader.dispose()
+  this.pickPerspectiveShader.dispose()
+  this.pickOrthoShader.dispose()
+
+  //Vertex array
+  this.vao.dispose()
+
+  //Buffers
+  this.pointBuffer.dispose()
+  this.colorBuffer.dispose()
+  this.glyphBuffer.dispose()
+  this.idBuffer.dispose()
+}
+
+function createPointCloud(options) {
+  var gl = options.gl
+
+  var shader                = shaders.createPerspective(gl)
+  var orthoShader           = shaders.createOrtho(gl)
+  var projectShader         = shaders.createProject(gl)
+  var pickPerspectiveShader = shaders.createPickPerspective(gl)
+  var pickOrthoShader       = shaders.createPickOrtho(gl)
+  var pickProjectShader     = shaders.createPickProject(gl)
+
+  var pointBuffer = createBuffer(gl)
+  var colorBuffer = createBuffer(gl)
+  var glyphBuffer = createBuffer(gl)
+  var idBuffer    = createBuffer(gl)
+  var vao = createVAO(gl, [
+    {
+      buffer: pointBuffer,
+      size: 3,
+      type: gl.FLOAT
+    },
+    {
+      buffer: colorBuffer,
+      size: 4,
+      type: gl.FLOAT
+    },
+    {
+      buffer: glyphBuffer,
+      size: 2,
+      type: gl.FLOAT
+    },
+    {
+      buffer: idBuffer,
+      size: 4,
+      type: gl.UNSIGNED_BYTE,
+      normalized: true
+    }
+  ])
+
+  var pointCloud = new PointCloud(
+    gl,
+    shader,
+    orthoShader,
+    projectShader,
+    pointBuffer,
+    colorBuffer,
+    glyphBuffer,
+    idBuffer,
+    vao,
+    pickPerspectiveShader,
+    pickOrthoShader,
+    pickProjectShader)
+
+  pointCloud.update(options)
+
+  return pointCloud
+}
+
+},{"./lib/glyphs":148,"./lib/shaders":149,"gl-buffer":75,"gl-mat4/multiply":96,"gl-vao":189,"typedarray-pool":233}],151:[function(require,module,exports){
+'use strict'
+
+
+
+exports.boxVertex = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n  gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n"
+exports.boxFragment = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 color;\n\nvoid main() {\n  gl_FragColor = color;\n}\n"
+
+},{}],152:[function(require,module,exports){
+'use strict'
+
+var createShader = require('gl-shader')
+var createBuffer = require('gl-buffer')
+
+var SHADERS = require('./lib/shaders')
+
+module.exports = createSelectBox
+
+function SelectBox(plot, boxBuffer, boxShader) {
+  this.plot = plot
+  this.boxBuffer = boxBuffer
+  this.boxShader = boxShader
+
+  this.enabled = true
+
+  this.selectBox = [Infinity,Infinity,-Infinity,-Infinity]
+
+  this.borderColor = [0,0,0,1]
+  this.innerFill   = false
+  this.innerColor  = [0,0,0,0.25]
+  this.outerFill   = true
+  this.outerColor  = [0,0,0,0.5]
+  this.borderWidth = 10
+}
+
+var proto = SelectBox.prototype
+
+proto.draw = function() {
+  if(!this.enabled) {
+    return
+  }
+
+  var plot         = this.plot
+  var selectBox    = this.selectBox
+  var lineWidth    = this.borderWidth
+
+  var innerFill    = this.innerFill
+  var innerColor   = this.innerColor
+  var outerFill    = this.outerFill
+  var outerColor   = this.outerColor
+  var borderColor  = this.borderColor
+
+  var boxes        = plot.box
+  var screenBox    = plot.screenBox
+  var dataBox      = plot.dataBox
+  var viewBox      = plot.viewBox
+  var pixelRatio   = plot.pixelRatio
+
+  //Map select box into pixel coordinates
+  var loX = (selectBox[0]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0]
+  var loY = (selectBox[1]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1]
+  var hiX = (selectBox[2]-dataBox[0])*(viewBox[2]-viewBox[0])/(dataBox[2]-dataBox[0])+viewBox[0]
+  var hiY = (selectBox[3]-dataBox[1])*(viewBox[3]-viewBox[1])/(dataBox[3]-dataBox[1])+viewBox[1]
+
+  loX = Math.max(loX, viewBox[0])
+  loY = Math.max(loY, viewBox[1])
+  hiX = Math.min(hiX, viewBox[2])
+  hiY = Math.min(hiY, viewBox[3])
+
+  if(hiX < loX || hiY < loY) {
+    return
+  }
+
+  boxes.bind()
+
+  //Draw box
+  var screenWidth  = screenBox[2] - screenBox[0]
+  var screenHeight = screenBox[3] - screenBox[1]
+
+  if(this.outerFill) {
+    boxes.drawBox(0, 0, screenWidth, loY, outerColor)
+    boxes.drawBox(0, loY, loX, hiY, outerColor)
+    boxes.drawBox(0, hiY, screenWidth, screenHeight, outerColor)
+    boxes.drawBox(hiX, loY, screenWidth, hiY, outerColor)
+  }
+
+  if(this.innerFill) {
+    boxes.drawBox(loX, loY, hiX, hiY, innerColor)
+  }
+
+  //Draw border
+  if(lineWidth > 0) {
+
+    //Draw border
+    var w = lineWidth * pixelRatio
+    boxes.drawBox(loX-w, loY-w, hiX+w, loY+w, borderColor)
+    boxes.drawBox(loX-w, hiY-w, hiX+w, hiY+w, borderColor)
+    boxes.drawBox(loX-w, loY-w, loX+w, hiY+w, borderColor)
+    boxes.drawBox(hiX-w, loY-w, hiX+w, hiY+w, borderColor)
+  }
+}
+
+proto.update = function(options) {
+  options = options || {}
+
+  this.innerFill    = !!options.innerFill
+  this.outerFill    = !!options.outerFill
+  this.innerColor   = (options.innerColor   || [0,0,0,0.5]).slice()
+  this.outerColor   = (options.outerColor   || [0,0,0,0.5]).slice()
+  this.borderColor  = (options.borderColor || [0,0,0,1]).slice()
+  this.borderWidth  = options.borderWidth || 0
+  this.selectBox    = (options.selectBox || this.selectBox).slice()
+}
+
+proto.dispose = function() {
+  this.boxBuffer.dispose()
+  this.boxShader.dispose()
+  this.plot.removeOverlay(this)
+}
+
+function createSelectBox(plot, options) {
+  var gl = plot.gl
+  var buffer = createBuffer(gl, [
+    0, 0,
+    0, 1,
+    1, 0,
+    1, 1 ])
+  var shader = createShader(gl, SHADERS.boxVertex, SHADERS.boxFragment)
+  var selectBox = new SelectBox(plot, buffer, shader)
+  selectBox.update(options)
+  plot.addOverlay(selectBox)
+  return selectBox
+}
+
+},{"./lib/shaders":151,"gl-buffer":75,"gl-shader":154}],153:[function(require,module,exports){
+'use strict'
+
+module.exports = createSelectBuffer
+
+var createFBO = require('gl-fbo')
+var pool      = require('typedarray-pool')
+var ndarray   = require('ndarray')
+
+var nextPow2  = require('bit-twiddle').nextPow2
+
+var selectRange = require('cwise/lib/wrapper')({"args":["array",{"offset":[0,0,1],"array":0},{"offset":[0,0,2],"array":0},{"offset":[0,0,3],"array":0},"scalar","scalar","index"],"pre":{"body":"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"body":{"body":"{if(255>_inline_31_arg0_||255>_inline_31_arg1_||255>_inline_31_arg2_||255>_inline_31_arg3_){var _inline_31_l=_inline_31_arg4_-_inline_31_arg6_[0],_inline_31_a=_inline_31_arg5_-_inline_31_arg6_[1],_inline_31_f=_inline_31_l*_inline_31_l+_inline_31_a*_inline_31_a;_inline_31_f<this_closestD2&&(this_closestD2=_inline_31_f,this_closestX=_inline_31_arg6_[0],this_closestY=_inline_31_arg6_[1])}}","args":[{"name":"_inline_31_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_31_arg1_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_31_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_31_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_31_arg4_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_31_arg5_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_31_arg6_","lvalue":false,"rvalue":true,"count":4}],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":["_inline_31_a","_inline_31_f","_inline_31_l"]},"post":{"body":"{return[this_closestX,this_closestY,this_closestD2]}","args":[],"thisVars":["this_closestD2","this_closestX","this_closestY"],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64})
+
+function SelectResult(x, y, id, value, distance) {
+  this.coord = [x, y]
+  this.id = id
+  this.value = value
+  this.distance = distance
+}
+
+function SelectBuffer(gl, fbo, buffer) {
+  this.gl     = gl
+  this.fbo    = fbo
+  this.buffer = buffer
+  this._readTimeout = null
+  var self = this
+
+  this._readCallback = function() {
+    if(!self.gl) {
+      return
+    }
+    fbo.bind()
+    gl.readPixels(0,0,fbo.shape[0],fbo.shape[1],gl.RGBA,gl.UNSIGNED_BYTE,self.buffer)
+    self._readTimeout = null
+  }
+}
+
+var proto = SelectBuffer.prototype
+
+Object.defineProperty(proto, 'shape', {
+  get: function() {
+    if(!this.gl) {
+      return [0,0]
+    }
+    return this.fbo.shape.slice()
+  },
+  set: function(v) {
+    if(!this.gl) {
+      return
+    }
+    this.fbo.shape = v
+    var c = this.fbo.shape[0]
+    var r = this.fbo.shape[1]
+    if(r*c*4 > this.buffer.length) {
+      pool.free(this.buffer)
+      var buffer = this.buffer = pool.mallocUint8(nextPow2(r*c*4))
+      for(var i=0; i<r*c*4; ++i) {
+        buffer[i] = 0xff
+      }
+    }
+    return v
+  }
+})
+
+proto.begin = function() {
+  var gl = this.gl
+  var shape = this.shape
+  if(!gl) {
+    return
+  }
+
+  this.fbo.bind()
+  gl.clearColor(1,1,1,1)
+  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
+}
+
+proto.end = function() {
+  var gl = this.gl
+  if(!gl) {
+    return
+  }
+  gl.bindFramebuffer(gl.FRAMEBUFFER, null)
+  if(!this._readTimeout) {
+    clearTimeout(this._readTimeout)
+  }
+  this._readTimeout = setTimeout(this._readCallback, 1)
+}
+
+proto.query = function(x, y, radius) {
+  if(!this.gl) {
+    return null
+  }
+
+  var shape = this.fbo.shape.slice()
+
+  x = x|0
+  y = y|0
+  if(typeof radius !== 'number') {
+    radius = 1.0
+  }
+
+  var x0 = Math.min(Math.max(x - radius, 0), shape[0])|0
+  var x1 = Math.min(Math.max(x + radius, 0), shape[0])|0
+  var y0 = Math.min(Math.max(y - radius, 0), shape[1])|0
+  var y1 = Math.min(Math.max(y + radius, 0), shape[1])|0
+
+  if(x1 <= x0 || y1 <= y0) {
+    return null
+  }
+
+  var dims   = [x1-x0,y1-y0]
+  var region = ndarray(
+    this.buffer,
+    [dims[0], dims[1], 4],
+    [4, shape[0]*4, 1],
+    4*(x0 + shape[0]*y0));
+
+  var closest = selectRange(region.hi(dims[0],dims[1],1), radius, radius)
+  var dx = closest[0]
+  var dy = closest[1]
+  if(dx < 0 || Math.pow(this.radius, 2) < closest[2]) {
+    return null
+  }
+
+  var c0 = region.get(dx, dy, 0)
+  var c1 = region.get(dx, dy, 1)
+  var c2 = region.get(dx, dy, 2)
+  var c3 = region.get(dx, dy, 3)
+
+  return new SelectResult(
+     (dx + x0)|0,
+     (dy + y0)|0,
+     c0,
+     [c1, c2, c3],
+     Math.sqrt(closest[2]))
+}
+
+proto.dispose = function() {
+  if(!this.gl) {
+    return
+  }
+  this.fbo.dispose()
+  pool.free(this.buffer)
+  this.gl = null
+  if(this._readTimeout) {
+    clearTimeout(this._readTimeout)
+  }
+}
+
+function createSelectBuffer(gl, shape) {
+  var fbo = createFBO(gl, shape)
+  var buffer = pool.mallocUint8(shape[0]*shape[1]*4)
+  return new SelectBuffer(gl, fbo, buffer)
+}
+
+},{"bit-twiddle":49,"cwise/lib/wrapper":69,"gl-fbo":80,"ndarray":208,"typedarray-pool":233}],154:[function(require,module,exports){
+'use strict'
+
+var createUniformWrapper   = require('./lib/create-uniforms')
+var createAttributeWrapper = require('./lib/create-attributes')
+var makeReflect            = require('./lib/reflect')
+var shaderCache            = require('./lib/shader-cache')
+var runtime                = require('./lib/runtime-reflect')
+var GLError                = require("./lib/GLError")
+
+//Shader object
+function Shader(gl) {
+  this.gl         = gl
+
+  //Default initialize these to null
+  this._vref      =
+  this._fref      =
+  this._relink    =
+  this.vertShader =
+  this.fragShader =
+  this.program    =
+  this.attributes =
+  this.uniforms   =
+  this.types      = null
+}
+
+var proto = Shader.prototype
+
+proto.bind = function() {
+  if(!this.program) {
+    this._relink()
+  }
+  this.gl.useProgram(this.program)
+}
+
+proto.dispose = function() {
+  if(this._fref) {
+    this._fref.dispose()
+  }
+  if(this._vref) {
+    this._vref.dispose()
+  }
+  this.attributes =
+  this.types      =
+  this.vertShader =
+  this.fragShader =
+  this.program    =
+  this._relink    =
+  this._fref      =
+  this._vref      = null
+}
+
+function compareAttributes(a, b) {
+  if(a.name < b.name) {
+    return -1
+  }
+  return 1
+}
+
+//Update export hook for glslify-live
+proto.update = function(
+    vertSource
+  , fragSource
+  , uniforms
+  , attributes) {
+
+  //If only one object passed, assume glslify style output
+  if(!fragSource || arguments.length === 1) {
+    var obj = vertSource
+    vertSource = obj.vertex
+    fragSource = obj.fragment
+    uniforms   = obj.uniforms
+    attributes = obj.attributes
+  }
+
+  var wrapper = this
+  var gl      = wrapper.gl
+
+  //Compile vertex and fragment shaders
+  var pvref = wrapper._vref
+  wrapper._vref = shaderCache.shader(gl, gl.VERTEX_SHADER, vertSource)
+  if(pvref) {
+    pvref.dispose()
+  }
+  wrapper.vertShader = wrapper._vref.shader
+  var pfref = this._fref
+  wrapper._fref = shaderCache.shader(gl, gl.FRAGMENT_SHADER, fragSource)
+  if(pfref) {
+    pfref.dispose()
+  }
+  wrapper.fragShader = wrapper._fref.shader
+
+  //If uniforms/attributes is not specified, use RT reflection
+  if(!uniforms || !attributes) {
+
+    //Create initial test program
+    var testProgram = gl.createProgram()
+    gl.attachShader(testProgram, wrapper.fragShader)
+    gl.attachShader(testProgram, wrapper.vertShader)
+    gl.linkProgram(testProgram)
+    if(!gl.getProgramParameter(testProgram, gl.LINK_STATUS)) {
+      var errLog = gl.getProgramInfoLog(testProgram)
+      throw new GLError(errLog, 'Error linking program:' + errLog)
+    }
+
+    //Load data from runtime
+    uniforms   = uniforms   || runtime.uniforms(gl, testProgram)
+    attributes = attributes || runtime.attributes(gl, testProgram)
+
+    //Release test program
+    gl.deleteProgram(testProgram)
+  }
+
+  //Sort attributes lexicographically
+  // overrides undefined WebGL behavior for attribute locations
+  attributes = attributes.slice()
+  attributes.sort(compareAttributes)
+
+  //Convert attribute types, read out locations
+  var attributeUnpacked  = []
+  var attributeNames     = []
+  var attributeLocations = []
+  for(var i=0; i<attributes.length; ++i) {
+    var attr = attributes[i]
+    if(attr.type.indexOf('mat') >= 0) {
+      var size = attr.type.charAt(attr.type.length-1)|0
+      var locVector = new Array(size)
+      for(var j=0; j<size; ++j) {
+        locVector[j] = attributeLocations.length
+        attributeNames.push(attr.name + '[' + j + ']')
+        if(typeof attr.location === 'number') {
+          attributeLocations.push(attr.location + j)
+        } else if(Array.isArray(attr.location) &&
+                  attr.location.length === size &&
+                  typeof attr.location[j] === 'number') {
+          attributeLocations.push(attr.location[j]|0)
+        } else {
+          attributeLocations.push(-1)
+        }
+      }
+      attributeUnpacked.push({
+        name: attr.name,
+        type: attr.type,
+        locations: locVector
+      })
+    } else {
+      attributeUnpacked.push({
+        name: attr.name,
+        type: attr.type,
+        locations: [ attributeLocations.length ]
+      })
+      attributeNames.push(attr.name)
+      if(typeof attr.location === 'number') {
+        attributeLocations.push(attr.location|0)
+      } else {
+        attributeLocations.push(-1)
+      }
+    }
+  }
+
+  //For all unspecified attributes, assign them lexicographically min attribute
+  var curLocation = 0
+  for(var i=0; i<attributeLocations.length; ++i) {
+    if(attributeLocations[i] < 0) {
+      while(attributeLocations.indexOf(curLocation) >= 0) {
+        curLocation += 1
+      }
+      attributeLocations[i] = curLocation
+    }
+  }
+
+  //Rebuild program and recompute all uniform locations
+  var uniformLocations = new Array(uniforms.length)
+  function relink() {
+    wrapper.program = shaderCache.program(
+        gl
+      , wrapper._vref
+      , wrapper._fref
+      , attributeNames
+      , attributeLocations)
+
+    for(var i=0; i<uniforms.length; ++i) {
+      uniformLocations[i] = gl.getUniformLocation(
+          wrapper.program
+        , uniforms[i].name)
+    }
+  }
+
+  //Perform initial linking, reuse program used for reflection
+  relink()
+
+  //Save relinking procedure, defer until runtime
+  wrapper._relink = relink
+
+  //Generate type info
+  wrapper.types = {
+    uniforms:   makeReflect(uniforms),
+    attributes: makeReflect(attributes)
+  }
+
+  //Generate attribute wrappers
+  wrapper.attributes = createAttributeWrapper(
+      gl
+    , wrapper
+    , attributeUnpacked
+    , attributeLocations)
+
+  //Generate uniform wrappers
+  Object.defineProperty(wrapper, 'uniforms', createUniformWrapper(
+      gl
+    , wrapper
+    , uniforms
+    , uniformLocations))
+}
+
+//Compiles and links a shader program with the given attribute and vertex list
+function createShader(
+    gl
+  , vertSource
+  , fragSource
+  , uniforms
+  , attributes) {
+
+  var shader = new Shader(gl)
+
+  shader.update(
+      vertSource
+    , fragSource
+    , uniforms
+    , attributes)
+
+  return shader
+}
+
+module.exports = createShader
+
+},{"./lib/GLError":155,"./lib/create-attributes":156,"./lib/create-uniforms":157,"./lib/reflect":158,"./lib/runtime-reflect":159,"./lib/shader-cache":160}],155:[function(require,module,exports){
+function GLError (rawError, shortMessage, longMessage) {
+    this.shortMessage = shortMessage || ''
+    this.longMessage = longMessage || ''
+    this.rawError = rawError || ''
+    this.message =
+      'gl-shader: ' + (shortMessage || rawError || '') +
+      (longMessage ? '\n'+longMessage : '')
+    this.stack = (new Error()).stack
+}
+GLError.prototype = new Error
+GLError.prototype.name = 'GLError'
+GLError.prototype.constructor = GLError
+module.exports = GLError
+
+},{}],156:[function(require,module,exports){
+'use strict'
+
+module.exports = createAttributeWrapper
+
+var GLError = require("./GLError")
+
+function ShaderAttribute(
+    gl
+  , wrapper
+  , index
+  , locations
+  , dimension
+  , constFunc) {
+  this._gl        = gl
+  this._wrapper   = wrapper
+  this._index     = index
+  this._locations = locations
+  this._dimension = dimension
+  this._constFunc = constFunc
+}
+
+var proto = ShaderAttribute.prototype
+
+proto.pointer = function setAttribPointer(
+    type
+  , normalized
+  , stride
+  , offset) {
+
+  var self      = this
+  var gl        = self._gl
+  var location  = self._locations[self._index]
+
+  gl.vertexAttribPointer(
+      location
+    , self._dimension
+    , type || gl.FLOAT
+    , !!normalized
+    , stride || 0
+    , offset || 0)
+  gl.enableVertexAttribArray(location)
+}
+
+proto.set = function(x0, x1, x2, x3) {
+  return this._constFunc(this._locations[this._index], x0, x1, x2, x3)
+}
+
+Object.defineProperty(proto, 'location', {
+  get: function() {
+    return this._locations[this._index]
+  }
+  , set: function(v) {
+    if(v !== this._locations[this._index]) {
+      this._locations[this._index] = v|0
+      this._wrapper.program = null
+    }
+    return v|0
+  }
+})
+
+//Adds a vector attribute to obj
+function addVectorAttribute(
+    gl
+  , wrapper
+  , index
+  , locations
+  , dimension
+  , obj
+  , name) {
+
+  //Construct constant function
+  var constFuncArgs = [ 'gl', 'v' ]
+  var varNames = []
+  for(var i=0; i<dimension; ++i) {
+    constFuncArgs.push('x'+i)
+    varNames.push('x'+i)
+  }
+  constFuncArgs.push(
+    'if(x0.length===void 0){return gl.vertexAttrib' +
+    dimension + 'f(v,' +
+    varNames.join() +
+    ')}else{return gl.vertexAttrib' +
+    dimension +
+    'fv(v,x0)}')
+  var constFunc = Function.apply(null, constFuncArgs)
+
+  //Create attribute wrapper
+  var attr = new ShaderAttribute(
+      gl
+    , wrapper
+    , index
+    , locations
+    , dimension
+    , constFunc)
+
+  //Create accessor
+  Object.defineProperty(obj, name, {
+    set: function(x) {
+      gl.disableVertexAttribArray(locations[index])
+      constFunc(gl, locations[index], x)
+      return x
+    }
+    , get: function() {
+      return attr
+    }
+    , enumerable: true
+  })
+}
+
+function addMatrixAttribute(
+    gl
+  , wrapper
+  , index
+  , locations
+  , dimension
+  , obj
+  , name) {
+
+  var parts = new Array(dimension)
+  var attrs = new Array(dimension)
+  for(var i=0; i<dimension; ++i) {
+    addVectorAttribute(
+        gl
+      , wrapper
+      , index[i]
+      , locations
+      , dimension
+      , parts
+      , i)
+    attrs[i] = parts[i]
+  }
+
+  Object.defineProperty(parts, 'location', {
+    set: function(v) {
+      if(Array.isArray(v)) {
+        for(var i=0; i<dimension; ++i) {
+          attrs[i].location = v[i]
+        }
+      } else {
+        for(var i=0; i<dimension; ++i) {
+          attrs[i].location = v + i
+        }
+      }
+      return v
+    }
+    , get: function() {
+      var result = new Array(dimension)
+      for(var i=0; i<dimension; ++i) {
+        result[i] = locations[index[i]]
+      }
+      return result
+    }
+    , enumerable: true
+  })
+
+  parts.pointer = function(type, normalized, stride, offset) {
+    type       = type || gl.FLOAT
+    normalized = !!normalized
+    stride     = stride || (dimension * dimension)
+    offset     = offset || 0
+    for(var i=0; i<dimension; ++i) {
+      var location = locations[index[i]]
+      gl.vertexAttribPointer(
+            location
+          , dimension
+          , type
+          , normalized
+          , stride
+          , offset + i * dimension)
+      gl.enableVertexAttribArray(location)
+    }
+  }
+
+  var scratch = new Array(dimension)
+  var vertexAttrib = gl['vertexAttrib' + dimension + 'fv']
+
+  Object.defineProperty(obj, name, {
+    set: function(x) {
+      for(var i=0; i<dimension; ++i) {
+        var loc = locations[index[i]]
+        gl.disableVertexAttribArray(loc)
+        if(Array.isArray(x[0])) {
+          vertexAttrib.call(gl, loc, x[i])
+        } else {
+          for(var j=0; j<dimension; ++j) {
+            scratch[j] = x[dimension*i + j]
+          }
+          vertexAttrib.call(gl, loc, scratch)
+        }
+      }
+      return x
+    }
+    , get: function() {
+      return parts
+    }
+    , enumerable: true
+  })
+}
+
+//Create shims for attributes
+function createAttributeWrapper(
+    gl
+  , wrapper
+  , attributes
+  , locations) {
+
+  var obj = {}
+  for(var i=0, n=attributes.length; i<n; ++i) {
+
+    var a = attributes[i]
+    var name = a.name
+    var type = a.type
+    var locs = a.locations
+
+    switch(type) {
+      case 'bool':
+      case 'int':
+      case 'float':
+        addVectorAttribute(
+            gl
+          , wrapper
+          , locs[0]
+          , locations
+          , 1
+          , obj
+          , name)
+      break
+
+      default:
+        if(type.indexOf('vec') >= 0) {
+          var d = type.charCodeAt(type.length-1) - 48
+          if(d < 2 || d > 4) {
+            throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type)
+          }
+          addVectorAttribute(
+              gl
+            , wrapper
+            , locs[0]
+            , locations
+            , d
+            , obj
+            , name)
+        } else if(type.indexOf('mat') >= 0) {
+          var d = type.charCodeAt(type.length-1) - 48
+          if(d < 2 || d > 4) {
+            throw new GLError('', 'Invalid data type for attribute ' + name + ': ' + type)
+          }
+          addMatrixAttribute(
+              gl
+            , wrapper
+            , locs
+            , locations
+            , d
+            , obj
+            , name)
+        } else {
+          throw new GLError('', 'Unknown data type for attribute ' + name + ': ' + type)
+        }
+      break
+    }
+  }
+  return obj
+}
+
+},{"./GLError":155}],157:[function(require,module,exports){
+'use strict'
+
+var coallesceUniforms = require('./reflect')
+var GLError = require("./GLError")
+
+module.exports = createUniformWrapper
+
+//Binds a function and returns a value
+function identity(x) {
+  var c = new Function('y', 'return function(){return y}')
+  return c(x)
+}
+
+function makeVector(length, fill) {
+  var result = new Array(length)
+  for(var i=0; i<length; ++i) {
+    result[i] = fill
+  }
+  return result
+}
+
+//Create shims for uniforms
+function createUniformWrapper(gl, wrapper, uniforms, locations) {
+
+  function makeGetter(index) {
+    var proc = new Function(
+        'gl'
+      , 'wrapper'
+      , 'locations'
+      , 'return function(){return gl.getUniform(wrapper.program,locations[' + index + '])}')
+    return proc(gl, wrapper, locations)
+  }
+
+  function makePropSetter(path, index, type) {
+    switch(type) {
+      case 'bool':
+      case 'int':
+      case 'sampler2D':
+      case 'samplerCube':
+        return 'gl.uniform1i(locations[' + index + '],obj' + path + ')'
+      case 'float':
+        return 'gl.uniform1f(locations[' + index + '],obj' + path + ')'
+      default:
+        var vidx = type.indexOf('vec')
+        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
+          var d = type.charCodeAt(type.length-1) - 48
+          if(d < 2 || d > 4) {
+            throw new GLError('', 'Invalid data type')
+          }
+          switch(type.charAt(0)) {
+            case 'b':
+            case 'i':
+              return 'gl.uniform' + d + 'iv(locations[' + index + '],obj' + path + ')'
+            case 'v':
+              return 'gl.uniform' + d + 'fv(locations[' + index + '],obj' + path + ')'
+            default:
+              throw new GLError('', 'Unrecognized data type for vector ' + name + ': ' + type)
+          }
+        } else if(type.indexOf('mat') === 0 && type.length === 4) {
+          var d = type.charCodeAt(type.length-1) - 48
+          if(d < 2 || d > 4) {
+            throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type)
+          }
+          return 'gl.uniformMatrix' + d + 'fv(locations[' + index + '],false,obj' + path + ')'
+        } else {
+          throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type)
+        }
+      break
+    }
+  }
+
+  function enumerateIndices(prefix, type) {
+    if(typeof type !== 'object') {
+      return [ [prefix, type] ]
+    }
+    var indices = []
+    for(var id in type) {
+      var prop = type[id]
+      var tprefix = prefix
+      if(parseInt(id) + '' === id) {
+        tprefix += '[' + id + ']'
+      } else {
+        tprefix += '.' + id
+      }
+      if(typeof prop === 'object') {
+        indices.push.apply(indices, enumerateIndices(tprefix, prop))
+      } else {
+        indices.push([tprefix, prop])
+      }
+    }
+    return indices
+  }
+
+  function makeSetter(type) {
+    var code = [ 'return function updateProperty(obj){' ]
+    var indices = enumerateIndices('', type)
+    for(var i=0; i<indices.length; ++i) {
+      var item = indices[i]
+      var path = item[0]
+      var idx  = item[1]
+      if(locations[idx]) {
+        code.push(makePropSetter(path, idx, uniforms[idx].type))
+      }
+    }
+    code.push('return obj}')
+    var proc = new Function('gl', 'locations', code.join('\n'))
+    return proc(gl, locations)
+  }
+
+  function defaultValue(type) {
+    switch(type) {
+      case 'bool':
+        return false
+      case 'int':
+      case 'sampler2D':
+      case 'samplerCube':
+        return 0
+      case 'float':
+        return 0.0
+      default:
+        var vidx = type.indexOf('vec')
+        if(0 <= vidx && vidx <= 1 && type.length === 4 + vidx) {
+          var d = type.charCodeAt(type.length-1) - 48
+          if(d < 2 || d > 4) {
+            throw new GLError('', 'Invalid data type')
+          }
+          if(type.charAt(0) === 'b') {
+            return makeVector(d, false)
+          }
+          return makeVector(d, 0)
+        } else if(type.indexOf('mat') === 0 && type.length === 4) {
+          var d = type.charCodeAt(type.length-1) - 48
+          if(d < 2 || d > 4) {
+            throw new GLError('', 'Invalid uniform dimension type for matrix ' + name + ': ' + type)
+          }
+          return makeVector(d*d, 0)
+        } else {
+          throw new GLError('', 'Unknown uniform data type for ' + name + ': ' + type)
+        }
+      break
+    }
+  }
+
+  function storeProperty(obj, prop, type) {
+    if(typeof type === 'object') {
+      var child = processObject(type)
+      Object.defineProperty(obj, prop, {
+        get: identity(child),
+        set: makeSetter(type),
+        enumerable: true,
+        configurable: false
+      })
+    } else {
+      if(locations[type]) {
+        Object.defineProperty(obj, prop, {
+          get: makeGetter(type),
+          set: makeSetter(type),
+          enumerable: true,
+          configurable: false
+        })
+      } else {
+        obj[prop] = defaultValue(uniforms[type].type)
+      }
+    }
+  }
+
+  function processObject(obj) {
+    var result
+    if(Array.isArray(obj)) {
+      result = new Array(obj.length)
+      for(var i=0; i<obj.length; ++i) {
+        storeProperty(result, i, obj[i])
+      }
+    } else {
+      result = {}
+      for(var id in obj) {
+        storeProperty(result, id, obj[id])
+      }
+    }
+    return result
+  }
+
+  //Return data
+  var coallesced = coallesceUniforms(uniforms, true)
+  return {
+    get: identity(processObject(coallesced)),
+    set: makeSetter(coallesced),
+    enumerable: true,
+    configurable: true
+  }
+}
+
+},{"./GLError":155,"./reflect":158}],158:[function(require,module,exports){
+'use strict'
+
+module.exports = makeReflectTypes
+
+//Construct type info for reflection.
+//
+// This iterates over the flattened list of uniform type values and smashes them into a JSON object.
+//
+// The leaves of the resulting object are either indices or type strings representing primitive glslify types
+function makeReflectTypes(uniforms, useIndex) {
+  var obj = {}
+  for(var i=0; i<uniforms.length; ++i) {
+    var n = uniforms[i].name
+    var parts = n.split(".")
+    var o = obj
+    for(var j=0; j<parts.length; ++j) {
+      var x = parts[j].split("[")
+      if(x.length > 1) {
+        if(!(x[0] in o)) {
+          o[x[0]] = []
+        }
+        o = o[x[0]]
+        for(var k=1; k<x.length; ++k) {
+          var y = parseInt(x[k])
+          if(k<x.length-1 || j<parts.length-1) {
+            if(!(y in o)) {
+              if(k < x.length-1) {
+                o[y] = []
+              } else {
+                o[y] = {}
+              }
+            }
+            o = o[y]
+          } else {
+            if(useIndex) {
+              o[y] = i
+            } else {
+              o[y] = uniforms[i].type
+            }
+          }
+        }
+      } else if(j < parts.length-1) {
+        if(!(x[0] in o)) {
+          o[x[0]] = {}
+        }
+        o = o[x[0]]
+      } else {
+        if(useIndex) {
+          o[x[0]] = i
+        } else {
+          o[x[0]] = uniforms[i].type
+        }
+      }
+    }
+  }
+  return obj
+}
+},{}],159:[function(require,module,exports){
+'use strict'
+
+exports.uniforms    = runtimeUniforms
+exports.attributes  = runtimeAttributes
+
+var GL_TO_GLSL_TYPES = {
+  'FLOAT':       'float',
+  'FLOAT_VEC2':  'vec2',
+  'FLOAT_VEC3':  'vec3',
+  'FLOAT_VEC4':  'vec4',
+  'INT':         'int',
+  'INT_VEC2':    'ivec2',
+  'INT_VEC3':    'ivec3',
+  'INT_VEC4':    'ivec4',
+  'BOOL':        'bool',
+  'BOOL_VEC2':   'bvec2',
+  'BOOL_VEC3':   'bvec3',
+  'BOOL_VEC4':   'bvec4',
+  'FLOAT_MAT2':  'mat2',
+  'FLOAT_MAT3':  'mat3',
+  'FLOAT_MAT4':  'mat4',
+  'SAMPLER_2D':  'sampler2D',
+  'SAMPLER_CUBE':'samplerCube'
+}
+
+var GL_TABLE = null
+
+function getType(gl, type) {
+  if(!GL_TABLE) {
+    var typeNames = Object.keys(GL_TO_GLSL_TYPES)
+    GL_TABLE = {}
+    for(var i=0; i<typeNames.length; ++i) {
+      var tn = typeNames[i]
+      GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]
+    }
+  }
+  return GL_TABLE[type]
+}
+
+function runtimeUniforms(gl, program) {
+  var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS)
+  var result = []
+  for(var i=0; i<numUniforms; ++i) {
+    var info = gl.getActiveUniform(program, i)
+    if(info) {
+      var type = getType(gl, info.type)
+      if(info.size > 1) {
+        for(var j=0; j<info.size; ++j) {
+          result.push({
+            name: info.name.replace('[0]', '[' + j + ']'),
+            type: type
+          })
+        }
+      } else {
+        result.push({
+          name: info.name,
+          type: type
+        })
+      }
+    }
+  }
+  return result
+}
+
+function runtimeAttributes(gl, program) {
+  var numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES)
+  var result = []
+  for(var i=0; i<numAttributes; ++i) {
+    var info = gl.getActiveAttrib(program, i)
+    if(info) {
+      result.push({
+        name: info.name,
+        type: getType(gl, info.type)
+      })
+    }
+  }
+  return result
+}
+
+},{}],160:[function(require,module,exports){
+'use strict'
+
+exports.shader   = getShaderReference
+exports.program  = createProgram
+
+var GLError = require("./GLError")
+var formatCompilerError = require('gl-format-compiler-error');
+
+var weakMap = typeof WeakMap === 'undefined' ? require('weakmap-shim') : WeakMap
+var CACHE = new weakMap()
+
+var SHADER_COUNTER = 0
+
+function ShaderReference(id, src, type, shader, programs, count, cache) {
+  this.id       = id
+  this.src      = src
+  this.type     = type
+  this.shader   = shader
+  this.count    = count
+  this.programs = []
+  this.cache    = cache
+}
+
+ShaderReference.prototype.dispose = function() {
+  if(--this.count === 0) {
+    var cache    = this.cache
+    var gl       = cache.gl
+
+    //Remove program references
+    var programs = this.programs
+    for(var i=0, n=programs.length; i<n; ++i) {
+      var p = cache.programs[programs[i]]
+      if(p) {
+        delete cache.programs[i]
+        gl.deleteProgram(p)
+      }
+    }
+
+    //Remove shader reference
+    gl.deleteShader(this.shader)
+    delete cache.shaders[(this.type === gl.FRAGMENT_SHADER)|0][this.src]
+  }
+}
+
+function ContextCache(gl) {
+  this.gl       = gl
+  this.shaders  = [{}, {}]
+  this.programs = {}
+}
+
+var proto = ContextCache.prototype
+
+function compileShader(gl, type, src) {
+  var shader = gl.createShader(type)
+  gl.shaderSource(shader, src)
+  gl.compileShader(shader)
+  if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
+    var errLog = gl.getShaderInfoLog(shader)
+    try {
+        var fmt = formatCompilerError(errLog, src, type);
+    } catch (e){
+        console.warn('Failed to format compiler error: ' + e);
+        throw new GLError(errLog, 'Error compiling shader:\n' + errLog)
+    }
+    throw new GLError(errLog, fmt.short, fmt.long)
+  }
+  return shader
+}
+
+proto.getShaderReference = function(type, src) {
+  var gl      = this.gl
+  var shaders = this.shaders[(type === gl.FRAGMENT_SHADER)|0]
+  var shader  = shaders[src]
+  if(!shader || !gl.isShader(shader.shader)) {
+    var shaderObj = compileShader(gl, type, src)
+    shader = shaders[src] = new ShaderReference(
+      SHADER_COUNTER++,
+      src,
+      type,
+      shaderObj,
+      [],
+      1,
+      this)
+  } else {
+    shader.count += 1
+  }
+  return shader
+}
+
+function linkProgram(gl, vshader, fshader, attribs, locations) {
+  var program = gl.createProgram()
+  gl.attachShader(program, vshader)
+  gl.attachShader(program, fshader)
+  for(var i=0; i<attribs.length; ++i) {
+    gl.bindAttribLocation(program, locations[i], attribs[i])
+  }
+  gl.linkProgram(program)
+  if(!gl.getProgramParameter(program, gl.LINK_STATUS)) {
+    var errLog = gl.getProgramInfoLog(program)
+    throw new GLError(errLog, 'Error linking program: ' + errLog)
+  }
+  return program
+}
+
+proto.getProgram = function(vref, fref, attribs, locations) {
+  var token = [vref.id, fref.id, attribs.join(':'), locations.join(':')].join('@')
+  var prog  = this.programs[token]
+  if(!prog || !this.gl.isProgram(prog)) {
+    this.programs[token] = prog = linkProgram(
+      this.gl,
+      vref.shader,
+      fref.shader,
+      attribs,
+      locations)
+    vref.programs.push(token)
+    fref.programs.push(token)
+  }
+  return prog
+}
+
+function getCache(gl) {
+  var ctxCache = CACHE.get(gl)
+  if(!ctxCache) {
+    ctxCache = new ContextCache(gl)
+    CACHE.set(gl, ctxCache)
+  }
+  return ctxCache
+}
+
+function getShaderReference(gl, type, src) {
+  return getCache(gl).getShaderReference(type, src)
+}
+
+function createProgram(gl, vref, fref, attribs, locations) {
+  return getCache(gl).getProgram(vref, fref, attribs, locations)
+}
+
+},{"./GLError":155,"gl-format-compiler-error":161,"weakmap-shim":177}],161:[function(require,module,exports){
+
+var sprintf = require('sprintf-js').sprintf;
+var glConstants = require('gl-constants/lookup');
+var shaderName = require('glsl-shader-name');
+var addLineNumbers = require('add-line-numbers');
+
+module.exports = formatCompilerError;
+
+function formatCompilerError(errLog, src, type) {
+    "use strict";
+
+    var name = shaderName(src) || 'of unknown name (see npm glsl-shader-name)';
+
+    var typeName = 'unknown type';
+    if (type !== undefined) {
+        typeName = type === glConstants.FRAGMENT_SHADER ? 'fragment' : 'vertex'
+    }
+
+    var longForm = sprintf('Error compiling %s shader %s:\n', typeName, name);
+    var shortForm = sprintf("%s%s", longForm, errLog);
+
+    var errorStrings = errLog.split('\n');
+    var errors = {};
+
+    for (var i = 0; i < errorStrings.length; i++) {
+        var errorString = errorStrings[i];
+        if (errorString === '') continue;
+        var lineNo = parseInt(errorString.split(':')[2]);
+        if (isNaN(lineNo)) {
+            throw new Error(sprintf('Could not parse error: %s', errorString));
+        }
+        errors[lineNo] = errorString;
+    }
+
+    var lines = addLineNumbers(src).split('\n');
+
+    for (var i = 0; i < lines.length; i++) {
+        if (!errors[i+3] && !errors[i+2] && !errors[i+1]) continue;
+        var line = lines[i];
+        longForm += line + '\n';
+        if (errors[i+1]) {
+            var e = errors[i+1];
+            e = e.substr(e.split(':', 3).join(':').length + 1).trim();
+            longForm += sprintf('^^^ %s\n\n', e);
+        }
+    }
+
+    return {
+        long: longForm.trim(),
+        short: shortForm.trim()
+    };
+}
+
+
+},{"add-line-numbers":162,"gl-constants/lookup":166,"glsl-shader-name":167,"sprintf-js":174}],162:[function(require,module,exports){
+var padLeft = require('pad-left')
+
+module.exports = addLineNumbers
+function addLineNumbers (string, start, delim) {
+  start = typeof start === 'number' ? start : 1
+  delim = delim || ': '
+
+  var lines = string.split(/\r?\n/)
+  var totalDigits = String(lines.length + start - 1).length
+  return lines.map(function (line, i) {
+    var c = i + start
+    var digits = String(c).length
+    var prefix = padLeft(c, totalDigits - digits)
+    return prefix + delim + line
+  }).join('\n')
+}
+
+},{"pad-left":163}],163:[function(require,module,exports){
+/*!
+ * pad-left <https://github.com/jonschlinkert/pad-left>
+ *
+ * Copyright (c) 2014-2015, Jon Schlinkert.
+ * Licensed under the MIT license.
+ */
+
+'use strict';
+
+var repeat = require('repeat-string');
+
+module.exports = function padLeft(str, num, ch) {
+  ch = typeof ch !== 'undefined' ? (ch + '') : ' ';
+  return repeat(ch, num) + str;
+};
+},{"repeat-string":164}],164:[function(require,module,exports){
+/*!
+ * repeat-string <https://github.com/jonschlinkert/repeat-string>
+ *
+ * Copyright (c) 2014-2015, Jon Schlinkert.
+ * Licensed under the MIT License.
+ */
+
+'use strict';
+
+/**
+ * Expose `repeat`
+ */
+
+module.exports = repeat;
+
+/**
+ * Repeat the given `string` the specified `number`
+ * of times.
+ *
+ * **Example:**
+ *
+ * ```js
+ * var repeat = require('repeat-string');
+ * repeat('A', 5);
+ * //=> AAAAA
+ * ```
+ *
+ * @param {String} `string` The string to repeat
+ * @param {Number} `number` The number of times to repeat the string
+ * @return {String} Repeated string
+ * @api public
+ */
+
+function repeat(str, num) {
+  if (typeof str !== 'string') {
+    throw new TypeError('repeat-string expects a string.');
+  }
+
+  if (num === 1) return str;
+  if (num === 2) return str + str;
+
+  var max = str.length * num;
+  if (cache !== str || typeof cache === 'undefined') {
+    cache = str;
+    res = '';
+  }
+
+  while (max > res.length && num > 0) {
+    if (num & 1) {
+      res += str;
+    }
+
+    num >>= 1;
+    if (!num) break;
+    str += str;
+  }
+
+  return res.substr(0, max);
+}
+
+/**
+ * Results cache
+ */
+
+var res = '';
+var cache;
+
+},{}],165:[function(require,module,exports){
+module.exports = {
+  0: 'NONE',
+  1: 'ONE',
+  2: 'LINE_LOOP',
+  3: 'LINE_STRIP',
+  4: 'TRIANGLES',
+  5: 'TRIANGLE_STRIP',
+  6: 'TRIANGLE_FAN',
+  256: 'DEPTH_BUFFER_BIT',
+  512: 'NEVER',
+  513: 'LESS',
+  514: 'EQUAL',
+  515: 'LEQUAL',
+  516: 'GREATER',
+  517: 'NOTEQUAL',
+  518: 'GEQUAL',
+  519: 'ALWAYS',
+  768: 'SRC_COLOR',
+  769: 'ONE_MINUS_SRC_COLOR',
+  770: 'SRC_ALPHA',
+  771: 'ONE_MINUS_SRC_ALPHA',
+  772: 'DST_ALPHA',
+  773: 'ONE_MINUS_DST_ALPHA',
+  774: 'DST_COLOR',
+  775: 'ONE_MINUS_DST_COLOR',
+  776: 'SRC_ALPHA_SATURATE',
+  1024: 'STENCIL_BUFFER_BIT',
+  1028: 'FRONT',
+  1029: 'BACK',
+  1032: 'FRONT_AND_BACK',
+  1280: 'INVALID_ENUM',
+  1281: 'INVALID_VALUE',
+  1282: 'INVALID_OPERATION',
+  1285: 'OUT_OF_MEMORY',
+  1286: 'INVALID_FRAMEBUFFER_OPERATION',
+  2304: 'CW',
+  2305: 'CCW',
+  2849: 'LINE_WIDTH',
+  2884: 'CULL_FACE',
+  2885: 'CULL_FACE_MODE',
+  2886: 'FRONT_FACE',
+  2928: 'DEPTH_RANGE',
+  2929: 'DEPTH_TEST',
+  2930: 'DEPTH_WRITEMASK',
+  2931: 'DEPTH_CLEAR_VALUE',
+  2932: 'DEPTH_FUNC',
+  2960: 'STENCIL_TEST',
+  2961: 'STENCIL_CLEAR_VALUE',
+  2962: 'STENCIL_FUNC',
+  2963: 'STENCIL_VALUE_MASK',
+  2964: 'STENCIL_FAIL',
+  2965: 'STENCIL_PASS_DEPTH_FAIL',
+  2966: 'STENCIL_PASS_DEPTH_PASS',
+  2967: 'STENCIL_REF',
+  2968: 'STENCIL_WRITEMASK',
+  2978: 'VIEWPORT',
+  3024: 'DITHER',
+  3042: 'BLEND',
+  3088: 'SCISSOR_BOX',
+  3089: 'SCISSOR_TEST',
+  3106: 'COLOR_CLEAR_VALUE',
+  3107: 'COLOR_WRITEMASK',
+  3317: 'UNPACK_ALIGNMENT',
+  3333: 'PACK_ALIGNMENT',
+  3379: 'MAX_TEXTURE_SIZE',
+  3386: 'MAX_VIEWPORT_DIMS',
+  3408: 'SUBPIXEL_BITS',
+  3410: 'RED_BITS',
+  3411: 'GREEN_BITS',
+  3412: 'BLUE_BITS',
+  3413: 'ALPHA_BITS',
+  3414: 'DEPTH_BITS',
+  3415: 'STENCIL_BITS',
+  3553: 'TEXTURE_2D',
+  4352: 'DONT_CARE',
+  4353: 'FASTEST',
+  4354: 'NICEST',
+  5120: 'BYTE',
+  5121: 'UNSIGNED_BYTE',
+  5122: 'SHORT',
+  5123: 'UNSIGNED_SHORT',
+  5124: 'INT',
+  5125: 'UNSIGNED_INT',
+  5126: 'FLOAT',
+  5386: 'INVERT',
+  5890: 'TEXTURE',
+  6401: 'STENCIL_INDEX',
+  6402: 'DEPTH_COMPONENT',
+  6406: 'ALPHA',
+  6407: 'RGB',
+  6408: 'RGBA',
+  6409: 'LUMINANCE',
+  6410: 'LUMINANCE_ALPHA',
+  7680: 'KEEP',
+  7681: 'REPLACE',
+  7682: 'INCR',
+  7683: 'DECR',
+  7936: 'VENDOR',
+  7937: 'RENDERER',
+  7938: 'VERSION',
+  9728: 'NEAREST',
+  9729: 'LINEAR',
+  9984: 'NEAREST_MIPMAP_NEAREST',
+  9985: 'LINEAR_MIPMAP_NEAREST',
+  9986: 'NEAREST_MIPMAP_LINEAR',
+  9987: 'LINEAR_MIPMAP_LINEAR',
+  10240: 'TEXTURE_MAG_FILTER',
+  10241: 'TEXTURE_MIN_FILTER',
+  10242: 'TEXTURE_WRAP_S',
+  10243: 'TEXTURE_WRAP_T',
+  10497: 'REPEAT',
+  10752: 'POLYGON_OFFSET_UNITS',
+  16384: 'COLOR_BUFFER_BIT',
+  32769: 'CONSTANT_COLOR',
+  32770: 'ONE_MINUS_CONSTANT_COLOR',
+  32771: 'CONSTANT_ALPHA',
+  32772: 'ONE_MINUS_CONSTANT_ALPHA',
+  32773: 'BLEND_COLOR',
+  32774: 'FUNC_ADD',
+  32777: 'BLEND_EQUATION_RGB',
+  32778: 'FUNC_SUBTRACT',
+  32779: 'FUNC_REVERSE_SUBTRACT',
+  32819: 'UNSIGNED_SHORT_4_4_4_4',
+  32820: 'UNSIGNED_SHORT_5_5_5_1',
+  32823: 'POLYGON_OFFSET_FILL',
+  32824: 'POLYGON_OFFSET_FACTOR',
+  32854: 'RGBA4',
+  32855: 'RGB5_A1',
+  32873: 'TEXTURE_BINDING_2D',
+  32926: 'SAMPLE_ALPHA_TO_COVERAGE',
+  32928: 'SAMPLE_COVERAGE',
+  32936: 'SAMPLE_BUFFERS',
+  32937: 'SAMPLES',
+  32938: 'SAMPLE_COVERAGE_VALUE',
+  32939: 'SAMPLE_COVERAGE_INVERT',
+  32968: 'BLEND_DST_RGB',
+  32969: 'BLEND_SRC_RGB',
+  32970: 'BLEND_DST_ALPHA',
+  32971: 'BLEND_SRC_ALPHA',
+  33071: 'CLAMP_TO_EDGE',
+  33170: 'GENERATE_MIPMAP_HINT',
+  33189: 'DEPTH_COMPONENT16',
+  33306: 'DEPTH_STENCIL_ATTACHMENT',
+  33635: 'UNSIGNED_SHORT_5_6_5',
+  33648: 'MIRRORED_REPEAT',
+  33901: 'ALIASED_POINT_SIZE_RANGE',
+  33902: 'ALIASED_LINE_WIDTH_RANGE',
+  33984: 'TEXTURE0',
+  33985: 'TEXTURE1',
+  33986: 'TEXTURE2',
+  33987: 'TEXTURE3',
+  33988: 'TEXTURE4',
+  33989: 'TEXTURE5',
+  33990: 'TEXTURE6',
+  33991: 'TEXTURE7',
+  33992: 'TEXTURE8',
+  33993: 'TEXTURE9',
+  33994: 'TEXTURE10',
+  33995: 'TEXTURE11',
+  33996: 'TEXTURE12',
+  33997: 'TEXTURE13',
+  33998: 'TEXTURE14',
+  33999: 'TEXTURE15',
+  34000: 'TEXTURE16',
+  34001: 'TEXTURE17',
+  34002: 'TEXTURE18',
+  34003: 'TEXTURE19',
+  34004: 'TEXTURE20',
+  34005: 'TEXTURE21',
+  34006: 'TEXTURE22',
+  34007: 'TEXTURE23',
+  34008: 'TEXTURE24',
+  34009: 'TEXTURE25',
+  34010: 'TEXTURE26',
+  34011: 'TEXTURE27',
+  34012: 'TEXTURE28',
+  34013: 'TEXTURE29',
+  34014: 'TEXTURE30',
+  34015: 'TEXTURE31',
+  34016: 'ACTIVE_TEXTURE',
+  34024: 'MAX_RENDERBUFFER_SIZE',
+  34041: 'DEPTH_STENCIL',
+  34055: 'INCR_WRAP',
+  34056: 'DECR_WRAP',
+  34067: 'TEXTURE_CUBE_MAP',
+  34068: 'TEXTURE_BINDING_CUBE_MAP',
+  34069: 'TEXTURE_CUBE_MAP_POSITIVE_X',
+  34070: 'TEXTURE_CUBE_MAP_NEGATIVE_X',
+  34071: 'TEXTURE_CUBE_MAP_POSITIVE_Y',
+  34072: 'TEXTURE_CUBE_MAP_NEGATIVE_Y',
+  34073: 'TEXTURE_CUBE_MAP_POSITIVE_Z',
+  34074: 'TEXTURE_CUBE_MAP_NEGATIVE_Z',
+  34076: 'MAX_CUBE_MAP_TEXTURE_SIZE',
+  34338: 'VERTEX_ATTRIB_ARRAY_ENABLED',
+  34339: 'VERTEX_ATTRIB_ARRAY_SIZE',
+  34340: 'VERTEX_ATTRIB_ARRAY_STRIDE',
+  34341: 'VERTEX_ATTRIB_ARRAY_TYPE',
+  34342: 'CURRENT_VERTEX_ATTRIB',
+  34373: 'VERTEX_ATTRIB_ARRAY_POINTER',
+  34466: 'NUM_COMPRESSED_TEXTURE_FORMATS',
+  34467: 'COMPRESSED_TEXTURE_FORMATS',
+  34660: 'BUFFER_SIZE',
+  34661: 'BUFFER_USAGE',
+  34816: 'STENCIL_BACK_FUNC',
+  34817: 'STENCIL_BACK_FAIL',
+  34818: 'STENCIL_BACK_PASS_DEPTH_FAIL',
+  34819: 'STENCIL_BACK_PASS_DEPTH_PASS',
+  34877: 'BLEND_EQUATION_ALPHA',
+  34921: 'MAX_VERTEX_ATTRIBS',
+  34922: 'VERTEX_ATTRIB_ARRAY_NORMALIZED',
+  34930: 'MAX_TEXTURE_IMAGE_UNITS',
+  34962: 'ARRAY_BUFFER',
+  34963: 'ELEMENT_ARRAY_BUFFER',
+  34964: 'ARRAY_BUFFER_BINDING',
+  34965: 'ELEMENT_ARRAY_BUFFER_BINDING',
+  34975: 'VERTEX_ATTRIB_ARRAY_BUFFER_BINDING',
+  35040: 'STREAM_DRAW',
+  35044: 'STATIC_DRAW',
+  35048: 'DYNAMIC_DRAW',
+  35632: 'FRAGMENT_SHADER',
+  35633: 'VERTEX_SHADER',
+  35660: 'MAX_VERTEX_TEXTURE_IMAGE_UNITS',
+  35661: 'MAX_COMBINED_TEXTURE_IMAGE_UNITS',
+  35663: 'SHADER_TYPE',
+  35664: 'FLOAT_VEC2',
+  35665: 'FLOAT_VEC3',
+  35666: 'FLOAT_VEC4',
+  35667: 'INT_VEC2',
+  35668: 'INT_VEC3',
+  35669: 'INT_VEC4',
+  35670: 'BOOL',
+  35671: 'BOOL_VEC2',
+  35672: 'BOOL_VEC3',
+  35673: 'BOOL_VEC4',
+  35674: 'FLOAT_MAT2',
+  35675: 'FLOAT_MAT3',
+  35676: 'FLOAT_MAT4',
+  35678: 'SAMPLER_2D',
+  35680: 'SAMPLER_CUBE',
+  35712: 'DELETE_STATUS',
+  35713: 'COMPILE_STATUS',
+  35714: 'LINK_STATUS',
+  35715: 'VALIDATE_STATUS',
+  35716: 'INFO_LOG_LENGTH',
+  35717: 'ATTACHED_SHADERS',
+  35718: 'ACTIVE_UNIFORMS',
+  35719: 'ACTIVE_UNIFORM_MAX_LENGTH',
+  35720: 'SHADER_SOURCE_LENGTH',
+  35721: 'ACTIVE_ATTRIBUTES',
+  35722: 'ACTIVE_ATTRIBUTE_MAX_LENGTH',
+  35724: 'SHADING_LANGUAGE_VERSION',
+  35725: 'CURRENT_PROGRAM',
+  36003: 'STENCIL_BACK_REF',
+  36004: 'STENCIL_BACK_VALUE_MASK',
+  36005: 'STENCIL_BACK_WRITEMASK',
+  36006: 'FRAMEBUFFER_BINDING',
+  36007: 'RENDERBUFFER_BINDING',
+  36048: 'FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE',
+  36049: 'FRAMEBUFFER_ATTACHMENT_OBJECT_NAME',
+  36050: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL',
+  36051: 'FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE',
+  36053: 'FRAMEBUFFER_COMPLETE',
+  36054: 'FRAMEBUFFER_INCOMPLETE_ATTACHMENT',
+  36055: 'FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT',
+  36057: 'FRAMEBUFFER_INCOMPLETE_DIMENSIONS',
+  36061: 'FRAMEBUFFER_UNSUPPORTED',
+  36064: 'COLOR_ATTACHMENT0',
+  36096: 'DEPTH_ATTACHMENT',
+  36128: 'STENCIL_ATTACHMENT',
+  36160: 'FRAMEBUFFER',
+  36161: 'RENDERBUFFER',
+  36162: 'RENDERBUFFER_WIDTH',
+  36163: 'RENDERBUFFER_HEIGHT',
+  36164: 'RENDERBUFFER_INTERNAL_FORMAT',
+  36168: 'STENCIL_INDEX8',
+  36176: 'RENDERBUFFER_RED_SIZE',
+  36177: 'RENDERBUFFER_GREEN_SIZE',
+  36178: 'RENDERBUFFER_BLUE_SIZE',
+  36179: 'RENDERBUFFER_ALPHA_SIZE',
+  36180: 'RENDERBUFFER_DEPTH_SIZE',
+  36181: 'RENDERBUFFER_STENCIL_SIZE',
+  36194: 'RGB565',
+  36336: 'LOW_FLOAT',
+  36337: 'MEDIUM_FLOAT',
+  36338: 'HIGH_FLOAT',
+  36339: 'LOW_INT',
+  36340: 'MEDIUM_INT',
+  36341: 'HIGH_INT',
+  36346: 'SHADER_COMPILER',
+  36347: 'MAX_VERTEX_UNIFORM_VECTORS',
+  36348: 'MAX_VARYING_VECTORS',
+  36349: 'MAX_FRAGMENT_UNIFORM_VECTORS',
+  37440: 'UNPACK_FLIP_Y_WEBGL',
+  37441: 'UNPACK_PREMULTIPLY_ALPHA_WEBGL',
+  37442: 'CONTEXT_LOST_WEBGL',
+  37443: 'UNPACK_COLORSPACE_CONVERSION_WEBGL',
+  37444: 'BROWSER_DEFAULT_WEBGL'
+}
+
+},{}],166:[function(require,module,exports){
+var gl10 = require('./1.0/numbers')
+
+module.exports = function lookupConstant (number) {
+  return gl10[number]
+}
+
+},{"./1.0/numbers":165}],167:[function(require,module,exports){
+var tokenize = require('glsl-tokenizer')
+var atob     = require('atob-lite')
+
+module.exports = getName
+
+function getName(src) {
+  var tokens = Array.isArray(src)
+    ? src
+    : tokenize(src)
+
+  for (var i = 0; i < tokens.length; i++) {
+    var token = tokens[i]
+    if (token.type !== 'preprocessor') continue
+    var match = token.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/)
+    if (!match) continue
+    if (!match[2]) continue
+
+    var b64  = match[1]
+    var name = match[2]
+
+    return (b64 ? atob(name) : name).trim()
+  }
+}
+
+},{"atob-lite":168,"glsl-tokenizer":173}],168:[function(require,module,exports){
+module.exports = function _atob(str) {
+  return atob(str)
+}
+
+},{}],169:[function(require,module,exports){
+module.exports = tokenize
+
+var literals = require('./lib/literals')
+  , operators = require('./lib/operators')
+  , builtins = require('./lib/builtins')
+
+var NORMAL = 999          // <-- never emitted
+  , TOKEN = 9999          // <-- never emitted
+  , BLOCK_COMMENT = 0
+  , LINE_COMMENT = 1
+  , PREPROCESSOR = 2
+  , OPERATOR = 3
+  , INTEGER = 4
+  , FLOAT = 5
+  , IDENT = 6
+  , BUILTIN = 7
+  , KEYWORD = 8
+  , WHITESPACE = 9
+  , EOF = 10
+  , HEX = 11
+
+var map = [
+    'block-comment'
+  , 'line-comment'
+  , 'preprocessor'
+  , 'operator'
+  , 'integer'
+  , 'float'
+  , 'ident'
+  , 'builtin'
+  , 'keyword'
+  , 'whitespace'
+  , 'eof'
+  , 'integer'
+]
+
+function tokenize() {
+  var i = 0
+    , total = 0
+    , mode = NORMAL
+    , c
+    , last
+    , content = []
+    , tokens = []
+    , token_idx = 0
+    , token_offs = 0
+    , line = 1
+    , col = 0
+    , start = 0
+    , isnum = false
+    , isoperator = false
+    , input = ''
+    , len
+
+  return function(data) {
+    tokens = []
+    if (data !== null) return write(data)
+    return end()
+  }
+
+  function token(data) {
+    if (data.length) {
+      tokens.push({
+        type: map[mode]
+      , data: data
+      , position: start
+      , line: line
+      , column: col
+      })
+    }
+  }
+
+  function write(chunk) {
+    i = 0
+    input += chunk
+    len = input.length
+
+    var last
+
+    while(c = input[i], i < len) {
+      last = i
+
+      switch(mode) {
+        case BLOCK_COMMENT: i = block_comment(); break
+        case LINE_COMMENT: i = line_comment(); break
+        case PREPROCESSOR: i = preprocessor(); break
+        case OPERATOR: i = operator(); break
+        case INTEGER: i = integer(); break
+        case HEX: i = hex(); break
+        case FLOAT: i = decimal(); break
+        case TOKEN: i = readtoken(); break
+        case WHITESPACE: i = whitespace(); break
+        case NORMAL: i = normal(); break
+      }
+
+      if(last !== i) {
+        switch(input[last]) {
+          case '\n': col = 0; ++line; break
+          default: ++col; break
+        }
+      }
+    }
+
+    total += i
+    input = input.slice(i)
+    return tokens
+  }
+
+  function end(chunk) {
+    if(content.length) {
+      token(content.join(''))
+    }
+
+    mode = EOF
+    token('(eof)')
+    return tokens
+  }
+
+  function normal() {
+    content = content.length ? [] : content
+
+    if(last === '/' && c === '*') {
+      start = total + i - 1
+      mode = BLOCK_COMMENT
+      last = c
+      return i + 1
+    }
+
+    if(last === '/' && c === '/') {
+      start = total + i - 1
+      mode = LINE_COMMENT
+      last = c
+      return i + 1
+    }
+
+    if(c === '#') {
+      mode = PREPROCESSOR
+      start = total + i
+      return i
+    }
+
+    if(/\s/.test(c)) {
+      mode = WHITESPACE
+      start = total + i
+      return i
+    }
+
+    isnum = /\d/.test(c)
+    isoperator = /[^\w_]/.test(c)
+
+    start = total + i
+    mode = isnum ? INTEGER : isoperator ? OPERATOR : TOKEN
+    return i
+  }
+
+  function whitespace() {
+    if(/[^\s]/g.test(c)) {
+      token(content.join(''))
+      mode = NORMAL
+      return i
+    }
+    content.push(c)
+    last = c
+    return i + 1
+  }
+
+  function preprocessor() {
+    if(c === '\n' && last !== '\\') {
+      token(content.join(''))
+      mode = NORMAL
+      return i
+    }
+    content.push(c)
+    last = c
+    return i + 1
+  }
+
+  function line_comment() {
+    return preprocessor()
+  }
+
+  function block_comment() {
+    if(c === '/' && last === '*') {
+      content.push(c)
+      token(content.join(''))
+      mode = NORMAL
+      return i + 1
+    }
+
+    content.push(c)
+    last = c
+    return i + 1
+  }
+
+  function operator() {
+    if(last === '.' && /\d/.test(c)) {
+      mode = FLOAT
+      return i
+    }
+
+    if(last === '/' && c === '*') {
+      mode = BLOCK_COMMENT
+      return i
+    }
+
+    if(last === '/' && c === '/') {
+      mode = LINE_COMMENT
+      return i
+    }
+
+    if(c === '.' && content.length) {
+      while(determine_operator(content));
+
+      mode = FLOAT
+      return i
+    }
+
+    if(c === ';' || c === ')' || c === '(') {
+      if(content.length) while(determine_operator(content));
+      token(c)
+      mode = NORMAL
+      return i + 1
+    }
+
+    var is_composite_operator = content.length === 2 && c !== '='
+    if(/[\w_\d\s]/.test(c) || is_composite_operator) {
+      while(determine_operator(content));
+      mode = NORMAL
+      return i
+    }
+
+    content.push(c)
+    last = c
+    return i + 1
+  }
+
+  function determine_operator(buf) {
+    var j = 0
+      , idx
+      , res
+
+    do {
+      idx = operators.indexOf(buf.slice(0, buf.length + j).join(''))
+      res = operators[idx]
+
+      if(idx === -1) {
+        if(j-- + buf.length > 0) continue
+        res = buf.slice(0, 1).join('')
+      }
+
+      token(res)
+
+      start += res.length
+      content = content.slice(res.length)
+      return content.length
+    } while(1)
+  }
+
+  function hex() {
+    if(/[^a-fA-F0-9]/.test(c)) {
+      token(content.join(''))
+      mode = NORMAL
+      return i
+    }
+
+    content.push(c)
+    last = c
+    return i + 1
+  }
+
+  function integer() {
+    if(c === '.') {
+      content.push(c)
+      mode = FLOAT
+      last = c
+      return i + 1
+    }
+
+    if(/[eE]/.test(c)) {
+      content.push(c)
+      mode = FLOAT
+      last = c
+      return i + 1
+    }
+
+    if(c === 'x' && content.length === 1 && content[0] === '0') {
+      mode = HEX
+      content.push(c)
+      last = c
+      return i + 1
+    }
+
+    if(/[^\d]/.test(c)) {
+      token(content.join(''))
+      mode = NORMAL
+      return i
+    }
+
+    content.push(c)
+    last = c
+    return i + 1
+  }
+
+  function decimal() {
+    if(c === 'f') {
+      content.push(c)
+      last = c
+      i += 1
+    }
+
+    if(/[eE]/.test(c)) {
+      content.push(c)
+      last = c
+      return i + 1
+    }
+
+    if(/[^\d]/.test(c)) {
+      token(content.join(''))
+      mode = NORMAL
+      return i
+    }
+    content.push(c)
+    last = c
+    return i + 1
+  }
+
+  function readtoken() {
+    if(/[^\d\w_]/.test(c)) {
+      var contentstr = content.join('')
+      if(literals.indexOf(contentstr) > -1) {
+        mode = KEYWORD
+      } else if(builtins.indexOf(contentstr) > -1) {
+        mode = BUILTIN
+      } else {
+        mode = IDENT
+      }
+      token(content.join(''))
+      mode = NORMAL
+      return i
+    }
+    content.push(c)
+    last = c
+    return i + 1
+  }
+}
+
+},{"./lib/builtins":170,"./lib/literals":171,"./lib/operators":172}],170:[function(require,module,exports){
+module.exports = [
+    'gl_Position'
+  , 'gl_PointSize'
+  , 'gl_ClipVertex'
+  , 'gl_FragCoord'
+  , 'gl_FrontFacing'
+  , 'gl_FragColor'
+  , 'gl_FragData'
+  , 'gl_FragDepth'
+  , 'gl_Color'
+  , 'gl_SecondaryColor'
+  , 'gl_Normal'
+  , 'gl_Vertex'
+  , 'gl_MultiTexCoord0'
+  , 'gl_MultiTexCoord1'
+  , 'gl_MultiTexCoord2'
+  , 'gl_MultiTexCoord3'
+  , 'gl_MultiTexCoord4'
+  , 'gl_MultiTexCoord5'
+  , 'gl_MultiTexCoord6'
+  , 'gl_MultiTexCoord7'
+  , 'gl_FogCoord'
+  , 'gl_MaxLights'
+  , 'gl_MaxClipPlanes'
+  , 'gl_MaxTextureUnits'
+  , 'gl_MaxTextureCoords'
+  , 'gl_MaxVertexAttribs'
+  , 'gl_MaxVertexUniformComponents'
+  , 'gl_MaxVaryingFloats'
+  , 'gl_MaxVertexTextureImageUnits'
+  , 'gl_MaxCombinedTextureImageUnits'
+  , 'gl_MaxTextureImageUnits'
+  , 'gl_MaxFragmentUniformComponents'
+  , 'gl_MaxDrawBuffers'
+  , 'gl_ModelViewMatrix'
+  , 'gl_ProjectionMatrix'
+  , 'gl_ModelViewProjectionMatrix'
+  , 'gl_TextureMatrix'
+  , 'gl_NormalMatrix'
+  , 'gl_ModelViewMatrixInverse'
+  , 'gl_ProjectionMatrixInverse'
+  , 'gl_ModelViewProjectionMatrixInverse'
+  , 'gl_TextureMatrixInverse'
+  , 'gl_ModelViewMatrixTranspose'
+  , 'gl_ProjectionMatrixTranspose'
+  , 'gl_ModelViewProjectionMatrixTranspose'
+  , 'gl_TextureMatrixTranspose'
+  , 'gl_ModelViewMatrixInverseTranspose'
+  , 'gl_ProjectionMatrixInverseTranspose'
+  , 'gl_ModelViewProjectionMatrixInverseTranspose'
+  , 'gl_TextureMatrixInverseTranspose'
+  , 'gl_NormalScale'
+  , 'gl_DepthRangeParameters'
+  , 'gl_DepthRange'
+  , 'gl_ClipPlane'
+  , 'gl_PointParameters'
+  , 'gl_Point'
+  , 'gl_MaterialParameters'
+  , 'gl_FrontMaterial'
+  , 'gl_BackMaterial'
+  , 'gl_LightSourceParameters'
+  , 'gl_LightSource'
+  , 'gl_LightModelParameters'
+  , 'gl_LightModel'
+  , 'gl_LightModelProducts'
+  , 'gl_FrontLightModelProduct'
+  , 'gl_BackLightModelProduct'
+  , 'gl_LightProducts'
+  , 'gl_FrontLightProduct'
+  , 'gl_BackLightProduct'
+  , 'gl_FogParameters'
+  , 'gl_Fog'
+  , 'gl_TextureEnvColor'
+  , 'gl_EyePlaneS'
+  , 'gl_EyePlaneT'
+  , 'gl_EyePlaneR'
+  , 'gl_EyePlaneQ'
+  , 'gl_ObjectPlaneS'
+  , 'gl_ObjectPlaneT'
+  , 'gl_ObjectPlaneR'
+  , 'gl_ObjectPlaneQ'
+  , 'gl_FrontColor'
+  , 'gl_BackColor'
+  , 'gl_FrontSecondaryColor'
+  , 'gl_BackSecondaryColor'
+  , 'gl_TexCoord'
+  , 'gl_FogFragCoord'
+  , 'gl_Color'
+  , 'gl_SecondaryColor'
+  , 'gl_TexCoord'
+  , 'gl_FogFragCoord'
+  , 'gl_PointCoord'
+  , 'radians'
+  , 'degrees'
+  , 'sin'
+  , 'cos'
+  , 'tan'
+  , 'asin'
+  , 'acos'
+  , 'atan'
+  , 'pow'
+  , 'exp'
+  , 'log'
+  , 'exp2'
+  , 'log2'
+  , 'sqrt'
+  , 'inversesqrt'
+  , 'abs'
+  , 'sign'
+  , 'floor'
+  , 'ceil'
+  , 'fract'
+  , 'mod'
+  , 'min'
+  , 'max'
+  , 'clamp'
+  , 'mix'
+  , 'step'
+  , 'smoothstep'
+  , 'length'
+  , 'distance'
+  , 'dot'
+  , 'cross'
+  , 'normalize'
+  , 'faceforward'
+  , 'reflect'
+  , 'refract'
+  , 'matrixCompMult'
+  , 'lessThan'
+  , 'lessThanEqual'
+  , 'greaterThan'
+  , 'greaterThanEqual'
+  , 'equal'
+  , 'notEqual'
+  , 'any'
+  , 'all'
+  , 'not'
+  , 'texture2D'
+  , 'texture2DProj'
+  , 'texture2DLod'
+  , 'texture2DProjLod'
+  , 'textureCube'
+  , 'textureCubeLod'
+  , 'dFdx'
+  , 'dFdy'
+]
+
+},{}],171:[function(require,module,exports){
+module.exports = [
+  // current
+    'precision'
+  , 'highp'
+  , 'mediump'
+  , 'lowp'
+  , 'attribute'
+  , 'const'
+  , 'uniform'
+  , 'varying'
+  , 'break'
+  , 'continue'
+  , 'do'
+  , 'for'
+  , 'while'
+  , 'if'
+  , 'else'
+  , 'in'
+  , 'out'
+  , 'inout'
+  , 'float'
+  , 'int'
+  , 'void'
+  , 'bool'
+  , 'true'
+  , 'false'
+  , 'discard'
+  , 'return'
+  , 'mat2'
+  , 'mat3'
+  , 'mat4'
+  , 'vec2'
+  , 'vec3'
+  , 'vec4'
+  , 'ivec2'
+  , 'ivec3'
+  , 'ivec4'
+  , 'bvec2'
+  , 'bvec3'
+  , 'bvec4'
+  , 'sampler1D'
+  , 'sampler2D'
+  , 'sampler3D'
+  , 'samplerCube'
+  , 'sampler1DShadow'
+  , 'sampler2DShadow'
+  , 'struct'
+
+  // future
+  , 'asm'
+  , 'class'
+  , 'union'
+  , 'enum'
+  , 'typedef'
+  , 'template'
+  , 'this'
+  , 'packed'
+  , 'goto'
+  , 'switch'
+  , 'default'
+  , 'inline'
+  , 'noinline'
+  , 'volatile'
+  , 'public'
+  , 'static'
+  , 'extern'
+  , 'external'
+  , 'interface'
+  , 'long'
+  , 'short'
+  , 'double'
+  , 'half'
+  , 'fixed'
+  , 'unsigned'
+  , 'input'
+  , 'output'
+  , 'hvec2'
+  , 'hvec3'
+  , 'hvec4'
+  , 'dvec2'
+  , 'dvec3'
+  , 'dvec4'
+  , 'fvec2'
+  , 'fvec3'
+  , 'fvec4'
+  , 'sampler2DRect'
+  , 'sampler3DRect'
+  , 'sampler2DRectShadow'
+  , 'sizeof'
+  , 'cast'
+  , 'namespace'
+  , 'using'
+]
+
+},{}],172:[function(require,module,exports){
+module.exports = [
+    '<<='
+  , '>>='
+  , '++'
+  , '--'
+  , '<<'
+  , '>>'
+  , '<='
+  , '>='
+  , '=='
+  , '!='
+  , '&&'
+  , '||'
+  , '+='
+  , '-='
+  , '*='
+  , '/='
+  , '%='
+  , '&='
+  , '^^'
+  , '^='
+  , '|='
+  , '('
+  , ')'
+  , '['
+  , ']'
+  , '.'
+  , '!'
+  , '~'
+  , '*'
+  , '/'
+  , '%'
+  , '+'
+  , '-'
+  , '<'
+  , '>'
+  , '&'
+  , '^'
+  , '|'
+  , '?'
+  , ':'
+  , '='
+  , ','
+  , ';'
+  , '{'
+  , '}'
+]
+
+},{}],173:[function(require,module,exports){
+var tokenize = require('./index')
+
+module.exports = tokenizeString
+
+function tokenizeString(str) {
+  var generator = tokenize()
+  var tokens = []
+
+  tokens = tokens.concat(generator(str))
+  tokens = tokens.concat(generator(null))
+
+  return tokens
+}
+
+},{"./index":169}],174:[function(require,module,exports){
+(function(window) {
+    var re = {
+        not_string: /[^s]/,
+        number: /[diefg]/,
+        json: /[j]/,
+        not_json: /[^j]/,
+        text: /^[^\x25]+/,
+        modulo: /^\x25{2}/,
+        placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/,
+        key: /^([a-z_][a-z_\d]*)/i,
+        key_access: /^\.([a-z_][a-z_\d]*)/i,
+        index_access: /^\[(\d+)\]/,
+        sign: /^[\+\-]/
+    }
+
+    function sprintf() {
+        var key = arguments[0], cache = sprintf.cache
+        if (!(cache[key] && cache.hasOwnProperty(key))) {
+            cache[key] = sprintf.parse(key)
+        }
+        return sprintf.format.call(null, cache[key], arguments)
+    }
+
+    sprintf.format = function(parse_tree, argv) {
+        var cursor = 1, tree_length = parse_tree.length, node_type = "", arg, output = [], i, k, match, pad, pad_character, pad_length, is_positive = true, sign = ""
+        for (i = 0; i < tree_length; i++) {
+            node_type = get_type(parse_tree[i])
+            if (node_type === "string") {
+                output[output.length] = parse_tree[i]
+            }
+            else if (node_type === "array") {
+                match = parse_tree[i] // convenience purposes only
+                if (match[2]) { // keyword argument
+                    arg = argv[cursor]
+                    for (k = 0; k < match[2].length; k++) {
+                        if (!arg.hasOwnProperty(match[2][k])) {
+                            throw new Error(sprintf("[sprintf] property '%s' does not exist", match[2][k]))
+                        }
+                        arg = arg[match[2][k]]
+                    }
+                }
+                else if (match[1]) { // positional argument (explicit)
+                    arg = argv[match[1]]
+                }
+                else { // positional argument (implicit)
+                    arg = argv[cursor++]
+                }
+
+                if (get_type(arg) == "function") {
+                    arg = arg()
+                }
+
+                if (re.not_string.test(match[8]) && re.not_json.test(match[8]) && (get_type(arg) != "number" && isNaN(arg))) {
+                    throw new TypeError(sprintf("[sprintf] expecting number but found %s", get_type(arg)))
+                }
+
+                if (re.number.test(match[8])) {
+                    is_positive = arg >= 0
+                }
+
+                switch (match[8]) {
+                    case "b":
+                        arg = arg.toString(2)
+                    break
+                    case "c":
+                        arg = String.fromCharCode(arg)
+                    break
+                    case "d":
+                    case "i":
+                        arg = parseInt(arg, 10)
+                    break
+                    case "j":
+                        arg = JSON.stringify(arg, null, match[6] ? parseInt(match[6]) : 0)
+                    break
+                    case "e":
+                        arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential()
+                    break
+                    case "f":
+                        arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg)
+                    break
+                    case "g":
+                        arg = match[7] ? parseFloat(arg).toPrecision(match[7]) : parseFloat(arg)
+                    break
+                    case "o":
+                        arg = arg.toString(8)
+                    break
+                    case "s":
+                        arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg)
+                    break
+                    case "u":
+                        arg = arg >>> 0
+                    break
+                    case "x":
+                        arg = arg.toString(16)
+                    break
+                    case "X":
+                        arg = arg.toString(16).toUpperCase()
+                    break
+                }
+                if (re.json.test(match[8])) {
+                    output[output.length] = arg
+                }
+                else {
+                    if (re.number.test(match[8]) && (!is_positive || match[3])) {
+                        sign = is_positive ? "+" : "-"
+                        arg = arg.toString().replace(re.sign, "")
+                    }
+                    else {
+                        sign = ""
+                    }
+                    pad_character = match[4] ? match[4] === "0" ? "0" : match[4].charAt(1) : " "
+                    pad_length = match[6] - (sign + arg).length
+                    pad = match[6] ? (pad_length > 0 ? str_repeat(pad_character, pad_length) : "") : ""
+                    output[output.length] = match[5] ? sign + arg + pad : (pad_character === "0" ? sign + pad + arg : pad + sign + arg)
+                }
+            }
+        }
+        return output.join("")
+    }
+
+    sprintf.cache = {}
+
+    sprintf.parse = function(fmt) {
+        var _fmt = fmt, match = [], parse_tree = [], arg_names = 0
+        while (_fmt) {
+            if ((match = re.text.exec(_fmt)) !== null) {
+                parse_tree[parse_tree.length] = match[0]
+            }
+            else if ((match = re.modulo.exec(_fmt)) !== null) {
+                parse_tree[parse_tree.length] = "%"
+            }
+            else if ((match = re.placeholder.exec(_fmt)) !== null) {
+                if (match[2]) {
+                    arg_names |= 1
+                    var field_list = [], replacement_field = match[2], field_match = []
+                    if ((field_match = re.key.exec(replacement_field)) !== null) {
+                        field_list[field_list.length] = field_match[1]
+                        while ((replacement_field = replacement_field.substring(field_match[0].length)) !== "") {
+                            if ((field_match = re.key_access.exec(replacement_field)) !== null) {
+                                field_list[field_list.length] = field_match[1]
+                            }
+                            else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
+                                field_list[field_list.length] = field_match[1]
+                            }
+                            else {
+                                throw new SyntaxError("[sprintf] failed to parse named argument key")
+                            }
+                        }
+                    }
+                    else {
+                        throw new SyntaxError("[sprintf] failed to parse named argument key")
+                    }
+                    match[2] = field_list
+                }
+                else {
+                    arg_names |= 2
+                }
+                if (arg_names === 3) {
+                    throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported")
+                }
+                parse_tree[parse_tree.length] = match
+            }
+            else {
+                throw new SyntaxError("[sprintf] unexpected placeholder")
+            }
+            _fmt = _fmt.substring(match[0].length)
+        }
+        return parse_tree
+    }
+
+    var vsprintf = function(fmt, argv, _argv) {
+        _argv = (argv || []).slice(0)
+        _argv.splice(0, 0, fmt)
+        return sprintf.apply(null, _argv)
+    }
+
+    /**
+     * helpers
+     */
+    function get_type(variable) {
+        return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase()
+    }
+
+    function str_repeat(input, multiplier) {
+        return Array(multiplier + 1).join(input)
+    }
+
+    /**
+     * export to either browser or node.js
+     */
+    if (typeof exports !== "undefined") {
+        exports.sprintf = sprintf
+        exports.vsprintf = vsprintf
+    }
+    else {
+        window.sprintf = sprintf
+        window.vsprintf = vsprintf
+
+        if (typeof define === "function" && define.amd) {
+            define(function() {
+                return {
+                    sprintf: sprintf,
+                    vsprintf: vsprintf
+                }
+            })
+        }
+    }
+})(typeof window === "undefined" ? this : window);
+
+},{}],175:[function(require,module,exports){
+var hiddenStore = require('./hidden-store.js');
+
+module.exports = createStore;
+
+function createStore() {
+    var key = {};
+
+    return function (obj) {
+        if ((typeof obj !== 'object' || obj === null) &&
+            typeof obj !== 'function'
+        ) {
+            throw new Error('Weakmap-shim: Key must be object')
+        }
+
+        var store = obj.valueOf(key);
+        return store && store.identity === key ?
+            store : hiddenStore(obj, key);
+    };
+}
+
+},{"./hidden-store.js":176}],176:[function(require,module,exports){
+module.exports = hiddenStore;
+
+function hiddenStore(obj, key) {
+    var store = { identity: key };
+    var valueOf = obj.valueOf;
+
+    Object.defineProperty(obj, "valueOf", {
+        value: function (value) {
+            return value !== key ?
+                valueOf.apply(this, arguments) : store;
+        },
+        writable: true
+    });
+
+    return store;
+}
+
+},{}],177:[function(require,module,exports){
+// Original - @Gozola. 
+// https://gist.github.com/Gozala/1269991
+// This is a reimplemented version (with a few bug fixes).
+
+var createStore = require('./create-store.js');
+
+module.exports = weakMap;
+
+function weakMap() {
+    var privates = createStore();
+
+    return {
+        'get': function (key, fallback) {
+            var store = privates(key)
+            return store.hasOwnProperty('value') ?
+                store.value : fallback
+        },
+        'set': function (key, value) {
+            privates(key).value = value;
+        },
+        'has': function(key) {
+            return 'value' in privates(key);
+        },
+        'delete': function (key) {
+            return delete privates(key).value;
+        }
+    }
+}
+
+},{"./create-store.js":175}],178:[function(require,module,exports){
+'use strict'
+
+module.exports = createSpikes2D
+
+function GLSpikes2D(plot) {
+  this.plot = plot
+  this.enable = [true, true, false, false]
+  this.width  = [1, 1, 1, 1]
+  this.color  = [[0,0,0,1],
+                 [0,0,0,1],
+                 [0,0,0,1],
+                 [0,0,0,1]]
+  this.center = [Infinity, Infinity]
+}
+
+var proto = GLSpikes2D.prototype
+
+proto.update = function(options) {
+  options = options || {}
+  this.enable = (options.enable || [true,true,false,false]).slice()
+  this.width  = (options.width || [1,1,1,1]).slice()
+  this.color  = (options.color || [
+                  [0,0,0,1],
+                  [0,0,0,1],
+                  [0,0,0,1],
+                  [0,0,0,1]]).map(function(x) { return x.slice() })
+  this.center = (options.center || [Infinity,Infinity]).slice()
+  this.plot.setOverlayDirty()
+}
+
+proto.draw = function() {
+  var spikeEnable = this.enable
+  var spikeWidth  = this.width
+  var spikeColor  = this.color
+  var spikeCenter = this.center
+  var plot        = this.plot
+  var line        = plot.line
+
+  var dataBox     = plot.dataBox
+  var viewPixels  = plot.viewBox
+
+  line.bind()
+
+  if(dataBox[0] <= spikeCenter[0] && spikeCenter[0] <= dataBox[2] &&
+     dataBox[1] <= spikeCenter[1] && spikeCenter[1] <= dataBox[3]) {
+
+    var centerX = viewPixels[0] + (spikeCenter[0] - dataBox[0]) / (dataBox[2] - dataBox[0]) * (viewPixels[2] - viewPixels[0])
+    var centerY = viewPixels[1] + (spikeCenter[1] - dataBox[1]) / (dataBox[3] - dataBox[1]) * (viewPixels[3] - viewPixels[1])
+
+    if(spikeEnable[0]) {
+     line.drawLine(
+       centerX, centerY,
+       viewPixels[0], centerY,
+       spikeWidth[0], spikeColor[0])
+    }
+    if(spikeEnable[1]) {
+     line.drawLine(
+       centerX, centerY,
+       centerX, viewPixels[1],
+       spikeWidth[1], spikeColor[1])
+    }
+    if(spikeEnable[2]) {
+      line.drawLine(
+        centerX, centerY,
+        viewPixels[2], centerY,
+        spikeWidth[2], spikeColor[2])
+    }
+    if(spikeEnable[3]) {
+      line.drawLine(
+        centerX, centerY,
+        centerX, viewPixels[3],
+        spikeWidth[3], spikeColor[3])
+    }
+  }
+}
+
+proto.dispose = function() {
+  this.plot.removeOverlay(this)
+}
+
+function createSpikes2D(plot, options) {
+  var spikes = new GLSpikes2D(plot)
+  spikes.update(options)
+  plot.addOverlay(spikes)
+  return spikes
+}
+
+},{}],179:[function(require,module,exports){
+var createShader  = require('gl-shader')
+
+
+var vertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec4 uv;\nattribute vec2 f;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n  worldCoordinate = vec3(uv.zw, f.x);\n  vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n  vec4 clipPosition = projection * view * worldPosition;\n  gl_Position = clipPosition;\n  value = f.x;\n  kill = f.y;\n  planeCoordinate = uv.xy;\n  \n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * worldPosition;\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  lightDirection = lightPosition - cameraCoordinate.xyz;\n  eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  surfaceNormal  = normalize((vec4(normal,0) * inverseModel).xyz);\n}"
+var fragSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat beckmannSpecular_1_1(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness) {\n  return beckmannDistribution_2_0(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\n\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n  if(kill > 0.0 ||\n    any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n    discard;\n  }\n\n  vec3 N = normalize(surfaceNormal);\n  vec3 V = normalize(eyeDirection);\n  vec3 L = normalize(lightDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = beckmannSpecular_1_1(L, V, N, roughness);\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  float interpValue = (value - lowerBound.z) / (upperBound.z - lowerBound.z);\n  vec4 surfaceColor = texture2D(colormap, vec2(interpValue, interpValue));\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n"
+var contourVertSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec4 uv;\n\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n  vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n  vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n  vec4 clipPosition = projection * view * worldPosition;\n  clipPosition.z = clipPosition.z + zOffset;\n\n  gl_Position = clipPosition;\n  value = dataCoordinate.z;\n  kill = -1.0;\n  worldCoordinate = dataCoordinate;\n  planeCoordinate = uv.zw;\n\n  //Don't do lighting for contours\n  surfaceNormal   = vec3(1,0,0);\n  eyeDirection    = vec3(0,1,0);\n  lightDirection  = vec3(0,0,1);\n}\n"
+var pickSrc = "#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n  float vh = 255.0 * v;\n  float upper = floor(vh);\n  float lower = fract(vh);\n  return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n  if(kill > 0.0 || \n    any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n    discard;\n  }\n  vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n  vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n  gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}"
+
+exports.createShader = function(gl) {
+  var shader = createShader(gl, vertSrc, fragSrc, null, [
+    {name: 'uv', type: 'vec4'},
+    {name: 'f', type: 'vec2'},
+    {name: 'normal', type: 'vec3'}
+  ])
+  shader.attributes.uv.location = 0
+  shader.attributes.f.location = 1
+  shader.attributes.normal.location = 2
+  return shader
+}
+exports.createPickShader = function(gl) {
+  var shader = createShader(gl, vertSrc, pickSrc, null, [
+    {name: 'uv', type: 'vec4'},
+    {name: 'f', type: 'vec2'},
+    {name: 'normal', type: 'vec3'}
+  ])
+  shader.attributes.uv.location = 0
+  shader.attributes.f.location = 1
+  shader.attributes.normal.location = 2
+  return shader
+}
+exports.createContourShader = function(gl) {
+  var shader = createShader(gl, contourVertSrc, fragSrc, null, [
+    {name: 'uv', type: 'vec4'}
+  ])
+  shader.attributes.uv.location = 0
+  return shader
+}
+exports.createPickContourShader = function(gl) {
+  var shader = createShader(gl, contourVertSrc, pickSrc, null, [
+    {name: 'uv', type: 'vec4'}
+  ])
+  shader.attributes.uv.location = 0
+  return shader
+}
+
+},{"gl-shader":154}],180:[function(require,module,exports){
+arguments[4][20][0].apply(exports,arguments)
+},{"dup":20}],181:[function(require,module,exports){
+'use strict'
+
+module.exports      = gradient
+
+var dup             = require('dup')
+var cwiseCompiler   = require('cwise-compiler')
+
+var TEMPLATE_CACHE  = {}
+var GRADIENT_CACHE  = {}
+
+var EmptyProc = {
+  body: "",
+  args: [],
+  thisVars: [],
+  localVars: []
+}
+
+var centralDiff = cwiseCompiler({
+  args: [ 'array', 'array', 'array' ],
+  pre: EmptyProc,
+  post: EmptyProc,
+  body: {
+    args: [ {
+      name: 'out', 
+      lvalue: true,
+      rvalue: false,
+      count: 1
+    }, {
+      name: 'left', 
+      lvalue: false,
+      rvalue: true,
+      count: 1
+    }, {
+      name: 'right', 
+      lvalue: false,
+      rvalue: true,
+      count: 1
+    }],
+    body: "out=0.5*(left-right)",
+    thisVars: [],
+    localVars: []
+  },
+  funcName: 'cdiff'
+})
+
+var zeroOut = cwiseCompiler({
+  args: [ 'array' ],
+  pre: EmptyProc,
+  post: EmptyProc,
+  body: {
+    args: [ {
+      name: 'out', 
+      lvalue: true,
+      rvalue: false,
+      count: 1
+    }],
+    body: "out=0",
+    thisVars: [],
+    localVars: []
+  },
+  funcName: 'zero'
+})
+
+function generateTemplate(d) {
+  if(d in TEMPLATE_CACHE) {
+    return TEMPLATE_CACHE[d]
+  }
+  var code = []
+  for(var i=0; i<d; ++i) {
+    code.push('out', i, 's=0.5*(inp', i, 'l-inp', i, 'r);')
+  }
+  var args = [ 'array' ]
+  var names = ['junk']
+  for(var i=0; i<d; ++i) {
+    args.push('array')
+    names.push('out' + i + 's')
+    var o = dup(d)
+    o[i] = -1
+    args.push({
+      array: 0,
+      offset: o.slice()
+    })
+    o[i] = 1
+    args.push({
+      array: 0,
+      offset: o.slice()
+    })
+    names.push('inp' + i + 'l', 'inp' + i + 'r')
+  }
+  return TEMPLATE_CACHE[d] = cwiseCompiler({
+    args: args,
+    pre:  EmptyProc,
+    post: EmptyProc,
+    body: {
+      body: code.join(''),
+      args: names.map(function(n) {
+        return {
+          name: n,
+          lvalue: n.indexOf('out') === 0,
+          rvalue: n.indexOf('inp') === 0,
+          count: (n!=='junk')|0
+        }
+      }),
+      thisVars: [],
+      localVars: []
+    },
+    funcName: 'fdTemplate' + d
+  })
+}
+
+function generateGradient(boundaryConditions) {
+  var token = boundaryConditions.join()
+  var proc = GRADIENT_CACHE[token]
+  if(proc) {
+    return proc
+  }
+
+  var d = boundaryConditions.length
+  var code = ['function gradient(dst,src){var s=src.shape.slice();' ]
+  
+  function handleBoundary(facet) {
+    var cod = d - facet.length
+
+    var loStr = []
+    var hiStr = []
+    var pickStr = []
+    for(var i=0; i<d; ++i) {
+      if(facet.indexOf(i+1) >= 0) {
+        pickStr.push('0')
+      } else if(facet.indexOf(-(i+1)) >= 0) {
+        pickStr.push('s['+i+']-1')
+      } else {
+        pickStr.push('-1')
+        loStr.push('1')
+        hiStr.push('s['+i+']-2')
+      }
+    }
+    var boundStr = '.lo(' + loStr.join() + ').hi(' + hiStr.join() + ')'
+    if(loStr.length === 0) {
+      boundStr = ''
+    }
+        
+    if(cod > 0) {
+      code.push('if(1') 
+      for(var i=0; i<d; ++i) {
+        if(facet.indexOf(i+1) >= 0 || facet.indexOf(-(i+1)) >= 0) {
+          continue
+        }
+        code.push('&&s[', i, ']>2')
+      }
+      code.push('){grad', cod, '(src.pick(', pickStr.join(), ')', boundStr)
+      for(var i=0; i<d; ++i) {
+        if(facet.indexOf(i+1) >= 0 || facet.indexOf(-(i+1)) >= 0) {
+          continue
+        }
+        code.push(',dst.pick(', pickStr.join(), ',', i, ')', boundStr)
+      }
+      code.push(');')
+    }
+
+    for(var i=0; i<facet.length; ++i) {
+      var bnd = Math.abs(facet[i])-1
+      var outStr = 'dst.pick(' + pickStr.join() + ',' + bnd + ')' + boundStr
+      switch(boundaryConditions[bnd]) {
+
+        case 'clamp':
+          var cPickStr = pickStr.slice()
+          var dPickStr = pickStr.slice()
+          if(facet[i] < 0) {
+            cPickStr[bnd] = 's[' + bnd + ']-2'
+          } else {
+            dPickStr[bnd] = '1'
+          }
+          if(cod === 0) {
+            code.push('if(s[', bnd, ']>1){dst.set(',
+              pickStr.join(), ',', bnd, ',0.5*(src.get(',
+                cPickStr.join(), ')-src.get(',
+                dPickStr.join(), ')))}else{dst.set(',
+              pickStr.join(), ',', bnd, ',0)};')
+          } else {
+            code.push('if(s[', bnd, ']>1){diff(', outStr, 
+                ',src.pick(', cPickStr.join(), ')', boundStr, 
+                ',src.pick(', dPickStr.join(), ')', boundStr, 
+                ');}else{zero(', outStr, ');};')
+          }
+        break
+
+        case 'mirror':
+          if(cod === 0) {
+            code.push('dst.set(', pickStr.join(), ',', bnd, ',0);')
+          } else {
+            code.push('zero(', outStr, ');')
+          }
+        break
+
+        case 'wrap':
+          var aPickStr = pickStr.slice()
+          var bPickStr = pickStr.slice()
+          if(facet[i] < 0) {
+            aPickStr[bnd] = 's[' + bnd + ']-2'
+            bPickStr[bnd] = '0'
+            
+          } else {
+            aPickStr[bnd] = 's[' + bnd + ']-1'
+            bPickStr[bnd] = '1'
+          }
+          if(cod === 0) {
+            code.push('if(s[', bnd, ']>2){dst.set(',
+              pickStr.join(), ',', bnd, ',0.5*(src.get(',
+                aPickStr.join(), ')-src.get(',
+                bPickStr.join(), ')))}else{dst.set(',
+              pickStr.join(), ',', bnd, ',0)};')
+          } else {
+            code.push('if(s[', bnd, ']>2){diff(', outStr, 
+                ',src.pick(', aPickStr.join(), ')', boundStr, 
+                ',src.pick(', bPickStr.join(), ')', boundStr, 
+                ');}else{zero(', outStr, ');};')
+          }
+        break
+
+        default:
+          throw new Error('ndarray-gradient: Invalid boundary condition')
+      }
+    }
+
+    if(cod > 0) {
+      code.push('};')
+    }
+  }
+
+  //Enumerate ridges, facets, etc. of hypercube
+  for(var i=0; i<(1<<d); ++i) {
+    var faces = []
+    for(var j=0; j<d; ++j) {
+      if(i & (1<<j)) {
+        faces.push(j+1)
+      }
+    }
+    for(var k=0; k<(1<<faces.length); ++k) {
+      var sfaces = faces.slice()
+      for(var j=0; j<faces.length; ++j) {
+        if(k & (1<<j)) {
+          sfaces[j] = -sfaces[j]
+        }
+      }
+      handleBoundary(sfaces)
+    }
+  }
+
+  code.push('return dst;};return gradient')
+
+  //Compile and link routine, save cached procedure
+  var linkNames = [ 'diff', 'zero' ]
+  var linkArgs  = [ centralDiff, zeroOut ]
+  for(var i=1; i<=d; ++i) {
+    linkNames.push('grad' + i)
+    linkArgs.push(generateTemplate(i))
+  }
+  linkNames.push(code.join(''))
+
+  var link = Function.apply(void 0, linkNames)
+  var proc = link.apply(void 0, linkArgs)
+  TEMPLATE_CACHE[token] = proc
+  return proc
+}
+
+function gradient(out, inp, bc) {
+  if(Array.isArray(bc)) {
+    if(bc.length !== inp.dimension) {
+      throw new Error('ndarray-gradient: invalid boundary conditions')
+    }
+  } else if(typeof bc === 'string') {
+    bc = dup(inp.dimension, bc)
+  } else {
+    bc = dup(inp.dimension, 'clamp')
+  }
+  if(out.dimension !== inp.dimension + 1) {
+    throw new Error('ndarray-gradient: output dimension must be +1 input dimension')
+  }
+  if(out.shape[inp.dimension] !== inp.dimension) {
+    throw new Error('ndarray-gradient: output shape must match input shape')
+  }
+  for(var i=0; i<inp.dimension; ++i) {
+    if(out.shape[i] !== inp.shape[i]) {
+      throw new Error('ndarray-gradient: shape mismatch')
+    }
+  }
+  if(inp.size === 0) {
+    return out
+  }
+  if(inp.dimension <= 0) {
+    out.set(0)
+    return out
+  }
+  var cached = generateGradient(bc)
+  return cached(out, inp)
+}
+},{"cwise-compiler":66,"dup":72}],182:[function(require,module,exports){
+"use strict"
+
+var ndarray = require("ndarray")
+var do_convert = require("./doConvert.js")
+
+module.exports = function convert(arr, result) {
+  var shape = [], c = arr, sz = 1
+  while(c instanceof Array) {
+    shape.push(c.length)
+    sz *= c.length
+    c = c[0]
+  }
+  if(shape.length === 0) {
+    return ndarray()
+  }
+  if(!result) {
+    result = ndarray(new Float64Array(sz), shape)
+  }
+  do_convert(result, arr)
+  return result
+}
+
+},{"./doConvert.js":183,"ndarray":208}],183:[function(require,module,exports){
+module.exports=require('cwise-compiler')({"args":["array","scalar","index"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{\nvar _inline_1_v=_inline_1_arg1_,_inline_1_i\nfor(_inline_1_i=0;_inline_1_i<_inline_1_arg2_.length-1;++_inline_1_i) {\n_inline_1_v=_inline_1_v[_inline_1_arg2_[_inline_1_i]]\n}\n_inline_1_arg0_=_inline_1_v[_inline_1_arg2_[_inline_1_arg2_.length-1]]\n}","args":[{"name":"_inline_1_arg0_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_1_arg1_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_1_arg2_","lvalue":false,"rvalue":true,"count":4}],"thisVars":[],"localVars":["_inline_1_i","_inline_1_v"]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"funcName":"convert","blockSize":64})
+
+},{"cwise-compiler":66}],184:[function(require,module,exports){
+'use strict'
+
+module.exports = createSurfacePlot
+
+var bits          = require('bit-twiddle')
+var createBuffer  = require('gl-buffer')
+var createVAO     = require('gl-vao')
+var createTexture = require('gl-texture2d')
+var pool          = require('typedarray-pool')
+var colormap      = require('colormap')
+var ops           = require('ndarray-ops')
+var pack          = require('ndarray-pack')
+var ndarray       = require('ndarray')
+var surfaceNets   = require('surface-nets')
+var multiply      = require('gl-mat4/multiply')
+var invert        = require('gl-mat4/invert')
+var bsearch       = require('binary-search-bounds')
+var gradient      = require('ndarray-gradient')
+var ndarray       = require('ndarray')
+var shaders       = require('./lib/shaders')
+
+var createShader            = shaders.createShader
+var createContourShader     = shaders.createContourShader
+var createPickShader        = shaders.createPickShader
+var createPickContourShader = shaders.createPickContourShader
+
+var SURFACE_VERTEX_SIZE = 4 * (4 + 2 + 3)
+
+var IDENTITY = [
+  1, 0, 0, 0,
+  0, 1, 0, 0,
+  0, 0, 1, 0,
+  0, 0, 0, 1 ]
+
+var QUAD = [
+  [0, 0],
+  [0, 1],
+  [1, 0],
+  [1, 1],
+  [1, 0],
+  [0, 1]
+]
+
+var PERMUTATIONS = [
+  [0,0,0,0,0,0,0,0,0],
+  [0,0,0,0,0,0,0,0,0],
+  [0,0,0,0,0,0,0,0,0]
+]
+
+;(function() {
+  for(var i=0; i<3; ++i) {
+    var p = PERMUTATIONS[i]
+    var u = (i+1) % 3
+    var v = (i+2) % 3
+    p[u + 0] = 1
+    p[v + 3] = 1
+    p[i + 6] = 1
+  }
+})()
+
+function SurfacePickResult(position, index, uv, level, dataCoordinate) {
+  this.position     = position
+  this.index        = index
+  this.uv           = uv
+  this.level        = level
+  this.dataCoordinate = dataCoordinate
+}
+
+var N_COLORS = 265
+
+function genColormap(name) {
+  var x = pack([colormap({
+    colormap: name,
+    nshades: N_COLORS,
+    format: 'rgba'
+  }).map(function(c) {
+    return [c[0], c[1], c[2], 255*c[3]]
+  })])
+  ops.divseq(x, 255.0)
+  return x
+}
+
+function clampVec(v) {
+  var result = new Array(3)
+  for(var i=0; i<3; ++i) {
+    result[i] = Math.min(Math.max(v[i], -1e8), 1e8)
+  }
+  return result
+}
+
+function SurfacePlot(
+  gl,
+  shape,
+  bounds,
+  shader,
+  pickShader,
+  coordinates,
+  vao,
+  colorMap,
+  contourShader,
+  contourPickShader,
+  contourBuffer,
+  contourVAO,
+  dynamicBuffer,
+  dynamicVAO) {
+
+  this.gl                 = gl
+  this.shape              = shape
+  this.bounds             = bounds
+
+  this._shader            = shader
+  this._pickShader        = pickShader
+  this._coordinateBuffer  = coordinates
+  this._vao               = vao
+  this._colorMap          = colorMap
+
+  this._contourShader     = contourShader
+  this._contourPickShader = contourPickShader
+  this._contourBuffer     = contourBuffer
+  this._contourVAO        = contourVAO
+  this._contourOffsets    = [[], [], []]
+  this._contourCounts     = [[], [], []]
+  this._vertexCount       = 0
+
+  this._pickResult        = new SurfacePickResult([0,0,0], [0,0], [0,0], [0,0,0], [0,0,0])
+
+  this._dynamicBuffer     = dynamicBuffer
+  this._dynamicVAO        = dynamicVAO
+  this._dynamicOffsets    = [0,0,0]
+  this._dynamicCounts     = [0,0,0]
+
+  this.contourWidth       = [ 1, 1, 1 ]
+  this.contourLevels      = [[1], [1], [1]]
+  this.contourTint        = [0, 0, 0]
+  this.contourColor       = [[0.5,0.5,0.5,1], [0.5,0.5,0.5,1], [0.5,0.5,0.5,1]]
+
+  this.showContour        = true
+  this.showSurface        = true
+
+  this.enableHighlight    = [true, true, true]
+  this.highlightColor     = [[0,0,0,1], [0,0,0,1], [0,0,0,1]]
+  this.highlightTint      = [ 1, 1, 1 ]
+  this.highlightLevel     = [-1, -1, -1]
+
+  //Dynamic contour options
+  this.enableDynamic      = [ true, true, true ]
+  this.dynamicLevel       = [ NaN, NaN, NaN ]
+  this.dynamicColor       = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1] ]
+  this.dynamicTint        = [ 1, 1, 1 ]
+  this.dynamicWidth       = [ 1, 1, 1 ]
+
+  this.axesBounds         = [[Infinity,Infinity,Infinity],[-Infinity,-Infinity,-Infinity]]
+  this.surfaceProject     = [ false, false, false ]
+  this.contourProject     = [[ false, false, false ],
+                             [ false, false, false ],
+                             [ false, false, false ]]
+
+  this.colorBounds        = [ false, false ]
+
+  //Store xyz fields, need this for picking
+  this._field             = [
+      ndarray(pool.mallocFloat(1024), [0,0]),
+      ndarray(pool.mallocFloat(1024), [0,0]),
+      ndarray(pool.mallocFloat(1024), [0,0]) ]
+
+  this.pickId             = 1
+  this.clipBounds         = [[-Infinity,-Infinity,-Infinity],[Infinity,Infinity,Infinity]]
+
+  this.snapToData         = false
+
+  this.opacity            = 1.0
+
+  this.lightPosition      = [10, 10000, 0]
+  this.ambientLight       = 0.8
+  this.diffuseLight       = 0.8
+  this.specularLight      = 2.0
+  this.roughness          = 0.5
+  this.fresnel            = 1.5
+
+  this.dirty              = true
+}
+
+var proto = SurfacePlot.prototype
+
+proto.isTransparent = function() {
+  return this.opacity < 1
+}
+
+proto.isOpaque = function() {
+  if(this.opacity >= 1) {
+    return true
+  }
+  for(var i=0; i<3; ++i) {
+    if(this._contourCounts[i].length > 0 || this._dynamicCounts[i] > 0) {
+      return true
+    }
+  }
+  return false
+}
+
+proto.pickSlots = 1
+
+proto.setPickBase = function(id) {
+  this.pickId = id
+}
+
+var ZERO_VEC = [0,0,0]
+
+var PROJECT_DATA = {
+  showSurface: false,
+  showContour: false,
+  projections: [IDENTITY.slice(), IDENTITY.slice(), IDENTITY.slice()],
+  clipBounds:   [
+    [[0,0,0], [0,0,0]],
+    [[0,0,0], [0,0,0]],
+    [[0,0,0], [0,0,0]]]
+}
+
+function computeProjectionData(camera, obj) {
+  //Compute cube properties
+  var cubeAxis  = (obj.axes && obj.axes.lastCubeProps.axis) || ZERO_VEC
+
+  var showSurface = obj.showSurface
+  var showContour = obj.showContour
+
+  for(var i=0; i<3; ++i) {
+    showSurface = showSurface || obj.surfaceProject[i]
+    for(var j=0; j<3; ++j) {
+      showContour = showContour || obj.contourProject[i][j]
+    }
+  }
+
+  for(var i=0; i<3; ++i) {
+    //Construct projection onto axis
+    var axisSquish = PROJECT_DATA.projections[i]
+    for(var j=0; j<16; ++j) {
+      axisSquish[j] = 0
+    }
+    for(var j=0; j<4; ++j) {
+      axisSquish[5*j] = 1
+    }
+    axisSquish[5*i] = 0
+    axisSquish[12+i] = obj.axesBounds[+(cubeAxis[i]>0)][i]
+    multiply(axisSquish, camera.model, axisSquish)
+
+    var nclipBounds = PROJECT_DATA.clipBounds[i]
+    for(var k=0; k<2; ++k) {
+      for(var j=0; j<3; ++j) {
+        nclipBounds[k][j] = camera.clipBounds[k][j]
+      }
+    }
+    nclipBounds[0][i] = -1e8
+    nclipBounds[1][i] = 1e8
+  }
+
+  PROJECT_DATA.showSurface = showSurface
+  PROJECT_DATA.showContour = showContour
+
+  return PROJECT_DATA
+}
+
+var UNIFORMS = {
+  model:      IDENTITY,
+  view:       IDENTITY,
+  projection: IDENTITY,
+  inverseModel: IDENTITY.slice(),
+  lowerBound: [0,0,0],
+  upperBound: [0,0,0],
+  colorMap:   0,
+  clipBounds: [[0,0,0], [0,0,0]],
+  height:     0.0,
+  contourTint: 0,
+  contourColor: [0,0,0,1],
+  permutation: [1,0,0,0,1,0,0,0,1],
+  zOffset: -1e-4,
+  kambient: 1,
+  kdiffuse: 1,
+  kspecular: 1,
+  lightPosition: [1000,1000,1000],
+  eyePosition: [0,0,0],
+  roughness: 1,
+  fresnel: 1,
+  opacity: 1
+}
+
+var MATRIX_INVERSE = IDENTITY.slice()
+var DEFAULT_PERM = [1,0,0,0,1,0,0,0,1]
+
+function drawCore(params, transparent) {
+  params = params || {}
+  var gl = this.gl
+
+  gl.disable(gl.CULL_FACE)
+
+  this._colorMap.bind(0)
+
+  var uniforms = UNIFORMS
+  uniforms.model        = params.model || IDENTITY
+  uniforms.view         = params.view || IDENTITY
+  uniforms.projection   = params.projection || IDENTITY
+  uniforms.lowerBound   = [this.bounds[0][0], this.bounds[0][1], this.colorBounds[0] || this.bounds[0][2]]
+  uniforms.upperBound   = [this.bounds[1][0], this.bounds[1][1], this.colorBounds[1] || this.bounds[1][2]]
+  uniforms.contourColor = this.contourColor[0]
+
+  uniforms.inverseModel = invert(uniforms.inverseModel, uniforms.model)
+
+  for(var i=0; i<2; ++i) {
+    var clipClamped = uniforms.clipBounds[i]
+    for(var j=0; j<3; ++j) {
+      clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8)
+    }
+  }
+
+  uniforms.kambient   = this.ambientLight
+  uniforms.kdiffuse   = this.diffuseLight
+  uniforms.kspecular  = this.specularLight
+
+  uniforms.shape =
+
+  uniforms.roughness  = this.roughness
+  uniforms.fresnel    = this.fresnel
+  uniforms.opacity    = this.opacity
+
+  uniforms.height = 0.0
+  uniforms.permutation = DEFAULT_PERM
+
+  //Compute camera matrix inverse
+  var invCameraMatrix = MATRIX_INVERSE
+  multiply(invCameraMatrix, uniforms.view, uniforms.model)
+  multiply(invCameraMatrix, uniforms.projection, invCameraMatrix)
+  invert(invCameraMatrix, invCameraMatrix)
+
+  for(var i=0; i<3; ++i) {
+    uniforms.eyePosition[i] = invCameraMatrix[12+i] / invCameraMatrix[15]
+  }
+
+  var w = invCameraMatrix[15]
+  for(var i=0; i<3; ++i) {
+    w += this.lightPosition[i] * invCameraMatrix[4*i+3]
+  }
+  for(var i=0; i<3; ++i) {
+    var s = invCameraMatrix[12+i]
+    for(var j=0; j<3; ++j) {
+      s += invCameraMatrix[4*j+i] * this.lightPosition[j]
+    }
+    uniforms.lightPosition[i] = s / w
+  }
+
+  var projectData = computeProjectionData(uniforms, this)
+
+  if(projectData.showSurface && (transparent === (this.opacity < 1))) {
+    //Set up uniforms
+    this._shader.bind()
+    this._shader.uniforms = uniforms
+
+    //Draw it
+    this._vao.bind()
+
+    if(this.showSurface) {
+      this._vao.draw(gl.TRIANGLES, this._vertexCount)
+    }
+
+    //Draw projections of surface
+    for(var i=0; i<3; ++i) {
+      if(!this.surfaceProject[i]) {
+        continue
+      }
+      this._shader.uniforms.model = projectData.projections[i]
+      this._shader.uniforms.clipBounds = projectData.clipBounds[i]
+      this._vao.draw(gl.TRIANGLES, this._vertexCount)
+    }
+
+    this._vao.unbind()
+  }
+
+  if(projectData.showContour && !transparent) {
+    var shader = this._contourShader
+
+    //Don't apply lighting to contours
+    uniforms.kambient = 1.0
+    uniforms.kdiffuse = 0.0
+    uniforms.kspecular = 0.0
+    uniforms.opacity = 1.0
+
+    shader.bind()
+    shader.uniforms = uniforms
+
+    //Draw contour lines
+    var vao = this._contourVAO
+    vao.bind()
+
+    //Draw contour levels
+    for(var i=0; i<3; ++i) {
+      shader.uniforms.permutation = PERMUTATIONS[i]
+      gl.lineWidth(this.contourWidth[i])
+
+      for(var j=0; j<this.contourLevels[i].length; ++j) {
+        if(j === this.highlightLevel[i]) {
+          shader.uniforms.contourColor = this.highlightColor[i]
+          shader.uniforms.contourTint  = this.highlightTint[i]
+
+        } else if(j === 0 || (j-1) === this.highlightLevel[i]) {
+          shader.uniforms.contourColor = this.contourColor[i]
+          shader.uniforms.contourTint  = this.contourTint[i]
+        }
+        shader.uniforms.height = this.contourLevels[i][j]
+        vao.draw(gl.LINES, this._contourCounts[i][j], this._contourOffsets[i][j])
+      }
+    }
+
+    //Draw projections of surface
+    for(var i=0; i<3; ++i) {
+      shader.uniforms.model      = projectData.projections[i]
+      shader.uniforms.clipBounds = projectData.clipBounds[i]
+      for(var j=0; j<3; ++j) {
+        if(!this.contourProject[i][j]) {
+          continue
+        }
+        shader.uniforms.permutation = PERMUTATIONS[j]
+        gl.lineWidth(this.contourWidth[j])
+        for(var k=0; k<this.contourLevels[j].length; ++k) {
+          if(k === this.highlightLevel[j]) {
+            shader.uniforms.contourColor  = this.highlightColor[j]
+            shader.uniforms.contourTint   = this.highlightTint[j]
+          } else if(k === 0 || (k-1) === this.highlightLevel[j]) {
+            shader.uniforms.contourColor  = this.contourColor[j]
+            shader.uniforms.contourTint   = this.contourTint[j]
+          }
+          shader.uniforms.height = this.contourLevels[j][k]
+          vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k])
+        }
+      }
+    }
+
+    //Draw dynamic contours
+    vao = this._dynamicVAO
+    vao.bind()
+
+    //Draw contour levels
+    for(var i=0; i<3; ++i) {
+      if(this._dynamicCounts[i] === 0) {
+        continue
+      }
+
+      shader.uniforms.model       = uniforms.model
+      shader.uniforms.clipBounds  = uniforms.clipBounds
+      shader.uniforms.permutation = PERMUTATIONS[i]
+      gl.lineWidth(this.dynamicWidth[i])
+
+      shader.uniforms.contourColor = this.dynamicColor[i]
+      shader.uniforms.contourTint  = this.dynamicTint[i]
+      shader.uniforms.height       = this.dynamicLevel[i]
+      vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i])
+
+      for(var j=0; j<3; ++j) {
+        if(!this.contourProject[j][i]) {
+          continue
+        }
+
+        shader.uniforms.model      = projectData.projections[j]
+        shader.uniforms.clipBounds = projectData.clipBounds[j]
+        vao.draw(gl.LINES, this._dynamicCounts[i], this._dynamicOffsets[i])
+      }
+    }
+
+    vao.unbind()
+  }
+}
+
+proto.draw = function(params) {
+  return drawCore.call(this, params, false)
+}
+
+proto.drawTransparent = function(params) {
+  return drawCore.call(this, params, true)
+}
+
+var PICK_UNIFORMS = {
+  model:          IDENTITY,
+  view:           IDENTITY,
+  projection:     IDENTITY,
+  inverseModel:   IDENTITY,
+  clipBounds:     [[0,0,0],[0,0,0]],
+  height:         0.0,
+  shape:          [0,0],
+  pickId:         0,
+  lowerBound:     [0,0,0],
+  upperBound:     [0,0,0],
+  zOffset:        0.0,
+  permutation:    [1,0,0,0,1,0,0,0,1],
+  lightPosition:  [0,0,0],
+  eyePosition:    [0,0,0]
+}
+
+proto.drawPick = function(params) {
+  params = params || {}
+  var gl = this.gl
+  gl.disable(gl.CULL_FACE)
+
+  var uniforms = PICK_UNIFORMS
+  uniforms.model = params.model || IDENTITY
+  uniforms.view = params.view || IDENTITY
+  uniforms.projection = params.projection || IDENTITY
+  uniforms.shape = this._field[2].shape
+  uniforms.pickId = this.pickId / 255.0
+  uniforms.lowerBound = this.bounds[0]
+  uniforms.upperBound = this.bounds[1]
+  uniforms.permutation = DEFAULT_PERM
+
+  for(var i=0; i<2; ++i) {
+    var clipClamped = uniforms.clipBounds[i]
+    for(var j=0; j<3; ++j) {
+      clipClamped[j] = Math.min(Math.max(this.clipBounds[i][j], -1e8), 1e8)
+    }
+  }
+
+  var projectData = computeProjectionData(uniforms, this)
+
+  if(projectData.showSurface) {
+    //Set up uniforms
+    this._pickShader.bind()
+    this._pickShader.uniforms = uniforms
+
+    //Draw it
+    this._vao.bind()
+    this._vao.draw(gl.TRIANGLES, this._vertexCount)
+
+    //Draw projections of surface
+    for(var i=0; i<3; ++i) {
+      if(!this.surfaceProject[i]) {
+        continue
+      }
+      this._pickShader.uniforms.model = projectData.projections[i]
+      this._pickShader.uniforms.clipBounds = projectData.clipBounds[i]
+      this._vao.draw(gl.TRIANGLES, this._vertexCount)
+    }
+
+    this._vao.unbind()
+  }
+
+  if(projectData.showContour) {
+    var shader = this._contourPickShader
+
+    shader.bind()
+    shader.uniforms = uniforms
+
+    var vao = this._contourVAO
+    vao.bind()
+
+    for(var j=0; j<3; ++j) {
+      gl.lineWidth(this.contourWidth[j])
+      shader.uniforms.permutation = PERMUTATIONS[j]
+      for(var i=0; i<this.contourLevels[j].length; ++i) {
+        shader.uniforms.height = this.contourLevels[j][i]
+        vao.draw(gl.LINES, this._contourCounts[j][i], this._contourOffsets[j][i])
+      }
+    }
+
+    //Draw projections of surface
+    for(var i=0; i<3; ++i) {
+      shader.uniforms.model      = projectData.projections[i]
+      shader.uniforms.clipBounds = projectData.clipBounds[i]
+
+      for(var j=0; j<3; ++j) {
+        if(!this.contourProject[i][j]) {
+          continue
+        }
+
+        shader.uniforms.permutation = PERMUTATIONS[j]
+        gl.lineWidth(this.contourWidth[j])
+        for(var k=0; k<this.contourLevels[j].length; ++k) {
+          shader.uniforms.height = this.contourLevels[j][k]
+          vao.draw(gl.LINES, this._contourCounts[j][k], this._contourOffsets[j][k])
+        }
+      }
+    }
+
+    vao.unbind()
+  }
+}
+
+
+proto.pick = function(selection) {
+  if(!selection) {
+    return null
+  }
+
+  if(selection.id !== this.pickId) {
+    return null
+  }
+
+  var shape = this._field[2].shape
+
+  var result = this._pickResult
+
+  //Compute uv coordinate
+  var x = shape[0] * (selection.value[0] + (selection.value[2]>>4)/16.0)/255.0
+  var ix = Math.floor(x)
+  var fx = x - ix
+
+  var y = shape[1] * (selection.value[1] + (selection.value[2]&15)/16.0)/255.0
+  var iy = Math.floor(y)
+  var fy = y - iy
+
+  ix += 1
+  iy += 1
+
+  //Compute xyz coordinate
+  var pos = result.position
+  pos[0] = pos[1] = pos[2] = 0
+  for(var dx=0; dx<2; ++dx) {
+    var s = dx ? fx : 1.0 - fx
+    for(var dy=0; dy<2; ++dy) {
+      var t = dy ? fy : 1.0 - fy
+
+      var r = ix + dx
+      var c = iy + dy
+      var w = s * t
+
+      for(var i=0; i<3; ++i) {
+        pos[i] += this._field[i].get(r,c) * w
+      }
+    }
+  }
+
+  //Find closest level
+  var levelIndex = this._pickResult.level
+  for(var j=0; j<3; ++j) {
+    levelIndex[j] = bsearch.le(this.contourLevels[j], pos[j])
+    if(levelIndex[j] < 0) {
+      if(this.contourLevels[j].length > 0) {
+        levelIndex[j] = 0
+      }
+    } else if(levelIndex[j] < this.contourLevels[j].length-1) {
+      var a = this.contourLevels[j][levelIndex[j]]
+      var b = this.contourLevels[j][levelIndex[j]+1]
+      if(Math.abs(a-pos[j]) > Math.abs(b-pos[j])) {
+        levelIndex[j] += 1
+      }
+    }
+  }
+
+  result.index[0] = fx<0.5 ? ix : (ix+1)
+  result.index[1] = fy<0.5 ? iy : (iy+1)
+
+  result.uv[0] = x/shape[0]
+  result.uv[1] = y/shape[1]
+
+  for(var i=0; i<3; ++i) {
+    result.dataCoordinate[i] = this._field[i].get(result.index[0], result.index[1])
+  }
+
+  return result
+}
+
+function padField(nfield, field) {
+
+  var shape = field.shape.slice()
+  var nshape = nfield.shape.slice()
+
+  //Center
+  ops.assign(nfield.lo(1,1).hi(shape[0], shape[1]), field)
+
+  //Edges
+  ops.assign(nfield.lo(1).hi(shape[0], 1),
+              field.hi(shape[0], 1))
+  ops.assign(nfield.lo(1,nshape[1]-1).hi(shape[0],1),
+              field.lo(0,shape[1]-1).hi(shape[0],1))
+  ops.assign(nfield.lo(0,1).hi(1,shape[1]),
+              field.hi(1))
+  ops.assign(nfield.lo(nshape[0]-1,1).hi(1,shape[1]),
+              field.lo(shape[0]-1))
+  //Corners
+  nfield.set(0,0, field.get(0,0))
+  nfield.set(0,nshape[1]-1, field.get(0,shape[1]-1))
+  nfield.set(nshape[0]-1,0, field.get(shape[0]-1,0))
+  nfield.set(nshape[0]-1,nshape[1]-1, field.get(shape[0]-1,shape[1]-1))
+}
+
+function handleArray(param, ctor) {
+  if(Array.isArray(param)) {
+    return [ ctor(param[0]), ctor(param[1]), ctor(param[2]) ]
+  }
+  return [ ctor(param), ctor(param), ctor(param) ]
+}
+
+function toColor(x) {
+  if(Array.isArray(x)) {
+    if(x.length === 3) {
+      return [x[0], x[1], x[2], 1]
+    }
+    return [x[0], x[1], x[2], x[3]]
+  }
+  return [0,0,0,1]
+}
+
+function handleColor(param) {
+  if(Array.isArray(param)) {
+    if(Array.isArray(param)) {
+      return [  toColor(param[0]),
+                toColor(param[1]),
+                toColor(param[2]) ]
+    } else {
+      var c = toColor(param)
+      return [
+        c.slice(),
+        c.slice(),
+        c.slice() ]
+    }
+  }
+}
+
+proto.update = function(params) {
+  params = params || {}
+
+  this.dirty = true
+
+  if('contourWidth' in params) {
+    this.contourWidth = handleArray(params.contourWidth, Number)
+  }
+  if('showContour' in params) {
+    this.showContour = handleArray(params.showContour, Boolean)
+  }
+  if('showSurface' in params) {
+    this.showSurface = !!params.showSurface
+  }
+  if('contourTint' in params) {
+    this.contourTint = handleArray(params.contourTint, Boolean)
+  }
+  if('contourColor' in params) {
+    this.contourColor = handleColor(params.contourColor)
+  }
+  if('contourProject' in params) {
+    this.contourProject = handleArray(params.contourProject, function(x) {
+      return handleArray(x, Boolean)
+    })
+  }
+  if('surfaceProject' in params) {
+    this.surfaceProject = params.surfaceProject
+  }
+  if('dynamicColor' in params) {
+    this.dynamicColor = handleColor(params.dynamicColor)
+  }
+  if('dynamicTint' in params) {
+    this.dynamicTint = handleArray(params.dynamicTint, Number)
+  }
+  if('dynamicWidth' in params) {
+    this.dynamicWidth = handleArray(params.dynamicWidth, Number)
+  }
+  if('opacity' in params) {
+    this.opacity = params.opacity
+  }
+  if('colorBounds' in params) {
+    this.colorBounds = params.colorBounds
+  }
+
+  var field = params.field || (params.coords && params.coords[2]) || null
+
+  if(!field) {
+    if(this._field[2].shape[0] || this._field[2].shape[2]) {
+      field = this._field[2].lo(1,1).hi(this._field[2].shape[0]-2, this._field[2].shape[1]-2)
+    } else {
+      field = this._field[2].hi(0,0)
+    }
+  }
+
+  //Update field
+  if('field' in params || 'coords' in params) {
+    var fsize = (field.shape[0]+2)*(field.shape[1]+2)
+
+    //Resize if necessary
+    if(fsize > this._field[2].data.length) {
+      pool.freeFloat(this._field[2].data)
+      this._field[2].data = pool.mallocFloat(bits.nextPow2(fsize))
+    }
+
+    //Pad field
+    this._field[2] = ndarray(this._field[2].data, [field.shape[0]+2, field.shape[1]+2])
+    padField(this._field[2], field)
+
+    //Save shape of field
+    this.shape = field.shape.slice()
+    var shape = this.shape
+
+    //Resize coordinate fields if necessary
+    for(var i=0; i<2; ++i) {
+      if(this._field[2].size > this._field[i].data.length) {
+        pool.freeFloat(this._field[i].data)
+        this._field[i].data = pool.mallocFloat(this._field[2].size)
+      }
+      this._field[i] = ndarray(this._field[i].data, [shape[0]+2, shape[1]+2])
+    }
+
+    //Generate x/y coordinates
+    if(params.coords) {
+      var coords = params.coords
+      if(!Array.isArray(coords) || coords.length !== 3) {
+        throw new Error('gl-surface: invalid coordinates for x/y')
+      }
+      for(var i=0; i<2; ++i) {
+        var coord = coords[i]
+        for(var j=0; j<2; ++j) {
+          if(coord.shape[j] !== shape[j]) {
+            throw new Error('gl-surface: coords have incorrect shape')
+          }
+        }
+        padField(this._field[i], coord)
+      }
+    } else if(params.ticks) {
+      var ticks = params.ticks
+      if(!Array.isArray(ticks) || ticks.length !== 2) {
+        throw new Error('gl-surface: invalid ticks')
+      }
+      for(var i=0; i<2; ++i) {
+        var tick = ticks[i]
+        if(Array.isArray(tick) || tick.length) {
+          tick = ndarray(tick)
+        }
+        if(tick.shape[0] !== shape[i]) {
+          throw new Error('gl-surface: invalid tick length')
+        }
+        //Make a copy view of the tick array
+        var tick2 = ndarray(tick.data, shape)
+        tick2.stride[i] = tick.stride[0]
+        tick2.stride[i^1] = 0
+
+        //Fill in field array
+        padField(this._field[i], tick2)
+      }
+    } else {
+      for(var i=0; i<2; ++i) {
+        var offset = [0,0]
+        offset[i] = 1
+        this._field[i] = ndarray(this._field[i].data, [shape[0]+2, shape[1]+2], offset, 0)
+      }
+      this._field[0].set(0,0,0)
+      for(var j=0; j<shape[0]; ++j) {
+        this._field[0].set(j+1,0,j)
+      }
+      this._field[0].set(shape[0]+1,0,shape[0]-1)
+      this._field[1].set(0,0,0)
+      for(var j=0; j<shape[1]; ++j) {
+        this._field[1].set(0,j+1,j)
+      }
+      this._field[1].set(0,shape[1]+1, shape[1]-1)
+    }
+
+    //Save shape
+    var fields = this._field
+
+    //Compute surface normals
+    var fieldSize = fields[2].size
+    var dfields = ndarray(pool.mallocFloat(fields[2].size*3*2), [3, shape[0]+2, shape[1]+2, 2])
+    for(var i=0; i<3; ++i) {
+      gradient(dfields.pick(i), fields[i], 'mirror')
+    }
+    var normals = ndarray(pool.mallocFloat(fields[2].size*3), [shape[0]+2, shape[1]+2, 3])
+    for(var i=0; i<shape[0]+2; ++i) {
+      for(var j=0; j<shape[1]+2; ++j) {
+        var dxdu = dfields.get(0, i, j, 0)
+        var dxdv = dfields.get(0, i, j, 1)
+        var dydu = dfields.get(1, i, j, 0)
+        var dydv = dfields.get(1, i, j, 1)
+        var dzdu = dfields.get(2, i, j, 0)
+        var dzdv = dfields.get(2, i, j, 1)
+
+        var nx = dydu * dzdv - dydv * dzdu
+        var ny = dzdu * dxdv - dzdv * dxdu
+        var nz = dxdu * dydv - dxdv * dydu
+
+        var nl = Math.sqrt(nx*nx + ny * ny + nz * nz)
+        if(nl < 1e-8) {
+          nl = Math.max(Math.abs(nx), Math.abs(ny), Math.abs(nz))
+          if(nl < 1e-8) {
+            nz = 1.0
+            ny = nx = 0.0
+            nl = 1.0
+          } else {
+            nl = 1.0/ nl
+          }
+        } else {
+          nl = 1.0 / Math.sqrt(nl)
+        }
+
+        normals.set(i,j,0, nx*nl)
+        normals.set(i,j,1, ny*nl)
+        normals.set(i,j,2, nz*nl)
+      }
+    }
+    pool.free(dfields.data)
+
+    //Initialize surface
+    var lo = [ Infinity, Infinity, Infinity]
+    var hi = [-Infinity,-Infinity,-Infinity]
+    var count   = (shape[0]-1) * (shape[1]-1) * 6
+    var tverts  = pool.mallocFloat(bits.nextPow2(9*count))
+    var tptr    = 0
+    var fptr    = 0
+    var vertexCount = 0
+    for(var i=0; i<shape[0]-1; ++i) {
+  j_loop:
+      for(var j=0; j<shape[1]-1; ++j) {
+
+        //Test for NaNs
+        for(var dx=0; dx<2; ++dx) {
+          for(var dy=0; dy<2; ++dy) {
+            for(var k=0; k<3; ++k) {
+              var f = this._field[k].get(1+i+dx, 1+j+dy)
+              if(isNaN(f) || !isFinite(f)) {
+                continue j_loop
+              }
+            }
+          }
+        }
+        for(var k=0; k<6; ++k) {
+          var r = i + QUAD[k][0]
+          var c = j + QUAD[k][1]
+
+          var tx = this._field[0].get(r+1, c+1)
+          var ty = this._field[1].get(r+1, c+1)
+          var f  = this._field[2].get(r+1, c+1)
+          var nx = normals.get(r+1, c+1, 0)
+          var ny = normals.get(r+1, c+1, 1)
+          var nz = normals.get(r+1, c+1, 2)
+
+          tverts[tptr++] = r
+          tverts[tptr++] = c
+          tverts[tptr++] = tx
+          tverts[tptr++] = ty
+          tverts[tptr++] = f
+          tverts[tptr++] = 0
+          tverts[tptr++] = nx
+          tverts[tptr++] = ny
+          tverts[tptr++] = nz
+
+          lo[0] = Math.min(lo[0], tx)
+          lo[1] = Math.min(lo[1], ty)
+          lo[2] = Math.min(lo[2], f)
+
+          hi[0] = Math.max(hi[0], tx)
+          hi[1] = Math.max(hi[1], ty)
+          hi[2] = Math.max(hi[2], f)
+
+          vertexCount += 1
+        }
+      }
+    }
+    this._vertexCount = vertexCount
+    this._coordinateBuffer.update(tverts.subarray(0,tptr))
+    pool.freeFloat(tverts)
+    pool.free(normals.data)
+
+    //Update bounds
+    this.bounds = [lo, hi]
+  }
+
+  //Update level crossings
+  var levelsChanged = false
+  if('levels' in params) {
+    var levels = params.levels
+    if(!Array.isArray(levels[0])) {
+      levels = [ [], [], levels ]
+    } else {
+      levels = levels.slice()
+    }
+    for(var i=0; i<3; ++i) {
+      levels[i] = levels[i].slice()
+      levels.sort(function(a,b) {
+        return a-b
+      })
+    }
+change_test:
+    for(var i=0; i<3; ++i) {
+      if(levels[i].length !== this.contourLevels[i].length) {
+        levelsChanged = true
+        break
+      }
+      for(var j=0; j<levels[i].length; ++j) {
+        if(levels[i][j] !== this.contourLevels[i][j]) {
+          levelsChanged = true
+          break change_test
+        }
+      }
+    }
+    this.contourLevels = levels
+  }
+
+  if(levelsChanged) {
+    var fields = this._field
+    var shape  = this.shape
+
+    //Update contour lines
+    var contourVerts = []
+
+    for(var dim=0; dim<3; ++dim) {
+      var levels = this.contourLevels[dim]
+      var levelOffsets = []
+      var levelCounts  = []
+
+      var parts = [0,0]
+      var graphParts = [0,0]
+
+      for(var i=0; i<levels.length; ++i) {
+        var graph = surfaceNets(this._field[dim], levels[i])
+        levelOffsets.push((contourVerts.length/4)|0)
+        var vertexCount = 0
+
+  edge_loop:
+        for(var j=0; j<graph.cells.length; ++j) {
+          var e = graph.cells[j]
+          for(var k=0; k<2; ++k) {
+            var p = graph.positions[e[k]]
+
+            var x = p[0]
+            var ix = Math.floor(x)|0
+            var fx = x - ix
+
+            var y = p[1]
+            var iy = Math.floor(y)|0
+            var fy = y - iy
+
+            var hole = false
+  dd_loop:
+            for(var dd=0; dd<2; ++dd) {
+              parts[dd] = 0.0
+              var iu = (dim + dd + 1) % 3
+              for(var dx=0; dx<2; ++dx) {
+                var s = dx ? fx : 1.0 - fx
+                var r = Math.min(Math.max(ix+dx, 0), shape[0])|0
+                for(var dy=0; dy<2; ++dy) {
+                  var t = dy ? fy : 1.0 - fy
+                  var c = Math.min(Math.max(iy+dy, 0), shape[1])|0
+
+                  var f = this._field[iu].get(r,c)
+                  if(!isFinite(f) || isNaN(f)) {
+                    hole = true
+                    break dd_loop
+                  }
+
+                  var w = s * t
+                  parts[dd] += w * f
+                }
+              }
+            }
+
+            if(!hole) {
+              contourVerts.push(parts[0], parts[1], p[0], p[1])
+              vertexCount += 1
+            } else {
+              if(k > 0) {
+                //If we already added first edge, pop off verts
+                for(var l=0; l<4; ++l) {
+                  contourVerts.pop()
+                }
+                vertexCount -= 1
+              }
+              continue edge_loop
+            }
+          }
+        }
+        levelCounts.push(vertexCount)
+      }
+
+      //Store results
+      this._contourOffsets[dim]  = levelOffsets
+      this._contourCounts[dim]   = levelCounts
+    }
+
+    var floatBuffer = pool.mallocFloat(contourVerts.length)
+    for(var i=0; i<contourVerts.length; ++i) {
+      floatBuffer[i] = contourVerts[i]
+    }
+    this._contourBuffer.update(floatBuffer)
+    pool.freeFloat(floatBuffer)
+  }
+
+  if(params.colormap) {
+    this._colorMap.setPixels(genColormap(params.colormap))
+  }
+}
+
+proto.dispose = function() {
+  this._shader.dispose()
+  this._vao.dispose()
+  this._coordinateBuffer.dispose()
+  this._colorMap.dispose()
+  this._contourBuffer.dispose()
+  this._contourVAO.dispose()
+  this._contourShader.dispose()
+  this._contourPickShader.dispose()
+  this._dynamicBuffer.dispose()
+  this._dynamicVAO.dispose()
+  for(var i=0; i<3; ++i) {
+    pool.freeFloat(this._field[i].data)
+  }
+}
+
+proto.highlight = function(selection) {
+  if(!selection) {
+    this._dynamicCounts = [0,0,0]
+    this.dyanamicLevel = [NaN, NaN, NaN]
+    this.highlightLevel = [-1,-1,-1]
+    return
+  }
+
+  for(var i=0; i<3; ++i) {
+    if(this.enableHighlight[i]) {
+      this.highlightLevel[i] = selection.level[i]
+    } else {
+      this.highlightLevel[i] = -1
+    }
+  }
+
+  var levels
+  if(this.snapToData) {
+    levels = selection.dataCoordinate
+  } else {
+    levels = selection.position
+  }
+  if( (!this.enableDynamic[0] || levels[0] === this.dynamicLevel[0]) &&
+      (!this.enableDynamic[1] || levels[1] === this.dynamicLevel[1]) &&
+      (!this.enableDynamic[2] || levels[2] === this.dynamicLevel[2]) ) {
+    return
+  }
+
+  var vertexCount = 0
+  var shape = this.shape
+  var scratchBuffer = pool.mallocFloat(12 * shape[0] * shape[1])
+
+  for(var d=0; d<3; ++d) {
+    if(!this.enableDynamic[d]) {
+      this.dynamicLevel[d] = NaN
+      this._dynamicCounts[d] = 0
+      continue
+    }
+
+    this.dynamicLevel[d] = levels[d]
+
+    var u = (d+1) % 3
+    var v = (d+2) % 3
+
+    var f = this._field[d]
+    var g = this._field[u]
+    var h = this._field[v]
+
+    var graph     = surfaceNets(f, levels[d])
+    var edges     = graph.cells
+    var positions = graph.positions
+
+    this._dynamicOffsets[d] = vertexCount
+
+    for(var i=0; i<edges.length; ++i) {
+      var e = edges[i]
+      for(var j=0; j<2; ++j) {
+        var p  = positions[e[j]]
+
+        var x  = +p[0]
+        var ix = x|0
+        var jx = Math.min(ix+1, shape[0])|0
+        var fx = x - ix
+        var hx = 1.0 - fx
+
+        var y  = +p[1]
+        var iy = y|0
+        var jy = Math.min(iy+1, shape[1])|0
+        var fy = y - iy
+        var hy = 1.0 - fy
+
+        var w00 = hx * hy
+        var w01 = hx * fy
+        var w10 = fx * hy
+        var w11 = fx * fy
+
+        var cu =  w00 * g.get(ix,iy) +
+                  w01 * g.get(ix,jy) +
+                  w10 * g.get(jx,iy) +
+                  w11 * g.get(jx,jy)
+
+        var cv =  w00 * h.get(ix,iy) +
+                  w01 * h.get(ix,jy) +
+                  w10 * h.get(jx,iy) +
+                  w11 * h.get(jx,jy)
+
+        if(isNaN(cu) || isNaN(cv)) {
+          if(j) {
+            vertexCount -= 1
+          }
+          break
+        }
+
+        scratchBuffer[2*vertexCount+0] = cu
+        scratchBuffer[2*vertexCount+1] = cv
+
+        vertexCount += 1
+      }
+    }
+
+    this._dynamicCounts[d] = vertexCount - this._dynamicOffsets[d]
+  }
+
+  this._dynamicBuffer.update(scratchBuffer.subarray(0, 2*vertexCount))
+  pool.freeFloat(scratchBuffer)
+}
+
+function createSurfacePlot(params) {
+  var gl = params.gl
+  var field = params.field || (params.coords && params.coords[2]) || ndarray([], [0,0])
+
+  var shader = createShader(gl)
+  var pickShader = createPickShader(gl)
+  var contourShader = createContourShader(gl)
+  var contourPickShader = createPickContourShader(gl)
+
+  var coordinateBuffer = createBuffer(gl)
+  var vao = createVAO(gl, [
+      { buffer: coordinateBuffer,
+        size: 4,
+        stride: SURFACE_VERTEX_SIZE,
+        offset: 0
+      },
+      { buffer: coordinateBuffer,
+        size: 2,
+        stride: SURFACE_VERTEX_SIZE,
+        offset: 16
+      },
+      {
+        buffer: coordinateBuffer,
+        size: 3,
+        stride: SURFACE_VERTEX_SIZE,
+        offset: 24
+      }
+    ])
+
+  var contourBuffer = createBuffer(gl)
+  var contourVAO = createVAO(gl, [
+    {
+      buffer: contourBuffer,
+      size: 4
+    }])
+
+  var dynamicBuffer = createBuffer(gl)
+  var dynamicVAO = createVAO(gl, [
+    {
+      buffer: dynamicBuffer,
+      size: 2,
+      type: gl.FLOAT
+    }])
+
+  var cmap = createTexture(gl, 1, N_COLORS, gl.RGBA, gl.UNSIGNED_BYTE)
+  cmap.minFilter = gl.LINEAR
+  cmap.magFilter = gl.LINEAR
+
+  var surface = new SurfacePlot(
+    gl,
+    [0,0],
+    [[0,0,0], [0,0,0]],
+    shader,
+    pickShader,
+    coordinateBuffer,
+    vao,
+    cmap,
+    contourShader,
+    contourPickShader,
+    contourBuffer,
+    contourVAO,
+    dynamicBuffer,
+    dynamicVAO)
+
+  var nparams = {
+    levels: [[], [], []]
+  }
+  for(var id in params) {
+    nparams[id] = params[id]
+  }
+  nparams.colormap = nparams.colormap || 'jet'
+
+  surface.update(nparams)
+
+  return surface
+}
+
+},{"./lib/shaders":179,"binary-search-bounds":180,"bit-twiddle":49,"colormap":57,"gl-buffer":75,"gl-mat4/invert":94,"gl-mat4/multiply":96,"gl-texture2d":185,"gl-vao":189,"ndarray":208,"ndarray-gradient":181,"ndarray-ops":207,"ndarray-pack":182,"surface-nets":227,"typedarray-pool":233}],185:[function(require,module,exports){
+'use strict'
+
+var ndarray = require('ndarray')
+var ops     = require('ndarray-ops')
+var pool    = require('typedarray-pool')
+
+module.exports = createTexture2D
+
+var linearTypes = null
+var filterTypes = null
+var wrapTypes   = null
+
+function lazyInitLinearTypes(gl) {
+  linearTypes = [
+    gl.LINEAR,
+    gl.NEAREST_MIPMAP_LINEAR,
+    gl.LINEAR_MIPMAP_NEAREST,
+    gl.LINEAR_MIPMAP_NEAREST
+  ]
+  filterTypes = [
+    gl.NEAREST,
+    gl.LINEAR,
+    gl.NEAREST_MIPMAP_NEAREST,
+    gl.NEAREST_MIPMAP_LINEAR,
+    gl.LINEAR_MIPMAP_NEAREST,
+    gl.LINEAR_MIPMAP_LINEAR
+  ]
+  wrapTypes = [
+    gl.REPEAT,
+    gl.CLAMP_TO_EDGE,
+    gl.MIRRORED_REPEAT
+  ]
+}
+
+var convertFloatToUint8 = function(out, inp) {
+  ops.muls(out, inp, 255.0)
+}
+
+function reshapeTexture(tex, w, h) {
+  var gl = tex.gl
+  var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)
+  if(w < 0 || w > maxSize || h < 0 || h > maxSize) {
+    throw new Error('gl-texture2d: Invalid texture size')
+  }
+  tex._shape = [w, h]
+  tex.bind()
+  gl.texImage2D(gl.TEXTURE_2D, 0, tex.format, w, h, 0, tex.format, tex.type, null)
+  tex._mipLevels = [0]
+  return tex
+}
+
+function Texture2D(gl, handle, width, height, format, type) {
+  this.gl = gl
+  this.handle = handle
+  this.format = format
+  this.type = type
+  this._shape = [width, height]
+  this._mipLevels = [0]
+  this._magFilter = gl.NEAREST
+  this._minFilter = gl.NEAREST
+  this._wrapS = gl.CLAMP_TO_EDGE
+  this._wrapT = gl.CLAMP_TO_EDGE
+  this._anisoSamples = 1
+
+  var parent = this
+  var wrapVector = [this._wrapS, this._wrapT]
+  Object.defineProperties(wrapVector, [
+    {
+      get: function() {
+        return parent._wrapS
+      },
+      set: function(v) {
+        return parent.wrapS = v
+      }
+    },
+    {
+      get: function() {
+        return parent._wrapT
+      },
+      set: function(v) {
+        return parent.wrapT = v
+      }
+    }
+  ])
+  this._wrapVector = wrapVector
+
+  var shapeVector = [this._shape[0], this._shape[1]]
+  Object.defineProperties(shapeVector, [
+    {
+      get: function() {
+        return parent._shape[0]
+      },
+      set: function(v) {
+        return parent.width = v
+      }
+    },
+    {
+      get: function() {
+        return parent._shape[1]
+      },
+      set: function(v) {
+        return parent.height = v
+      }
+    }
+  ])
+  this._shapeVector = shapeVector
+}
+
+var proto = Texture2D.prototype
+
+Object.defineProperties(proto, {
+  minFilter: {
+    get: function() {
+      return this._minFilter
+    },
+    set: function(v) {
+      this.bind()
+      var gl = this.gl
+      if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) {
+        if(!gl.getExtension('OES_texture_float_linear')) {
+          v = gl.NEAREST
+        }
+      }
+      if(filterTypes.indexOf(v) < 0) {
+        throw new Error('gl-texture2d: Unknown filter mode ' + v)
+      }
+      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, v)
+      return this._minFilter = v
+    }
+  },
+  magFilter: {
+    get: function() {
+      return this._magFilter
+    },
+    set: function(v) {
+      this.bind()
+      var gl = this.gl
+      if(this.type === gl.FLOAT && linearTypes.indexOf(v) >= 0) {
+        if(!gl.getExtension('OES_texture_float_linear')) {
+          v = gl.NEAREST
+        }
+      }
+      if(filterTypes.indexOf(v) < 0) {
+        throw new Error('gl-texture2d: Unknown filter mode ' + v)
+      }
+      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, v)
+      return this._magFilter = v
+    }
+  },
+  mipSamples: {
+    get: function() {
+      return this._anisoSamples
+    },
+    set: function(i) {
+      var psamples = this._anisoSamples
+      this._anisoSamples = Math.max(i, 1)|0
+      if(psamples !== this._anisoSamples) {
+        var ext = gl.getExtension('EXT_texture_filter_anisotropic')
+        if(ext) {
+          this.gl.texParameterf(this.gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, this._anisoSamples)
+        }
+      }
+      return this._anisoSamples
+    }
+  },
+  wrapS: {
+    get: function() {
+      return this._wrapS
+    },
+    set: function(v) {
+      this.bind()
+      if(wrapTypes.indexOf(v) < 0) {
+        throw new Error('gl-texture2d: Unknown wrap mode ' + v)
+      }
+      this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, v)
+      return this._wrapS = v
+    }
+  },
+  wrapT: {
+    get: function() {
+      return this._wrapT
+    },
+    set: function(v) {
+      this.bind()
+      if(wrapTypes.indexOf(v) < 0) {
+        throw new Error('gl-texture2d: Unknown wrap mode ' + v)
+      }
+      this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, v)
+      return this._wrapT = v
+    }
+  },
+  wrap: {
+    get: function() {
+      return this._wrapVector
+    },
+    set: function(v) {
+      if(!Array.isArray(v)) {
+        v = [v,v]
+      }
+      if(v.length !== 2) {
+        throw new Error('gl-texture2d: Must specify wrap mode for rows and columns')
+      }
+      for(var i=0; i<2; ++i) {
+        if(wrapTypes.indexOf(v[i]) < 0) {
+          throw new Error('gl-texture2d: Unknown wrap mode ' + v)
+        }
+      }
+      this._wrapS = v[0]
+      this._wrapT = v[1]
+
+      var gl = this.gl
+      this.bind()
+      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS)
+      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT)
+
+      return v
+    }
+  },
+  shape: {
+    get: function() {
+      return this._shapeVector
+    },
+    set: function(x) {
+      if(!Array.isArray(x)) {
+        x = [x|0,x|0]
+      } else {
+        if(x.length !== 2) {
+          throw new Error('gl-texture2d: Invalid texture shape')
+        }
+      }
+      reshapeTexture(this, x[0]|0, x[1]|0)
+      return [x[0]|0, x[1]|0]
+    }
+  },
+  width: {
+    get: function() {
+      return this._shape[0]
+    },
+    set: function(w) {
+      w = w|0
+      reshapeTexture(this, w, this._shape[1])
+      return w
+    }
+  },
+  height: {
+    get: function() {
+      return this._shape[1]
+    },
+    set: function(h) {
+      h = h|0
+      reshapeTexture(this, this._shape[0], h)
+      return h
+    }
+  }
+})
+
+proto.bind = function(unit) {
+  var gl = this.gl
+  if(unit !== undefined) {
+    gl.activeTexture(gl.TEXTURE0 + (unit|0))
+  }
+  gl.bindTexture(gl.TEXTURE_2D, this.handle)
+  if(unit !== undefined) {
+    return (unit|0)
+  }
+  return gl.getParameter(gl.ACTIVE_TEXTURE) - gl.TEXTURE0
+}
+
+proto.dispose = function() {
+  this.gl.deleteTexture(this.handle)
+}
+
+proto.generateMipmap = function() {
+  this.bind()
+  this.gl.generateMipmap(this.gl.TEXTURE_2D)
+
+  //Update mip levels
+  var l = Math.min(this._shape[0], this._shape[1])
+  for(var i=0; l>0; ++i, l>>>=1) {
+    if(this._mipLevels.indexOf(i) < 0) {
+      this._mipLevels.push(i)
+    }
+  }
+}
+
+proto.setPixels = function(data, x_off, y_off, mip_level) {
+  var gl = this.gl
+  this.bind()
+  if(Array.isArray(x_off)) {
+    mip_level = y_off
+    y_off = x_off[1]|0
+    x_off = x_off[0]|0
+  } else {
+    x_off = x_off || 0
+    y_off = y_off || 0
+  }
+  mip_level = mip_level || 0
+  if(data instanceof HTMLCanvasElement ||
+     data instanceof ImageData ||
+     data instanceof HTMLImageElement ||
+     data instanceof HTMLVideoElement) {
+    var needsMip = this._mipLevels.indexOf(mip_level) < 0
+    if(needsMip) {
+      gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, this.type, data)
+      this._mipLevels.push(mip_level)
+    } else {
+      gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, this.format, this.type, data)
+    }
+  } else if(data.shape && data.stride && data.data) {
+    if(data.shape.length < 2 ||
+       x_off + data.shape[1] > this._shape[1]>>>mip_level ||
+       y_off + data.shape[0] > this._shape[0]>>>mip_level ||
+       x_off < 0 ||
+       y_off < 0) {
+      throw new Error('gl-texture2d: Texture dimensions are out of bounds')
+    }
+    texSubImageArray(gl, x_off, y_off, mip_level, this.format, this.type, this._mipLevels, data)
+  } else {
+    throw new Error('gl-texture2d: Unsupported data type')
+  }
+}
+
+
+function isPacked(shape, stride) {
+  if(shape.length === 3) {
+    return  (stride[2] === 1) &&
+            (stride[1] === shape[0]*shape[2]) &&
+            (stride[0] === shape[2])
+  }
+  return  (stride[0] === 1) &&
+          (stride[1] === shape[0])
+}
+
+function texSubImageArray(gl, x_off, y_off, mip_level, cformat, ctype, mipLevels, array) {
+  var dtype = array.dtype
+  var shape = array.shape.slice()
+  if(shape.length < 2 || shape.length > 3) {
+    throw new Error('gl-texture2d: Invalid ndarray, must be 2d or 3d')
+  }
+  var type = 0, format = 0
+  var packed = isPacked(shape, array.stride.slice())
+  if(dtype === 'float32') {
+    type = gl.FLOAT
+  } else if(dtype === 'float64') {
+    type = gl.FLOAT
+    packed = false
+    dtype = 'float32'
+  } else if(dtype === 'uint8') {
+    type = gl.UNSIGNED_BYTE
+  } else {
+    type = gl.UNSIGNED_BYTE
+    packed = false
+    dtype = 'uint8'
+  }
+  var channels = 1
+  if(shape.length === 2) {
+    format = gl.LUMINANCE
+    shape = [shape[0], shape[1], 1]
+    array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset)
+  } else if(shape.length === 3) {
+    if(shape[2] === 1) {
+      format = gl.ALPHA
+    } else if(shape[2] === 2) {
+      format = gl.LUMINANCE_ALPHA
+    } else if(shape[2] === 3) {
+      format = gl.RGB
+    } else if(shape[2] === 4) {
+      format = gl.RGBA
+    } else {
+      throw new Error('gl-texture2d: Invalid shape for pixel coords')
+    }
+    channels = shape[2]
+  } else {
+    throw new Error('gl-texture2d: Invalid shape for texture')
+  }
+  //For 1-channel textures allow conversion between formats
+  if((format  === gl.LUMINANCE || format  === gl.ALPHA) &&
+     (cformat === gl.LUMINANCE || cformat === gl.ALPHA)) {
+    format = cformat
+  }
+  if(format !== cformat) {
+    throw new Error('gl-texture2d: Incompatible texture format for setPixels')
+  }
+  var size = array.size
+  var needsMip = mipLevels.indexOf(mip_level) < 0
+  if(needsMip) {
+    mipLevels.push(mip_level)
+  }
+  if(type === ctype && packed) {
+    //Array data types are compatible, can directly copy into texture
+    if(array.offset === 0 && array.data.length === size) {
+      if(needsMip) {
+        gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data)
+      } else {
+        gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data)
+      }
+    } else {
+      if(needsMip) {
+        gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, array.data.subarray(array.offset, array.offset+size))
+      } else {
+        gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, array.data.subarray(array.offset, array.offset+size))
+      }
+    }
+  } else {
+    //Need to do type conversion to pack data into buffer
+    var pack_buffer
+    if(ctype === gl.FLOAT) {
+      pack_buffer = pool.mallocFloat32(size)
+    } else {
+      pack_buffer = pool.mallocUint8(size)
+    }
+    var pack_view = ndarray(pack_buffer, shape, [shape[2], shape[2]*shape[0], 1])
+    if(type === gl.FLOAT && ctype === gl.UNSIGNED_BYTE) {
+      convertFloatToUint8(pack_view, array)
+    } else {
+      ops.assign(pack_view, array)
+    }
+    if(needsMip) {
+      gl.texImage2D(gl.TEXTURE_2D, mip_level, cformat, shape[0], shape[1], 0, cformat, ctype, pack_buffer.subarray(0, size))
+    } else {
+      gl.texSubImage2D(gl.TEXTURE_2D, mip_level, x_off, y_off, shape[0], shape[1], cformat, ctype, pack_buffer.subarray(0, size))
+    }
+    if(ctype === gl.FLOAT) {
+      pool.freeFloat32(pack_buffer)
+    } else {
+      pool.freeUint8(pack_buffer)
+    }
+  }
+}
+
+function initTexture(gl) {
+  var tex = gl.createTexture()
+  gl.bindTexture(gl.TEXTURE_2D, tex)
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
+  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
+  return tex
+}
+
+function createTextureShape(gl, width, height, format, type) {
+  var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)
+  if(width < 0 || width > maxTextureSize || height < 0 || height  > maxTextureSize) {
+    throw new Error('gl-texture2d: Invalid texture shape')
+  }
+  if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) {
+    throw new Error('gl-texture2d: Floating point textures not supported on this platform')
+  }
+  var tex = initTexture(gl)
+  gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, 0, format, type, null)
+  return new Texture2D(gl, tex, width, height, format, type)
+}
+
+function createTextureDOM(gl, element, format, type) {
+  var tex = initTexture(gl)
+  gl.texImage2D(gl.TEXTURE_2D, 0, format, format, type, element)
+  return new Texture2D(gl, tex, element.width|0, element.height|0, format, type)
+}
+
+//Creates a texture from an ndarray
+function createTextureArray(gl, array) {
+  var dtype = array.dtype
+  var shape = array.shape.slice()
+  var maxSize = gl.getParameter(gl.MAX_TEXTURE_SIZE)
+  if(shape[0] < 0 || shape[0] > maxSize || shape[1] < 0 || shape[1] > maxSize) {
+    throw new Error('gl-texture2d: Invalid texture size')
+  }
+  var packed = isPacked(shape, array.stride.slice())
+  var type = 0
+  if(dtype === 'float32') {
+    type = gl.FLOAT
+  } else if(dtype === 'float64') {
+    type = gl.FLOAT
+    packed = false
+    dtype = 'float32'
+  } else if(dtype === 'uint8') {
+    type = gl.UNSIGNED_BYTE
+  } else {
+    type = gl.UNSIGNED_BYTE
+    packed = false
+    dtype = 'uint8'
+  }
+  var format = 0
+  if(shape.length === 2) {
+    format = gl.LUMINANCE
+    shape = [shape[0], shape[1], 1]
+    array = ndarray(array.data, shape, [array.stride[0], array.stride[1], 1], array.offset)
+  } else if(shape.length === 3) {
+    if(shape[2] === 1) {
+      format = gl.ALPHA
+    } else if(shape[2] === 2) {
+      format = gl.LUMINANCE_ALPHA
+    } else if(shape[2] === 3) {
+      format = gl.RGB
+    } else if(shape[2] === 4) {
+      format = gl.RGBA
+    } else {
+      throw new Error('gl-texture2d: Invalid shape for pixel coords')
+    }
+  } else {
+    throw new Error('gl-texture2d: Invalid shape for texture')
+  }
+  if(type === gl.FLOAT && !gl.getExtension('OES_texture_float')) {
+    type = gl.UNSIGNED_BYTE
+    packed = false
+  }
+  var buffer, buf_store
+  var size = array.size
+  if(!packed) {
+    var stride = [shape[2], shape[2]*shape[0], 1]
+    buf_store = pool.malloc(size, dtype)
+    var buf_array = ndarray(buf_store, shape, stride, 0)
+    if((dtype === 'float32' || dtype === 'float64') && type === gl.UNSIGNED_BYTE) {
+      convertFloatToUint8(buf_array, array)
+    } else {
+      ops.assign(buf_array, array)
+    }
+    buffer = buf_store.subarray(0, size)
+  } else if (array.offset === 0 && array.data.length === size) {
+    buffer = array.data
+  } else {
+    buffer = array.data.subarray(array.offset, array.offset + size)
+  }
+  var tex = initTexture(gl)
+  gl.texImage2D(gl.TEXTURE_2D, 0, format, shape[0], shape[1], 0, format, type, buffer)
+  if(!packed) {
+    pool.free(buf_store)
+  }
+  return new Texture2D(gl, tex, shape[0], shape[1], format, type)
+}
+
+function createTexture2D(gl) {
+  if(arguments.length <= 1) {
+    throw new Error('gl-texture2d: Missing arguments for texture2d constructor')
+  }
+  if(!linearTypes) {
+    lazyInitLinearTypes(gl)
+  }
+  if(typeof arguments[1] === 'number') {
+    return createTextureShape(gl, arguments[1], arguments[2], arguments[3]||gl.RGBA, arguments[4]||gl.UNSIGNED_BYTE)
+  }
+  if(Array.isArray(arguments[1])) {
+    return createTextureShape(gl, arguments[1][0]|0, arguments[1][1]|0, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE)
+  }
+  if(typeof arguments[1] === 'object') {
+    var obj = arguments[1]
+    if(obj instanceof HTMLCanvasElement ||
+       obj instanceof HTMLImageElement ||
+       obj instanceof HTMLVideoElement ||
+       obj instanceof ImageData) {
+      return createTextureDOM(gl, obj, arguments[2]||gl.RGBA, arguments[3]||gl.UNSIGNED_BYTE)
+    } else if(obj.shape && obj.data && obj.stride) {
+      return createTextureArray(gl, obj)
+    }
+  }
+  throw new Error('gl-texture2d: Invalid arguments for texture2d constructor')
+}
+
+},{"ndarray":208,"ndarray-ops":207,"typedarray-pool":233}],186:[function(require,module,exports){
+"use strict"
+
+function doBind(gl, elements, attributes) {
+  if(elements) {
+    elements.bind()
+  } else {
+    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null)
+  }
+  var nattribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS)|0
+  if(attributes) {
+    if(attributes.length > nattribs) {
+      throw new Error("gl-vao: Too many vertex attributes")
+    }
+    for(var i=0; i<attributes.length; ++i) {
+      var attrib = attributes[i]
+      if(attrib.buffer) {
+        var buffer = attrib.buffer
+        var size = attrib.size || 4
+        var type = attrib.type || gl.FLOAT
+        var normalized = !!attrib.normalized
+        var stride = attrib.stride || 0
+        var offset = attrib.offset || 0
+        buffer.bind()
+        gl.enableVertexAttribArray(i)
+        gl.vertexAttribPointer(i, size, type, normalized, stride, offset)
+      } else {
+        if(typeof attrib === "number") {
+          gl.vertexAttrib1f(i, attrib)
+        } else if(attrib.length === 1) {
+          gl.vertexAttrib1f(i, attrib[0])
+        } else if(attrib.length === 2) {
+          gl.vertexAttrib2f(i, attrib[0], attrib[1])
+        } else if(attrib.length === 3) {
+          gl.vertexAttrib3f(i, attrib[0], attrib[1], attrib[2])
+        } else if(attrib.length === 4) {
+          gl.vertexAttrib4f(i, attrib[0], attrib[1], attrib[2], attrib[3])
+        } else {
+          throw new Error("gl-vao: Invalid vertex attribute")
+        }
+        gl.disableVertexAttribArray(i)
+      }
+    }
+    for(; i<nattribs; ++i) {
+      gl.disableVertexAttribArray(i)
+    }
+  } else {
+    gl.bindBuffer(gl.ARRAY_BUFFER, null)
+    for(var i=0; i<nattribs; ++i) {
+      gl.disableVertexAttribArray(i)
+    }
+  }
+}
+
+module.exports = doBind
+},{}],187:[function(require,module,exports){
+"use strict"
+
+var bindAttribs = require("./do-bind.js")
+
+function VAOEmulated(gl) {
+  this.gl = gl
+  this._elements = null
+  this._attributes = null
+  this._elementsType = gl.UNSIGNED_SHORT
+}
+
+VAOEmulated.prototype.bind = function() {
+  bindAttribs(this.gl, this._elements, this._attributes)
+}
+
+VAOEmulated.prototype.update = function(attributes, elements, elementsType) {
+  this._elements = elements
+  this._attributes = attributes
+  this._elementsType = elementsType || this.gl.UNSIGNED_SHORT
+}
+
+VAOEmulated.prototype.dispose = function() { }
+VAOEmulated.prototype.unbind = function() { }
+
+VAOEmulated.prototype.draw = function(mode, count, offset) {
+  offset = offset || 0
+  var gl = this.gl
+  if(this._elements) {
+    gl.drawElements(mode, count, this._elementsType, offset)
+  } else {
+    gl.drawArrays(mode, offset, count)
+  }
+}
+
+function createVAOEmulated(gl) {
+  return new VAOEmulated(gl)
+}
+
+module.exports = createVAOEmulated
+},{"./do-bind.js":186}],188:[function(require,module,exports){
+"use strict"
+
+var bindAttribs = require("./do-bind.js")
+
+function VertexAttribute(location, dimension, a, b, c, d) {
+  this.location = location
+  this.dimension = dimension
+  this.a = a
+  this.b = b
+  this.c = c
+  this.d = d
+}
+
+VertexAttribute.prototype.bind = function(gl) {
+  switch(this.dimension) {
+    case 1:
+      gl.vertexAttrib1f(this.location, this.a)
+    break
+    case 2:
+      gl.vertexAttrib2f(this.location, this.a, this.b)
+    break
+    case 3:
+      gl.vertexAttrib3f(this.location, this.a, this.b, this.c)
+    break
+    case 4:
+      gl.vertexAttrib4f(this.location, this.a, this.b, this.c, this.d)
+    break
+  }
+}
+
+function VAONative(gl, ext, handle) {
+  this.gl = gl
+  this._ext = ext
+  this.handle = handle
+  this._attribs = []
+  this._useElements = false
+  this._elementsType = gl.UNSIGNED_SHORT
+}
+
+VAONative.prototype.bind = function() {
+  this._ext.bindVertexArrayOES(this.handle)
+  for(var i=0; i<this._attribs.length; ++i) {
+    this._attribs[i].bind(this.gl)
+  }
+}
+
+VAONative.prototype.unbind = function() {
+  this._ext.bindVertexArrayOES(null)
+}
+
+VAONative.prototype.dispose = function() {
+  this._ext.deleteVertexArrayOES(this.handle)
+}
+
+VAONative.prototype.update = function(attributes, elements, elementsType) {
+  this.bind()
+  bindAttribs(this.gl, elements, attributes)
+  this.unbind()
+  this._attribs.length = 0
+  if(attributes)
+  for(var i=0; i<attributes.length; ++i) {
+    var a = attributes[i]
+    if(typeof a === "number") {
+      this._attribs.push(new VertexAttribute(i, 1, a))
+    } else if(Array.isArray(a)) {
+      this._attribs.push(new VertexAttribute(i, a.length, a[0], a[1], a[2], a[3]))
+    }
+  }
+  this._useElements = !!elements
+  this._elementsType = elementsType || this.gl.UNSIGNED_SHORT
+}
+
+VAONative.prototype.draw = function(mode, count, offset) {
+  offset = offset || 0
+  var gl = this.gl
+  if(this._useElements) {
+    gl.drawElements(mode, count, this._elementsType, offset)
+  } else {
+    gl.drawArrays(mode, offset, count)
+  }
+}
+
+function createVAONative(gl, ext) {
+  return new VAONative(gl, ext, ext.createVertexArrayOES())
+}
+
+module.exports = createVAONative
+},{"./do-bind.js":186}],189:[function(require,module,exports){
+"use strict"
+
+var createVAONative = require("./lib/vao-native.js")
+var createVAOEmulated = require("./lib/vao-emulated.js")
+
+function createVAO(gl, attributes, elements, elementsType) {
+  var ext = gl.getExtension('OES_vertex_array_object')
+  var vao
+  if(ext) {
+    vao = createVAONative(gl, ext)
+  } else {
+    vao = createVAOEmulated(gl)
+  }
+  vao.update(attributes, elements, elementsType)
+  return vao
+}
+
+module.exports = createVAO
+
+},{"./lib/vao-emulated.js":187,"./lib/vao-native.js":188}],190:[function(require,module,exports){
+module.exports = transformMat4
+
+/**
+ * Transforms the vec4 with a mat4.
+ *
+ * @param {vec4} out the receiving vector
+ * @param {vec4} a the vector to transform
+ * @param {mat4} m matrix to transform with
+ * @returns {vec4} out
+ */
+function transformMat4 (out, a, m) {
+  var x = a[0], y = a[1], z = a[2], w = a[3]
+  out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w
+  out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w
+  out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w
+  out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w
+  return out
+}
+
+},{}],191:[function(require,module,exports){
+"use strict"
+
+//High level idea:
+// 1. Use Clarkson's incremental construction to find convex hull
+// 2. Point location in triangulation by jump and walk
+
+module.exports = incrementalConvexHull
+
+var orient = require("robust-orientation")
+var compareCell = require("simplicial-complex").compareCells
+
+function compareInt(a, b) {
+  return a - b
+}
+
+function Simplex(vertices, adjacent, boundary) {
+  this.vertices = vertices
+  this.adjacent = adjacent
+  this.boundary = boundary
+  this.lastVisited = -1
+}
+
+Simplex.prototype.flip = function() {
+  var t = this.vertices[0]
+  this.vertices[0] = this.vertices[1]
+  this.vertices[1] = t
+  var u = this.adjacent[0]
+  this.adjacent[0] = this.adjacent[1]
+  this.adjacent[1] = u
+}
+
+function GlueFacet(vertices, cell, index) {
+  this.vertices = vertices
+  this.cell = cell
+  this.index = index
+}
+
+function compareGlue(a, b) {
+  return compareCell(a.vertices, b.vertices)
+}
+
+function bakeOrient(d) {
+  var code = ["function orient(){var tuple=this.tuple;return test("]
+  for(var i=0; i<=d; ++i) {
+    if(i > 0) {
+      code.push(",")
+    }
+    code.push("tuple[", i, "]")
+  }
+  code.push(")}return orient")
+  var proc = new Function("test", code.join(""))
+  var test = orient[d+1]
+  if(!test) {
+    test = orient
+  }
+  return proc(test)
+}
+
+var BAKED = []
+
+function Triangulation(dimension, vertices, simplices) {
+  this.dimension = dimension
+  this.vertices = vertices
+  this.simplices = simplices
+  this.interior = simplices.filter(function(c) {
+    return !c.boundary
+  })
+
+  this.tuple = new Array(dimension+1)
+  for(var i=0; i<=dimension; ++i) {
+    this.tuple[i] = this.vertices[i]
+  }
+
+  var o = BAKED[dimension]
+  if(!o) {
+    o = BAKED[dimension] = bakeOrient(dimension)
+  }
+  this.orient = o
+}
+
+var proto = Triangulation.prototype
+
+//Degenerate situation where we are on boundary, but coplanar to face
+proto.handleBoundaryDegeneracy = function(cell, point) {
+  var d = this.dimension
+  var n = this.vertices.length - 1
+  var tuple = this.tuple
+  var verts = this.vertices
+
+  //Dumb solution: Just do dfs from boundary cell until we find any peak, or terminate
+  var toVisit = [ cell ]
+  cell.lastVisited = -n
+  while(toVisit.length > 0) {
+    cell = toVisit.pop()
+    var cellVerts = cell.vertices
+    var cellAdj = cell.adjacent
+    for(var i=0; i<=d; ++i) {
+      var neighbor = cellAdj[i]
+      if(!neighbor.boundary || neighbor.lastVisited <= -n) {
+        continue
+      }
+      var nv = neighbor.vertices
+      for(var j=0; j<=d; ++j) {
+        var vv = nv[j]
+        if(vv < 0) {
+          tuple[j] = point
+        } else {
+          tuple[j] = verts[vv]
+        }
+      }
+      var o = this.orient()
+      if(o > 0) {
+        return neighbor
+      }
+      neighbor.lastVisited = -n
+      if(o === 0) {
+        toVisit.push(neighbor)
+      }
+    }
+  }
+  return null
+}
+
+proto.walk = function(point, random) {
+  //Alias local properties
+  var n = this.vertices.length - 1
+  var d = this.dimension
+  var verts = this.vertices
+  var tuple = this.tuple
+
+  //Compute initial jump cell
+  var initIndex = random ? (this.interior.length * Math.random())|0 : (this.interior.length-1)
+  var cell = this.interior[ initIndex ]
+
+  //Start walking
+outerLoop:
+  while(!cell.boundary) {
+    var cellVerts = cell.vertices
+    var cellAdj = cell.adjacent
+
+    for(var i=0; i<=d; ++i) {
+      tuple[i] = verts[cellVerts[i]]
+    }
+    cell.lastVisited = n
+
+    //Find farthest adjacent cell
+    for(var i=0; i<=d; ++i) {
+      var neighbor = cellAdj[i]
+      if(neighbor.lastVisited >= n) {
+        continue
+      }
+      var prev = tuple[i]
+      tuple[i] = point
+      var o = this.orient()
+      tuple[i] = prev
+      if(o < 0) {
+        cell = neighbor
+        continue outerLoop
+      } else {
+        if(!neighbor.boundary) {
+          neighbor.lastVisited = n
+        } else {
+          neighbor.lastVisited = -n
+        }
+      }
+    }
+    return
+  }
+
+  return cell
+}
+
+proto.addPeaks = function(point, cell) {
+  var n = this.vertices.length - 1
+  var d = this.dimension
+  var verts = this.vertices
+  var tuple = this.tuple
+  var interior = this.interior
+  var simplices = this.simplices
+
+  //Walking finished at boundary, time to add peaks
+  var tovisit = [ cell ]
+
+  //Stretch initial boundary cell into a peak
+  cell.lastVisited = n
+  cell.vertices[cell.vertices.indexOf(-1)] = n
+  cell.boundary = false
+  interior.push(cell)
+
+  //Record a list of all new boundaries created by added peaks so we can glue them together when we are all done
+  var glueFacets = []
+
+  //Do a traversal of the boundary walking outward from starting peak
+  while(tovisit.length > 0) {
+    //Pop off peak and walk over adjacent cells
+    var cell = tovisit.pop()
+    var cellVerts = cell.vertices
+    var cellAdj = cell.adjacent
+    var indexOfN = cellVerts.indexOf(n)
+    if(indexOfN < 0) {
+      continue
+    }
+
+    for(var i=0; i<=d; ++i) {
+      if(i === indexOfN) {
+        continue
+      }
+
+      //For each boundary neighbor of the cell
+      var neighbor = cellAdj[i]
+      if(!neighbor.boundary || neighbor.lastVisited >= n) {
+        continue
+      }
+
+      var nv = neighbor.vertices
+
+      //Test if neighbor is a peak
+      if(neighbor.lastVisited !== -n) {      
+        //Compute orientation of p relative to each boundary peak
+        var indexOfNeg1 = 0
+        for(var j=0; j<=d; ++j) {
+          if(nv[j] < 0) {
+            indexOfNeg1 = j
+            tuple[j] = point
+          } else {
+            tuple[j] = verts[nv[j]]
+          }
+        }
+        var o = this.orient()
+
+        //Test if neighbor cell is also a peak
+        if(o > 0) {
+          nv[indexOfNeg1] = n
+          neighbor.boundary = false
+          interior.push(neighbor)
+          tovisit.push(neighbor)
+          neighbor.lastVisited = n
+          continue
+        } else {
+          neighbor.lastVisited = -n
+        }
+      }
+
+      var na = neighbor.adjacent
+
+      //Otherwise, replace neighbor with new face
+      var vverts = cellVerts.slice()
+      var vadj = cellAdj.slice()
+      var ncell = new Simplex(vverts, vadj, true)
+      simplices.push(ncell)
+
+      //Connect to neighbor
+      var opposite = na.indexOf(cell)
+      if(opposite < 0) {
+        continue
+      }
+      na[opposite] = ncell
+      vadj[indexOfN] = neighbor
+
+      //Connect to cell
+      vverts[i] = -1
+      vadj[i] = cell
+      cellAdj[i] = ncell
+
+      //Flip facet
+      ncell.flip()
+
+      //Add to glue list
+      for(var j=0; j<=d; ++j) {
+        var uu = vverts[j]
+        if(uu < 0 || uu === n) {
+          continue
+        }
+        var nface = new Array(d-1)
+        var nptr = 0
+        for(var k=0; k<=d; ++k) {
+          var vv = vverts[k]
+          if(vv < 0 || k === j) {
+            continue
+          }
+          nface[nptr++] = vv
+        }
+        glueFacets.push(new GlueFacet(nface, ncell, j))
+      }
+    }
+  }
+
+  //Glue boundary facets together
+  glueFacets.sort(compareGlue)
+
+  for(var i=0; i+1<glueFacets.length; i+=2) {
+    var a = glueFacets[i]
+    var b = glueFacets[i+1]
+    var ai = a.index
+    var bi = b.index
+    if(ai < 0 || bi < 0) {
+      continue
+    }
+    a.cell.adjacent[a.index] = b.cell
+    b.cell.adjacent[b.index] = a.cell
+  }
+}
+
+proto.insert = function(point, random) {
+  //Add point
+  var verts = this.vertices
+  verts.push(point)
+
+  var cell = this.walk(point, random)
+  if(!cell) {
+    return
+  }
+
+  //Alias local properties
+  var d = this.dimension
+  var tuple = this.tuple
+
+  //Degenerate case: If point is coplanar to cell, then walk until we find a non-degenerate boundary
+  for(var i=0; i<=d; ++i) {
+    var vv = cell.vertices[i]
+    if(vv < 0) {
+      tuple[i] = point
+    } else {
+      tuple[i] = verts[vv]
+    }
+  }
+  var o = this.orient(tuple)
+  if(o < 0) {
+    return
+  } else if(o === 0) {
+    cell = this.handleBoundaryDegeneracy(cell, point)
+    if(!cell) {
+      return
+    }
+  }
+
+  //Add peaks
+  this.addPeaks(point, cell)
+}
+
+//Extract all boundary cells
+proto.boundary = function() {
+  var d = this.dimension
+  var boundary = []
+  var cells = this.simplices
+  var nc = cells.length
+  for(var i=0; i<nc; ++i) {
+    var c = cells[i]
+    if(c.boundary) {
+      var bcell = new Array(d)
+      var cv = c.vertices
+      var ptr = 0
+      var parity = 0
+      for(var j=0; j<=d; ++j) {
+        if(cv[j] >= 0) {
+          bcell[ptr++] = cv[j]
+        } else {
+          parity = j&1
+        }
+      }
+      if(parity === (d&1)) {
+        var t = bcell[0]
+        bcell[0] = bcell[1]
+        bcell[1] = t
+      }
+      boundary.push(bcell)
+    }
+  }
+  return boundary
+}
+
+function incrementalConvexHull(points, randomSearch) {
+  var n = points.length
+  if(n === 0) {
+    throw new Error("Must have at least d+1 points")
+  }
+  var d = points[0].length
+  if(n <= d) {
+    throw new Error("Must input at least d+1 points")
+  }
+
+  //FIXME: This could be degenerate, but need to select d+1 non-coplanar points to bootstrap process
+  var initialSimplex = points.slice(0, d+1)
+
+  //Make sure initial simplex is positively oriented
+  var o = orient.apply(void 0, initialSimplex)
+  if(o === 0) {
+    throw new Error("Input not in general position")
+  }
+  var initialCoords = new Array(d+1)
+  for(var i=0; i<=d; ++i) {
+    initialCoords[i] = i
+  }
+  if(o < 0) {
+    initialCoords[0] = 1
+    initialCoords[1] = 0
+  }
+
+  //Create initial topological index, glue pointers together (kind of messy)
+  var initialCell = new Simplex(initialCoords, new Array(d+1), false)
+  var boundary = initialCell.adjacent
+  var list = new Array(d+2)
+  for(var i=0; i<=d; ++i) {
+    var verts = initialCoords.slice()
+    for(var j=0; j<=d; ++j) {
+      if(j === i) {
+        verts[j] = -1
+      }
+    }
+    var t = verts[0]
+    verts[0] = verts[1]
+    verts[1] = t
+    var cell = new Simplex(verts, new Array(d+1), true)
+    boundary[i] = cell
+    list[i] = cell
+  }
+  list[d+1] = initialCell
+  for(var i=0; i<=d; ++i) {
+    var verts = boundary[i].vertices
+    var adj = boundary[i].adjacent
+    for(var j=0; j<=d; ++j) {
+      var v = verts[j]
+      if(v < 0) {
+        adj[j] = initialCell
+        continue
+      }
+      for(var k=0; k<=d; ++k) {
+        if(boundary[k].vertices.indexOf(v) < 0) {
+          adj[j] = boundary[k]
+        }
+      }
+    }
+  }
+
+  //Initialize triangles
+  var triangles = new Triangulation(d, initialSimplex, list)
+
+  //Insert remaining points
+  var useRandom = !!randomSearch
+  for(var i=d+1; i<n; ++i) {
+    triangles.insert(points[i], useRandom)
+  }
+  
+  //Extract boundary cells
+  return triangles.boundary()
+}
+},{"robust-orientation":214,"simplicial-complex":194}],192:[function(require,module,exports){
+arguments[4][49][0].apply(exports,arguments)
+},{"dup":49}],193:[function(require,module,exports){
+"use strict"; "use restrict";
+
+module.exports = UnionFind;
+
+function UnionFind(count) {
+  this.roots = new Array(count);
+  this.ranks = new Array(count);
+  
+  for(var i=0; i<count; ++i) {
+    this.roots[i] = i;
+    this.ranks[i] = 0;
+  }
+}
+
+var proto = UnionFind.prototype
+
+Object.defineProperty(proto, "length", {
+  "get": function() {
+    return this.roots.length
+  }
+})
+
+proto.makeSet = function() {
+  var n = this.roots.length;
+  this.roots.push(n);
+  this.ranks.push(0);
+  return n;
+}
+
+proto.find = function(x) {
+  var x0 = x
+  var roots = this.roots;
+  while(roots[x] !== x) {
+    x = roots[x]
+  }
+  while(roots[x0] !== x) {
+    var y = roots[x0]
+    roots[x0] = x
+    x0 = y
+  }
+  return x;
+}
+
+proto.link = function(x, y) {
+  var xr = this.find(x)
+    , yr = this.find(y);
+  if(xr === yr) {
+    return;
+  }
+  var ranks = this.ranks
+    , roots = this.roots
+    , xd    = ranks[xr]
+    , yd    = ranks[yr];
+  if(xd < yd) {
+    roots[xr] = yr;
+  } else if(yd < xd) {
+    roots[yr] = xr;
+  } else {
+    roots[yr] = xr;
+    ++ranks[xr];
+  }
+}
+},{}],194:[function(require,module,exports){
+"use strict"; "use restrict";
+
+var bits      = require("bit-twiddle")
+  , UnionFind = require("union-find")
+
+//Returns the dimension of a cell complex
+function dimension(cells) {
+  var d = 0
+    , max = Math.max
+  for(var i=0, il=cells.length; i<il; ++i) {
+    d = max(d, cells[i].length)
+  }
+  return d-1
+}
+exports.dimension = dimension
+
+//Counts the number of vertices in faces
+function countVertices(cells) {
+  var vc = -1
+    , max = Math.max
+  for(var i=0, il=cells.length; i<il; ++i) {
+    var c = cells[i]
+    for(var j=0, jl=c.length; j<jl; ++j) {
+      vc = max(vc, c[j])
+    }
+  }
+  return vc+1
+}
+exports.countVertices = countVertices
+
+//Returns a deep copy of cells
+function cloneCells(cells) {
+  var ncells = new Array(cells.length)
+  for(var i=0, il=cells.length; i<il; ++i) {
+    ncells[i] = cells[i].slice(0)
+  }
+  return ncells
+}
+exports.cloneCells = cloneCells
+
+//Ranks a pair of cells up to permutation
+function compareCells(a, b) {
+  var n = a.length
+    , t = a.length - b.length
+    , min = Math.min
+  if(t) {
+    return t
+  }
+  switch(n) {
+    case 0:
+      return 0;
+    case 1:
+      return a[0] - b[0];
+    case 2:
+      var d = a[0]+a[1]-b[0]-b[1]
+      if(d) {
+        return d
+      }
+      return min(a[0],a[1]) - min(b[0],b[1])
+    case 3:
+      var l1 = a[0]+a[1]
+        , m1 = b[0]+b[1]
+      d = l1+a[2] - (m1+b[2])
+      if(d) {
+        return d
+      }
+      var l0 = min(a[0], a[1])
+        , m0 = min(b[0], b[1])
+        , d  = min(l0, a[2]) - min(m0, b[2])
+      if(d) {
+        return d
+      }
+      return min(l0+a[2], l1) - min(m0+b[2], m1)
+    
+    //TODO: Maybe optimize n=4 as well?
+    
+    default:
+      var as = a.slice(0)
+      as.sort()
+      var bs = b.slice(0)
+      bs.sort()
+      for(var i=0; i<n; ++i) {
+        t = as[i] - bs[i]
+        if(t) {
+          return t
+        }
+      }
+      return 0
+  }
+}
+exports.compareCells = compareCells
+
+function compareZipped(a, b) {
+  return compareCells(a[0], b[0])
+}
+
+//Puts a cell complex into normal order for the purposes of findCell queries
+function normalize(cells, attr) {
+  if(attr) {
+    var len = cells.length
+    var zipped = new Array(len)
+    for(var i=0; i<len; ++i) {
+      zipped[i] = [cells[i], attr[i]]
+    }
+    zipped.sort(compareZipped)
+    for(var i=0; i<len; ++i) {
+      cells[i] = zipped[i][0]
+      attr[i] = zipped[i][1]
+    }
+    return cells
+  } else {
+    cells.sort(compareCells)
+    return cells
+  }
+}
+exports.normalize = normalize
+
+//Removes all duplicate cells in the complex
+function unique(cells) {
+  if(cells.length === 0) {
+    return []
+  }
+  var ptr = 1
+    , len = cells.length
+  for(var i=1; i<len; ++i) {
+    var a = cells[i]
+    if(compareCells(a, cells[i-1])) {
+      if(i === ptr) {
+        ptr++
+        continue
+      }
+      cells[ptr++] = a
+    }
+  }
+  cells.length = ptr
+  return cells
+}
+exports.unique = unique;
+
+//Finds a cell in a normalized cell complex
+function findCell(cells, c) {
+  var lo = 0
+    , hi = cells.length-1
+    , r  = -1
+  while (lo <= hi) {
+    var mid = (lo + hi) >> 1
+      , s   = compareCells(cells[mid], c)
+    if(s <= 0) {
+      if(s === 0) {
+        r = mid
+      }
+      lo = mid + 1
+    } else if(s > 0) {
+      hi = mid - 1
+    }
+  }
+  return r
+}
+exports.findCell = findCell;
+
+//Builds an index for an n-cell.  This is more general than dual, but less efficient
+function incidence(from_cells, to_cells) {
+  var index = new Array(from_cells.length)
+  for(var i=0, il=index.length; i<il; ++i) {
+    index[i] = []
+  }
+  var b = []
+  for(var i=0, n=to_cells.length; i<n; ++i) {
+    var c = to_cells[i]
+    var cl = c.length
+    for(var k=1, kn=(1<<cl); k<kn; ++k) {
+      b.length = bits.popCount(k)
+      var l = 0
+      for(var j=0; j<cl; ++j) {
+        if(k & (1<<j)) {
+          b[l++] = c[j]
+        }
+      }
+      var idx=findCell(from_cells, b)
+      if(idx < 0) {
+        continue
+      }
+      while(true) {
+        index[idx++].push(i)
+        if(idx >= from_cells.length || compareCells(from_cells[idx], b) !== 0) {
+          break
+        }
+      }
+    }
+  }
+  return index
+}
+exports.incidence = incidence
+
+//Computes the dual of the mesh.  This is basically an optimized version of buildIndex for the situation where from_cells is just the list of vertices
+function dual(cells, vertex_count) {
+  if(!vertex_count) {
+    return incidence(unique(skeleton(cells, 0)), cells, 0)
+  }
+  var res = new Array(vertex_count)
+  for(var i=0; i<vertex_count; ++i) {
+    res[i] = []
+  }
+  for(var i=0, len=cells.length; i<len; ++i) {
+    var c = cells[i]
+    for(var j=0, cl=c.length; j<cl; ++j) {
+      res[c[j]].push(i)
+    }
+  }
+  return res
+}
+exports.dual = dual
+
+//Enumerates all cells in the complex
+function explode(cells) {
+  var result = []
+  for(var i=0, il=cells.length; i<il; ++i) {
+    var c = cells[i]
+      , cl = c.length|0
+    for(var j=1, jl=(1<<cl); j<jl; ++j) {
+      var b = []
+      for(var k=0; k<cl; ++k) {
+        if((j >>> k) & 1) {
+          b.push(c[k])
+        }
+      }
+      result.push(b)
+    }
+  }
+  return normalize(result)
+}
+exports.explode = explode
+
+//Enumerates all of the n-cells of a cell complex
+function skeleton(cells, n) {
+  if(n < 0) {
+    return []
+  }
+  var result = []
+    , k0     = (1<<(n+1))-1
+  for(var i=0; i<cells.length; ++i) {
+    var c = cells[i]
+    for(var k=k0; k<(1<<c.length); k=bits.nextCombination(k)) {
+      var b = new Array(n+1)
+        , l = 0
+      for(var j=0; j<c.length; ++j) {
+        if(k & (1<<j)) {
+          b[l++] = c[j]
+        }
+      }
+      result.push(b)
+    }
+  }
+  return normalize(result)
+}
+exports.skeleton = skeleton;
+
+//Computes the boundary of all cells, does not remove duplicates
+function boundary(cells) {
+  var res = []
+  for(var i=0,il=cells.length; i<il; ++i) {
+    var c = cells[i]
+    for(var j=0,cl=c.length; j<cl; ++j) {
+      var b = new Array(c.length-1)
+      for(var k=0, l=0; k<cl; ++k) {
+        if(k !== j) {
+          b[l++] = c[k]
+        }
+      }
+      res.push(b)
+    }
+  }
+  return normalize(res)
+}
+exports.boundary = boundary;
+
+//Computes connected components for a dense cell complex
+function connectedComponents_dense(cells, vertex_count) {
+  var labels = new UnionFind(vertex_count)
+  for(var i=0; i<cells.length; ++i) {
+    var c = cells[i]
+    for(var j=0; j<c.length; ++j) {
+      for(var k=j+1; k<c.length; ++k) {
+        labels.link(c[j], c[k])
+      }
+    }
+  }
+  var components = []
+    , component_labels = labels.ranks
+  for(var i=0; i<component_labels.length; ++i) {
+    component_labels[i] = -1
+  }
+  for(var i=0; i<cells.length; ++i) {
+    var l = labels.find(cells[i][0])
+    if(component_labels[l] < 0) {
+      component_labels[l] = components.length
+      components.push([cells[i].slice(0)])
+    } else {
+      components[component_labels[l]].push(cells[i].slice(0))
+    }
+  }
+  return components
+}
+
+//Computes connected components for a sparse graph
+function connectedComponents_sparse(cells) {
+  var vertices  = unique(normalize(skeleton(cells, 0)))
+    , labels    = new UnionFind(vertices.length)
+  for(var i=0; i<cells.length; ++i) {
+    var c = cells[i]
+    for(var j=0; j<c.length; ++j) {
+      var vj = findCell(vertices, [c[j]])
+      for(var k=j+1; k<c.length; ++k) {
+        labels.link(vj, findCell(vertices, [c[k]]))
+      }
+    }
+  }
+  var components        = []
+    , component_labels  = labels.ranks
+  for(var i=0; i<component_labels.length; ++i) {
+    component_labels[i] = -1
+  }
+  for(var i=0; i<cells.length; ++i) {
+    var l = labels.find(findCell(vertices, [cells[i][0]]));
+    if(component_labels[l] < 0) {
+      component_labels[l] = components.length
+      components.push([cells[i].slice(0)])
+    } else {
+      components[component_labels[l]].push(cells[i].slice(0))
+    }
+  }
+  return components
+}
+
+//Computes connected components for a cell complex
+function connectedComponents(cells, vertex_count) {
+  if(vertex_count) {
+    return connectedComponents_dense(cells, vertex_count)
+  }
+  return connectedComponents_sparse(cells)
+}
+exports.connectedComponents = connectedComponents
+
+},{"bit-twiddle":192,"union-find":193}],195:[function(require,module,exports){
+"use strict"
+
+function iota(n) {
+  var result = new Array(n)
+  for(var i=0; i<n; ++i) {
+    result[i] = i
+  }
+  return result
+}
+
+module.exports = iota
+},{}],196:[function(require,module,exports){
+'use strict'
+
+module.exports = mouseListen
+
+var mouse = require('mouse-event')
+
+function mouseListen(element, callback) {
+
+  if(!callback) {
+    callback = element
+    element = window
+  }
+
+  var buttonState = 0
+  var x = 0
+  var y = 0
+  var mods = {
+    shift:   false,
+    alt:     false,
+    control: false,
+    meta:    false
+  }
+  var attached = false
+
+  function updateMods(ev) {
+    var changed = false
+    if('altKey' in ev) {
+      changed = changed || ev.altKey !== mods.alt
+      mods.alt = !!ev.altKey
+    }
+    if('shiftKey' in ev) {
+      changed = changed || ev.shiftKey !== mods.shift
+      mods.shift = !!ev.shiftKey
+    }
+    if('ctrlKey' in ev) {
+      changed = changed || ev.ctrlKey !== mods.control
+      mods.control = !!ev.ctrlKey
+    }
+    if('metaKey' in ev) {
+      changed = changed || ev.metaKey !== mods.meta
+      mods.meta = !!ev.metaKey
+    }
+    return changed
+  }
+
+  function handleEvent(nextButtons, ev) {
+    var nextX = mouse.x(ev)
+    var nextY = mouse.y(ev)
+    if('buttons' in ev) {
+      nextButtons = ev.buttons|0
+    }
+    if(nextButtons !== buttonState ||
+       nextX !== x ||
+       nextY !== y ||
+       updateMods(ev)) {
+      buttonState = nextButtons|0
+      x = nextX||0
+      y = nextY||0
+      callback(buttonState, x, y, mods)
+    }
+  }
+
+  function clearState(ev) {
+    handleEvent(0, ev)
+  }
+
+  function handleBlur() {
+    if(buttonState ||
+      x ||
+      y ||
+      mods.shift ||
+      mods.alt ||
+      mods.meta ||
+      mods.control) {
+
+      x = y = 0
+      buttonState = 0
+      mods.shift = mods.alt = mods.control = mods.meta = false
+      callback(0, 0, 0, mods)
+    }
+  }
+
+  function handleMods(ev) {
+    if(updateMods(ev)) {
+      callback(buttonState, x, y, mods)
+    }
+  }
+
+  function handleMouseMove(ev) {
+    if(mouse.buttons(ev) === 0) {
+      handleEvent(0, ev)
+    } else {
+      handleEvent(buttonState, ev)
+    }
+  }
+
+  function handleMouseDown(ev) {
+    handleEvent(buttonState | mouse.buttons(ev), ev)
+  }
+
+  function handleMouseUp(ev) {
+    handleEvent(buttonState & ~mouse.buttons(ev), ev)
+  }
+
+  function attachListeners() {
+    if(attached) {
+      return
+    }
+    attached = true
+
+    element.addEventListener('mousemove', handleMouseMove)
+
+    element.addEventListener('mousedown', handleMouseDown)
+
+    element.addEventListener('mouseup', handleMouseUp)
+
+    element.addEventListener('mouseleave', clearState)
+    element.addEventListener('mouseenter', clearState)
+    element.addEventListener('mouseout', clearState)
+    element.addEventListener('mouseover', clearState)
+
+    element.addEventListener('blur', handleBlur)
+
+    element.addEventListener('keyup', handleMods)
+    element.addEventListener('keydown', handleMods)
+    element.addEventListener('keypress', handleMods)
+
+    if(element !== window) {
+      window.addEventListener('blur', handleBlur)
+
+      window.addEventListener('keyup', handleMods)
+      window.addEventListener('keydown', handleMods)
+      window.addEventListener('keypress', handleMods)
+    }
+  }
+
+  function detachListeners() {
+    if(!attached) {
+      return
+    }
+    attached = false
+
+    element.removeEventListener('mousemove', handleMouseMove)
+
+    element.removeEventListener('mousedown', handleMouseDown)
+
+    element.removeEventListener('mouseup', handleMouseUp)
+
+    element.removeEventListener('mouseleave', clearState)
+    element.removeEventListener('mouseenter', clearState)
+    element.removeEventListener('mouseout', clearState)
+    element.removeEventListener('mouseover', clearState)
+
+    element.removeEventListener('blur', handleBlur)
+
+    element.removeEventListener('keyup', handleMods)
+    element.removeEventListener('keydown', handleMods)
+    element.removeEventListener('keypress', handleMods)
+
+    if(element !== window) {
+      window.removeEventListener('blur', handleBlur)
+
+      window.removeEventListener('keyup', handleMods)
+      window.removeEventListener('keydown', handleMods)
+      window.removeEventListener('keypress', handleMods)
+    }
+  }
+
+  //Attach listeners
+  attachListeners()
+
+  var result = {
+    element: element
+  }
+
+  Object.defineProperties(result, {
+    enabled: {
+      get: function() { return attached },
+      set: function(f) {
+        if(f) {
+          attachListeners()
+        } else {
+          detachListeners
+        }
+      },
+      enumerable: true
+    },
+    buttons: {
+      get: function() { return buttonState },
+      enumerable: true
+    },
+    x: {
+      get: function() { return x },
+      enumerable: true
+    },
+    y: {
+      get: function() { return y },
+      enumerable: true
+    },
+    mods: {
+      get: function() { return mods },
+      enumerable: true
+    }
+  })
+
+  return result
+}
+
+},{"mouse-event":197}],197:[function(require,module,exports){
+'use strict'
+
+function mouseButtons(ev) {
+  if(typeof ev === 'object') {
+    if('buttons' in ev) {
+      return ev.buttons
+    } else if('which' in ev) {
+      var b = ev.which
+      if(b === 2) {
+        return 4
+      } else if(b === 3) {
+        return 2
+      } else if(b > 0) {
+        return 1<<(b-1)
+      }
+    } else if('button' in ev) {
+      var b = ev.button
+      if(b === 1) {
+        return 4
+      } else if(b === 2) {
+        return 2
+      } else if(b >= 0) {
+        return 1<<b
+      }
+    }
+  }
+  return 0
+}
+exports.buttons = mouseButtons
+
+function mouseElement(ev) {
+  return ev.target || ev.srcElement || window
+}
+exports.element = mouseElement
+
+function mouseRelativeX(ev) {
+  if(typeof ev === 'object') {
+    if('offsetX' in ev) {
+      return ev.offsetX
+    }
+    var target = mouseElement(ev)
+    var bounds = target.getBoundingClientRect()
+    return ev.clientX - bounds.left
+  }
+  return 0
+}
+exports.x = mouseRelativeX
+
+function mouseRelativeY(ev) {
+  if(typeof ev === 'object') {
+    if('offsetY' in ev) {
+      return ev.offsetY
+    }
+    var target = mouseElement(ev)
+    var bounds = target.getBoundingClientRect()
+    return ev.clientY - bounds.top
+  }
+  return 0
+}
+exports.y = mouseRelativeY
+
+},{}],198:[function(require,module,exports){
+module.exports = function parseUnit(str, out) {
+    if (!out)
+        out = [ 0, '' ]
+
+    str = String(str)
+    var num = parseFloat(str, 10)
+    out[0] = num
+    out[1] = str.match(/[\d.\-\+]*\s*(.*)/)[1] || ''
+    return out
+}
+},{}],199:[function(require,module,exports){
+'use strict'
+
+var parseUnit = require('parse-unit')
+
+module.exports = toPX
+
+var PIXELS_PER_INCH = 96
+
+function getPropertyInPX(element, prop) {
+  var parts = parseUnit(getComputedStyle(element).getPropertyValue(prop))
+  return parts[0] * toPX(parts[1], element)
+}
+
+//This brutal hack is needed
+function getSizeBrutal(unit, element) {
+  var testDIV = document.createElement('div')
+  testDIV.style['font-size'] = '128' + unit
+  element.appendChild(testDIV)
+  var size = getPropertyInPX(testDIV, 'font-size') / 128
+  element.removeChild(testDIV)
+  return size
+}
+
+function toPX(str, element) {
+  element = element || document.body
+  str = (str || 'px').trim().toLowerCase()
+  if(element === window || element === document) {
+    element = document.body 
+  }
+  switch(str) {
+    case '%':  //Ambiguous, not sure if we should use width or height
+      return element.clientHeight / 100.0
+    case 'ch':
+    case 'ex':
+      return getSizeBrutal(str, element)
+    case 'em':
+      return getPropertyInPX(element, 'font-size')
+    case 'rem':
+      return getPropertyInPX(document.body, 'font-size')
+    case 'vw':
+      return window.innerWidth/100
+    case 'vh':
+      return window.innerHeight/100
+    case 'vmin':
+      return Math.min(window.innerWidth, window.innerHeight) / 100
+    case 'vmax':
+      return Math.max(window.innerWidth, window.innerHeight) / 100
+    case 'in':
+      return PIXELS_PER_INCH
+    case 'cm':
+      return PIXELS_PER_INCH / 2.54
+    case 'mm':
+      return PIXELS_PER_INCH / 25.4
+    case 'pt':
+      return PIXELS_PER_INCH / 72
+    case 'pc':
+      return PIXELS_PER_INCH / 6
+  }
+  return 1
+}
+},{"parse-unit":198}],200:[function(require,module,exports){
+'use strict'
+
+var toPX = require('to-px')
+
+module.exports = mouseWheelListen
+
+function mouseWheelListen(element, callback, noScroll) {
+  if(typeof element === 'function') {
+    noScroll = !!callback
+    callback = element
+    element = window
+  }
+  var lineHeight = toPX('ex', element)
+  element.addEventListener('wheel', function(ev) {
+    if(noScroll) {
+      ev.preventDefault()
+    }
+    var dx = ev.deltaX || 0
+    var dy = ev.deltaY || 0
+    var dz = ev.deltaZ || 0
+    var mode = ev.deltaMode
+    var scale = 1
+    switch(mode) {
+      case 1:
+        scale = lineHeight
+      break
+      case 2:
+        scale = window.innerHeight
+      break
+    }
+    dx *= scale
+    dy *= scale
+    dz *= scale
+    if(dx || dy || dz) {
+      return callback(dx, dy, dz)
+    }
+  })
+}
+},{"to-px":199}],201:[function(require,module,exports){
+"use strict"
+
+
+
+var fill = require('cwise/lib/wrapper')({"args":["index","array","scalar"],"pre":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"body":{"body":"{_inline_1_arg1_=_inline_1_arg2_.apply(void 0,_inline_1_arg0_)}","args":[{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_1_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_1_arg2_","lvalue":false,"rvalue":true,"count":1}],"thisVars":[],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"cwise","blockSize":64})
+
+module.exports = function(array, f) {
+  fill(array, f)
+  return array
+}
+
+},{"cwise/lib/wrapper":69}],202:[function(require,module,exports){
+'use strict'
+
+module.exports = invert
+
+var invert2 = require('gl-mat2/invert')
+var invert3 = require('gl-mat3/invert')
+var invert4 = require('gl-mat4/invert')
+
+function invert(out, M) {
+  switch(M.length) {
+    case 0:
+    break
+    case 1:
+      out[0] = 1.0 / M[0]
+    break
+    case 4:
+      invert2(out, M)
+    break
+    case 9:
+      invert3(out, M)
+    break
+    case 16:
+      invert4(out, M)
+    break
+    default:
+      throw new Error('currently supports matrices up to 4x4')
+    break
+  }
+  return out
+}
+},{"gl-mat2/invert":203,"gl-mat3/invert":87,"gl-mat4/invert":94}],203:[function(require,module,exports){
+module.exports = invert
+
+/**
+ * Inverts a mat2
+ *
+ * @alias mat2.invert
+ * @param {mat2} out the receiving matrix
+ * @param {mat2} a the source matrix
+ * @returns {mat2} out
+ */
+function invert(out, a) {
+  var a0 = a[0]
+  var a1 = a[1]
+  var a2 = a[2]
+  var a3 = a[3]
+  var det = a0 * a3 - a2 * a1
+
+  if (!det) return null
+  det = 1.0 / det
+
+  out[0] =  a3 * det
+  out[1] = -a1 * det
+  out[2] = -a2 * det
+  out[3] =  a0 * det
+
+  return out
+}
+
+},{}],204:[function(require,module,exports){
+"use strict"
+
+function interp1d(arr, x) {
+  var ix = Math.floor(x)
+    , fx = x - ix
+    , s0 = 0 <= ix   && ix   < arr.shape[0]
+    , s1 = 0 <= ix+1 && ix+1 < arr.shape[0]
+    , w0 = s0 ? +arr.get(ix)   : 0.0
+    , w1 = s1 ? +arr.get(ix+1) : 0.0
+  return (1.0-fx)*w0 + fx*w1
+}
+
+function interp2d(arr, x, y) {
+  var ix = Math.floor(x)
+    , fx = x - ix
+    , s0 = 0 <= ix   && ix   < arr.shape[0]
+    , s1 = 0 <= ix+1 && ix+1 < arr.shape[0]
+    , iy = Math.floor(y)
+    , fy = y - iy
+    , t0 = 0 <= iy   && iy   < arr.shape[1]
+    , t1 = 0 <= iy+1 && iy+1 < arr.shape[1]
+    , w00 = s0&&t0 ? arr.get(ix  ,iy  ) : 0.0
+    , w01 = s0&&t1 ? arr.get(ix  ,iy+1) : 0.0
+    , w10 = s1&&t0 ? arr.get(ix+1,iy  ) : 0.0
+    , w11 = s1&&t1 ? arr.get(ix+1,iy+1) : 0.0
+  return (1.0-fy) * ((1.0-fx)*w00 + fx*w10) + fy * ((1.0-fx)*w01 + fx*w11)
+}
+
+function interp3d(arr, x, y, z) {
+  var ix = Math.floor(x)
+    , fx = x - ix
+    , s0 = 0 <= ix   && ix   < arr.shape[0]
+    , s1 = 0 <= ix+1 && ix+1 < arr.shape[0]
+    , iy = Math.floor(y)
+    , fy = y - iy
+    , t0 = 0 <= iy   && iy   < arr.shape[1]
+    , t1 = 0 <= iy+1 && iy+1 < arr.shape[1]
+    , iz = Math.floor(z)
+    , fz = z - iz
+    , u0 = 0 <= iz   && iz   < arr.shape[2]
+    , u1 = 0 <= iz+1 && iz+1 < arr.shape[2]
+    , w000 = s0&&t0&&u0 ? arr.get(ix,iy,iz)       : 0.0
+    , w010 = s0&&t1&&u0 ? arr.get(ix,iy+1,iz)     : 0.0
+    , w100 = s1&&t0&&u0 ? arr.get(ix+1,iy,iz)     : 0.0
+    , w110 = s1&&t1&&u0 ? arr.get(ix+1,iy+1,iz)   : 0.0
+    , w001 = s0&&t0&&u1 ? arr.get(ix,iy,iz+1)     : 0.0
+    , w011 = s0&&t1&&u1 ? arr.get(ix,iy+1,iz+1)   : 0.0
+    , w101 = s1&&t0&&u1 ? arr.get(ix+1,iy,iz+1)   : 0.0
+    , w111 = s1&&t1&&u1 ? arr.get(ix+1,iy+1,iz+1) : 0.0
+  return (1.0-fz) * ((1.0-fy) * ((1.0-fx)*w000 + fx*w100) + fy * ((1.0-fx)*w010 + fx*w110)) + fz * ((1.0-fy) * ((1.0-fx)*w001 + fx*w101) + fy * ((1.0-fx)*w011 + fx*w111))
+}
+
+function interpNd(arr) {
+  var d = arr.shape.length|0
+    , ix = new Array(d)
+    , fx = new Array(d)
+    , s0 = new Array(d)
+    , s1 = new Array(d)
+    , i, t
+  for(i=0; i<d; ++i) {
+    t = +arguments[i+1]
+    ix[i] = Math.floor(t)
+    fx[i] = t - ix[i]
+    s0[i] = (0 <= ix[i]   && ix[i]   < arr.shape[i])
+    s1[i] = (0 <= ix[i]+1 && ix[i]+1 < arr.shape[i])
+  }
+  var r = 0.0, j, w, idx
+i_loop:
+  for(i=0; i<(1<<d); ++i) {
+    w = 1.0
+    idx = arr.offset
+    for(j=0; j<d; ++j) {
+      if(i & (1<<j)) {
+        if(!s1[j]) {
+          continue i_loop
+        }
+        w *= fx[j]
+        idx += arr.stride[j] * (ix[j] + 1)
+      } else {
+        if(!s0[j]) {
+          continue i_loop
+        }
+        w *= 1.0 - fx[j]
+        idx += arr.stride[j] * ix[j]
+      }
+    }
+    r += w * arr.data[idx]
+  }
+  return r
+}
+
+function interpolate(arr, x, y, z) {
+  switch(arr.shape.length) {
+    case 0:
+      return 0.0
+    case 1:
+      return interp1d(arr, x)
+    case 2:
+      return interp2d(arr, x, y)
+    case 3:
+      return interp3d(arr, x, y, z)
+    default:
+      return interpNd.apply(undefined, arguments)
+  }
+}
+module.exports = interpolate
+module.exports.d1 = interp1d
+module.exports.d2 = interp2d
+module.exports.d3 = interp3d
+
+},{}],205:[function(require,module,exports){
+'use strict'
+
+var interp  = require('ndarray-linear-interpolate')
+
+
+var do_warp = require('cwise/lib/wrapper')({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=new Array(_inline_6_arg4_)}","args":[{"name":"_inline_6_arg0_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_6_arg1_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_6_arg2_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_6_arg3_","lvalue":false,"rvalue":false,"count":0},{"name":"_inline_6_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_7_arg2_(this_warped,_inline_7_arg0_),_inline_7_arg1_=_inline_7_arg3_.apply(void 0,this_warped)}","args":[{"name":"_inline_7_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_7_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_7_arg3_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warpND","blockSize":64})
+
+var do_warp_1 = require('cwise/lib/wrapper')({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_10_arg2_(this_warped,_inline_10_arg0_),_inline_10_arg1_=_inline_10_arg3_(_inline_10_arg4_,this_warped[0])}","args":[{"name":"_inline_10_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_10_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_10_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp1D","blockSize":64})
+
+var do_warp_2 = require('cwise/lib/wrapper')({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_13_arg2_(this_warped,_inline_13_arg0_),_inline_13_arg1_=_inline_13_arg3_(_inline_13_arg4_,this_warped[0],this_warped[1])}","args":[{"name":"_inline_13_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_13_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_13_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp2D","blockSize":64})
+
+var do_warp_3 = require('cwise/lib/wrapper')({"args":["index","array","scalar","scalar","scalar"],"pre":{"body":"{this_warped=[0,0,0]}","args":[],"thisVars":["this_warped"],"localVars":[]},"body":{"body":"{_inline_16_arg2_(this_warped,_inline_16_arg0_),_inline_16_arg1_=_inline_16_arg3_(_inline_16_arg4_,this_warped[0],this_warped[1],this_warped[2])}","args":[{"name":"_inline_16_arg0_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg1_","lvalue":true,"rvalue":false,"count":1},{"name":"_inline_16_arg2_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg3_","lvalue":false,"rvalue":true,"count":1},{"name":"_inline_16_arg4_","lvalue":false,"rvalue":true,"count":1}],"thisVars":["this_warped"],"localVars":[]},"post":{"body":"{}","args":[],"thisVars":[],"localVars":[]},"debug":false,"funcName":"warp3D","blockSize":64})
+
+module.exports = function warp(dest, src, func) {
+  switch(src.shape.length) {
+    case 1:
+      do_warp_1(dest, func, interp.d1, src)
+      break
+    case 2:
+      do_warp_2(dest, func, interp.d2, src)
+      break
+    case 3:
+      do_warp_3(dest, func, interp.d3, src)
+      break
+    default:
+      do_warp(dest, func, interp.bind(undefined, src), src.shape.length)
+      break
+  }
+  return dest
+}
+
+},{"cwise/lib/wrapper":69,"ndarray-linear-interpolate":204}],206:[function(require,module,exports){
+'use strict'
+
+var warp = require('ndarray-warp')
+var invert = require('gl-matrix-invert')
+
+module.exports = applyHomography
+
+function applyHomography(dest, src, Xi) {
+  var n = src.dimension
+  var X = invert([], Xi)
+  warp(dest, src, function(out_c, inp_c) {
+    for(var i=0; i<n; ++i) {
+      out_c[i] = X[(n+1)*n + i]
+      for(var j=0; j<n; ++j) {
+        out_c[i] += X[(n+1)*j+i] * inp_c[j]
+      }
+    }
+    var w = X[(n+1)*(n+1)-1]
+    for(var j=0; j<n; ++j) {
+      w += X[(n+1)*j+n] * inp_c[j]
+    }
+    var wr = 1.0 / w
+    for(var i=0; i<n; ++i) {
+      out_c[i] *= wr
+    }
+    return out_c
+  })
+  return dest
+}
+},{"gl-matrix-invert":202,"ndarray-warp":205}],207:[function(require,module,exports){
+"use strict"
+
+var compile = require("cwise-compiler")
+
+var EmptyProc = {
+  body: "",
+  args: [],
+  thisVars: [],
+  localVars: []
+}
+
+function fixup(x) {
+  if(!x) {
+    return EmptyProc
+  }
+  for(var i=0; i<x.args.length; ++i) {
+    var a = x.args[i]
+    if(i === 0) {
+      x.args[i] = {name: a, lvalue:true, rvalue: !!x.rvalue, count:x.count||1 }
+    } else {
+      x.args[i] = {name: a, lvalue:false, rvalue:true, count: 1}
+    }
+  }
+  if(!x.thisVars) {
+    x.thisVars = []
+  }
+  if(!x.localVars) {
+    x.localVars = []
+  }
+  return x
+}
+
+function pcompile(user_args) {
+  return compile({
+    args:     user_args.args,
+    pre:      fixup(user_args.pre),
+    body:     fixup(user_args.body),
+    post:     fixup(user_args.proc),
+    funcName: user_args.funcName
+  })
+}
+
+function makeOp(user_args) {
+  var args = []
+  for(var i=0; i<user_args.args.length; ++i) {
+    args.push("a"+i)
+  }
+  var wrapper = new Function("P", [
+    "return function ", user_args.funcName, "_ndarrayops(", args.join(","), ") {P(", args.join(","), ");return a0}"
+  ].join(""))
+  return wrapper(pcompile(user_args))
+}
+
+var assign_ops = {
+  add:  "+",
+  sub:  "-",
+  mul:  "*",
+  div:  "/",
+  mod:  "%",
+  band: "&",
+  bor:  "|",
+  bxor: "^",
+  lshift: "<<",
+  rshift: ">>",
+  rrshift: ">>>"
+}
+;(function(){
+  for(var id in assign_ops) {
+    var op = assign_ops[id]
+    exports[id] = makeOp({
+      args: ["array","array","array"],
+      body: {args:["a","b","c"],
+             body: "a=b"+op+"c"},
+      funcName: id
+    })
+    exports[id+"eq"] = makeOp({
+      args: ["array","array"],
+      body: {args:["a","b"],
+             body:"a"+op+"=b"},
+      rvalue: true,
+      funcName: id+"eq"
+    })
+    exports[id+"s"] = makeOp({
+      args: ["array", "array", "scalar"],
+      body: {args:["a","b","s"],
+             body:"a=b"+op+"s"},
+      funcName: id+"s"
+    })
+    exports[id+"seq"] = makeOp({
+      args: ["array","scalar"],
+      body: {args:["a","s"],
+             body:"a"+op+"=s"},
+      rvalue: true,
+      funcName: id+"seq"
+    })
+  }
+})();
+
+var unary_ops = {
+  not: "!",
+  bnot: "~",
+  neg: "-",
+  recip: "1.0/"
+}
+;(function(){
+  for(var id in unary_ops) {
+    var op = unary_ops[id]
+    exports[id] = makeOp({
+      args: ["array", "array"],
+      body: {args:["a","b"],
+             body:"a="+op+"b"},
+      funcName: id
+    })
+    exports[id+"eq"] = makeOp({
+      args: ["array"],
+      body: {args:["a"],
+             body:"a="+op+"a"},
+      rvalue: true,
+      count: 2,
+      funcName: id+"eq"
+    })
+  }
+})();
+
+var binary_ops = {
+  and: "&&",
+  or: "||",
+  eq: "===",
+  neq: "!==",
+  lt: "<",
+  gt: ">",
+  leq: "<=",
+  geq: ">="
+}
+;(function() {
+  for(var id in binary_ops) {
+    var op = binary_ops[id]
+    exports[id] = makeOp({
+      args: ["array","array","array"],
+      body: {args:["a", "b", "c"],
+             body:"a=b"+op+"c"},
+      funcName: id
+    })
+    exports[id+"s"] = makeOp({
+      args: ["array","array","scalar"],
+      body: {args:["a", "b", "s"],
+             body:"a=b"+op+"s"},
+      funcName: id+"s"
+    })
+    exports[id+"eq"] = makeOp({
+      args: ["array", "array"],
+      body: {args:["a", "b"],
+             body:"a=a"+op+"b"},
+      rvalue:true,
+      count:2,
+      funcName: id+"eq"
+    })
+    exports[id+"seq"] = makeOp({
+      args: ["array", "scalar"],
+      body: {args:["a","s"],
+             body:"a=a"+op+"s"},
+      rvalue:true,
+      count:2,
+      funcName: id+"seq"
+    })
+  }
+})();
+
+var math_unary = [
+  "abs",
+  "acos",
+  "asin",
+  "atan",
+  "ceil",
+  "cos",
+  "exp",
+  "floor",
+  "log",
+  "round",
+  "sin",
+  "sqrt",
+  "tan"
+]
+;(function() {
+  for(var i=0; i<math_unary.length; ++i) {
+    var f = math_unary[i]
+    exports[f] = makeOp({
+                    args: ["array", "array"],
+                    pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
+                    body: {args:["a","b"], body:"a=this_f(b)", thisVars:["this_f"]},
+                    funcName: f
+                  })
+    exports[f+"eq"] = makeOp({
+                      args: ["array"],
+                      pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
+                      body: {args: ["a"], body:"a=this_f(a)", thisVars:["this_f"]},
+                      rvalue: true,
+                      count: 2,
+                      funcName: f+"eq"
+                    })
+  }
+})();
+
+var math_comm = [
+  "max",
+  "min",
+  "atan2",
+  "pow"
+]
+;(function(){
+  for(var i=0; i<math_comm.length; ++i) {
+    var f= math_comm[i]
+    exports[f] = makeOp({
+                  args:["array", "array", "array"],
+                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
+                  body: {args:["a","b","c"], body:"a=this_f(b,c)", thisVars:["this_f"]},
+                  funcName: f
+                })
+    exports[f+"s"] = makeOp({
+                  args:["array", "array", "scalar"],
+                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
+                  body: {args:["a","b","c"], body:"a=this_f(b,c)", thisVars:["this_f"]},
+                  funcName: f+"s"
+                  })
+    exports[f+"eq"] = makeOp({ args:["array", "array"],
+                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
+                  body: {args:["a","b"], body:"a=this_f(a,b)", thisVars:["this_f"]},
+                  rvalue: true,
+                  count: 2,
+                  funcName: f+"eq"
+                  })
+    exports[f+"seq"] = makeOp({ args:["array", "scalar"],
+                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
+                  body: {args:["a","b"], body:"a=this_f(a,b)", thisVars:["this_f"]},
+                  rvalue:true,
+                  count:2,
+                  funcName: f+"seq"
+                  })
+  }
+})();
+
+var math_noncomm = [
+  "atan2",
+  "pow"
+]
+;(function(){
+  for(var i=0; i<math_noncomm.length; ++i) {
+    var f= math_noncomm[i]
+    exports[f+"op"] = makeOp({
+                  args:["array", "array", "array"],
+                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
+                  body: {args:["a","b","c"], body:"a=this_f(c,b)", thisVars:["this_f"]},
+                  funcName: f+"op"
+                })
+    exports[f+"ops"] = makeOp({
+                  args:["array", "array", "scalar"],
+                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
+                  body: {args:["a","b","c"], body:"a=this_f(c,b)", thisVars:["this_f"]},
+                  funcName: f+"ops"
+                  })
+    exports[f+"opeq"] = makeOp({ args:["array", "array"],
+                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
+                  body: {args:["a","b"], body:"a=this_f(b,a)", thisVars:["this_f"]},
+                  rvalue: true,
+                  count: 2,
+                  funcName: f+"opeq"
+                  })
+    exports[f+"opseq"] = makeOp({ args:["array", "scalar"],
+                  pre: {args:[], body:"this_f=Math."+f, thisVars:["this_f"]},
+                  body: {args:["a","b"], body:"a=this_f(b,a)", thisVars:["this_f"]},
+                  rvalue:true,
+                  count:2,
+                  funcName: f+"opseq"
+                  })
+  }
+})();
+
+exports.any = compile({
+  args:["array"],
+  pre: EmptyProc,
+  body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "if(a){return true}", localVars: [], thisVars: []},
+  post: {args:[], localVars:[], thisVars:[], body:"return false"},
+  funcName: "any"
+})
+
+exports.all = compile({
+  args:["array"],
+  pre: EmptyProc,
+  body: {args:[{name:"x", lvalue:false, rvalue:true, count:1}], body: "if(!x){return false}", localVars: [], thisVars: []},
+  post: {args:[], localVars:[], thisVars:[], body:"return true"},
+  funcName: "all"
+})
+
+exports.sum = compile({
+  args:["array"],
+  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
+  body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s+=a", localVars: [], thisVars: ["this_s"]},
+  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
+  funcName: "sum"
+})
+
+exports.prod = compile({
+  args:["array"],
+  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=1"},
+  body: {args:[{name:"a", lvalue:false, rvalue:true, count:1}], body: "this_s*=a", localVars: [], thisVars: ["this_s"]},
+  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
+  funcName: "prod"
+})
+
+exports.norm2squared = compile({
+  args:["array"],
+  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
+  body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]},
+  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
+  funcName: "norm2squared"
+})
+  
+exports.norm2 = compile({
+  args:["array"],
+  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
+  body: {args:[{name:"a", lvalue:false, rvalue:true, count:2}], body: "this_s+=a*a", localVars: [], thisVars: ["this_s"]},
+  post: {args:[], localVars:[], thisVars:["this_s"], body:"return Math.sqrt(this_s)"},
+  funcName: "norm2"
+})
+  
+
+exports.norminf = compile({
+  args:["array"],
+  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
+  body: {args:[{name:"a", lvalue:false, rvalue:true, count:4}], body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}", localVars: [], thisVars: ["this_s"]},
+  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
+  funcName: "norminf"
+})
+
+exports.norm1 = compile({
+  args:["array"],
+  pre: {args:[], localVars:[], thisVars:["this_s"], body:"this_s=0"},
+  body: {args:[{name:"a", lvalue:false, rvalue:true, count:3}], body: "this_s+=a<0?-a:a", localVars: [], thisVars: ["this_s"]},
+  post: {args:[], localVars:[], thisVars:["this_s"], body:"return this_s"},
+  funcName: "norm1"
+})
+
+exports.sup = compile({
+  args: [ "array" ],
+  pre:
+   { body: "this_h=-Infinity",
+     args: [],
+     thisVars: [ "this_h" ],
+     localVars: [] },
+  body:
+   { body: "if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",
+     args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
+     thisVars: [ "this_h" ],
+     localVars: [] },
+  post:
+   { body: "return this_h",
+     args: [],
+     thisVars: [ "this_h" ],
+     localVars: [] }
+ })
+
+exports.inf = compile({
+  args: [ "array" ],
+  pre:
+   { body: "this_h=Infinity",
+     args: [],
+     thisVars: [ "this_h" ],
+     localVars: [] },
+  body:
+   { body: "if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_",
+     args: [{"name":"_inline_1_arg0_","lvalue":false,"rvalue":true,"count":2} ],
+     thisVars: [ "this_h" ],
+     localVars: [] },
+  post:
+   { body: "return this_h",
+     args: [],
+     thisVars: [ "this_h" ],
+     localVars: [] }
+ })
+
+exports.argmin = compile({
+  args:["index","array","shape"],
+  pre:{
+    body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}",
+    args:[
+      {name:"_inline_0_arg0_",lvalue:false,rvalue:false,count:0},
+      {name:"_inline_0_arg1_",lvalue:false,rvalue:false,count:0},
+      {name:"_inline_0_arg2_",lvalue:false,rvalue:true,count:1}
+      ],
+    thisVars:["this_i","this_v"],
+    localVars:[]},
+  body:{
+    body:"{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
+    args:[
+      {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
+      {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
+    thisVars:["this_i","this_v"],
+    localVars:["_inline_1_k"]},
+  post:{
+    body:"{return this_i}",
+    args:[],
+    thisVars:["this_i"],
+    localVars:[]}
+})
+
+exports.argmax = compile({
+  args:["index","array","shape"],
+  pre:{
+    body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}",
+    args:[
+      {name:"_inline_0_arg0_",lvalue:false,rvalue:false,count:0},
+      {name:"_inline_0_arg1_",lvalue:false,rvalue:false,count:0},
+      {name:"_inline_0_arg2_",lvalue:false,rvalue:true,count:1}
+      ],
+    thisVars:["this_i","this_v"],
+    localVars:[]},
+  body:{
+    body:"{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",
+    args:[
+      {name:"_inline_1_arg0_",lvalue:false,rvalue:true,count:2},
+      {name:"_inline_1_arg1_",lvalue:false,rvalue:true,count:2}],
+    thisVars:["this_i","this_v"],
+    localVars:["_inline_1_k"]},
+  post:{
+    body:"{return this_i}",
+    args:[],
+    thisVars:["this_i"],
+    localVars:[]}
+})  
+
+exports.random = makeOp({
+  args: ["array"],
+  pre: {args:[], body:"this_f=Math.random", thisVars:["this_f"]},
+  body: {args: ["a"], body:"a=this_f()", thisVars:["this_f"]},
+  funcName: "random"
+})
+
+exports.assign = makeOp({
+  args:["array", "array"],
+  body: {args:["a", "b"], body:"a=b"},
+  funcName: "assign" })
+
+exports.assigns = makeOp({
+  args:["array", "scalar"],
+  body: {args:["a", "b"], body:"a=b"},
+  funcName: "assigns" })
+
+
+exports.equals = compile({
+  args:["array", "array"],
+  pre: EmptyProc,
+  body: {args:[{name:"x", lvalue:false, rvalue:true, count:1},
+               {name:"y", lvalue:false, rvalue:true, count:1}], 
+        body: "if(x!==y){return false}", 
+        localVars: [], 
+        thisVars: []},
+  post: {args:[], localVars:[], thisVars:[], body:"return true"},
+  funcName: "equals"
+})
+
+
+
+},{"cwise-compiler":66}],208:[function(require,module,exports){
+var iota = require("iota-array")
+var isBuffer = require("is-buffer")
+
+var hasTypedArrays  = ((typeof Float64Array) !== "undefined")
+
+function compare1st(a, b) {
+  return a[0] - b[0]
+}
+
+function order() {
+  var stride = this.stride
+  var terms = new Array(stride.length)
+  var i
+  for(i=0; i<terms.length; ++i) {
+    terms[i] = [Math.abs(stride[i]), i]
+  }
+  terms.sort(compare1st)
+  var result = new Array(terms.length)
+  for(i=0; i<result.length; ++i) {
+    result[i] = terms[i][1]
+  }
+  return result
+}
+
+function compileConstructor(dtype, dimension) {
+  var className = ["View", dimension, "d", dtype].join("")
+  if(dimension < 0) {
+    className = "View_Nil" + dtype
+  }
+  var useGetters = (dtype === "generic")
+
+  if(dimension === -1) {
+    //Special case for trivial arrays
+    var code =
+      "function "+className+"(a){this.data=a;};\
+var proto="+className+".prototype;\
+proto.dtype='"+dtype+"';\
+proto.index=function(){return -1};\
+proto.size=0;\
+proto.dimension=-1;\
+proto.shape=proto.stride=proto.order=[];\
+proto.lo=proto.hi=proto.transpose=proto.step=\
+function(){return new "+className+"(this.data);};\
+proto.get=proto.set=function(){};\
+proto.pick=function(){return null};\
+return function construct_"+className+"(a){return new "+className+"(a);}"
+    var procedure = new Function(code)
+    return procedure()
+  } else if(dimension === 0) {
+    //Special case for 0d arrays
+    var code =
+      "function "+className+"(a,d) {\
+this.data = a;\
+this.offset = d\
+};\
+var proto="+className+".prototype;\
+proto.dtype='"+dtype+"';\
+proto.index=function(){return this.offset};\
+proto.dimension=0;\
+proto.size=1;\
+proto.shape=\
+proto.stride=\
+proto.order=[];\
+proto.lo=\
+proto.hi=\
+proto.transpose=\
+proto.step=function "+className+"_copy() {\
+return new "+className+"(this.data,this.offset)\
+};\
+proto.pick=function "+className+"_pick(){\
+return TrivialArray(this.data);\
+};\
+proto.valueOf=proto.get=function "+className+"_get(){\
+return "+(useGetters ? "this.data.get(this.offset)" : "this.data[this.offset]")+
+"};\
+proto.set=function "+className+"_set(v){\
+return "+(useGetters ? "this.data.set(this.offset,v)" : "this.data[this.offset]=v")+"\
+};\
+return function construct_"+className+"(a,b,c,d){return new "+className+"(a,d)}"
+    var procedure = new Function("TrivialArray", code)
+    return procedure(CACHED_CONSTRUCTORS[dtype][0])
+  }
+
+  var code = ["'use strict'"]
+
+  //Create constructor for view
+  var indices = iota(dimension)
+  var args = indices.map(function(i) { return "i"+i })
+  var index_str = "this.offset+" + indices.map(function(i) {
+        return "this.stride[" + i + "]*i" + i
+      }).join("+")
+  var shapeArg = indices.map(function(i) {
+      return "b"+i
+    }).join(",")
+  var strideArg = indices.map(function(i) {
+      return "c"+i
+    }).join(",")
+  code.push(
+    "function "+className+"(a," + shapeArg + "," + strideArg + ",d){this.data=a",
+      "this.shape=[" + shapeArg + "]",
+      "this.stride=[" + strideArg + "]",
+      "this.offset=d|0}",
+    "var proto="+className+".prototype",
+    "proto.dtype='"+dtype+"'",
+    "proto.dimension="+dimension)
+
+  //view.size:
+  code.push("Object.defineProperty(proto,'size',{get:function "+className+"_size(){\
+return "+indices.map(function(i) { return "this.shape["+i+"]" }).join("*"),
+"}})")
+
+  //view.order:
+  if(dimension === 1) {
+    code.push("proto.order=[0]")
+  } else {
+    code.push("Object.defineProperty(proto,'order',{get:")
+    if(dimension < 4) {
+      code.push("function "+className+"_order(){")
+      if(dimension === 2) {
+        code.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})")
+      } else if(dimension === 3) {
+        code.push(
+"var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);\
+if(s0>s1){\
+if(s1>s2){\
+return [2,1,0];\
+}else if(s0>s2){\
+return [1,2,0];\
+}else{\
+return [1,0,2];\
+}\
+}else if(s0>s2){\
+return [2,0,1];\
+}else if(s2>s1){\
+return [0,1,2];\
+}else{\
+return [0,2,1];\
+}}})")
+      }
+    } else {
+      code.push("ORDER})")
+    }
+  }
+
+  //view.set(i0, ..., v):
+  code.push(
+"proto.set=function "+className+"_set("+args.join(",")+",v){")
+  if(useGetters) {
+    code.push("return this.data.set("+index_str+",v)}")
+  } else {
+    code.push("return this.data["+index_str+"]=v}")
+  }
+
+  //view.get(i0, ...):
+  code.push("proto.get=function "+className+"_get("+args.join(",")+"){")
+  if(useGetters) {
+    code.push("return this.data.get("+index_str+")}")
+  } else {
+    code.push("return this.data["+index_str+"]}")
+  }
+
+  //view.index:
+  code.push(
+    "proto.index=function "+className+"_index(", args.join(), "){return "+index_str+"}")
+
+  //view.hi():
+  code.push("proto.hi=function "+className+"_hi("+args.join(",")+"){return new "+className+"(this.data,"+
+    indices.map(function(i) {
+      return ["(typeof i",i,"!=='number'||i",i,"<0)?this.shape[", i, "]:i", i,"|0"].join("")
+    }).join(",")+","+
+    indices.map(function(i) {
+      return "this.stride["+i + "]"
+    }).join(",")+",this.offset)}")
+
+  //view.lo():
+  var a_vars = indices.map(function(i) { return "a"+i+"=this.shape["+i+"]" })
+  var c_vars = indices.map(function(i) { return "c"+i+"=this.stride["+i+"]" })
+  code.push("proto.lo=function "+className+"_lo("+args.join(",")+"){var b=this.offset,d=0,"+a_vars.join(",")+","+c_vars.join(","))
+  for(var i=0; i<dimension; ++i) {
+    code.push(
+"if(typeof i"+i+"==='number'&&i"+i+">=0){\
+d=i"+i+"|0;\
+b+=c"+i+"*d;\
+a"+i+"-=d}")
+  }
+  code.push("return new "+className+"(this.data,"+
+    indices.map(function(i) {
+      return "a"+i
+    }).join(",")+","+
+    indices.map(function(i) {
+      return "c"+i
+    }).join(",")+",b)}")
+
+  //view.step():
+  code.push("proto.step=function "+className+"_step("+args.join(",")+"){var "+
+    indices.map(function(i) {
+      return "a"+i+"=this.shape["+i+"]"
+    }).join(",")+","+
+    indices.map(function(i) {
+      return "b"+i+"=this.stride["+i+"]"
+    }).join(",")+",c=this.offset,d=0,ceil=Math.ceil")
+  for(var i=0; i<dimension; ++i) {
+    code.push(
+"if(typeof i"+i+"==='number'){\
+d=i"+i+"|0;\
+if(d<0){\
+c+=b"+i+"*(a"+i+"-1);\
+a"+i+"=ceil(-a"+i+"/d)\
+}else{\
+a"+i+"=ceil(a"+i+"/d)\
+}\
+b"+i+"*=d\
+}")
+  }
+  code.push("return new "+className+"(this.data,"+
+    indices.map(function(i) {
+      return "a" + i
+    }).join(",")+","+
+    indices.map(function(i) {
+      return "b" + i
+    }).join(",")+",c)}")
+
+  //view.transpose():
+  var tShape = new Array(dimension)
+  var tStride = new Array(dimension)
+  for(var i=0; i<dimension; ++i) {
+    tShape[i] = "a[i"+i+"]"
+    tStride[i] = "b[i"+i+"]"
+  }
+  code.push("proto.transpose=function "+className+"_transpose("+args+"){"+
+    args.map(function(n,idx) { return n + "=(" + n + "===undefined?" + idx + ":" + n + "|0)"}).join(";"),
+    "var a=this.shape,b=this.stride;return new "+className+"(this.data,"+tShape.join(",")+","+tStride.join(",")+",this.offset)}")
+
+  //view.pick():
+  code.push("proto.pick=function "+className+"_pick("+args+"){var a=[],b=[],c=this.offset")
+  for(var i=0; i<dimension; ++i) {
+    code.push("if(typeof i"+i+"==='number'&&i"+i+">=0){c=(c+this.stride["+i+"]*i"+i+")|0}else{a.push(this.shape["+i+"]);b.push(this.stride["+i+"])}")
+  }
+  code.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}")
+
+  //Add return statement
+  code.push("return function construct_"+className+"(data,shape,stride,offset){return new "+className+"(data,"+
+    indices.map(function(i) {
+      return "shape["+i+"]"
+    }).join(",")+","+
+    indices.map(function(i) {
+      return "stride["+i+"]"
+    }).join(",")+",offset)}")
+
+  //Compile procedure
+  var procedure = new Function("CTOR_LIST", "ORDER", code.join("\n"))
+  return procedure(CACHED_CONSTRUCTORS[dtype], order)
+}
+
+function arrayDType(data) {
+  if(isBuffer(data)) {
+    return "buffer"
+  }
+  if(hasTypedArrays) {
+    switch(Object.prototype.toString.call(data)) {
+      case "[object Float64Array]":
+        return "float64"
+      case "[object Float32Array]":
+        return "float32"
+      case "[object Int8Array]":
+        return "int8"
+      case "[object Int16Array]":
+        return "int16"
+      case "[object Int32Array]":
+        return "int32"
+      case "[object Uint8Array]":
+        return "uint8"
+      case "[object Uint16Array]":
+        return "uint16"
+      case "[object Uint32Array]":
+        return "uint32"
+      case "[object Uint8ClampedArray]":
+        return "uint8_clamped"
+    }
+  }
+  if(Array.isArray(data)) {
+    return "array"
+  }
+  return "generic"
+}
+
+var CACHED_CONSTRUCTORS = {
+  "float32":[],
+  "float64":[],
+  "int8":[],
+  "int16":[],
+  "int32":[],
+  "uint8":[],
+  "uint16":[],
+  "uint32":[],
+  "array":[],
+  "uint8_clamped":[],
+  "buffer":[],
+  "generic":[]
+}
+
+;(function() {
+  for(var id in CACHED_CONSTRUCTORS) {
+    CACHED_CONSTRUCTORS[id].push(compileConstructor(id, -1))
+  }
+});
+
+function wrappedNDArrayCtor(data, shape, stride, offset) {
+  if(data === undefined) {
+    var ctor = CACHED_CONSTRUCTORS.array[0]
+    return ctor([])
+  } else if(typeof data === "number") {
+    data = [data]
+  }
+  if(shape === undefined) {
+    shape = [ data.length ]
+  }
+  var d = shape.length
+  if(stride === undefined) {
+    stride = new Array(d)
+    for(var i=d-1, sz=1; i>=0; --i) {
+      stride[i] = sz
+      sz *= shape[i]
+    }
+  }
+  if(offset === undefined) {
+    offset = 0
+    for(var i=0; i<d; ++i) {
+      if(stride[i] < 0) {
+        offset -= (shape[i]-1)*stride[i]
+      }
+    }
+  }
+  var dtype = arrayDType(data)
+  var ctor_list = CACHED_CONSTRUCTORS[dtype]
+  while(ctor_list.length <= d+1) {
+    ctor_list.push(compileConstructor(dtype, ctor_list.length-1))
+  }
+  var ctor = ctor_list[d+1]
+  return ctor(data, shape, stride, offset)
+}
+
+module.exports = wrappedNDArrayCtor
+
+},{"iota-array":195,"is-buffer":209}],209:[function(require,module,exports){
+/**
+ * Determine if an object is Buffer
+ *
+ * Author:   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
+ * License:  MIT
+ *
+ * `npm install is-buffer`
+ */
+
+module.exports = function (obj) {
+  return !!(obj != null &&
+    (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor)
+      (obj.constructor &&
+      typeof obj.constructor.isBuffer === 'function' &&
+      obj.constructor.isBuffer(obj))
+    ))
+}
+
+},{}],210:[function(require,module,exports){
+(function (global){
+module.exports =
+  global.performance &&
+  global.performance.now ? function now() {
+    return performance.now()
+  } : Date.now || function now() {
+    return +new Date
+  }
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],211:[function(require,module,exports){
+"use strict"
+
+var determinant = require("robust-determinant")
+
+var NUM_EXPAND = 6
+
+function generateSolver(n) {
+  var funcName = "robustLinearSolve" + n + "d"
+  var code = ["function ", funcName, "(A,b){return ["]
+  for(var i=0; i<n; ++i) {
+    code.push("det([")
+    for(var j=0; j<n; ++j) {
+      if(j > 0) {
+        code.push(",")
+      }
+      code.push("[")
+      for(var k=0; k<n; ++k) {
+        if(k > 0) {
+          code.push(",")
+        }
+        if(k === i) {
+          code.push("+b[", j, "]")
+        } else {
+          code.push("+A[", j, "][", k, "]")
+        }
+      }
+      code.push("]")
+    }
+    code.push("]),")
+  }
+  code.push("det(A)]}return ", funcName)
+  var proc = new Function("det", code.join(""))
+  if(n < 6) {
+    return proc(determinant[n])
+  }
+  return proc(determinant)
+}
+
+function robustLinearSolve0d() {
+  return [ 0 ]
+}
+
+function robustLinearSolve1d(A, b) {
+  return [ [ b[0] ], [ A[0][0] ] ]
+}
+
+var CACHE = [
+  robustLinearSolve0d,
+  robustLinearSolve1d
+]
+
+function generateDispatch() {
+  while(CACHE.length < NUM_EXPAND) {
+    CACHE.push(generateSolver(CACHE.length))
+  }
+  var procArgs = []
+  var code = ["function dispatchLinearSolve(A,b){switch(A.length){"]
+  for(var i=0; i<NUM_EXPAND; ++i) {
+    procArgs.push("s" + i)
+    code.push("case ", i, ":return s", i, "(A,b);")
+  }
+  code.push("}var s=CACHE[A.length];if(!s)s=CACHE[A.length]=g(A.length);return s(A,b)}return dispatchLinearSolve")
+  procArgs.push("CACHE", "g", code.join(""))
+  var proc = Function.apply(undefined, procArgs)
+  module.exports = proc.apply(undefined, CACHE.concat([CACHE, generateSolver]))
+  for(var i=0; i<NUM_EXPAND; ++i) {
+    module.exports[i] = CACHE[i]
+  }
+}
+
+generateDispatch()
+},{"robust-determinant":213}],212:[function(require,module,exports){
+"use strict"
+
+module.exports = compressExpansion
+
+function compressExpansion(e) {
+  var m = e.length
+  var Q = e[e.length-1]
+  var bottom = m
+  for(var i=m-2; i>=0; --i) {
+    var a = Q
+    var b = e[i]
+    Q = a + b
+    var bv = Q - a
+    var q = b - bv
+    if(q) {
+      e[--bottom] = Q
+      Q = q
+    }
+  }
+  var top = 0
+  for(var i=bottom; i<m; ++i) {
+    var a = e[i]
+    var b = Q
+    Q = a + b
+    var bv = Q - a
+    var q = b - bv
+    if(q) {
+      e[top++] = q
+    }
+  }
+  e[top++] = Q
+  e.length = top
+  return e
+}
+},{}],213:[function(require,module,exports){
+"use strict"
+
+var twoProduct = require("two-product")
+var robustSum = require("robust-sum")
+var robustScale = require("robust-scale")
+var compress = require("robust-compress")
+
+var NUM_EXPANDED = 6
+
+function cofactor(m, c) {
+  var result = new Array(m.length-1)
+  for(var i=1; i<m.length; ++i) {
+    var r = result[i-1] = new Array(m.length-1)
+    for(var j=0,k=0; j<m.length; ++j) {
+      if(j === c) {
+        continue
+      }
+      r[k++] = m[i][j]
+    }
+  }
+  return result
+}
+
+function matrix(n) {
+  var result = new Array(n)
+  for(var i=0; i<n; ++i) {
+    result[i] = new Array(n)
+    for(var j=0; j<n; ++j) {
+      result[i][j] = ["m[", i, "][", j, "]"].join("")
+    }
+  }
+  return result
+}
+
+function sign(n) {
+  if(n & 1) {
+    return "-"
+  }
+  return ""
+}
+
+function generateSum(expr) {
+  if(expr.length === 1) {
+    return expr[0]
+  } else if(expr.length === 2) {
+    return ["sum(", expr[0], ",", expr[1], ")"].join("")
+  } else {
+    var m = expr.length>>1
+    return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("")
+  }
+}
+
+function determinant(m) {
+  if(m.length === 2) {
+    return ["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")
+  } else {
+    var expr = []
+    for(var i=0; i<m.length; ++i) {
+      expr.push(["scale(", determinant(cofactor(m, i)), ",", sign(i), m[0][i], ")"].join(""))
+    }
+    return generateSum(expr)
+  }
+}
+
+function compileDeterminant(n) {
+  var proc = new Function("sum", "scale", "prod", "compress", [
+    "function robustDeterminant",n, "(m){return compress(", 
+      determinant(matrix(n)),
+    ")};return robustDeterminant", n].join(""))
+  return proc(robustSum, robustScale, twoProduct, compress)
+}
+
+var CACHE = [
+  function robustDeterminant0() { return [0] },
+  function robustDeterminant1(m) { return [m[0][0]] }
+]
+
+function generateDispatch() {
+  while(CACHE.length < NUM_EXPANDED) {
+    CACHE.push(compileDeterminant(CACHE.length))
+  }
+  var procArgs = []
+  var code = ["function robustDeterminant(m){switch(m.length){"]
+  for(var i=0; i<NUM_EXPANDED; ++i) {
+    procArgs.push("det" + i)
+    code.push("case ", i, ":return det", i, "(m);")
+  }
+  code.push("}\
+var det=CACHE[m.length];\
+if(!det)\
+det=CACHE[m.length]=gen(m.length);\
+return det(m);\
+}\
+return robustDeterminant")
+  procArgs.push("CACHE", "gen", code.join(""))
+  var proc = Function.apply(undefined, procArgs)
+  module.exports = proc.apply(undefined, CACHE.concat([CACHE, compileDeterminant]))
+  for(var i=0; i<CACHE.length; ++i) {
+    module.exports[i] = CACHE[i]
+  }
+}
+
+generateDispatch()
+},{"robust-compress":212,"robust-scale":215,"robust-sum":217,"two-product":231}],214:[function(require,module,exports){
+"use strict"
+
+var twoProduct = require("two-product")
+var robustSum = require("robust-sum")
+var robustScale = require("robust-scale")
+var robustSubtract = require("robust-subtract")
+
+var NUM_EXPAND = 5
+
+var EPSILON     = 1.1102230246251565e-16
+var ERRBOUND3   = (3.0 + 16.0 * EPSILON) * EPSILON
+var ERRBOUND4   = (7.0 + 56.0 * EPSILON) * EPSILON
+
+function cofactor(m, c) {
+  var result = new Array(m.length-1)
+  for(var i=1; i<m.length; ++i) {
+    var r = result[i-1] = new Array(m.length-1)
+    for(var j=0,k=0; j<m.length; ++j) {
+      if(j === c) {
+        continue
+      }
+      r[k++] = m[i][j]
+    }
+  }
+  return result
+}
+
+function matrix(n) {
+  var result = new Array(n)
+  for(var i=0; i<n; ++i) {
+    result[i] = new Array(n)
+    for(var j=0; j<n; ++j) {
+      result[i][j] = ["m", j, "[", (n-i-1), "]"].join("")
+    }
+  }
+  return result
+}
+
+function sign(n) {
+  if(n & 1) {
+    return "-"
+  }
+  return ""
+}
+
+function generateSum(expr) {
+  if(expr.length === 1) {
+    return expr[0]
+  } else if(expr.length === 2) {
+    return ["sum(", expr[0], ",", expr[1], ")"].join("")
+  } else {
+    var m = expr.length>>1
+    return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("")
+  }
+}
+
+function determinant(m) {
+  if(m.length === 2) {
+    return [["sum(prod(", m[0][0], ",", m[1][1], "),prod(-", m[0][1], ",", m[1][0], "))"].join("")]
+  } else {
+    var expr = []
+    for(var i=0; i<m.length; ++i) {
+      expr.push(["scale(", generateSum(determinant(cofactor(m, i))), ",", sign(i), m[0][i], ")"].join(""))
+    }
+    return expr
+  }
+}
+
+function orientation(n) {
+  var pos = []
+  var neg = []
+  var m = matrix(n)
+  var args = []
+  for(var i=0; i<n; ++i) {
+    if((i&1)===0) {
+      pos.push.apply(pos, determinant(cofactor(m, i)))
+    } else {
+      neg.push.apply(neg, determinant(cofactor(m, i)))
+    }
+    args.push("m" + i)
+  }
+  var posExpr = generateSum(pos)
+  var negExpr = generateSum(neg)
+  var funcName = "orientation" + n + "Exact"
+  var code = ["function ", funcName, "(", args.join(), "){var p=", posExpr, ",n=", negExpr, ",d=sub(p,n);\
+return d[d.length-1];};return ", funcName].join("")
+  var proc = new Function("sum", "prod", "scale", "sub", code)
+  return proc(robustSum, twoProduct, robustScale, robustSubtract)
+}
+
+var orientation3Exact = orientation(3)
+var orientation4Exact = orientation(4)
+
+var CACHED = [
+  function orientation0() { return 0 },
+  function orientation1() { return 0 },
+  function orientation2(a, b) { 
+    return b[0] - a[0]
+  },
+  function orientation3(a, b, c) {
+    var l = (a[1] - c[1]) * (b[0] - c[0])
+    var r = (a[0] - c[0]) * (b[1] - c[1])
+    var det = l - r
+    var s
+    if(l > 0) {
+      if(r <= 0) {
+        return det
+      } else {
+        s = l + r
+      }
+    } else if(l < 0) {
+      if(r >= 0) {
+        return det
+      } else {
+        s = -(l + r)
+      }
+    } else {
+      return det
+    }
+    var tol = ERRBOUND3 * s
+    if(det >= tol || det <= -tol) {
+      return det
+    }
+    return orientation3Exact(a, b, c)
+  },
+  function orientation4(a,b,c,d) {
+    var adx = a[0] - d[0]
+    var bdx = b[0] - d[0]
+    var cdx = c[0] - d[0]
+    var ady = a[1] - d[1]
+    var bdy = b[1] - d[1]
+    var cdy = c[1] - d[1]
+    var adz = a[2] - d[2]
+    var bdz = b[2] - d[2]
+    var cdz = c[2] - d[2]
+    var bdxcdy = bdx * cdy
+    var cdxbdy = cdx * bdy
+    var cdxady = cdx * ady
+    var adxcdy = adx * cdy
+    var adxbdy = adx * bdy
+    var bdxady = bdx * ady
+    var det = adz * (bdxcdy - cdxbdy) 
+            + bdz * (cdxady - adxcdy)
+            + cdz * (adxbdy - bdxady)
+    var permanent = (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz)
+                  + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz)
+                  + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz)
+    var tol = ERRBOUND4 * permanent
+    if ((det > tol) || (-det > tol)) {
+      return det
+    }
+    return orientation4Exact(a,b,c,d)
+  }
+]
+
+function slowOrient(args) {
+  var proc = CACHED[args.length]
+  if(!proc) {
+    proc = CACHED[args.length] = orientation(args.length)
+  }
+  return proc.apply(undefined, args)
+}
+
+function generateOrientationProc() {
+  while(CACHED.length <= NUM_EXPAND) {
+    CACHED.push(orientation(CACHED.length))
+  }
+  var args = []
+  var procArgs = ["slow"]
+  for(var i=0; i<=NUM_EXPAND; ++i) {
+    args.push("a" + i)
+    procArgs.push("o" + i)
+  }
+  var code = [
+    "function getOrientation(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;"
+  ]
+  for(var i=2; i<=NUM_EXPAND; ++i) {
+    code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");")
+  }
+  code.push("}var s=new Array(arguments.length);for(var i=0;i<arguments.length;++i){s[i]=arguments[i]};return slow(s);}return getOrientation")
+  procArgs.push(code.join(""))
+
+  var proc = Function.apply(undefined, procArgs)
+  module.exports = proc.apply(undefined, [slowOrient].concat(CACHED))
+  for(var i=0; i<=NUM_EXPAND; ++i) {
+    module.exports[i] = CACHED[i]
+  }
+}
+
+generateOrientationProc()
+},{"robust-scale":215,"robust-subtract":216,"robust-sum":217,"two-product":231}],215:[function(require,module,exports){
+"use strict"
+
+var twoProduct = require("two-product")
+var twoSum = require("two-sum")
+
+module.exports = scaleLinearExpansion
+
+function scaleLinearExpansion(e, scale) {
+  var n = e.length
+  if(n === 1) {
+    var ts = twoProduct(e[0], scale)
+    if(ts[0]) {
+      return ts
+    }
+    return [ ts[1] ]
+  }
+  var g = new Array(2 * n)
+  var q = [0.1, 0.1]
+  var t = [0.1, 0.1]
+  var count = 0
+  twoProduct(e[0], scale, q)
+  if(q[0]) {
+    g[count++] = q[0]
+  }
+  for(var i=1; i<n; ++i) {
+    twoProduct(e[i], scale, t)
+    var pq = q[1]
+    twoSum(pq, t[0], q)
+    if(q[0]) {
+      g[count++] = q[0]
+    }
+    var a = t[1]
+    var b = q[1]
+    var x = a + b
+    var bv = x - a
+    var y = b - bv
+    q[1] = x
+    if(y) {
+      g[count++] = y
+    }
+  }
+  if(q[1]) {
+    g[count++] = q[1]
+  }
+  if(count === 0) {
+    g[count++] = 0.0
+  }
+  g.length = count
+  return g
+}
+},{"two-product":231,"two-sum":232}],216:[function(require,module,exports){
+"use strict"
+
+module.exports = robustSubtract
+
+//Easy case: Add two scalars
+function scalarScalar(a, b) {
+  var x = a + b
+  var bv = x - a
+  var av = x - bv
+  var br = b - bv
+  var ar = a - av
+  var y = ar + br
+  if(y) {
+    return [y, x]
+  }
+  return [x]
+}
+
+function robustSubtract(e, f) {
+  var ne = e.length|0
+  var nf = f.length|0
+  if(ne === 1 && nf === 1) {
+    return scalarScalar(e[0], -f[0])
+  }
+  var n = ne + nf
+  var g = new Array(n)
+  var count = 0
+  var eptr = 0
+  var fptr = 0
+  var abs = Math.abs
+  var ei = e[eptr]
+  var ea = abs(ei)
+  var fi = -f[fptr]
+  var fa = abs(fi)
+  var a, b
+  if(ea < fa) {
+    b = ei
+    eptr += 1
+    if(eptr < ne) {
+      ei = e[eptr]
+      ea = abs(ei)
+    }
+  } else {
+    b = fi
+    fptr += 1
+    if(fptr < nf) {
+      fi = -f[fptr]
+      fa = abs(fi)
+    }
+  }
+  if((eptr < ne && ea < fa) || (fptr >= nf)) {
+    a = ei
+    eptr += 1
+    if(eptr < ne) {
+      ei = e[eptr]
+      ea = abs(ei)
+    }
+  } else {
+    a = fi
+    fptr += 1
+    if(fptr < nf) {
+      fi = -f[fptr]
+      fa = abs(fi)
+    }
+  }
+  var x = a + b
+  var bv = x - a
+  var y = b - bv
+  var q0 = y
+  var q1 = x
+  var _x, _bv, _av, _br, _ar
+  while(eptr < ne && fptr < nf) {
+    if(ea < fa) {
+      a = ei
+      eptr += 1
+      if(eptr < ne) {
+        ei = e[eptr]
+        ea = abs(ei)
+      }
+    } else {
+      a = fi
+      fptr += 1
+      if(fptr < nf) {
+        fi = -f[fptr]
+        fa = abs(fi)
+      }
+    }
+    b = q0
+    x = a + b
+    bv = x - a
+    y = b - bv
+    if(y) {
+      g[count++] = y
+    }
+    _x = q1 + x
+    _bv = _x - q1
+    _av = _x - _bv
+    _br = x - _bv
+    _ar = q1 - _av
+    q0 = _ar + _br
+    q1 = _x
+  }
+  while(eptr < ne) {
+    a = ei
+    b = q0
+    x = a + b
+    bv = x - a
+    y = b - bv
+    if(y) {
+      g[count++] = y
+    }
+    _x = q1 + x
+    _bv = _x - q1
+    _av = _x - _bv
+    _br = x - _bv
+    _ar = q1 - _av
+    q0 = _ar + _br
+    q1 = _x
+    eptr += 1
+    if(eptr < ne) {
+      ei = e[eptr]
+    }
+  }
+  while(fptr < nf) {
+    a = fi
+    b = q0
+    x = a + b
+    bv = x - a
+    y = b - bv
+    if(y) {
+      g[count++] = y
+    } 
+    _x = q1 + x
+    _bv = _x - q1
+    _av = _x - _bv
+    _br = x - _bv
+    _ar = q1 - _av
+    q0 = _ar + _br
+    q1 = _x
+    fptr += 1
+    if(fptr < nf) {
+      fi = -f[fptr]
+    }
+  }
+  if(q0) {
+    g[count++] = q0
+  }
+  if(q1) {
+    g[count++] = q1
+  }
+  if(!count) {
+    g[count++] = 0.0  
+  }
+  g.length = count
+  return g
+}
+},{}],217:[function(require,module,exports){
+"use strict"
+
+module.exports = linearExpansionSum
+
+//Easy case: Add two scalars
+function scalarScalar(a, b) {
+  var x = a + b
+  var bv = x - a
+  var av = x - bv
+  var br = b - bv
+  var ar = a - av
+  var y = ar + br
+  if(y) {
+    return [y, x]
+  }
+  return [x]
+}
+
+function linearExpansionSum(e, f) {
+  var ne = e.length|0
+  var nf = f.length|0
+  if(ne === 1 && nf === 1) {
+    return scalarScalar(e[0], f[0])
+  }
+  var n = ne + nf
+  var g = new Array(n)
+  var count = 0
+  var eptr = 0
+  var fptr = 0
+  var abs = Math.abs
+  var ei = e[eptr]
+  var ea = abs(ei)
+  var fi = f[fptr]
+  var fa = abs(fi)
+  var a, b
+  if(ea < fa) {
+    b = ei
+    eptr += 1
+    if(eptr < ne) {
+      ei = e[eptr]
+      ea = abs(ei)
+    }
+  } else {
+    b = fi
+    fptr += 1
+    if(fptr < nf) {
+      fi = f[fptr]
+      fa = abs(fi)
+    }
+  }
+  if((eptr < ne && ea < fa) || (fptr >= nf)) {
+    a = ei
+    eptr += 1
+    if(eptr < ne) {
+      ei = e[eptr]
+      ea = abs(ei)
+    }
+  } else {
+    a = fi
+    fptr += 1
+    if(fptr < nf) {
+      fi = f[fptr]
+      fa = abs(fi)
+    }
+  }
+  var x = a + b
+  var bv = x - a
+  var y = b - bv
+  var q0 = y
+  var q1 = x
+  var _x, _bv, _av, _br, _ar
+  while(eptr < ne && fptr < nf) {
+    if(ea < fa) {
+      a = ei
+      eptr += 1
+      if(eptr < ne) {
+        ei = e[eptr]
+        ea = abs(ei)
+      }
+    } else {
+      a = fi
+      fptr += 1
+      if(fptr < nf) {
+        fi = f[fptr]
+        fa = abs(fi)
+      }
+    }
+    b = q0
+    x = a + b
+    bv = x - a
+    y = b - bv
+    if(y) {
+      g[count++] = y
+    }
+    _x = q1 + x
+    _bv = _x - q1
+    _av = _x - _bv
+    _br = x - _bv
+    _ar = q1 - _av
+    q0 = _ar + _br
+    q1 = _x
+  }
+  while(eptr < ne) {
+    a = ei
+    b = q0
+    x = a + b
+    bv = x - a
+    y = b - bv
+    if(y) {
+      g[count++] = y
+    }
+    _x = q1 + x
+    _bv = _x - q1
+    _av = _x - _bv
+    _br = x - _bv
+    _ar = q1 - _av
+    q0 = _ar + _br
+    q1 = _x
+    eptr += 1
+    if(eptr < ne) {
+      ei = e[eptr]
+    }
+  }
+  while(fptr < nf) {
+    a = fi
+    b = q0
+    x = a + b
+    bv = x - a
+    y = b - bv
+    if(y) {
+      g[count++] = y
+    } 
+    _x = q1 + x
+    _bv = _x - q1
+    _av = _x - _bv
+    _br = x - _bv
+    _ar = q1 - _av
+    q0 = _ar + _br
+    q1 = _x
+    fptr += 1
+    if(fptr < nf) {
+      fi = f[fptr]
+    }
+  }
+  if(q0) {
+    g[count++] = q0
+  }
+  if(q1) {
+    g[count++] = q1
+  }
+  if(!count) {
+    g[count++] = 0.0  
+  }
+  g.length = count
+  return g
+}
+},{}],218:[function(require,module,exports){
+'use strict'
+
+module.exports = toSuperScript
+
+var SUPERSCRIPTS = {
+  ' ': ' ',
+  '0': 'â°',
+  '1': 'Â¹',
+  '2': 'Â²',
+  '3': 'Â³',
+  '4': 'âŽ',
+  '5': 'âµ',
+  '6': 'â¶',
+  '7': 'â·',
+  '8': 'âž',
+  '9': 'â¹',
+  '+': 'âº',
+  '-': 'â»',
+  'a': 'áµ',
+  'b': 'áµ',
+  'c': 'á¶',
+  'd': 'áµ',
+  'e': 'áµ',
+  'f': 'á¶ ',
+  'g': 'áµ',
+  'h': 'Ê°',
+  'i': 'â±',
+  'j': 'Ê²',
+  'k': 'áµ',
+  'l': 'Ë¡',
+  'm': 'áµ',
+  'n': 'â¿',
+  'o': 'áµ',
+  'p': 'áµ',
+  'r': 'Ê³',
+  's': 'Ë¢',
+  't': 'áµ',
+  'u': 'áµ',
+  'v': 'áµ',
+  'w': 'Ê·',
+  'x': 'Ë£',
+  'y': 'Êž',
+  'z': 'á¶»'
+}
+
+function toSuperScript(x) {
+  return x.split('').map(function(c) {
+    if(c in SUPERSCRIPTS) {
+      return SUPERSCRIPTS[c]
+    }
+    return ''
+  }).join('')
+}
+
+},{}],219:[function(require,module,exports){
+"use strict"
+
+var pool = require("typedarray-pool")
+
+module.exports = createSurfaceExtractor
+
+//Helper macros
+function array(i) {
+  return "a" + i
+}
+function data(i) {
+  return "d" + i
+}
+function cube(i,bitmask) {
+  return "c" + i + "_" + bitmask
+}
+function shape(i) {
+  return "s" + i
+}
+function stride(i,j) {
+  return "t" + i + "_" + j
+}
+function offset(i) {
+  return "o" + i
+}
+function scalar(i) {
+  return "x" + i
+}
+function pointer(i) {
+  return "p" + i
+}
+function delta(i,bitmask) {
+  return "d" + i + "_" + bitmask
+}
+function index(i) {
+  return "i" + i
+}
+function step(i,j) {
+  return "u" + i + "_" + j
+}
+function pcube(bitmask) {
+  return "b" + bitmask
+}
+function qcube(bitmask) {
+  return "y" + bitmask
+}
+function pdelta(bitmask) {
+  return "e" + bitmask
+}
+function vert(i) {
+  return "v" + i
+}
+var VERTEX_IDS = "V"
+var PHASES = "P"
+var VERTEX_COUNT = "N"
+var POOL_SIZE = "Q"
+var POINTER = "X"
+var TEMPORARY = "T"
+
+function permBitmask(dimension, mask, order) {
+  var r = 0
+  for(var i=0; i<dimension; ++i) {
+    if(mask & (1<<i)) {
+      r |= (1<<order[i])
+    }
+  }
+  return r
+}
+
+//Generates the surface procedure
+function compileSurfaceProcedure(vertexFunc, faceFunc, phaseFunc, scalarArgs, order, typesig) {
+  var arrayArgs = typesig.length
+  var dimension = order.length
+
+  if(dimension < 2) {
+    throw new Error("ndarray-extract-contour: Dimension must be at least 2")
+  }
+
+  var funcName = "extractContour" + order.join("_")
+  var code = []
+  var vars = []
+  var args = []
+
+  //Assemble arguments
+  for(var i=0; i<arrayArgs; ++i) {
+    args.push(array(i))  
+  }
+  for(var i=0; i<scalarArgs; ++i) {
+    args.push(scalar(i))
+  }
+
+  //Shape
+  for(var i=0; i<dimension; ++i) {
+    vars.push(shape(i) + "=" + array(0) + ".shape[" + i + "]|0")
+  }
+  //Data, stride, offset pointers
+  for(var i=0; i<arrayArgs; ++i) {
+    vars.push(data(i) + "=" + array(i) + ".data",
+              offset(i) + "=" + array(i) + ".offset|0")
+    for(var j=0; j<dimension; ++j) {
+      vars.push(stride(i,j) + "=" + array(i) + ".stride[" + j + "]|0")
+    }
+  }
+  //Pointer, delta and cube variables
+  for(var i=0; i<arrayArgs; ++i) {
+    vars.push(pointer(i) + "=" + offset(i))
+    vars.push(cube(i,0))
+    for(var j=1; j<(1<<dimension); ++j) {
+      var ptrStr = []
+      for(var k=0; k<dimension; ++k) {
+        if(j & (1<<k)) {
+          ptrStr.push("-" + stride(i,k))
+        }
+      }
+      vars.push(delta(i,j) + "=(" + ptrStr.join("") + ")|0")
+      vars.push(cube(i,j) + "=0")
+    }
+  }
+  //Create step variables
+  for(var i=0; i<arrayArgs; ++i) {
+    for(var j=0; j<dimension; ++j) {
+      var stepVal = [ stride(i,order[j]) ]
+      if(j > 0) {
+        stepVal.push(stride(i, order[j-1]) + "*" + shape(order[j-1]) )
+      }
+      vars.push(step(i,order[j]) + "=(" + stepVal.join("-") + ")|0")
+    }
+  }
+  //Create index variables
+  for(var i=0; i<dimension; ++i) {
+    vars.push(index(i) + "=0")
+  }
+  //Vertex count
+  vars.push(VERTEX_COUNT + "=0")
+  //Compute pool size, initialize pool step
+  var sizeVariable = ["2"]
+  for(var i=dimension-2; i>=0; --i) {
+    sizeVariable.push(shape(order[i]))
+  }
+  //Previous phases and vertex_ids
+  vars.push(POOL_SIZE + "=(" + sizeVariable.join("*") + ")|0",
+            PHASES + "=mallocUint32(" + POOL_SIZE + ")",
+            VERTEX_IDS + "=mallocUint32(" + POOL_SIZE + ")",
+            POINTER + "=0")
+  //Create cube variables for phases
+  vars.push(pcube(0) + "=0")
+  for(var j=1; j<(1<<dimension); ++j) {
+    var cubeDelta = []
+    var cubeStep = [ ]
+    for(var k=0; k<dimension; ++k) {
+      if(j & (1<<k)) {
+        if(cubeStep.length === 0) {
+          cubeDelta.push("1")
+        } else {
+          cubeDelta.unshift(cubeStep.join("*"))
+        }
+      }
+      cubeStep.push(shape(order[k]))
+    }
+    var signFlag = ""
+    if(cubeDelta[0].indexOf(shape(order[dimension-2])) < 0) {
+      signFlag = "-"
+    }
+    var jperm = permBitmask(dimension, j, order)
+    vars.push(pdelta(jperm) + "=(-" + cubeDelta.join("-") + ")|0",
+              qcube(jperm) + "=(" + signFlag + cubeDelta.join("-") + ")|0",
+              pcube(jperm) + "=0")
+  }
+  vars.push(vert(0) + "=0", TEMPORARY + "=0")
+
+  function forLoopBegin(i, start) {
+    code.push("for(", index(order[i]), "=", start, ";",
+      index(order[i]), "<", shape(order[i]), ";",
+      "++", index(order[i]), "){")
+  }
+
+  function forLoopEnd(i) {
+    for(var j=0; j<arrayArgs; ++j) {
+      code.push(pointer(j), "+=", step(j,order[i]), ";")
+    }
+    code.push("}")
+  }
+
+  function fillEmptySlice(k) {
+    for(var i=k-1; i>=0; --i) {
+      forLoopBegin(i, 0) 
+    }
+    var phaseFuncArgs = []
+    for(var i=0; i<arrayArgs; ++i) {
+      if(typesig[i]) {
+        phaseFuncArgs.push(data(i) + ".get(" + pointer(i) + ")")
+      } else {
+        phaseFuncArgs.push(data(i) + "[" + pointer(i) + "]")
+      }
+    }
+    for(var i=0; i<scalarArgs; ++i) {
+      phaseFuncArgs.push(scalar(i))
+    }
+    code.push(PHASES, "[", POINTER, "++]=phase(", phaseFuncArgs.join(), ");")
+    for(var i=0; i<k; ++i) {
+      forLoopEnd(i)
+    }
+    for(var j=0; j<arrayArgs; ++j) {
+      code.push(pointer(j), "+=", step(j,order[k]), ";")
+    }
+  }
+
+  function processGridCell(mask) {
+    //Read in local data
+    for(var i=0; i<arrayArgs; ++i) {
+      if(typesig[i]) {
+        code.push(cube(i,0), "=", data(i), ".get(", pointer(i), ");")
+      } else {
+        code.push(cube(i,0), "=", data(i), "[", pointer(i), "];")
+      }
+    }
+
+    //Read in phase
+    var phaseFuncArgs = []
+    for(var i=0; i<arrayArgs; ++i) {
+      phaseFuncArgs.push(cube(i,0))
+    }
+    for(var i=0; i<scalarArgs; ++i) {
+      phaseFuncArgs.push(scalar(i))
+    }
+    
+    code.push(pcube(0), "=", PHASES, "[", POINTER, "]=phase(", phaseFuncArgs.join(), ");")
+    
+    //Read in other cube data
+    for(var j=1; j<(1<<dimension); ++j) {
+      code.push(pcube(j), "=", PHASES, "[", POINTER, "+", pdelta(j), "];")
+    }
+
+    //Check for boundary crossing
+    var vertexPredicate = []
+    for(var j=1; j<(1<<dimension); ++j) {
+      vertexPredicate.push("(" + pcube(0) + "!==" + pcube(j) + ")")
+    }
+    code.push("if(", vertexPredicate.join("||"), "){")
+
+    //Read in boundary data
+    var vertexArgs = []
+    for(var i=0; i<dimension; ++i) {
+      vertexArgs.push(index(i))
+    }
+    for(var i=0; i<arrayArgs; ++i) {
+      vertexArgs.push(cube(i,0))
+      for(var j=1; j<(1<<dimension); ++j) {
+        if(typesig[i]) {
+          code.push(cube(i,j), "=", data(i), ".get(", pointer(i), "+", delta(i,j), ");")
+        } else {
+          code.push(cube(i,j), "=", data(i), "[", pointer(i), "+", delta(i,j), "];")
+        }
+        vertexArgs.push(cube(i,j))
+      }
+    }
+    for(var i=0; i<(1<<dimension); ++i) {
+      vertexArgs.push(pcube(i))
+    }
+    for(var i=0; i<scalarArgs; ++i) {
+      vertexArgs.push(scalar(i))
+    }
+
+    //Generate vertex
+    code.push("vertex(", vertexArgs.join(), ");",
+      vert(0), "=", VERTEX_IDS, "[", POINTER, "]=", VERTEX_COUNT, "++;")
+
+    //Check for face crossings
+    var base = (1<<dimension)-1
+    var corner = pcube(base)
+    for(var j=0; j<dimension; ++j) {
+      if((mask & ~(1<<j))===0) {
+        //Check face
+        var subset = base^(1<<j)
+        var edge = pcube(subset)
+        var faceArgs = [ ]
+        for(var k=subset; k>0; k=(k-1)&subset) {
+          faceArgs.push(VERTEX_IDS + "[" + POINTER + "+" + pdelta(k) + "]")
+        }
+        faceArgs.push(vert(0))
+        for(var k=0; k<arrayArgs; ++k) {
+          if(j&1) {
+            faceArgs.push(cube(k,base), cube(k,subset))
+          } else {
+            faceArgs.push(cube(k,subset), cube(k,base))
+          }
+        }
+        if(j&1) {
+          faceArgs.push(corner, edge)
+        } else {
+          faceArgs.push(edge, corner)
+        }
+        for(var k=0; k<scalarArgs; ++k) {
+          faceArgs.push(scalar(k))
+        }
+        code.push("if(", corner, "!==", edge, "){",
+          "face(", faceArgs.join(), ")}")
+      }
+    }
+    
+    //Increment pointer, close off if statement
+    code.push("}",
+      POINTER, "+=1;")
+  }
+
+  function flip() {
+    for(var j=1; j<(1<<dimension); ++j) {
+      code.push(TEMPORARY, "=", pdelta(j), ";",
+                pdelta(j), "=", qcube(j), ";",
+                qcube(j), "=", TEMPORARY, ";")
+    }
+  }
+
+  function createLoop(i, mask) {
+    if(i < 0) {
+      processGridCell(mask)
+      return
+    }
+    fillEmptySlice(i)
+    code.push("if(", shape(order[i]), ">0){",
+      index(order[i]), "=1;")
+    createLoop(i-1, mask|(1<<order[i]))
+
+    for(var j=0; j<arrayArgs; ++j) {
+      code.push(pointer(j), "+=", step(j,order[i]), ";")
+    }
+    if(i === dimension-1) {
+      code.push(POINTER, "=0;")
+      flip()
+    }
+    forLoopBegin(i, 2)
+    createLoop(i-1, mask)
+    if(i === dimension-1) {
+      code.push("if(", index(order[dimension-1]), "&1){",
+        POINTER, "=0;}")
+      flip()
+    }
+    forLoopEnd(i)
+    code.push("}")
+  }
+
+  createLoop(dimension-1, 0)
+
+  //Release scratch memory
+  code.push("freeUint32(", VERTEX_IDS, ");freeUint32(", PHASES, ");")
+
+  //Compile and link procedure
+  var procedureCode = [
+    "'use strict';",
+    "function ", funcName, "(", args.join(), "){",
+      "var ", vars.join(), ";",
+      code.join(""),
+    "}",
+    "return ", funcName ].join("")
+
+  var proc = new Function(
+    "vertex", 
+    "face", 
+    "phase", 
+    "mallocUint32", 
+    "freeUint32",
+    procedureCode)
+  return proc(
+    vertexFunc, 
+    faceFunc, 
+    phaseFunc, 
+    pool.mallocUint32, 
+    pool.freeUint32)
+}
+
+function createSurfaceExtractor(args) {
+  function error(msg) {
+    throw new Error("ndarray-extract-contour: " + msg)
+  }
+  if(typeof args !== "object") {
+    error("Must specify arguments")
+  }
+  var order = args.order
+  if(!Array.isArray(order)) {
+    error("Must specify order")
+  }
+  var arrays = args.arrayArguments||1
+  if(arrays < 1) {
+    error("Must have at least one array argument")
+  }
+  var scalars = args.scalarArguments||0
+  if(scalars < 0) {
+    error("Scalar arg count must be > 0")
+  }
+  if(typeof args.vertex !== "function") {
+    error("Must specify vertex creation function")
+  }
+  if(typeof args.cell !== "function") {
+    error("Must specify cell creation function")
+  }
+  if(typeof args.phase !== "function") {
+    error("Must specify phase function")
+  }
+  var getters = args.getters || []
+  var typesig = new Array(arrays)
+  for(var i=0; i<arrays; ++i) {
+    if(getters.indexOf(i) >= 0) {
+      typesig[i] = true
+    } else {
+      typesig[i] = false
+    }
+  }
+  return compileSurfaceProcedure(
+    args.vertex,
+    args.cell,
+    args.phase,
+    scalars,
+    order,
+    typesig)
+}
+},{"typedarray-pool":233}],220:[function(require,module,exports){
+// transliterated from the python snippet here:
+// http://en.wikipedia.org/wiki/Lanczos_approximation
+
+var g = 7;
+var p = [
+    0.99999999999980993,
+    676.5203681218851,
+    -1259.1392167224028,
+    771.32342877765313,
+    -176.61502916214059,
+    12.507343278686905,
+    -0.13857109526572012,
+    9.9843695780195716e-6,
+    1.5056327351493116e-7
+];
+
+var g_ln = 607/128;
+var p_ln = [
+    0.99999999999999709182,
+    57.156235665862923517,
+    -59.597960355475491248,
+    14.136097974741747174,
+    -0.49191381609762019978,
+    0.33994649984811888699e-4,
+    0.46523628927048575665e-4,
+    -0.98374475304879564677e-4,
+    0.15808870322491248884e-3,
+    -0.21026444172410488319e-3,
+    0.21743961811521264320e-3,
+    -0.16431810653676389022e-3,
+    0.84418223983852743293e-4,
+    -0.26190838401581408670e-4,
+    0.36899182659531622704e-5
+];
+
+// Spouge approximation (suitable for large arguments)
+function lngamma(z) {
+
+    if(z < 0) return Number('0/0');
+    var x = p_ln[0];
+    for(var i = p_ln.length - 1; i > 0; --i) x += p_ln[i] / (z + i);
+    var t = z + g_ln + 0.5;
+    return .5*Math.log(2*Math.PI)+(z+.5)*Math.log(t)-t+Math.log(x)-Math.log(z);
+}
+
+module.exports = function gamma (z) {
+    if (z < 0.5) {
+        return Math.PI / (Math.sin(Math.PI * z) * gamma(1 - z));
+    }
+    else if(z > 100) return Math.exp(lngamma(z));
+    else {
+        z -= 1;
+        var x = p[0];
+        for (var i = 1; i < g + 2; i++) {
+            x += p[i] / (z + i);
+        }
+        var t = z + g + 0.5;
+
+        return Math.sqrt(2 * Math.PI)
+            * Math.pow(t, z + 0.5)
+            * Math.exp(-t)
+            * x
+        ;
+    }
+};
+
+module.exports.log = lngamma;
+
+},{}],221:[function(require,module,exports){
+"use strict"
+
+module.exports = permutationSign
+
+var BRUTE_FORCE_CUTOFF = 32
+
+var pool = require("typedarray-pool")
+
+function permutationSign(p) {
+  var n = p.length
+  if(n < BRUTE_FORCE_CUTOFF) {
+    //Use quadratic algorithm for small n
+    var sgn = 1
+    for(var i=0; i<n; ++i) {
+      for(var j=0; j<i; ++j) {
+        if(p[i] < p[j]) {
+          sgn = -sgn
+        } else if(p[i] === p[j]) {
+          return 0
+        }
+      }
+    }
+    return sgn
+  } else {
+    //Otherwise use linear time algorithm
+    var visited = pool.mallocUint8(n)
+    for(var i=0; i<n; ++i) {
+      visited[i] = 0
+    }
+    var sgn = 1
+    for(var i=0; i<n; ++i) {
+      if(!visited[i]) {
+        var count = 1
+        visited[i] = 1
+        for(var j=p[i]; j!==i; j=p[j]) {
+          if(visited[j]) {
+            pool.freeUint8(visited)
+            return 0
+          }
+          count += 1
+          visited[j] = 1
+        }
+        if(!(count & 1)) {
+          sgn = -sgn
+        }
+      }
+    }
+    pool.freeUint8(visited)
+    return sgn
+  }
+}
+},{"typedarray-pool":233}],222:[function(require,module,exports){
+"use strict"
+
+var pool = require("typedarray-pool")
+var inverse = require("invert-permutation")
+
+function rank(permutation) {
+  var n = permutation.length
+  switch(n) {
+    case 0:
+    case 1:
+      return 0
+    case 2:
+      return permutation[1]
+    default:
+      break
+  }
+  var p = pool.mallocUint32(n)
+  var pinv = pool.mallocUint32(n)
+  var r = 0, s, t, i
+  inverse(permutation, pinv)
+  for(i=0; i<n; ++i) {
+    p[i] = permutation[i]
+  }
+  for(i=n-1; i>0; --i) {
+    t = pinv[i]
+    s = p[i]
+    p[i] = p[t]
+    p[t] = s
+    pinv[i] = pinv[s]
+    pinv[s] = t
+    r = (r + s) * i
+  }
+  pool.freeUint32(pinv)
+  pool.freeUint32(p)
+  return r
+}
+
+function unrank(n, r, p) {
+  switch(n) {
+    case 0:
+      if(p) { return p }
+      return []
+    case 1:
+      if(p) {
+        p[0] = 0
+        return p
+      } else {
+        return [0]
+      }
+    case 2:
+      if(p) {
+        if(r) {
+          p[0] = 0
+          p[1] = 1
+        } else {
+          p[0] = 1
+          p[1] = 0
+        }
+        return p
+      } else {
+        return r ? [0,1] : [1,0]
+      }
+    default:
+      break
+  }
+  p = p || new Array(n)
+  var s, t, i, nf=1
+  p[0] = 0
+  for(i=1; i<n; ++i) {
+    p[i] = i
+    nf = (nf*i)|0
+  }
+  for(i=n-1; i>0; --i) {
+    s = (r / nf)|0
+    r = (r - s * nf)|0
+    nf = (nf / i)|0
+    t = p[i]|0
+    p[i] = p[s]|0
+    p[s] = t|0
+  }
+  return p
+}
+
+exports.rank = rank
+exports.unrank = unrank
+
+},{"invert-permutation":223,"typedarray-pool":233}],223:[function(require,module,exports){
+"use strict"
+
+function invertPermutation(pi, result) {
+  result = result || new Array(pi.length)
+  for(var i=0; i<pi.length; ++i) {
+    result[pi[i]] = i
+  }
+  return result
+}
+
+module.exports = invertPermutation
+},{}],224:[function(require,module,exports){
+"use strict"
+
+module.exports = triangulateCube
+
+var perm = require("permutation-rank")
+var sgn = require("permutation-parity")
+var gamma = require("gamma")
+
+function triangulateCube(dimension) {
+  if(dimension < 0) {
+    return [ ]
+  }
+  if(dimension === 0) {
+    return [ [0] ]
+  }
+  var dfactorial = Math.round(gamma(dimension+1))|0
+  var result = []
+  for(var i=0; i<dfactorial; ++i) {
+    var p = perm.unrank(dimension, i)
+    var cell = [ 0 ]
+    var v = 0
+    for(var j=0; j<p.length; ++j) {
+      v += (1<<p[j])
+      cell.push(v)
+    }
+    if(sgn(p) < 1) {
+      cell[0] = v
+      cell[dimension] = 0
+    }
+    result.push(cell)
+  }
+  return result
+}
+},{"gamma":220,"permutation-parity":221,"permutation-rank":222}],225:[function(require,module,exports){
+module.exports = require('cwise-compiler')({
+    args: ['array', {
+        offset: [1],
+        array: 0
+    }, 'scalar', 'scalar', 'index'],
+    pre: {
+        "body": "{}",
+        "args": [],
+        "thisVars": [],
+        "localVars": []
+    },
+    post: {
+        "body": "{}",
+        "args": [],
+        "thisVars": [],
+        "localVars": []
+    },
+    body: {
+        "body": "{\n        var _inline_1_da = _inline_1_arg0_ - _inline_1_arg3_\n        var _inline_1_db = _inline_1_arg1_ - _inline_1_arg3_\n        if((_inline_1_da >= 0) !== (_inline_1_db >= 0)) {\n          _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n        }\n      }",
+        "args": [{
+            "name": "_inline_1_arg0_",
+            "lvalue": false,
+            "rvalue": true,
+            "count": 1
+        }, {
+            "name": "_inline_1_arg1_",
+            "lvalue": false,
+            "rvalue": true,
+            "count": 1
+        }, {
+            "name": "_inline_1_arg2_",
+            "lvalue": false,
+            "rvalue": true,
+            "count": 1
+        }, {
+            "name": "_inline_1_arg3_",
+            "lvalue": false,
+            "rvalue": true,
+            "count": 2
+        }, {
+            "name": "_inline_1_arg4_",
+            "lvalue": false,
+            "rvalue": true,
+            "count": 1
+        }],
+        "thisVars": [],
+        "localVars": ["_inline_1_da", "_inline_1_db"]
+    },
+    funcName: 'zeroCrossings'
+})
+
+},{"cwise-compiler":66}],226:[function(require,module,exports){
+"use strict"
+
+module.exports = findZeroCrossings
+
+var core = require("./lib/zc-core")
+
+function findZeroCrossings(array, level) {
+  var cross = []
+  level = +level || 0.0
+  core(array.hi(array.shape[0]-1), cross, level)
+  return cross
+}
+},{"./lib/zc-core":225}],227:[function(require,module,exports){
+"use strict"
+
+module.exports = surfaceNets
+
+var generateContourExtractor = require("ndarray-extract-contour")
+var triangulateCube = require("triangulate-hypercube")
+var zeroCrossings = require("zero-crossings")
+
+function buildSurfaceNets(order, dtype) {
+  var dimension = order.length
+  var code = ["'use strict';"]
+  var funcName = "surfaceNets" + order.join("_") + "d" + dtype
+
+  //Contour extraction function
+  code.push(
+    "var contour=genContour({",
+      "order:[", order.join(), "],",
+      "scalarArguments: 3,",
+      "phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },")
+  if(dtype === "generic") {
+    code.push("getters:[0],")
+  }
+
+  //Generate vertex function
+  var cubeArgs = []
+  var extraArgs = []
+  for(var i=0; i<dimension; ++i) {
+    cubeArgs.push("d" + i)
+    extraArgs.push("d" + i)
+  }
+  for(var i=0; i<(1<<dimension); ++i) {
+    cubeArgs.push("v" + i)
+    extraArgs.push("v" + i)
+  }
+  for(var i=0; i<(1<<dimension); ++i) {
+    cubeArgs.push("p" + i)
+    extraArgs.push("p" + i)
+  }
+  cubeArgs.push("a", "b", "c")
+  extraArgs.push("a", "c")
+  code.push("vertex:function vertexFunc(", cubeArgs.join(), "){")
+  //Mask args together
+  var maskStr = []
+  for(var i=0; i<(1<<dimension); ++i) {
+    maskStr.push("(p" + i + "<<" + i + ")")
+  }
+  //Generate variables and giganto switch statement
+  code.push("var m=(", maskStr.join("+"), ")|0;if(m===0||m===", (1<<(1<<dimension))-1, "){return}")
+  var extraFuncs = []
+  var currentFunc = []
+  if(1<<(1<<dimension) <= 128) {
+    code.push("switch(m){")
+    currentFunc = code
+  } else {
+    code.push("switch(m>>>7){")
+  }
+  for(var i=0; i<1<<(1<<dimension); ++i) {
+    if(1<<(1<<dimension) > 128) {
+      if((i%128)===0) {
+        if(extraFuncs.length > 0) {
+          currentFunc.push("}}")
+        }
+        var efName = "vExtra" + extraFuncs.length
+        code.push("case ", (i>>>7), ":", efName, "(m&0x7f,", extraArgs.join(), ");break;")
+        currentFunc = [
+          "function ", efName, "(m,", extraArgs.join(), "){switch(m){"
+        ]
+        extraFuncs.push(currentFunc)
+      }  
+    }
+    currentFunc.push("case ", (i&0x7f), ":")
+    var crossings = new Array(dimension)
+    var denoms = new Array(dimension)
+    var crossingCount = new Array(dimension)
+    var bias = new Array(dimension)
+    var totalCrossings = 0
+    for(var j=0; j<dimension; ++j) {
+      crossings[j] = []
+      denoms[j] = []
+      crossingCount[j] = 0
+      bias[j] = 0
+    }
+    for(var j=0; j<(1<<dimension); ++j) {
+      for(var k=0; k<dimension; ++k) {
+        var u = j ^ (1<<k)
+        if(u > j) {
+          continue
+        }
+        if(!(i&(1<<u)) !== !(i&(1<<j))) {
+          var sign = 1
+          if(i&(1<<u)) {
+            denoms[k].push("v" + u + "-v" + j)
+          } else {
+            denoms[k].push("v" + j + "-v" + u)
+            sign = -sign
+          }
+          if(sign < 0) {
+            crossings[k].push("-v" + j + "-v" + u)
+            crossingCount[k] += 2
+          } else {
+            crossings[k].push("v" + j + "+v" + u)
+            crossingCount[k] -= 2            
+          }
+          totalCrossings += 1
+          for(var l=0; l<dimension; ++l) {
+            if(l === k) {
+              continue
+            }
+            if(u&(1<<l)) {
+              bias[l] += 1
+            } else {
+              bias[l] -= 1
+            }
+          }
+        }
+      }
+    }
+    var vertexStr = []
+    for(var k=0; k<dimension; ++k) {
+      if(crossings[k].length === 0) {
+        vertexStr.push("d" + k + "-0.5")
+      } else {
+        var cStr = ""
+        if(crossingCount[k] < 0) {
+          cStr = crossingCount[k] + "*c"
+        } else if(crossingCount[k] > 0) {
+          cStr = "+" + crossingCount[k] + "*c"
+        }
+        var weight = 0.5 * (crossings[k].length / totalCrossings)
+        var shift = 0.5 + 0.5 * (bias[k] / totalCrossings)
+        vertexStr.push("d" + k + "-" + shift + "-" + weight + "*(" + crossings[k].join("+") + cStr + ")/(" + denoms[k].join("+") + ")")
+        
+      }
+    }
+    currentFunc.push("a.push([", vertexStr.join(), "]);",
+      "break;")
+  }
+  code.push("}},")
+  if(extraFuncs.length > 0) {
+    currentFunc.push("}}")
+  }
+
+  //Create face function
+  var faceArgs = []
+  for(var i=0; i<(1<<(dimension-1)); ++i) {
+    faceArgs.push("v" + i)
+  }
+  faceArgs.push("c0", "c1", "p0", "p1", "a", "b", "c")
+  code.push("cell:function cellFunc(", faceArgs.join(), "){")
+
+  var facets = triangulateCube(dimension-1)
+  code.push("if(p0){b.push(",
+    facets.map(function(f) {
+      return "[" + f.map(function(v) {
+        return "v" + v
+      }) + "]"
+    }).join(), ")}else{b.push(",
+    facets.map(function(f) {
+      var e = f.slice()
+      e.reverse()
+      return "[" + e.map(function(v) {
+        return "v" + v
+      }) + "]"
+    }).join(),
+    ")}}});function ", funcName, "(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ", funcName, ";")
+
+  for(var i=0; i<extraFuncs.length; ++i) {
+    code.push(extraFuncs[i].join(""))
+  }
+
+  //Compile and link
+  var proc = new Function("genContour", code.join(""))
+  return proc(generateContourExtractor)
+}
+
+//1D case: Need to handle specially
+function mesh1D(array, level) {
+  var zc = zeroCrossings(array, level)
+  var n = zc.length
+  var npos = new Array(n)
+  var ncel = new Array(n)
+  for(var i=0; i<n; ++i) {
+    npos[i] = [ zc[i] ]
+    ncel[i] = [ i ]
+  }
+  return {
+    positions: npos,
+    cells: ncel
+  }
+}
+
+var CACHE = {}
+
+function surfaceNets(array,level) {
+  if(array.dimension <= 0) {
+    return { positions: [], cells: [] }
+  } else if(array.dimension === 1) {
+    return mesh1D(array, level)
+  }
+  var typesig = array.order.join() + "-" + array.dtype
+  var proc = CACHE[typesig]
+  var level = (+level) || 0.0
+  if(!proc) {
+    proc = CACHE[typesig] = buildSurfaceNets(array.order, array.dtype)
+  }
+  return proc(array,level)
+}
+},{"ndarray-extract-contour":219,"triangulate-hypercube":224,"zero-crossings":226}],228:[function(require,module,exports){
+(function (process){
+'use strict'
+
+module.exports = textGet
+
+var vectorizeText = require('vectorize-text')
+
+var globals = window || process.global || {}
+var __TEXT_CACHE  = globals.__TEXT_CACHE || {}
+globals.__TEXT_CACHE = {}
+
+function unwrap(mesh) {
+  var cells     = mesh.cells
+  var positions = mesh.positions
+  var data      = new Float32Array(cells.length * 6)
+  var ptr       = 0
+  var shapeX    = 0
+  for(var i=0; i<cells.length; ++i) {
+    var tri = cells[i]
+    for(var j=0; j<3; ++j) {
+      var point = positions[tri[j]]
+      data[ptr++] = point[0]
+      data[ptr++] = point[1] + 1.4
+      shapeX      = Math.max(point[0], shapeX)
+    }
+  }
+  return {
+    data:  data,
+    shape: shapeX
+  }
+}
+
+function textGet(font, text) {
+  var fontcache = __TEXT_CACHE[font]
+   if(!fontcache) {
+     fontcache = __TEXT_CACHE[font] = {
+       ' ': {
+         data:   new Float32Array(0),
+         shape: 0.2
+       }
+     }
+   }
+   var mesh = fontcache[text]
+   if(!mesh) {
+     if(text.length <= 1 || !/\d/.test(text)) {
+       mesh = fontcache[text] = unwrap(vectorizeText(text, {
+         triangles:     true,
+         font:          font,
+         textAlign:     'left',
+         textBaseline:  'alphabetic'
+       }))
+     } else {
+       var parts = text.split(/(\d|\s)/)
+       var buffer = new Array(parts.length)
+       var bufferSize = 0
+       var shapeX = 0
+       for(var i=0; i<parts.length; ++i) {
+         buffer[i] = textGet(font, parts[i])
+         bufferSize += buffer[i].data.length
+         shapeX += buffer[i].shape
+         if(i>0) {
+           shapeX += 0.02
+         }
+       }
+
+       var data = new Float32Array(bufferSize)
+       var ptr     = 0
+       var xOffset = -0.5 * shapeX
+       for(var i=0; i<buffer.length; ++i) {
+         var bdata = buffer[i].data
+         for(var j=0; j<bdata.length; j+=2) {
+           data[ptr++] = bdata[j] + xOffset
+           data[ptr++] = bdata[j+1]
+         }
+         xOffset += buffer[i].shape + 0.02
+       }
+
+       mesh = fontcache[text] = {
+         data:  data,
+         shape: shapeX
+       }
+     }
+   }
+
+   return mesh
+}
+
+}).call(this,require('_process'))
+},{"_process":55,"vectorize-text":235}],229:[function(require,module,exports){
+// TinyColor v1.3.0
+// https://github.com/bgrins/TinyColor
+// Brian Grinstead, MIT License
+
+(function() {
+
+var trimLeft = /^\s+/,
+    trimRight = /\s+$/,
+    tinyCounter = 0,
+    math = Math,
+    mathRound = math.round,
+    mathMin = math.min,
+    mathMax = math.max,
+    mathRandom = math.random;
+
+function tinycolor (color, opts) {
+
+    color = (color) ? color : '';
+    opts = opts || { };
+
+    // If input is already a tinycolor, return itself
+    if (color instanceof tinycolor) {
+       return color;
+    }
+    // If we are called as a function, call using new instead
+    if (!(this instanceof tinycolor)) {
+        return new tinycolor(color, opts);
+    }
+
+    var rgb = inputToRGB(color);
+    this._originalInput = color,
+    this._r = rgb.r,
+    this._g = rgb.g,
+    this._b = rgb.b,
+    this._a = rgb.a,
+    this._roundA = mathRound(100*this._a) / 100,
+    this._format = opts.format || rgb.format;
+    this._gradientType = opts.gradientType;
+
+    // Don't let the range of [0,255] come back in [0,1].
+    // Potentially lose a little bit of precision here, but will fix issues where
+    // .5 gets interpreted as half of the total, instead of half of 1
+    // If it was supposed to be 128, this was already taken care of by `inputToRgb`
+    if (this._r < 1) { this._r = mathRound(this._r); }
+    if (this._g < 1) { this._g = mathRound(this._g); }
+    if (this._b < 1) { this._b = mathRound(this._b); }
+
+    this._ok = rgb.ok;
+    this._tc_id = tinyCounter++;
+}
+
+tinycolor.prototype = {
+    isDark: function() {
+        return this.getBrightness() < 128;
+    },
+    isLight: function() {
+        return !this.isDark();
+    },
+    isValid: function() {
+        return this._ok;
+    },
+    getOriginalInput: function() {
+      return this._originalInput;
+    },
+    getFormat: function() {
+        return this._format;
+    },
+    getAlpha: function() {
+        return this._a;
+    },
+    getBrightness: function() {
+        //http://www.w3.org/TR/AERT#color-contrast
+        var rgb = this.toRgb();
+        return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
+    },
+    getLuminance: function() {
+        //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
+        var rgb = this.toRgb();
+        var RsRGB, GsRGB, BsRGB, R, G, B;
+        RsRGB = rgb.r/255;
+        GsRGB = rgb.g/255;
+        BsRGB = rgb.b/255;
+
+        if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}
+        if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}
+        if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}
+        return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
+    },
+    setAlpha: function(value) {
+        this._a = boundAlpha(value);
+        this._roundA = mathRound(100*this._a) / 100;
+        return this;
+    },
+    toHsv: function() {
+        var hsv = rgbToHsv(this._r, this._g, this._b);
+        return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
+    },
+    toHsvString: function() {
+        var hsv = rgbToHsv(this._r, this._g, this._b);
+        var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
+        return (this._a == 1) ?
+          "hsv("  + h + ", " + s + "%, " + v + "%)" :
+          "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
+    },
+    toHsl: function() {
+        var hsl = rgbToHsl(this._r, this._g, this._b);
+        return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
+    },
+    toHslString: function() {
+        var hsl = rgbToHsl(this._r, this._g, this._b);
+        var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
+        return (this._a == 1) ?
+          "hsl("  + h + ", " + s + "%, " + l + "%)" :
+          "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
+    },
+    toHex: function(allow3Char) {
+        return rgbToHex(this._r, this._g, this._b, allow3Char);
+    },
+    toHexString: function(allow3Char) {
+        return '#' + this.toHex(allow3Char);
+    },
+    toHex8: function() {
+        return rgbaToHex(this._r, this._g, this._b, this._a);
+    },
+    toHex8String: function() {
+        return '#' + this.toHex8();
+    },
+    toRgb: function() {
+        return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
+    },
+    toRgbString: function() {
+        return (this._a == 1) ?
+          "rgb("  + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
+          "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
+    },
+    toPercentageRgb: function() {
+        return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
+    },
+    toPercentageRgbString: function() {
+        return (this._a == 1) ?
+          "rgb("  + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
+          "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
+    },
+    toName: function() {
+        if (this._a === 0) {
+            return "transparent";
+        }
+
+        if (this._a < 1) {
+            return false;
+        }
+
+        return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
+    },
+    toFilter: function(secondColor) {
+        var hex8String = '#' + rgbaToHex(this._r, this._g, this._b, this._a);
+        var secondHex8String = hex8String;
+        var gradientType = this._gradientType ? "GradientType = 1, " : "";
+
+        if (secondColor) {
+            var s = tinycolor(secondColor);
+            secondHex8String = s.toHex8String();
+        }
+
+        return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
+    },
+    toString: function(format) {
+        var formatSet = !!format;
+        format = format || this._format;
+
+        var formattedString = false;
+        var hasAlpha = this._a < 1 && this._a >= 0;
+        var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name");
+
+        if (needsAlphaFormat) {
+            // Special case for "transparent", all other non-alpha formats
+            // will return rgba when there is transparency.
+            if (format === "name" && this._a === 0) {
+                return this.toName();
+            }
+            return this.toRgbString();
+        }
+        if (format === "rgb") {
+            formattedString = this.toRgbString();
+        }
+        if (format === "prgb") {
+            formattedString = this.toPercentageRgbString();
+        }
+        if (format === "hex" || format === "hex6") {
+            formattedString = this.toHexString();
+        }
+        if (format === "hex3") {
+            formattedString = this.toHexString(true);
+        }
+        if (format === "hex8") {
+            formattedString = this.toHex8String();
+        }
+        if (format === "name") {
+            formattedString = this.toName();
+        }
+        if (format === "hsl") {
+            formattedString = this.toHslString();
+        }
+        if (format === "hsv") {
+            formattedString = this.toHsvString();
+        }
+
+        return formattedString || this.toHexString();
+    },
+    clone: function() {
+        return tinycolor(this.toString());
+    },
+
+    _applyModification: function(fn, args) {
+        var color = fn.apply(null, [this].concat([].slice.call(args)));
+        this._r = color._r;
+        this._g = color._g;
+        this._b = color._b;
+        this.setAlpha(color._a);
+        return this;
+    },
+    lighten: function() {
+        return this._applyModification(lighten, arguments);
+    },
+    brighten: function() {
+        return this._applyModification(brighten, arguments);
+    },
+    darken: function() {
+        return this._applyModification(darken, arguments);
+    },
+    desaturate: function() {
+        return this._applyModification(desaturate, arguments);
+    },
+    saturate: function() {
+        return this._applyModification(saturate, arguments);
+    },
+    greyscale: function() {
+        return this._applyModification(greyscale, arguments);
+    },
+    spin: function() {
+        return this._applyModification(spin, arguments);
+    },
+
+    _applyCombination: function(fn, args) {
+        return fn.apply(null, [this].concat([].slice.call(args)));
+    },
+    analogous: function() {
+        return this._applyCombination(analogous, arguments);
+    },
+    complement: function() {
+        return this._applyCombination(complement, arguments);
+    },
+    monochromatic: function() {
+        return this._applyCombination(monochromatic, arguments);
+    },
+    splitcomplement: function() {
+        return this._applyCombination(splitcomplement, arguments);
+    },
+    triad: function() {
+        return this._applyCombination(triad, arguments);
+    },
+    tetrad: function() {
+        return this._applyCombination(tetrad, arguments);
+    }
+};
+
+// If input is an object, force 1 into "1.0" to handle ratios properly
+// String input requires "1.0" as input, so 1 will be treated as 1
+tinycolor.fromRatio = function(color, opts) {
+    if (typeof color == "object") {
+        var newColor = {};
+        for (var i in color) {
+            if (color.hasOwnProperty(i)) {
+                if (i === "a") {
+                    newColor[i] = color[i];
+                }
+                else {
+                    newColor[i] = convertToPercentage(color[i]);
+                }
+            }
+        }
+        color = newColor;
+    }
+
+    return tinycolor(color, opts);
+};
+
+// Given a string or object, convert that input to RGB
+// Possible string inputs:
+//
+//     "red"
+//     "#f00" or "f00"
+//     "#ff0000" or "ff0000"
+//     "#ff000000" or "ff000000"
+//     "rgb 255 0 0" or "rgb (255, 0, 0)"
+//     "rgb 1.0 0 0" or "rgb (1, 0, 0)"
+//     "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
+//     "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
+//     "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
+//     "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
+//     "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
+//
+function inputToRGB(color) {
+
+    var rgb = { r: 0, g: 0, b: 0 };
+    var a = 1;
+    var ok = false;
+    var format = false;
+
+    if (typeof color == "string") {
+        color = stringInputToObject(color);
+    }
+
+    if (typeof color == "object") {
+        if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) {
+            rgb = rgbToRgb(color.r, color.g, color.b);
+            ok = true;
+            format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
+        }
+        else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) {
+            color.s = convertToPercentage(color.s);
+            color.v = convertToPercentage(color.v);
+            rgb = hsvToRgb(color.h, color.s, color.v);
+            ok = true;
+            format = "hsv";
+        }
+        else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) {
+            color.s = convertToPercentage(color.s);
+            color.l = convertToPercentage(color.l);
+            rgb = hslToRgb(color.h, color.s, color.l);
+            ok = true;
+            format = "hsl";
+        }
+
+        if (color.hasOwnProperty("a")) {
+            a = color.a;
+        }
+    }
+
+    a = boundAlpha(a);
+
+    return {
+        ok: ok,
+        format: color.format || format,
+        r: mathMin(255, mathMax(rgb.r, 0)),
+        g: mathMin(255, mathMax(rgb.g, 0)),
+        b: mathMin(255, mathMax(rgb.b, 0)),
+        a: a
+    };
+}
+
+
+// Conversion Functions
+// --------------------
+
+// `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
+// <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
+
+// `rgbToRgb`
+// Handle bounds / percentage checking to conform to CSS color spec
+// <http://www.w3.org/TR/css3-color/>
+// *Assumes:* r, g, b in [0, 255] or [0, 1]
+// *Returns:* { r, g, b } in [0, 255]
+function rgbToRgb(r, g, b){
+    return {
+        r: bound01(r, 255) * 255,
+        g: bound01(g, 255) * 255,
+        b: bound01(b, 255) * 255
+    };
+}
+
+// `rgbToHsl`
+// Converts an RGB color value to HSL.
+// *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
+// *Returns:* { h, s, l } in [0,1]
+function rgbToHsl(r, g, b) {
+
+    r = bound01(r, 255);
+    g = bound01(g, 255);
+    b = bound01(b, 255);
+
+    var max = mathMax(r, g, b), min = mathMin(r, g, b);
+    var h, s, l = (max + min) / 2;
+
+    if(max == min) {
+        h = s = 0; // achromatic
+    }
+    else {
+        var d = max - min;
+        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+        switch(max) {
+            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
+            case g: h = (b - r) / d + 2; break;
+            case b: h = (r - g) / d + 4; break;
+        }
+
+        h /= 6;
+    }
+
+    return { h: h, s: s, l: l };
+}
+
+// `hslToRgb`
+// Converts an HSL color value to RGB.
+// *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
+// *Returns:* { r, g, b } in the set [0, 255]
+function hslToRgb(h, s, l) {
+    var r, g, b;
+
+    h = bound01(h, 360);
+    s = bound01(s, 100);
+    l = bound01(l, 100);
+
+    function hue2rgb(p, q, t) {
+        if(t < 0) t += 1;
+        if(t > 1) t -= 1;
+        if(t < 1/6) return p + (q - p) * 6 * t;
+        if(t < 1/2) return q;
+        if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
+        return p;
+    }
+
+    if(s === 0) {
+        r = g = b = l; // achromatic
+    }
+    else {
+        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+        var p = 2 * l - q;
+        r = hue2rgb(p, q, h + 1/3);
+        g = hue2rgb(p, q, h);
+        b = hue2rgb(p, q, h - 1/3);
+    }
+
+    return { r: r * 255, g: g * 255, b: b * 255 };
+}
+
+// `rgbToHsv`
+// Converts an RGB color value to HSV
+// *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
+// *Returns:* { h, s, v } in [0,1]
+function rgbToHsv(r, g, b) {
+
+    r = bound01(r, 255);
+    g = bound01(g, 255);
+    b = bound01(b, 255);
+
+    var max = mathMax(r, g, b), min = mathMin(r, g, b);
+    var h, s, v = max;
+
+    var d = max - min;
+    s = max === 0 ? 0 : d / max;
+
+    if(max == min) {
+        h = 0; // achromatic
+    }
+    else {
+        switch(max) {
+            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
+            case g: h = (b - r) / d + 2; break;
+            case b: h = (r - g) / d + 4; break;
+        }
+        h /= 6;
+    }
+    return { h: h, s: s, v: v };
+}
+
+// `hsvToRgb`
+// Converts an HSV color value to RGB.
+// *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
+// *Returns:* { r, g, b } in the set [0, 255]
+ function hsvToRgb(h, s, v) {
+
+    h = bound01(h, 360) * 6;
+    s = bound01(s, 100);
+    v = bound01(v, 100);
+
+    var i = math.floor(h),
+        f = h - i,
+        p = v * (1 - s),
+        q = v * (1 - f * s),
+        t = v * (1 - (1 - f) * s),
+        mod = i % 6,
+        r = [v, q, p, p, t, v][mod],
+        g = [t, v, v, q, p, p][mod],
+        b = [p, p, t, v, v, q][mod];
+
+    return { r: r * 255, g: g * 255, b: b * 255 };
+}
+
+// `rgbToHex`
+// Converts an RGB color to hex
+// Assumes r, g, and b are contained in the set [0, 255]
+// Returns a 3 or 6 character hex
+function rgbToHex(r, g, b, allow3Char) {
+
+    var hex = [
+        pad2(mathRound(r).toString(16)),
+        pad2(mathRound(g).toString(16)),
+        pad2(mathRound(b).toString(16))
+    ];
+
+    // Return a 3 character hex if possible
+    if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
+        return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
+    }
+
+    return hex.join("");
+}
+
+// `rgbaToHex`
+// Converts an RGBA color plus alpha transparency to hex
+// Assumes r, g, b and a are contained in the set [0, 255]
+// Returns an 8 character hex
+function rgbaToHex(r, g, b, a) {
+
+    var hex = [
+        pad2(convertDecimalToHex(a)),
+        pad2(mathRound(r).toString(16)),
+        pad2(mathRound(g).toString(16)),
+        pad2(mathRound(b).toString(16))
+    ];
+
+    return hex.join("");
+}
+
+// `equals`
+// Can be called with any tinycolor input
+tinycolor.equals = function (color1, color2) {
+    if (!color1 || !color2) { return false; }
+    return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
+};
+
+tinycolor.random = function() {
+    return tinycolor.fromRatio({
+        r: mathRandom(),
+        g: mathRandom(),
+        b: mathRandom()
+    });
+};
+
+
+// Modification Functions
+// ----------------------
+// Thanks to less.js for some of the basics here
+// <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>
+
+function desaturate(color, amount) {
+    amount = (amount === 0) ? 0 : (amount || 10);
+    var hsl = tinycolor(color).toHsl();
+    hsl.s -= amount / 100;
+    hsl.s = clamp01(hsl.s);
+    return tinycolor(hsl);
+}
+
+function saturate(color, amount) {
+    amount = (amount === 0) ? 0 : (amount || 10);
+    var hsl = tinycolor(color).toHsl();
+    hsl.s += amount / 100;
+    hsl.s = clamp01(hsl.s);
+    return tinycolor(hsl);
+}
+
+function greyscale(color) {
+    return tinycolor(color).desaturate(100);
+}
+
+function lighten (color, amount) {
+    amount = (amount === 0) ? 0 : (amount || 10);
+    var hsl = tinycolor(color).toHsl();
+    hsl.l += amount / 100;
+    hsl.l = clamp01(hsl.l);
+    return tinycolor(hsl);
+}
+
+function brighten(color, amount) {
+    amount = (amount === 0) ? 0 : (amount || 10);
+    var rgb = tinycolor(color).toRgb();
+    rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
+    rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
+    rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
+    return tinycolor(rgb);
+}
+
+function darken (color, amount) {
+    amount = (amount === 0) ? 0 : (amount || 10);
+    var hsl = tinycolor(color).toHsl();
+    hsl.l -= amount / 100;
+    hsl.l = clamp01(hsl.l);
+    return tinycolor(hsl);
+}
+
+// Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
+// Values outside of this range will be wrapped into this range.
+function spin(color, amount) {
+    var hsl = tinycolor(color).toHsl();
+    var hue = (mathRound(hsl.h) + amount) % 360;
+    hsl.h = hue < 0 ? 360 + hue : hue;
+    return tinycolor(hsl);
+}
+
+// Combination Functions
+// ---------------------
+// Thanks to jQuery xColor for some of the ideas behind these
+// <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>
+
+function complement(color) {
+    var hsl = tinycolor(color).toHsl();
+    hsl.h = (hsl.h + 180) % 360;
+    return tinycolor(hsl);
+}
+
+function triad(color) {
+    var hsl = tinycolor(color).toHsl();
+    var h = hsl.h;
+    return [
+        tinycolor(color),
+        tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
+        tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
+    ];
+}
+
+function tetrad(color) {
+    var hsl = tinycolor(color).toHsl();
+    var h = hsl.h;
+    return [
+        tinycolor(color),
+        tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
+        tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
+        tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
+    ];
+}
+
+function splitcomplement(color) {
+    var hsl = tinycolor(color).toHsl();
+    var h = hsl.h;
+    return [
+        tinycolor(color),
+        tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
+        tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
+    ];
+}
+
+function analogous(color, results, slices) {
+    results = results || 6;
+    slices = slices || 30;
+
+    var hsl = tinycolor(color).toHsl();
+    var part = 360 / slices;
+    var ret = [tinycolor(color)];
+
+    for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
+        hsl.h = (hsl.h + part) % 360;
+        ret.push(tinycolor(hsl));
+    }
+    return ret;
+}
+
+function monochromatic(color, results) {
+    results = results || 6;
+    var hsv = tinycolor(color).toHsv();
+    var h = hsv.h, s = hsv.s, v = hsv.v;
+    var ret = [];
+    var modification = 1 / results;
+
+    while (results--) {
+        ret.push(tinycolor({ h: h, s: s, v: v}));
+        v = (v + modification) % 1;
+    }
+
+    return ret;
+}
+
+// Utility Functions
+// ---------------------
+
+tinycolor.mix = function(color1, color2, amount) {
+    amount = (amount === 0) ? 0 : (amount || 50);
+
+    var rgb1 = tinycolor(color1).toRgb();
+    var rgb2 = tinycolor(color2).toRgb();
+
+    var p = amount / 100;
+    var w = p * 2 - 1;
+    var a = rgb2.a - rgb1.a;
+
+    var w1;
+
+    if (w * a == -1) {
+        w1 = w;
+    } else {
+        w1 = (w + a) / (1 + w * a);
+    }
+
+    w1 = (w1 + 1) / 2;
+
+    var w2 = 1 - w1;
+
+    var rgba = {
+        r: rgb2.r * w1 + rgb1.r * w2,
+        g: rgb2.g * w1 + rgb1.g * w2,
+        b: rgb2.b * w1 + rgb1.b * w2,
+        a: rgb2.a * p  + rgb1.a * (1 - p)
+    };
+
+    return tinycolor(rgba);
+};
+
+
+// Readability Functions
+// ---------------------
+// <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)
+
+// `contrast`
+// Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
+tinycolor.readability = function(color1, color2) {
+    var c1 = tinycolor(color1);
+    var c2 = tinycolor(color2);
+    return (Math.max(c1.getLuminance(),c2.getLuminance())+0.05) / (Math.min(c1.getLuminance(),c2.getLuminance())+0.05);
+};
+
+// `isReadable`
+// Ensure that foreground and background color combinations meet WCAG2 guidelines.
+// The third argument is an optional Object.
+//      the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA';
+//      the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'.
+// If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}.
+
+// *Example*
+//    tinycolor.isReadable("#000", "#111") => false
+//    tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false
+tinycolor.isReadable = function(color1, color2, wcag2) {
+    var readability = tinycolor.readability(color1, color2);
+    var wcag2Parms, out;
+
+    out = false;
+
+    wcag2Parms = validateWCAG2Parms(wcag2);
+    switch (wcag2Parms.level + wcag2Parms.size) {
+        case "AAsmall":
+        case "AAAlarge":
+            out = readability >= 4.5;
+            break;
+        case "AAlarge":
+            out = readability >= 3;
+            break;
+        case "AAAsmall":
+            out = readability >= 7;
+            break;
+    }
+    return out;
+
+};
+
+// `mostReadable`
+// Given a base color and a list of possible foreground or background
+// colors for that base, returns the most readable color.
+// Optionally returns Black or White if the most readable color is unreadable.
+// *Example*
+//    tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255"
+//    tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString();  // "#ffffff"
+//    tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3"
+//    tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff"
+tinycolor.mostReadable = function(baseColor, colorList, args) {
+    var bestColor = null;
+    var bestScore = 0;
+    var readability;
+    var includeFallbackColors, level, size ;
+    args = args || {};
+    includeFallbackColors = args.includeFallbackColors ;
+    level = args.level;
+    size = args.size;
+
+    for (var i= 0; i < colorList.length ; i++) {
+        readability = tinycolor.readability(baseColor, colorList[i]);
+        if (readability > bestScore) {
+            bestScore = readability;
+            bestColor = tinycolor(colorList[i]);
+        }
+    }
+
+    if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) {
+        return bestColor;
+    }
+    else {
+        args.includeFallbackColors=false;
+        return tinycolor.mostReadable(baseColor,["#fff", "#000"],args);
+    }
+};
+
+
+// Big List of Colors
+// ------------------
+// <http://www.w3.org/TR/css3-color/#svg-color>
+var names = tinycolor.names = {
+    aliceblue: "f0f8ff",
+    antiquewhite: "faebd7",
+    aqua: "0ff",
+    aquamarine: "7fffd4",
+    azure: "f0ffff",
+    beige: "f5f5dc",
+    bisque: "ffe4c4",
+    black: "000",
+    blanchedalmond: "ffebcd",
+    blue: "00f",
+    blueviolet: "8a2be2",
+    brown: "a52a2a",
+    burlywood: "deb887",
+    burntsienna: "ea7e5d",
+    cadetblue: "5f9ea0",
+    chartreuse: "7fff00",
+    chocolate: "d2691e",
+    coral: "ff7f50",
+    cornflowerblue: "6495ed",
+    cornsilk: "fff8dc",
+    crimson: "dc143c",
+    cyan: "0ff",
+    darkblue: "00008b",
+    darkcyan: "008b8b",
+    darkgoldenrod: "b8860b",
+    darkgray: "a9a9a9",
+    darkgreen: "006400",
+    darkgrey: "a9a9a9",
+    darkkhaki: "bdb76b",
+    darkmagenta: "8b008b",
+    darkolivegreen: "556b2f",
+    darkorange: "ff8c00",
+    darkorchid: "9932cc",
+    darkred: "8b0000",
+    darksalmon: "e9967a",
+    darkseagreen: "8fbc8f",
+    darkslateblue: "483d8b",
+    darkslategray: "2f4f4f",
+    darkslategrey: "2f4f4f",
+    darkturquoise: "00ced1",
+    darkviolet: "9400d3",
+    deeppink: "ff1493",
+    deepskyblue: "00bfff",
+    dimgray: "696969",
+    dimgrey: "696969",
+    dodgerblue: "1e90ff",
+    firebrick: "b22222",
+    floralwhite: "fffaf0",
+    forestgreen: "228b22",
+    fuchsia: "f0f",
+    gainsboro: "dcdcdc",
+    ghostwhite: "f8f8ff",
+    gold: "ffd700",
+    goldenrod: "daa520",
+    gray: "808080",
+    green: "008000",
+    greenyellow: "adff2f",
+    grey: "808080",
+    honeydew: "f0fff0",
+    hotpink: "ff69b4",
+    indianred: "cd5c5c",
+    indigo: "4b0082",
+    ivory: "fffff0",
+    khaki: "f0e68c",
+    lavender: "e6e6fa",
+    lavenderblush: "fff0f5",
+    lawngreen: "7cfc00",
+    lemonchiffon: "fffacd",
+    lightblue: "add8e6",
+    lightcoral: "f08080",
+    lightcyan: "e0ffff",
+    lightgoldenrodyellow: "fafad2",
+    lightgray: "d3d3d3",
+    lightgreen: "90ee90",
+    lightgrey: "d3d3d3",
+    lightpink: "ffb6c1",
+    lightsalmon: "ffa07a",
+    lightseagreen: "20b2aa",
+    lightskyblue: "87cefa",
+    lightslategray: "789",
+    lightslategrey: "789",
+    lightsteelblue: "b0c4de",
+    lightyellow: "ffffe0",
+    lime: "0f0",
+    limegreen: "32cd32",
+    linen: "faf0e6",
+    magenta: "f0f",
+    maroon: "800000",
+    mediumaquamarine: "66cdaa",
+    mediumblue: "0000cd",
+    mediumorchid: "ba55d3",
+    mediumpurple: "9370db",
+    mediumseagreen: "3cb371",
+    mediumslateblue: "7b68ee",
+    mediumspringgreen: "00fa9a",
+    mediumturquoise: "48d1cc",
+    mediumvioletred: "c71585",
+    midnightblue: "191970",
+    mintcream: "f5fffa",
+    mistyrose: "ffe4e1",
+    moccasin: "ffe4b5",
+    navajowhite: "ffdead",
+    navy: "000080",
+    oldlace: "fdf5e6",
+    olive: "808000",
+    olivedrab: "6b8e23",
+    orange: "ffa500",
+    orangered: "ff4500",
+    orchid: "da70d6",
+    palegoldenrod: "eee8aa",
+    palegreen: "98fb98",
+    paleturquoise: "afeeee",
+    palevioletred: "db7093",
+    papayawhip: "ffefd5",
+    peachpuff: "ffdab9",
+    peru: "cd853f",
+    pink: "ffc0cb",
+    plum: "dda0dd",
+    powderblue: "b0e0e6",
+    purple: "800080",
+    rebeccapurple: "663399",
+    red: "f00",
+    rosybrown: "bc8f8f",
+    royalblue: "4169e1",
+    saddlebrown: "8b4513",
+    salmon: "fa8072",
+    sandybrown: "f4a460",
+    seagreen: "2e8b57",
+    seashell: "fff5ee",
+    sienna: "a0522d",
+    silver: "c0c0c0",
+    skyblue: "87ceeb",
+    slateblue: "6a5acd",
+    slategray: "708090",
+    slategrey: "708090",
+    snow: "fffafa",
+    springgreen: "00ff7f",
+    steelblue: "4682b4",
+    tan: "d2b48c",
+    teal: "008080",
+    thistle: "d8bfd8",
+    tomato: "ff6347",
+    turquoise: "40e0d0",
+    violet: "ee82ee",
+    wheat: "f5deb3",
+    white: "fff",
+    whitesmoke: "f5f5f5",
+    yellow: "ff0",
+    yellowgreen: "9acd32"
+};
+
+// Make it easy to access colors via `hexNames[hex]`
+var hexNames = tinycolor.hexNames = flip(names);
+
+
+// Utilities
+// ---------
+
+// `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
+function flip(o) {
+    var flipped = { };
+    for (var i in o) {
+        if (o.hasOwnProperty(i)) {
+            flipped[o[i]] = i;
+        }
+    }
+    return flipped;
+}
+
+// Return a valid alpha value [0,1] with all invalid values being set to 1
+function boundAlpha(a) {
+    a = parseFloat(a);
+
+    if (isNaN(a) || a < 0 || a > 1) {
+        a = 1;
+    }
+
+    return a;
+}
+
+// Take input from [0, n] and return it as [0, 1]
+function bound01(n, max) {
+    if (isOnePointZero(n)) { n = "100%"; }
+
+    var processPercent = isPercentage(n);
+    n = mathMin(max, mathMax(0, parseFloat(n)));
+
+    // Automatically convert percentage into number
+    if (processPercent) {
+        n = parseInt(n * max, 10) / 100;
+    }
+
+    // Handle floating point rounding errors
+    if ((math.abs(n - max) < 0.000001)) {
+        return 1;
+    }
+
+    // Convert into [0, 1] range if it isn't already
+    return (n % max) / parseFloat(max);
+}
+
+// Force a number between 0 and 1
+function clamp01(val) {
+    return mathMin(1, mathMax(0, val));
+}
+
+// Parse a base-16 hex value into a base-10 integer
+function parseIntFromHex(val) {
+    return parseInt(val, 16);
+}
+
+// Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
+// <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
+function isOnePointZero(n) {
+    return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
+}
+
+// Check to see if string passed in is a percentage
+function isPercentage(n) {
+    return typeof n === "string" && n.indexOf('%') != -1;
+}
+
+// Force a hex value to have 2 characters
+function pad2(c) {
+    return c.length == 1 ? '0' + c : '' + c;
+}
+
+// Replace a decimal with it's percentage value
+function convertToPercentage(n) {
+    if (n <= 1) {
+        n = (n * 100) + "%";
+    }
+
+    return n;
+}
+
+// Converts a decimal to a hex value
+function convertDecimalToHex(d) {
+    return Math.round(parseFloat(d) * 255).toString(16);
+}
+// Converts a hex value to a decimal
+function convertHexToDecimal(h) {
+    return (parseIntFromHex(h) / 255);
+}
+
+var matchers = (function() {
+
+    // <http://www.w3.org/TR/css3-values/#integers>
+    var CSS_INTEGER = "[-\\+]?\\d+%?";
+
+    // <http://www.w3.org/TR/css3-values/#number-value>
+    var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
+
+    // Allow positive/negative integer/number.  Don't capture the either/or, just the entire outcome.
+    var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
+
+    // Actual matching.
+    // Parentheses and commas are optional, but not required.
+    // Whitespace can take the place of commas or opening paren
+    var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
+    var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
+
+    return {
+        rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
+        rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
+        hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
+        hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
+        hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
+        hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
+        hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
+        hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
+        hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
+    };
+})();
+
+// `stringInputToObject`
+// Permissive string parsing.  Take in a number of formats, and output an object
+// based on detected format.  Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
+function stringInputToObject(color) {
+
+    color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
+    var named = false;
+    if (names[color]) {
+        color = names[color];
+        named = true;
+    }
+    else if (color == 'transparent') {
+        return { r: 0, g: 0, b: 0, a: 0, format: "name" };
+    }
+
+    // Try to match string input using regular expressions.
+    // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
+    // Just return an object and let the conversion functions handle that.
+    // This way the result will be the same whether the tinycolor is initialized with string or object.
+    var match;
+    if ((match = matchers.rgb.exec(color))) {
+        return { r: match[1], g: match[2], b: match[3] };
+    }
+    if ((match = matchers.rgba.exec(color))) {
+        return { r: match[1], g: match[2], b: match[3], a: match[4] };
+    }
+    if ((match = matchers.hsl.exec(color))) {
+        return { h: match[1], s: match[2], l: match[3] };
+    }
+    if ((match = matchers.hsla.exec(color))) {
+        return { h: match[1], s: match[2], l: match[3], a: match[4] };
+    }
+    if ((match = matchers.hsv.exec(color))) {
+        return { h: match[1], s: match[2], v: match[3] };
+    }
+    if ((match = matchers.hsva.exec(color))) {
+        return { h: match[1], s: match[2], v: match[3], a: match[4] };
+    }
+    if ((match = matchers.hex8.exec(color))) {
+        return {
+            a: convertHexToDecimal(match[1]),
+            r: parseIntFromHex(match[2]),
+            g: parseIntFromHex(match[3]),
+            b: parseIntFromHex(match[4]),
+            format: named ? "name" : "hex8"
+        };
+    }
+    if ((match = matchers.hex6.exec(color))) {
+        return {
+            r: parseIntFromHex(match[1]),
+            g: parseIntFromHex(match[2]),
+            b: parseIntFromHex(match[3]),
+            format: named ? "name" : "hex"
+        };
+    }
+    if ((match = matchers.hex3.exec(color))) {
+        return {
+            r: parseIntFromHex(match[1] + '' + match[1]),
+            g: parseIntFromHex(match[2] + '' + match[2]),
+            b: parseIntFromHex(match[3] + '' + match[3]),
+            format: named ? "name" : "hex"
+        };
+    }
+
+    return false;
+}
+
+function validateWCAG2Parms(parms) {
+    // return valid WCAG2 parms for isReadable.
+    // If input parms are invalid, return {"level":"AA", "size":"small"}
+    var level, size;
+    parms = parms || {"level":"AA", "size":"small"};
+    level = (parms.level || "AA").toUpperCase();
+    size = (parms.size || "small").toLowerCase();
+    if (level !== "AA" && level !== "AAA") {
+        level = "AA";
+    }
+    if (size !== "small" && size !== "large") {
+        size = "small";
+    }
+    return {"level":level, "size":size};
+}
+
+// Node: Export function
+if (typeof module !== "undefined" && module.exports) {
+    module.exports = tinycolor;
+}
+// AMD/requirejs: Define the module
+else if (typeof define === 'function' && define.amd) {
+    define(function () {return tinycolor;});
+}
+// Browser: Expose to window
+else {
+    window.tinycolor = tinycolor;
+}
+
+})();
+
+},{}],230:[function(require,module,exports){
+!function() {
+  var topojson = {
+    version: "1.6.20",
+    mesh: function(topology) { return object(topology, meshArcs.apply(this, arguments)); },
+    meshArcs: meshArcs,
+    merge: function(topology) { return object(topology, mergeArcs.apply(this, arguments)); },
+    mergeArcs: mergeArcs,
+    feature: featureOrCollection,
+    neighbors: neighbors,
+    presimplify: presimplify
+  };
+
+  function stitchArcs(topology, arcs) {
+    var stitchedArcs = {},
+        fragmentByStart = {},
+        fragmentByEnd = {},
+        fragments = [],
+        emptyIndex = -1;
+
+    // Stitch empty arcs first, since they may be subsumed by other arcs.
+    arcs.forEach(function(i, j) {
+      var arc = topology.arcs[i < 0 ? ~i : i], t;
+      if (arc.length < 3 && !arc[1][0] && !arc[1][1]) {
+        t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t;
+      }
+    });
+
+    arcs.forEach(function(i) {
+      var e = ends(i),
+          start = e[0],
+          end = e[1],
+          f, g;
+
+      if (f = fragmentByEnd[start]) {
+        delete fragmentByEnd[f.end];
+        f.push(i);
+        f.end = end;
+        if (g = fragmentByStart[end]) {
+          delete fragmentByStart[g.start];
+          var fg = g === f ? f : f.concat(g);
+          fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg;
+        } else {
+          fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
+        }
+      } else if (f = fragmentByStart[end]) {
+        delete fragmentByStart[f.start];
+        f.unshift(i);
+        f.start = start;
+        if (g = fragmentByEnd[start]) {
+          delete fragmentByEnd[g.end];
+          var gf = g === f ? f : g.concat(f);
+          fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf;
+        } else {
+          fragmentByStart[f.start] = fragmentByEnd[f.end] = f;
+        }
+      } else {
+        f = [i];
+        fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f;
+      }
+    });
+
+    function ends(i) {
+      var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1;
+      if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; });
+      else p1 = arc[arc.length - 1];
+      return i < 0 ? [p1, p0] : [p0, p1];
+    }
+
+    function flush(fragmentByEnd, fragmentByStart) {
+      for (var k in fragmentByEnd) {
+        var f = fragmentByEnd[k];
+        delete fragmentByStart[f.start];
+        delete f.start;
+        delete f.end;
+        f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; });
+        fragments.push(f);
+      }
+    }
+
+    flush(fragmentByEnd, fragmentByStart);
+    flush(fragmentByStart, fragmentByEnd);
+    arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); });
+
+    return fragments;
+  }
+
+  function meshArcs(topology, o, filter) {
+    var arcs = [];
+
+    if (arguments.length > 1) {
+      var geomsByArc = [],
+          geom;
+
+      function arc(i) {
+        var j = i < 0 ? ~i : i;
+        (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom});
+      }
+
+      function line(arcs) {
+        arcs.forEach(arc);
+      }
+
+      function polygon(arcs) {
+        arcs.forEach(line);
+      }
+
+      function geometry(o) {
+        if (o.type === "GeometryCollection") o.geometries.forEach(geometry);
+        else if (o.type in geometryType) geom = o, geometryType[o.type](o.arcs);
+      }
+
+      var geometryType = {
+        LineString: line,
+        MultiLineString: polygon,
+        Polygon: polygon,
+        MultiPolygon: function(arcs) { arcs.forEach(polygon); }
+      };
+
+      geometry(o);
+
+      geomsByArc.forEach(arguments.length < 3
+          ? function(geoms) { arcs.push(geoms[0].i); }
+          : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); });
+    } else {
+      for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push(i);
+    }
+
+    return {type: "MultiLineString", arcs: stitchArcs(topology, arcs)};
+  }
+
+  function mergeArcs(topology, objects) {
+    var polygonsByArc = {},
+        polygons = [],
+        components = [];
+
+    objects.forEach(function(o) {
+      if (o.type === "Polygon") register(o.arcs);
+      else if (o.type === "MultiPolygon") o.arcs.forEach(register);
+    });
+
+    function register(polygon) {
+      polygon.forEach(function(ring) {
+        ring.forEach(function(arc) {
+          (polygonsByArc[arc = arc < 0 ? ~arc : arc] || (polygonsByArc[arc] = [])).push(polygon);
+        });
+      });
+      polygons.push(polygon);
+    }
+
+    function exterior(ring) {
+      return cartesianRingArea(object(topology, {type: "Polygon", arcs: [ring]}).coordinates[0]) > 0; // TODO allow spherical?
+    }
+
+    polygons.forEach(function(polygon) {
+      if (!polygon._) {
+        var component = [],
+            neighbors = [polygon];
+        polygon._ = 1;
+        components.push(component);
+        while (polygon = neighbors.pop()) {
+          component.push(polygon);
+          polygon.forEach(function(ring) {
+            ring.forEach(function(arc) {
+              polygonsByArc[arc < 0 ? ~arc : arc].forEach(function(polygon) {
+                if (!polygon._) {
+                  polygon._ = 1;
+                  neighbors.push(polygon);
+                }
+              });
+            });
+          });
+        }
+      }
+    });
+
+    polygons.forEach(function(polygon) {
+      delete polygon._;
+    });
+
+    return {
+      type: "MultiPolygon",
+      arcs: components.map(function(polygons) {
+        var arcs = [], n;
+
+        // Extract the exterior (unique) arcs.
+        polygons.forEach(function(polygon) {
+          polygon.forEach(function(ring) {
+            ring.forEach(function(arc) {
+              if (polygonsByArc[arc < 0 ? ~arc : arc].length < 2) {
+                arcs.push(arc);
+              }
+            });
+          });
+        });
+
+        // Stitch the arcs into one or more rings.
+        arcs = stitchArcs(topology, arcs);
+
+        // If more than one ring is returned,
+        // at most one of these rings can be the exterior;
+        // this exterior ring has the same winding order
+        // as any exterior ring in the original polygons.
+        if ((n = arcs.length) > 1) {
+          var sgn = exterior(polygons[0][0]);
+          for (var i = 0, t; i < n; ++i) {
+            if (sgn === exterior(arcs[i])) {
+              t = arcs[0], arcs[0] = arcs[i], arcs[i] = t;
+              break;
+            }
+          }
+        }
+
+        return arcs;
+      })
+    };
+  }
+
+  function featureOrCollection(topology, o) {
+    return o.type === "GeometryCollection" ? {
+      type: "FeatureCollection",
+      features: o.geometries.map(function(o) { return feature(topology, o); })
+    } : feature(topology, o);
+  }
+
+  function feature(topology, o) {
+    var f = {
+      type: "Feature",
+      id: o.id,
+      properties: o.properties || {},
+      geometry: object(topology, o)
+    };
+    if (o.id == null) delete f.id;
+    return f;
+  }
+
+  function object(topology, o) {
+    var absolute = transformAbsolute(topology.transform),
+        arcs = topology.arcs;
+
+    function arc(i, points) {
+      if (points.length) points.pop();
+      for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, p; k < n; ++k) {
+        points.push(p = a[k].slice());
+        absolute(p, k);
+      }
+      if (i < 0) reverse(points, n);
+    }
+
+    function point(p) {
+      p = p.slice();
+      absolute(p, 0);
+      return p;
+    }
+
+    function line(arcs) {
+      var points = [];
+      for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points);
+      if (points.length < 2) points.push(points[0].slice());
+      return points;
+    }
+
+    function ring(arcs) {
+      var points = line(arcs);
+      while (points.length < 4) points.push(points[0].slice());
+      return points;
+    }
+
+    function polygon(arcs) {
+      return arcs.map(ring);
+    }
+
+    function geometry(o) {
+      var t = o.type;
+      return t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)}
+          : t in geometryType ? {type: t, coordinates: geometryType[t](o)}
+          : null;
+    }
+
+    var geometryType = {
+      Point: function(o) { return point(o.coordinates); },
+      MultiPoint: function(o) { return o.coordinates.map(point); },
+      LineString: function(o) { return line(o.arcs); },
+      MultiLineString: function(o) { return o.arcs.map(line); },
+      Polygon: function(o) { return polygon(o.arcs); },
+      MultiPolygon: function(o) { return o.arcs.map(polygon); }
+    };
+
+    return geometry(o);
+  }
+
+  function reverse(array, n) {
+    var t, j = array.length, i = j - n; while (i < --j) t = array[i], array[i++] = array[j], array[j] = t;
+  }
+
+  function bisect(a, x) {
+    var lo = 0, hi = a.length;
+    while (lo < hi) {
+      var mid = lo + hi >>> 1;
+      if (a[mid] < x) lo = mid + 1;
+      else hi = mid;
+    }
+    return lo;
+  }
+
+  function neighbors(objects) {
+    var indexesByArc = {}, // arc index -> array of object indexes
+        neighbors = objects.map(function() { return []; });
+
+    function line(arcs, i) {
+      arcs.forEach(function(a) {
+        if (a < 0) a = ~a;
+        var o = indexesByArc[a];
+        if (o) o.push(i);
+        else indexesByArc[a] = [i];
+      });
+    }
+
+    function polygon(arcs, i) {
+      arcs.forEach(function(arc) { line(arc, i); });
+    }
+
+    function geometry(o, i) {
+      if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); });
+      else if (o.type in geometryType) geometryType[o.type](o.arcs, i);
+    }
+
+    var geometryType = {
+      LineString: line,
+      MultiLineString: polygon,
+      Polygon: polygon,
+      MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); }
+    };
+
+    objects.forEach(geometry);
+
+    for (var i in indexesByArc) {
+      for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) {
+        for (var k = j + 1; k < m; ++k) {
+          var ij = indexes[j], ik = indexes[k], n;
+          if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik);
+          if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij);
+        }
+      }
+    }
+
+    return neighbors;
+  }
+
+  function presimplify(topology, triangleArea) {
+    var absolute = transformAbsolute(topology.transform),
+        relative = transformRelative(topology.transform),
+        heap = minAreaHeap();
+
+    if (!triangleArea) triangleArea = cartesianTriangleArea;
+
+    topology.arcs.forEach(function(arc) {
+      var triangles = [],
+          maxArea = 0,
+          triangle;
+
+      // To store each pointâs effective area, we create a new array rather than
+      // extending the passed-in point to workaround a Chrome/V8 bug (getting
+      // stuck in smi mode). For midpoints, the initial effective area of
+      // Infinity will be computed in the next step.
+      for (var i = 0, n = arc.length, p; i < n; ++i) {
+        p = arc[i];
+        absolute(arc[i] = [p[0], p[1], Infinity], i);
+      }
+
+      for (var i = 1, n = arc.length - 1; i < n; ++i) {
+        triangle = arc.slice(i - 1, i + 2);
+        triangle[1][2] = triangleArea(triangle);
+        triangles.push(triangle);
+        heap.push(triangle);
+      }
+
+      for (var i = 0, n = triangles.length; i < n; ++i) {
+        triangle = triangles[i];
+        triangle.previous = triangles[i - 1];
+        triangle.next = triangles[i + 1];
+      }
+
+      while (triangle = heap.pop()) {
+        var previous = triangle.previous,
+            next = triangle.next;
+
+        // If the area of the current point is less than that of the previous point
+        // to be eliminated, use the latter's area instead. This ensures that the
+        // current point cannot be eliminated without eliminating previously-
+        // eliminated points.
+        if (triangle[1][2] < maxArea) triangle[1][2] = maxArea;
+        else maxArea = triangle[1][2];
+
+        if (previous) {
+          previous.next = next;
+          previous[2] = triangle[2];
+          update(previous);
+        }
+
+        if (next) {
+          next.previous = previous;
+          next[0] = triangle[0];
+          update(next);
+        }
+      }
+
+      arc.forEach(relative);
+    });
+
+    function update(triangle) {
+      heap.remove(triangle);
+      triangle[1][2] = triangleArea(triangle);
+      heap.push(triangle);
+    }
+
+    return topology;
+  }
+
+  function cartesianRingArea(ring) {
+    var i = -1,
+        n = ring.length,
+        a,
+        b = ring[n - 1],
+        area = 0;
+
+    while (++i < n) {
+      a = b;
+      b = ring[i];
+      area += a[0] * b[1] - a[1] * b[0];
+    }
+
+    return area / 2;
+  }
+
+  function cartesianTriangleArea(triangle) {
+    var a = triangle[0], b = triangle[1], c = triangle[2];
+    return Math.abs((a[0] - c[0]) * (b[1] - a[1]) - (a[0] - b[0]) * (c[1] - a[1]));
+  }
+
+  function compareArea(a, b) {
+    return a[1][2] - b[1][2];
+  }
+
+  function minAreaHeap() {
+    var heap = {},
+        array = [],
+        size = 0;
+
+    heap.push = function(object) {
+      up(array[object._ = size] = object, size++);
+      return size;
+    };
+
+    heap.pop = function() {
+      if (size <= 0) return;
+      var removed = array[0], object;
+      if (--size > 0) object = array[size], down(array[object._ = 0] = object, 0);
+      return removed;
+    };
+
+    heap.remove = function(removed) {
+      var i = removed._, object;
+      if (array[i] !== removed) return; // invalid request
+      if (i !== --size) object = array[size], (compareArea(object, removed) < 0 ? up : down)(array[object._ = i] = object, i);
+      return i;
+    };
+
+    function up(object, i) {
+      while (i > 0) {
+        var j = ((i + 1) >> 1) - 1,
+            parent = array[j];
+        if (compareArea(object, parent) >= 0) break;
+        array[parent._ = i] = parent;
+        array[object._ = i = j] = object;
+      }
+    }
+
+    function down(object, i) {
+      while (true) {
+        var r = (i + 1) << 1,
+            l = r - 1,
+            j = i,
+            child = array[j];
+        if (l < size && compareArea(array[l], child) < 0) child = array[j = l];
+        if (r < size && compareArea(array[r], child) < 0) child = array[j = r];
+        if (j === i) break;
+        array[child._ = i] = child;
+        array[object._ = i = j] = object;
+      }
+    }
+
+    return heap;
+  }
+
+  function transformAbsolute(transform) {
+    if (!transform) return noop;
+    var x0,
+        y0,
+        kx = transform.scale[0],
+        ky = transform.scale[1],
+        dx = transform.translate[0],
+        dy = transform.translate[1];
+    return function(point, i) {
+      if (!i) x0 = y0 = 0;
+      point[0] = (x0 += point[0]) * kx + dx;
+      point[1] = (y0 += point[1]) * ky + dy;
+    };
+  }
+
+  function transformRelative(transform) {
+    if (!transform) return noop;
+    var x0,
+        y0,
+        kx = transform.scale[0],
+        ky = transform.scale[1],
+        dx = transform.translate[0],
+        dy = transform.translate[1];
+    return function(point, i) {
+      if (!i) x0 = y0 = 0;
+      var x1 = (point[0] - dx) / kx | 0,
+          y1 = (point[1] - dy) / ky | 0;
+      point[0] = x1 - x0;
+      point[1] = y1 - y0;
+      x0 = x1;
+      y0 = y1;
+    };
+  }
+
+  function noop() {}
+
+  if (typeof define === "function" && define.amd) define(topojson);
+  else if (typeof module === "object" && module.exports) module.exports = topojson;
+  else this.topojson = topojson;
+}();
+
+},{}],231:[function(require,module,exports){
+"use strict"
+
+module.exports = twoProduct
+
+var SPLITTER = +(Math.pow(2, 27) + 1.0)
+
+function twoProduct(a, b, result) {
+  var x = a * b
+
+  var c = SPLITTER * a
+  var abig = c - a
+  var ahi = c - abig
+  var alo = a - ahi
+
+  var d = SPLITTER * b
+  var bbig = d - b
+  var bhi = d - bbig
+  var blo = b - bhi
+
+  var err1 = x - (ahi * bhi)
+  var err2 = err1 - (alo * bhi)
+  var err3 = err2 - (ahi * blo)
+
+  var y = alo * blo - err3
+
+  if(result) {
+    result[0] = y
+    result[1] = x
+    return result
+  }
+
+  return [ y, x ]
+}
+},{}],232:[function(require,module,exports){
+"use strict"
+
+module.exports = fastTwoSum
+
+function fastTwoSum(a, b, result) {
+	var x = a + b
+	var bv = x - a
+	var av = x - bv
+	var br = b - bv
+	var ar = a - av
+	if(result) {
+		result[0] = ar + br
+		result[1] = x
+		return result
+	}
+	return [ar+br, x]
+}
+},{}],233:[function(require,module,exports){
+(function (global,Buffer){
+'use strict'
+
+var bits = require('bit-twiddle')
+var dup = require('dup')
+
+//Legacy pool support
+if(!global.__TYPEDARRAY_POOL) {
+  global.__TYPEDARRAY_POOL = {
+      UINT8   : dup([32, 0])
+    , UINT16  : dup([32, 0])
+    , UINT32  : dup([32, 0])
+    , INT8    : dup([32, 0])
+    , INT16   : dup([32, 0])
+    , INT32   : dup([32, 0])
+    , FLOAT   : dup([32, 0])
+    , DOUBLE  : dup([32, 0])
+    , DATA    : dup([32, 0])
+    , UINT8C  : dup([32, 0])
+    , BUFFER  : dup([32, 0])
+  }
+}
+
+var hasUint8C = (typeof Uint8ClampedArray) !== 'undefined'
+var POOL = global.__TYPEDARRAY_POOL
+
+//Upgrade pool
+if(!POOL.UINT8C) {
+  POOL.UINT8C = dup([32, 0])
+}
+if(!POOL.BUFFER) {
+  POOL.BUFFER = dup([32, 0])
+}
+
+//New technique: Only allocate from ArrayBufferView and Buffer
+var DATA    = POOL.DATA
+  , BUFFER  = POOL.BUFFER
+
+exports.free = function free(array) {
+  if(Buffer.isBuffer(array)) {
+    BUFFER[bits.log2(array.length)].push(array)
+  } else {
+    if(Object.prototype.toString.call(array) !== '[object ArrayBuffer]') {
+      array = array.buffer
+    }
+    if(!array) {
+      return
+    }
+    var n = array.length || array.byteLength
+    var log_n = bits.log2(n)|0
+    DATA[log_n].push(array)
+  }
+}
+
+function freeArrayBuffer(buffer) {
+  if(!buffer) {
+    return
+  }
+  var n = buffer.length || buffer.byteLength
+  var log_n = bits.log2(n)
+  DATA[log_n].push(buffer)
+}
+
+function freeTypedArray(array) {
+  freeArrayBuffer(array.buffer)
+}
+
+exports.freeUint8 =
+exports.freeUint16 =
+exports.freeUint32 =
+exports.freeInt8 =
+exports.freeInt16 =
+exports.freeInt32 =
+exports.freeFloat32 = 
+exports.freeFloat =
+exports.freeFloat64 = 
+exports.freeDouble = 
+exports.freeUint8Clamped = 
+exports.freeDataView = freeTypedArray
+
+exports.freeArrayBuffer = freeArrayBuffer
+
+exports.freeBuffer = function freeBuffer(array) {
+  BUFFER[bits.log2(array.length)].push(array)
+}
+
+exports.malloc = function malloc(n, dtype) {
+  if(dtype === undefined || dtype === 'arraybuffer') {
+    return mallocArrayBuffer(n)
+  } else {
+    switch(dtype) {
+      case 'uint8':
+        return mallocUint8(n)
+      case 'uint16':
+        return mallocUint16(n)
+      case 'uint32':
+        return mallocUint32(n)
+      case 'int8':
+        return mallocInt8(n)
+      case 'int16':
+        return mallocInt16(n)
+      case 'int32':
+        return mallocInt32(n)
+      case 'float':
+      case 'float32':
+        return mallocFloat(n)
+      case 'double':
+      case 'float64':
+        return mallocDouble(n)
+      case 'uint8_clamped':
+        return mallocUint8Clamped(n)
+      case 'buffer':
+        return mallocBuffer(n)
+      case 'data':
+      case 'dataview':
+        return mallocDataView(n)
+
+      default:
+        return null
+    }
+  }
+  return null
+}
+
+function mallocArrayBuffer(n) {
+  var n = bits.nextPow2(n)
+  var log_n = bits.log2(n)
+  var d = DATA[log_n]
+  if(d.length > 0) {
+    return d.pop()
+  }
+  return new ArrayBuffer(n)
+}
+exports.mallocArrayBuffer = mallocArrayBuffer
+
+function mallocUint8(n) {
+  return new Uint8Array(mallocArrayBuffer(n), 0, n)
+}
+exports.mallocUint8 = mallocUint8
+
+function mallocUint16(n) {
+  return new Uint16Array(mallocArrayBuffer(2*n), 0, n)
+}
+exports.mallocUint16 = mallocUint16
+
+function mallocUint32(n) {
+  return new Uint32Array(mallocArrayBuffer(4*n), 0, n)
+}
+exports.mallocUint32 = mallocUint32
+
+function mallocInt8(n) {
+  return new Int8Array(mallocArrayBuffer(n), 0, n)
+}
+exports.mallocInt8 = mallocInt8
+
+function mallocInt16(n) {
+  return new Int16Array(mallocArrayBuffer(2*n), 0, n)
+}
+exports.mallocInt16 = mallocInt16
+
+function mallocInt32(n) {
+  return new Int32Array(mallocArrayBuffer(4*n), 0, n)
+}
+exports.mallocInt32 = mallocInt32
+
+function mallocFloat(n) {
+  return new Float32Array(mallocArrayBuffer(4*n), 0, n)
+}
+exports.mallocFloat32 = exports.mallocFloat = mallocFloat
+
+function mallocDouble(n) {
+  return new Float64Array(mallocArrayBuffer(8*n), 0, n)
+}
+exports.mallocFloat64 = exports.mallocDouble = mallocDouble
+
+function mallocUint8Clamped(n) {
+  if(hasUint8C) {
+    return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n)
+  } else {
+    return mallocUint8(n)
+  }
+}
+exports.mallocUint8Clamped = mallocUint8Clamped
+
+function mallocDataView(n) {
+  return new DataView(mallocArrayBuffer(n), 0, n)
+}
+exports.mallocDataView = mallocDataView
+
+function mallocBuffer(n) {
+  n = bits.nextPow2(n)
+  var log_n = bits.log2(n)
+  var cache = BUFFER[log_n]
+  if(cache.length > 0) {
+    return cache.pop()
+  }
+  return new Buffer(n)
+}
+exports.mallocBuffer = mallocBuffer
+
+exports.clearCache = function clearCache() {
+  for(var i=0; i<32; ++i) {
+    POOL.UINT8[i].length = 0
+    POOL.UINT16[i].length = 0
+    POOL.UINT32[i].length = 0
+    POOL.INT8[i].length = 0
+    POOL.INT16[i].length = 0
+    POOL.INT32[i].length = 0
+    POOL.FLOAT[i].length = 0
+    POOL.DOUBLE[i].length = 0
+    POOL.UINT8C[i].length = 0
+    DATA[i].length = 0
+    BUFFER[i].length = 0
+  }
+}
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
+},{"bit-twiddle":49,"buffer":50,"dup":72}],234:[function(require,module,exports){
+"use strict"
+
+function unique_pred(list, compare) {
+  var ptr = 1
+    , len = list.length
+    , a=list[0], b=list[0]
+  for(var i=1; i<len; ++i) {
+    b = a
+    a = list[i]
+    if(compare(a, b)) {
+      if(i === ptr) {
+        ptr++
+        continue
+      }
+      list[ptr++] = a
+    }
+  }
+  list.length = ptr
+  return list
+}
+
+function unique_eq(list) {
+  var ptr = 1
+    , len = list.length
+    , a=list[0], b = list[0]
+  for(var i=1; i<len; ++i, b=a) {
+    b = a
+    a = list[i]
+    if(a !== b) {
+      if(i === ptr) {
+        ptr++
+        continue
+      }
+      list[ptr++] = a
+    }
+  }
+  list.length = ptr
+  return list
+}
+
+function unique(list, compare, sorted) {
+  if(list.length === 0) {
+    return list
+  }
+  if(compare) {
+    if(!sorted) {
+      list.sort(compare)
+    }
+    return unique_pred(list, compare)
+  }
+  if(!sorted) {
+    list.sort()
+  }
+  return unique_eq(list)
+}
+
+module.exports = unique
+
+},{}],235:[function(require,module,exports){
+"use strict"
+
+module.exports = createText
+
+var vectorizeText = require("./lib/vtext")
+var defaultCanvas = null
+var defaultContext = null
+
+if(typeof document !== 'undefined') {
+  defaultCanvas = document.createElement('canvas')
+  defaultCanvas.width = 8192
+  defaultCanvas.height = 1024
+  defaultContext = defaultCanvas.getContext("2d")
+}
+
+function createText(str, options) {
+  if((typeof options !== "object") || (options === null)) {
+    options = {}
+  }
+  return vectorizeText(
+    str,
+    options.canvas || defaultCanvas,
+    options.context || defaultContext,
+    options)
+}
+
+},{"./lib/vtext":236}],236:[function(require,module,exports){
+"use strict"
+
+module.exports = vectorizeText
+module.exports.processPixels = processPixels
+
+var surfaceNets = require('surface-nets')
+var ndarray = require('ndarray')
+var simplify = require('simplify-planar-graph')
+var cleanPSLG = require('clean-pslg')
+var cdt2d = require('cdt2d')
+var toPolygonCrappy = require('planar-graph-to-polyline')
+
+function transformPositions(positions, options, size) {
+  var align = options.textAlign || "start"
+  var baseline = options.textBaseline || "alphabetic"
+
+  var lo = [1<<30, 1<<30]
+  var hi = [0,0]
+  var n = positions.length
+  for(var i=0; i<n; ++i) {
+    var p = positions[i]
+    for(var j=0; j<2; ++j) {
+      lo[j] = Math.min(lo[j], p[j])|0
+      hi[j] = Math.max(hi[j], p[j])|0
+    }
+  }
+
+  var xShift = 0
+  switch(align) {
+    case "center":
+      xShift = -0.5 * (lo[0] + hi[0])
+    break
+
+    case "right":
+    case "end":
+      xShift = -hi[0]
+    break
+
+    case "left":
+    case "start":
+      xShift = -lo[0]
+    break
+
+    default:
+      throw new Error("vectorize-text: Unrecognized textAlign: '" + align + "'")
+  }
+
+  var yShift = 0
+  switch(baseline) {
+    case "hanging":
+    case "top":
+      yShift = -lo[1]
+    break
+
+    case "middle":
+      yShift = -0.5 * (lo[1] + hi[1])
+    break
+
+    case "alphabetic":
+    case "ideographic":
+      yShift = -3 * size
+    break
+
+    case "bottom":
+      yShift = -hi[1]
+    break
+
+    default:
+      throw new Error("vectorize-text: Unrecoginized textBaseline: '" + baseline + "'")
+  }
+
+  var scale = 1.0 / size
+  if("lineHeight" in options) {
+    scale *= +options.lineHeight
+  } else if("width" in options) {
+    scale = options.width / (hi[0] - lo[0])
+  } else if("height" in options) {
+    scale = options.height / (hi[1] - lo[1])
+  }
+
+  return positions.map(function(p) {
+    return [ scale * (p[0] + xShift), scale * (p[1] + yShift) ]
+  })
+}
+
+function getPixels(canvas, context, str, size) {
+  var width = Math.ceil(context.measureText(str).width + 2*size)|0
+  if(width > 8192) {
+    throw new Error("vectorize-text: String too long (sorry, this will get fixed later)")
+  }
+  var height = 3 * size
+  if(canvas.height < height) {
+    canvas.height = height
+  }
+
+  context.fillStyle = "#000"
+  context.fillRect(0, 0, canvas.width, canvas.height)
+
+  context.fillStyle = "#fff"
+  context.fillText(str, size, 2*size)
+
+  //Cut pixels from image
+  var pixelData = context.getImageData(0, 0, width, height)
+  var pixels = ndarray(pixelData.data, [height, width, 4])
+
+  return pixels.pick(-1,-1,0).transpose(1,0)
+}
+
+function getContour(pixels, doSimplify) {
+  var contour = surfaceNets(pixels, 128)
+  if(doSimplify) {
+    return simplify(contour.cells, contour.positions, 0.25)
+  }
+  return {
+    edges: contour.cells,
+    positions: contour.positions
+  }
+}
+
+function processPixelsImpl(pixels, options, size, simplify) {
+  //Extract contour
+  var contour = getContour(pixels, simplify)
+
+  //Apply warp to positions
+  var positions = transformPositions(contour.positions, options, size)
+  var edges     = contour.edges
+  var flip = "ccw" === options.orientation
+
+  //Clean up the PSLG, resolve self intersections, etc.
+  cleanPSLG(positions, edges)
+
+  //If triangulate flag passed, triangulate the result
+  if(options.polygons || options.polygon || options.polyline) {
+    var result = toPolygonCrappy(edges, positions)
+    var nresult = new Array(result.length)
+    for(var i=0; i<result.length; ++i) {
+      var loops = result[i]
+      var nloops = new Array(loops.length)
+      for(var j=0; j<loops.length; ++j) {
+        var loop = loops[j]
+        var nloop = new Array(loop.length)
+        for(var k=0; k<loop.length; ++k) {
+          nloop[k] = positions[loop[k]].slice()
+        }
+        if(flip) {
+          nloop.reverse()
+        }
+        nloops[j] = nloop
+      }
+      nresult[i] = nloops
+    }
+    return nresult
+  } else if(options.triangles || options.triangulate || options.triangle) {
+    return {
+      cells: cdt2d(positions, edges, {
+        delaunay: false,
+        exterior: false,
+        interior: true
+      }),
+      positions: positions
+    }
+  } else {
+    return {
+      edges:     edges,
+      positions: positions
+    }
+  }
+}
+
+function processPixels(pixels, options, size) {
+  try {
+    return processPixelsImpl(pixels, options, size, true)
+  } catch(e) {}
+  try {
+    return processPixelsImpl(pixels, options, size, false)
+  } catch(e) {}
+  if(options.polygons || options.polyline || options.polygon) {
+    return []
+  }
+  if(options.triangles || options.triangulate || options.triangle) {
+    return {
+      cells: [],
+      positions: []
+    }
+  }
+  return {
+    edges: [],
+    positions: []
+  }
+}
+
+function vectorizeText(str, canvas, context, options) {
+  var size = options.size || 64
+  var family = options.font || "normal"
+
+  context.font = size + "px " + family
+  context.textAlign = "start"
+  context.textBaseline = "alphabetic"
+  context.direction = "ltr"
+
+  var pixels = getPixels(canvas, context, str, size)
+
+  return processPixels(pixels, options, size)
+}
+
+},{"cdt2d":237,"clean-pslg":244,"ndarray":208,"planar-graph-to-polyline":290,"simplify-planar-graph":294,"surface-nets":227}],237:[function(require,module,exports){
+'use strict'
+
+var monotoneTriangulate = require('./lib/monotone')
+var makeIndex = require('./lib/triangulation')
+var delaunayFlip = require('./lib/delaunay')
+var filterTriangulation = require('./lib/filter')
+
+module.exports = cdt2d
+
+function canonicalizeEdge(e) {
+  return [Math.min(e[0], e[1]), Math.max(e[0], e[1])]
+}
+
+function compareEdge(a, b) {
+  return a[0]-b[0] || a[1]-b[1]
+}
+
+function canonicalizeEdges(edges) {
+  return edges.map(canonicalizeEdge).sort(compareEdge)
+}
+
+function getDefault(options, property, dflt) {
+  if(property in options) {
+    return options[property]
+  }
+  return dflt
+}
+
+function cdt2d(points, edges, options) {
+
+  if(!Array.isArray(edges)) {
+    options = edges || {}
+    edges = []
+  } else {
+    options = options || {}
+    edges = edges || []
+  }
+
+  //Parse out options
+  var delaunay = !!getDefault(options, 'delaunay', true)
+  var interior = !!getDefault(options, 'interior', true)
+  var exterior = !!getDefault(options, 'exterior', true)
+  var infinity = !!getDefault(options, 'infinity', false)
+
+  //Handle trivial case
+  if((!interior && !exterior) || points.length === 0) {
+    return []
+  }
+
+  //Construct initial triangulation
+  var cells = monotoneTriangulate(points, edges)
+
+  //If delaunay refinement needed, then improve quality by edge flipping
+  if(delaunay || interior !== exterior || infinity) {
+
+    //Index all of the cells to support fast neighborhood queries
+    var triangulation = makeIndex(points.length, canonicalizeEdges(edges))
+    for(var i=0; i<cells.length; ++i) {
+      var f = cells[i]
+      triangulation.addTriangle(f[0], f[1], f[2])
+    }
+
+    //Run edge flipping
+    if(delaunay) {
+      delaunayFlip(points, triangulation)
+    }
+
+    //Filter points
+    if(!exterior) {
+      return filterTriangulation(triangulation, -1)
+    } else if(!interior) {
+      return filterTriangulation(triangulation,  1, infinity)
+    } else if(infinity) {
+      return filterTriangulation(triangulation, 0, infinity)
+    } else {
+      return triangulation.cells()
+    }
+    
+  } else {
+    return cells
+  }
+}
+
+},{"./lib/delaunay":238,"./lib/filter":239,"./lib/monotone":240,"./lib/triangulation":241}],238:[function(require,module,exports){
+'use strict'
+
+var inCircle = require('robust-in-sphere')[4]
+var bsearch = require('binary-search-bounds')
+
+module.exports = delaunayRefine
+
+function testFlip(points, triangulation, stack, a, b, x) {
+  var y = triangulation.opposite(a, b)
+
+  //Test boundary edge
+  if(y < 0) {
+    return
+  }
+
+  //Swap edge if order flipped
+  if(b < a) {
+    var tmp = a
+    a = b
+    b = tmp
+    tmp = x
+    x = y
+    y = tmp
+  }
+
+  //Test if edge is constrained
+  if(triangulation.isConstraint(a, b)) {
+    return
+  }
+
+  //Test if edge is delaunay
+  if(inCircle(points[a], points[b], points[x], points[y]) < 0) {
+    stack.push(a, b)
+  }
+}
+
+//Assume edges are sorted lexicographically
+function delaunayRefine(points, triangulation) {
+  var stack = []
+
+  var numPoints = points.length
+  var stars = triangulation.stars
+  for(var a=0; a<numPoints; ++a) {
+    var star = stars[a]
+    for(var j=1; j<star.length; j+=2) {
+      var b = star[j]
+
+      //If order is not consistent, then skip edge
+      if(b < a) {
+        continue
+      }
+
+      //Check if edge is constrained
+      if(triangulation.isConstraint(a, b)) {
+        continue
+      }
+
+      //Find opposite edge
+      var x = star[j-1], y = -1
+      for(var k=1; k<star.length; k+=2) {
+        if(star[k-1] === b) {
+          y = star[k]
+          break
+        }
+      }
+
+      //If this is a boundary edge, don't flip it
+      if(y < 0) {
+        continue
+      }
+
+      //If edge is in circle, flip it
+      if(inCircle(points[a], points[b], points[x], points[y]) < 0) {
+        stack.push(a, b)
+      }
+    }
+  }
+
+  while(stack.length > 0) {
+    var b = stack.pop()
+    var a = stack.pop()
+
+    //Find opposite pairs
+    var x = -1, y = -1
+    var star = stars[a]
+    for(var i=1; i<star.length; i+=2) {
+      var s = star[i-1]
+      var t = star[i]
+      if(s === b) {
+        y = t
+      } else if(t === b) {
+        x = s
+      }
+    }
+
+    //If x/y are both valid then skip edge
+    if(x < 0 || y < 0) {
+      continue
+    }
+
+    //If edge is now delaunay, then don't flip it
+    if(inCircle(points[a], points[b], points[x], points[y]) >= 0) {
+      continue
+    }
+
+    //Flip the edge
+    triangulation.flip(a, b)
+
+    //Test flipping neighboring edges
+    testFlip(points, triangulation, stack, x, a, y)
+    testFlip(points, triangulation, stack, a, y, x)
+    testFlip(points, triangulation, stack, y, b, x)
+    testFlip(points, triangulation, stack, b, x, y)
+  }
+}
+
+},{"binary-search-bounds":242,"robust-in-sphere":243}],239:[function(require,module,exports){
+'use strict'
+
+var bsearch = require('binary-search-bounds')
+
+module.exports = classifyFaces
+
+function FaceIndex(cells, neighbor, constraint, flags, active, next, boundary) {
+  this.cells       = cells
+  this.neighbor    = neighbor
+  this.flags       = flags
+  this.constraint  = constraint
+  this.active      = active
+  this.next        = next
+  this.boundary    = boundary
+}
+
+var proto = FaceIndex.prototype
+
+function compareCell(a, b) {
+  return a[0] - b[0] ||
+         a[1] - b[1] ||
+         a[2] - b[2]
+}
+
+proto.locate = (function() {
+  var key = [0,0,0]
+  return function(a, b, c) {
+    var x = a, y = b, z = c
+    if(b < c) {
+      if(b < a) {
+        x = b
+        y = c
+        z = a
+      }
+    } else if(c < a) {
+      x = c
+      y = a
+      z = b
+    }
+    if(x < 0) {
+      return -1
+    }
+    key[0] = x
+    key[1] = y
+    key[2] = z
+    return bsearch.eq(this.cells, key, compareCell)
+  }
+})()
+
+function indexCells(triangulation, infinity) {
+  //First get cells and canonicalize
+  var cells = triangulation.cells()
+  var nc = cells.length
+  for(var i=0; i<nc; ++i) {
+    var c = cells[i]
+    var x = c[0], y = c[1], z = c[2]
+    if(y < z) {
+      if(y < x) {
+        c[0] = y
+        c[1] = z
+        c[2] = x
+      }
+    } else if(z < x) {
+      c[0] = z
+      c[1] = x
+      c[2] = y
+    }
+  }
+  cells.sort(compareCell)
+
+  //Initialize flag array
+  var flags = new Array(nc)
+  for(var i=0; i<flags.length; ++i) {
+    flags[i] = 0
+  }
+
+  //Build neighbor index, initialize queues
+  var active = []
+  var next   = []
+  var neighbor = new Array(3*nc)
+  var constraint = new Array(3*nc)
+  var boundary = null
+  if(infinity) {
+    boundary = []
+  }
+  var index = new FaceIndex(
+    cells,
+    neighbor,
+    constraint,
+    flags,
+    active,
+    next,
+    boundary)
+  for(var i=0; i<nc; ++i) {
+    var c = cells[i]
+    for(var j=0; j<3; ++j) {
+      var x = c[j], y = c[(j+1)%3]
+      var a = neighbor[3*i+j] = index.locate(y, x, triangulation.opposite(y, x))
+      var b = constraint[3*i+j] = triangulation.isConstraint(x, y)
+      if(a < 0) {
+        if(b) {
+          next.push(i)
+        } else {
+          active.push(i)
+          flags[i] = 1
+        }
+        if(infinity) {
+          boundary.push([y, x, -1])
+        }
+      }
+    }
+  }
+  return index
+}
+
+function filterCells(cells, flags, target) {
+  var ptr = 0
+  for(var i=0; i<cells.length; ++i) {
+    if(flags[i] === target) {
+      cells[ptr++] = cells[i]
+    }
+  }
+  cells.length = ptr
+  return cells
+}
+
+function classifyFaces(triangulation, target, infinity) {
+  var index = indexCells(triangulation, infinity)
+
+  if(target === 0) {
+    if(infinity) {
+      return index.cells.concat(index.boundary)
+    } else {
+      return index.cells
+    }
+  }
+
+  var side = 1
+  var active = index.active
+  var next = index.next
+  var flags = index.flags
+  var cells = index.cells
+  var constraint = index.constraint
+  var neighbor = index.neighbor
+
+  while(active.length > 0 || next.length > 0) {
+    while(active.length > 0) {
+      var t = active.pop()
+      if(flags[t] === -side) {
+        continue
+      }
+      flags[t] = side
+      var c = cells[t]
+      for(var j=0; j<3; ++j) {
+        var f = neighbor[3*t+j]
+        if(f >= 0 && flags[f] === 0) {
+          if(constraint[3*t+j]) {
+            next.push(f)
+          } else {
+            active.push(f)
+            flags[f] = side
+          }
+        }
+      }
+    }
+
+    //Swap arrays and loop
+    var tmp = next
+    next = active
+    active = tmp
+    next.length = 0
+    side = -side
+  }
+
+  var result = filterCells(cells, flags, target)
+  if(infinity) {
+    return result.concat(index.boundary)
+  }
+  return result
+}
+
+},{"binary-search-bounds":242}],240:[function(require,module,exports){
+'use strict'
+
+var bsearch = require('binary-search-bounds')
+var orient = require('robust-orientation')[3]
+
+var EVENT_POINT = 0
+var EVENT_END   = 1
+var EVENT_START = 2
+
+module.exports = monotoneTriangulate
+
+//A partial convex hull fragment, made of two unimonotone polygons
+function PartialHull(a, b, idx, lowerIds, upperIds) {
+  this.a = a
+  this.b = b
+  this.idx = idx
+  this.lowerIds = lowerIds
+  this.upperIds = upperIds
+}
+
+//An event in the sweep line procedure
+function Event(a, b, type, idx) {
+  this.a    = a
+  this.b    = b
+  this.type = type
+  this.idx  = idx
+}
+
+//This is used to compare events for the sweep line procedure
+// Points are:
+//  1. sorted lexicographically
+//  2. sorted by type  (point < end < start)
+//  3. segments sorted by winding order
+//  4. sorted by index
+function compareEvent(a, b) {
+  var d =
+    (a.a[0] - b.a[0]) ||
+    (a.a[1] - b.a[1]) ||
+    (a.type - b.type)
+  if(d) { return d }
+  if(a.type !== EVENT_POINT) {
+    d = orient(a.a, a.b, b.b)
+    if(d) { return d }
+  }
+  return a.idx - b.idx
+}
+
+function testPoint(hull, p) {
+  return orient(hull.a, hull.b, p)
+}
+
+function addPoint(cells, hulls, points, p, idx) {
+  var lo = bsearch.lt(hulls, p, testPoint)
+  var hi = bsearch.gt(hulls, p, testPoint)
+  for(var i=lo; i<hi; ++i) {
+    var hull = hulls[i]
+
+    //Insert p into lower hull
+    var lowerIds = hull.lowerIds
+    var m = lowerIds.length
+    while(m > 1 && orient(
+        points[lowerIds[m-2]],
+        points[lowerIds[m-1]],
+        p) > 0) {
+      cells.push(
+        [lowerIds[m-1],
+         lowerIds[m-2],
+         idx])
+      m -= 1
+    }
+    lowerIds.length = m
+    lowerIds.push(idx)
+
+    //Insert p into upper hull
+    var upperIds = hull.upperIds
+    var m = upperIds.length
+    while(m > 1 && orient(
+        points[upperIds[m-2]],
+        points[upperIds[m-1]],
+        p) < 0) {
+      cells.push(
+        [upperIds[m-2],
+         upperIds[m-1],
+         idx])
+      m -= 1
+    }
+    upperIds.length = m
+    upperIds.push(idx)
+  }
+}
+
+function findSplit(hull, edge) {
+  var d
+  if(hull.a[0] < edge.a[0]) {
+    d = orient(hull.a, hull.b, edge.a)
+  } else {
+    d = orient(edge.b, edge.a, hull.a)
+  }
+  if(d) { return d }
+  if(edge.b[0] < hull.b[0]) {
+    d = orient(hull.a, hull.b, edge.b)
+  } else {
+    d = orient(edge.b, edge.a, hull.b)
+  }
+  return d || hull.idx - edge.idx
+}
+
+function splitHulls(hulls, points, event) {
+  var splitIdx = bsearch.le(hulls, event, findSplit)
+  var hull = hulls[splitIdx]
+  var upperIds = hull.upperIds
+  var x = upperIds[upperIds.length-1]
+  hull.upperIds = [x]
+  hulls.splice(splitIdx+1, 0,
+    new PartialHull(event.a, event.b, event.idx, [x], upperIds))
+}
+
+
+function mergeHulls(hulls, points, event) {
+  //Swap pointers for merge search
+  var tmp = event.a
+  event.a = event.b
+  event.b = tmp
+  var mergeIdx = bsearch.eq(hulls, event, findSplit)
+  var upper = hulls[mergeIdx]
+  var lower = hulls[mergeIdx-1]
+  lower.upperIds = upper.upperIds
+  hulls.splice(mergeIdx, 1)
+}
+
+
+function monotoneTriangulate(points, edges) {
+
+  var numPoints = points.length
+  var numEdges = edges.length
+
+  var events = []
+
+  //Create point events
+  for(var i=0; i<numPoints; ++i) {
+    events.push(new Event(
+      points[i],
+      null,
+      EVENT_POINT,
+      i))
+  }
+
+  //Create edge events
+  for(var i=0; i<numEdges; ++i) {
+    var e = edges[i]
+    var a = points[e[0]]
+    var b = points[e[1]]
+    if(a[0] < b[0]) {
+      events.push(
+        new Event(a, b, EVENT_START, i),
+        new Event(b, a, EVENT_END, i))
+    } else if(a[0] > b[0]) {
+      events.push(
+        new Event(b, a, EVENT_START, i),
+        new Event(a, b, EVENT_END, i))
+    }
+  }
+
+  //Sort events
+  events.sort(compareEvent)
+
+  //Initialize hull
+  var minX = events[0].a[0] - (1 + Math.abs(events[0].a[0])) * Math.pow(2, -52)
+  var hull = [ new PartialHull([minX, 1], [minX, 0], -1, [], [], [], []) ]
+
+  //Process events in order
+  var cells = []
+  for(var i=0, numEvents=events.length; i<numEvents; ++i) {
+    var event = events[i]
+    var type = event.type
+    if(type === EVENT_POINT) {
+      addPoint(cells, hull, points, event.a, event.idx)
+    } else if(type === EVENT_START) {
+      splitHulls(hull, points, event)
+    } else {
+      mergeHulls(hull, points, event)
+    }
+  }
+
+  //Return triangulation
+  return cells
+}
+
+},{"binary-search-bounds":242,"robust-orientation":214}],241:[function(require,module,exports){
+'use strict'
+
+var bsearch = require('binary-search-bounds')
+
+module.exports = createTriangulation
+
+function Triangulation(stars, edges) {
+  this.stars = stars
+  this.edges = edges
+}
+
+var proto = Triangulation.prototype
+
+function removePair(list, j, k) {
+  for(var i=1, n=list.length; i<n; i+=2) {
+    if(list[i-1] === j && list[i] === k) {
+      list[i-1] = list[n-2]
+      list[i] = list[n-1]
+      list.length = n - 2
+      return
+    }
+  }
+}
+
+proto.isConstraint = (function() {
+  var e = [0,0]
+  function compareLex(a, b) {
+    return a[0] - b[0] || a[1] - b[1]
+  }
+  return function(i, j) {
+    e[0] = Math.min(i,j)
+    e[1] = Math.max(i,j)
+    return bsearch.eq(this.edges, e, compareLex) >= 0
+  }
+})()
+
+proto.removeTriangle = function(i, j, k) {
+  var stars = this.stars
+  removePair(stars[i], j, k)
+  removePair(stars[j], k, i)
+  removePair(stars[k], i, j)
+}
+
+proto.addTriangle = function(i, j, k) {
+  var stars = this.stars
+  stars[i].push(j, k)
+  stars[j].push(k, i)
+  stars[k].push(i, j)
+}
+
+proto.opposite = function(j, i) {
+  var list = this.stars[i]
+  for(var k=1, n=list.length; k<n; k+=2) {
+    if(list[k] === j) {
+      return list[k-1]
+    }
+  }
+  return -1
+}
+
+proto.flip = function(i, j) {
+  var a = this.opposite(i, j)
+  var b = this.opposite(j, i)
+  this.removeTriangle(i, j, a)
+  this.removeTriangle(j, i, b)
+  this.addTriangle(i, b, a)
+  this.addTriangle(j, a, b)
+}
+
+proto.edges = function() {
+  var stars = this.stars
+  var result = []
+  for(var i=0, n=stars.length; i<n; ++i) {
+    var list = stars[i]
+    for(var j=0, m=list.length; j<m; j+=2) {
+      result.push([list[j], list[j+1]])
+    }
+  }
+  return result
+}
+
+proto.cells = function() {
+  var stars = this.stars
+  var result = []
+  for(var i=0, n=stars.length; i<n; ++i) {
+    var list = stars[i]
+    for(var j=0, m=list.length; j<m; j+=2) {
+      var s = list[j]
+      var t = list[j+1]
+      if(i < Math.min(s, t)) {
+        result.push([i, s, t])
+      }
+    }
+  }
+  return result
+}
+
+function createTriangulation(numVerts, edges) {
+  var stars = new Array(numVerts)
+  for(var i=0; i<numVerts; ++i) {
+    stars[i] = []
+  }
+  return new Triangulation(stars, edges)
+}
+
+},{"binary-search-bounds":242}],242:[function(require,module,exports){
+arguments[4][121][0].apply(exports,arguments)
+},{"dup":121}],243:[function(require,module,exports){
+"use strict"
+
+var twoProduct = require("two-product")
+var robustSum = require("robust-sum")
+var robustDiff = require("robust-subtract")
+var robustScale = require("robust-scale")
+
+var NUM_EXPAND = 6
+
+function cofactor(m, c) {
+  var result = new Array(m.length-1)
+  for(var i=1; i<m.length; ++i) {
+    var r = result[i-1] = new Array(m.length-1)
+    for(var j=0,k=0; j<m.length; ++j) {
+      if(j === c) {
+        continue
+      }
+      r[k++] = m[i][j]
+    }
+  }
+  return result
+}
+
+function matrix(n) {
+  var result = new Array(n)
+  for(var i=0; i<n; ++i) {
+    result[i] = new Array(n)
+    for(var j=0; j<n; ++j) {
+      result[i][j] = ["m", j, "[", (n-i-2), "]"].join("")
+    }
+  }
+  return result
+}
+
+function generateSum(expr) {
+  if(expr.length === 1) {
+    return expr[0]
+  } else if(expr.length === 2) {
+    return ["sum(", expr[0], ",", expr[1], ")"].join("")
+  } else {
+    var m = expr.length>>1
+    return ["sum(", generateSum(expr.slice(0, m)), ",", generateSum(expr.slice(m)), ")"].join("")
+  }
+}
+
+function makeProduct(a, b) {
+  if(a.charAt(0) === "m") {
+    if(b.charAt(0) === "w") {
+      var toks = a.split("[")
+      return ["w", b.substr(1), "m", toks[0].substr(1)].join("")
+    } else {
+      return ["prod(", a, ",", b, ")"].join("")
+    }
+  } else {
+    return makeProduct(b, a)
+  }
+}
+
+function sign(s) {
+  if(s & 1 !== 0) {
+    return "-"
+  }
+  return ""
+}
+
+function determinant(m) {
+  if(m.length === 2) {
+    return [["diff(", makeProduct(m[0][0], m[1][1]), ",", makeProduct(m[1][0], m[0][1]), ")"].join("")]
+  } else {
+    var expr = []
+    for(var i=0; i<m.length; ++i) {
+      expr.push(["scale(", generateSum(determinant(cofactor(m, i))), ",", sign(i), m[0][i], ")"].join(""))
+    }
+    return expr
+  }
+}
+
+function makeSquare(d, n) {
+  var terms = []
+  for(var i=0; i<n-2; ++i) {
+    terms.push(["prod(m", d, "[", i, "],m", d, "[", i, "])"].join(""))
+  }
+  return generateSum(terms)
+}
+
+function orientation(n) {
+  var pos = []
+  var neg = []
+  var m = matrix(n)
+  for(var i=0; i<n; ++i) {
+    m[0][i] = "1"
+    m[n-1][i] = "w"+i
+  } 
+  for(var i=0; i<n; ++i) {
+    if((i&1)===0) {
+      pos.push.apply(pos,determinant(cofactor(m, i)))
+    } else {
+      neg.push.apply(neg,determinant(cofactor(m, i)))
+    }
+  }
+  var posExpr = generateSum(pos)
+  var negExpr = generateSum(neg)
+  var funcName = "exactInSphere" + n
+  var funcArgs = []
+  for(var i=0; i<n; ++i) {
+    funcArgs.push("m" + i)
+  }
+  var code = ["function ", funcName, "(", funcArgs.join(), "){"]
+  for(var i=0; i<n; ++i) {
+    code.push("var w",i,"=",makeSquare(i,n),";")
+    for(var j=0; j<n; ++j) {
+      if(j !== i) {
+        code.push("var w",i,"m",j,"=scale(w",i,",m",j,"[0]);")
+      }
+    }
+  }
+  code.push("var p=", posExpr, ",n=", negExpr, ",d=diff(p,n);return d[d.length-1];}return ", funcName)
+  var proc = new Function("sum", "diff", "prod", "scale", code.join(""))
+  return proc(robustSum, robustDiff, twoProduct, robustScale)
+}
+
+function inSphere0() { return 0 }
+function inSphere1() { return 0 }
+function inSphere2() { return 0 }
+
+var CACHED = [
+  inSphere0,
+  inSphere1,
+  inSphere2
+]
+
+function slowInSphere(args) {
+  var proc = CACHED[args.length]
+  if(!proc) {
+    proc = CACHED[args.length] = orientation(args.length)
+  }
+  return proc.apply(undefined, args)
+}
+
+function generateInSphereTest() {
+  while(CACHED.length <= NUM_EXPAND) {
+    CACHED.push(orientation(CACHED.length))
+  }
+  var args = []
+  var procArgs = ["slow"]
+  for(var i=0; i<=NUM_EXPAND; ++i) {
+    args.push("a" + i)
+    procArgs.push("o" + i)
+  }
+  var code = [
+    "function testInSphere(", args.join(), "){switch(arguments.length){case 0:case 1:return 0;"
+  ]
+  for(var i=2; i<=NUM_EXPAND; ++i) {
+    code.push("case ", i, ":return o", i, "(", args.slice(0, i).join(), ");")
+  }
+  code.push("}var s=new Array(arguments.length);for(var i=0;i<arguments.length;++i){s[i]=arguments[i]};return slow(s);}return testInSphere")
+  procArgs.push(code.join(""))
+
+  var proc = Function.apply(undefined, procArgs)
+
+  module.exports = proc.apply(undefined, [slowInSphere].concat(CACHED))
+  for(var i=0; i<=NUM_EXPAND; ++i) {
+    module.exports[i] = CACHED[i]
+  }
+}
+
+generateInSphereTest()
+},{"robust-scale":215,"robust-subtract":216,"robust-sum":217,"two-product":231}],244:[function(require,module,exports){
+'use strict'
+
+module.exports = cleanPSLG
+
+var UnionFind = require('union-find')
+var boxIntersect = require('box-intersect')
+var compareCell = require('compare-cell')
+var segseg = require('robust-segment-intersect')
+var rat = require('big-rat')
+var ratCmp = require('big-rat/cmp')
+var ratToFloat = require('big-rat/to-float')
+var ratVec = require('rat-vec')
+var nextafter = require('nextafter')
+
+var solveIntersection = require('./lib/rat-seg-intersect')
+
+//Bounds on a rational number when rounded to a float
+function boundRat(r) {
+  var f = ratToFloat(r)
+  var cmp = ratCmp(rat(f), r)
+  if(cmp < 0) {
+    return [f, nextafter(f, Infinity)]
+  } else if(cmp > 0) {
+    return [nextafter(f, -Infinity), f]
+  } else {
+    return [f, f]
+  }
+}
+
+//Convert a list of edges in a pslg to bounding boxes
+function boundEdges(points, edges) {
+  var bounds = new Array(edges.length)
+  for(var i=0; i<edges.length; ++i) {
+    var e = edges[i]
+    var a = points[e[0]]
+    var b = points[e[1]]
+    bounds[i] = [
+      Math.min(a[0], b[0]),
+      Math.min(a[1], b[1]),
+      Math.max(a[0], b[0]),
+      Math.max(a[1], b[1]) ]
+  }
+  return bounds
+}
+
+//Convert a list of points into bounding boxes by duplicating coords
+function boundPoints(points) {
+  var bounds = new Array(points.length)
+  for(var i=0; i<points.length; ++i) {
+    var p = points[i]
+    bounds[i] = [ p[0], p[1], p[0], p[1] ]
+  }
+  return bounds
+}
+
+//Find all pairs of crossing edges in a pslg (given edge bounds)
+function getCrossings(points, edges, edgeBounds) {
+  var result = []
+  boxIntersect(edgeBounds, function(i, j) {
+    var e = edges[i]
+    var f = edges[j]
+    if(e[0] === f[0] || e[0] === f[1] ||
+       e[1] === f[0] || e[1] === f[1]) {
+         return
+    }
+    var a = points[e[0]]
+    var b = points[e[1]]
+    var c = points[f[0]]
+    var d = points[f[1]]
+    if(segseg(a, b, c, d)) {
+      result.push([i, j])
+    }
+  })
+  return result
+}
+
+//Find all pairs of crossing vertices in a pslg (given edge/vert bounds)
+function getTJunctions(points, edges, edgeBounds, vertBounds) {
+  var result = []
+  boxIntersect(edgeBounds, vertBounds, function(i, v) {
+    var e = edges[i]
+    if(e[0] === v || e[1] === v) {
+      return
+    }
+    var p = points[v]
+    var a = points[e[0]]
+    var b = points[e[1]]
+    if(segseg(a, b, p, p)) {
+      result.push([i, v])
+    }
+  })
+  return result
+}
+
+
+//Cut edges along crossings/tjunctions
+function cutEdges(floatPoints, edges, crossings, junctions, useColor) {
+
+  //Convert crossings into tjunctions by constructing rational points
+  var ratPoints = []
+  for(var i=0; i<crossings.length; ++i) {
+    var crossing = crossings[i]
+    var e = crossing[0]
+    var f = crossing[1]
+    var ee = edges[e]
+    var ef = edges[f]
+    var x = solveIntersection(
+      ratVec(floatPoints[ee[0]]),
+      ratVec(floatPoints[ee[1]]),
+      ratVec(floatPoints[ef[0]]),
+      ratVec(floatPoints[ef[1]]))
+    if(!x) {
+      //Segments are parallel, should already be handled by t-junctions
+      continue
+    }
+    var idx = ratPoints.length + floatPoints.length
+    ratPoints.push(x)
+    junctions.push([e, idx], [f, idx])
+  }
+
+  //Sort tjunctions
+  function getPoint(idx) {
+    if(idx >= floatPoints.length) {
+      return ratPoints[idx-floatPoints.length]
+    }
+    var p = floatPoints[idx]
+    return [ rat(p[0]), rat(p[1]) ]
+  }
+  junctions.sort(function(a, b) {
+    if(a[0] !== b[0]) {
+      return a[0] - b[0]
+    }
+    var u = getPoint(a[1])
+    var v = getPoint(b[1])
+    return ratCmp(u[0], v[0]) || ratCmp(u[1], v[1])
+  })
+
+  //Split edges along junctions
+  for(var i=junctions.length-1; i>=0; --i) {
+    var junction = junctions[i]
+    var e = junction[0]
+
+    var edge = edges[e]
+    var s = edge[0]
+    var t = edge[1]
+
+    //Check if edge is not lexicographically sorted
+    var a = floatPoints[s]
+    var b = floatPoints[t]
+    if(((a[0] - b[0]) || (a[1] - b[1])) < 0) {
+      var tmp = s
+      s = t
+      t = tmp
+    }
+
+    //Split leading edge
+    edge[0] = s
+    var last = edge[1] = junction[1]
+
+    //If we are grouping edges by color, remember to track data
+    var color
+    if(useColor) {
+      color = edge[2]
+    }
+
+    //Split other edges
+    while(i > 0 && junctions[i-1][0] === e) {
+      var junction = junctions[--i]
+      var next = junction[1]
+      if(useColor) {
+        edges.push([last, next, color])
+      } else {
+        edges.push([last, next])
+      }
+      last = next
+    }
+
+    //Add final edge
+    if(useColor) {
+      edges.push([last, t, color])
+    } else {
+      edges.push([last, t])
+    }
+  }
+
+  //Return constructed rational points
+  return ratPoints
+}
+
+//Merge overlapping points
+function dedupPoints(floatPoints, ratPoints, floatBounds) {
+  var numPoints = floatPoints.length + ratPoints.length
+  var uf        = new UnionFind(numPoints)
+
+  //Compute rational bounds
+  var bounds = floatBounds
+  for(var i=0; i<ratPoints.length; ++i) {
+    var p = ratPoints[i]
+    var xb = boundRat(p[0])
+    var yb = boundRat(p[1])
+    bounds.push([ xb[0], yb[0], xb[1], yb[1] ])
+    floatPoints.push([ ratToFloat(p[0]), ratToFloat(p[1]) ])
+  }
+
+  //Link all points with over lapping boxes
+  boxIntersect(bounds, function(i, j) {
+    uf.link(i, j)
+  })
+
+  //Call find on each point to get a relabeling
+  var ptr = 0
+  var noDupes = true
+  var labels = new Array(numPoints)
+  for(var i=0; i<numPoints; ++i) {
+    var j = uf.find(i)
+    if(j === i) {
+      //If not a duplicate, then don't bother
+      labels[i] = ptr
+      floatPoints[ptr++] = floatPoints[i]
+    } else {
+      //Clear no-dupes flag, zero out label
+      noDupes = false
+      labels[i] = -1
+    }
+  }
+  floatPoints.length = ptr
+
+  //If no duplicates, return null to signal termination
+  if(noDupes) {
+    return null
+  }
+
+  //Do a second pass to fix up missing labels
+  for(var i=0; i<numPoints; ++i) {
+    if(labels[i] < 0) {
+      labels[i] = labels[uf.find(i)]
+    }
+  }
+
+  //Return resulting union-find data structure
+  return labels
+}
+
+function compareLex2(a,b) { return (a[0]-b[0]) || (a[1]-b[1]) }
+function compareLex3(a,b) {
+  var d = (a[0] - b[0]) || (a[1] - b[1])
+  if(d) {
+    return d
+  }
+  if(a[2] < b[2]) {
+    return -1
+  } else if(a[2] > b[2]) {
+    return 1
+  }
+  return 0
+}
+
+//Remove duplicate edge labels
+function dedupEdges(edges, labels, useColor) {
+  if(edges.length === 0) {
+    return
+  }
+  if(labels) {
+    for(var i=0; i<edges.length; ++i) {
+      var e = edges[i]
+      var a = labels[e[0]]
+      var b = labels[e[1]]
+      e[0] = Math.min(a, b)
+      e[1] = Math.max(a, b)
+    }
+  } else {
+    for(var i=0; i<edges.length; ++i) {
+      var e = edges[i]
+      var a = e[0]
+      var b = e[1]
+      e[0] = Math.min(a, b)
+      e[1] = Math.max(a, b)
+    }
+  }
+  if(useColor) {
+    edges.sort(compareLex3)
+  } else {
+    edges.sort(compareLex2)
+  }
+  var ptr = 1
+  for(var i=1; i<edges.length; ++i) {
+    var prev = edges[i-1]
+    var next = edges[i]
+    if(next[0] === prev[0] && next[1] === prev[1] &&
+      (!useColor || next[2] === prev[2])) {
+      continue
+    }
+    edges[ptr++] = next
+  }
+  edges.length = ptr
+}
+
+//Repeat until convergence
+function snapRound(points, edges, useColor) {
+
+  // 1. find edge crossings
+  var edgeBounds = boundEdges(points, edges)
+  var crossings  = getCrossings(points, edges, edgeBounds)
+
+  // 2. find t-junctions
+  var vertBounds = boundPoints(points)
+  var tjunctions = getTJunctions(points, edges, edgeBounds, vertBounds)
+
+  // 3. cut edges, construct rational points
+  var ratPoints  = cutEdges(points, edges, crossings, tjunctions, useColor)
+
+  // 4. dedupe verts
+  var labels     = dedupPoints(points, ratPoints, vertBounds)
+
+  // 6. dedupe edges
+  dedupEdges(edges, labels, useColor)
+
+  // 5. check termination
+  if(!labels) {
+    return (crossings.length > 0 || tjunctions.length > 0)
+  }
+
+  // More iterations necessary
+  return true
+}
+
+//Main loop, runs PSLG clean up until completion
+function cleanPSLG(points, edges, colors) {
+  var modified = false
+
+  //If using colors, augment edges with color data
+  var prevEdges
+  if(colors) {
+    prevEdges = edges
+    var augEdges = new Array(edges.length)
+    for(var i=0; i<edges.length; ++i) {
+      var e = edges[i]
+      augEdges[i] = [e[0], e[1], colors[i]]
+    }
+    edges = augEdges
+  }
+
+  //Run snap rounding until convergence
+  while(snapRound(points, edges, !!colors)) {
+    modified = true
+  }
+
+  //Strip color tags
+  if(!!colors && modified) {
+    prevEdges.length = 0
+    colors.length = 0
+    for(var i=0; i<edges.length; ++i) {
+      var e = edges[i]
+      prevEdges.push([e[0], e[1]])
+      colors.push(e[2])
+    }
+  }
+
+  return modified
+}
+
+},{"./lib/rat-seg-intersect":245,"big-rat":249,"big-rat/cmp":247,"big-rat/to-float":262,"box-intersect":263,"compare-cell":59,"nextafter":271,"rat-vec":273,"robust-segment-intersect":276,"union-find":277}],245:[function(require,module,exports){
+'use strict'
+
+//TODO: Move this to a separate module
+
+module.exports = solveIntersection
+
+var ratMul = require('big-rat/mul')
+var ratDiv = require('big-rat/div')
+var ratSub = require('big-rat/sub')
+var ratSign = require('big-rat/sign')
+var rvSub = require('rat-vec/sub')
+var rvAdd = require('rat-vec/add')
+var rvMuls = require('rat-vec/muls')
+
+var toFloat = require('big-rat/to-float')
+
+function ratPerp(a, b) {
+  return ratSub(ratMul(a[0], b[1]), ratMul(a[1], b[0]))
+}
+
+//Solve for intersection
+//  x = a + t (b-a)
+//  (x - c) ^ (d-c) = 0
+//  (t * (b-a) + (a-c) ) ^ (d-c) = 0
+//  t * (b-a)^(d-c) = (d-c)^(a-c)
+//  t = (d-c)^(a-c) / (b-a)^(d-c)
+
+function solveIntersection(a, b, c, d) {
+  var ba = rvSub(b, a)
+  var dc = rvSub(d, c)
+
+  var baXdc = ratPerp(ba, dc)
+
+  if(ratSign(baXdc) === 0) {
+    return null
+  }
+
+  var ac = rvSub(a, c)
+  var dcXac = ratPerp(dc, ac)
+
+  var t = ratDiv(dcXac, baXdc)
+
+  return rvAdd(a, rvMuls(ba, t))
+}
+
+},{"big-rat/div":248,"big-rat/mul":258,"big-rat/sign":260,"big-rat/sub":261,"big-rat/to-float":262,"rat-vec/add":272,"rat-vec/muls":274,"rat-vec/sub":275}],246:[function(require,module,exports){
+'use strict'
+
+var rationalize = require('./lib/rationalize')
+
+module.exports = add
+
+function add(a, b) {
+  return rationalize(
+    a[0].mul(b[1]).add(b[0].mul(a[1])),
+    a[1].mul(b[1]))
+}
+
+},{"./lib/rationalize":256}],247:[function(require,module,exports){
+'use strict'
+
+module.exports = cmp
+
+function cmp(a, b) {
+    return a[0].mul(b[1]).cmp(b[0].mul(a[1]))
+}
+
+},{}],248:[function(require,module,exports){
+'use strict'
+
+var rationalize = require('./lib/rationalize')
+
+module.exports = div
+
+function div(a, b) {
+  return rationalize(a[0].mul(b[1]), a[1].mul(b[0]))
+}
+
+},{"./lib/rationalize":256}],249:[function(require,module,exports){
+'use strict'
+
+var isRat = require('./is-rat')
+var isBN = require('./lib/is-bn')
+var num2bn = require('./lib/num-to-bn')
+var str2bn = require('./lib/str-to-bn')
+var rationalize = require('./lib/rationalize')
+var div = require('./div')
+
+module.exports = makeRational
+
+function makeRational(numer, denom) {
+  if(isRat(numer)) {
+    if(denom) {
+      return div(numer, makeRational(denom))
+    }
+    return [numer[0].clone(), numer[1].clone()]
+  }
+  var shift = 0
+  var a, b
+  if(isBN(numer)) {
+    a = numer.clone()
+  } else if(typeof numer === 'string') {
+    a = str2bn(numer)
+  } else if(numer === 0) {
+    return [num2bn(0), num2bn(1)]
+  } else if(numer === Math.floor(numer)) {
+    a = num2bn(numer)
+  } else {
+    while(numer !== Math.floor(numer)) {
+      numer = numer * Math.pow(2, 256)
+      shift -= 256
+    }
+    a = num2bn(numer)
+  }
+  if(isRat(denom)) {
+    a.mul(denom[1])
+    b = denom[0].clone()
+  } else if(isBN(denom)) {
+    b = denom.clone()
+  } else if(typeof denom === 'string') {
+    b = str2bn(denom)
+  } else if(!denom) {
+    b = num2bn(1)
+  } else if(denom === Math.floor(denom)) {
+    b = num2bn(denom)
+  } else {
+    while(denom !== Math.floor(denom)) {
+      denom = denom * Math.pow(2, 256)
+      shift += 256
+    }
+    b = num2bn(denom)
+  }
+  if(shift > 0) {
+    a = a.shln(shift)
+  } else if(shift < 0) {
+    b = b.shln(-shift)
+  }
+  return rationalize(a, b)
+}
+
+},{"./div":248,"./is-rat":250,"./lib/is-bn":254,"./lib/num-to-bn":255,"./lib/rationalize":256,"./lib/str-to-bn":257}],250:[function(require,module,exports){
+'use strict'
+
+var isBN = require('./lib/is-bn')
+
+module.exports = isRat
+
+function isRat(x) {
+  return Array.isArray(x) && x.length === 2 && isBN(x[0]) && isBN(x[1])
+}
+
+},{"./lib/is-bn":254}],251:[function(require,module,exports){
+'use strict'
+
+var bn = require('bn.js')
+
+module.exports = sign
+
+function sign(x) {
+  return x.cmp(new bn(0))
+}
+
+},{"bn.js":259}],252:[function(require,module,exports){
+'use strict'
+
+module.exports = bn2num
+
+//TODO: Make this better
+function bn2num(b) {
+  var l = b.length
+  var words = b.words
+  var out = 0
+  if (l === 1) {
+    out = words[0]
+  } else if (l === 2) {
+    out = words[0] + (words[1] * 0x4000000)
+  } else {
+    var out = 0
+    for (var i = 0; i < l; i++) {
+      var w = words[i]
+      out += w * Math.pow(0x4000000, i)
+    }
+  }
+  return b.sign ? -out : out
+}
+
+},{}],253:[function(require,module,exports){
+'use strict'
+
+var db = require('double-bits')
+var ctz = require('bit-twiddle').countTrailingZeros
+
+module.exports = ctzNumber
+
+//Counts the number of trailing zeros
+function ctzNumber(x) {
+  var l = ctz(db.lo(x))
+  if(l < 32) {
+    return l
+  }
+  var h = ctz(db.hi(x))
+  if(h > 20) {
+    return 52
+  }
+  return h + 32
+}
+
+},{"bit-twiddle":49,"double-bits":270}],254:[function(require,module,exports){
+'use strict'
+
+var BN = require('bn.js')
+
+module.exports = isBN
+
+//Test if x is a bignumber
+//FIXME: obviously this is the wrong way to do it
+function isBN(x) {
+  return x && typeof x === 'object' && Boolean(x.words)
+}
+
+},{"bn.js":259}],255:[function(require,module,exports){
+'use strict'
+
+var BN = require('bn.js')
+var db = require('double-bits')
+
+module.exports = num2bn
+
+function num2bn(x) {
+  var e = db.exponent(x)
+  if(e < 52) {
+    return new BN(x)
+  } else {
+    return (new BN(x * Math.pow(2, 52-e))).shln(e-52)
+  }
+}
+
+},{"bn.js":259,"double-bits":270}],256:[function(require,module,exports){
+'use strict'
+
+var num2bn = require('./num-to-bn')
+var sign = require('./bn-sign')
+
+module.exports = rationalize
+
+function rationalize(numer, denom) {
+  var snumer = sign(numer)
+  var sdenom = sign(denom)
+  if(snumer === 0) {
+    return [num2bn(0), num2bn(1)]
+  }
+  if(sdenom === 0) {
+    return [num2bn(0), num2bn(0)]
+  }
+  if(sdenom < 0) {
+    numer = numer.neg()
+    denom = denom.neg()
+  }
+  var d = numer.gcd(denom)
+  if(d.cmpn(1)) {
+    return [ numer.div(d), denom.div(d) ]
+  }
+  return [ numer, denom ]
+}
+
+},{"./bn-sign":251,"./num-to-bn":255}],257:[function(require,module,exports){
+'use strict'
+
+var BN = require('bn.js')
+
+module.exports = str2BN
+
+function str2BN(x) {
+  return new BN(x)
+}
+
+},{"bn.js":259}],258:[function(require,module,exports){
+'use strict'
+
+var rationalize = require('./lib/rationalize')
+
+module.exports = mul
+
+function mul(a, b) {
+  return rationalize(a[0].mul(b[0]), a[1].mul(b[1]))
+}
+
+},{"./lib/rationalize":256}],259:[function(require,module,exports){
+(function (module, exports) {
+
+'use strict';
+
+// Utils
+
+function assert(val, msg) {
+  if (!val)
+    throw new Error(msg || 'Assertion failed');
+}
+
+// Could use `inherits` module, but don't want to move from single file
+// architecture yet.
+function inherits(ctor, superCtor) {
+  ctor.super_ = superCtor;
+  var TempCtor = function () {};
+  TempCtor.prototype = superCtor.prototype;
+  ctor.prototype = new TempCtor();
+  ctor.prototype.constructor = ctor;
+}
+
+// BN
+
+function BN(number, base, endian) {
+  // May be `new BN(bn)` ?
+  if (number !== null &&
+      typeof number === 'object' &&
+      Array.isArray(number.words)) {
+    return number;
+  }
+
+  this.sign = false;
+  this.words = null;
+  this.length = 0;
+
+  // Reduction context
+  this.red = null;
+
+  if (base === 'le' || base === 'be') {
+    endian = base;
+    base = 10;
+  }
+
+  if (number !== null)
+    this._init(number || 0, base || 10, endian || 'be');
+}
+if (typeof module === 'object')
+  module.exports = BN;
+else
+  exports.BN = BN;
+
+BN.BN = BN;
+BN.wordSize = 26;
+
+BN.prototype._init = function init(number, base, endian) {
+  if (typeof number === 'number') {
+    return this._initNumber(number, base, endian);
+  } else if (typeof number === 'object') {
+    return this._initArray(number, base, endian);
+  }
+  if (base === 'hex')
+    base = 16;
+  assert(base === (base | 0) && base >= 2 && base <= 36);
+
+  number = number.toString().replace(/\s+/g, '');
+  var start = 0;
+  if (number[0] === '-')
+    start++;
+
+  if (base === 16)
+    this._parseHex(number, start);
+  else
+    this._parseBase(number, base, start);
+
+  if (number[0] === '-')
+    this.sign = true;
+
+  this.strip();
+
+  if (endian !== 'le')
+    return;
+
+  this._initArray(this.toArray(), base, endian);
+};
+
+BN.prototype._initNumber = function _initNumber(number, base, endian) {
+  if (number < 0) {
+    this.sign = true;
+    number = -number;
+  }
+  if (number < 0x4000000) {
+    this.words = [ number & 0x3ffffff ];
+    this.length = 1;
+  } else if (number < 0x10000000000000) {
+    this.words = [
+      number & 0x3ffffff,
+      (number / 0x4000000) & 0x3ffffff
+    ];
+    this.length = 2;
+  } else {
+    assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
+    this.words = [
+      number & 0x3ffffff,
+      (number / 0x4000000) & 0x3ffffff,
+      1
+    ];
+    this.length = 3;
+  }
+
+  if (endian !== 'le')
+    return;
+
+  // Reverse the bytes
+  this._initArray(this.toArray(), base, endian);
+};
+
+BN.prototype._initArray = function _initArray(number, base, endian) {
+  // Perhaps a Uint8Array
+  assert(typeof number.length === 'number');
+  if (number.length <= 0) {
+    this.words = [ 0 ];
+    this.length = 1;
+    return this;
+  }
+
+  this.length = Math.ceil(number.length / 3);
+  this.words = new Array(this.length);
+  for (var i = 0; i < this.length; i++)
+    this.words[i] = 0;
+
+  var off = 0;
+  if (endian === 'be') {
+    for (var i = number.length - 1, j = 0; i >= 0; i -= 3) {
+      var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
+      this.words[j] |= (w << off) & 0x3ffffff;
+      this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
+      off += 24;
+      if (off >= 26) {
+        off -= 26;
+        j++;
+      }
+    }
+  } else if (endian === 'le') {
+    for (var i = 0, j = 0; i < number.length; i += 3) {
+      var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
+      this.words[j] |= (w << off) & 0x3ffffff;
+      this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
+      off += 24;
+      if (off >= 26) {
+        off -= 26;
+        j++;
+      }
+    }
+  }
+  return this.strip();
+};
+
+function parseHex(str, start, end) {
+  var r = 0;
+  var len = Math.min(str.length, end);
+  for (var i = start; i < len; i++) {
+    var c = str.charCodeAt(i) - 48;
+
+    r <<= 4;
+
+    // 'a' - 'f'
+    if (c >= 49 && c <= 54)
+      r |= c - 49 + 0xa;
+
+    // 'A' - 'F'
+    else if (c >= 17 && c <= 22)
+      r |= c - 17 + 0xa;
+
+    // '0' - '9'
+    else
+      r |= c & 0xf;
+  }
+  return r;
+}
+
+BN.prototype._parseHex = function _parseHex(number, start) {
+  // Create possibly bigger array to ensure that it fits the number
+  this.length = Math.ceil((number.length - start) / 6);
+  this.words = new Array(this.length);
+  for (var i = 0; i < this.length; i++)
+    this.words[i] = 0;
+
+  // Scan 24-bit chunks and add them to the number
+  var off = 0;
+  for (var i = number.length - 6, j = 0; i >= start; i -= 6) {
+    var w = parseHex(number, i, i + 6);
+    this.words[j] |= (w << off) & 0x3ffffff;
+    this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
+    off += 24;
+    if (off >= 26) {
+      off -= 26;
+      j++;
+    }
+  }
+  if (i + 6 !== start) {
+    var w = parseHex(number, start, i + 6);
+    this.words[j] |= (w << off) & 0x3ffffff;
+    this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
+  }
+  this.strip();
+};
+
+function parseBase(str, start, end, mul) {
+  var r = 0;
+  var len = Math.min(str.length, end);
+  for (var i = start; i < len; i++) {
+    var c = str.charCodeAt(i) - 48;
+
+    r *= mul;
+
+    // 'a'
+    if (c >= 49)
+      r += c - 49 + 0xa;
+
+    // 'A'
+    else if (c >= 17)
+      r += c - 17 + 0xa;
+
+    // '0' - '9'
+    else
+      r += c;
+  }
+  return r;
+}
+
+BN.prototype._parseBase = function _parseBase(number, base, start) {
+  // Initialize as zero
+  this.words = [ 0 ];
+  this.length = 1;
+
+  // Find length of limb in base
+  for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base)
+    limbLen++;
+  limbLen--;
+  limbPow = (limbPow / base) | 0;
+
+  var total = number.length - start;
+  var mod = total % limbLen;
+  var end = Math.min(total, total - mod) + start;
+
+  var word = 0;
+  for (var i = start; i < end; i += limbLen) {
+    word = parseBase(number, i, i + limbLen, base);
+
+    this.imuln(limbPow);
+    if (this.words[0] + word < 0x4000000)
+      this.words[0] += word;
+    else
+      this._iaddn(word);
+  }
+
+  if (mod !== 0) {
+    var pow = 1;
+    var word = parseBase(number, i, number.length, base);
+
+    for (var i = 0; i < mod; i++)
+      pow *= base;
+    this.imuln(pow);
+    if (this.words[0] + word < 0x4000000)
+      this.words[0] += word;
+    else
+      this._iaddn(word);
+  }
+};
+
+BN.prototype.copy = function copy(dest) {
+  dest.words = new Array(this.length);
+  for (var i = 0; i < this.length; i++)
+    dest.words[i] = this.words[i];
+  dest.length = this.length;
+  dest.sign = this.sign;
+  dest.red = this.red;
+};
+
+BN.prototype.clone = function clone() {
+  var r = new BN(null);
+  this.copy(r);
+  return r;
+};
+
+// Remove leading `0` from `this`
+BN.prototype.strip = function strip() {
+  while (this.length > 1 && this.words[this.length - 1] === 0)
+    this.length--;
+  return this._normSign();
+};
+
+BN.prototype._normSign = function _normSign() {
+  // -0 = 0
+  if (this.length === 1 && this.words[0] === 0)
+    this.sign = false;
+  return this;
+};
+
+BN.prototype.inspect = function inspect() {
+  return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
+};
+
+/*
+
+var zeros = [];
+var groupSizes = [];
+var groupBases = [];
+
+var s = '';
+var i = -1;
+while (++i < BN.wordSize) {
+  zeros[i] = s;
+  s += '0';
+}
+groupSizes[0] = 0;
+groupSizes[1] = 0;
+groupBases[0] = 0;
+groupBases[1] = 0;
+var base = 2 - 1;
+while (++base < 36 + 1) {
+  var groupSize = 0;
+  var groupBase = 1;
+  while (groupBase < (1 << BN.wordSize) / base) {
+    groupBase *= base;
+    groupSize += 1;
+  }
+  groupSizes[base] = groupSize;
+  groupBases[base] = groupBase;
+}
+
+*/
+
+var zeros = [
+  '',
+  '0',
+  '00',
+  '000',
+  '0000',
+  '00000',
+  '000000',
+  '0000000',
+  '00000000',
+  '000000000',
+  '0000000000',
+  '00000000000',
+  '000000000000',
+  '0000000000000',
+  '00000000000000',
+  '000000000000000',
+  '0000000000000000',
+  '00000000000000000',
+  '000000000000000000',
+  '0000000000000000000',
+  '00000000000000000000',
+  '000000000000000000000',
+  '0000000000000000000000',
+  '00000000000000000000000',
+  '000000000000000000000000',
+  '0000000000000000000000000'
+];
+
+var groupSizes = [
+  0, 0,
+  25, 16, 12, 11, 10, 9, 8,
+  8, 7, 7, 7, 7, 6, 6,
+  6, 6, 6, 6, 6, 5, 5,
+  5, 5, 5, 5, 5, 5, 5,
+  5, 5, 5, 5, 5, 5, 5
+];
+
+var groupBases = [
+  0, 0,
+  33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
+  43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
+  16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
+  6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
+  24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
+];
+
+BN.prototype.toString = function toString(base, padding) {
+  base = base || 10;
+  if (base === 16 || base === 'hex') {
+    var out = '';
+    var off = 0;
+    var padding = padding | 0 || 1;
+    var carry = 0;
+    for (var i = 0; i < this.length; i++) {
+      var w = this.words[i];
+      var word = (((w << off) | carry) & 0xffffff).toString(16);
+      carry = (w >>> (24 - off)) & 0xffffff;
+      if (carry !== 0 || i !== this.length - 1)
+        out = zeros[6 - word.length] + word + out;
+      else
+        out = word + out;
+      off += 2;
+      if (off >= 26) {
+        off -= 26;
+        i--;
+      }
+    }
+    if (carry !== 0)
+      out = carry.toString(16) + out;
+    while (out.length % padding !== 0)
+      out = '0' + out;
+    if (this.sign)
+      out = '-' + out;
+    return out;
+  } else if (base === (base | 0) && base >= 2 && base <= 36) {
+    // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
+    var groupSize = groupSizes[base];
+    // var groupBase = Math.pow(base, groupSize);
+    var groupBase = groupBases[base];
+    var out = '';
+    var c = this.clone();
+    c.sign = false;
+    while (c.cmpn(0) !== 0) {
+      var r = c.modn(groupBase).toString(base);
+      c = c.idivn(groupBase);
+
+      if (c.cmpn(0) !== 0)
+        out = zeros[groupSize - r.length] + r + out;
+      else
+        out = r + out;
+    }
+    if (this.cmpn(0) === 0)
+      out = '0' + out;
+    if (this.sign)
+      out = '-' + out;
+    return out;
+  } else {
+    assert(false, 'Base should be between 2 and 36');
+  }
+};
+
+BN.prototype.toJSON = function toJSON() {
+  return this.toString(16);
+};
+
+BN.prototype.toArray = function toArray(endian) {
+  this.strip();
+  var res = new Array(this.byteLength());
+  res[0] = 0;
+
+  var q = this.clone();
+  if (endian !== 'le') {
+    // Assume big-endian
+    for (var i = 0; q.cmpn(0) !== 0; i++) {
+      var b = q.andln(0xff);
+      q.ishrn(8);
+
+      res[res.length - i - 1] = b;
+    }
+  } else {
+    // Assume little-endian
+    for (var i = 0; q.cmpn(0) !== 0; i++) {
+      var b = q.andln(0xff);
+      q.ishrn(8);
+
+      res[i] = b;
+    }
+  }
+
+  return res;
+};
+
+if (Math.clz32) {
+  BN.prototype._countBits = function _countBits(w) {
+    return 32 - Math.clz32(w);
+  };
+} else {
+  BN.prototype._countBits = function _countBits(w) {
+    var t = w;
+    var r = 0;
+    if (t >= 0x1000) {
+      r += 13;
+      t >>>= 13;
+    }
+    if (t >= 0x40) {
+      r += 7;
+      t >>>= 7;
+    }
+    if (t >= 0x8) {
+      r += 4;
+      t >>>= 4;
+    }
+    if (t >= 0x02) {
+      r += 2;
+      t >>>= 2;
+    }
+    return r + t;
+  };
+}
+
+BN.prototype._zeroBits = function _zeroBits(w) {
+  // Short-cut
+  if (w === 0)
+    return 26;
+
+  var t = w;
+  var r = 0;
+  if ((t & 0x1fff) === 0) {
+    r += 13;
+    t >>>= 13;
+  }
+  if ((t & 0x7f) === 0) {
+    r += 7;
+    t >>>= 7;
+  }
+  if ((t & 0xf) === 0) {
+    r += 4;
+    t >>>= 4;
+  }
+  if ((t & 0x3) === 0) {
+    r += 2;
+    t >>>= 2;
+  }
+  if ((t & 0x1) === 0)
+    r++;
+  return r;
+};
+
+// Return number of used bits in a BN
+BN.prototype.bitLength = function bitLength() {
+  var hi = 0;
+  var w = this.words[this.length - 1];
+  var hi = this._countBits(w);
+  return (this.length - 1) * 26 + hi;
+};
+
+// Number of trailing zero bits
+BN.prototype.zeroBits = function zeroBits() {
+  if (this.cmpn(0) === 0)
+    return 0;
+
+  var r = 0;
+  for (var i = 0; i < this.length; i++) {
+    var b = this._zeroBits(this.words[i]);
+    r += b;
+    if (b !== 26)
+      break;
+  }
+  return r;
+};
+
+BN.prototype.byteLength = function byteLength() {
+  return Math.ceil(this.bitLength() / 8);
+};
+
+// Return negative clone of `this`
+BN.prototype.neg = function neg() {
+  if (this.cmpn(0) === 0)
+    return this.clone();
+
+  var r = this.clone();
+  r.sign = !this.sign;
+  return r;
+};
+
+
+// Or `num` with `this` in-place
+BN.prototype.ior = function ior(num) {
+  this.sign = this.sign || num.sign;
+
+  while (this.length < num.length)
+    this.words[this.length++] = 0;
+
+  for (var i = 0; i < num.length; i++)
+    this.words[i] = this.words[i] | num.words[i];
+
+  return this.strip();
+};
+
+
+// Or `num` with `this`
+BN.prototype.or = function or(num) {
+  if (this.length > num.length)
+    return this.clone().ior(num);
+  else
+    return num.clone().ior(this);
+};
+
+
+// And `num` with `this` in-place
+BN.prototype.iand = function iand(num) {
+  this.sign = this.sign && num.sign;
+
+  // b = min-length(num, this)
+  var b;
+  if (this.length > num.length)
+    b = num;
+  else
+    b = this;
+
+  for (var i = 0; i < b.length; i++)
+    this.words[i] = this.words[i] & num.words[i];
+
+  this.length = b.length;
+
+  return this.strip();
+};
+
+
+// And `num` with `this`
+BN.prototype.and = function and(num) {
+  if (this.length > num.length)
+    return this.clone().iand(num);
+  else
+    return num.clone().iand(this);
+};
+
+
+// Xor `num` with `this` in-place
+BN.prototype.ixor = function ixor(num) {
+  this.sign = this.sign || num.sign;
+
+  // a.length > b.length
+  var a;
+  var b;
+  if (this.length > num.length) {
+    a = this;
+    b = num;
+  } else {
+    a = num;
+    b = this;
+  }
+
+  for (var i = 0; i < b.length; i++)
+    this.words[i] = a.words[i] ^ b.words[i];
+
+  if (this !== a)
+    for (; i < a.length; i++)
+      this.words[i] = a.words[i];
+
+  this.length = a.length;
+
+  return this.strip();
+};
+
+
+// Xor `num` with `this`
+BN.prototype.xor = function xor(num) {
+  if (this.length > num.length)
+    return this.clone().ixor(num);
+  else
+    return num.clone().ixor(this);
+};
+
+
+// Set `bit` of `this`
+BN.prototype.setn = function setn(bit, val) {
+  assert(typeof bit === 'number' && bit >= 0);
+
+  var off = (bit / 26) | 0;
+  var wbit = bit % 26;
+
+  while (this.length <= off)
+    this.words[this.length++] = 0;
+
+  if (val)
+    this.words[off] = this.words[off] | (1 << wbit);
+  else
+    this.words[off] = this.words[off] & ~(1 << wbit);
+
+  return this.strip();
+};
+
+
+// Add `num` to `this` in-place
+BN.prototype.iadd = function iadd(num) {
+  // negative + positive
+  if (this.sign && !num.sign) {
+    this.sign = false;
+    var r = this.isub(num);
+    this.sign = !this.sign;
+    return this._normSign();
+
+  // positive + negative
+  } else if (!this.sign && num.sign) {
+    num.sign = false;
+    var r = this.isub(num);
+    num.sign = true;
+    return r._normSign();
+  }
+
+  // a.length > b.length
+  var a;
+  var b;
+  if (this.length > num.length) {
+    a = this;
+    b = num;
+  } else {
+    a = num;
+    b = this;
+  }
+
+  var carry = 0;
+  for (var i = 0; i < b.length; i++) {
+    var r = a.words[i] + b.words[i] + carry;
+    this.words[i] = r & 0x3ffffff;
+    carry = r >>> 26;
+  }
+  for (; carry !== 0 && i < a.length; i++) {
+    var r = a.words[i] + carry;
+    this.words[i] = r & 0x3ffffff;
+    carry = r >>> 26;
+  }
+
+  this.length = a.length;
+  if (carry !== 0) {
+    this.words[this.length] = carry;
+    this.length++;
+  // Copy the rest of the words
+  } else if (a !== this) {
+    for (; i < a.length; i++)
+      this.words[i] = a.words[i];
+  }
+
+  return this;
+};
+
+// Add `num` to `this`
+BN.prototype.add = function add(num) {
+  if (num.sign && !this.sign) {
+    num.sign = false;
+    var res = this.sub(num);
+    num.sign = true;
+    return res;
+  } else if (!num.sign && this.sign) {
+    this.sign = false;
+    var res = num.sub(this);
+    this.sign = true;
+    return res;
+  }
+
+  if (this.length > num.length)
+    return this.clone().iadd(num);
+  else
+    return num.clone().iadd(this);
+};
+
+// Subtract `num` from `this` in-place
+BN.prototype.isub = function isub(num) {
+  // this - (-num) = this + num
+  if (num.sign) {
+    num.sign = false;
+    var r = this.iadd(num);
+    num.sign = true;
+    return r._normSign();
+
+  // -this - num = -(this + num)
+  } else if (this.sign) {
+    this.sign = false;
+    this.iadd(num);
+    this.sign = true;
+    return this._normSign();
+  }
+
+  // At this point both numbers are positive
+  var cmp = this.cmp(num);
+
+  // Optimization - zeroify
+  if (cmp === 0) {
+    this.sign = false;
+    this.length = 1;
+    this.words[0] = 0;
+    return this;
+  }
+
+  // a > b
+  var a;
+  var b;
+  if (cmp > 0) {
+    a = this;
+    b = num;
+  } else {
+    a = num;
+    b = this;
+  }
+
+  var carry = 0;
+  for (var i = 0; i < b.length; i++) {
+    var r = a.words[i] - b.words[i] + carry;
+    carry = r >> 26;
+    this.words[i] = r & 0x3ffffff;
+  }
+  for (; carry !== 0 && i < a.length; i++) {
+    var r = a.words[i] + carry;
+    carry = r >> 26;
+    this.words[i] = r & 0x3ffffff;
+  }
+
+  // Copy rest of the words
+  if (carry === 0 && i < a.length && a !== this)
+    for (; i < a.length; i++)
+      this.words[i] = a.words[i];
+  this.length = Math.max(this.length, i);
+
+  if (a !== this)
+    this.sign = true;
+
+  return this.strip();
+};
+
+// Subtract `num` from `this`
+BN.prototype.sub = function sub(num) {
+  return this.clone().isub(num);
+};
+
+/*
+// NOTE: This could be potentionally used to generate loop-less multiplications
+function _genCombMulTo(alen, blen) {
+  var len = alen + blen - 1;
+  var src = [
+    'var a = this.words, b = num.words, o = out.words, c = 0, w, ' +
+        'mask = 0x3ffffff, shift = 0x4000000;',
+    'out.length = ' + len + ';'
+  ];
+  for (var k = 0; k < len; k++) {
+    var minJ = Math.max(0, k - alen + 1);
+    var maxJ = Math.min(k, blen - 1);
+
+    for (var j = minJ; j <= maxJ; j++) {
+      var i = k - j;
+      var mul = 'a[' + i + '] * b[' + j + ']';
+
+      if (j === minJ) {
+        src.push('w = ' + mul + ' + c;');
+        src.push('c = (w / shift) | 0;');
+      } else {
+        src.push('w += ' + mul + ';');
+        src.push('c += (w / shift) | 0;');
+      }
+      src.push('w &= mask;');
+    }
+    src.push('o[' + k + '] = w;');
+  }
+  src.push('if (c !== 0) {',
+           '  o[' + k + '] = c;',
+           '  out.length++;',
+           '}',
+           'return out;');
+
+  return src.join('\n');
+}
+*/
+
+BN.prototype._smallMulTo = function _smallMulTo(num, out) {
+  out.sign = num.sign !== this.sign;
+  out.length = this.length + num.length;
+
+  var carry = 0;
+  for (var k = 0; k < out.length - 1; k++) {
+    // Sum all words with the same `i + j = k` and accumulate `ncarry`,
+    // note that ncarry could be >= 0x3ffffff
+    var ncarry = carry >>> 26;
+    var rword = carry & 0x3ffffff;
+    var maxJ = Math.min(k, num.length - 1);
+    for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
+      var i = k - j;
+      var a = this.words[i] | 0;
+      var b = num.words[j] | 0;
+      var r = a * b;
+
+      var lo = r & 0x3ffffff;
+      ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
+      lo = (lo + rword) | 0;
+      rword = lo & 0x3ffffff;
+      ncarry = (ncarry + (lo >>> 26)) | 0;
+    }
+    out.words[k] = rword;
+    carry = ncarry;
+  }
+  if (carry !== 0) {
+    out.words[k] = carry;
+  } else {
+    out.length--;
+  }
+
+  return out.strip();
+};
+
+BN.prototype._bigMulTo = function _bigMulTo(num, out) {
+  out.sign = num.sign !== this.sign;
+  out.length = this.length + num.length;
+
+  var carry = 0;
+  var hncarry = 0;
+  for (var k = 0; k < out.length - 1; k++) {
+    // Sum all words with the same `i + j = k` and accumulate `ncarry`,
+    // note that ncarry could be >= 0x3ffffff
+    var ncarry = hncarry;
+    hncarry = 0;
+    var rword = carry & 0x3ffffff;
+    var maxJ = Math.min(k, num.length - 1);
+    for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
+      var i = k - j;
+      var a = this.words[i] | 0;
+      var b = num.words[j] | 0;
+      var r = a * b;
+
+      var lo = r & 0x3ffffff;
+      ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
+      lo = (lo + rword) | 0;
+      rword = lo & 0x3ffffff;
+      ncarry = (ncarry + (lo >>> 26)) | 0;
+
+      hncarry += ncarry >>> 26;
+      ncarry &= 0x3ffffff;
+    }
+    out.words[k] = rword;
+    carry = ncarry;
+    ncarry = hncarry;
+  }
+  if (carry !== 0) {
+    out.words[k] = carry;
+  } else {
+    out.length--;
+  }
+
+  return out.strip();
+};
+
+BN.prototype.mulTo = function mulTo(num, out) {
+  var res;
+  if (this.length + num.length < 63)
+    res = this._smallMulTo(num, out);
+  else
+    res = this._bigMulTo(num, out);
+  return res;
+};
+
+// Multiply `this` by `num`
+BN.prototype.mul = function mul(num) {
+  var out = new BN(null);
+  out.words = new Array(this.length + num.length);
+  return this.mulTo(num, out);
+};
+
+// In-place Multiplication
+BN.prototype.imul = function imul(num) {
+  if (this.cmpn(0) === 0 || num.cmpn(0) === 0) {
+    this.words[0] = 0;
+    this.length = 1;
+    return this;
+  }
+
+  var tlen = this.length;
+  var nlen = num.length;
+
+  this.sign = num.sign !== this.sign;
+  this.length = this.length + num.length;
+  this.words[this.length - 1] = 0;
+
+  for (var k = this.length - 2; k >= 0; k--) {
+    // Sum all words with the same `i + j = k` and accumulate `carry`,
+    // note that carry could be >= 0x3ffffff
+    var carry = 0;
+    var rword = 0;
+    var maxJ = Math.min(k, nlen - 1);
+    for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) {
+      var i = k - j;
+      var a = this.words[i];
+      var b = num.words[j];
+      var r = a * b;
+
+      var lo = r & 0x3ffffff;
+      carry += (r / 0x4000000) | 0;
+      lo += rword;
+      rword = lo & 0x3ffffff;
+      carry += lo >>> 26;
+    }
+    this.words[k] = rword;
+    this.words[k + 1] += carry;
+    carry = 0;
+  }
+
+  // Propagate overflows
+  var carry = 0;
+  for (var i = 1; i < this.length; i++) {
+    var w = this.words[i] + carry;
+    this.words[i] = w & 0x3ffffff;
+    carry = w >>> 26;
+  }
+
+  return this.strip();
+};
+
+BN.prototype.imuln = function imuln(num) {
+  assert(typeof num === 'number');
+
+  // Carry
+  var carry = 0;
+  for (var i = 0; i < this.length; i++) {
+    var w = this.words[i] * num;
+    var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
+    carry >>= 26;
+    carry += (w / 0x4000000) | 0;
+    // NOTE: lo is 27bit maximum
+    carry += lo >>> 26;
+    this.words[i] = lo & 0x3ffffff;
+  }
+
+  if (carry !== 0) {
+    this.words[i] = carry;
+    this.length++;
+  }
+
+  return this;
+};
+
+BN.prototype.muln = function muln(num) {
+  return this.clone().imuln(num);
+};
+
+// `this` * `this`
+BN.prototype.sqr = function sqr() {
+  return this.mul(this);
+};
+
+// `this` * `this` in-place
+BN.prototype.isqr = function isqr() {
+  return this.mul(this);
+};
+
+// Shift-left in-place
+BN.prototype.ishln = function ishln(bits) {
+  assert(typeof bits === 'number' && bits >= 0);
+  var r = bits % 26;
+  var s = (bits - r) / 26;
+  var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
+
+  if (r !== 0) {
+    var carry = 0;
+    for (var i = 0; i < this.length; i++) {
+      var newCarry = this.words[i] & carryMask;
+      var c = (this.words[i] - newCarry) << r;
+      this.words[i] = c | carry;
+      carry = newCarry >>> (26 - r);
+    }
+    if (carry) {
+      this.words[i] = carry;
+      this.length++;
+    }
+  }
+
+  if (s !== 0) {
+    for (var i = this.length - 1; i >= 0; i--)
+      this.words[i + s] = this.words[i];
+    for (var i = 0; i < s; i++)
+      this.words[i] = 0;
+    this.length += s;
+  }
+
+  return this.strip();
+};
+
+// Shift-right in-place
+// NOTE: `hint` is a lowest bit before trailing zeroes
+// NOTE: if `extended` is present - it will be filled with destroyed bits
+BN.prototype.ishrn = function ishrn(bits, hint, extended) {
+  assert(typeof bits === 'number' && bits >= 0);
+  var h;
+  if (hint)
+    h = (hint - (hint % 26)) / 26;
+  else
+    h = 0;
+
+  var r = bits % 26;
+  var s = Math.min((bits - r) / 26, this.length);
+  var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
+  var maskedWords = extended;
+
+  h -= s;
+  h = Math.max(0, h);
+
+  // Extended mode, copy masked part
+  if (maskedWords) {
+    for (var i = 0; i < s; i++)
+      maskedWords.words[i] = this.words[i];
+    maskedWords.length = s;
+  }
+
+  if (s === 0) {
+    // No-op, we should not move anything at all
+  } else if (this.length > s) {
+    this.length -= s;
+    for (var i = 0; i < this.length; i++)
+      this.words[i] = this.words[i + s];
+  } else {
+    this.words[0] = 0;
+    this.length = 1;
+  }
+
+  var carry = 0;
+  for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
+    var word = this.words[i];
+    this.words[i] = (carry << (26 - r)) | (word >>> r);
+    carry = word & mask;
+  }
+
+  // Push carried bits as a mask
+  if (maskedWords && carry !== 0)
+    maskedWords.words[maskedWords.length++] = carry;
+
+  if (this.length === 0) {
+    this.words[0] = 0;
+    this.length = 1;
+  }
+
+  this.strip();
+
+  return this;
+};
+
+// Shift-left
+BN.prototype.shln = function shln(bits) {
+  return this.clone().ishln(bits);
+};
+
+// Shift-right
+BN.prototype.shrn = function shrn(bits) {
+  return this.clone().ishrn(bits);
+};
+
+// Test if n bit is set
+BN.prototype.testn = function testn(bit) {
+  assert(typeof bit === 'number' && bit >= 0);
+  var r = bit % 26;
+  var s = (bit - r) / 26;
+  var q = 1 << r;
+
+  // Fast case: bit is much higher than all existing words
+  if (this.length <= s) {
+    return false;
+  }
+
+  // Check bit and return
+  var w = this.words[s];
+
+  return !!(w & q);
+};
+
+// Return only lowers bits of number (in-place)
+BN.prototype.imaskn = function imaskn(bits) {
+  assert(typeof bits === 'number' && bits >= 0);
+  var r = bits % 26;
+  var s = (bits - r) / 26;
+
+  assert(!this.sign, 'imaskn works only with positive numbers');
+
+  if (r !== 0)
+    s++;
+  this.length = Math.min(s, this.length);
+
+  if (r !== 0) {
+    var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
+    this.words[this.length - 1] &= mask;
+  }
+
+  return this.strip();
+};
+
+// Return only lowers bits of number
+BN.prototype.maskn = function maskn(bits) {
+  return this.clone().imaskn(bits);
+};
+
+// Add plain number `num` to `this`
+BN.prototype.iaddn = function iaddn(num) {
+  assert(typeof num === 'number');
+  if (num < 0)
+    return this.isubn(-num);
+
+  // Possible sign change
+  if (this.sign) {
+    if (this.length === 1 && this.words[0] < num) {
+      this.words[0] = num - this.words[0];
+      this.sign = false;
+      return this;
+    }
+
+    this.sign = false;
+    this.isubn(num);
+    this.sign = true;
+    return this;
+  }
+
+  // Add without checks
+  return this._iaddn(num);
+};
+
+BN.prototype._iaddn = function _iaddn(num) {
+  this.words[0] += num;
+
+  // Carry
+  for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
+    this.words[i] -= 0x4000000;
+    if (i === this.length - 1)
+      this.words[i + 1] = 1;
+    else
+      this.words[i + 1]++;
+  }
+  this.length = Math.max(this.length, i + 1);
+
+  return this;
+};
+
+// Subtract plain number `num` from `this`
+BN.prototype.isubn = function isubn(num) {
+  assert(typeof num === 'number');
+  if (num < 0)
+    return this.iaddn(-num);
+
+  if (this.sign) {
+    this.sign = false;
+    this.iaddn(num);
+    this.sign = true;
+    return this;
+  }
+
+  this.words[0] -= num;
+
+  // Carry
+  for (var i = 0; i < this.length && this.words[i] < 0; i++) {
+    this.words[i] += 0x4000000;
+    this.words[i + 1] -= 1;
+  }
+
+  return this.strip();
+};
+
+BN.prototype.addn = function addn(num) {
+  return this.clone().iaddn(num);
+};
+
+BN.prototype.subn = function subn(num) {
+  return this.clone().isubn(num);
+};
+
+BN.prototype.iabs = function iabs() {
+  this.sign = false;
+
+  return this;
+};
+
+BN.prototype.abs = function abs() {
+  return this.clone().iabs();
+};
+
+BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
+  // Bigger storage is needed
+  var len = num.length + shift;
+  var i;
+  if (this.words.length < len) {
+    var t = new Array(len);
+    for (var i = 0; i < this.length; i++)
+      t[i] = this.words[i];
+    this.words = t;
+  } else {
+    i = this.length;
+  }
+
+  // Zeroify rest
+  this.length = Math.max(this.length, len);
+  for (; i < this.length; i++)
+    this.words[i] = 0;
+
+  var carry = 0;
+  for (var i = 0; i < num.length; i++) {
+    var w = this.words[i + shift] + carry;
+    var right = num.words[i] * mul;
+    w -= right & 0x3ffffff;
+    carry = (w >> 26) - ((right / 0x4000000) | 0);
+    this.words[i + shift] = w & 0x3ffffff;
+  }
+  for (; i < this.length - shift; i++) {
+    var w = this.words[i + shift] + carry;
+    carry = w >> 26;
+    this.words[i + shift] = w & 0x3ffffff;
+  }
+
+  if (carry === 0)
+    return this.strip();
+
+  // Subtraction overflow
+  assert(carry === -1);
+  carry = 0;
+  for (var i = 0; i < this.length; i++) {
+    var w = -this.words[i] + carry;
+    carry = w >> 26;
+    this.words[i] = w & 0x3ffffff;
+  }
+  this.sign = true;
+
+  return this.strip();
+};
+
+BN.prototype._wordDiv = function _wordDiv(num, mode) {
+  var shift = this.length - num.length;
+
+  var a = this.clone();
+  var b = num;
+
+  // Normalize
+  var bhi = b.words[b.length - 1];
+  var bhiBits = this._countBits(bhi);
+  shift = 26 - bhiBits;
+  if (shift !== 0) {
+    b = b.shln(shift);
+    a.ishln(shift);
+    bhi = b.words[b.length - 1];
+  }
+
+  // Initialize quotient
+  var m = a.length - b.length;
+  var q;
+
+  if (mode !== 'mod') {
+    q = new BN(null);
+    q.length = m + 1;
+    q.words = new Array(q.length);
+    for (var i = 0; i < q.length; i++)
+      q.words[i] = 0;
+  }
+
+  var diff = a.clone()._ishlnsubmul(b, 1, m);
+  if (!diff.sign) {
+    a = diff;
+    if (q)
+      q.words[m] = 1;
+  }
+
+  for (var j = m - 1; j >= 0; j--) {
+    var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1];
+
+    // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
+    // (0x7ffffff)
+    qj = Math.min((qj / bhi) | 0, 0x3ffffff);
+
+    a._ishlnsubmul(b, qj, j);
+    while (a.sign) {
+      qj--;
+      a.sign = false;
+      a._ishlnsubmul(b, 1, j);
+      if (a.cmpn(0) !== 0)
+        a.sign = !a.sign;
+    }
+    if (q)
+      q.words[j] = qj;
+  }
+  if (q)
+    q.strip();
+  a.strip();
+
+  // Denormalize
+  if (mode !== 'div' && shift !== 0)
+    a.ishrn(shift);
+  return { div: q ? q : null, mod: a };
+};
+
+BN.prototype.divmod = function divmod(num, mode) {
+  assert(num.cmpn(0) !== 0);
+
+  if (this.sign && !num.sign) {
+    var res = this.neg().divmod(num, mode);
+    var div;
+    var mod;
+    if (mode !== 'mod')
+      div = res.div.neg();
+    if (mode !== 'div')
+      mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod);
+    return {
+      div: div,
+      mod: mod
+    };
+  } else if (!this.sign && num.sign) {
+    var res = this.divmod(num.neg(), mode);
+    var div;
+    if (mode !== 'mod')
+      div = res.div.neg();
+    return { div: div, mod: res.mod };
+  } else if (this.sign && num.sign) {
+    return this.neg().divmod(num.neg(), mode);
+  }
+
+  // Both numbers are positive at this point
+
+  // Strip both numbers to approximate shift value
+  if (num.length > this.length || this.cmp(num) < 0)
+    return { div: new BN(0), mod: this };
+
+  // Very short reduction
+  if (num.length === 1) {
+    if (mode === 'div')
+      return { div: this.divn(num.words[0]), mod: null };
+    else if (mode === 'mod')
+      return { div: null, mod: new BN(this.modn(num.words[0])) };
+    return {
+      div: this.divn(num.words[0]),
+      mod: new BN(this.modn(num.words[0]))
+    };
+  }
+
+  return this._wordDiv(num, mode);
+};
+
+// Find `this` / `num`
+BN.prototype.div = function div(num) {
+  return this.divmod(num, 'div').div;
+};
+
+// Find `this` % `num`
+BN.prototype.mod = function mod(num) {
+  return this.divmod(num, 'mod').mod;
+};
+
+// Find Round(`this` / `num`)
+BN.prototype.divRound = function divRound(num) {
+  var dm = this.divmod(num);
+
+  // Fast case - exact division
+  if (dm.mod.cmpn(0) === 0)
+    return dm.div;
+
+  var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod;
+
+  var half = num.shrn(1);
+  var r2 = num.andln(1);
+  var cmp = mod.cmp(half);
+
+  // Round down
+  if (cmp < 0 || r2 === 1 && cmp === 0)
+    return dm.div;
+
+  // Round up
+  return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1);
+};
+
+BN.prototype.modn = function modn(num) {
+  assert(num <= 0x3ffffff);
+  var p = (1 << 26) % num;
+
+  var acc = 0;
+  for (var i = this.length - 1; i >= 0; i--)
+    acc = (p * acc + this.words[i]) % num;
+
+  return acc;
+};
+
+// In-place division by number
+BN.prototype.idivn = function idivn(num) {
+  assert(num <= 0x3ffffff);
+
+  var carry = 0;
+  for (var i = this.length - 1; i >= 0; i--) {
+    var w = this.words[i] + carry * 0x4000000;
+    this.words[i] = (w / num) | 0;
+    carry = w % num;
+  }
+
+  return this.strip();
+};
+
+BN.prototype.divn = function divn(num) {
+  return this.clone().idivn(num);
+};
+
+BN.prototype.egcd = function egcd(p) {
+  assert(!p.sign);
+  assert(p.cmpn(0) !== 0);
+
+  var x = this;
+  var y = p.clone();
+
+  if (x.sign)
+    x = x.mod(p);
+  else
+    x = x.clone();
+
+  // A * x + B * y = x
+  var A = new BN(1);
+  var B = new BN(0);
+
+  // C * x + D * y = y
+  var C = new BN(0);
+  var D = new BN(1);
+
+  var g = 0;
+
+  while (x.isEven() && y.isEven()) {
+    x.ishrn(1);
+    y.ishrn(1);
+    ++g;
+  }
+
+  var yp = y.clone();
+  var xp = x.clone();
+
+  while (x.cmpn(0) !== 0) {
+    while (x.isEven()) {
+      x.ishrn(1);
+      if (A.isEven() && B.isEven()) {
+        A.ishrn(1);
+        B.ishrn(1);
+      } else {
+        A.iadd(yp).ishrn(1);
+        B.isub(xp).ishrn(1);
+      }
+    }
+
+    while (y.isEven()) {
+      y.ishrn(1);
+      if (C.isEven() && D.isEven()) {
+        C.ishrn(1);
+        D.ishrn(1);
+      } else {
+        C.iadd(yp).ishrn(1);
+        D.isub(xp).ishrn(1);
+      }
+    }
+
+    if (x.cmp(y) >= 0) {
+      x.isub(y);
+      A.isub(C);
+      B.isub(D);
+    } else {
+      y.isub(x);
+      C.isub(A);
+      D.isub(B);
+    }
+  }
+
+  return {
+    a: C,
+    b: D,
+    gcd: y.ishln(g)
+  };
+};
+
+// This is reduced incarnation of the binary EEA
+// above, designated to invert members of the
+// _prime_ fields F(p) at a maximal speed
+BN.prototype._invmp = function _invmp(p) {
+  assert(!p.sign);
+  assert(p.cmpn(0) !== 0);
+
+  var a = this;
+  var b = p.clone();
+
+  if (a.sign)
+    a = a.mod(p);
+  else
+    a = a.clone();
+
+  var x1 = new BN(1);
+  var x2 = new BN(0);
+
+  var delta = b.clone();
+
+  while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
+    while (a.isEven()) {
+      a.ishrn(1);
+      if (x1.isEven())
+        x1.ishrn(1);
+      else
+        x1.iadd(delta).ishrn(1);
+    }
+    while (b.isEven()) {
+      b.ishrn(1);
+      if (x2.isEven())
+        x2.ishrn(1);
+      else
+        x2.iadd(delta).ishrn(1);
+    }
+    if (a.cmp(b) >= 0) {
+      a.isub(b);
+      x1.isub(x2);
+    } else {
+      b.isub(a);
+      x2.isub(x1);
+    }
+  }
+  if (a.cmpn(1) === 0)
+    return x1;
+  else
+    return x2;
+};
+
+BN.prototype.gcd = function gcd(num) {
+  if (this.cmpn(0) === 0)
+    return num.clone();
+  if (num.cmpn(0) === 0)
+    return this.clone();
+
+  var a = this.clone();
+  var b = num.clone();
+  a.sign = false;
+  b.sign = false;
+
+  // Remove common factor of two
+  for (var shift = 0; a.isEven() && b.isEven(); shift++) {
+    a.ishrn(1);
+    b.ishrn(1);
+  }
+
+  do {
+    while (a.isEven())
+      a.ishrn(1);
+    while (b.isEven())
+      b.ishrn(1);
+
+    var r = a.cmp(b);
+    if (r < 0) {
+      // Swap `a` and `b` to make `a` always bigger than `b`
+      var t = a;
+      a = b;
+      b = t;
+    } else if (r === 0 || b.cmpn(1) === 0) {
+      break;
+    }
+
+    a.isub(b);
+  } while (true);
+
+  return b.ishln(shift);
+};
+
+// Invert number in the field F(num)
+BN.prototype.invm = function invm(num) {
+  return this.egcd(num).a.mod(num);
+};
+
+BN.prototype.isEven = function isEven() {
+  return (this.words[0] & 1) === 0;
+};
+
+BN.prototype.isOdd = function isOdd() {
+  return (this.words[0] & 1) === 1;
+};
+
+// And first word and num
+BN.prototype.andln = function andln(num) {
+  return this.words[0] & num;
+};
+
+// Increment at the bit position in-line
+BN.prototype.bincn = function bincn(bit) {
+  assert(typeof bit === 'number');
+  var r = bit % 26;
+  var s = (bit - r) / 26;
+  var q = 1 << r;
+
+  // Fast case: bit is much higher than all existing words
+  if (this.length <= s) {
+    for (var i = this.length; i < s + 1; i++)
+      this.words[i] = 0;
+    this.words[s] |= q;
+    this.length = s + 1;
+    return this;
+  }
+
+  // Add bit and propagate, if needed
+  var carry = q;
+  for (var i = s; carry !== 0 && i < this.length; i++) {
+    var w = this.words[i];
+    w += carry;
+    carry = w >>> 26;
+    w &= 0x3ffffff;
+    this.words[i] = w;
+  }
+  if (carry !== 0) {
+    this.words[i] = carry;
+    this.length++;
+  }
+  return this;
+};
+
+BN.prototype.cmpn = function cmpn(num) {
+  var sign = num < 0;
+  if (sign)
+    num = -num;
+
+  if (this.sign && !sign)
+    return -1;
+  else if (!this.sign && sign)
+    return 1;
+
+  num &= 0x3ffffff;
+  this.strip();
+
+  var res;
+  if (this.length > 1) {
+    res = 1;
+  } else {
+    var w = this.words[0];
+    res = w === num ? 0 : w < num ? -1 : 1;
+  }
+  if (this.sign)
+    res = -res;
+  return res;
+};
+
+// Compare two numbers and return:
+// 1 - if `this` > `num`
+// 0 - if `this` == `num`
+// -1 - if `this` < `num`
+BN.prototype.cmp = function cmp(num) {
+  if (this.sign && !num.sign)
+    return -1;
+  else if (!this.sign && num.sign)
+    return 1;
+
+  var res = this.ucmp(num);
+  if (this.sign)
+    return -res;
+  else
+    return res;
+};
+
+// Unsigned comparison
+BN.prototype.ucmp = function ucmp(num) {
+  // At this point both numbers have the same sign
+  if (this.length > num.length)
+    return 1;
+  else if (this.length < num.length)
+    return -1;
+
+  var res = 0;
+  for (var i = this.length - 1; i >= 0; i--) {
+    var a = this.words[i];
+    var b = num.words[i];
+
+    if (a === b)
+      continue;
+    if (a < b)
+      res = -1;
+    else if (a > b)
+      res = 1;
+    break;
+  }
+  return res;
+};
+
+//
+// A reduce context, could be using montgomery or something better, depending
+// on the `m` itself.
+//
+BN.red = function red(num) {
+  return new Red(num);
+};
+
+BN.prototype.toRed = function toRed(ctx) {
+  assert(!this.red, 'Already a number in reduction context');
+  assert(!this.sign, 'red works only with positives');
+  return ctx.convertTo(this)._forceRed(ctx);
+};
+
+BN.prototype.fromRed = function fromRed() {
+  assert(this.red, 'fromRed works only with numbers in reduction context');
+  return this.red.convertFrom(this);
+};
+
+BN.prototype._forceRed = function _forceRed(ctx) {
+  this.red = ctx;
+  return this;
+};
+
+BN.prototype.forceRed = function forceRed(ctx) {
+  assert(!this.red, 'Already a number in reduction context');
+  return this._forceRed(ctx);
+};
+
+BN.prototype.redAdd = function redAdd(num) {
+  assert(this.red, 'redAdd works only with red numbers');
+  return this.red.add(this, num);
+};
+
+BN.prototype.redIAdd = function redIAdd(num) {
+  assert(this.red, 'redIAdd works only with red numbers');
+  return this.red.iadd(this, num);
+};
+
+BN.prototype.redSub = function redSub(num) {
+  assert(this.red, 'redSub works only with red numbers');
+  return this.red.sub(this, num);
+};
+
+BN.prototype.redISub = function redISub(num) {
+  assert(this.red, 'redISub works only with red numbers');
+  return this.red.isub(this, num);
+};
+
+BN.prototype.redShl = function redShl(num) {
+  assert(this.red, 'redShl works only with red numbers');
+  return this.red.shl(this, num);
+};
+
+BN.prototype.redMul = function redMul(num) {
+  assert(this.red, 'redMul works only with red numbers');
+  this.red._verify2(this, num);
+  return this.red.mul(this, num);
+};
+
+BN.prototype.redIMul = function redIMul(num) {
+  assert(this.red, 'redMul works only with red numbers');
+  this.red._verify2(this, num);
+  return this.red.imul(this, num);
+};
+
+BN.prototype.redSqr = function redSqr() {
+  assert(this.red, 'redSqr works only with red numbers');
+  this.red._verify1(this);
+  return this.red.sqr(this);
+};
+
+BN.prototype.redISqr = function redISqr() {
+  assert(this.red, 'redISqr works only with red numbers');
+  this.red._verify1(this);
+  return this.red.isqr(this);
+};
+
+// Square root over p
+BN.prototype.redSqrt = function redSqrt() {
+  assert(this.red, 'redSqrt works only with red numbers');
+  this.red._verify1(this);
+  return this.red.sqrt(this);
+};
+
+BN.prototype.redInvm = function redInvm() {
+  assert(this.red, 'redInvm works only with red numbers');
+  this.red._verify1(this);
+  return this.red.invm(this);
+};
+
+// Return negative clone of `this` % `red modulo`
+BN.prototype.redNeg = function redNeg() {
+  assert(this.red, 'redNeg works only with red numbers');
+  this.red._verify1(this);
+  return this.red.neg(this);
+};
+
+BN.prototype.redPow = function redPow(num) {
+  assert(this.red && !num.red, 'redPow(normalNum)');
+  this.red._verify1(this);
+  return this.red.pow(this, num);
+};
+
+// Prime numbers with efficient reduction
+var primes = {
+  k256: null,
+  p224: null,
+  p192: null,
+  p25519: null
+};
+
+// Pseudo-Mersenne prime
+function MPrime(name, p) {
+  // P = 2 ^ N - K
+  this.name = name;
+  this.p = new BN(p, 16);
+  this.n = this.p.bitLength();
+  this.k = new BN(1).ishln(this.n).isub(this.p);
+
+  this.tmp = this._tmp();
+}
+
+MPrime.prototype._tmp = function _tmp() {
+  var tmp = new BN(null);
+  tmp.words = new Array(Math.ceil(this.n / 13));
+  return tmp;
+};
+
+MPrime.prototype.ireduce = function ireduce(num) {
+  // Assumes that `num` is less than `P^2`
+  // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
+  var r = num;
+  var rlen;
+
+  do {
+    this.split(r, this.tmp);
+    r = this.imulK(r);
+    r = r.iadd(this.tmp);
+    rlen = r.bitLength();
+  } while (rlen > this.n);
+
+  var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
+  if (cmp === 0) {
+    r.words[0] = 0;
+    r.length = 1;
+  } else if (cmp > 0) {
+    r.isub(this.p);
+  } else {
+    r.strip();
+  }
+
+  return r;
+};
+
+MPrime.prototype.split = function split(input, out) {
+  input.ishrn(this.n, 0, out);
+};
+
+MPrime.prototype.imulK = function imulK(num) {
+  return num.imul(this.k);
+};
+
+function K256() {
+  MPrime.call(
+    this,
+    'k256',
+    'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
+}
+inherits(K256, MPrime);
+
+K256.prototype.split = function split(input, output) {
+  // 256 = 9 * 26 + 22
+  var mask = 0x3fffff;
+
+  var outLen = Math.min(input.length, 9);
+  for (var i = 0; i < outLen; i++)
+    output.words[i] = input.words[i];
+  output.length = outLen;
+
+  if (input.length <= 9) {
+    input.words[0] = 0;
+    input.length = 1;
+    return;
+  }
+
+  // Shift by 9 limbs
+  var prev = input.words[9];
+  output.words[output.length++] = prev & mask;
+
+  for (var i = 10; i < input.length; i++) {
+    var next = input.words[i];
+    input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
+    prev = next;
+  }
+  input.words[i - 10] = prev >>> 22;
+  input.length -= 9;
+};
+
+K256.prototype.imulK = function imulK(num) {
+  // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
+  num.words[num.length] = 0;
+  num.words[num.length + 1] = 0;
+  num.length += 2;
+
+  // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
+  var hi;
+  var lo = 0;
+  for (var i = 0; i < num.length; i++) {
+    var w = num.words[i];
+    hi = w * 0x40;
+    lo += w * 0x3d1;
+    hi += (lo / 0x4000000) | 0;
+    lo &= 0x3ffffff;
+
+    num.words[i] = lo;
+
+    lo = hi;
+  }
+
+  // Fast length reduction
+  if (num.words[num.length - 1] === 0) {
+    num.length--;
+    if (num.words[num.length - 1] === 0)
+      num.length--;
+  }
+  return num;
+};
+
+function P224() {
+  MPrime.call(
+    this,
+    'p224',
+    'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
+}
+inherits(P224, MPrime);
+
+function P192() {
+  MPrime.call(
+    this,
+    'p192',
+    'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
+}
+inherits(P192, MPrime);
+
+function P25519() {
+  // 2 ^ 255 - 19
+  MPrime.call(
+    this,
+    '25519',
+    '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
+}
+inherits(P25519, MPrime);
+
+P25519.prototype.imulK = function imulK(num) {
+  // K = 0x13
+  var carry = 0;
+  for (var i = 0; i < num.length; i++) {
+    var hi = num.words[i] * 0x13 + carry;
+    var lo = hi & 0x3ffffff;
+    hi >>>= 26;
+
+    num.words[i] = lo;
+    carry = hi;
+  }
+  if (carry !== 0)
+    num.words[num.length++] = carry;
+  return num;
+};
+
+// Exported mostly for testing purposes, use plain name instead
+BN._prime = function prime(name) {
+  // Cached version of prime
+  if (primes[name])
+    return primes[name];
+
+  var prime;
+  if (name === 'k256')
+    prime = new K256();
+  else if (name === 'p224')
+    prime = new P224();
+  else if (name === 'p192')
+    prime = new P192();
+  else if (name === 'p25519')
+    prime = new P25519();
+  else
+    throw new Error('Unknown prime ' + name);
+  primes[name] = prime;
+
+  return prime;
+};
+
+//
+// Base reduction engine
+//
+function Red(m) {
+  if (typeof m === 'string') {
+    var prime = BN._prime(m);
+    this.m = prime.p;
+    this.prime = prime;
+  } else {
+    this.m = m;
+    this.prime = null;
+  }
+}
+
+Red.prototype._verify1 = function _verify1(a) {
+  assert(!a.sign, 'red works only with positives');
+  assert(a.red, 'red works only with red numbers');
+};
+
+Red.prototype._verify2 = function _verify2(a, b) {
+  assert(!a.sign && !b.sign, 'red works only with positives');
+  assert(a.red && a.red === b.red,
+         'red works only with red numbers');
+};
+
+Red.prototype.imod = function imod(a) {
+  if (this.prime)
+    return this.prime.ireduce(a)._forceRed(this);
+  return a.mod(this.m)._forceRed(this);
+};
+
+Red.prototype.neg = function neg(a) {
+  var r = a.clone();
+  r.sign = !r.sign;
+  return r.iadd(this.m)._forceRed(this);
+};
+
+Red.prototype.add = function add(a, b) {
+  this._verify2(a, b);
+
+  var res = a.add(b);
+  if (res.cmp(this.m) >= 0)
+    res.isub(this.m);
+  return res._forceRed(this);
+};
+
+Red.prototype.iadd = function iadd(a, b) {
+  this._verify2(a, b);
+
+  var res = a.iadd(b);
+  if (res.cmp(this.m) >= 0)
+    res.isub(this.m);
+  return res;
+};
+
+Red.prototype.sub = function sub(a, b) {
+  this._verify2(a, b);
+
+  var res = a.sub(b);
+  if (res.cmpn(0) < 0)
+    res.iadd(this.m);
+  return res._forceRed(this);
+};
+
+Red.prototype.isub = function isub(a, b) {
+  this._verify2(a, b);
+
+  var res = a.isub(b);
+  if (res.cmpn(0) < 0)
+    res.iadd(this.m);
+  return res;
+};
+
+Red.prototype.shl = function shl(a, num) {
+  this._verify1(a);
+  return this.imod(a.shln(num));
+};
+
+Red.prototype.imul = function imul(a, b) {
+  this._verify2(a, b);
+  return this.imod(a.imul(b));
+};
+
+Red.prototype.mul = function mul(a, b) {
+  this._verify2(a, b);
+  return this.imod(a.mul(b));
+};
+
+Red.prototype.isqr = function isqr(a) {
+  return this.imul(a, a);
+};
+
+Red.prototype.sqr = function sqr(a) {
+  return this.mul(a, a);
+};
+
+Red.prototype.sqrt = function sqrt(a) {
+  if (a.cmpn(0) === 0)
+    return a.clone();
+
+  var mod3 = this.m.andln(3);
+  assert(mod3 % 2 === 1);
+
+  // Fast case
+  if (mod3 === 3) {
+    var pow = this.m.add(new BN(1)).ishrn(2);
+    var r = this.pow(a, pow);
+    return r;
+  }
+
+  // Tonelli-Shanks algorithm (Totally unoptimized and slow)
+  //
+  // Find Q and S, that Q * 2 ^ S = (P - 1)
+  var q = this.m.subn(1);
+  var s = 0;
+  while (q.cmpn(0) !== 0 && q.andln(1) === 0) {
+    s++;
+    q.ishrn(1);
+  }
+  assert(q.cmpn(0) !== 0);
+
+  var one = new BN(1).toRed(this);
+  var nOne = one.redNeg();
+
+  // Find quadratic non-residue
+  // NOTE: Max is such because of generalized Riemann hypothesis.
+  var lpow = this.m.subn(1).ishrn(1);
+  var z = this.m.bitLength();
+  z = new BN(2 * z * z).toRed(this);
+  while (this.pow(z, lpow).cmp(nOne) !== 0)
+    z.redIAdd(nOne);
+
+  var c = this.pow(z, q);
+  var r = this.pow(a, q.addn(1).ishrn(1));
+  var t = this.pow(a, q);
+  var m = s;
+  while (t.cmp(one) !== 0) {
+    var tmp = t;
+    for (var i = 0; tmp.cmp(one) !== 0; i++)
+      tmp = tmp.redSqr();
+    assert(i < m);
+    var b = this.pow(c, new BN(1).ishln(m - i - 1));
+
+    r = r.redMul(b);
+    c = b.redSqr();
+    t = t.redMul(c);
+    m = i;
+  }
+
+  return r;
+};
+
+Red.prototype.invm = function invm(a) {
+  var inv = a._invmp(this.m);
+  if (inv.sign) {
+    inv.sign = false;
+    return this.imod(inv).redNeg();
+  } else {
+    return this.imod(inv);
+  }
+};
+
+Red.prototype.pow = function pow(a, num) {
+  var w = [];
+
+  if (num.cmpn(0) === 0)
+    return new BN(1);
+
+  var q = num.clone();
+
+  while (q.cmpn(0) !== 0) {
+    w.push(q.andln(1));
+    q.ishrn(1);
+  }
+
+  // Skip leading zeroes
+  var res = a;
+  for (var i = 0; i < w.length; i++, res = this.sqr(res))
+    if (w[i] !== 0)
+      break;
+
+  if (++i < w.length) {
+    for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) {
+      if (w[i] === 0)
+        continue;
+      res = this.mul(res, q);
+    }
+  }
+
+  return res;
+};
+
+Red.prototype.convertTo = function convertTo(num) {
+  var r = num.mod(this.m);
+  if (r === num)
+    return r.clone();
+  else
+    return r;
+};
+
+Red.prototype.convertFrom = function convertFrom(num) {
+  var res = num.clone();
+  res.red = null;
+  return res;
+};
+
+//
+// Montgomery method engine
+//
+
+BN.mont = function mont(num) {
+  return new Mont(num);
+};
+
+function Mont(m) {
+  Red.call(this, m);
+
+  this.shift = this.m.bitLength();
+  if (this.shift % 26 !== 0)
+    this.shift += 26 - (this.shift % 26);
+  this.r = new BN(1).ishln(this.shift);
+  this.r2 = this.imod(this.r.sqr());
+  this.rinv = this.r._invmp(this.m);
+
+  this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
+  this.minv.sign = true;
+  this.minv = this.minv.mod(this.r);
+}
+inherits(Mont, Red);
+
+Mont.prototype.convertTo = function convertTo(num) {
+  return this.imod(num.shln(this.shift));
+};
+
+Mont.prototype.convertFrom = function convertFrom(num) {
+  var r = this.imod(num.mul(this.rinv));
+  r.red = null;
+  return r;
+};
+
+Mont.prototype.imul = function imul(a, b) {
+  if (a.cmpn(0) === 0 || b.cmpn(0) === 0) {
+    a.words[0] = 0;
+    a.length = 1;
+    return a;
+  }
+
+  var t = a.imul(b);
+  var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
+  var u = t.isub(c).ishrn(this.shift);
+  var res = u;
+  if (u.cmp(this.m) >= 0)
+    res = u.isub(this.m);
+  else if (u.cmpn(0) < 0)
+    res = u.iadd(this.m);
+
+  return res._forceRed(this);
+};
+
+Mont.prototype.mul = function mul(a, b) {
+  if (a.cmpn(0) === 0 || b.cmpn(0) === 0)
+    return new BN(0)._forceRed(this);
+
+  var t = a.mul(b);
+  var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
+  var u = t.isub(c).ishrn(this.shift);
+  var res = u;
+  if (u.cmp(this.m) >= 0)
+    res = u.isub(this.m);
+  else if (u.cmpn(0) < 0)
+    res = u.iadd(this.m);
+
+  return res._forceRed(this);
+};
+
+Mont.prototype.invm = function invm(a) {
+  // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
+  var res = this.imod(a._invmp(this.m).mul(this.r2));
+  return res._forceRed(this);
+};
+
+})(typeof module === 'undefined' || module, this);
+
+},{}],260:[function(require,module,exports){
+'use strict'
+
+var bnsign = require('./lib/bn-sign')
+
+module.exports = sign
+
+function sign(x) {
+  return bnsign(x[0]) * bnsign(x[1])
+}
+
+},{"./lib/bn-sign":251}],261:[function(require,module,exports){
+'use strict'
+
+var rationalize = require('./lib/rationalize')
+
+module.exports = sub
+
+function sub(a, b) {
+  return rationalize(a[0].mul(b[1]).sub(a[1].mul(b[0])), a[1].mul(b[1]))
+}
+
+},{"./lib/rationalize":256}],262:[function(require,module,exports){
+'use strict'
+
+var bn2num = require('./lib/bn-to-num')
+var ctz = require('./lib/ctz')
+
+module.exports = roundRat
+
+//Round a rational to the closest float
+function roundRat(f) {
+  var a = f[0]
+  var b = f[1]
+  if(a.cmpn(0) === 0) {
+    return 0
+  }
+  var h = a.divmod(b)
+  var iv = h.div
+  var x = bn2num(iv)
+  var ir = h.mod
+  if(ir.cmpn(0) === 0) {
+    return x
+  }
+  if(x) {
+    var s = ctz(x) + 4
+    var y = bn2num(ir.shln(s).divRound(b))
+
+    // flip the sign of y if x is negative
+    if (x<0) {
+      y = -y;
+    }
+
+    return x + y * Math.pow(2, -s)
+  } else {
+    var ybits = b.bitLength() - ir.bitLength() + 53
+    var y = bn2num(ir.shln(ybits).divRound(b))
+    if(ybits < 1023) {
+      return y * Math.pow(2, -ybits)
+    }
+    y *= Math.pow(2, -1023)
+    return y * Math.pow(2, 1023-ybits)
+  }
+}
+
+},{"./lib/bn-to-num":252,"./lib/ctz":253}],263:[function(require,module,exports){
+'use strict'
+
+module.exports = boxIntersectWrapper
+
+var pool = require('typedarray-pool')
+var sweep = require('./lib/sweep')
+var boxIntersectIter = require('./lib/intersect')
+
+function boxEmpty(d, box) {
+  for(var j=0; j<d; ++j) {
+    if(!(box[j] <= box[j+d])) {
+      return true
+    }
+  }
+  return false
+}
+
+//Unpack boxes into a flat typed array, remove empty boxes
+function convertBoxes(boxes, d, data, ids) {
+  var ptr = 0
+  var count = 0
+  for(var i=0, n=boxes.length; i<n; ++i) {
+    var b = boxes[i]
+    if(boxEmpty(d, b)) {
+      continue
+    }
+    for(var j=0; j<2*d; ++j) {
+      data[ptr++] = b[j]
+    }
+    ids[count++] = i
+  }
+  return count
+}
+
+//Perform type conversions, check bounds
+function boxIntersect(red, blue, visit, full) {
+  var n = red.length
+  var m = blue.length
+
+  //If either array is empty, then we can skip this whole thing
+  if(n <= 0 || m <= 0) {
+    return
+  }
+
+  //Compute dimension, if it is 0 then we skip
+  var d = (red[0].length)>>>1
+  if(d <= 0) {
+    return
+  }
+
+  var retval
+
+  //Convert red boxes
+  var redList  = pool.mallocDouble(2*d*n)
+  var redIds   = pool.mallocInt32(n)
+  n = convertBoxes(red, d, redList, redIds)
+
+  if(n > 0) {
+    if(d === 1 && full) {
+      //Special case: 1d complete
+      sweep.init(n)
+      retval = sweep.sweepComplete(
+        d, visit, 
+        0, n, redList, redIds,
+        0, n, redList, redIds)
+    } else {
+
+      //Convert blue boxes
+      var blueList = pool.mallocDouble(2*d*m)
+      var blueIds  = pool.mallocInt32(m)
+      m = convertBoxes(blue, d, blueList, blueIds)
+
+      if(m > 0) {
+        sweep.init(n+m)
+
+        if(d === 1) {
+          //Special case: 1d bipartite
+          retval = sweep.sweepBipartite(
+            d, visit, 
+            0, n, redList,  redIds,
+            0, m, blueList, blueIds)
+        } else {
+          //General case:  d>1
+          retval = boxIntersectIter(
+            d, visit,    full,
+            n, redList,  redIds,
+            m, blueList, blueIds)
+        }
+
+        pool.free(blueList)
+        pool.free(blueIds)
+      }
+    }
+
+    pool.free(redList)
+    pool.free(redIds)
+  }
+
+  return retval
+}
+
+
+var RESULT
+
+function appendItem(i,j) {
+  RESULT.push([i,j])
+}
+
+function intersectFullArray(x) {
+  RESULT = []
+  boxIntersect(x, x, appendItem, true)
+  return RESULT
+}
+
+function intersectBipartiteArray(x, y) {
+  RESULT = []
+  boxIntersect(x, y, appendItem, false)
+  return RESULT
+}
+
+//User-friendly wrapper, handle full input and no-visitor cases
+function boxIntersectWrapper(arg0, arg1, arg2) {
+  var result
+  switch(arguments.length) {
+    case 1:
+      return intersectFullArray(arg0)
+    case 2:
+      if(typeof arg1 === 'function') {
+        return boxIntersect(arg0, arg0, arg1, true)
+      } else {
+        return intersectBipartiteArray(arg0, arg1)
+      }
+    case 3:
+      return boxIntersect(arg0, arg1, arg2, false)
+    default:
+      throw new Error('box-intersect: Invalid arguments')
+  }
+}
+},{"./lib/intersect":265,"./lib/sweep":269,"typedarray-pool":233}],264:[function(require,module,exports){
+'use strict'
+
+var DIMENSION   = 'd'
+var AXIS        = 'ax'
+var VISIT       = 'vv'
+var FLIP        = 'fp'
+
+var ELEM_SIZE   = 'es'
+
+var RED_START   = 'rs'
+var RED_END     = 're'
+var RED_BOXES   = 'rb'
+var RED_INDEX   = 'ri'
+var RED_PTR     = 'rp'
+
+var BLUE_START  = 'bs'
+var BLUE_END    = 'be'
+var BLUE_BOXES  = 'bb'
+var BLUE_INDEX  = 'bi'
+var BLUE_PTR    = 'bp'
+
+var RETVAL      = 'rv'
+
+var INNER_LABEL = 'Q'
+
+var ARGS = [
+  DIMENSION,
+  AXIS,
+  VISIT,
+  RED_START,
+  RED_END,
+  RED_BOXES,
+  RED_INDEX,
+  BLUE_START,
+  BLUE_END,
+  BLUE_BOXES,
+  BLUE_INDEX
+]
+
+function generateBruteForce(redMajor, flip, full) {
+  var funcName = 'bruteForce' + 
+    (redMajor ? 'Red' : 'Blue') + 
+    (flip ? 'Flip' : '') +
+    (full ? 'Full' : '')
+
+  var code = ['function ', funcName, '(', ARGS.join(), '){',
+    'var ', ELEM_SIZE, '=2*', DIMENSION, ';']
+
+  var redLoop = 
+    'for(var i=' + RED_START + ',' + RED_PTR + '=' + ELEM_SIZE + '*' + RED_START + ';' +
+        'i<' + RED_END +';' +
+        '++i,' + RED_PTR + '+=' + ELEM_SIZE + '){' +
+        'var x0=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '],' +
+            'x1=' + RED_BOXES + '[' + AXIS + '+' + RED_PTR + '+' + DIMENSION + '],' +
+            'xi=' + RED_INDEX + '[i];'
+
+  var blueLoop = 
+    'for(var j=' + BLUE_START + ',' + BLUE_PTR + '=' + ELEM_SIZE + '*' + BLUE_START + ';' +
+        'j<' + BLUE_END + ';' +
+        '++j,' + BLUE_PTR + '+=' + ELEM_SIZE + '){' +
+        'var y0=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '],' +
+            (full ? 'y1=' + BLUE_BOXES + '[' + AXIS + '+' + BLUE_PTR + '+' + DIMENSION + '],' : '') +
+            'yi=' + BLUE_INDEX + '[j];'
+
+  if(redMajor) {
+    code.push(redLoop, INNER_LABEL, ':', blueLoop)
+  } else {
+    code.push(blueLoop, INNER_LABEL, ':', redLoop)
+  }
+
+  if(full) {
+    code.push('if(y1<x0||x1<y0)continue;')
+  } else if(flip) {
+    code.push('if(y0<=x0||x1<y0)continue;')
+  } else {
+    code.push('if(y0<x0||x1<y0)continue;')
+  }
+
+  code.push('for(var k='+AXIS+'+1;k<'+DIMENSION+';++k){'+
+    'var r0='+RED_BOXES+'[k+'+RED_PTR+'],'+
+        'r1='+RED_BOXES+'[k+'+DIMENSION+'+'+RED_PTR+'],'+
+        'b0='+BLUE_BOXES+'[k+'+BLUE_PTR+'],'+
+        'b1='+BLUE_BOXES+'[k+'+DIMENSION+'+'+BLUE_PTR+'];'+
+      'if(r1<b0||b1<r0)continue ' + INNER_LABEL + ';}' +
+      'var ' + RETVAL + '=' + VISIT + '(')
+
+  if(flip) {
+    code.push('yi,xi')
+  } else {
+    code.push('xi,yi')
+  }
+
+  code.push(');if(' + RETVAL + '!==void 0)return ' + RETVAL + ';}}}')
+
+  return {
+    name: funcName, 
+    code: code.join('')
+  }
+}
+
+function bruteForcePlanner(full) {
+  var funcName = 'bruteForce' + (full ? 'Full' : 'Partial')
+  var prefix = []
+  var fargs = ARGS.slice()
+  if(!full) {
+    fargs.splice(3, 0, FLIP)
+  }
+
+  var code = ['function ' + funcName + '(' + fargs.join() + '){']
+
+  function invoke(redMajor, flip) {
+    var res = generateBruteForce(redMajor, flip, full)
+    prefix.push(res.code)
+    code.push('return ' + res.name + '(' + ARGS.join() + ');')
+  }
+
+  code.push('if(' + RED_END + '-' + RED_START + '>' +
+                    BLUE_END + '-' + BLUE_START + '){')
+
+  if(full) {
+    invoke(true, false)
+    code.push('}else{')
+    invoke(false, false)
+  } else {
+    code.push('if(' + FLIP + '){')
+    invoke(true, true)
+    code.push('}else{')
+    invoke(true, false)
+    code.push('}}else{if(' + FLIP + '){')
+    invoke(false, true)
+    code.push('}else{')
+    invoke(false, false)
+    code.push('}')
+  }
+  code.push('}}return ' + funcName)
+
+  var codeStr = prefix.join('') + code.join('')
+  var proc = new Function(codeStr)
+  return proc()
+}
+
+
+exports.partial = bruteForcePlanner(false)
+exports.full    = bruteForcePlanner(true)
+},{}],265:[function(require,module,exports){
+'use strict'
+
+module.exports = boxIntersectIter
+
+var pool = require('typedarray-pool')
+var bits = require('bit-twiddle')
+var bruteForce = require('./brute')
+var bruteForcePartial = bruteForce.partial
+var bruteForceFull = bruteForce.full
+var sweep = require('./sweep')
+var findMedian = require('./median')
+var genPartition = require('./partition')
+
+//Twiddle parameters
+var BRUTE_FORCE_CUTOFF    = 128       //Cut off for brute force search
+var SCAN_CUTOFF           = (1<<22)   //Cut off for two way scan
+var SCAN_COMPLETE_CUTOFF  = (1<<22)  
+
+//Partition functions
+var partitionInteriorContainsInterval = genPartition(
+  '!(lo>=p0)&&!(p1>=hi)', 
+  ['p0', 'p1'])
+
+var partitionStartEqual = genPartition(
+  'lo===p0',
+  ['p0'])
+
+var partitionStartLessThan = genPartition(
+  'lo<p0',
+  ['p0'])
+
+var partitionEndLessThanEqual = genPartition(
+  'hi<=p0',
+  ['p0'])
+
+var partitionContainsPoint = genPartition(
+  'lo<=p0&&p0<=hi',
+  ['p0'])
+
+var partitionContainsPointProper = genPartition(
+  'lo<p0&&p0<=hi',
+  ['p0'])
+
+//Frame size for iterative loop
+var IFRAME_SIZE = 6
+var DFRAME_SIZE = 2
+
+//Data for box statck
+var INIT_CAPACITY = 1024
+var BOX_ISTACK  = pool.mallocInt32(INIT_CAPACITY)
+var BOX_DSTACK  = pool.mallocDouble(INIT_CAPACITY)
+
+//Initialize iterative loop queue
+function iterInit(d, count) {
+  var levels = (8 * bits.log2(count+1) * (d+1))|0
+  var maxInts = bits.nextPow2(IFRAME_SIZE*levels)
+  if(BOX_ISTACK.length < maxInts) {
+    pool.free(BOX_ISTACK)
+    BOX_ISTACK = pool.mallocInt32(maxInts)
+  }
+  var maxDoubles = bits.nextPow2(DFRAME_SIZE*levels)
+  if(BOX_DSTACK < maxDoubles) {
+    pool.free(BOX_DSTACK)
+    BOX_DSTACK = pool.mallocDouble(maxDoubles)
+  }
+}
+
+//Append item to queue
+function iterPush(ptr,
+  axis, 
+  redStart, redEnd, 
+  blueStart, blueEnd, 
+  state, 
+  lo, hi) {
+
+  var iptr = IFRAME_SIZE * ptr
+  BOX_ISTACK[iptr]   = axis
+  BOX_ISTACK[iptr+1] = redStart
+  BOX_ISTACK[iptr+2] = redEnd
+  BOX_ISTACK[iptr+3] = blueStart
+  BOX_ISTACK[iptr+4] = blueEnd
+  BOX_ISTACK[iptr+5] = state
+
+  var dptr = DFRAME_SIZE * ptr
+  BOX_DSTACK[dptr]   = lo
+  BOX_DSTACK[dptr+1] = hi
+}
+
+//Special case:  Intersect single point with list of intervals
+function onePointPartial(
+  d, axis, visit, flip,
+  redStart, redEnd, red, redIndex,
+  blueOffset, blue, blueId) {
+
+  var elemSize = 2 * d
+  var bluePtr  = blueOffset * elemSize
+  var blueX    = blue[bluePtr + axis]
+
+red_loop:
+  for(var i=redStart, redPtr=redStart*elemSize; i<redEnd; ++i, redPtr+=elemSize) {
+    var r0 = red[redPtr+axis]
+    var r1 = red[redPtr+axis+d]
+    if(blueX < r0 || r1 < blueX) {
+      continue
+    }
+    if(flip && blueX === r0) {
+      continue
+    }
+    var redId = redIndex[i]
+    for(var j=axis+1; j<d; ++j) {
+      var r0 = red[redPtr+j]
+      var r1 = red[redPtr+j+d]
+      var b0 = blue[bluePtr+j]
+      var b1 = blue[bluePtr+j+d]
+      if(r1 < b0 || b1 < r0) {
+        continue red_loop
+      }
+    }
+    var retval
+    if(flip) {
+      retval = visit(blueId, redId)
+    } else {
+      retval = visit(redId, blueId)
+    }
+    if(retval !== void 0) {
+      return retval
+    }
+  }
+}
+
+//Special case:  Intersect one point with list of intervals
+function onePointFull(
+  d, axis, visit,
+  redStart, redEnd, red, redIndex,
+  blueOffset, blue, blueId) {
+
+  var elemSize = 2 * d
+  var bluePtr  = blueOffset * elemSize
+  var blueX    = blue[bluePtr + axis]
+
+red_loop:
+  for(var i=redStart, redPtr=redStart*elemSize; i<redEnd; ++i, redPtr+=elemSize) {
+    var redId = redIndex[i]
+    if(redId === blueId) {
+      continue
+    }
+    var r0 = red[redPtr+axis]
+    var r1 = red[redPtr+axis+d]
+    if(blueX < r0 || r1 < blueX) {
+      continue
+    }
+    for(var j=axis+1; j<d; ++j) {
+      var r0 = red[redPtr+j]
+      var r1 = red[redPtr+j+d]
+      var b0 = blue[bluePtr+j]
+      var b1 = blue[bluePtr+j+d]
+      if(r1 < b0 || b1 < r0) {
+        continue red_loop
+      }
+    }
+    var retval = visit(redId, blueId)
+    if(retval !== void 0) {
+      return retval
+    }
+  }
+}
+
+//The main box intersection routine
+function boxIntersectIter(
+  d, visit, initFull,
+  xSize, xBoxes, xIndex,
+  ySize, yBoxes, yIndex) {
+
+  //Reserve memory for stack
+  iterInit(d, xSize + ySize)
+
+  var top  = 0
+  var elemSize = 2 * d
+  var retval
+
+  iterPush(top++,
+      0,
+      0, xSize,
+      0, ySize,
+      initFull ? 16 : 0, 
+      -Infinity, Infinity)
+  if(!initFull) {
+    iterPush(top++,
+      0,
+      0, ySize,
+      0, xSize,
+      1, 
+      -Infinity, Infinity)
+  }
+
+  while(top > 0) {
+    top  -= 1
+
+    var iptr = top * IFRAME_SIZE
+    var axis      = BOX_ISTACK[iptr]
+    var redStart  = BOX_ISTACK[iptr+1]
+    var redEnd    = BOX_ISTACK[iptr+2]
+    var blueStart = BOX_ISTACK[iptr+3]
+    var blueEnd   = BOX_ISTACK[iptr+4]
+    var state     = BOX_ISTACK[iptr+5]
+
+    var dptr = top * DFRAME_SIZE
+    var lo        = BOX_DSTACK[dptr]
+    var hi        = BOX_DSTACK[dptr+1]
+
+    //Unpack state info
+    var flip      = (state & 1)
+    var full      = !!(state & 16)
+
+    //Unpack indices
+    var red       = xBoxes
+    var redIndex  = xIndex
+    var blue      = yBoxes
+    var blueIndex = yIndex
+    if(flip) {
+      red         = yBoxes
+      redIndex    = yIndex
+      blue        = xBoxes
+      blueIndex   = xIndex
+    }
+
+    if(state & 2) {
+      redEnd = partitionStartLessThan(
+        d, axis,
+        redStart, redEnd, red, redIndex,
+        hi)
+      if(redStart >= redEnd) {
+        continue
+      }
+    }
+    if(state & 4) {
+      redStart = partitionEndLessThanEqual(
+        d, axis,
+        redStart, redEnd, red, redIndex,
+        lo)
+      if(redStart >= redEnd) {
+        continue
+      }
+    }
+    
+    var redCount  = redEnd  - redStart
+    var blueCount = blueEnd - blueStart
+
+    if(full) {
+      if(d * redCount * (redCount + blueCount) < SCAN_COMPLETE_CUTOFF) {
+        retval = sweep.scanComplete(
+          d, axis, visit, 
+          redStart, redEnd, red, redIndex,
+          blueStart, blueEnd, blue, blueIndex)
+        if(retval !== void 0) {
+          return retval
+        }
+        continue
+      }
+    } else {
+      if(d * Math.min(redCount, blueCount) < BRUTE_FORCE_CUTOFF) {
+        //If input small, then use brute force
+        retval = bruteForcePartial(
+            d, axis, visit, flip,
+            redStart,  redEnd,  red,  redIndex,
+            blueStart, blueEnd, blue, blueIndex)
+        if(retval !== void 0) {
+          return retval
+        }
+        continue
+      } else if(d * redCount * blueCount < SCAN_CUTOFF) {
+        //If input medium sized, then use sweep and prune
+        retval = sweep.scanBipartite(
+          d, axis, visit, flip, 
+          redStart, redEnd, red, redIndex,
+          blueStart, blueEnd, blue, blueIndex)
+        if(retval !== void 0) {
+          return retval
+        }
+        continue
+      }
+    }
+    
+    //First, find all red intervals whose interior contains (lo,hi)
+    var red0 = partitionInteriorContainsInterval(
+      d, axis, 
+      redStart, redEnd, red, redIndex,
+      lo, hi)
+
+    //Lower dimensional case
+    if(redStart < red0) {
+
+      if(d * (red0 - redStart) < BRUTE_FORCE_CUTOFF) {
+        //Special case for small inputs: use brute force
+        retval = bruteForceFull(
+          d, axis+1, visit,
+          redStart, red0, red, redIndex,
+          blueStart, blueEnd, blue, blueIndex)
+        if(retval !== void 0) {
+          return retval
+        }
+      } else if(axis === d-2) {
+        if(flip) {
+          retval = sweep.sweepBipartite(
+            d, visit,
+            blueStart, blueEnd, blue, blueIndex,
+            redStart, red0, red, redIndex)
+        } else {
+          retval = sweep.sweepBipartite(
+            d, visit,
+            redStart, red0, red, redIndex,
+            blueStart, blueEnd, blue, blueIndex)
+        }
+        if(retval !== void 0) {
+          return retval
+        }
+      } else {
+        iterPush(top++,
+          axis+1,
+          redStart, red0,
+          blueStart, blueEnd,
+          flip,
+          -Infinity, Infinity)
+        iterPush(top++,
+          axis+1,
+          blueStart, blueEnd,
+          redStart, red0,
+          flip^1,
+          -Infinity, Infinity)
+      }
+    }
+
+    //Divide and conquer phase
+    if(red0 < redEnd) {
+
+      //Cut blue into 3 parts:
+      //
+      //  Points < mid point
+      //  Points = mid point
+      //  Points > mid point
+      //
+      var blue0 = findMedian(
+        d, axis, 
+        blueStart, blueEnd, blue, blueIndex)
+      var mid = blue[elemSize * blue0 + axis]
+      var blue1 = partitionStartEqual(
+        d, axis,
+        blue0, blueEnd, blue, blueIndex,
+        mid)
+
+      //Right case
+      if(blue1 < blueEnd) {
+        iterPush(top++,
+          axis,
+          red0, redEnd,
+          blue1, blueEnd,
+          (flip|4) + (full ? 16 : 0),
+          mid, hi)
+      }
+
+      //Left case
+      if(blueStart < blue0) {
+        iterPush(top++,
+          axis,
+          red0, redEnd,
+          blueStart, blue0,
+          (flip|2) + (full ? 16 : 0),
+          lo, mid)
+      }
+
+      //Center case (the hard part)
+      if(blue0 + 1 === blue1) {
+        //Optimization: Range with exactly 1 point, use a brute force scan
+        if(full) {
+          retval = onePointFull(
+            d, axis, visit,
+            red0, redEnd, red, redIndex,
+            blue0, blue, blueIndex[blue0])
+        } else {
+          retval = onePointPartial(
+            d, axis, visit, flip,
+            red0, redEnd, red, redIndex,
+            blue0, blue, blueIndex[blue0])
+        }
+        if(retval !== void 0) {
+          return retval
+        }
+      } else if(blue0 < blue1) {
+        var red1
+        if(full) {
+          //If full intersection, need to handle special case
+          red1 = partitionContainsPoint(
+            d, axis,
+            red0, redEnd, red, redIndex,
+            mid)
+          if(red0 < red1) {
+            var redX = partitionStartEqual(
+              d, axis,
+              red0, red1, red, redIndex,
+              mid)
+            if(axis === d-2) {
+              //Degenerate sweep intersection:
+              //  [red0, redX] with [blue0, blue1]
+              if(red0 < redX) {
+                retval = sweep.sweepComplete(
+                  d, visit,
+                  red0, redX, red, redIndex,
+                  blue0, blue1, blue, blueIndex)
+                if(retval !== void 0) {
+                  return retval
+                }
+              }
+
+              //Normal sweep intersection:
+              //  [redX, red1] with [blue0, blue1]
+              if(redX < red1) {
+                retval = sweep.sweepBipartite(
+                  d, visit,
+                  redX, red1, red, redIndex,
+                  blue0, blue1, blue, blueIndex)
+                if(retval !== void 0) {
+                  return retval
+                }
+              }
+            } else {
+              if(red0 < redX) {
+                iterPush(top++,
+                  axis+1,
+                  red0, redX,
+                  blue0, blue1,
+                  16,
+                  -Infinity, Infinity)
+              }
+              if(redX < red1) {
+                iterPush(top++,
+                  axis+1,
+                  redX, red1,
+                  blue0, blue1,
+                  0,
+                  -Infinity, Infinity)
+                iterPush(top++,
+                  axis+1,
+                  blue0, blue1,
+                  redX, red1,
+                  1,
+                  -Infinity, Infinity)
+              }
+            }
+          }
+        } else {
+          if(flip) {
+            red1 = partitionContainsPointProper(
+              d, axis,
+              red0, redEnd, red, redIndex,
+              mid)
+          } else {
+            red1 = partitionContainsPoint(
+              d, axis,
+              red0, redEnd, red, redIndex,
+              mid)
+          }
+          if(red0 < red1) {
+            if(axis === d-2) {
+              if(flip) {
+                retval = sweep.sweepBipartite(
+                  d, visit,
+                  blue0, blue1, blue, blueIndex,
+                  red0, red1, red, redIndex)
+              } else {
+                retval = sweep.sweepBipartite(
+                  d, visit,
+                  red0, red1, red, redIndex,
+                  blue0, blue1, blue, blueIndex)
+              }
+            } else {
+              iterPush(top++,
+                axis+1,
+                red0, red1,
+                blue0, blue1,
+                flip,
+                -Infinity, Infinity)
+              iterPush(top++,
+                axis+1,
+                blue0, blue1,
+                red0, red1,
+                flip^1,
+                -Infinity, Infinity)
+            }
+          }
+        }
+      }
+    }
+  }
+}
+},{"./brute":264,"./median":266,"./partition":267,"./sweep":269,"bit-twiddle":49,"typedarray-pool":233}],266:[function(require,module,exports){
+'use strict'
+
+module.exports = findMedian
+
+var genPartition = require('./partition')
+
+var partitionStartLessThan = genPartition('lo<p0', ['p0'])
+
+var PARTITION_THRESHOLD = 8   //Cut off for using insertion sort in findMedian
+
+//Base case for median finding:  Use insertion sort
+function insertionSort(d, axis, start, end, boxes, ids) {
+  var elemSize = 2 * d
+  var boxPtr = elemSize * (start+1) + axis
+  for(var i=start+1; i<end; ++i, boxPtr+=elemSize) {
+    var x = boxes[boxPtr]
+    for(var j=i, ptr=elemSize*(i-1); 
+        j>start && boxes[ptr+axis] > x; 
+        --j, ptr-=elemSize) {
+      //Swap
+      var aPtr = ptr
+      var bPtr = ptr+elemSize
+      for(var k=0; k<elemSize; ++k, ++aPtr, ++bPtr) {
+        var y = boxes[aPtr]
+        boxes[aPtr] = boxes[bPtr]
+        boxes[bPtr] = y
+      }
+      var tmp = ids[j]
+      ids[j] = ids[j-1]
+      ids[j-1] = tmp
+    }
+  }
+}
+
+//Find median using quick select algorithm
+//  takes O(n) time with high probability
+function findMedian(d, axis, start, end, boxes, ids) {
+  if(end <= start+1) {
+    return start
+  }
+
+  var lo       = start
+  var hi       = end
+  var mid      = ((end + start) >>> 1)
+  var elemSize = 2*d
+  var pivot    = mid
+  var value    = boxes[elemSize*mid+axis]
+  
+  while(lo < hi) {
+    if(hi - lo < PARTITION_THRESHOLD) {
+      insertionSort(d, axis, lo, hi, boxes, ids)
+      value = boxes[elemSize*mid+axis]
+      break
+    }
+    
+    //Select pivot using median-of-3
+    var count  = hi - lo
+    var pivot0 = (Math.random()*count+lo)|0
+    var value0 = boxes[elemSize*pivot0 + axis]
+    var pivot1 = (Math.random()*count+lo)|0
+    var value1 = boxes[elemSize*pivot1 + axis]
+    var pivot2 = (Math.random()*count+lo)|0
+    var value2 = boxes[elemSize*pivot2 + axis]
+    if(value0 <= value1) {
+      if(value2 >= value1) {
+        pivot = pivot1
+        value = value1
+      } else if(value0 >= value2) {
+        pivot = pivot0
+        value = value0
+      } else {
+        pivot = pivot2
+        value = value2
+      }
+    } else {
+      if(value1 >= value2) {
+        pivot = pivot1
+        value = value1
+      } else if(value2 >= value0) {
+        pivot = pivot0
+        value = value0
+      } else {
+        pivot = pivot2
+        value = value2
+      }
+    }
+
+    //Swap pivot to end of array
+    var aPtr = elemSize * (hi-1)
+    var bPtr = elemSize * pivot
+    for(var i=0; i<elemSize; ++i, ++aPtr, ++bPtr) {
+      var x = boxes[aPtr]
+      boxes[aPtr] = boxes[bPtr]
+      boxes[bPtr] = x
+    }
+    var y = ids[hi-1]
+    ids[hi-1] = ids[pivot]
+    ids[pivot] = y
+
+    //Partition using pivot
+    pivot = partitionStartLessThan(
+      d, axis, 
+      lo, hi-1, boxes, ids,
+      value)
+
+    //Swap pivot back
+    var aPtr = elemSize * (hi-1)
+    var bPtr = elemSize * pivot
+    for(var i=0; i<elemSize; ++i, ++aPtr, ++bPtr) {
+      var x = boxes[aPtr]
+      boxes[aPtr] = boxes[bPtr]
+      boxes[bPtr] = x
+    }
+    var y = ids[hi-1]
+    ids[hi-1] = ids[pivot]
+    ids[pivot] = y
+
+    //Swap pivot to last pivot
+    if(mid < pivot) {
+      hi = pivot-1
+      while(lo < hi && 
+        boxes[elemSize*(hi-1)+axis] === value) {
+        hi -= 1
+      }
+      hi += 1
+    } else if(pivot < mid) {
+      lo = pivot + 1
+      while(lo < hi &&
+        boxes[elemSize*lo+axis] === value) {
+        lo += 1
+      }
+    } else {
+      break
+    }
+  }
+
+  //Make sure pivot is at start
+  return partitionStartLessThan(
+    d, axis, 
+    start, mid, boxes, ids,
+    boxes[elemSize*mid+axis])
+}
+},{"./partition":267}],267:[function(require,module,exports){
+'use strict'
+
+module.exports = genPartition
+
+var code = 'for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m'
+
+function genPartition(predicate, args) {
+  var fargs ='abcdef'.split('').concat(args)
+  var reads = []
+  if(predicate.indexOf('lo') >= 0) {
+    reads.push('lo=e[k+n]')
+  }
+  if(predicate.indexOf('hi') >= 0) {
+    reads.push('hi=e[k+o]')
+  }
+  fargs.push(
+    code.replace('_', reads.join())
+        .replace('$', predicate))
+  return Function.apply(void 0, fargs)
+}
+},{}],268:[function(require,module,exports){
+'use strict';
+
+//This code is extracted from ndarray-sort
+//It is inlined here as a temporary workaround
+
+module.exports = wrapper;
+
+var INSERT_SORT_CUTOFF = 32
+
+function wrapper(data, n0) {
+  if (n0 <= 4*INSERT_SORT_CUTOFF) {
+    insertionSort(0, n0 - 1, data);
+  } else {
+    quickSort(0, n0 - 1, data);
+  }
+}
+
+function insertionSort(left, right, data) {
+  var ptr = 2*(left+1)
+  for(var i=left+1; i<=right; ++i) {
+    var a = data[ptr++]
+    var b = data[ptr++]
+    var j = i
+    var jptr = ptr-2
+    while(j-- > left) {
+      var x = data[jptr-2]
+      var y = data[jptr-1]
+      if(x < a) {
+        break
+      } else if(x === a && y < b) {
+        break
+      }
+      data[jptr]   = x
+      data[jptr+1] = y
+      jptr -= 2
+    }
+    data[jptr]   = a
+    data[jptr+1] = b
+  }
+}
+
+function swap(i, j, data) {
+  i *= 2
+  j *= 2
+  var x = data[i]
+  var y = data[i+1]
+  data[i] = data[j]
+  data[i+1] = data[j+1]
+  data[j] = x
+  data[j+1] = y
+}
+
+function move(i, j, data) {
+  i *= 2
+  j *= 2
+  data[i] = data[j]
+  data[i+1] = data[j+1]
+}
+
+function rotate(i, j, k, data) {
+  i *= 2
+  j *= 2
+  k *= 2
+  var x = data[i]
+  var y = data[i+1]
+  data[i] = data[j]
+  data[i+1] = data[j+1]
+  data[j] = data[k]
+  data[j+1] = data[k+1]
+  data[k] = x
+  data[k+1] = y
+}
+
+function shufflePivot(i, j, px, py, data) {
+  i *= 2
+  j *= 2
+  data[i] = data[j]
+  data[j] = px
+  data[i+1] = data[j+1]
+  data[j+1] = py
+}
+
+function compare(i, j, data) {
+  i *= 2
+  j *= 2
+  var x = data[i],
+      y = data[j]
+  if(x < y) {
+    return false
+  } else if(x === y) {
+    return data[i+1] > data[j+1]
+  }
+  return true
+}
+
+function comparePivot(i, y, b, data) {
+  i *= 2
+  var x = data[i]
+  if(x < y) {
+    return true
+  } else if(x === y) {
+    return data[i+1] < b
+  }
+  return false
+}
+
+function quickSort(left, right, data) {
+  var sixth = (right - left + 1) / 6 | 0, 
+      index1 = left + sixth, 
+      index5 = right - sixth, 
+      index3 = left + right >> 1, 
+      index2 = index3 - sixth, 
+      index4 = index3 + sixth, 
+      el1 = index1, 
+      el2 = index2, 
+      el3 = index3, 
+      el4 = index4, 
+      el5 = index5, 
+      less = left + 1, 
+      great = right - 1, 
+      tmp = 0
+  if(compare(el1, el2, data)) {
+    tmp = el1
+    el1 = el2
+    el2 = tmp
+  }
+  if(compare(el4, el5, data)) {
+    tmp = el4
+    el4 = el5
+    el5 = tmp
+  }
+  if(compare(el1, el3, data)) {
+    tmp = el1
+    el1 = el3
+    el3 = tmp
+  }
+  if(compare(el2, el3, data)) {
+    tmp = el2
+    el2 = el3
+    el3 = tmp
+  }
+  if(compare(el1, el4, data)) {
+    tmp = el1
+    el1 = el4
+    el4 = tmp
+  }
+  if(compare(el3, el4, data)) {
+    tmp = el3
+    el3 = el4
+    el4 = tmp
+  }
+  if(compare(el2, el5, data)) {
+    tmp = el2
+    el2 = el5
+    el5 = tmp
+  }
+  if(compare(el2, el3, data)) {
+    tmp = el2
+    el2 = el3
+    el3 = tmp
+  }
+  if(compare(el4, el5, data)) {
+    tmp = el4
+    el4 = el5
+    el5 = tmp
+  }
+
+  var pivot1X = data[2*el2]
+  var pivot1Y = data[2*el2+1]
+  var pivot2X = data[2*el4]
+  var pivot2Y = data[2*el4+1]
+
+  var ptr0 = 2 * el1;
+  var ptr2 = 2 * el3;
+  var ptr4 = 2 * el5;
+  var ptr5 = 2 * index1;
+  var ptr6 = 2 * index3;
+  var ptr7 = 2 * index5;
+  for (var i1 = 0; i1 < 2; ++i1) {
+    var x = data[ptr0+i1];
+    var y = data[ptr2+i1];
+    var z = data[ptr4+i1];
+    data[ptr5+i1] = x;
+    data[ptr6+i1] = y;
+    data[ptr7+i1] = z;
+  }
+
+  move(index2, left, data)
+  move(index4, right, data)
+  for (var k = less; k <= great; ++k) {
+    if (comparePivot(k, pivot1X, pivot1Y, data)) {
+      if (k !== less) {
+        swap(k, less, data)
+      }
+      ++less;
+    } else {
+      if (!comparePivot(k, pivot2X, pivot2Y, data)) {
+        while (true) {
+          if (!comparePivot(great, pivot2X, pivot2Y, data)) {
+            if (--great < k) {
+              break;
+            }
+            continue;
+          } else {
+            if (comparePivot(great, pivot1X, pivot1Y, data)) {
+              rotate(k, less, great, data)
+              ++less;
+              --great;
+            } else {
+              swap(k, great, data)
+              --great;
+            }
+            break;
+          }
+        }
+      }
+    }
+  }
+  shufflePivot(left, less-1, pivot1X, pivot1Y, data)
+  shufflePivot(right, great+1, pivot2X, pivot2Y, data)
+  if (less - 2 - left <= INSERT_SORT_CUTOFF) {
+    insertionSort(left, less - 2, data);
+  } else {
+    quickSort(left, less - 2, data);
+  }
+  if (right - (great + 2) <= INSERT_SORT_CUTOFF) {
+    insertionSort(great + 2, right, data);
+  } else {
+    quickSort(great + 2, right, data);
+  }
+  if (great - less <= INSERT_SORT_CUTOFF) {
+    insertionSort(less, great, data);
+  } else {
+    quickSort(less, great, data);
+  }
+}
+},{}],269:[function(require,module,exports){
+'use strict'
+
+module.exports = {
+  init:           sqInit,
+  sweepBipartite: sweepBipartite,
+  sweepComplete:  sweepComplete,
+  scanBipartite:  scanBipartite,
+  scanComplete:   scanComplete
+}
+
+var pool  = require('typedarray-pool')
+var bits  = require('bit-twiddle')
+var isort = require('./sort')
+
+//Flag for blue
+var BLUE_FLAG = (1<<28)
+
+//1D sweep event queue stuff (use pool to save space)
+var INIT_CAPACITY      = 1024
+var RED_SWEEP_QUEUE    = pool.mallocInt32(INIT_CAPACITY)
+var RED_SWEEP_INDEX    = pool.mallocInt32(INIT_CAPACITY)
+var BLUE_SWEEP_QUEUE   = pool.mallocInt32(INIT_CAPACITY)
+var BLUE_SWEEP_INDEX   = pool.mallocInt32(INIT_CAPACITY)
+var COMMON_SWEEP_QUEUE = pool.mallocInt32(INIT_CAPACITY)
+var COMMON_SWEEP_INDEX = pool.mallocInt32(INIT_CAPACITY)
+var SWEEP_EVENTS       = pool.mallocDouble(INIT_CAPACITY * 8)
+
+//Reserves memory for the 1D sweep data structures
+function sqInit(count) {
+  var rcount = bits.nextPow2(count)
+  if(RED_SWEEP_QUEUE.length < rcount) {
+    pool.free(RED_SWEEP_QUEUE)
+    RED_SWEEP_QUEUE = pool.mallocInt32(rcount)
+  }
+  if(RED_SWEEP_INDEX.length < rcount) {
+    pool.free(RED_SWEEP_INDEX)
+    RED_SWEEP_INDEX = pool.mallocInt32(rcount)
+  }
+  if(BLUE_SWEEP_QUEUE.length < rcount) {
+    pool.free(BLUE_SWEEP_QUEUE)
+    BLUE_SWEEP_QUEUE = pool.mallocInt32(rcount)
+  }
+  if(BLUE_SWEEP_INDEX.length < rcount) {
+    pool.free(BLUE_SWEEP_INDEX)
+    BLUE_SWEEP_INDEX = pool.mallocInt32(rcount)
+  }
+  if(COMMON_SWEEP_QUEUE.length < rcount) {
+    pool.free(COMMON_SWEEP_QUEUE)
+    COMMON_SWEEP_QUEUE = pool.mallocInt32(rcount)
+  }
+  if(COMMON_SWEEP_INDEX.length < rcount) {
+    pool.free(COMMON_SWEEP_INDEX)
+    COMMON_SWEEP_INDEX = pool.mallocInt32(rcount)
+  }
+  var eventLength = 8 * rcount
+  if(SWEEP_EVENTS.length < eventLength) {
+    pool.free(SWEEP_EVENTS)
+    SWEEP_EVENTS = pool.mallocDouble(eventLength)
+  }
+}
+
+//Remove an item from the active queue in O(1)
+function sqPop(queue, index, count, item) {
+  var idx = index[item]
+  var top = queue[count-1]
+  queue[idx] = top
+  index[top] = idx
+}
+
+//Insert an item into the active queue in O(1)
+function sqPush(queue, index, count, item) {
+  queue[count] = item
+  index[item]  = count
+}
+
+//Recursion base case: use 1D sweep algorithm
+function sweepBipartite(
+    d, visit,
+    redStart,  redEnd, red, redIndex,
+    blueStart, blueEnd, blue, blueIndex) {
+
+  //store events as pairs [coordinate, idx]
+  //
+  //  red create:  -(idx+1)
+  //  red destroy: idx
+  //  blue create: -(idx+BLUE_FLAG)
+  //  blue destroy: idx+BLUE_FLAG
+  //
+  var ptr      = 0
+  var elemSize = 2*d
+  var istart   = d-1
+  var iend     = elemSize-1
+
+  for(var i=redStart; i<redEnd; ++i) {
+    var idx = redIndex[i]
+    var redOffset = elemSize*i
+    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
+    SWEEP_EVENTS[ptr++] = -(idx+1)
+    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
+    SWEEP_EVENTS[ptr++] = idx
+  }
+
+  for(var i=blueStart; i<blueEnd; ++i) {
+    var idx = blueIndex[i]+BLUE_FLAG
+    var blueOffset = elemSize*i
+    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
+    SWEEP_EVENTS[ptr++] = -idx
+    SWEEP_EVENTS[ptr++] = blue[blueOffset+iend]
+    SWEEP_EVENTS[ptr++] = idx
+  }
+
+  //process events from left->right
+  var n = ptr >>> 1
+  isort(SWEEP_EVENTS, n)
+  
+  var redActive  = 0
+  var blueActive = 0
+  for(var i=0; i<n; ++i) {
+    var e = SWEEP_EVENTS[2*i+1]|0
+    if(e >= BLUE_FLAG) {
+      //blue destroy event
+      e = (e-BLUE_FLAG)|0
+      sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, e)
+    } else if(e >= 0) {
+      //red destroy event
+      sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e)
+    } else if(e <= -BLUE_FLAG) {
+      //blue create event
+      e = (-e-BLUE_FLAG)|0
+      for(var j=0; j<redActive; ++j) {
+        var retval = visit(RED_SWEEP_QUEUE[j], e)
+        if(retval !== void 0) {
+          return retval
+        }
+      }
+      sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, e)
+    } else {
+      //red create event
+      e = (-e-1)|0
+      for(var j=0; j<blueActive; ++j) {
+        var retval = visit(e, BLUE_SWEEP_QUEUE[j])
+        if(retval !== void 0) {
+          return retval
+        }
+      }
+      sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, e)
+    }
+  }
+}
+
+//Complete sweep
+function sweepComplete(d, visit, 
+  redStart, redEnd, red, redIndex,
+  blueStart, blueEnd, blue, blueIndex) {
+
+  var ptr      = 0
+  var elemSize = 2*d
+  var istart   = d-1
+  var iend     = elemSize-1
+
+  for(var i=redStart; i<redEnd; ++i) {
+    var idx = (redIndex[i]+1)<<1
+    var redOffset = elemSize*i
+    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
+    SWEEP_EVENTS[ptr++] = -idx
+    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
+    SWEEP_EVENTS[ptr++] = idx
+  }
+
+  for(var i=blueStart; i<blueEnd; ++i) {
+    var idx = (blueIndex[i]+1)<<1
+    var blueOffset = elemSize*i
+    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
+    SWEEP_EVENTS[ptr++] = (-idx)|1
+    SWEEP_EVENTS[ptr++] = blue[blueOffset+iend]
+    SWEEP_EVENTS[ptr++] = idx|1
+  }
+
+  //process events from left->right
+  var n = ptr >>> 1
+  isort(SWEEP_EVENTS, n)
+  
+  var redActive    = 0
+  var blueActive   = 0
+  var commonActive = 0
+  for(var i=0; i<n; ++i) {
+    var e     = SWEEP_EVENTS[2*i+1]|0
+    var color = e&1
+    if(i < n-1 && (e>>1) === (SWEEP_EVENTS[2*i+3]>>1)) {
+      color = 2
+      i += 1
+    }
+    
+    if(e < 0) {
+      //Create event
+      var id = -(e>>1) - 1
+
+      //Intersect with common
+      for(var j=0; j<commonActive; ++j) {
+        var retval = visit(COMMON_SWEEP_QUEUE[j], id)
+        if(retval !== void 0) {
+          return retval
+        }
+      }
+
+      if(color !== 0) {
+        //Intersect with red
+        for(var j=0; j<redActive; ++j) {
+          var retval = visit(RED_SWEEP_QUEUE[j], id)
+          if(retval !== void 0) {
+            return retval
+          }
+        }
+      }
+
+      if(color !== 1) {
+        //Intersect with blue
+        for(var j=0; j<blueActive; ++j) {
+          var retval = visit(BLUE_SWEEP_QUEUE[j], id)
+          if(retval !== void 0) {
+            return retval
+          }
+        }
+      }
+
+      if(color === 0) {
+        //Red
+        sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, id)
+      } else if(color === 1) {
+        //Blue
+        sqPush(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive++, id)
+      } else if(color === 2) {
+        //Both
+        sqPush(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive++, id)
+      }
+    } else {
+      //Destroy event
+      var id = (e>>1) - 1
+      if(color === 0) {
+        //Red
+        sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, id)
+      } else if(color === 1) {
+        //Blue
+        sqPop(BLUE_SWEEP_QUEUE, BLUE_SWEEP_INDEX, blueActive--, id)
+      } else if(color === 2) {
+        //Both
+        sqPop(COMMON_SWEEP_QUEUE, COMMON_SWEEP_INDEX, commonActive--, id)
+      }
+    }
+  }
+}
+
+//Sweep and prune/scanline algorithm:
+//  Scan along axis, detect intersections
+//  Brute force all boxes along axis
+function scanBipartite(
+  d, axis, visit, flip,
+  redStart,  redEnd, red, redIndex,
+  blueStart, blueEnd, blue, blueIndex) {
+  
+  var ptr      = 0
+  var elemSize = 2*d
+  var istart   = axis
+  var iend     = axis+d
+
+  var redShift  = 1
+  var blueShift = 1
+  if(flip) {
+    blueShift = BLUE_FLAG
+  } else {
+    redShift  = BLUE_FLAG
+  }
+
+  for(var i=redStart; i<redEnd; ++i) {
+    var idx = i + redShift
+    var redOffset = elemSize*i
+    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
+    SWEEP_EVENTS[ptr++] = -idx
+    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
+    SWEEP_EVENTS[ptr++] = idx
+  }
+  for(var i=blueStart; i<blueEnd; ++i) {
+    var idx = i + blueShift
+    var blueOffset = elemSize*i
+    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
+    SWEEP_EVENTS[ptr++] = -idx
+  }
+
+  //process events from left->right
+  var n = ptr >>> 1
+  isort(SWEEP_EVENTS, n)
+  
+  var redActive    = 0
+  for(var i=0; i<n; ++i) {
+    var e = SWEEP_EVENTS[2*i+1]|0
+    if(e < 0) {
+      var idx   = -e
+      var isRed = false
+      if(idx >= BLUE_FLAG) {
+        isRed = !flip
+        idx -= BLUE_FLAG 
+      } else {
+        isRed = !!flip
+        idx -= 1
+      }
+      if(isRed) {
+        sqPush(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive++, idx)
+      } else {
+        var blueId  = blueIndex[idx]
+        var bluePtr = elemSize * idx
+        
+        var b0 = blue[bluePtr+axis+1]
+        var b1 = blue[bluePtr+axis+1+d]
+
+red_loop:
+        for(var j=0; j<redActive; ++j) {
+          var oidx   = RED_SWEEP_QUEUE[j]
+          var redPtr = elemSize * oidx
+
+          if(b1 < red[redPtr+axis+1] || 
+             red[redPtr+axis+1+d] < b0) {
+            continue
+          }
+
+          for(var k=axis+2; k<d; ++k) {
+            if(blue[bluePtr + k + d] < red[redPtr + k] || 
+               red[redPtr + k + d] < blue[bluePtr + k]) {
+              continue red_loop
+            }
+          }
+
+          var redId  = redIndex[oidx]
+          var retval
+          if(flip) {
+            retval = visit(blueId, redId)
+          } else {
+            retval = visit(redId, blueId)
+          }
+          if(retval !== void 0) {
+            return retval 
+          }
+        }
+      }
+    } else {
+      sqPop(RED_SWEEP_QUEUE, RED_SWEEP_INDEX, redActive--, e - redShift)
+    }
+  }
+}
+
+function scanComplete(
+  d, axis, visit,
+  redStart,  redEnd, red, redIndex,
+  blueStart, blueEnd, blue, blueIndex) {
+
+  var ptr      = 0
+  var elemSize = 2*d
+  var istart   = axis
+  var iend     = axis+d
+
+  for(var i=redStart; i<redEnd; ++i) {
+    var idx = i + BLUE_FLAG
+    var redOffset = elemSize*i
+    SWEEP_EVENTS[ptr++] = red[redOffset+istart]
+    SWEEP_EVENTS[ptr++] = -idx
+    SWEEP_EVENTS[ptr++] = red[redOffset+iend]
+    SWEEP_EVENTS[ptr++] = idx
+  }
+  for(var i=blueStart; i<blueEnd; ++i) {
+    var idx = i + 1
+    var blueOffset = elemSize*i
+    SWEEP_EVENTS[ptr++] = blue[blueOffset+istart]
+    SWEEP_EVENTS[ptr++] = -idx
+  }
+
+  //process events from left->right
+  var n = ptr >>> 1
+  isort(SWEEP_EVENTS, n)
+  
+  var redActive    = 0
+  for(var i=0; i<n; ++i) {
+    var e = SWEEP_EVENTS[2*i+1]|0
+    if(e < 0) {
+      var idx   = -e
+      if(idx >= BLUE_FLAG) {
+        RED_SWEEP_QUEUE[redActive++] = idx - BLUE_FLAG
+      } else {
+        idx -= 1
+        var blueId  = blueIndex[idx]
+        var bluePtr = elemSize * idx
+
+        var b0 = blue[bluePtr+axis+1]
+        var b1 = blue[bluePtr+axis+1+d]
+
+red_loop:
+        for(var j=0; j<redActive; ++j) {
+          var oidx   = RED_SWEEP_QUEUE[j]
+          var redId  = redIndex[oidx]
+
+          if(redId === blueId) {
+            break
+          }
+
+          var redPtr = elemSize * oidx
+          if(b1 < red[redPtr+axis+1] || 
+            red[redPtr+axis+1+d] < b0) {
+            continue
+          }
+          for(var k=axis+2; k<d; ++k) {
+            if(blue[bluePtr + k + d] < red[redPtr + k] || 
+               red[redPtr + k + d]   < blue[bluePtr + k]) {
+              continue red_loop
+            }
+          }
+
+          var retval = visit(redId, blueId)
+          if(retval !== void 0) {
+            return retval 
+          }
+        }
+      }
+    } else {
+      var idx = e - BLUE_FLAG
+      for(var j=redActive-1; j>=0; --j) {
+        if(RED_SWEEP_QUEUE[j] === idx) {
+          for(var k=j+1; k<redActive; ++k) {
+            RED_SWEEP_QUEUE[k-1] = RED_SWEEP_QUEUE[k]
+          }
+          break
+        }
+      }
+      --redActive
+    }
+  }
+}
+},{"./sort":268,"bit-twiddle":49,"typedarray-pool":233}],270:[function(require,module,exports){
+(function (Buffer){
+var hasTypedArrays = false
+if(typeof Float64Array !== "undefined") {
+  var DOUBLE_VIEW = new Float64Array(1)
+    , UINT_VIEW   = new Uint32Array(DOUBLE_VIEW.buffer)
+  DOUBLE_VIEW[0] = 1.0
+  hasTypedArrays = true
+  if(UINT_VIEW[1] === 0x3ff00000) {
+    //Use little endian
+    module.exports = function doubleBitsLE(n) {
+      DOUBLE_VIEW[0] = n
+      return [ UINT_VIEW[0], UINT_VIEW[1] ]
+    }
+    function toDoubleLE(lo, hi) {
+      UINT_VIEW[0] = lo
+      UINT_VIEW[1] = hi
+      return DOUBLE_VIEW[0]
+    }
+    module.exports.pack = toDoubleLE
+    function lowUintLE(n) {
+      DOUBLE_VIEW[0] = n
+      return UINT_VIEW[0]
+    }
+    module.exports.lo = lowUintLE
+    function highUintLE(n) {
+      DOUBLE_VIEW[0] = n
+      return UINT_VIEW[1]
+    }
+    module.exports.hi = highUintLE
+  } else if(UINT_VIEW[0] === 0x3ff00000) {
+    //Use big endian
+    module.exports = function doubleBitsBE(n) {
+      DOUBLE_VIEW[0] = n
+      return [ UINT_VIEW[1], UINT_VIEW[0] ]
+    }
+    function toDoubleBE(lo, hi) {
+      UINT_VIEW[1] = lo
+      UINT_VIEW[0] = hi
+      return DOUBLE_VIEW[0]
+    }
+    module.exports.pack = toDoubleBE
+    function lowUintBE(n) {
+      DOUBLE_VIEW[0] = n
+      return UINT_VIEW[1]
+    }
+    module.exports.lo = lowUintBE
+    function highUintBE(n) {
+      DOUBLE_VIEW[0] = n
+      return UINT_VIEW[0]
+    }
+    module.exports.hi = highUintBE
+  } else {
+    hasTypedArrays = false
+  }
+}
+if(!hasTypedArrays) {
+  var buffer = new Buffer(8)
+  module.exports = function doubleBits(n) {
+    buffer.writeDoubleLE(n, 0, true)
+    return [ buffer.readUInt32LE(0, true), buffer.readUInt32LE(4, true) ]
+  }
+  function toDouble(lo, hi) {
+    buffer.writeUInt32LE(lo, 0, true)
+    buffer.writeUInt32LE(hi, 4, true)
+    return buffer.readDoubleLE(0, true)
+  }
+  module.exports.pack = toDouble  
+  function lowUint(n) {
+    buffer.writeDoubleLE(n, 0, true)
+    return buffer.readUInt32LE(0, true)
+  }
+  module.exports.lo = lowUint
+  function highUint(n) {
+    buffer.writeDoubleLE(n, 0, true)
+    return buffer.readUInt32LE(4, true)
+  }
+  module.exports.hi = highUint
+}
+
+module.exports.sign = function(n) {
+  return module.exports.hi(n) >>> 31
+}
+
+module.exports.exponent = function(n) {
+  var b = module.exports.hi(n)
+  return ((b<<1) >>> 21) - 1023
+}
+
+module.exports.fraction = function(n) {
+  var lo = module.exports.lo(n)
+  var hi = module.exports.hi(n)
+  var b = hi & ((1<<20) - 1)
+  if(hi & 0x7ff00000) {
+    b += (1<<20)
+  }
+  return [lo, b]
+}
+
+module.exports.denormalized = function(n) {
+  var hi = module.exports.hi(n)
+  return !(hi & 0x7ff00000)
+}
+}).call(this,require("buffer").Buffer)
+},{"buffer":50}],271:[function(require,module,exports){
+"use strict"
+
+var doubleBits = require("double-bits")
+
+var SMALLEST_DENORM = Math.pow(2, -1074)
+var UINT_MAX = (-1)>>>0
+
+module.exports = nextafter
+
+function nextafter(x, y) {
+  if(isNaN(x) || isNaN(y)) {
+    return NaN
+  }
+  if(x === y) {
+    return x
+  }
+  if(x === 0) {
+    if(y < 0) {
+      return -SMALLEST_DENORM
+    } else {
+      return SMALLEST_DENORM
+    }
+  }
+  var hi = doubleBits.hi(x)
+  var lo = doubleBits.lo(x)
+  if((y > x) === (x > 0)) {
+    if(lo === UINT_MAX) {
+      hi += 1
+      lo = 0
+    } else {
+      lo += 1
+    }
+  } else {
+    if(lo === 0) {
+      lo = UINT_MAX
+      hi -= 1
+    } else {
+      lo -= 1
+    }
+  }
+  return doubleBits.pack(lo, hi)
+}
+},{"double-bits":270}],272:[function(require,module,exports){
+'use strict'
+
+var bnadd = require('big-rat/add')
+
+module.exports = add
+
+function add(a, b) {
+  var n = a.length
+  var r = new Array(n)
+    for(var i=0; i<n; ++i) {
+    r[i] = bnadd(a[i], b[i])
+  }
+  return r
+}
+
+},{"big-rat/add":246}],273:[function(require,module,exports){
+'use strict'
+
+module.exports = float2rat
+
+var rat = require('big-rat')
+
+function float2rat(v) {
+  var result = new Array(v.length)
+  for(var i=0; i<v.length; ++i) {
+    result[i] = rat(v[i])
+  }
+  return result
+}
+
+},{"big-rat":249}],274:[function(require,module,exports){
+'use strict'
+
+var rat = require('big-rat')
+var mul = require('big-rat/mul')
+
+module.exports = muls
+
+function muls(a, x) {
+  var s = rat(x)
+  var n = a.length
+  var r = new Array(n)
+  for(var i=0; i<n; ++i) {
+    r[i] = mul(a[i], s)
+  }
+  return r
+}
+
+},{"big-rat":249,"big-rat/mul":258}],275:[function(require,module,exports){
+'use strict'
+
+var bnsub = require('big-rat/sub')
+
+module.exports = sub
+
+function sub(a, b) {
+  var n = a.length
+  var r = new Array(n)
+    for(var i=0; i<n; ++i) {
+    r[i] = bnsub(a[i], b[i])
+  }
+  return r
+}
+
+},{"big-rat/sub":261}],276:[function(require,module,exports){
+"use strict"
+
+module.exports = segmentsIntersect
+
+var orient = require("robust-orientation")[3]
+
+function checkCollinear(a0, a1, b0, b1) {
+
+  for(var d=0; d<2; ++d) {
+    var x0 = a0[d]
+    var y0 = a1[d]
+    var l0 = Math.min(x0, y0)
+    var h0 = Math.max(x0, y0)    
+
+    var x1 = b0[d]
+    var y1 = b1[d]
+    var l1 = Math.min(x1, y1)
+    var h1 = Math.max(x1, y1)    
+
+    if(h1 < l0 || h0 < l1) {
+      return false
+    }
+  }
+
+  return true
+}
+
+function segmentsIntersect(a0, a1, b0, b1) {
+  var x0 = orient(a0, b0, b1)
+  var y0 = orient(a1, b0, b1)
+  if((x0 > 0 && y0 > 0) || (x0 < 0 && y0 < 0)) {
+    return false
+  }
+
+  var x1 = orient(b0, a0, a1)
+  var y1 = orient(b1, a0, a1)
+  if((x1 > 0 && y1 > 0) || (x1 < 0 && y1 < 0)) {
+    return false
+  }
+
+  //Check for degenerate collinear case
+  if(x0 === 0 && y0 === 0 && x1 === 0 && y1 === 0) {
+    return checkCollinear(a0, a1, b0, b1)
+  }
+
+  return true
+}
+},{"robust-orientation":214}],277:[function(require,module,exports){
+arguments[4][193][0].apply(exports,arguments)
+},{"dup":193}],278:[function(require,module,exports){
+'use strict'
+
+module.exports = trimLeaves
+
+var e2a = require('edges-to-adjacency-list')
+
+function trimLeaves(edges, positions) {
+  var adj = e2a(edges, positions.length)
+  var live = new Array(positions.length)
+  var nbhd = new Array(positions.length)
+
+  var dead = []
+  for(var i=0; i<positions.length; ++i) {
+    var count = adj[i].length
+    nbhd[i] = count
+    live[i] = true
+    if(count <= 1) {
+      dead.push(i)
+    }
+  }
+
+  while(dead.length > 0) {
+    var v = dead.pop()
+    live[v] = false
+    var n = adj[v]
+    for(var i=0; i<n.length; ++i) {
+      var u = n[i]
+      if(--nbhd[u] === 0) {
+        dead.push(u)
+      }
+    }
+  }
+
+  var newIndex = new Array(positions.length)
+  var npositions = []
+  for(var i=0; i<positions.length; ++i) {
+    if(live[i]) {
+      var v = npositions.length
+      newIndex[i] = v
+      npositions.push(positions[i])
+    } else {
+      newIndex[i] = -1
+    }
+  }
+
+  var nedges = []
+  for(var i=0; i<edges.length; ++i) {
+    var e = edges[i]
+    if(live[e[0]] && live[e[1]]) {
+      nedges.push([ newIndex[e[0]], newIndex[e[1]] ])
+    }
+  }
+  
+  return [ nedges, npositions ]
+}
+},{"edges-to-adjacency-list":279}],279:[function(require,module,exports){
+"use strict"
+
+module.exports = edgeToAdjacency
+
+var uniq = require("uniq")
+
+function edgeToAdjacency(edges, numVertices) {
+  var numEdges = edges.length
+  if(typeof numVertices !== "number") {
+    numVertices = 0
+    for(var i=0; i<numEdges; ++i) {
+      var e = edges[i]
+      numVertices = Math.max(numVertices, e[0], e[1])
+    }
+    numVertices = (numVertices|0) + 1
+  }
+  numVertices = numVertices|0
+  var adj = new Array(numVertices)
+  for(var i=0; i<numVertices; ++i) {
+    adj[i] = []
+  }
+  for(var i=0; i<numEdges; ++i) {
+    var e = edges[i]
+    adj[e[0]].push(e[1])
+    adj[e[1]].push(e[0])
+  }
+  for(var j=0; j<numVertices; ++j) {
+    uniq(adj[j], function(a, b) {
+      return a - b
+    })
+  }
+  return adj
+}
+},{"uniq":234}],280:[function(require,module,exports){
+"use strict"
+
+module.exports = planarDual
+
+var compareAngle = require("compare-angle")
+
+function planarDual(cells, positions) {
+
+  var numVertices = positions.length|0
+  var numEdges = cells.length
+  var adj = [new Array(numVertices), new Array(numVertices)]
+  for(var i=0; i<numVertices; ++i) {
+    adj[0][i] = []
+    adj[1][i] = []
+  }
+  for(var i=0; i<numEdges; ++i) {
+    var c = cells[i]
+    adj[0][c[0]].push(c)
+    adj[1][c[1]].push(c)
+  }
+
+  var cycles = []
+
+  //Add isolated vertices as trivial case
+  for(var i=0; i<numVertices; ++i) {
+    if(adj[0][i].length + adj[1][i].length === 0) {
+      cycles.push( [i] )
+    }
+  }
+
+  //Remove a half edge
+  function cut(c, i) {
+    var a = adj[i][c[i]]
+    a.splice(a.indexOf(c), 1)
+  }
+
+  //Find next vertex and cut edge
+  function next(a, b, noCut) {
+    var nextCell, nextVertex, nextDir
+    for(var i=0; i<2; ++i) {
+      if(adj[i][b].length > 0) {
+        nextCell = adj[i][b][0]
+        nextDir = i
+        break
+      }
+    }
+    nextVertex = nextCell[nextDir^1]
+
+    for(var dir=0; dir<2; ++dir) {
+      var nbhd = adj[dir][b]
+      for(var k=0; k<nbhd.length; ++k) {
+        var e = nbhd[k]
+        var p = e[dir^1]
+        var cmp = compareAngle(
+            positions[a], 
+            positions[b], 
+            positions[nextVertex],
+            positions[p])
+        if(cmp > 0) {
+          nextCell = e
+          nextVertex = p
+          nextDir = dir
+        }
+      }
+    }
+    if(noCut) {
+      return nextVertex
+    }
+    if(nextCell) {
+      cut(nextCell, nextDir)
+    }
+    return nextVertex
+  }
+
+  function extractCycle(v, dir) {
+    var e0 = adj[dir][v][0]
+    var cycle = [v]
+    cut(e0, dir)
+    var u = e0[dir^1]
+    var d0 = dir
+    while(true) {
+      while(u !== v) {
+        cycle.push(u)
+        u = next(cycle[cycle.length-2], u, false)
+      }
+      if(adj[0][v].length + adj[1][v].length === 0) {
+        break
+      }
+      var a = cycle[cycle.length-1]
+      var b = v
+      var c = cycle[1]
+      var d = next(a, b, true)
+      if(compareAngle(positions[a], positions[b], positions[c], positions[d]) < 0) {
+        break
+      }
+      cycle.push(v)
+      u = next(a, b)
+    }
+    return cycle
+  }
+
+  function shouldGlue(pcycle, ncycle) {
+    return (ncycle[1] === ncycle[ncycle.length-1])
+  }
+
+  for(var i=0; i<numVertices; ++i) {
+    for(var j=0; j<2; ++j) {
+      var pcycle = []
+      while(adj[j][i].length > 0) {
+        var ni = adj[0][i].length
+        var ncycle = extractCycle(i,j)
+        if(shouldGlue(pcycle, ncycle)) {
+          //Glue together trivial cycles
+          pcycle.push.apply(pcycle, ncycle)
+        } else {
+          if(pcycle.length > 0) {
+            cycles.push(pcycle)
+          }
+          pcycle = ncycle
+        }
+      }
+      if(pcycle.length > 0) {
+        cycles.push(pcycle)
+      }
+    }
+  }
+
+  //Combine paths and loops together
+  return cycles
+}
+},{"compare-angle":281}],281:[function(require,module,exports){
+"use strict"
+
+module.exports = compareAngle
+
+var orient = require("robust-orientation")
+var sgn = require("signum")
+var twoSum = require("two-sum")
+var robustProduct = require("robust-product")
+var robustSum = require("robust-sum")
+
+function testInterior(a, b, c) {
+  var x0 = twoSum(a[0], -b[0])
+  var y0 = twoSum(a[1], -b[1])
+  var x1 = twoSum(c[0], -b[0])
+  var y1 = twoSum(c[1], -b[1])
+
+  var d = robustSum(
+    robustProduct(x0, x1),
+    robustProduct(y0, y1))
+
+  return d[d.length-1] >= 0
+}
+
+function compareAngle(a, b, c, d) {
+  var bcd = orient(b, c, d)
+  if(bcd === 0) {
+    //Handle degenerate cases
+    var sabc = sgn(orient(a, b, c))
+    var sabd = sgn(orient(a, b, d))
+    if(sabc === sabd) {
+      if(sabc === 0) {
+        var ic = testInterior(a, b, c)
+        var id = testInterior(a, b, d)
+        if(ic === id) {
+          return 0
+        } else if(ic) {
+          return 1
+        } else {
+          return -1
+        }
+      }
+      return 0
+    } else if(sabd === 0) {
+      if(sabc > 0) {
+        return -1
+      } else if(testInterior(a, b, d)) {
+        return -1
+      } else {
+        return 1
+      }
+    } else if(sabc === 0) {
+      if(sabd > 0) {
+        return 1
+      } else if(testInterior(a, b, c)) {
+        return 1
+      } else {
+        return -1
+      }
+    }
+    return sgn(sabd - sabc)
+  }
+  var abc = orient(a, b, c)
+  if(abc > 0) {
+    if(bcd > 0 && orient(a, b, d) > 0) {
+      return 1
+    }
+    return -1
+  } else if(abc < 0) {
+    if(bcd > 0 || orient(a, b, d) > 0) {
+      return 1
+    }
+    return -1
+  } else {
+    var abd = orient(a, b, d)
+    if(abd > 0) {
+      return 1
+    } else {
+      if(testInterior(a, b, c)) {
+        return 1
+      } else {
+        return -1
+      }
+    }
+  }
+}
+},{"robust-orientation":214,"robust-product":282,"robust-sum":217,"signum":283,"two-sum":232}],282:[function(require,module,exports){
+"use strict"
+
+var robustSum = require("robust-sum")
+var robustScale = require("robust-scale")
+
+module.exports = robustProduct
+
+function robustProduct(a, b) {
+  if(a.length === 1) {
+    return robustScale(b, a[0])
+  }
+  if(b.length === 1) {
+    return robustScale(a, b[0])
+  }
+  if(a.length === 0 || b.length === 0) {
+    return [0]
+  }
+  var r = [0]
+  if(a.length < b.length) {
+    for(var i=0; i<a.length; ++i) {
+      r = robustSum(r, robustScale(b, a[i]))
+    }
+  } else {
+    for(var i=0; i<b.length; ++i) {
+      r = robustSum(r, robustScale(a, b[i]))
+    }    
+  }
+  return r
+}
+},{"robust-scale":215,"robust-sum":217}],283:[function(require,module,exports){
+"use strict"
+
+module.exports = function signum(x) {
+  if(x < 0) { return -1 }
+  if(x > 0) { return 1 }
+  return 0.0
+}
+},{}],284:[function(require,module,exports){
+arguments[4][20][0].apply(exports,arguments)
+},{"dup":20}],285:[function(require,module,exports){
+"use strict"
+
+var bounds = require("binary-search-bounds")
+
+var NOT_FOUND = 0
+var SUCCESS = 1
+var EMPTY = 2
+
+module.exports = createWrapper
+
+function IntervalTreeNode(mid, left, right, leftPoints, rightPoints) {
+  this.mid = mid
+  this.left = left
+  this.right = right
+  this.leftPoints = leftPoints
+  this.rightPoints = rightPoints
+  this.count = (left ? left.count : 0) + (right ? right.count : 0) + leftPoints.length
+}
+
+var proto = IntervalTreeNode.prototype
+
+function copy(a, b) {
+  a.mid = b.mid
+  a.left = b.left
+  a.right = b.right
+  a.leftPoints = b.leftPoints
+  a.rightPoints = b.rightPoints
+  a.count = b.count
+}
+
+function rebuild(node, intervals) {
+  var ntree = createIntervalTree(intervals)
+  node.mid = ntree.mid
+  node.left = ntree.left
+  node.right = ntree.right
+  node.leftPoints = ntree.leftPoints
+  node.rightPoints = ntree.rightPoints
+  node.count = ntree.count
+}
+
+function rebuildWithInterval(node, interval) {
+  var intervals = node.intervals([])
+  intervals.push(interval)
+  rebuild(node, intervals)    
+}
+
+function rebuildWithoutInterval(node, interval) {
+  var intervals = node.intervals([])
+  var idx = intervals.indexOf(interval)
+  if(idx < 0) {
+    return NOT_FOUND
+  }
+  intervals.splice(idx, 1)
+  rebuild(node, intervals)
+  return SUCCESS
+}
+
+proto.intervals = function(result) {
+  result.push.apply(result, this.leftPoints)
+  if(this.left) {
+    this.left.intervals(result)
+  }
+  if(this.right) {
+    this.right.intervals(result)
+  }
+  return result
+}
+
+proto.insert = function(interval) {
+  var weight = this.count - this.leftPoints.length
+  this.count += 1
+  if(interval[1] < this.mid) {
+    if(this.left) {
+      if(4*(this.left.count+1) > 3*(weight+1)) {
+        rebuildWithInterval(this, interval)
+      } else {
+        this.left.insert(interval)
+      }
+    } else {
+      this.left = createIntervalTree([interval])
+    }
+  } else if(interval[0] > this.mid) {
+    if(this.right) {
+      if(4*(this.right.count+1) > 3*(weight+1)) {
+        rebuildWithInterval(this, interval)
+      } else {
+        this.right.insert(interval)
+      }
+    } else {
+      this.right = createIntervalTree([interval])
+    }
+  } else {
+    var l = bounds.ge(this.leftPoints, interval, compareBegin)
+    var r = bounds.ge(this.rightPoints, interval, compareEnd)
+    this.leftPoints.splice(l, 0, interval)
+    this.rightPoints.splice(r, 0, interval)
+  }
+}
+
+proto.remove = function(interval) {
+  var weight = this.count - this.leftPoints
+  if(interval[1] < this.mid) {
+    if(!this.left) {
+      return NOT_FOUND
+    }
+    var rw = this.right ? this.right.count : 0
+    if(4 * rw > 3 * (weight-1)) {
+      return rebuildWithoutInterval(this, interval)
+    }
+    var r = this.left.remove(interval)
+    if(r === EMPTY) {
+      this.left = null
+      this.count -= 1
+      return SUCCESS
+    } else if(r === SUCCESS) {
+      this.count -= 1
+    }
+    return r
+  } else if(interval[0] > this.mid) {
+    if(!this.right) {
+      return NOT_FOUND
+    }
+    var lw = this.left ? this.left.count : 0
+    if(4 * lw > 3 * (weight-1)) {
+      return rebuildWithoutInterval(this, interval)
+    }
+    var r = this.right.remove(interval)
+    if(r === EMPTY) {
+      this.right = null
+      this.count -= 1
+      return SUCCESS
+    } else if(r === SUCCESS) {
+      this.count -= 1
+    }
+    return r
+  } else {
+    if(this.count === 1) {
+      if(this.leftPoints[0] === interval) {
+        return EMPTY
+      } else {
+        return NOT_FOUND
+      }
+    }
+    if(this.leftPoints.length === 1 && this.leftPoints[0] === interval) {
+      if(this.left && this.right) {
+        var p = this
+        var n = this.left
+        while(n.right) {
+          p = n
+          n = n.right
+        }
+        if(p === this) {
+          n.right = this.right
+        } else {
+          var l = this.left
+          var r = this.right
+          p.count -= n.count
+          p.right = n.left
+          n.left = l
+          n.right = r
+        }
+        copy(this, n)
+        this.count = (this.left?this.left.count:0) + (this.right?this.right.count:0) + this.leftPoints.length
+      } else if(this.left) {
+        copy(this, this.left)
+      } else {
+        copy(this, this.right)
+      }
+      return SUCCESS
+    }
+    for(var l = bounds.ge(this.leftPoints, interval, compareBegin); l<this.leftPoints.length; ++l) {
+      if(this.leftPoints[l][0] !== interval[0]) {
+        break
+      }
+      if(this.leftPoints[l] === interval) {
+        this.count -= 1
+        this.leftPoints.splice(l, 1)
+        for(var r = bounds.ge(this.rightPoints, interval, compareEnd); r<this.rightPoints.length; ++r) {
+          if(this.rightPoints[r][1] !== interval[1]) {
+            break
+          } else if(this.rightPoints[r] === interval) {
+            this.rightPoints.splice(r, 1)
+            return SUCCESS
+          }
+        }
+      }
+    }
+    return NOT_FOUND
+  }
+}
+
+function reportLeftRange(arr, hi, cb) {
+  for(var i=0; i<arr.length && arr[i][0] <= hi; ++i) {
+    var r = cb(arr[i])
+    if(r) { return r }
+  }
+}
+
+function reportRightRange(arr, lo, cb) {
+  for(var i=arr.length-1; i>=0 && arr[i][1] >= lo; --i) {
+    var r = cb(arr[i])
+    if(r) { return r }
+  }
+}
+
+function reportRange(arr, cb) {
+  for(var i=0; i<arr.length; ++i) {
+    var r = cb(arr[i])
+    if(r) { return r }
+  }
+}
+
+proto.queryPoint = function(x, cb) {
+  if(x < this.mid) {
+    if(this.left) {
+      var r = this.left.queryPoint(x, cb)
+      if(r) { return r }
+    }
+    return reportLeftRange(this.leftPoints, x, cb)
+  } else if(x > this.mid) {
+    if(this.right) {
+      var r = this.right.queryPoint(x, cb)
+      if(r) { return r }
+    }
+    return reportRightRange(this.rightPoints, x, cb)
+  } else {
+    return reportRange(this.leftPoints, cb)
+  }
+}
+
+proto.queryInterval = function(lo, hi, cb) {
+  if(lo < this.mid && this.left) {
+    var r = this.left.queryInterval(lo, hi, cb)
+    if(r) { return r }
+  }
+  if(hi > this.mid && this.right) {
+    var r = this.right.queryInterval(lo, hi, cb)
+    if(r) { return r }
+  }
+  if(hi < this.mid) {
+    return reportLeftRange(this.leftPoints, hi, cb)
+  } else if(lo > this.mid) {
+    return reportRightRange(this.rightPoints, lo, cb)
+  } else {
+    return reportRange(this.leftPoints, cb)
+  }
+}
+
+function compareNumbers(a, b) {
+  return a - b
+}
+
+function compareBegin(a, b) {
+  var d = a[0] - b[0]
+  if(d) { return d }
+  return a[1] - b[1]
+}
+
+function compareEnd(a, b) {
+  var d = a[1] - b[1]
+  if(d) { return d }
+  return a[0] - b[0]
+}
+
+function createIntervalTree(intervals) {
+  if(intervals.length === 0) {
+    return null
+  }
+  var pts = []
+  for(var i=0; i<intervals.length; ++i) {
+    pts.push(intervals[i][0], intervals[i][1])
+  }
+  pts.sort(compareNumbers)
+
+  var mid = pts[pts.length>>1]
+
+  var leftIntervals = []
+  var rightIntervals = []
+  var centerIntervals = []
+  for(var i=0; i<intervals.length; ++i) {
+    var s = intervals[i]
+    if(s[1] < mid) {
+      leftIntervals.push(s)
+    } else if(mid < s[0]) {
+      rightIntervals.push(s)
+    } else {
+      centerIntervals.push(s)
+    }
+  }
+
+  //Split center intervals
+  var leftPoints = centerIntervals
+  var rightPoints = centerIntervals.slice()
+  leftPoints.sort(compareBegin)
+  rightPoints.sort(compareEnd)
+
+  return new IntervalTreeNode(mid, 
+    createIntervalTree(leftIntervals),
+    createIntervalTree(rightIntervals),
+    leftPoints,
+    rightPoints)
+}
+
+//User friendly wrapper that makes it possible to support empty trees
+function IntervalTree(root) {
+  this.root = root
+}
+
+var tproto = IntervalTree.prototype
+
+tproto.insert = function(interval) {
+  if(this.root) {
+    this.root.insert(interval)
+  } else {
+    this.root = new IntervalTreeNode(interval[0], null, null, [interval], [interval])
+  }
+}
+
+tproto.remove = function(interval) {
+  if(this.root) {
+    var r = this.root.remove(interval)
+    if(r === EMPTY) {
+      this.root = null
+    }
+    return r !== NOT_FOUND
+  }
+  return false
+}
+
+tproto.queryPoint = function(p, cb) {
+  if(this.root) {
+    return this.root.queryPoint(p, cb)
+  }
+}
+
+tproto.queryInterval = function(lo, hi, cb) {
+  if(lo <= hi && this.root) {
+    return this.root.queryInterval(lo, hi, cb)
+  }
+}
+
+Object.defineProperty(tproto, "count", {
+  get: function() {
+    if(this.root) {
+      return this.root.count
+    }
+    return 0
+  }
+})
+
+Object.defineProperty(tproto, "intervals", {
+  get: function() {
+    if(this.root) {
+      return this.root.intervals([])
+    }
+    return []
+  }
+})
+
+function createWrapper(intervals) {
+  if(!intervals || intervals.length === 0) {
+    return new IntervalTree(null)
+  }
+  return new IntervalTree(createIntervalTree(intervals))
+}
+
+},{"binary-search-bounds":284}],286:[function(require,module,exports){
+"use strict"
+
+module.exports = orderSegments
+
+var orient = require("robust-orientation")
+
+function horizontalOrder(a, b) {
+  var bl, br
+  if(b[0][0] < b[1][0]) {
+    bl = b[0]
+    br = b[1]
+  } else if(b[0][0] > b[1][0]) {
+    bl = b[1]
+    br = b[0]
+  } else {
+    var alo = Math.min(a[0][1], a[1][1])
+    var ahi = Math.max(a[0][1], a[1][1])
+    var blo = Math.min(b[0][1], b[1][1])
+    var bhi = Math.max(b[0][1], b[1][1])
+    if(ahi < blo) {
+      return ahi - blo
+    }
+    if(alo > bhi) {
+      return alo - bhi
+    }
+    return ahi - bhi
+  }
+  var al, ar
+  if(a[0][1] < a[1][1]) {
+    al = a[0]
+    ar = a[1]
+  } else {
+    al = a[1]
+    ar = a[0]
+  }
+  var d = orient(br, bl, al)
+  if(d) {
+    return d
+  }
+  d = orient(br, bl, ar)
+  if(d) {
+    return d
+  }
+  return ar - br
+}
+
+function orderSegments(b, a) {
+  var al, ar
+  if(a[0][0] < a[1][0]) {
+    al = a[0]
+    ar = a[1]
+  } else if(a[0][0] > a[1][0]) {
+    al = a[1]
+    ar = a[0]
+  } else {
+    return horizontalOrder(a, b)
+  }
+  var bl, br
+  if(b[0][0] < b[1][0]) {
+    bl = b[0]
+    br = b[1]
+  } else if(b[0][0] > b[1][0]) {
+    bl = b[1]
+    br = b[0]
+  } else {
+    return -horizontalOrder(b, a)
+  }
+  var d1 = orient(al, ar, br)
+  var d2 = orient(al, ar, bl)
+  if(d1 < 0) {
+    if(d2 <= 0) {
+      return d1
+    }
+  } else if(d1 > 0) {
+    if(d2 >= 0) {
+      return d1
+    }
+  } else if(d2) {
+    return d2
+  }
+  d1 = orient(br, bl, ar)
+  d2 = orient(br, bl, al)
+  if(d1 < 0) {
+    if(d2 <= 0) {
+      return d1
+    }
+  } else if(d1 > 0) {
+    if(d2 >= 0) {
+      return d1
+    }
+  } else if(d2) {
+    return d2
+  }
+  return ar[0] - br[0]
+}
+},{"robust-orientation":214}],287:[function(require,module,exports){
+"use strict"
+
+module.exports = createRBTree
+
+var RED   = 0
+var BLACK = 1
+
+function RBNode(color, key, value, left, right, count) {
+  this._color = color
+  this.key = key
+  this.value = value
+  this.left = left
+  this.right = right
+  this._count = count
+}
+
+function cloneNode(node) {
+  return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count)
+}
+
+function repaint(color, node) {
+  return new RBNode(color, node.key, node.value, node.left, node.right, node._count)
+}
+
+function recount(node) {
+  node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0)
+}
+
+function RedBlackTree(compare, root) {
+  this._compare = compare
+  this.root = root
+}
+
+var proto = RedBlackTree.prototype
+
+Object.defineProperty(proto, "keys", {
+  get: function() {
+    var result = []
+    this.forEach(function(k,v) {
+      result.push(k)
+    })
+    return result
+  }
+})
+
+Object.defineProperty(proto, "values", {
+  get: function() {
+    var result = []
+    this.forEach(function(k,v) {
+      result.push(v)
+    })
+    return result
+  }
+})
+
+//Returns the number of nodes in the tree
+Object.defineProperty(proto, "length", {
+  get: function() {
+    if(this.root) {
+      return this.root._count
+    }
+    return 0
+  }
+})
+
+//Insert a new item into the tree
+proto.insert = function(key, value) {
+  var cmp = this._compare
+  //Find point to insert new node at
+  var n = this.root
+  var n_stack = []
+  var d_stack = []
+  while(n) {
+    var d = cmp(key, n.key)
+    n_stack.push(n)
+    d_stack.push(d)
+    if(d <= 0) {
+      n = n.left
+    } else {
+      n = n.right
+    }
+  }
+  //Rebuild path to leaf node
+  n_stack.push(new RBNode(RED, key, value, null, null, 1))
+  for(var s=n_stack.length-2; s>=0; --s) {
+    var n = n_stack[s]
+    if(d_stack[s] <= 0) {
+      n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1)
+    } else {
+      n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1)
+    }
+  }
+  //Rebalance tree using rotations
+  //console.log("start insert", key, d_stack)
+  for(var s=n_stack.length-1; s>1; --s) {
+    var p = n_stack[s-1]
+    var n = n_stack[s]
+    if(p._color === BLACK || n._color === BLACK) {
+      break
+    }
+    var pp = n_stack[s-2]
+    if(pp.left === p) {
+      if(p.left === n) {
+        var y = pp.right
+        if(y && y._color === RED) {
+          //console.log("LLr")
+          p._color = BLACK
+          pp.right = repaint(BLACK, y)
+          pp._color = RED
+          s -= 1
+        } else {
+          //console.log("LLb")
+          pp._color = RED
+          pp.left = p.right
+          p._color = BLACK
+          p.right = pp
+          n_stack[s-2] = p
+          n_stack[s-1] = n
+          recount(pp)
+          recount(p)
+          if(s >= 3) {
+            var ppp = n_stack[s-3]
+            if(ppp.left === pp) {
+              ppp.left = p
+            } else {
+              ppp.right = p
+            }
+          }
+          break
+        }
+      } else {
+        var y = pp.right
+        if(y && y._color === RED) {
+          //console.log("LRr")
+          p._color = BLACK
+          pp.right = repaint(BLACK, y)
+          pp._color = RED
+          s -= 1
+        } else {
+          //console.log("LRb")
+          p.right = n.left
+          pp._color = RED
+          pp.left = n.right
+          n._color = BLACK
+          n.left = p
+          n.right = pp
+          n_stack[s-2] = n
+          n_stack[s-1] = p
+          recount(pp)
+          recount(p)
+          recount(n)
+          if(s >= 3) {
+            var ppp = n_stack[s-3]
+            if(ppp.left === pp) {
+              ppp.left = n
+            } else {
+              ppp.right = n
+            }
+          }
+          break
+        }
+      }
+    } else {
+      if(p.right === n) {
+        var y = pp.left
+        if(y && y._color === RED) {
+          //console.log("RRr", y.key)
+          p._color = BLACK
+          pp.left = repaint(BLACK, y)
+          pp._color = RED
+          s -= 1
+        } else {
+          //console.log("RRb")
+          pp._color = RED
+          pp.right = p.left
+          p._color = BLACK
+          p.left = pp
+          n_stack[s-2] = p
+          n_stack[s-1] = n
+          recount(pp)
+          recount(p)
+          if(s >= 3) {
+            var ppp = n_stack[s-3]
+            if(ppp.right === pp) {
+              ppp.right = p
+            } else {
+              ppp.left = p
+            }
+          }
+          break
+        }
+      } else {
+        var y = pp.left
+        if(y && y._color === RED) {
+          //console.log("RLr")
+          p._color = BLACK
+          pp.left = repaint(BLACK, y)
+          pp._color = RED
+          s -= 1
+        } else {
+          //console.log("RLb")
+          p.left = n.right
+          pp._color = RED
+          pp.right = n.left
+          n._color = BLACK
+          n.right = p
+          n.left = pp
+          n_stack[s-2] = n
+          n_stack[s-1] = p
+          recount(pp)
+          recount(p)
+          recount(n)
+          if(s >= 3) {
+            var ppp = n_stack[s-3]
+            if(ppp.right === pp) {
+              ppp.right = n
+            } else {
+              ppp.left = n
+            }
+          }
+          break
+        }
+      }
+    }
+  }
+  //Return new tree
+  n_stack[0]._color = BLACK
+  return new RedBlackTree(cmp, n_stack[0])
+}
+
+
+//Visit all nodes inorder
+function doVisitFull(visit, node) {
+  if(node.left) {
+    var v = doVisitFull(visit, node.left)
+    if(v) { return v }
+  }
+  var v = visit(node.key, node.value)
+  if(v) { return v }
+  if(node.right) {
+    return doVisitFull(visit, node.right)
+  }
+}
+
+//Visit half nodes in order
+function doVisitHalf(lo, compare, visit, node) {
+  var l = compare(lo, node.key)
+  if(l <= 0) {
+    if(node.left) {
+      var v = doVisitHalf(lo, compare, visit, node.left)
+      if(v) { return v }
+    }
+    var v = visit(node.key, node.value)
+    if(v) { return v }
+  }
+  if(node.right) {
+    return doVisitHalf(lo, compare, visit, node.right)
+  }
+}
+
+//Visit all nodes within a range
+function doVisit(lo, hi, compare, visit, node) {
+  var l = compare(lo, node.key)
+  var h = compare(hi, node.key)
+  var v
+  if(l <= 0) {
+    if(node.left) {
+      v = doVisit(lo, hi, compare, visit, node.left)
+      if(v) { return v }
+    }
+    if(h > 0) {
+      v = visit(node.key, node.value)
+      if(v) { return v }
+    }
+  }
+  if(h > 0 && node.right) {
+    return doVisit(lo, hi, compare, visit, node.right)
+  }
+}
+
+
+proto.forEach = function rbTreeForEach(visit, lo, hi) {
+  if(!this.root) {
+    return
+  }
+  switch(arguments.length) {
+    case 1:
+      return doVisitFull(visit, this.root)
+    break
+
+    case 2:
+      return doVisitHalf(lo, this._compare, visit, this.root)
+    break
+
+    case 3:
+      if(this._compare(lo, hi) >= 0) {
+        return
+      }
+      return doVisit(lo, hi, this._compare, visit, this.root)
+    break
+  }
+}
+
+//First item in list
+Object.defineProperty(proto, "begin", {
+  get: function() {
+    var stack = []
+    var n = this.root
+    while(n) {
+      stack.push(n)
+      n = n.left
+    }
+    return new RedBlackTreeIterator(this, stack)
+  }
+})
+
+//Last item in list
+Object.defineProperty(proto, "end", {
+  get: function() {
+    var stack = []
+    var n = this.root
+    while(n) {
+      stack.push(n)
+      n = n.right
+    }
+    return new RedBlackTreeIterator(this, stack)
+  }
+})
+
+//Find the ith item in the tree
+proto.at = function(idx) {
+  if(idx < 0) {
+    return new RedBlackTreeIterator(this, [])
+  }
+  var n = this.root
+  var stack = []
+  while(true) {
+    stack.push(n)
+    if(n.left) {
+      if(idx < n.left._count) {
+        n = n.left
+        continue
+      }
+      idx -= n.left._count
+    }
+    if(!idx) {
+      return new RedBlackTreeIterator(this, stack)
+    }
+    idx -= 1
+    if(n.right) {
+      if(idx >= n.right._count) {
+        break
+      }
+      n = n.right
+    } else {
+      break
+    }
+  }
+  return new RedBlackTreeIterator(this, [])
+}
+
+proto.ge = function(key) {
+  var cmp = this._compare
+  var n = this.root
+  var stack = []
+  var last_ptr = 0
+  while(n) {
+    var d = cmp(key, n.key)
+    stack.push(n)
+    if(d <= 0) {
+      last_ptr = stack.length
+    }
+    if(d <= 0) {
+      n = n.left
+    } else {
+      n = n.right
+    }
+  }
+  stack.length = last_ptr
+  return new RedBlackTreeIterator(this, stack)
+}
+
+proto.gt = function(key) {
+  var cmp = this._compare
+  var n = this.root
+  var stack = []
+  var last_ptr = 0
+  while(n) {
+    var d = cmp(key, n.key)
+    stack.push(n)
+    if(d < 0) {
+      last_ptr = stack.length
+    }
+    if(d < 0) {
+      n = n.left
+    } else {
+      n = n.right
+    }
+  }
+  stack.length = last_ptr
+  return new RedBlackTreeIterator(this, stack)
+}
+
+proto.lt = function(key) {
+  var cmp = this._compare
+  var n = this.root
+  var stack = []
+  var last_ptr = 0
+  while(n) {
+    var d = cmp(key, n.key)
+    stack.push(n)
+    if(d > 0) {
+      last_ptr = stack.length
+    }
+    if(d <= 0) {
+      n = n.left
+    } else {
+      n = n.right
+    }
+  }
+  stack.length = last_ptr
+  return new RedBlackTreeIterator(this, stack)
+}
+
+proto.le = function(key) {
+  var cmp = this._compare
+  var n = this.root
+  var stack = []
+  var last_ptr = 0
+  while(n) {
+    var d = cmp(key, n.key)
+    stack.push(n)
+    if(d >= 0) {
+      last_ptr = stack.length
+    }
+    if(d < 0) {
+      n = n.left
+    } else {
+      n = n.right
+    }
+  }
+  stack.length = last_ptr
+  return new RedBlackTreeIterator(this, stack)
+}
+
+//Finds the item with key if it exists
+proto.find = function(key) {
+  var cmp = this._compare
+  var n = this.root
+  var stack = []
+  while(n) {
+    var d = cmp(key, n.key)
+    stack.push(n)
+    if(d === 0) {
+      return new RedBlackTreeIterator(this, stack)
+    }
+    if(d <= 0) {
+      n = n.left
+    } else {
+      n = n.right
+    }
+  }
+  return new RedBlackTreeIterator(this, [])
+}
+
+//Removes item with key from tree
+proto.remove = function(key) {
+  var iter = this.find(key)
+  if(iter) {
+    return iter.remove()
+  }
+  return this
+}
+
+//Returns the item at `key`
+proto.get = function(key) {
+  var cmp = this._compare
+  var n = this.root
+  while(n) {
+    var d = cmp(key, n.key)
+    if(d === 0) {
+      return n.value
+    }
+    if(d <= 0) {
+      n = n.left
+    } else {
+      n = n.right
+    }
+  }
+  return
+}
+
+//Iterator for red black tree
+function RedBlackTreeIterator(tree, stack) {
+  this.tree = tree
+  this._stack = stack
+}
+
+var iproto = RedBlackTreeIterator.prototype
+
+//Test if iterator is valid
+Object.defineProperty(iproto, "valid", {
+  get: function() {
+    return this._stack.length > 0
+  }
+})
+
+//Node of the iterator
+Object.defineProperty(iproto, "node", {
+  get: function() {
+    if(this._stack.length > 0) {
+      return this._stack[this._stack.length-1]
+    }
+    return null
+  },
+  enumerable: true
+})
+
+//Makes a copy of an iterator
+iproto.clone = function() {
+  return new RedBlackTreeIterator(this.tree, this._stack.slice())
+}
+
+//Swaps two nodes
+function swapNode(n, v) {
+  n.key = v.key
+  n.value = v.value
+  n.left = v.left
+  n.right = v.right
+  n._color = v._color
+  n._count = v._count
+}
+
+//Fix up a double black node in a tree
+function fixDoubleBlack(stack) {
+  var n, p, s, z
+  for(var i=stack.length-1; i>=0; --i) {
+    n = stack[i]
+    if(i === 0) {
+      n._color = BLACK
+      return
+    }
+    //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key)
+    p = stack[i-1]
+    if(p.left === n) {
+      //console.log("left child")
+      s = p.right
+      if(s.right && s.right._color === RED) {
+        //console.log("case 1: right sibling child red")
+        s = p.right = cloneNode(s)
+        z = s.right = cloneNode(s.right)
+        p.right = s.left
+        s.left = p
+        s.right = z
+        s._color = p._color
+        n._color = BLACK
+        p._color = BLACK
+        z._color = BLACK
+        recount(p)
+        recount(s)
+        if(i > 1) {
+          var pp = stack[i-2]
+          if(pp.left === p) {
+            pp.left = s
+          } else {
+            pp.right = s
+          }
+        }
+        stack[i-1] = s
+        return
+      } else if(s.left && s.left._color === RED) {
+        //console.log("case 1: left sibling child red")
+        s = p.right = cloneNode(s)
+        z = s.left = cloneNode(s.left)
+        p.right = z.left
+        s.left = z.right
+        z.left = p
+        z.right = s
+        z._color = p._color
+        p._color = BLACK
+        s._color = BLACK
+        n._color = BLACK
+        recount(p)
+        recount(s)
+        recount(z)
+        if(i > 1) {
+          var pp = stack[i-2]
+          if(pp.left === p) {
+            pp.left = z
+          } else {
+            pp.right = z
+          }
+        }
+        stack[i-1] = z
+        return
+      }
+      if(s._color === BLACK) {
+        if(p._color === RED) {
+          //console.log("case 2: black sibling, red parent", p.right.value)
+          p._color = BLACK
+          p.right = repaint(RED, s)
+          return
+        } else {
+          //console.log("case 2: black sibling, black parent", p.right.value)
+          p.right = repaint(RED, s)
+          continue  
+        }
+      } else {
+        //console.log("case 3: red sibling")
+        s = cloneNode(s)
+        p.right = s.left
+        s.left = p
+        s._color = p._color
+        p._color = RED
+        recount(p)
+        recount(s)
+        if(i > 1) {
+          var pp = stack[i-2]
+          if(pp.left === p) {
+            pp.left = s
+          } else {
+            pp.right = s
+          }
+        }
+        stack[i-1] = s
+        stack[i] = p
+        if(i+1 < stack.length) {
+          stack[i+1] = n
+        } else {
+          stack.push(n)
+        }
+        i = i+2
+      }
+    } else {
+      //console.log("right child")
+      s = p.left
+      if(s.left && s.left._color === RED) {
+        //console.log("case 1: left sibling child red", p.value, p._color)
+        s = p.left = cloneNode(s)
+        z = s.left = cloneNode(s.left)
+        p.left = s.right
+        s.right = p
+        s.left = z
+        s._color = p._color
+        n._color = BLACK
+        p._color = BLACK
+        z._color = BLACK
+        recount(p)
+        recount(s)
+        if(i > 1) {
+          var pp = stack[i-2]
+          if(pp.right === p) {
+            pp.right = s
+          } else {
+            pp.left = s
+          }
+        }
+        stack[i-1] = s
+        return
+      } else if(s.right && s.right._color === RED) {
+        //console.log("case 1: right sibling child red")
+        s = p.left = cloneNode(s)
+        z = s.right = cloneNode(s.right)
+        p.left = z.right
+        s.right = z.left
+        z.right = p
+        z.left = s
+        z._color = p._color
+        p._color = BLACK
+        s._color = BLACK
+        n._color = BLACK
+        recount(p)
+        recount(s)
+        recount(z)
+        if(i > 1) {
+          var pp = stack[i-2]
+          if(pp.right === p) {
+            pp.right = z
+          } else {
+            pp.left = z
+          }
+        }
+        stack[i-1] = z
+        return
+      }
+      if(s._color === BLACK) {
+        if(p._color === RED) {
+          //console.log("case 2: black sibling, red parent")
+          p._color = BLACK
+          p.left = repaint(RED, s)
+          return
+        } else {
+          //console.log("case 2: black sibling, black parent")
+          p.left = repaint(RED, s)
+          continue  
+        }
+      } else {
+        //console.log("case 3: red sibling")
+        s = cloneNode(s)
+        p.left = s.right
+        s.right = p
+        s._color = p._color
+        p._color = RED
+        recount(p)
+        recount(s)
+        if(i > 1) {
+          var pp = stack[i-2]
+          if(pp.right === p) {
+            pp.right = s
+          } else {
+            pp.left = s
+          }
+        }
+        stack[i-1] = s
+        stack[i] = p
+        if(i+1 < stack.length) {
+          stack[i+1] = n
+        } else {
+          stack.push(n)
+        }
+        i = i+2
+      }
+    }
+  }
+}
+
+//Removes item at iterator from tree
+iproto.remove = function() {
+  var stack = this._stack
+  if(stack.length === 0) {
+    return this.tree
+  }
+  //First copy path to node
+  var cstack = new Array(stack.length)
+  var n = stack[stack.length-1]
+  cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count)
+  for(var i=stack.length-2; i>=0; --i) {
+    var n = stack[i]
+    if(n.left === stack[i+1]) {
+      cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
+    } else {
+      cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
+    }
+  }
+
+  //Get node
+  n = cstack[cstack.length-1]
+  //console.log("start remove: ", n.value)
+
+  //If not leaf, then swap with previous node
+  if(n.left && n.right) {
+    //console.log("moving to leaf")
+
+    //First walk to previous leaf
+    var split = cstack.length
+    n = n.left
+    while(n.right) {
+      cstack.push(n)
+      n = n.right
+    }
+    //Copy path to leaf
+    var v = cstack[split-1]
+    cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count))
+    cstack[split-1].key = n.key
+    cstack[split-1].value = n.value
+
+    //Fix up stack
+    for(var i=cstack.length-2; i>=split; --i) {
+      n = cstack[i]
+      cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
+    }
+    cstack[split-1].left = cstack[split]
+  }
+  //console.log("stack=", cstack.map(function(v) { return v.value }))
+
+  //Remove leaf node
+  n = cstack[cstack.length-1]
+  if(n._color === RED) {
+    //Easy case: removing red leaf
+    //console.log("RED leaf")
+    var p = cstack[cstack.length-2]
+    if(p.left === n) {
+      p.left = null
+    } else if(p.right === n) {
+      p.right = null
+    }
+    cstack.pop()
+    for(var i=0; i<cstack.length; ++i) {
+      cstack[i]._count--
+    }
+    return new RedBlackTree(this.tree._compare, cstack[0])
+  } else {
+    if(n.left || n.right) {
+      //Second easy case:  Single child black parent
+      //console.log("BLACK single child")
+      if(n.left) {
+        swapNode(n, n.left)
+      } else if(n.right) {
+        swapNode(n, n.right)
+      }
+      //Child must be red, so repaint it black to balance color
+      n._color = BLACK
+      for(var i=0; i<cstack.length-1; ++i) {
+        cstack[i]._count--
+      }
+      return new RedBlackTree(this.tree._compare, cstack[0])
+    } else if(cstack.length === 1) {
+      //Third easy case: root
+      //console.log("ROOT")
+      return new RedBlackTree(this.tree._compare, null)
+    } else {
+      //Hard case: Repaint n, and then do some nasty stuff
+      //console.log("BLACK leaf no children")
+      for(var i=0; i<cstack.length; ++i) {
+        cstack[i]._count--
+      }
+      var parent = cstack[cstack.length-2]
+      fixDoubleBlack(cstack)
+      //Fix up links
+      if(parent.left === n) {
+        parent.left = null
+      } else {
+        parent.right = null
+      }
+    }
+  }
+  return new RedBlackTree(this.tree._compare, cstack[0])
+}
+
+//Returns key
+Object.defineProperty(iproto, "key", {
+  get: function() {
+    if(this._stack.length > 0) {
+      return this._stack[this._stack.length-1].key
+    }
+    return
+  },
+  enumerable: true
+})
+
+//Returns value
+Object.defineProperty(iproto, "value", {
+  get: function() {
+    if(this._stack.length > 0) {
+      return this._stack[this._stack.length-1].value
+    }
+    return
+  },
+  enumerable: true
+})
+
+
+//Returns the position of this iterator in the sorted list
+Object.defineProperty(iproto, "index", {
+  get: function() {
+    var idx = 0
+    var stack = this._stack
+    if(stack.length === 0) {
+      var r = this.tree.root
+      if(r) {
+        return r._count
+      }
+      return 0
+    } else if(stack[stack.length-1].left) {
+      idx = stack[stack.length-1].left._count
+    }
+    for(var s=stack.length-2; s>=0; --s) {
+      if(stack[s+1] === stack[s].right) {
+        ++idx
+        if(stack[s].left) {
+          idx += stack[s].left._count
+        }
+      }
+    }
+    return idx
+  },
+  enumerable: true
+})
+
+//Advances iterator to next element in list
+iproto.next = function() {
+  var stack = this._stack
+  if(stack.length === 0) {
+    return
+  }
+  var n = stack[stack.length-1]
+  if(n.right) {
+    n = n.right
+    while(n) {
+      stack.push(n)
+      n = n.left
+    }
+  } else {
+    stack.pop()
+    while(stack.length > 0 && stack[stack.length-1].right === n) {
+      n = stack[stack.length-1]
+      stack.pop()
+    }
+  }
+}
+
+//Checks if iterator is at end of tree
+Object.defineProperty(iproto, "hasNext", {
+  get: function() {
+    var stack = this._stack
+    if(stack.length === 0) {
+      return false
+    }
+    if(stack[stack.length-1].right) {
+      return true
+    }
+    for(var s=stack.length-1; s>0; --s) {
+      if(stack[s-1].left === stack[s]) {
+        return true
+      }
+    }
+    return false
+  }
+})
+
+//Update value
+iproto.update = function(value) {
+  var stack = this._stack
+  if(stack.length === 0) {
+    throw new Error("Can't update empty node!")
+  }
+  var cstack = new Array(stack.length)
+  var n = stack[stack.length-1]
+  cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count)
+  for(var i=stack.length-2; i>=0; --i) {
+    n = stack[i]
+    if(n.left === stack[i+1]) {
+      cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count)
+    } else {
+      cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count)
+    }
+  }
+  return new RedBlackTree(this.tree._compare, cstack[0])
+}
+
+//Moves iterator backward one element
+iproto.prev = function() {
+  var stack = this._stack
+  if(stack.length === 0) {
+    return
+  }
+  var n = stack[stack.length-1]
+  if(n.left) {
+    n = n.left
+    while(n) {
+      stack.push(n)
+      n = n.right
+    }
+  } else {
+    stack.pop()
+    while(stack.length > 0 && stack[stack.length-1].left === n) {
+      n = stack[stack.length-1]
+      stack.pop()
+    }
+  }
+}
+
+//Checks if iterator is at start of tree
+Object.defineProperty(iproto, "hasPrev", {
+  get: function() {
+    var stack = this._stack
+    if(stack.length === 0) {
+      return false
+    }
+    if(stack[stack.length-1].left) {
+      return true
+    }
+    for(var s=stack.length-1; s>0; --s) {
+      if(stack[s-1].right === stack[s]) {
+        return true
+      }
+    }
+    return false
+  }
+})
+
+//Default comparison function
+function defaultCompare(a, b) {
+  if(a < b) {
+    return -1
+  }
+  if(a > b) {
+    return 1
+  }
+  return 0
+}
+
+//Build a tree
+function createRBTree(compare) {
+  return new RedBlackTree(compare || defaultCompare, null)
+}
+},{}],288:[function(require,module,exports){
+"use strict"
+
+module.exports = createSlabDecomposition
+
+var bounds = require("binary-search-bounds")
+var createRBTree = require("functional-red-black-tree")
+var orient = require("robust-orientation")
+var orderSegments = require("./lib/order-segments")
+
+function SlabDecomposition(slabs, coordinates, horizontal) {
+  this.slabs = slabs
+  this.coordinates = coordinates
+  this.horizontal = horizontal
+}
+
+var proto = SlabDecomposition.prototype
+
+function compareHorizontal(e, y) {
+  return e.y - y
+}
+
+function searchBucket(root, p) {
+  var lastNode = null
+  while(root) {
+    var seg = root.key
+    var l, r
+    if(seg[0][0] < seg[1][0]) {
+      l = seg[0]
+      r = seg[1]
+    } else {
+      l = seg[1]
+      r = seg[0]
+    }
+    var o = orient(l, r, p)
+    if(o < 0) {
+      root = root.left
+    } else if(o > 0) {
+      if(p[0] !== seg[1][0]) {
+        lastNode = root
+        root = root.right
+      } else {
+        var val = searchBucket(root.right, p)
+        if(val) {
+          return val
+        }
+        root = root.left
+      }
+    } else {
+      if(p[0] !== seg[1][0]) {
+        return root
+      } else {
+        var val = searchBucket(root.right, p)
+        if(val) {
+          return val
+        }
+        root = root.left
+      }
+    }
+  }
+  return lastNode
+}
+
+proto.castUp = function(p) {
+  var bucket = bounds.le(this.coordinates, p[0])
+  if(bucket < 0) {
+    return -1
+  }
+  var root = this.slabs[bucket]
+  var hitNode = searchBucket(this.slabs[bucket], p)
+  var lastHit = -1
+  if(hitNode) {
+    lastHit = hitNode.value
+  }
+  //Edge case: need to handle horizontal segments (sucks)
+  if(this.coordinates[bucket] === p[0]) {
+    var lastSegment = null
+    if(hitNode) {
+      lastSegment = hitNode.key
+    }
+    if(bucket > 0) {
+      var otherHitNode = searchBucket(this.slabs[bucket-1], p)
+      if(otherHitNode) {
+        if(lastSegment) {
+          if(orderSegments(otherHitNode.key, lastSegment) > 0) {
+            lastSegment = otherHitNode.key
+            lastHit = otherHitNode.value
+          }
+        } else {
+          lastHit = otherHitNode.value
+          lastSegment = otherHitNode.key
+        }
+      }
+    }
+    var horiz = this.horizontal[bucket]
+    if(horiz.length > 0) {
+      var hbucket = bounds.ge(horiz, p[1], compareHorizontal)
+      if(hbucket < horiz.length) {
+        var e = horiz[hbucket]
+        if(p[1] === e.y) {
+          if(e.closed) {
+            return e.index
+          } else {
+            while(hbucket < horiz.length-1 && horiz[hbucket+1].y === p[1]) {
+              hbucket = hbucket+1
+              e = horiz[hbucket]
+              if(e.closed) {
+                return e.index
+              }
+            }
+            if(e.y === p[1] && !e.start) {
+              hbucket = hbucket+1
+              if(hbucket >= horiz.length) {
+                return lastHit
+              }
+              e = horiz[hbucket]
+            }
+          }
+        }
+        //Check if e is above/below last segment
+        if(e.start) {
+          if(lastSegment) {
+            var o = orient(lastSegment[0], lastSegment[1], [p[0], e.y])
+            if(lastSegment[0][0] > lastSegment[1][0]) {
+              o = -o
+            }
+            if(o > 0) {
+              lastHit = e.index
+            }
+          } else {
+            lastHit = e.index
+          }
+        } else if(e.y !== p[1]) {
+          lastHit = e.index
+        }
+      }
+    }
+  }
+  return lastHit
+}
+
+function IntervalSegment(y, index, start, closed) {
+  this.y = y
+  this.index = index
+  this.start = start
+  this.closed = closed
+}
+
+function Event(x, segment, create, index) {
+  this.x = x
+  this.segment = segment
+  this.create = create
+  this.index = index
+}
+
+
+function createSlabDecomposition(segments) {
+  var numSegments = segments.length
+  var numEvents = 2 * numSegments
+  var events = new Array(numEvents)
+  for(var i=0; i<numSegments; ++i) {
+    var s = segments[i]
+    var f = s[0][0] < s[1][0]
+    events[2*i] = new Event(s[0][0], s, f, i)
+    events[2*i+1] = new Event(s[1][0], s, !f, i)
+  }
+  events.sort(function(a,b) {
+    var d = a.x - b.x
+    if(d) {
+      return d
+    }
+    d = a.create - b.create
+    if(d) {
+      return d
+    }
+    return Math.min(a.segment[0][1], a.segment[1][1]) - Math.min(b.segment[0][1], b.segment[1][1])
+  })
+  var tree = createRBTree(orderSegments)
+  var slabs = []
+  var lines = []
+  var horizontal = []
+  var lastX = -Infinity
+  for(var i=0; i<numEvents; ) {
+    var x = events[i].x
+    var horiz = []
+    while(i < numEvents) {
+      var e = events[i]
+      if(e.x !== x) {
+        break
+      }
+      i += 1
+      if(e.segment[0][0] === e.x && e.segment[1][0] === e.x) {
+        if(e.create) {
+          if(e.segment[0][1] < e.segment[1][1]) {
+            horiz.push(new IntervalSegment(
+                e.segment[0][1],
+                e.index,
+                true,
+                true))
+            horiz.push(new IntervalSegment(
+                e.segment[1][1],
+                e.index,
+                false,
+                false))
+          } else {
+            horiz.push(new IntervalSegment(
+                e.segment[1][1],
+                e.index,
+                true,
+                false))
+            horiz.push(new IntervalSegment(
+                e.segment[0][1],
+                e.index,
+                false,
+                true))
+          }
+        }
+      } else {
+        if(e.create) {
+          tree = tree.insert(e.segment, e.index)
+        } else {
+          tree = tree.remove(e.segment)
+        }
+      }
+    }
+    slabs.push(tree.root)
+    lines.push(x)
+    horizontal.push(horiz)
+  }
+  return new SlabDecomposition(slabs, lines, horizontal)
+}
+},{"./lib/order-segments":286,"binary-search-bounds":284,"functional-red-black-tree":287,"robust-orientation":214}],289:[function(require,module,exports){
+module.exports = preprocessPolygon
+
+var orient = require('robust-orientation')[3]
+var makeSlabs = require('slab-decomposition')
+var makeIntervalTree = require('interval-tree-1d')
+var bsearch = require('binary-search-bounds')
+
+function visitInterval() {
+  return true
+}
+
+function intervalSearch(table) {
+  return function(x, y) {
+    var tree = table[x]
+    if(tree) {
+      return !!tree.queryPoint(y, visitInterval)
+    }
+    return false
+  }
+}
+
+function buildVerticalIndex(segments) {
+  var table = {}
+  for(var i=0; i<segments.length; ++i) {
+    var s = segments[i]
+    var x = s[0][0]
+    var y0 = s[0][1]
+    var y1 = s[1][1]
+    var p = [ Math.min(y0, y1), Math.max(y0, y1) ]
+    if(x in table) {
+      table[x].push(p)
+    } else {
+      table[x] = [ p ]
+    }
+  }
+  var intervalTable = {}
+  var keys = Object.keys(table)
+  for(var i=0; i<keys.length; ++i) {
+    var segs = table[keys[i]]
+    intervalTable[keys[i]] = makeIntervalTree(segs)
+  }
+  return intervalSearch(intervalTable)
+}
+
+function buildSlabSearch(slabs, coordinates) {
+  return function(p) {
+    var bucket = bsearch.le(coordinates, p[0])
+    if(bucket < 0) {
+      return 1
+    }
+    var root = slabs[bucket]
+    if(!root) {
+      if(bucket > 0 && coordinates[bucket] === p[0]) {
+        root = slabs[bucket-1]
+      } else {
+        return 1
+      }
+    }
+    var lastOrientation = 1
+    while(root) {
+      var s = root.key
+      var o = orient(p, s[0], s[1])
+      if(s[0][0] < s[1][0]) {
+        if(o < 0) {
+          root = root.left
+        } else if(o > 0) {
+          lastOrientation = -1
+          root = root.right
+        } else {
+          return 0
+        }
+      } else {
+        if(o > 0) {
+          root = root.left
+        } else if(o < 0) {
+          lastOrientation = 1
+          root = root.right
+        } else {
+          return 0
+        }
+      }
+    }
+    return lastOrientation
+  }
+}
+
+function classifyEmpty(p) {
+  return 1
+}
+
+function createClassifyVertical(testVertical) {
+  return function classify(p) {
+    if(testVertical(p[0], p[1])) {
+      return 0
+    }
+    return 1
+  }
+}
+
+function createClassifyPointDegen(testVertical, testNormal) {
+  return function classify(p) {
+    if(testVertical(p[0], p[1])) {
+      return 0
+    }
+    return testNormal(p)
+  }
+}
+
+function preprocessPolygon(loops) {
+  //Compute number of loops
+  var numLoops = loops.length
+
+  //Unpack segments
+  var segments = []
+  var vsegments = []
+  var ptr = 0
+  for(var i=0; i<numLoops; ++i) {
+    var loop = loops[i]
+    var numVertices = loop.length
+    for(var s=numVertices-1,t=0; t<numVertices; s=(t++)) {
+      var a = loop[s]
+      var b = loop[t]
+      if(a[0] === b[0]) {
+        vsegments.push([a,b])
+      } else {
+        segments.push([a,b])
+      }
+    }
+  }
+
+  //Degenerate case: All loops are empty
+  if(segments.length === 0) {
+    if(vsegments.length === 0) {
+      return classifyEmpty
+    } else {
+      return createClassifyVertical(buildVerticalIndex(vsegments))
+    }
+  }
+
+  //Build slab decomposition
+  var slabs = makeSlabs(segments)
+  var testSlab = buildSlabSearch(slabs.slabs, slabs.coordinates)
+
+  if(vsegments.length === 0) {
+    return testSlab
+  } else {
+    return createClassifyPointDegen(
+      buildVerticalIndex(vsegments),
+      testSlab)
+  }
+}
+},{"binary-search-bounds":284,"interval-tree-1d":285,"robust-orientation":214,"slab-decomposition":288}],290:[function(require,module,exports){
+'use strict'
+
+module.exports = planarGraphToPolyline
+
+var e2a = require('edges-to-adjacency-list')
+var planarDual = require('planar-dual')
+var preprocessPolygon = require('point-in-big-polygon')
+var twoProduct = require('two-product')
+var robustSum = require('robust-sum')
+var uniq = require('uniq')
+var trimLeaves = require('./lib/trim-leaves')
+
+function makeArray(length, fill) {
+  var result = new Array(length)
+  for(var i=0; i<length; ++i) {
+    result[i] = fill
+  }
+  return result
+}
+
+function makeArrayOfArrays(length) {
+  var result = new Array(length)
+  for(var i=0; i<length; ++i) {
+    result[i] = []
+  }
+  return result
+}
+
+
+function planarGraphToPolyline(edges, positions) {
+
+  //Trim leaves
+  var result = trimLeaves(edges, positions)
+  edges = result[0]
+  positions = result[1]
+
+  var numVertices = positions.length
+  var numEdges = edges.length
+
+  //Calculate adjacency list, check manifold
+  var adj = e2a(edges, positions.length)
+  for(var i=0; i<numVertices; ++i) {
+    if(adj[i].length % 2 === 1) {
+      throw new Error('planar-graph-to-polyline: graph must be manifold')
+    }
+  }
+
+  //Get faces
+  var faces = planarDual(edges, positions)
+
+  //Check orientation of a polygon using exact arithmetic
+  function ccw(c) {
+    var n = c.length
+    var area = [0]
+    for(var j=0; j<n; ++j) {
+      var a = positions[c[j]]
+      var b = positions[c[(j+1)%n]]
+      var t00 = twoProduct(-a[0], a[1])
+      var t01 = twoProduct(-a[0], b[1])
+      var t10 = twoProduct( b[0], a[1])
+      var t11 = twoProduct( b[0], b[1])
+      area = robustSum(area, robustSum(robustSum(t00, t01), robustSum(t10, t11)))
+    }
+    return area[area.length-1] > 0
+  }
+
+  //Extract all clockwise faces
+  faces = faces.filter(ccw)
+
+  //Detect which loops are contained in one another to handle parent-of relation
+  var numFaces = faces.length
+  var parent = new Array(numFaces)
+  var containment = new Array(numFaces)
+  for(var i=0; i<numFaces; ++i) {
+    parent[i] = i
+    var row = new Array(numFaces)
+    var loopVertices = faces[i].map(function(v) {
+      return positions[v]
+    })
+    var pmc = preprocessPolygon([loopVertices])
+    var count = 0
+    outer:
+    for(var j=0; j<numFaces; ++j) {
+      row[j] = 0
+      if(i === j) {
+        continue
+      }
+      var c = faces[j]
+      var n = c.length
+      for(var k=0; k<n; ++k) {
+        var d = pmc(positions[c[k]])
+        if(d !== 0) {
+          if(d < 0) {
+            row[j] = 1
+            count += 1
+          }
+          continue outer
+        }
+      }
+      row[j] = 1
+      count += 1
+    }
+    containment[i] = [count, i, row]
+  }
+  containment.sort(function(a,b) {
+    return b[0] - a[0]
+  })
+  for(var i=0; i<numFaces; ++i) {
+    var row = containment[i]
+    var idx = row[1]
+    var children = row[2]
+    for(var j=0; j<numFaces; ++j) {
+      if(children[j]) {
+        parent[j] = idx
+      }
+    }
+  }
+
+  //Initialize face adjacency list
+  var fadj = makeArrayOfArrays(numFaces)
+  for(var i=0; i<numFaces; ++i) {
+    fadj[i].push(parent[i])
+    fadj[parent[i]].push(i)
+  }
+
+  //Build adjacency matrix for edges
+  var edgeAdjacency = {}
+  var internalVertices = makeArray(numVertices, false)
+  for(var i=0; i<numFaces; ++i) {
+    var c = faces[i]
+    var n = c.length
+    for(var j=0; j<n; ++j) {
+      var a = c[j]
+      var b = c[(j+1)%n]
+      var key = Math.min(a,b) + ":" + Math.max(a,b)
+      if(key in edgeAdjacency) {
+        var neighbor = edgeAdjacency[key]
+        fadj[neighbor].push(i)
+        fadj[i].push(neighbor)
+        internalVertices[a] = internalVertices[b] = true
+      } else {
+        edgeAdjacency[key] = i
+      }
+    }
+  }
+
+  function sharedBoundary(c) {
+    var n = c.length
+    for(var i=0; i<n; ++i) {
+      if(!internalVertices[c[i]]) {
+        return false
+      }
+    }
+    return true
+  }
+
+  var toVisit = []
+  var parity = makeArray(numFaces, -1)
+  for(var i=0; i<numFaces; ++i) {
+    if(parent[i] === i && !sharedBoundary(faces[i])) {
+      toVisit.push(i)
+      parity[i] = 0
+    } else {
+      parity[i] = -1
+    }
+  }
+
+  //Using face adjacency, classify faces as in/out
+  var result = []
+  while(toVisit.length > 0) {
+    var top = toVisit.pop()
+    var nbhd = fadj[top]
+    uniq(nbhd, function(a,b) {
+      return a-b
+    })
+    var nnbhr = nbhd.length
+    var p = parity[top]
+    var polyline
+    if(p === 0) {
+      var c = faces[top]
+      polyline = [c]
+    }
+    for(var i=0; i<nnbhr; ++i) {
+      var f = nbhd[i]
+      if(parity[f] >= 0) {
+        continue
+      }
+      parity[f] = p^1
+      toVisit.push(f)
+      if(p === 0) {
+        var c = faces[f]
+        if(!sharedBoundary(c)) {
+          c.reverse()
+          polyline.push(c)
+        }
+      }
+    }
+    if(p === 0) {
+      result.push(polyline)
+    }
+  }
+
+  return result
+}
+},{"./lib/trim-leaves":278,"edges-to-adjacency-list":279,"planar-dual":280,"point-in-big-polygon":289,"robust-sum":217,"two-product":231,"uniq":234}],291:[function(require,module,exports){
+arguments[4][49][0].apply(exports,arguments)
+},{"dup":49}],292:[function(require,module,exports){
+"use strict"; "use restrict";
+
+module.exports = UnionFind;
+
+function UnionFind(count) {
+  this.roots = new Array(count);
+  this.ranks = new Array(count);
+  
+  for(var i=0; i<count; ++i) {
+    this.roots[i] = i;
+    this.ranks[i] = 0;
+  }
+}
+
+UnionFind.prototype.length = function() {
+  return this.roots.length;
+}
+
+UnionFind.prototype.makeSet = function() {
+  var n = this.roots.length;
+  this.roots.push(n);
+  this.ranks.push(0);
+  return n;
+}
+
+UnionFind.prototype.find = function(x) {
+  var roots = this.roots;
+  while(roots[x] !== x) {
+    var y = roots[x];
+    roots[x] = roots[y];
+    x = y;
+  }
+  return x;
+}
+
+UnionFind.prototype.link = function(x, y) {
+  var xr = this.find(x)
+    , yr = this.find(y);
+  if(xr === yr) {
+    return;
+  }
+  var ranks = this.ranks
+    , roots = this.roots
+    , xd    = ranks[xr]
+    , yd    = ranks[yr];
+  if(xd < yd) {
+    roots[xr] = yr;
+  } else if(yd < xd) {
+    roots[yr] = xr;
+  } else {
+    roots[yr] = xr;
+    ++ranks[xr];
+  }
+}
+
+
+},{}],293:[function(require,module,exports){
+arguments[4][194][0].apply(exports,arguments)
+},{"bit-twiddle":291,"dup":194,"union-find":292}],294:[function(require,module,exports){
+"use strict"
+
+module.exports = simplifyPolygon
+
+var orient = require("robust-orientation")
+var sc = require("simplicial-complex")
+
+function errorWeight(base, a, b) {
+  var area = Math.abs(orient(base, a, b))
+  var perim = Math.sqrt(Math.pow(a[0] - b[0], 2) + Math.pow(a[1]-b[1], 2))
+  return area / perim
+}
+
+function simplifyPolygon(cells, positions, minArea) {
+
+  var n = positions.length
+  var nc = cells.length
+  var inv = new Array(n)
+  var outv = new Array(n)
+  var weights = new Array(n)
+  var dead = new Array(n)
+  
+  //Initialize tables
+  for(var i=0; i<n; ++i) {
+    inv[i] = outv[i] = -1
+    weights[i] = Infinity
+    dead[i] = false
+  }
+
+  //Compute neighbors
+  for(var i=0; i<nc; ++i) {
+    var c = cells[i]
+    if(c.length !== 2) {
+      throw new Error("Input must be a graph")
+    }
+    var s = c[1]
+    var t = c[0]
+    if(outv[t] !== -1) {
+      outv[t] = -2
+    } else {
+      outv[t] = s
+    }
+    if(inv[s] !== -1) {
+      inv[s] = -2
+    } else {
+      inv[s] = t
+    }
+  }
+
+  //Updates the weight for vertex i
+  function computeWeight(i) {
+    if(dead[i]) {
+      return Infinity
+    }
+    //TODO: Check that the line segment doesn't cross once simplified
+    var s = inv[i]
+    var t = outv[i]
+    if((s<0) || (t<0)) {
+      return Infinity
+    } else {
+      return errorWeight(positions[i], positions[s], positions[t])
+    }
+  }
+
+  //Swaps two nodes on the heap (i,j) are the index of the nodes
+  function heapSwap(i,j) {
+    var a = heap[i]
+    var b = heap[j]
+    heap[i] = b
+    heap[j] = a
+    index[a] = j
+    index[b] = i
+  }
+
+  //Returns the weight of node i on the heap
+  function heapWeight(i) {
+    return weights[heap[i]]
+  }
+
+  function heapParent(i) {
+    if(i & 1) {
+      return (i - 1) >> 1
+    }
+    return (i >> 1) - 1
+  }
+
+  //Bubble element i down the heap
+  function heapDown(i) {
+    var w = heapWeight(i)
+    while(true) {
+      var tw = w
+      var left  = 2*i + 1
+      var right = 2*(i + 1)
+      var next = i
+      if(left < heapCount) {
+        var lw = heapWeight(left)
+        if(lw < tw) {
+          next = left
+          tw = lw
+        }
+      }
+      if(right < heapCount) {
+        var rw = heapWeight(right)
+        if(rw < tw) {
+          next = right
+        }
+      }
+      if(next === i) {
+        return i
+      }
+      heapSwap(i, next)
+      i = next      
+    }
+  }
+
+  //Bubbles element i up the heap
+  function heapUp(i) {
+    var w = heapWeight(i)
+    while(i > 0) {
+      var parent = heapParent(i)
+      if(parent >= 0) {
+        var pw = heapWeight(parent)
+        if(w < pw) {
+          heapSwap(i, parent)
+          i = parent
+          continue
+        }
+      }
+      return i
+    }
+  }
+
+  //Pop minimum element
+  function heapPop() {
+    if(heapCount > 0) {
+      var head = heap[0]
+      heapSwap(0, heapCount-1)
+      heapCount -= 1
+      heapDown(0)
+      return head
+    }
+    return -1
+  }
+
+  //Update heap item i
+  function heapUpdate(i, w) {
+    var a = heap[i]
+    if(weights[a] === w) {
+      return i
+    }
+    weights[a] = -Infinity
+    heapUp(i)
+    heapPop()
+    weights[a] = w
+    heapCount += 1
+    return heapUp(heapCount-1)
+  }
+
+  //Kills a vertex (assume vertex already removed from heap)
+  function kill(i) {
+    if(dead[i]) {
+      return
+    }
+    //Kill vertex
+    dead[i] = true
+    //Fixup topology
+    var s = inv[i]
+    var t = outv[i]
+    if(inv[t] >= 0) {
+      inv[t] = s
+    }
+    if(outv[s] >= 0) {
+      outv[s] = t
+    }
+
+    //Update weights on s and t
+    if(index[s] >= 0) {
+      heapUpdate(index[s], computeWeight(s))
+    }
+    if(index[t] >= 0) {
+      heapUpdate(index[t], computeWeight(t))
+    }
+  }
+
+  //Initialize weights and heap
+  var heap = []
+  var index = new Array(n)
+  for(var i=0; i<n; ++i) {
+    var w = weights[i] = computeWeight(i)
+    if(w < Infinity) {
+      index[i] = heap.length
+      heap.push(i)
+    } else {
+      index[i] = -1
+    }
+  }
+  var heapCount = heap.length
+  for(var i=heapCount>>1; i>=0; --i) {
+    heapDown(i)
+  }
+  
+  //Kill vertices
+  while(true) {
+    var hmin = heapPop()
+    if((hmin < 0) || (weights[hmin] > minArea)) {
+      break
+    }
+    kill(hmin)
+  }
+
+  //Build collapsed vertex table
+  var npositions = []
+  for(var i=0; i<n; ++i) {
+    if(!dead[i]) {
+      index[i] = npositions.length
+      npositions.push(positions[i].slice())
+    }
+  }
+  var nv = npositions.length
+
+  function tortoiseHare(seq, start) {
+    if(seq[start] < 0) {
+      return start
+    }
+    var t = start
+    var h = start
+    do {
+      //Walk two steps with h
+      var nh = seq[h]
+      if(!dead[h] || nh < 0 || nh === h) {
+        break
+      }
+      h = nh
+      nh = seq[h]
+      if(!dead[h] || nh < 0 || nh === h) {
+        break
+      }
+      h = nh
+
+      //Walk one step with t
+      t = seq[t]
+    } while(t !== h)
+    //Compress cycles
+    for(var v=start; v!==h; v = seq[v]) {
+      seq[v] = h
+    }
+    return h
+  }
+
+  var ncells = []
+  cells.forEach(function(c) {
+    var tin = tortoiseHare(inv, c[0])
+    var tout = tortoiseHare(outv, c[1])
+    if(tin >= 0 && tout >= 0 && tin !== tout) {
+      var cin = index[tin]
+      var cout = index[tout]
+      if(cin !== cout) {
+        ncells.push([ cin, cout ])
+      }
+    }
+  })
+
+  //Normalize result
+  sc.unique(sc.normalize(ncells))
+
+  //Return final list of cells
+  return {
+    positions: npositions,
+    edges: ncells
+  }
+}
+},{"robust-orientation":214,"simplicial-complex":293}],295:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+/**
+ * centerx is a center of scaling tuned for maximum scalability of
+ * the arrowhead ie throughout mag=0.3..3 the head is joined smoothly
+ * to the line, but the endpoint moves.
+ * backoff is the distance to move the arrowhead, and the end of the
+ * line, in order to end at the right place
+ *
+ * TODO: option to have the pointed-to  point a little in front of the
+ * end of the line, as people tend to want a bit of a gap there...
+ */
+
+module.exports = [
+    // no arrow
+    '',
+    // wide with flat back
+    {
+        path: 'M-2.4,-3V3L0.6,0Z',
+        backoff: 0.6
+    },
+    // narrower with flat back
+    {
+        path: 'M-3.7,-2.5V2.5L1.3,0Z',
+        backoff: 1.3
+    },
+    // barbed
+    {
+        path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z',
+        backoff: 1.55
+    },
+    // wide line-drawn
+    {
+        path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z',
+        backoff: 1.6
+    },
+    // narrower line-drawn
+    {
+        path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z',
+        backoff: 2
+    },
+    // circle
+    {
+        path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z',
+        backoff: 0
+    },
+    // square
+    {
+        path: 'M2,2V-2H-2V2Z',
+        backoff: 0
+    }
+];
+
+},{}],296:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var ARROWPATHS = require('./arrow_paths');
+var Cartesian = require('../../plots/cartesian');
+var fontAttrs = require('../../plots/font_attributes');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+
+module.exports = {
+    _isLinkedToArray: true,
+
+    text: {
+        valType: 'string',
+        
+        
+    },
+    textangle: {
+        valType: 'angle',
+        dflt: 0,
+        
+        
+    },
+    font: extendFlat({}, fontAttrs, {
+        
+    }),
+    opacity: {
+        valType: 'number',
+        min: 0,
+        max: 1,
+        dflt: 1,
+        
+        
+    },
+    align: {
+        valType: 'enumerated',
+        values: ['left', 'center', 'right'],
+        dflt: 'center',
+        
+        
+    },
+    bgcolor: {
+        valType: 'color',
+        dflt: 'rgba(0,0,0,0)',
+        
+        
+    },
+    bordercolor: {
+        valType: 'color',
+        dflt: 'rgba(0,0,0,0)',
+        
+        
+    },
+    borderpad: {
+        valType: 'number',
+        min: 0,
+        dflt: 1,
+        
+        
+    },
+    borderwidth: {
+        valType: 'number',
+        min: 0,
+        dflt: 1,
+        
+        
+    },
+    // arrow
+    showarrow: {
+        valType: 'boolean',
+        dflt: true,
+        
+        
+    },
+    arrowcolor: {
+        valType: 'color',
+        
+        
+    },
+    arrowhead: {
+        valType: 'integer',
+        min: 0,
+        max: ARROWPATHS.length,
+        dflt: 1,
+        
+        
+    },
+    arrowsize: {
+        valType: 'number',
+        min: 0.3,
+        dflt: 1,
+        
+        
+    },
+    arrowwidth: {
+        valType: 'number',
+        min: 0.1,
+        
+        
+    },
+    ax: {
+        valType: 'number',
+        dflt: -10,
+        
+        
+    },
+    ay: {
+        valType: 'number',
+        dflt: -30,
+        
+        
+    },
+    // positioning
+    xref: {
+        valType: 'enumerated',
+        values: [
+            'paper',
+            Cartesian.idRegex.x.toString()
+        ],
+        
+        
+    },
+    x: {
+        valType: 'number',
+        
+        
+    },
+    xanchor: {
+        valType: 'enumerated',
+        values: ['auto', 'left', 'center', 'right'],
+        dflt: 'auto',
+        
+        
+    },
+    yref: {
+        valType: 'enumerated',
+        values: [
+            'paper',
+            Cartesian.idRegex.y.toString()
+        ],
+        
+        
+    },
+    y: {
+        valType: 'number',
+        
+        
+    },
+    yanchor: {
+        valType: 'enumerated',
+        values: ['auto', 'top', 'middle', 'bottom'],
+        dflt: 'auto',
+        
+        
+    },
+
+    _deprecated: {
+        ref: {
+            valType: 'string',
+            
+            
+        }
+    }
+};
+
+},{"../../lib/extend":345,"../../plots/cartesian":375,"../../plots/font_attributes":383,"./arrow_paths":295}],297:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../../plotly');
+var d3 = require('d3');
+var isNumeric = require('fast-isnumeric');
+
+var annotations = module.exports = {};
+
+annotations.ARROWPATHS = require('./arrow_paths');
+
+annotations.layoutAttributes = require('./attributes');
+
+annotations.supplyLayoutDefaults = function(layoutIn, layoutOut) {
+    var containerIn = layoutIn.annotations || [],
+        containerOut = layoutOut.annotations = [];
+
+    for(var i = 0; i < containerIn.length; i++) {
+        containerOut.push(handleAnnotationDefaults(containerIn[i] || {}, layoutOut));
+    }
+};
+
+function handleAnnotationDefaults(annIn, fullLayout) {
+    var annOut = {};
+
+    function coerce(attr, dflt) {
+        return Plotly.Lib.coerce(annIn, annOut, annotations.layoutAttributes, attr, dflt);
+    }
+
+    coerce('opacity');
+    coerce('align');
+    coerce('bgcolor');
+    var borderColor = coerce('bordercolor'),
+        borderOpacity = Plotly.Color.opacity(borderColor);
+    coerce('borderpad');
+    var borderWidth = coerce('borderwidth');
+    var showArrow = coerce('showarrow');
+    if(showArrow) {
+        coerce('arrowcolor',
+            borderOpacity ? annOut.bordercolor : Plotly.Color.defaultLine);
+        coerce('arrowhead');
+        coerce('arrowsize');
+        coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2);
+        coerce('ax');
+        coerce('ay');
+
+        // if you have one part of arrow length you should have both
+        Plotly.Lib.noneOrAll(annIn, annOut, ['ax', 'ay']);
+    }
+    coerce('text', showArrow ? '&nbsp;' : 'new text');
+    coerce('textangle');
+    Plotly.Lib.coerceFont(coerce, 'font', fullLayout.font);
+
+    // positioning
+    var axLetters = ['x','y'];
+    for(var i = 0; i < 2; i++) {
+        var axLetter = axLetters[i],
+            tdMock = {_fullLayout: fullLayout};
+
+        // xref, yref
+        var axRef = Plotly.Axes.coerceRef(annIn, annOut, tdMock, axLetter);
+
+        // x, y
+        var defaultPosition = 0.5;
+        if(axRef!=='paper') {
+            var ax = Plotly.Axes.getFromId(tdMock, axRef);
+            defaultPosition = ax.range[0] + defaultPosition * (ax.range[1] - ax.range[0]);
+
+            // convert date or category strings to numbers
+            if(['date','category'].indexOf(ax.type)!==-1 &&
+                    typeof annIn[axLetter]==='string') {
+                var newval;
+                if(ax.type==='date') {
+                    newval = Plotly.Lib.dateTime2ms(annIn[axLetter]);
+                    if(newval!==false) annIn[axLetter] = newval;
+                }
+                else if((ax._categories||[]).length) {
+                    newval = ax._categories.indexOf(annIn[axLetter]);
+                    if(newval!==-1) annIn[axLetter] = newval;
+                }
+            }
+        }
+        coerce(axLetter, defaultPosition);
+
+        // xanchor, yanchor
+        if(!showArrow) coerce(axLetter + 'anchor');
+    }
+
+    // if you have one coordinate you should have both
+    Plotly.Lib.noneOrAll(annIn, annOut, ['x', 'y']);
+
+    return annOut;
+}
+
+annotations.drawAll = function(gd) {
+    var fullLayout = gd._fullLayout;
+    fullLayout._infolayer.selectAll('.annotation').remove();
+    for(var i = 0; i < fullLayout.annotations.length; i++) {
+        annotations.draw(gd, i);
+    }
+    return Plotly.Plots.previousPromises(gd);
+};
+
+annotations.add = function(gd) {
+    var nextAnn = gd._fullLayout.annotations.length;
+    Plotly.relayout(gd, 'annotations['+nextAnn+']', 'add');
+};
+
+// -----------------------------------------------------
+// make or edit an annotation on the graph
+// -----------------------------------------------------
+
+// annotations are stored in gd.layout.annotations, an array of objects
+// index can point to one item in this array,
+//  or non-numeric to simply add a new one
+//  or -1 to modify all existing
+// opt can be the full options object, or one key (to be set to value)
+//  or undefined to simply redraw
+// if opt is blank, val can be 'add' or a full options object to add a new
+//  annotation at that point in the array, or 'remove' to delete this one
+annotations.draw = function(gd, index, opt, value) {
+    var layout = gd.layout,
+        fullLayout = gd._fullLayout,
+        i;
+
+    if(!isNumeric(index) || index===-1) {
+        // no index provided - we're operating on ALL annotations
+        if(!index && Array.isArray(value)) {
+            // a whole annotation array is passed in
+            // (as in, redo of delete all)
+            layout.annotations = value;
+            annotations.supplyLayoutDefaults(layout, fullLayout);
+            annotations.drawAll(gd);
+            return;
+        }
+        else if(value==='remove') {
+            // delete all
+            delete layout.annotations;
+            fullLayout.annotations = [];
+            annotations.drawAll(gd);
+            return;
+        }
+        else if(opt && value!=='add') {
+            // make the same change to all annotations
+            for(i = 0; i < fullLayout.annotations.length; i++) {
+                annotations.draw(gd, i, opt, value);
+            }
+            return;
+        }
+        else {
+            // add a new empty annotation
+            index = fullLayout.annotations.length;
+            fullLayout.annotations.push({});
+        }
+    }
+
+    if(!opt && value) {
+        if(value==='remove') {
+            fullLayout._infolayer.selectAll('.annotation[data-index="'+index+'"]')
+                .remove();
+            fullLayout.annotations.splice(index,1);
+            layout.annotations.splice(index,1);
+            for(i=index; i<fullLayout.annotations.length; i++) {
+                fullLayout._infolayer
+                    .selectAll('.annotation[data-index="'+(i+1)+'"]')
+                    .attr('data-index',String(i));
+
+                // redraw all annotations past the removed one,
+                // so they bind to the right events
+                annotations.draw(gd,i);
+            }
+            return;
+        }
+        else if(value==='add' || Plotly.Lib.isPlainObject(value)) {
+            fullLayout.annotations.splice(index,0,{});
+
+            var rule = Plotly.Lib.isPlainObject(value) ?
+                    Plotly.Lib.extendFlat({}, value) :
+                    {text: 'New text'};
+
+            if(layout.annotations) {
+                layout.annotations.splice(index, 0, rule);
+            } else {
+                layout.annotations = [rule];
+            }
+
+            for(i=fullLayout.annotations.length-1; i>index; i--) {
+                fullLayout._infolayer
+                    .selectAll('.annotation[data-index="'+(i-1)+'"]')
+                    .attr('data-index',String(i));
+                annotations.draw(gd,i);
+            }
+        }
+    }
+
+    // remove the existing annotation if there is one
+    fullLayout._infolayer.selectAll('.annotation[data-index="'+index+'"]').remove();
+
+    // remember a few things about what was already there,
+    var optionsIn = layout.annotations[index],
+        oldPrivate = fullLayout.annotations[index];
+
+    // not sure how we're getting here... but C12 is seeing a bug
+    // where we fail here when they add/remove annotations
+    if(!optionsIn) return;
+
+    var oldRef = {xref: optionsIn.xref, yref: optionsIn.yref};
+
+    // alter the input annotation as requested
+    var optionsEdit = {};
+    if(typeof opt === 'string' && opt) optionsEdit[opt] = value;
+    else if(Plotly.Lib.isPlainObject(opt)) optionsEdit = opt;
+
+    var optionKeys = Object.keys(optionsEdit);
+    for(i = 0; i < optionKeys.length; i++) {
+        var k = optionKeys[i];
+        Plotly.Lib.nestedProperty(optionsIn, k).set(optionsEdit[k]);
+    }
+
+    var gs = fullLayout._size;
+
+    var axLetters = ['x', 'y'];
+    for(i = 0; i < 2; i++) {
+        var axLetter = axLetters[i];
+        // if we don't have an explicit position already,
+        // don't set one just because we're changing references
+        // or axis type.
+        // the defaults will be consistent most of the time anyway,
+        // except in log/linear changes
+        if(optionsEdit[axLetter]!==undefined ||
+                optionsIn[axLetter]===undefined) {
+            continue;
+        }
+
+        var axOld = Plotly.Axes.getFromId(gd,
+                Plotly.Axes.coerceRef(oldRef, {}, gd, axLetter)),
+            axNew = Plotly.Axes.getFromId(gd,
+                Plotly.Axes.coerceRef(optionsIn, {}, gd, axLetter)),
+            position = optionsIn[axLetter],
+            axTypeOld = oldPrivate['_' + axLetter + 'type'];
+
+        if(optionsEdit[axLetter + 'ref']!==undefined) {
+            var autoAnchor = optionsIn[axLetter + 'anchor'] === 'auto',
+                plotSize = (axLetter === 'x' ? gs.w : gs.h),
+                halfSizeFrac = (oldPrivate['_' + axLetter + 'size'] || 0) /
+                    (2 * plotSize);
+            if(axOld && axNew) { // data -> different data
+                // go to the same fraction of the axis length
+                // whether or not these axes share a domain
+
+                // first convert to fraction of the axis
+                position = (position - axOld.range[0]) /
+                    (axOld.range[1] - axOld.range[0]);
+
+                // then convert to new data coordinates at the same fraction
+                position = axNew.range[0] +
+                    position * (axNew.range[1] - axNew.range[0]);
+            }
+            else if(axOld) { // data -> paper
+                // first convert to fraction of the axis
+                position = (position - axOld.range[0]) /
+                    (axOld.range[1] - axOld.range[0]);
+
+                // next scale the axis to the whole plot
+                position = axOld.domain[0] +
+                    position * (axOld.domain[1] - axOld.domain[0]);
+
+                // finally see if we need to adjust auto alignment
+                // because auto always means middle / center alignment for data,
+                // but it changes for page alignment based on the closest side
+                if(autoAnchor) {
+                    var posPlus = position + halfSizeFrac,
+                        posMinus = position - halfSizeFrac;
+                    if(position + posMinus < 2/3) position = posMinus;
+                    else if(position + posPlus > 4/3) position = posPlus;
+                }
+            }
+            else if(axNew) { // paper -> data
+                // first see if we need to adjust auto alignment
+                if(autoAnchor) {
+                    if(position < 1/3) position += halfSizeFrac;
+                    else if(position > 2/3) position -= halfSizeFrac;
+                }
+
+                // next convert to fraction of the axis
+                position = (position - axNew.domain[0]) /
+                    (axNew.domain[1] - axNew.domain[0]);
+
+                // finally convert to data coordinates
+                position = axNew.range[0] +
+                    position * (axNew.range[1] - axNew.range[0]);
+            }
+        }
+
+        if(axNew && axNew===axOld && axTypeOld) {
+            if(axTypeOld==='log' && axNew.type!=='log') {
+                position = Math.pow(10,position);
+            }
+            else if(axTypeOld!=='log' && axNew.type==='log') {
+                position = (position>0) ?
+                    Math.log(position)/Math.LN10 : undefined;
+            }
+        }
+
+        optionsIn[axLetter] = position;
+    }
+
+    var options = handleAnnotationDefaults(optionsIn, fullLayout);
+    fullLayout.annotations[index] = options;
+
+    var xa = Plotly.Axes.getFromId(gd, options.xref),
+        ya = Plotly.Axes.getFromId(gd, options.yref),
+        annPosPx = {x: 0, y: 0},
+        textangle = +options.textangle || 0;
+
+    // create the components
+    // made a single group to contain all, so opacity can work right
+    // with border/arrow together this could handle a whole bunch of
+    // cleanup at this point, but works for now
+    var anngroup = fullLayout._infolayer.append('g')
+        .classed('annotation', true)
+        .attr('data-index', String(index))
+        .style('opacity', options.opacity)
+        .on('click', function() {
+            gd._dragging = false;
+            gd.emit('plotly_clickannotation', {
+                index: index,
+                annotation: optionsIn,
+                fullAnnotation: options
+            });
+        });
+
+    // another group for text+background so that they can rotate together
+    var anng = anngroup.append('g')
+        .classed('annotation-text-g', true)
+        .attr('data-index', String(index));
+
+    var ann = anng.append('svg')
+        .call(Plotly.Drawing.setPosition, 0, 0);
+
+    var borderwidth = options.borderwidth,
+        borderpad = options.borderpad,
+        borderfull = borderwidth + borderpad;
+
+    var annbg = ann.append('rect')
+        .attr('class','bg')
+        .style('stroke-width', borderwidth+'px')
+        .call(Plotly.Color.stroke, options.bordercolor)
+        .call(Plotly.Color.fill, options.bgcolor);
+
+    var font = options.font;
+
+    var anntext = ann.append('text')
+        .classed('annotation', true)
+        .attr('data-unformatted', options.text)
+        .text(options.text);
+
+    function textLayout(s) {
+        s.call(Plotly.Drawing.font, font)
+        .attr({
+            'text-anchor': {
+                left: 'start',
+                right: 'end'
+            }[options.align] || 'middle'
+        });
+        Plotly.util.convertToTspans(s, drawGraphicalElements);
+        return s;
+    }
+
+    function drawGraphicalElements() {
+
+        // make sure lines are aligned the way they will be
+        // at the end, even if their position changes
+        anntext.selectAll('tspan.line').attr({y: 0, x: 0});
+
+        var mathjaxGroup = ann.select('.annotation-math-group'),
+            hasMathjax = !mathjaxGroup.empty(),
+            anntextBB = Plotly.Drawing.bBox(
+                (hasMathjax ? mathjaxGroup : anntext).node()),
+            annwidth = anntextBB.width,
+            annheight = anntextBB.height,
+            outerwidth = Math.round(annwidth + 2 * borderfull),
+            outerheight = Math.round(annheight + 2 * borderfull);
+
+
+        // save size in the annotation object for use by autoscale
+        options._w = annwidth;
+        options._h = annheight;
+
+        function shiftFraction(v, anchor) {
+            if(anchor==='auto') {
+                if(v < 1/3) anchor = 'left';
+                else if(v > 2/3) anchor = 'right';
+                else anchor = 'center';
+            }
+            return {
+                center: 0,
+                middle: 0,
+                left: 0.5,
+                bottom: -0.5,
+                right: -0.5,
+                top: 0.5
+            }[anchor];
+        }
+
+        var annotationIsOffscreen = false;
+        ['x', 'y'].forEach(function(axLetter) {
+            var ax = Plotly.Axes.getFromId(gd,
+                    options[axLetter+'ref']||axLetter),
+                dimAngle = (textangle + (axLetter==='x' ? 0 : 90)) * Math.PI/180,
+                annSize = outerwidth * Math.abs(Math.cos(dimAngle)) +
+                          outerheight * Math.abs(Math.sin(dimAngle)),
+                anchor = options[axLetter + 'anchor'],
+                alignPosition;
+
+            // calculate pixel position
+            if(ax) {
+                // hide the annotation if it's pointing
+                // outside the visible plot (as long as the axis
+                // isn't autoranged - then we need to draw it
+                // anyway to get its bounding box)
+                if(!ax.autorange && ((options[axLetter] - ax.range[0]) *
+                                     (options[axLetter] - ax.range[1]) > 0)) {
+                    annotationIsOffscreen = true;
+                    return;
+                }
+                annPosPx[axLetter] = ax._offset+ax.l2p(options[axLetter]);
+                alignPosition = 0.5;
+            }
+            else {
+                alignPosition = options[axLetter];
+                if(axLetter === 'y') alignPosition = 1 - alignPosition;
+                annPosPx[axLetter] = (axLetter === 'x') ?
+                    (gs.l + gs.w * alignPosition) :
+                    (gs.t + gs.h * alignPosition);
+            }
+
+            var alignShift = 0;
+            if(options.showarrow) {
+                alignShift = options['a' + axLetter];
+            }
+            else {
+                alignShift = annSize * shiftFraction(alignPosition, anchor);
+            }
+            annPosPx[axLetter] += alignShift;
+
+            // save the current axis type for later log/linear changes
+            options['_' + axLetter + 'type'] = ax && ax.type;
+
+            // save the size and shift in this dim for autorange
+            options['_' + axLetter + 'size'] = annSize;
+            options['_' + axLetter + 'shift'] = alignShift;
+        });
+
+        if(annotationIsOffscreen) {
+            ann.remove();
+            return;
+        }
+
+        var arrowX, arrowY;
+
+        // make sure the arrowhead (if there is one)
+        // and the annotation center are visible
+        if(options.showarrow) {
+            arrowX = Plotly.Lib.constrain(annPosPx.x - options.ax, 1, fullLayout.width - 1);
+            arrowY = Plotly.Lib.constrain(annPosPx.y - options.ay, 1, fullLayout.height - 1);
+        }
+        annPosPx.x = Plotly.Lib.constrain(annPosPx.x, 1, fullLayout.width - 1);
+        annPosPx.y = Plotly.Lib.constrain(annPosPx.y, 1, fullLayout.height - 1);
+
+        var texty = borderfull - anntextBB.top,
+            textx = borderfull - anntextBB.left;
+
+        if(hasMathjax) {
+            mathjaxGroup.select('svg').attr({x: borderfull - 1, y: borderfull});
+        }
+        else {
+            anntext.attr({x: textx, y: texty});
+            anntext.selectAll('tspan.line').attr({y: texty, x: textx});
+        }
+
+        annbg.call(Plotly.Drawing.setRect, borderwidth / 2, borderwidth / 2,
+            outerwidth-borderwidth, outerheight - borderwidth);
+        ann.call(Plotly.Drawing.setRect,
+            Math.round(annPosPx.x - outerwidth / 2),
+            Math.round(annPosPx.y - outerheight / 2),
+            outerwidth, outerheight);
+
+        var annbase = 'annotations['+index+']';
+
+        // add the arrow
+        // uses options[arrowwidth,arrowcolor,arrowhead] for styling
+        var drawArrow = function(dx, dy) {
+            d3.select(gd)
+                .selectAll('.annotation-arrow-g[data-index="' + index + '"]')
+                .remove();
+            // find where to start the arrow:
+            // at the border of the textbox, if that border is visible,
+            // or at the edge of the lines of text, if the border is hidden
+            // TODO: tspan bounding box fails in chrome
+            // looks like there may be a cross-browser solution, see
+            // http://stackoverflow.com/questions/5364980/
+            //    how-to-get-the-width-of-an-svg-tspan-element
+            var arrowX0 = annPosPx.x + dx,
+                arrowY0 = annPosPx.y + dy,
+
+                // create transform matrix and related functions
+                transform =
+                    Plotly.Lib.rotationXYMatrix(textangle, arrowX0, arrowY0),
+                applyTransform = Plotly.Lib.apply2DTransform(transform),
+                applyTransform2 = Plotly.Lib.apply2DTransform2(transform),
+
+                // calculate and transform bounding box
+                xHalf = annbg.attr('width')/2,
+                yHalf = annbg.attr('height')/2,
+                edges = [
+                    [arrowX0 - xHalf, arrowY0 - yHalf, arrowX0 - xHalf, arrowY0 + yHalf],
+                    [arrowX0 - xHalf, arrowY0 + yHalf, arrowX0 + xHalf, arrowY0 + yHalf],
+                    [arrowX0 + xHalf, arrowY0 + yHalf, arrowX0 + xHalf, arrowY0 - yHalf],
+                    [arrowX0 + xHalf, arrowY0 - yHalf, arrowX0 - xHalf, arrowY0 - yHalf]
+                ].map(applyTransform2);
+
+            // Remove the line if it ends inside the box.  Use ray
+            // casting for rotated boxes: see which edges intersect a
+            // line from the arrowhead to far away and reduce with xor
+            // to get the parity of the number of intersections.
+            if(edges.reduce(function(a, x) {
+                return a ^
+                    !!lineIntersect(arrowX, arrowY, arrowX + 1e6, arrowY + 1e6,
+                            x[0], x[1], x[2], x[3]);
+            }, false)) {
+                // no line or arrow - so quit drawArrow now
+                return;
+            }
+
+            edges.forEach(function(x) {
+                var p = lineIntersect(arrowX0, arrowY0, arrowX, arrowY,
+                            x[0], x[1], x[2], x[3]);
+                if(p) {
+                    arrowX0 = p.x;
+                    arrowY0 = p.y;
+                }
+            });
+
+            var strokewidth = options.arrowwidth,
+                arrowColor = options.arrowcolor;
+
+            var arrowgroup = anngroup.append('g')
+                .style({opacity: Plotly.Color.opacity(arrowColor)})
+                .classed('annotation-arrow-g', true)
+                .attr('data-index', String(index));
+
+            var arrow = arrowgroup.append('path')
+                .attr('d', 'M'+arrowX0+','+arrowY0+'L'+arrowX+','+arrowY)
+                .style('stroke-width', strokewidth+'px')
+                .call(Plotly.Color.stroke,
+                    Plotly.Color.rgb(arrowColor));
+
+            annotations.arrowhead(arrow, options.arrowhead, 'end', options.arrowsize);
+
+            var arrowdrag = arrowgroup.append('path')
+                .classed('annotation', true)
+                .classed('anndrag', true)
+                .attr({
+                    'data-index': String(index),
+                    d: 'M3,3H-3V-3H3ZM0,0L' + (arrowX0-arrowX) + ',' + (arrowY0-arrowY),
+                    transform: 'translate('+arrowX+','+arrowY+')'
+                })
+                .style('stroke-width', (strokewidth+6)+'px')
+                .call(Plotly.Color.stroke, 'rgba(0,0,0,0)')
+                .call(Plotly.Color.fill, 'rgba(0,0,0,0)');
+
+            if(gd._context.editable) {
+                var update,
+                    annx0,
+                    anny0;
+
+                Plotly.Fx.dragElement({
+                    element: arrowdrag.node(),
+                    prepFn: function() {
+                        annx0 = Number(ann.attr('x'));
+                        anny0 = Number(ann.attr('y'));
+                        update = {};
+                        if(xa && xa.autorange) {
+                            update[xa._name+'.autorange'] = true;
+                        }
+                        if(ya && ya.autorange) {
+                            update[ya._name+'.autorange'] = true;
+                        }
+                    },
+                    moveFn: function(dx, dy) {
+                        arrowgroup.attr('transform', 'translate('+dx+','+dy+')');
+
+                        var annxy0 = applyTransform(annx0, anny0),
+                            xcenter = annxy0[0] + dx,
+                            ycenter = annxy0[1] + dy;
+                        ann.call(Plotly.Drawing.setPosition,
+                            xcenter, ycenter);
+
+                        update[annbase+'.x'] = xa ?
+                            (options.x + dx / xa._m) :
+                            ((arrowX + dx - gs.l) / gs.w);
+                        update[annbase+'.y'] = ya ?
+                            (options.y + dy / ya._m) :
+                            (1 - ((arrowY + dy - gs.t) / gs.h));
+
+                        anng.attr({
+                            transform: 'rotate(' + textangle + ',' +
+                                   xcenter + ',' + ycenter + ')'
+                        });
+                    },
+                    doneFn: function(dragged) {
+                        if(dragged) {
+                            Plotly.relayout(gd, update);
+                            var notesBox = document.querySelector('.js-notes-box-panel');
+                            if(notesBox) notesBox.redraw(notesBox.selectedObj);
+                        }
+                    }
+                });
+            }
+        };
+
+        if(options.showarrow) drawArrow(0, 0);
+
+        // create transform matrix and related functions
+        var transform = Plotly.Lib.rotationXYMatrix(textangle,
+                annPosPx.x, annPosPx.y),
+            applyTransform = Plotly.Lib.apply2DTransform(transform);
+
+        // user dragging the annotation (text, not arrow)
+        if(gd._context.editable) {
+            var x0,
+                y0,
+                update;
+
+            Plotly.Fx.dragElement({
+                element: ann.node(),
+                prepFn: function() {
+                    x0 = Number(ann.attr('x'));
+                    y0 = Number(ann.attr('y'));
+                    update = {};
+                },
+                moveFn: function(dx, dy) {
+                    ann.call(Plotly.Drawing.setPosition, x0 + dx, y0 + dy);
+                    var csr = 'pointer';
+                    if(options.showarrow) {
+                        update[annbase+'.ax'] = options.ax + dx;
+                        update[annbase+'.ay'] = options.ay + dy;
+                        drawArrow(dx, dy);
+                    }
+                    else {
+                        if(xa) update[annbase + '.x'] = options.x + dx / xa._m;
+                        else {
+                            var widthFraction = options._xsize / gs.w,
+                                xLeft = options.x + options._xshift / gs.w - widthFraction / 2;
+
+                            update[annbase + '.x'] = Plotly.Fx.dragAlign(xLeft + dx / gs.w,
+                                widthFraction, 0, 1, options.xanchor);
+                        }
+
+                        if(ya) update[annbase + '.y'] = options.y + dy / ya._m;
+                        else {
+                            var heightFraction = options._ysize / gs.h,
+                                yBottom = options.y - options._yshift / gs.h - heightFraction / 2;
+
+                            update[annbase + '.y'] = Plotly.Fx.dragAlign(yBottom - dy / gs.h,
+                                heightFraction, 0, 1, options.yanchor);
+                        }
+                        if(!xa || !ya) {
+                            csr = Plotly.Fx.dragCursors(
+                                xa ? 0.5 : update[annbase + '.x'],
+                                ya ? 0.5 : update[annbase + '.y'],
+                                options.xanchor, options.yanchor
+                            );
+                        }
+                    }
+
+                    var xy1 = applyTransform(x0, y0),
+                        x1 = xy1[0] + dx,
+                        y1 = xy1[1] + dy;
+
+                    ann.call(Plotly.Drawing.setPosition, x1, y1);
+
+                    anng.attr({
+                        transform: 'rotate(' + textangle + ',' +
+                               x1 + ',' + y1 + ')'
+                    });
+
+                    Plotly.Fx.setCursor(ann, csr);
+                },
+                doneFn: function(dragged) {
+                    Plotly.Fx.setCursor(ann);
+                    if(dragged) {
+                        Plotly.relayout(gd, update);
+                        var notesBox = document.querySelector('.js-notes-box-panel');
+                        if(notesBox) notesBox.redraw(notesBox.selectedObj);
+                    }
+                }
+            });
+        }
+    }
+
+    if(gd._context.editable) {
+        anntext.call(Plotly.util.makeEditable, ann)
+            .call(textLayout)
+            .on('edit', function(_text) {
+                options.text = _text;
+                this.attr({'data-unformatted': options.text});
+                this.call(textLayout);
+                var update = {};
+                update['annotations['+index+'].text'] = options.text;
+                if(xa && xa.autorange) {
+                    update[xa._name+'.autorange'] = true;
+                }
+                if(ya && ya.autorange) {
+                    update[ya._name+'.autorange'] = true;
+                }
+                Plotly.relayout(gd,update);
+            });
+    }
+    else anntext.call(textLayout);
+
+    // rotate and position text and background
+    anng.attr({transform: 'rotate(' + textangle + ',' +
+                        annPosPx.x + ',' + annPosPx.y + ')'})
+        .call(Plotly.Drawing.setPosition, annPosPx.x, annPosPx.y);
+};
+
+// add arrowhead(s) to a path or line d3 element el3
+// style: 1-6, first 5 are pointers, 6 is circle, 7 is square, 8 is none
+// ends is 'start', 'end' (default), 'start+end'
+// mag is magnification vs. default (default 1)
+annotations.arrowhead = function(el3, style, ends, mag) {
+    if(!isNumeric(mag)) mag = 1;
+    var el = el3.node(),
+        headStyle = annotations.ARROWPATHS[style||0];
+    if(!headStyle) return;
+
+    if(typeof ends !== 'string' || !ends) ends = 'end';
+
+    var scale = (Plotly.Drawing.getPx(el3,'stroke-width') || 1) * mag,
+        stroke = el3.style('stroke') || Plotly.Color.defaultLine,
+        opacity = el3.style('stroke-opacity') || 1,
+        doStart = ends.indexOf('start') >= 0,
+        doEnd = ends.indexOf('end') >= 0,
+        backOff = headStyle.backoff * scale,
+        start,
+        end,
+        startRot,
+        endRot;
+
+    if(el.nodeName === 'line') {
+        start = {x: +el3.attr('x1'), y: +el3.attr('y1')};
+        end = {x: +el3.attr('x2'), y: +el3.attr('y2')};
+        startRot = Math.atan2(start.y - end.y, start.x - end.x);
+        endRot = startRot + Math.PI;
+        if(backOff) {
+            var backOffX = backOff * Math.cos(startRot),
+                backOffY = backOff * Math.sin(startRot);
+
+            if(doStart) {
+                start.x -= backOffX;
+                start.y -= backOffY;
+                el3.attr({x1: start.x, y1: start.y});
+            }
+            if(doEnd) {
+                end.x += backOffX;
+                end.y += backOffY;
+                el3.attr({x2: end.x, y2: end.y});
+            }
+        }
+    }
+    else if(el.nodeName === 'path') {
+        var pathlen = el.getTotalLength(),
+            // using dash to hide the backOff region of the path.
+            // if we ever allow dash for the arrow we'll have to
+            // do better than this hack... maybe just manually
+            // combine the two
+            dashArray = '';
+
+        if(doStart) {
+            var start0 = el.getPointAtLength(0),
+                dstart = el.getPointAtLength(0.1);
+            startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x);
+            start = el.getPointAtLength(Math.min(backOff, pathlen));
+            if(backOff) dashArray = '0px,' + backOff + 'px,';
+        }
+
+        if(doEnd) {
+            var end0 = el.getPointAtLength(pathlen),
+                dend = el.getPointAtLength(pathlen - 0.1);
+            endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x);
+            end = el.getPointAtLength(Math.max(0, pathlen - backOff));
+
+            if(backOff) {
+                var shortening = dashArray ? 2 * backOff : backOff;
+                dashArray += (pathlen - shortening) + 'px,' + pathlen + 'px';
+            }
+        }
+        else if(dashArray) dashArray += pathlen + 'px';
+
+        if(dashArray) el3.style('stroke-dasharray', dashArray);
+    }
+
+    var drawhead = function(p, rot) {
+        if(style>5) rot=0; // don't rotate square or circle
+        d3.select(el.parentElement).append('path')
+            .attr({
+                'class': el3.attr('class'),
+                d: headStyle.path,
+                transform:
+                    'translate(' + p.x + ',' + p.y + ')' +
+                    'rotate(' + (rot * 180 / Math.PI) + ')' +
+                    'scale(' + scale + ')'
+            })
+            .style({
+                fill: stroke,
+                opacity: opacity,
+                'stroke-width': 0
+            });
+    };
+
+    if(doStart) drawhead(start, startRot);
+    if(doEnd) drawhead(end, endRot);
+};
+
+annotations.calcAutorange = function(gd) {
+    var fullLayout = gd._fullLayout,
+        annotationList = fullLayout.annotations;
+
+    if(!annotationList.length || !gd._fullData.length) return;
+
+    var annotationAxes = {};
+    annotationList.forEach(function(ann) {
+        annotationAxes[ann.xref] = true;
+        annotationAxes[ann.yref] = true;
+    });
+
+    var autorangedAnnos = Plotly.Axes.list(gd)
+        .filter(function(ax) {
+            return ax.autorange && annotationAxes[ax._id];
+        });
+    if(!autorangedAnnos.length) return;
+
+    return Plotly.Lib.syncOrAsync([
+        annotations.drawAll,
+        annAutorange
+    ], gd);
+};
+
+function annAutorange(gd) {
+    var fullLayout = gd._fullLayout;
+
+    // find the bounding boxes for each of these annotations'
+    // relative to their anchor points
+    // use the arrow and the text bg rectangle,
+    // as the whole anno may include hidden text in its bbox
+    fullLayout.annotations.forEach(function(ann) {
+        var xa = Plotly.Axes.getFromId(gd, ann.xref),
+            ya = Plotly.Axes.getFromId(gd, ann.yref);
+        if(!(xa || ya)) return;
+
+        var halfWidth = (ann._xsize || 0)/2,
+            xShift = ann._xshift || 0,
+            halfHeight = (ann._ysize || 0)/2,
+            yShift = ann._yshift || 0,
+            leftSize = halfWidth - xShift,
+            rightSize = halfWidth + xShift,
+            topSize = halfHeight - yShift,
+            bottomSize = halfHeight + yShift;
+        if(ann.showarrow) {
+            var headSize = 3 * ann.arrowsize * ann.arrowwidth;
+            leftSize = Math.max(leftSize, headSize);
+            rightSize = Math.max(rightSize, headSize);
+            topSize = Math.max(topSize, headSize);
+            bottomSize = Math.max(bottomSize, headSize);
+        }
+        if(xa && xa.autorange) {
+            Plotly.Axes.expand(xa, [xa.l2c(ann.x)],{
+                ppadplus: rightSize,
+                ppadminus: leftSize
+            });
+        }
+        if(ya && ya.autorange) {
+            Plotly.Axes.expand(ya, [ya.l2c(ann.y)], {
+                ppadplus: bottomSize,
+                ppadminus: topSize
+            });
+        }
+    });
+}
+
+// look for intersection of two line segments
+//   (1->2 and 3->4) - returns array [x,y] if they do, null if not
+function lineIntersect(x1, y1, x2, y2, x3, y3, x4, y4) {
+    var a = x2 - x1,
+        b = x3 - x1,
+        c = x4 - x3,
+        d = y2 - y1,
+        e = y3 - y1,
+        f = y4 - y3,
+        det = a * f - c * d;
+    // parallel lines? intersection is undefined
+    // ignore the case where they are colinear
+    if(det === 0) return null;
+    var t = (b * f - c * e) / det,
+        u = (b * d - a * e) / det;
+    // segments do not intersect?
+    if(u<0 || u>1 || t<0 || t>1) return null;
+
+    return {x: x1 + a * t, y: y1 + d * t};
+}
+
+},{"../../plotly":366,"./arrow_paths":295,"./attributes":296,"d3":70,"fast-isnumeric":74}],298:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+// IMPORTANT - default colors should be in hex for compatibility
+exports.defaults = [
+    '#1f77b4',  // muted blue
+    '#ff7f0e',  // safety orange
+    '#2ca02c',  // cooked asparagus green
+    '#d62728',  // brick red
+    '#9467bd',  // muted purple
+    '#8c564b',  // chestnut brown
+    '#e377c2',  // raspberry yogurt pink
+    '#7f7f7f',  // middle gray
+    '#bcbd22',  // curry yellow-green
+    '#17becf'   // blue-teal
+];
+
+exports.defaultLine = '#444';
+
+exports.lightLine = '#eee';
+
+exports.background = '#fff';
+
+},{}],299:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var tinycolor = require('tinycolor2');
+var isNumeric = require('fast-isnumeric');
+
+var color = module.exports = {};
+
+var colorAttrs = require('./attributes');
+color.defaults = colorAttrs.defaults;
+color.defaultLine = colorAttrs.defaultLine;
+color.lightLine = colorAttrs.lightLine;
+color.background = colorAttrs.background;
+
+color.tinyRGB = function(tc) {
+    var c = tc.toRgb();
+    return 'rgb(' + Math.round(c.r) + ', ' +
+        Math.round(c.g) + ', ' + Math.round(c.b) + ')';
+};
+
+color.rgb = function(cstr) { return color.tinyRGB(tinycolor(cstr)); };
+
+color.opacity = function(cstr) { return cstr ? tinycolor(cstr).getAlpha() : 0; };
+
+color.addOpacity = function(cstr, op) {
+    var c = tinycolor(cstr).toRgb();
+    return 'rgba(' + Math.round(c.r) + ', ' +
+        Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')';
+};
+
+// combine two colors into one apparent color
+// if back has transparency or is missing,
+// color.background is assumed behind it
+color.combine = function(front, back) {
+    var fc = tinycolor(front).toRgb();
+    if(fc.a===1) return tinycolor(front).toRgbString();
+
+    var bc = tinycolor(back||color.background).toRgb(),
+        bcflat = bc.a===1 ? bc : {
+            r: 255 * (1-bc.a) + bc.r*bc.a,
+            g: 255 * (1-bc.a) + bc.g*bc.a,
+            b: 255 * (1-bc.a) + bc.b*bc.a
+        },
+        fcflat = {
+            r: bcflat.r*(1-fc.a) + fc.r*fc.a,
+            g: bcflat.g*(1-fc.a) + fc.g*fc.a,
+            b: bcflat.b*(1-fc.a) + fc.b*fc.a
+        };
+    return tinycolor(fcflat).toRgbString();
+};
+
+color.stroke = function(s, c) {
+    var tc = tinycolor(c);
+    s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()});
+};
+
+color.fill = function(s, c) {
+    var tc = tinycolor(c);
+    s.style({'fill': color.tinyRGB(tc), 'fill-opacity': tc.getAlpha()});
+};
+
+// search container for colors with the deprecated rgb(fractions) format
+// and convert them to rgb(0-255 values)
+color.clean = function(container) {
+    if(!container || typeof container !== 'object') return;
+
+    var keys = Object.keys(container),
+        i,
+        j,
+        key,
+        val;
+
+    for(i = 0; i < keys.length; i++) {
+        key = keys[i];
+        val = container[key];
+
+        // only sanitize keys that end in "color" or "colorscale"
+        if(key.substr(key.length - 5) === 'color') {
+            if(Array.isArray(val)) {
+                for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]);
+            }
+            else container[key] = cleanOne(val);
+        }
+        else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) {
+            // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]]
+            for(j = 0; j < val.length; j++) {
+                if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]);
+            }
+        }
+        // recurse into arrays of objects, and plain objects
+        else if(Array.isArray(val)) {
+            var el0 = val[0];
+            if(!Array.isArray(el0) && el0 && typeof el0 === 'object') {
+                for(j = 0; j < val.length; j++) color.clean(val[j]);
+            }
+        }
+        else if(val && typeof val === 'object') color.clean(val);
+    }
+};
+
+function cleanOne(val) {
+    if(isNumeric(val) || typeof val !== 'string') return val;
+
+    var valTrim = val.trim();
+    if(valTrim.substr(0,3) !== 'rgb') return val;
+
+    var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/);
+    if(!match) return val;
+
+    var parts = match[1].trim().split(/\s*[\s,]\s*/),
+        rgba = valTrim.charAt(3) === 'a' && parts.length === 4;
+    if(!rgba && parts.length !== 3) return val;
+
+    for(var i = 0; i < parts.length; i++) {
+        if(!parts[i].length) return val;
+        parts[i] = Number(parts[i]);
+
+        // all parts must be non-negative numbers
+        if(!(parts[i] >= 0)) return val;
+        // alpha>1 gets clipped to 1
+        if(i === 3) {
+            if(parts[i] > 1) parts[i] = 1;
+        }
+        // r, g, b must be < 1 (ie 1 itself is not allowed)
+        else if(parts[i] >= 1) return val;
+    }
+
+    var rgbStr = Math.round(parts[0] * 255) + ', ' +
+        Math.round(parts[1] * 255) + ', ' +
+        Math.round(parts[2] * 255);
+
+    if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')';
+    return 'rgb(' + rgbStr + ')';
+}
+
+},{"./attributes":298,"fast-isnumeric":74,"tinycolor2":229}],300:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var axesAttrs = require('../../plots/cartesian/layout_attributes');
+var fontAttrs = require('../../plots/font_attributes');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+
+module.exports = {
+// TODO: only right is supported currently
+//     orient: {
+//         valType: 'enumerated',
+//         
+//         values: ['left', 'right', 'top', 'bottom'],
+//         dflt: 'right',
+//         
+//     },
+    thicknessmode: {
+        valType: 'enumerated',
+        values: ['fraction', 'pixels'],
+        
+        dflt: 'pixels',
+        
+    },
+    thickness: {
+        valType: 'number',
+        
+        min: 0,
+        dflt: 30,
+        
+    },
+    lenmode: {
+        valType: 'enumerated',
+        values: ['fraction', 'pixels'],
+        
+        dflt: 'fraction',
+        
+    },
+    len: {
+        valType: 'number',
+        min: 0,
+        dflt: 1,
+        
+        
+    },
+    x: {
+        valType: 'number',
+        dflt: 1.02,
+        min: -2,
+        max: 3,
+        
+        
+    },
+    xanchor: {
+        valType: 'enumerated',
+        values: ['left', 'center', 'right'],
+        dflt: 'left',
+        
+        
+    },
+    xpad: {
+        valType: 'number',
+        
+        min: 0,
+        dflt: 10,
+        
+    },
+    y: {
+        valType: 'number',
+        
+        dflt: 0.5,
+        min: -2,
+        max: 3,
+        
+    },
+    yanchor: {
+        valType: 'enumerated',
+        values: ['top', 'middle', 'bottom'],
+        
+        dflt: 'middle',
+        
+    },
+    ypad: {
+        valType: 'number',
+        
+        min: 0,
+        dflt: 10,
+        
+    },
+    // a possible line around the bar itself
+    outlinecolor: axesAttrs.linecolor,
+    outlinewidth: axesAttrs.linewidth,
+    // Should outlinewidth have {dflt: 0} ?
+    // another possible line outside the padding and tick labels
+    bordercolor: axesAttrs.linecolor,
+    borderwidth: {
+        valType: 'number',
+        
+        min: 0,
+        dflt: 0,
+        
+    },
+    bgcolor: {
+        valType: 'color',
+        
+        dflt: 'rgba(0,0,0,0)',
+        
+    },
+    // tick and title properties named and function exactly as in axes
+    tickmode: axesAttrs.tickmode,
+    nticks: axesAttrs.nticks,
+    tick0: axesAttrs.tick0,
+    dtick: axesAttrs.dtick,
+    tickvals: axesAttrs.tickvals,
+    ticktext: axesAttrs.ticktext,
+    ticks: extendFlat({}, axesAttrs.ticks, {dflt: ''}),
+    ticklen: axesAttrs.ticklen,
+    tickwidth: axesAttrs.tickwidth,
+    tickcolor: axesAttrs.tickcolor,
+    showticklabels: axesAttrs.showticklabels,
+    tickfont: axesAttrs.tickfont,
+    tickangle: axesAttrs.tickangle,
+    tickformat: axesAttrs.tickformat,
+    tickprefix: axesAttrs.tickprefix,
+    showtickprefix: axesAttrs.showtickprefix,
+    ticksuffix: axesAttrs.ticksuffix,
+    showticksuffix: axesAttrs.showticksuffix,
+    exponentformat: axesAttrs.exponentformat,
+    showexponent: axesAttrs.showexponent,
+    title: {
+        valType: 'string',
+        
+        dflt: 'Click to enter colorscale title',
+        
+    },
+    titlefont: extendFlat({}, fontAttrs, {
+        
+    }),
+    titleside: {
+        valType: 'enumerated',
+        values: ['right', 'top', 'bottom'],
+        
+        dflt: 'top',
+        
+    }
+};
+
+},{"../../lib/extend":345,"../../plots/cartesian/layout_attributes":376,"../../plots/font_attributes":383}],301:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+var handleTickValueDefaults = require('../../plots/cartesian/tick_value_defaults');
+var handleTickDefaults = require('../../plots/cartesian/tick_defaults');
+
+var attributes = require('./attributes');
+
+
+module.exports = function colorbarDefaults(containerIn, containerOut, layout) {
+    var colorbarOut = containerOut.colorbar = {},
+        colorbarIn = containerIn.colorbar || {};
+
+    function coerce(attr, dflt) {
+        return Lib.coerce(colorbarIn, colorbarOut, attributes, attr, dflt);
+    }
+
+    var thicknessmode = coerce('thicknessmode');
+    coerce('thickness', (thicknessmode === 'fraction') ?
+        30 / (layout.width - layout.margin.l - layout.margin.r) :
+        30
+    );
+
+    var lenmode = coerce('lenmode');
+    coerce('len', (lenmode === 'fraction') ?
+        1 :
+        layout.height - layout.margin.t - layout.margin.b
+    );
+
+    coerce('x');
+    coerce('xanchor');
+    coerce('xpad');
+    coerce('y');
+    coerce('yanchor');
+    coerce('ypad');
+    Lib.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']);
+
+    coerce('outlinecolor');
+    coerce('outlinewidth');
+    coerce('bordercolor');
+    coerce('borderwidth');
+    coerce('bgcolor');
+
+    handleTickValueDefaults(colorbarIn, colorbarOut, coerce, 'linear');
+
+    handleTickDefaults(colorbarIn, colorbarOut, coerce, 'linear',
+        {outerTicks: false, font: layout.font, noHover: true});
+
+    coerce('title');
+    Lib.coerceFont(coerce, 'titlefont', layout.font);
+    coerce('titleside');
+};
+
+},{"../../lib":349,"../../plots/cartesian/tick_defaults":381,"../../plots/cartesian/tick_value_defaults":382,"./attributes":300}],302:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var Plotly = require('../../plotly');
+var Plots = require('../../plots/plots');
+var Axes = require('../../plots/cartesian/axes');
+var Fx = require('../../plots/cartesian/graph_interact');
+var Lib = require('../../lib');
+var Drawing = require('../drawing');
+var Color = require('../color');
+var Titles = require('../titles');
+
+var handleAxisDefaults = require('../../plots/cartesian/axis_defaults');
+var handleAxisPositionDefaults = require('../../plots/cartesian/position_defaults');
+var axisLayoutAttrs = require('../../plots/cartesian/layout_attributes');
+
+var attributes = require('./attributes');
+
+
+module.exports = function draw(gd, id) {
+    // opts: options object, containing everything from attributes
+    // plus a few others that are the equivalent of the colorbar "data"
+    var opts = {};
+    Object.keys(attributes).forEach(function(k) {
+        opts[k] = null;
+    });
+    // fillcolor can be a d3 scale, domain is z values, range is colors
+    // or leave it out for no fill,
+    // or set to a string constant for single-color fill
+    opts.fillcolor = null;
+    // line.color has the same options as fillcolor
+    opts.line = {color: null, width: null, dash: null};
+    // levels of lines to draw.
+    // note that this DOES NOT determine the extent of the bar
+    // that's given by the domain of fillcolor
+    // (or line.color if no fillcolor domain)
+    opts.levels = {start: null, end: null, size: null};
+    // separate fill levels (for example, heatmap coloring of a
+    // contour map) if this is omitted, fillcolors will be
+    // evaluated halfway between levels
+    opts.filllevels = null;
+
+    function component() {
+        var fullLayout = gd._fullLayout;
+        if((typeof opts.fillcolor !== 'function') &&
+                (typeof opts.line.color !== 'function')) {
+            fullLayout._infolayer.selectAll('g.'+id).remove();
+            return;
+        }
+        var zrange = d3.extent(((typeof opts.fillcolor === 'function') ?
+                opts.fillcolor : opts.line.color).domain()),
+            linelevels = [],
+            filllevels = [],
+            l,
+            linecolormap = typeof opts.line.color === 'function' ?
+                opts.line.color : function() { return opts.line.color; },
+            fillcolormap = typeof opts.fillcolor === 'function' ?
+                opts.fillcolor : function() { return opts.fillcolor; };
+
+        var l0 = opts.levels.end + opts.levels.size/100,
+            ls = opts.levels.size,
+            zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]),
+            zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]);
+        for(l = opts.levels.start; (l - l0) * ls < 0; l += ls) {
+            if(l > zr0 && l < zr1) linelevels.push(l);
+        }
+
+        if(typeof opts.fillcolor === 'function') {
+            if(opts.filllevels) {
+                l0 = opts.filllevels.end + opts.filllevels.size / 100;
+                ls = opts.filllevels.size;
+                for(l = opts.filllevels.start; (l - l0) * ls < 0; l += ls) {
+                    if(l > zrange[0] && l < zrange[1]) filllevels.push(l);
+                }
+            }
+            else {
+                filllevels = linelevels.map(function(v) {
+                    return v-opts.levels.size / 2;
+                });
+                filllevels.push(filllevels[filllevels.length - 1] +
+                    opts.levels.size);
+            }
+        }
+        else if(opts.fillcolor && typeof opts.fillcolor==='string') {
+            // doesn't matter what this value is, with a single value
+            // we'll make a single fill rect covering the whole bar
+            filllevels = [0];
+        }
+
+        if(opts.levels.size<0) {
+            linelevels.reverse();
+            filllevels.reverse();
+        }
+
+        // now make a Plotly Axes object to scale with and draw ticks
+        // TODO: does not support orientation other than right
+
+        // we calculate pixel sizes based on the specified graph size,
+        // not the actual (in case something pushed the margins around)
+        // which is a little odd but avoids an odd iterative effect
+        // when the colorbar itself is pushing the margins.
+        // but then the fractional size is calculated based on the
+        // actual graph size, so that the axes will size correctly.
+        var originalPlotHeight = fullLayout.height - fullLayout.margin.t - fullLayout.margin.b,
+            originalPlotWidth = fullLayout.width - fullLayout.margin.l - fullLayout.margin.r,
+            thickPx = Math.round(opts.thickness *
+                (opts.thicknessmode==='fraction' ? originalPlotWidth : 1)),
+            thickFrac = thickPx / fullLayout._size.w,
+            lenPx = Math.round(opts.len *
+                (opts.lenmode==='fraction' ? originalPlotHeight : 1)),
+            lenFrac = lenPx / fullLayout._size.h,
+            xpadFrac = opts.xpad/fullLayout._size.w,
+            yExtraPx = (opts.borderwidth + opts.outlinewidth)/2,
+            ypadFrac = opts.ypad / fullLayout._size.h,
+
+            // x positioning: do it initially just for left anchor,
+            // then fix at the end (since we don't know the width yet)
+            xLeft = Math.round(opts.x*fullLayout._size.w + opts.xpad),
+            // for dragging... this is getting a little muddled...
+            xLeftFrac = opts.x - thickFrac *
+                ({middle: 0.5, right: 1}[opts.xanchor]||0),
+
+            // y positioning we can do correctly from the start
+            yBottomFrac = opts.y + lenFrac *
+                (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5),
+            yBottomPx = Math.round(fullLayout._size.h * (1-yBottomFrac)),
+            yTopPx = yBottomPx-lenPx,
+            titleEl,
+            cbAxisIn = {
+                type: 'linear',
+                range: zrange,
+                tickmode: opts.tickmode,
+                nticks: opts.nticks,
+                tick0: opts.tick0,
+                dtick: opts.dtick,
+                tickvals: opts.tickvals,
+                ticktext: opts.ticktext,
+                ticks: opts.ticks,
+                ticklen: opts.ticklen,
+                tickwidth: opts.tickwidth,
+                tickcolor: opts.tickcolor,
+                showticklabels: opts.showticklabels,
+                tickfont: opts.tickfont,
+                tickangle: opts.tickangle,
+                tickformat: opts.tickformat,
+                exponentformat: opts.exponentformat,
+                showexponent: opts.showexponent,
+                showtickprefix: opts.showtickprefix,
+                tickprefix: opts.tickprefix,
+                showticksuffix: opts.showticksuffix,
+                ticksuffix: opts.ticksuffix,
+                title: opts.title,
+                titlefont: opts.titlefont,
+                anchor: 'free',
+                position: 1
+            },
+            cbAxisOut = {},
+            axisOptions = {
+                letter: 'y',
+                font: fullLayout.font,
+                noHover: true
+            };
+
+        // Coerce w.r.t. Axes layoutAttributes:
+        // re-use axes.js logic without updating _fullData
+        function coerce(attr, dflt) {
+            return Lib.coerce(cbAxisIn, cbAxisOut, axisLayoutAttrs, attr, dflt);
+        }
+
+        // Prepare the Plotly axis object
+        handleAxisDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions);
+        handleAxisPositionDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions);
+
+        cbAxisOut._id = 'y' + id;
+        cbAxisOut._td = gd;
+
+        // position can't go in through supplyDefaults
+        // because that restricts it to [0,1]
+        cbAxisOut.position = opts.x + xpadFrac + thickFrac;
+
+        // save for other callers to access this axis
+        component.axis = cbAxisOut;
+
+        if(['top','bottom'].indexOf(opts.titleside)!==-1) {
+            cbAxisOut.titleside = opts.titleside;
+            cbAxisOut.titlex = opts.x + xpadFrac;
+            cbAxisOut.titley = yBottomFrac +
+                (opts.titleside==='top' ? lenFrac-ypadFrac : ypadFrac);
+        }
+
+        if(opts.line.color && opts.tickmode === 'auto') {
+            cbAxisOut.tickmode = 'linear';
+            cbAxisOut.tick0 = opts.levels.start;
+            var dtick = opts.levels.size;
+            // expand if too many contours, so we don't get too many ticks
+            var autoNtick = Lib.constrain(
+                    (yBottomPx-yTopPx)/50, 4, 15) + 1,
+                dtFactor = (zrange[1]-zrange[0]) /
+                    ((opts.nticks||autoNtick)*dtick);
+            if(dtFactor>1) {
+                var dtexp = Math.pow(10,Math.floor(
+                    Math.log(dtFactor)/Math.LN10));
+                dtick *= dtexp * Lib.roundUp(dtFactor/dtexp,[2,5,10]);
+                // if the contours are at round multiples, reset tick0
+                // so they're still at round multiples. Otherwise,
+                // keep the first label on the first contour level
+                if((Math.abs(opts.levels.start)/
+                        opts.levels.size+1e-6)%1 < 2e-6) {
+                    cbAxisOut.tick0 = 0;
+                }
+            }
+            cbAxisOut.dtick = dtick;
+        }
+
+        // set domain after init, because we may want to
+        // allow it outside [0,1]
+        cbAxisOut.domain = [
+            yBottomFrac+ypadFrac,
+            yBottomFrac+lenFrac-ypadFrac
+        ];
+        cbAxisOut.setScale();
+
+        // now draw the elements
+        var container = fullLayout._infolayer.selectAll('g.'+id).data([0]);
+        container.enter().append('g').classed(id,true)
+            .each(function() {
+                var s = d3.select(this);
+                s.append('rect').classed('cbbg',true);
+                s.append('g').classed('cbfills',true);
+                s.append('g').classed('cblines',true);
+                s.append('g').classed('cbaxis',true).classed('crisp',true);
+                s.append('g').classed('cbtitleunshift',true)
+                    .append('g').classed('cbtitle',true);
+                s.append('rect').classed('cboutline',true);
+            });
+        container.attr('transform','translate('+Math.round(fullLayout._size.l)+
+            ','+Math.round(fullLayout._size.t)+')');
+        // TODO: this opposite transform is a hack until we make it
+        // more rational which items get this offset
+        var titleCont = container.select('.cbtitleunshift')
+            .attr('transform', 'translate(-'+
+                Math.round(fullLayout._size.l) + ',-' +
+                Math.round(fullLayout._size.t) + ')');
+
+        cbAxisOut._axislayer = container.select('.cbaxis');
+        var titleHeight = 0;
+        if(['top', 'bottom'].indexOf(opts.titleside) !== -1) {
+            // draw the title so we know how much room it needs
+            // when we squish the axis
+            Titles.draw(gd, cbAxisOut._id + 'title');
+        }
+
+        function drawAxis() {
+            if(['top','bottom'].indexOf(opts.titleside)!==-1) {
+                // squish the axis top to make room for the title
+                var titleGroup = container.select('.cbtitle'),
+                    titleText = titleGroup.select('text'),
+                    titleTrans =
+                        [-opts.outlinewidth/2, opts.outlinewidth/2],
+                    mathJaxNode = titleGroup
+                        .select('.h'+cbAxisOut._id+'title-math-group')
+                        .node(),
+                    lineSize = 15.6;
+                if(titleText.node()) {
+                    lineSize =
+                        parseInt(titleText.style('font-size'), 10) * 1.3;
+                }
+                if(mathJaxNode) {
+                    titleHeight = Drawing.bBox(mathJaxNode).height;
+                    if(titleHeight>lineSize) {
+                        // not entirely sure how mathjax is doing
+                        // vertical alignment, but this seems to work.
+                        titleTrans[1] -= (titleHeight-lineSize)/2;
+                    }
+                }
+                else if(titleText.node() &&
+                        !titleText.classed('js-placeholder')) {
+                    titleHeight = Drawing.bBox(
+                        titleGroup.node()).height;
+                }
+                if(titleHeight) {
+                    // buffer btwn colorbar and title
+                    // TODO: configurable
+                    titleHeight += 5;
+
+                    if(opts.titleside==='top') {
+                        cbAxisOut.domain[1] -= titleHeight/fullLayout._size.h;
+                        titleTrans[1] *= -1;
+                    }
+                    else {
+                        cbAxisOut.domain[0] += titleHeight/fullLayout._size.h;
+                        var nlines = Math.max(1,
+                            titleText.selectAll('tspan.line').size());
+                        titleTrans[1] += (1-nlines)*lineSize;
+                    }
+
+                    titleGroup.attr('transform',
+                        'translate('+titleTrans+')');
+
+                    cbAxisOut.setScale();
+                }
+            }
+
+            container.selectAll('.cbfills,.cblines,.cbaxis')
+                .attr('transform','translate(0,'+
+                    Math.round(fullLayout._size.h*(1-cbAxisOut.domain[1]))+')');
+
+            var fills = container.select('.cbfills')
+                .selectAll('rect.cbfill')
+                    .data(filllevels);
+            fills.enter().append('rect')
+                .classed('cbfill',true)
+                .style('stroke','none');
+            fills.exit().remove();
+            fills.each(function(d,i) {
+                var z = [
+                    (i===0) ? zrange[0] :
+                        (filllevels[i]+filllevels[i-1])/2,
+                    (i===filllevels.length-1) ? zrange[1] :
+                        (filllevels[i]+filllevels[i+1])/2
+                ]
+                .map(cbAxisOut.c2p)
+                .map(Math.round);
+
+                // offset the side adjoining the next rectangle so they
+                // overlap, to prevent antialiasing gaps
+                if(i!==filllevels.length-1) {
+                    z[1] += (z[1]>z[0]) ? 1 : -1;
+                }
+                d3.select(this).attr({
+                    x: xLeft,
+                    width: Math.max(thickPx,2),
+                    y: d3.min(z),
+                    height: Math.max(d3.max(z)-d3.min(z),2)
+                })
+                .style('fill',fillcolormap(d));
+            });
+
+            var lines = container.select('.cblines')
+                .selectAll('path.cbline')
+                    .data(opts.line.color && opts.line.width ?
+                        linelevels : []);
+            lines.enter().append('path')
+                .classed('cbline',true);
+            lines.exit().remove();
+            lines.each(function(d) {
+                d3.select(this)
+                    .attr('d','M'+xLeft+',' +
+                        (Math.round(cbAxisOut.c2p(d))+(opts.line.width/2)%1) +
+                        'h'+thickPx)
+                    .call(Drawing.lineGroupStyle,
+                        opts.line.width, linecolormap(d), opts.line.dash);
+            });
+
+            // force full redraw of labels and ticks
+            cbAxisOut._axislayer.selectAll('g.'+cbAxisOut._id+'tick,path')
+                .remove();
+
+            cbAxisOut._pos = xLeft+thickPx +
+                (opts.outlinewidth||0)/2 - (opts.ticks==='outside' ? 1 : 0);
+            cbAxisOut.side = 'right';
+
+            return Axes.doTicks(gd, cbAxisOut);
+        }
+
+        function positionCB() {
+            // wait for the axis & title to finish rendering before
+            // continuing positioning
+            // TODO: why are we redrawing multiple times now with this?
+            // I guess autoMargin doesn't like being post-promise?
+            var innerWidth = thickPx + opts.outlinewidth/2 +
+                    Drawing.bBox(cbAxisOut._axislayer.node()).width;
+            titleEl = titleCont.select('text');
+            if(titleEl.node() && !titleEl.classed('js-placeholder')) {
+                var mathJaxNode = titleCont
+                        .select('.h'+cbAxisOut._id+'title-math-group')
+                        .node(),
+                    titleWidth;
+                if(mathJaxNode &&
+                        ['top','bottom'].indexOf(opts.titleside)!==-1) {
+                    titleWidth = Drawing.bBox(mathJaxNode).width;
+                }
+                else {
+                    // note: the formula below works for all titlesides,
+                    // (except for top/bottom mathjax, above)
+                    // but the weird fullLayout._size.l is because the titleunshift
+                    // transform gets removed by Drawing.bBox
+                    titleWidth =
+                        Drawing.bBox(titleCont.node()).right -
+                        xLeft - fullLayout._size.l;
+                }
+                innerWidth = Math.max(innerWidth,titleWidth);
+            }
+
+            var outerwidth = 2*opts.xpad + innerWidth +
+                    opts.borderwidth + opts.outlinewidth/2,
+                outerheight = yBottomPx-yTopPx;
+
+            container.select('.cbbg').attr({
+                x: xLeft-opts.xpad -
+                    (opts.borderwidth + opts.outlinewidth)/2,
+                y: yTopPx - yExtraPx,
+                width: Math.max(outerwidth,2),
+                height: Math.max(outerheight + 2*yExtraPx,2)
+            })
+            .call(Color.fill, opts.bgcolor)
+            .call(Color.stroke, opts.bordercolor)
+            .style({'stroke-width': opts.borderwidth});
+
+            container.selectAll('.cboutline').attr({
+                x: xLeft,
+                y: yTopPx + opts.ypad +
+                    (opts.titleside==='top' ? titleHeight : 0),
+                width: Math.max(thickPx,2),
+                height: Math.max(outerheight - 2*opts.ypad - titleHeight, 2)
+            })
+            .call(Color.stroke, opts.outlinecolor)
+            .style({
+                fill: 'None',
+                'stroke-width': opts.outlinewidth
+            });
+
+            // fix positioning for xanchor!='left'
+            var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) *
+                outerwidth;
+            container.attr('transform',
+                'translate('+(fullLayout._size.l-xoffset)+','+fullLayout._size.t+')');
+
+            //auto margin adjustment
+            Plots.autoMargin(gd, id,{
+                x: opts.x,
+                y: opts.y,
+                l: outerwidth * ({right: 1, center: 0.5}[opts.xanchor] || 0),
+                r: outerwidth * ({left: 1, center: 0.5}[opts.xanchor] || 0),
+                t: outerheight * ({bottom: 1, middle: 0.5}[opts.yanchor] || 0),
+                b: outerheight * ({top: 1, middle: 0.5}[opts.yanchor] || 0)
+            });
+        }
+
+        var cbDone = Lib.syncOrAsync([
+            Plots.previousPromises,
+            drawAxis,
+            Plots.previousPromises,
+            positionCB
+        ], gd);
+
+        if(cbDone && cbDone.then) (gd._promises || []).push(cbDone);
+
+        // dragging...
+        if(gd._context.editable) {
+            var t0,
+                xf,
+                yf;
+
+            Fx.dragElement({
+                element: container.node(),
+                prepFn: function() {
+                    t0 = container.attr('transform');
+                    Fx.setCursor(container);
+                },
+                moveFn: function(dx, dy) {
+                    var gs = gd._fullLayout._size;
+
+                    container.attr('transform',
+                        t0+' ' + 'translate('+dx+','+dy+')');
+
+                    xf = Fx.dragAlign(xLeftFrac + (dx/gs.w), thickFrac,
+                        0, 1, opts.xanchor);
+                    yf = Fx.dragAlign(yBottomFrac - (dy/gs.h), lenFrac,
+                        0, 1, opts.yanchor);
+
+                    var csr = Fx.dragCursors(xf, yf,
+                        opts.xanchor, opts.yanchor);
+                    Fx.setCursor(container, csr);
+                },
+                doneFn: function(dragged) {
+                    Fx.setCursor(container);
+
+                    if(dragged && xf!==undefined && yf!==undefined) {
+                        var idNum = id.substr(2),
+                            traceNum;
+                        gd._fullData.some(function(trace) {
+                            if(trace.uid===idNum) {
+                                traceNum = trace.index;
+                                return true;
+                            }
+                        });
+
+                        Plotly.restyle(gd,
+                            {'colorbar.x': xf, 'colorbar.y': yf},
+                            traceNum);
+                    }
+                }
+            });
+        }
+        return cbDone;
+    }
+
+    // setter/getters for every item defined in opts
+    Object.keys(opts).forEach(function(name) {
+        component[name] = function(v) {
+            // getter
+            if(!arguments.length) return opts[name];
+
+            // setter - for multi-part properties,
+            // set only the parts that are provided
+            opts[name] = Lib.isPlainObject(opts[name]) ?
+                 Lib.extendFlat(opts[name], v) :
+                 v;
+
+            return component;
+        };
+    });
+
+    // or use .options to set multiple options at once via a dictionary
+    component.options = function(o) {
+        Object.keys(o).forEach(function(name) {
+            // in case something random comes through
+            // that's not an option, ignore it
+            if(typeof component[name]==='function') {
+                component[name](o[name]);
+            }
+        });
+        return component;
+    };
+
+    component._opts = opts;
+
+    return component;
+};
+
+},{"../../lib":349,"../../plotly":366,"../../plots/cartesian/axes":369,"../../plots/cartesian/axis_defaults":370,"../../plots/cartesian/graph_interact":374,"../../plots/cartesian/layout_attributes":376,"../../plots/cartesian/position_defaults":378,"../../plots/plots":413,"../color":299,"../drawing":317,"../titles":332,"./attributes":300,"d3":70}],303:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+
+module.exports = function hasColorbar(container) {
+    return (
+        typeof container.colorbar === 'object' &&
+        container.colorbar !== null
+    );
+};
+
+},{}],304:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+
+exports.attributes = require('./attributes');
+
+exports.supplyDefaults = require('./defaults');
+
+exports.draw = require('./draw');
+
+exports.hasColorbar = require('./has_colorbar');
+
+},{"./attributes":300,"./defaults":301,"./draw":302,"./has_colorbar":303}],305:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+module.exports = {
+    zauto: {
+        valType: 'boolean',
+        
+        dflt: true,
+        
+    },
+    zmin: {
+        valType: 'number',
+        
+        dflt: null,
+        
+    },
+    zmax: {
+        valType: 'number',
+        
+        dflt: null,
+        
+    },
+    colorscale: {
+        valType: 'colorscale',
+        
+        
+    },
+    autocolorscale: {
+        valType: 'boolean',
+        
+        dflt: true,  // gets overrode in 'heatmap' & 'surface' for backwards comp.
+        
+    },
+    reversescale: {
+        valType: 'boolean',
+        
+        dflt: false,
+        
+    },
+    showscale: {
+        valType: 'boolean',
+        
+        dflt: true,
+        
+    },
+
+    _deprecated: {
+        scl: {
+            valType: 'colorscale',
+            
+            
+        },
+        reversescl: {
+            valType: 'boolean',
+            
+            
+        }
+    }
+};
+
+},{}],306:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var scales = require('./scales');
+var flipScale = require('./flip_scale');
+
+
+module.exports = function calc(trace, vals, containerStr, cLetter) {
+    var container, inputContainer;
+
+    if(containerStr) {
+        container = Lib.nestedProperty(trace, containerStr).get();
+        inputContainer = Lib.nestedProperty(trace._input, containerStr).get();
+    } else {
+        container = trace;
+        inputContainer = trace._input;
+    }
+
+    var auto = container[cLetter + 'auto'],
+        min = container[cLetter + 'min'],
+        max = container[cLetter + 'max'],
+        scl = container.colorscale;
+
+    if(auto!==false || min===undefined) {
+        min = Lib.aggNums(Math.min, null, vals);
+    }
+
+    if(auto!==false || max===undefined) {
+        max = Lib.aggNums(Math.max, null, vals);
+    }
+
+    if(min === max) {
+        min -= 0.5;
+        max += 0.5;
+    }
+
+    container[cLetter + 'min'] = min;
+    container[cLetter + 'max'] = max;
+
+    inputContainer[cLetter + 'min'] = min;
+    inputContainer[cLetter + 'max'] = max;
+
+    if(container.autocolorscale) {
+        if(min * max < 0) scl = scales.RdBu;
+        else if(min >= 0) scl = scales.Reds;
+        else scl = scales.Blues;
+
+        // reversescale is handled at the containerOut level
+        inputContainer.colorscale = scl;
+        if(container.reversescale) scl = flipScale(scl);
+        container.colorscale = scl;
+    }
+};
+
+},{"../../lib":349,"./flip_scale":309,"./scales":316}],307:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var scales = require('./scales');
+
+
+module.exports = scales.RdBu;
+
+},{"./scales":316}],308:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+
+var hasColorbar = require('../colorbar/has_colorbar');
+var colorbarDefaults = require('../colorbar/defaults');
+var isValidScale = require('./is_valid_scale');
+var flipScale = require('./flip_scale');
+
+
+module.exports = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) {
+    var prefix = opts.prefix,
+        cLetter = opts.cLetter,
+        containerStr = prefix.slice(0, prefix.length-1),
+        containerIn = prefix ?
+            Lib.nestedProperty(traceIn, containerStr).get() || {} :
+            traceIn,
+        containerOut = prefix ?
+            Lib.nestedProperty(traceOut, containerStr).get() || {} :
+            traceOut,
+        minIn = containerIn[cLetter + 'min'],
+        maxIn = containerIn[cLetter + 'max'],
+        sclIn = containerIn.colorscale;
+
+    var validMinMax = isNumeric(minIn) && isNumeric(maxIn) && (minIn < maxIn);
+    coerce(prefix + cLetter + 'auto', !validMinMax);
+    coerce(prefix + cLetter + 'min');
+    coerce(prefix + cLetter + 'max');
+
+    // handles both the trace case (autocolorscale is false by default) and
+    // the marker and marker.line case (autocolorscale is true by default)
+    var autoColorscaleDftl;
+    if(sclIn!==undefined) autoColorscaleDftl = !isValidScale(sclIn);
+    coerce(prefix + 'autocolorscale', autoColorscaleDftl);
+    var sclOut = coerce(prefix + 'colorscale');
+
+    // reversescale is handled at the containerOut level
+    var reverseScale = coerce(prefix + 'reversescale');
+    if(reverseScale) containerOut.colorscale = flipScale(sclOut);
+
+    // ... until Scatter.colorbar can handle marker line colorbars
+    if(prefix === 'marker.line.') return;
+
+    // handle both the trace case where the dflt is listed in attributes and
+    // the marker case where the dflt is determined by hasColorbar
+    var showScaleDftl;
+    if(prefix) showScaleDftl = hasColorbar(containerIn);
+    var showScale = coerce(prefix + 'showscale', showScaleDftl);
+
+    if(showScale) colorbarDefaults(containerIn, containerOut, layout);
+};
+
+},{"../../lib":349,"../colorbar/defaults":301,"../colorbar/has_colorbar":303,"./flip_scale":309,"./is_valid_scale":313,"fast-isnumeric":74}],309:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+module.exports = function flipScale(scl) {
+    var N = scl.length,
+        sclNew = new Array(N),
+        si;
+
+    for(var i = N-1, j = 0; i >= 0; i--, j++) {
+        si = scl[i];
+        sclNew[j] = [1 - si[0], si[1]];
+    }
+
+    return sclNew;
+};
+
+},{}],310:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var scales = require('./scales');
+var defaultScale = require('./default_scale');
+var isValidScaleArray = require('./is_valid_scale_array');
+
+
+module.exports = function getScale(scl, dflt) {
+    if(!dflt) dflt = defaultScale;
+    if(!scl) return dflt;
+
+    function parseScale() {
+        try {
+            scl = scales[scl] || JSON.parse(scl);
+        }
+        catch(e) {
+            scl = dflt;
+        }
+    }
+
+    if(typeof scl === 'string') {
+        parseScale();
+        // occasionally scl is double-JSON encoded...
+        if(typeof scl === 'string') parseScale();
+    }
+
+    if(!isValidScaleArray(scl)) return dflt;
+    return scl;
+};
+
+},{"./default_scale":307,"./is_valid_scale_array":314,"./scales":316}],311:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+
+var isValidScale = require('./is_valid_scale');
+
+
+module.exports = function hasColorscale(trace, containerStr) {
+    var container = containerStr ?
+            Lib.nestedProperty(trace, containerStr).get() || {} :
+            trace,
+        color = container.color,
+        isArrayWithOneNumber = false;
+
+    if(Array.isArray(color)) {
+        for(var i = 0; i < color.length; i++) {
+            if(isNumeric(color[i])) {
+                isArrayWithOneNumber = true;
+                break;
+            }
+        }
+    }
+
+    return (
+        (typeof container==='object' && container!==null) && (
+            isArrayWithOneNumber ||
+            container.showscale===true ||
+            (isNumeric(container.cmin) && isNumeric(container.cmax)) ||
+            isValidScale(container.colorscale) ||
+            (typeof container.colorbar==='object' && container.colorbar!==null)
+        )
+    );
+};
+
+},{"../../lib":349,"./is_valid_scale":313,"fast-isnumeric":74}],312:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+exports.scales = require('./scales');
+
+exports.defaultScale = require('./default_scale');
+
+exports.attributes = require('./attributes');
+
+exports.handleDefaults = require('./defaults');
+
+exports.calc = require('./calc');
+
+exports.hasColorscale = require('./has_colorscale');
+
+exports.isValidScale = require('./is_valid_scale');
+
+exports.getScale = require('./get_scale');
+
+exports.flipScale = require('./flip_scale');
+
+exports.makeScaleFunction = require('./make_scale_function');
+
+},{"./attributes":305,"./calc":306,"./default_scale":307,"./defaults":308,"./flip_scale":309,"./get_scale":310,"./has_colorscale":311,"./is_valid_scale":313,"./make_scale_function":315,"./scales":316}],313:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var scales = require('./scales');
+var isValidScaleArray = require('./is_valid_scale_array');
+
+
+module.exports = function isValidScale(scl) {
+    if(scales[scl] !== undefined) return true;
+    else return isValidScaleArray(scl);
+};
+
+},{"./is_valid_scale_array":314,"./scales":316}],314:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var tinycolor = require('tinycolor2');
+
+
+module.exports = function isValidScaleArray(scl) {
+    var isValid = true,
+        highestVal = 0,
+        si;
+
+    if(!Array.isArray(scl)) return false;
+    else {
+        if(+scl[0][0]!==0 || +scl[scl.length-1][0]!==1) return false;
+        for(var i = 0; i < scl.length; i++) {
+            si = scl[i];
+            if(si.length!==2 || +si[0]<highestVal || !tinycolor(si[1]).isValid()) {
+                isValid = false;
+                break;
+            }
+            highestVal = +si[0];
+        }
+        return isValid;
+    }
+};
+
+},{"tinycolor2":229}],315:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var tinycolor = require('tinycolor2');
+var isNumeric = require('fast-isnumeric');
+
+var Color = require('../color');
+
+
+module.exports = function makeScaleFunction(scl, cmin, cmax) {
+    var N = scl.length,
+        domain = new Array(N),
+        range = new Array(N),
+        si;
+
+    for(var i = 0; i < N; i++) {
+        si = scl[i];
+        domain[i] = cmin + si[0] * (cmax - cmin);
+        range[i] = si[1];
+    }
+
+    var sclFunc = d3.scale.linear()
+        .domain(domain)
+        .interpolate(d3.interpolateRgb)
+        .range(range);
+
+    return function(v) {
+        if(isNumeric(v)) return sclFunc(v);
+        else if(tinycolor(v).isValid()) return v;
+        else return Color.defaultLine;
+    };
+};
+
+},{"../color":299,"d3":70,"fast-isnumeric":74,"tinycolor2":229}],316:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+module.exports = {
+    'Greys': [
+        [0, 'rgb(0,0,0)'], [1, 'rgb(255,255,255)']
+    ],
+
+    'YlGnBu': [
+        [0, 'rgb(8,29,88)'], [0.125, 'rgb(37,52,148)'],
+        [0.25, 'rgb(34,94,168)'], [0.375, 'rgb(29,145,192)'],
+        [0.5, 'rgb(65,182,196)'], [0.625, 'rgb(127,205,187)'],
+        [0.75, 'rgb(199,233,180)'], [0.875, 'rgb(237,248,217)'],
+        [1, 'rgb(255,255,217)']
+    ],
+
+    'Greens': [
+        [0, 'rgb(0,68,27)'], [0.125, 'rgb(0,109,44)'],
+        [0.25, 'rgb(35,139,69)'], [0.375, 'rgb(65,171,93)'],
+        [0.5, 'rgb(116,196,118)'], [0.625, 'rgb(161,217,155)'],
+        [0.75, 'rgb(199,233,192)'], [0.875, 'rgb(229,245,224)'],
+        [1, 'rgb(247,252,245)']
+    ],
+
+    'YlOrRd': [
+        [0, 'rgb(128,0,38)'], [0.125, 'rgb(189,0,38)'],
+        [0.25, 'rgb(227,26,28)'], [0.375, 'rgb(252,78,42)'],
+        [0.5, 'rgb(253,141,60)'], [0.625, 'rgb(254,178,76)'],
+        [0.75, 'rgb(254,217,118)'], [0.875, 'rgb(255,237,160)'],
+        [1, 'rgb(255,255,204)']
+    ],
+
+    'Bluered': [
+        [0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']
+    ],
+
+    // modified RdBu based on
+    // www.sandia.gov/~kmorel/documents/ColorMaps/ColorMapsExpanded.pdf
+    'RdBu': [
+        [0, 'rgb(5,10,172)'], [0.35, 'rgb(106,137,247)'],
+        [0.5, 'rgb(190,190,190)'], [0.6, 'rgb(220,170,132)'],
+        [0.7, 'rgb(230,145,90)'], [1, 'rgb(178,10,28)']
+    ],
+
+    // Scale for non-negative numeric values
+    'Reds': [
+        [0, 'rgb(220,220,220)'], [0.2, 'rgb(245,195,157)'],
+        [0.4, 'rgb(245,160,105)'], [1, 'rgb(178,10,28)']
+    ],
+
+    // Scale for non-positive numeric values
+    'Blues': [
+        [0, 'rgb(5,10,172)'], [0.35, 'rgb(40,60,190)'],
+        [0.5, 'rgb(70,100,245)'], [0.6, 'rgb(90,120,245)'],
+        [0.7, 'rgb(106,137,247)'], [1, 'rgb(220,220,220)']
+    ],
+
+    'Picnic': [
+        [0, 'rgb(0,0,255)'], [0.1, 'rgb(51,153,255)'],
+        [0.2, 'rgb(102,204,255)'], [0.3, 'rgb(153,204,255)'],
+        [0.4, 'rgb(204,204,255)'], [0.5, 'rgb(255,255,255)'],
+        [0.6, 'rgb(255,204,255)'], [0.7, 'rgb(255,153,255)'],
+        [0.8, 'rgb(255,102,204)'], [0.9, 'rgb(255,102,102)'],
+        [1, 'rgb(255,0,0)']
+    ],
+
+    'Rainbow': [
+        [0, 'rgb(150,0,90)'], [0.125, 'rgb(0,0,200)'],
+        [0.25, 'rgb(0,25,255)'], [0.375, 'rgb(0,152,255)'],
+        [0.5, 'rgb(44,255,150)'], [0.625, 'rgb(151,255,0)'],
+        [0.75, 'rgb(255,234,0)'], [0.875, 'rgb(255,111,0)'],
+        [1, 'rgb(255,0,0)']
+    ],
+
+    'Portland': [
+        [0, 'rgb(12,51,131)'], [0.25, 'rgb(10,136,186)'],
+        [0.5, 'rgb(242,211,56)'], [0.75, 'rgb(242,143,56)'],
+        [1, 'rgb(217,30,30)']
+    ],
+
+    'Jet': [
+        [0, 'rgb(0,0,131)'], [0.125, 'rgb(0,60,170)'],
+        [0.375, 'rgb(5,255,255)'], [0.625, 'rgb(255,255,0)'],
+        [0.875, 'rgb(250,0,0)'], [1, 'rgb(128,0,0)']
+    ],
+
+    'Hot': [
+        [0, 'rgb(0,0,0)'], [0.3, 'rgb(230,0,0)'],
+        [0.6, 'rgb(255,210,0)'], [1, 'rgb(255,255,255)']
+    ],
+
+    'Blackbody': [
+        [0, 'rgb(0,0,0)'], [0.2, 'rgb(230,0,0)'],
+        [0.4, 'rgb(230,210,0)'], [0.7, 'rgb(255,255,255)'],
+        [1, 'rgb(160,200,255)']
+    ],
+
+    'Earth': [
+        [0, 'rgb(0,0,130)'], [0.1, 'rgb(0,180,180)'],
+        [0.2, 'rgb(40,210,40)'], [0.4, 'rgb(230,230,50)'],
+        [0.6, 'rgb(120,70,20)'], [1, 'rgb(255,255,255)']
+    ],
+
+    'Electric': [
+        [0, 'rgb(0,0,0)'], [0.15, 'rgb(30,0,100)'],
+        [0.4, 'rgb(120,0,100)'], [0.6, 'rgb(160,90,0)'],
+        [0.8, 'rgb(230,200,0)'], [1, 'rgb(255,250,220)']
+    ],
+
+    'Viridis': [
+        [0, '#440154'], [0.06274509803921569, '#48186a'],
+        [0.12549019607843137, '#472d7b'], [0.18823529411764706, '#424086'],
+        [0.25098039215686274, '#3b528b'], [0.3137254901960784, '#33638d'],
+        [0.3764705882352941, '#2c728e'], [0.4392156862745098, '#26828e'],
+        [0.5019607843137255, '#21918c'], [0.5647058823529412, '#1fa088'],
+        [0.6274509803921569, '#28ae80'], [0.6901960784313725, '#3fbc73'],
+        [0.7529411764705882, '#5ec962'], [0.8156862745098039, '#84d44b'],
+        [0.8784313725490196, '#addc30'], [0.9411764705882353, '#d8e219'],
+        [1, '#fde725']
+    ]
+};
+
+},{}],317:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../../plotly');
+var d3 = require('d3');
+var isNumeric = require('fast-isnumeric');
+
+var xmlnsNamespaces = require('../../constants/xmlns_namespaces');
+var subTypes = require('../../traces/scatter/subtypes');
+var makeBubbleSizeFn = require('../../traces/scatter/make_bubble_size_func');
+
+var drawing = module.exports = {};
+
+// -----------------------------------------------------
+// styling functions for plot elements
+// -----------------------------------------------------
+
+drawing.font = function(s, family, size, color) {
+    // also allow the form font(s, {family, size, color})
+    if(family && family.family) {
+        color = family.color;
+        size = family.size;
+        family = family.family;
+    }
+    if(family) s.style('font-family', family);
+    if(size+1) s.style('font-size', size + 'px');
+    if(color) s.call(Plotly.Color.fill, color);
+};
+
+drawing.setPosition = function(s, x, y) { s.attr('x',x).attr('y',y); };
+drawing.setSize = function(s, w, h) { s.attr('width',w).attr('height',h); };
+drawing.setRect = function(s, x, y, w, h) {
+    s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h);
+};
+
+drawing.translatePoints = function(s, xa, ya) {
+    s.each(function(d) {
+        // put xp and yp into d if pixel scaling is already done
+        var x = d.xp || xa.c2p(d.x),
+            y = d.yp || ya.c2p(d.y),
+            p = d3.select(this);
+        if(isNumeric(x) && isNumeric(y)) {
+            // for multiline text this works better
+            if(this.nodeName==='text') p.attr('x',x).attr('y',y);
+            else p.attr('transform', 'translate('+x+','+y+')');
+        }
+        else p.remove();
+    });
+};
+
+drawing.getPx = function(s, styleAttr) {
+    // helper to pull out a px value from a style that may contain px units
+    // s is a d3 selection (will pull from the first one)
+    return Number(s.style(styleAttr).replace(/px$/,''));
+};
+
+drawing.crispRound = function(td, lineWidth, dflt) {
+    // for lines that disable antialiasing we want to
+    // make sure the width is an integer, and at least 1 if it's nonzero
+
+    if(!lineWidth || !isNumeric(lineWidth)) return dflt || 0;
+
+    // but not for static plots - these don't get antialiased anyway.
+    if(td._context.staticPlot) return lineWidth;
+
+    if(lineWidth<1) return 1;
+    return Math.round(lineWidth);
+};
+
+drawing.lineGroupStyle = function(s, lw, lc, ld) {
+    s.style('fill','none')
+    .each(function(d) {
+        var line = (((d||[])[0]||{}).trace||{}).line||{},
+            lw1 = lw||line.width||0,
+            dash = ld||line.dash||'';
+
+        d3.select(this)
+            .call(Plotly.Color.stroke,lc||line.color)
+            .call(drawing.dashLine, dash, lw1);
+    });
+};
+
+drawing.dashLine = function(s, dash, lineWidth) {
+    var dlw = Math.max(lineWidth, 3);
+
+    if(dash==='solid') dash = '';
+    else if(dash==='dot') dash = dlw+'px,'+dlw+'px';
+    else if(dash==='dash') dash = (3*dlw)+'px,'+(3*dlw)+'px';
+    else if(dash==='longdash') dash = (5*dlw)+'px,'+(5*dlw)+'px';
+    else if(dash==='dashdot') {
+        dash = (3*dlw)+'px,'+dlw+'px,'+dlw+'px,'+dlw+'px';
+    }
+    else if(dash==='longdashdot') {
+        dash = (5*dlw)+'px,'+(2*dlw)+'px,'+dlw+'px,'+(2*dlw)+'px';
+    }
+    // otherwise user wrote the dasharray themselves - leave it be
+
+    s.style({
+        'stroke-dasharray': dash,
+        'stroke-width': lineWidth + 'px'
+    });
+};
+
+drawing.fillGroupStyle = function(s) {
+    s.style('stroke-width',0)
+    .each(function(d) {
+        var shape = d3.select(this);
+        try {
+            shape.call(Plotly.Color.fill, d[0].trace.fillcolor);
+        }
+        catch(e) {
+            console.log(e,s);
+            shape.remove();
+        }
+    });
+};
+
+var SYMBOLDEFS = require('./symbol_defs');
+
+drawing.symbolNames = [];
+drawing.symbolFuncs = [];
+drawing.symbolNeedLines = {};
+drawing.symbolNoDot = {};
+drawing.symbolList = [];
+
+Object.keys(SYMBOLDEFS).forEach(function(k) {
+    var symDef = SYMBOLDEFS[k];
+    drawing.symbolList = drawing.symbolList.concat(
+        [symDef.n, k, symDef.n+100, k+'-open']);
+    drawing.symbolNames[symDef.n] = k;
+    drawing.symbolFuncs[symDef.n] = symDef.f;
+    if(symDef.needLine) {
+        drawing.symbolNeedLines[symDef.n] = true;
+    }
+    if(symDef.noDot) {
+        drawing.symbolNoDot[symDef.n] = true;
+    }
+    else {
+        drawing.symbolList = drawing.symbolList.concat(
+            [symDef.n+200, k+'-dot', symDef.n+300, k+'-open-dot']);
+    }
+});
+var MAXSYMBOL = drawing.symbolNames.length,
+    // add a dot in the middle of the symbol
+    DOTPATH = 'M0,0.5L0.5,0L0,-0.5L-0.5,0Z';
+
+drawing.symbolNumber = function(v) {
+    if(typeof v === 'string') {
+        var vbase = 0;
+        if(v.indexOf('-open') > 0) {
+            vbase = 100;
+            v = v.replace('-open','');
+        }
+        if(v.indexOf('-dot') > 0) {
+            vbase += 200;
+            v = v.replace('-dot','');
+        }
+        v = drawing.symbolNames.indexOf(v);
+        if(v>=0) { v += vbase; }
+    }
+    if((v%100 >= MAXSYMBOL) || v>=400) { return 0; }
+    return Math.floor(Math.max(v,0));
+};
+
+drawing.pointStyle = function(s, trace) {
+    if(!s.size()) return;
+
+    var marker = trace.marker,
+        markerLine = marker.line;
+
+    // only scatter & box plots get marker path and opacity
+    // bars, histograms don't
+    if(Plotly.Plots.traceIs(trace, 'symbols')) {
+        var sizeFn = makeBubbleSizeFn(trace);
+
+        s.attr('d', function(d) {
+            var r;
+
+            // handle multi-trace graph edit case
+            if(d.ms==='various' || marker.size==='various') r = 3;
+            else r = subTypes.isBubble(trace) ?
+                        sizeFn(d.ms) : (marker.size || 6) / 2;
+
+            // store the calculated size so hover can use it
+            d.mrc = r;
+
+            // turn the symbol into a sanitized number
+            var x = drawing.symbolNumber(d.mx || marker.symbol) || 0,
+                xBase = x%100;
+
+            // save if this marker is open
+            // because that impacts how to handle colors
+            d.om = x%200 >= 100;
+
+            return drawing.symbolFuncs[xBase](r) +
+                (x >= 200 ? DOTPATH : '');
+        })
+        .style('opacity',function(d) {
+            return (d.mo+1 || marker.opacity+1) - 1;
+        });
+    }
+    // allow array marker and marker line colors to be
+    // scaled by given max and min to colorscales
+    var markerIn = (trace._input||{}).marker||{},
+        markerScale = drawing.tryColorscale(marker, markerIn, ''),
+        lineScale = drawing.tryColorscale(marker, markerIn, 'line.');
+
+    s.each(function(d) {
+        // 'so' is suspected outliers, for box plots
+        var fillColor,
+            lineColor,
+            lineWidth;
+        if(d.so) {
+            lineWidth = markerLine.outlierwidth;
+            lineColor = markerLine.outliercolor;
+            fillColor = marker.outliercolor;
+        }
+        else {
+            lineWidth = (d.mlw+1 || markerLine.width+1 ||
+                // TODO: we need the latter for legends... can we get rid of it?
+                (d.trace ? d.trace.marker.line.width : 0) + 1) -1;
+
+            if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc);
+            // weird case: array wasn't long enough to apply to every point
+            else if(Array.isArray(markerLine.color)) lineColor = Plotly.Color.defaultLine;
+            else lineColor = markerLine.color;
+
+            if('mc' in d) fillColor = d.mcc = markerScale(d.mc);
+            else if(Array.isArray(marker.color)) fillColor = Plotly.Color.defaultLine;
+            else fillColor = marker.color || 'rgba(0,0,0,0)';
+        }
+
+        var p = d3.select(this);
+        if(d.om) {
+            // open markers can't have zero linewidth, default to 1px,
+            // and use fill color as stroke color
+            p.call(Plotly.Color.stroke, fillColor)
+                .style({
+                    'stroke-width': (lineWidth||1) + 'px',
+                    fill: 'none'
+                });
+        }
+        else {
+            p.style('stroke-width', lineWidth + 'px')
+                .call(Plotly.Color.fill, fillColor);
+            if(lineWidth) {
+                p.call(Plotly.Color.stroke, lineColor);
+            }
+        }
+    });
+};
+
+// for a given color attribute (ie m -> mc = marker.color) look to see if we
+// have a colorscale for it (ie mscl, mcmin, mcmax) - if we do, translate
+// all numeric color values according to that scale
+drawing.tryColorscale = function(cont, contIn, prefix) {
+    var colorArray = Plotly.Lib.nestedProperty(cont, prefix + 'color').get(),
+        scl = Plotly.Lib.nestedProperty(cont, prefix + 'colorscale').get(),
+        auto = Plotly.Lib.nestedProperty(cont, prefix + 'cauto').get(),
+        minProp = Plotly.Lib.nestedProperty(cont, prefix + 'cmin'),
+        maxProp = Plotly.Lib.nestedProperty(cont, prefix + 'cmax'),
+        min = minProp.get(),
+        max = maxProp.get();
+
+    // TODO handle this in Colorscale.calc
+    if(scl && Array.isArray(colorArray)) {
+        if(auto || !isNumeric(min) || !isNumeric(max)) {
+            min = Infinity;
+            max = -Infinity;
+            colorArray.forEach(function(color) {
+                if(isNumeric(color)) {
+                    if(min > color) min = +color;
+                    if(max < color) max = +color;
+                }
+            });
+            if(min > max) {
+                min = 0;
+                max = 1;
+            }
+            minProp.set(min);
+            maxProp.set(max);
+            Plotly.Lib.nestedProperty(contIn, prefix + 'cmin').set(min);
+            Plotly.Lib.nestedProperty(contIn, prefix + 'cmax').set(max);
+        }
+        return Plotly.Colorscale.makeScaleFunction(scl, min, max);
+    }
+    else return Plotly.Lib.identity;
+};
+
+// draw text at points
+var TEXTOFFSETSIGN = {start: 1, end: -1, middle: 0, bottom: 1, top: -1},
+    LINEEXPAND = 1.3;
+drawing.textPointStyle = function(s, trace) {
+    s.each(function(d) {
+        var p = d3.select(this),
+            text = d.tx || trace.text;
+        if(!text || Array.isArray(text)) {
+            // isArray test handles the case of (intentionally) missing
+            // or empty text within a text array
+            p.remove();
+            return;
+        }
+
+        var pos = d.tp || trace.textposition,
+            v = pos.indexOf('top')!==-1 ? 'top' :
+                pos.indexOf('bottom')!==-1 ? 'bottom' : 'middle',
+            h = pos.indexOf('left')!==-1 ? 'end' :
+                pos.indexOf('right')!==-1 ? 'start' : 'middle',
+            fontSize = d.ts || trace.textfont.size,
+            // if markers are shown, offset a little more than
+            // the nominal marker size
+            // ie 2/1.6 * nominal, bcs some markers are a bit bigger
+            r = d.mrc ? (d.mrc/0.8 + 1) : 0;
+
+        fontSize = (isNumeric(fontSize) && fontSize>0) ? fontSize : 0;
+
+        p.call(drawing.font,
+                d.tf || trace.textfont.family,
+                fontSize,
+                d.tc || trace.textfont.color)
+            .attr('text-anchor',h)
+            .text(text)
+            .call(Plotly.util.convertToTspans);
+        var pgroup = d3.select(this.parentNode),
+            tspans = p.selectAll('tspan.line'),
+            numLines = ((tspans[0].length||1)-1)*LINEEXPAND+1,
+            dx = TEXTOFFSETSIGN[h]*r,
+            dy = fontSize*0.75 + TEXTOFFSETSIGN[v]*r +
+                (TEXTOFFSETSIGN[v]-1)*numLines*fontSize/2;
+
+        // fix the overall text group position
+        pgroup.attr('transform','translate('+dx+','+dy+')');
+
+        // then fix multiline text
+        if(numLines>1) {
+            tspans.attr({ x: p.attr('x'), y: p.attr('y') });
+        }
+    });
+};
+
+// generalized Catmull-Rom splines, per
+// http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
+var CatmullRomExp = 0.5;
+drawing.smoothopen = function(pts,smoothness) {
+    if(pts.length<3) { return 'M' + pts.join('L');}
+    var path = 'M'+pts[0],
+        tangents = [], i;
+    for(i=1; i<pts.length-1; i++) {
+        tangents.push(makeTangent(pts[i-1], pts[i], pts[i+1], smoothness));
+    }
+    path += 'Q'+tangents[0][0]+' '+pts[1];
+    for(i=2; i<pts.length-1; i++) {
+        path += 'C'+tangents[i-2][1]+' '+tangents[i-1][0]+' '+pts[i];
+    }
+    path += 'Q'+tangents[pts.length-3][1]+' '+pts[pts.length-1];
+    return path;
+};
+
+drawing.smoothclosed = function(pts,smoothness) {
+    if(pts.length<3) { return 'M' + pts.join('L') + 'Z'; }
+    var path = 'M'+pts[0],
+        pLast = pts.length-1,
+        tangents = [makeTangent(pts[pLast],
+                        pts[0], pts[1], smoothness)],
+        i;
+    for(i=1; i<pLast; i++) {
+        tangents.push(makeTangent(pts[i-1], pts[i], pts[i+1], smoothness));
+    }
+    tangents.push(
+        makeTangent(pts[pLast-1], pts[pLast], pts[0], smoothness)
+    );
+
+    for(i=1; i<=pLast; i++) {
+        path += 'C'+tangents[i-1][1]+' '+tangents[i][0]+' '+pts[i];
+    }
+    path += 'C'+tangents[pLast][1]+' '+tangents[0][0]+' '+pts[0] + 'Z';
+    return path;
+};
+
+function makeTangent(prevpt,thispt,nextpt,smoothness) {
+    var d1x = prevpt[0]-thispt[0],
+        d1y = prevpt[1]-thispt[1],
+        d2x = nextpt[0]-thispt[0],
+        d2y = nextpt[1]-thispt[1],
+        d1a = Math.pow(d1x*d1x + d1y*d1y, CatmullRomExp/2),
+        d2a = Math.pow(d2x*d2x + d2y*d2y, CatmullRomExp/2),
+        numx = (d2a*d2a*d1x - d1a*d1a*d2x)*smoothness,
+        numy = (d2a*d2a*d1y - d1a*d1a*d2y)*smoothness,
+        denom1 = 3*d2a*(d1a+d2a),
+        denom2 = 3*d1a*(d1a+d2a);
+    return [
+        [
+            d3.round(thispt[0]+(denom1 && numx/denom1),2),
+            d3.round(thispt[1]+(denom1 && numy/denom1),2)
+        ],[
+            d3.round(thispt[0]-(denom2 && numx/denom2),2),
+            d3.round(thispt[1]-(denom2 && numy/denom2),2)
+        ]
+    ];
+}
+
+// step paths - returns a generator function for paths
+// with the given step shape
+var STEPPATH = {
+    hv: function(p0,p1) {
+        return 'H'+d3.round(p1[0],2)+'V'+d3.round(p1[1],2);
+    },
+    vh: function(p0,p1) {
+        return 'V'+d3.round(p1[1],2)+'H'+d3.round(p1[0],2);
+    },
+    hvh: function(p0,p1) {
+        return 'H'+d3.round((p0[0]+p1[0])/2,2)+'V'+
+            d3.round(p1[1],2)+'H'+d3.round(p1[0],2);
+    },
+    vhv: function(p0,p1) {
+        return 'V'+d3.round((p0[1]+p1[1])/2,2)+'H'+
+            d3.round(p1[0],2)+'V'+d3.round(p1[1],2);
+    }
+};
+var STEPLINEAR = function(p0,p1) {
+    return 'L'+d3.round(p1[0],2)+','+d3.round(p1[1],2);
+};
+drawing.steps = function(shape) {
+    var onestep = STEPPATH[shape] || STEPLINEAR;
+    return function(pts) {
+        var path = 'M'+d3.round(pts[0][0],2)+','+d3.round(pts[0][1],2);
+        for(var i=1; i<pts.length; i++) {
+            path += onestep(pts[i-1],pts[i]);
+        }
+        return path;
+    };
+};
+
+// off-screen svg render testing element, shared by the whole page
+// uses the id 'js-plotly-tester' and stores it in gd._tester
+// makes a hash of cached text items in tester.node()._cache
+// so we can add references to rendered text (including all info
+// needed to fully determine its bounding rect)
+drawing.makeTester = function(gd) {
+    var tester = d3.select('body')
+        .selectAll('#js-plotly-tester')
+        .data([0]);
+
+    tester.enter().append('svg')
+        .attr('id', 'js-plotly-tester')
+        .attr(xmlnsNamespaces.svgAttrs)
+        .style({
+            position: 'absolute',
+            left: '-10000px',
+            top: '-10000px',
+            width: '9000px',
+            height: '9000px'
+        });
+
+    // browsers differ on how they describe the bounding rect of
+    // the svg if its contents spill over... so make a 1x1px
+    // reference point we can measure off of.
+    var testref = tester.selectAll('.js-reference-point').data([0]);
+    testref.enter().append('path')
+        .classed('js-reference-point', true)
+        .attr('d','M0,0H1V1H0Z')
+        .style({
+            'stroke-width': 0,
+            fill: 'black'
+        });
+
+    if(!tester.node()._cache) {
+        tester.node()._cache = {};
+    }
+
+    gd._tester = tester;
+    gd._testref = testref;
+};
+
+// use our offscreen tester to get a clientRect for an element,
+// in a reference frame where it isn't translated and its anchor
+// point is at (0,0)
+// always returns a copy of the bbox, so the caller can modify it safely
+var savedBBoxes = [],
+    maxSavedBBoxes = 10000;
+drawing.bBox = function(node) {
+    // cache elements we've already measured so we don't have to
+    // remeasure the same thing many times
+    var saveNum = node.attributes['data-bb'];
+    if(saveNum && saveNum.value) {
+        return Plotly.Lib.extendFlat({}, savedBBoxes[saveNum.value]);
+    }
+
+    var test3 = d3.select('#js-plotly-tester'),
+        tester = test3.node();
+
+    // copy the node to test into the tester
+    var testNode = node.cloneNode(true);
+    tester.appendChild(testNode);
+    // standardize its position... do we really want to do this?
+    d3.select(testNode).attr({
+        x: 0,
+        y: 0,
+        transform: ''
+    });
+
+    var testRect = testNode.getBoundingClientRect(),
+        refRect = test3.select('.js-reference-point')
+            .node().getBoundingClientRect();
+
+    tester.removeChild(testNode);
+
+    var bb = {
+        height: testRect.height,
+        width: testRect.width,
+        left: testRect.left - refRect.left,
+        top: testRect.top - refRect.top,
+        right: testRect.right - refRect.left,
+        bottom: testRect.bottom - refRect.top
+    };
+
+    // make sure we don't have too many saved boxes,
+    // or a long session could overload on memory
+    // by saving boxes for long-gone elements
+    if(savedBBoxes.length>=maxSavedBBoxes) {
+        d3.selectAll('[data-bb]').attr('data-bb', null);
+        savedBBoxes = [];
+    }
+
+    // cache this bbox
+    node.setAttribute('data-bb',savedBBoxes.length);
+    savedBBoxes.push(bb);
+
+    return Plotly.Lib.extendFlat({}, bb);
+};
+
+/*
+ * make a robust clipPath url from a local id
+ * note! We'd better not be exporting from a page
+ * with a <base> or the svg will not be portable!
+ */
+drawing.setClipUrl = function(s, localId) {
+    if(!localId) {
+        s.attr('clip-path', null);
+        return;
+    }
+
+    var url = '#' + localId,
+        base = d3.select('base');
+
+    if(base.size() && base.attr('href')) url = window.location.href + url;
+    s.attr('clip-path', 'url(' + url + ')');
+};
+
+},{"../../constants/xmlns_namespaces":338,"../../plotly":366,"../../traces/scatter/make_bubble_size_func":514,"../../traces/scatter/subtypes":520,"./symbol_defs":318,"d3":70,"fast-isnumeric":74}],318:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+/** Marker symbol definitions
+ * users can specify markers either by number or name
+ * add 100 (or '-open') and you get an open marker
+ *  open markers have no fill and use line color as the stroke color
+ * add 200 (or '-dot') and you get a dot in the middle
+ * add both and you get both
+ */
+
+module.exports = {
+    circle: {
+        n: 0,
+        f: function(r) {
+            var rs = d3.round(r,2);
+            return 'M'+rs+',0A'+rs+','+rs+' 0 1,1 0,-'+rs+
+                'A'+rs+','+rs+' 0 0,1 '+rs+',0Z';
+        }
+    },
+    square: {
+        n: 1,
+        f: function(r) {
+            var rs = d3.round(r,2);
+            return 'M'+rs+','+rs+'H-'+rs+'V-'+rs+'H'+rs+'Z';
+        }
+    },
+    diamond: {
+        n: 2,
+        f: function(r) {
+            var rd = d3.round(r*1.3,2);
+            return 'M'+rd+',0L0,'+rd+'L-'+rd+',0L0,-'+rd+'Z';
+        }
+    },
+    cross: {
+        n: 3,
+        f: function(r) {
+            var rc = d3.round(r*0.4,2),
+                rc2 = d3.round(r*1.2,2);
+            return 'M'+rc2+','+rc+'H'+rc+'V'+rc2+'H-'+rc+
+                'V'+rc+'H-'+rc2+'V-'+rc+'H-'+rc+'V-'+rc2+
+                'H'+rc+'V-'+rc+'H'+rc2+'Z';
+        }
+    },
+    x: {
+        n: 4,
+        f: function(r) {
+            var rx = d3.round(r*0.8/Math.sqrt(2),2),
+                ne = 'l'+rx+','+rx,
+                se = 'l'+rx+',-'+rx,
+                sw = 'l-'+rx+',-'+rx,
+                nw = 'l-'+rx+','+rx;
+            return 'M0,'+rx+ne+se+sw+se+sw+nw+sw+nw+ne+nw+ne+'Z';
+        }
+    },
+    'triangle-up': {
+        n: 5,
+        f: function(r) {
+            var rt = d3.round(r*2/Math.sqrt(3),2),
+                r2 = d3.round(r/2,2),
+                rs = d3.round(r,2);
+            return 'M-'+rt+','+r2+'H'+rt+'L0,-'+rs+'Z';
+        }
+    },
+    'triangle-down': {
+        n: 6,
+        f: function(r) {
+            var rt = d3.round(r*2/Math.sqrt(3),2),
+                r2 = d3.round(r/2,2),
+                rs = d3.round(r,2);
+            return 'M-'+rt+',-'+r2+'H'+rt+'L0,'+rs+'Z';
+        }
+    },
+    'triangle-left': {
+        n: 7,
+        f: function(r) {
+            var rt = d3.round(r*2/Math.sqrt(3),2),
+                r2 = d3.round(r/2,2),
+                rs = d3.round(r,2);
+            return 'M'+r2+',-'+rt+'V'+rt+'L-'+rs+',0Z';
+        }
+    },
+    'triangle-right': {
+        n: 8,
+        f: function(r) {
+            var rt = d3.round(r*2/Math.sqrt(3),2),
+                r2 = d3.round(r/2,2),
+                rs = d3.round(r,2);
+            return 'M-'+r2+',-'+rt+'V'+rt+'L'+rs+',0Z';
+        }
+    },
+    'triangle-ne': {
+        n: 9,
+        f: function(r) {
+            var r1 = d3.round(r*0.6,2),
+                r2 = d3.round(r*1.2,2);
+            return 'M-'+r2+',-'+r1+'H'+r1+'V'+r2+'Z';
+        }
+    },
+    'triangle-se': {
+        n: 10,
+        f: function(r) {
+            var r1 = d3.round(r*0.6,2),
+                r2 = d3.round(r*1.2,2);
+            return 'M'+r1+',-'+r2+'V'+r1+'H-'+r2+'Z';
+        }
+    },
+    'triangle-sw': {
+        n: 11,
+        f: function(r) {
+            var r1 = d3.round(r*0.6,2),
+                r2 = d3.round(r*1.2,2);
+            return 'M'+r2+','+r1+'H-'+r1+'V-'+r2+'Z';
+        }
+    },
+    'triangle-nw': {
+        n: 12,
+        f: function(r) {
+            var r1 = d3.round(r*0.6,2),
+                r2 = d3.round(r*1.2,2);
+            return 'M-'+r1+','+r2+'V-'+r1+'H'+r2+'Z';
+        }
+    },
+    pentagon: {
+        n: 13,
+        f: function(r) {
+            var x1 = d3.round(r*0.951,2),
+                x2 = d3.round(r*0.588,2),
+                y0 = d3.round(-r,2),
+                y1 = d3.round(r*-0.309,2),
+                y2 = d3.round(r*0.809,2);
+            return 'M'+x1+','+y1+'L'+x2+','+y2+'H-'+x2+
+                'L-'+x1+','+y1+'L0,'+y0+'Z';
+        }
+    },
+    hexagon: {
+        n: 14,
+        f: function(r) {
+            var y0 = d3.round(r,2),
+                y1 = d3.round(r/2,2),
+                x = d3.round(r*Math.sqrt(3)/2,2);
+            return 'M'+x+',-'+y1+'V'+y1+'L0,'+y0+
+                'L-'+x+','+y1+'V-'+y1+'L0,-'+y0+'Z';
+        }
+    },
+    hexagon2: {
+        n: 15,
+        f: function(r) {
+            var x0 = d3.round(r,2),
+                x1 = d3.round(r/2,2),
+                y = d3.round(r*Math.sqrt(3)/2,2);
+            return 'M-'+x1+','+y+'H'+x1+'L'+x0+
+                ',0L'+x1+',-'+y+'H-'+x1+'L-'+x0+',0Z';
+        }
+    },
+    octagon: {
+        n: 16,
+        f: function(r) {
+            var a = d3.round(r*0.924,2),
+                b = d3.round(r*0.383,2);
+            return 'M-'+b+',-'+a+'H'+b+'L'+a+',-'+b+'V'+b+
+                'L'+b+','+a+'H-'+b+'L-'+a+','+b+'V-'+b+'Z';
+        }
+    },
+    star: {
+        n: 17,
+        f: function(r) {
+            var rs = r*1.4,
+                x1 = d3.round(rs*0.225,2),
+                x2 = d3.round(rs*0.951,2),
+                x3 = d3.round(rs*0.363,2),
+                x4 = d3.round(rs*0.588,2),
+                y0 = d3.round(-rs,2),
+                y1 = d3.round(rs*-0.309,2),
+                y3 = d3.round(rs*0.118,2),
+                y4 = d3.round(rs*0.809,2),
+                y5 = d3.round(rs*0.382,2);
+            return 'M'+x1+','+y1+'H'+x2+'L'+x3+','+y3+
+                'L'+x4+','+y4+'L0,'+y5+'L-'+x4+','+y4+
+                'L-'+x3+','+y3+'L-'+x2+','+y1+'H-'+x1+
+                'L0,'+y0+'Z';
+        }
+    },
+    hexagram: {
+        n: 18,
+        f: function(r) {
+            var y = d3.round(r*0.66,2),
+                x1 = d3.round(r*0.38,2),
+                x2 = d3.round(r*0.76,2);
+            return 'M-'+x2+',0l-'+x1+',-'+y+'h'+x2+
+                'l'+x1+',-'+y+'l'+x1+','+y+'h'+x2+
+                'l-'+x1+','+y+'l'+x1+','+y+'h-'+x2+
+                'l-'+x1+','+y+'l-'+x1+',-'+y+'h-'+x2+'Z';
+        }
+    },
+    'star-triangle-up': {
+        n: 19,
+        f: function(r) {
+            var x = d3.round(r*Math.sqrt(3)*0.8,2),
+                y1 = d3.round(r*0.8,2),
+                y2 = d3.round(r*1.6,2),
+                rc = d3.round(r*4,2),
+                aPart = 'A '+rc+','+rc+' 0 0 1 ';
+            return 'M-'+x+','+y1+aPart+x+','+y1+
+                aPart+'0,-'+y2+aPart+'-'+x+','+y1+'Z';
+        }
+    },
+    'star-triangle-down': {
+        n: 20,
+        f: function(r) {
+            var x = d3.round(r*Math.sqrt(3)*0.8,2),
+                y1 = d3.round(r*0.8,2),
+                y2 = d3.round(r*1.6,2),
+                rc = d3.round(r*4,2),
+                aPart = 'A '+rc+','+rc+' 0 0 1 ';
+            return 'M'+x+',-'+y1+aPart+'-'+x+',-'+y1+
+                aPart+'0,'+y2+aPart+x+',-'+y1+'Z';
+        }
+    },
+    'star-square': {
+        n: 21,
+        f: function(r) {
+            var rp = d3.round(r*1.1,2),
+                rc = d3.round(r*2,2),
+                aPart = 'A '+rc+','+rc+' 0 0 1 ';
+            return 'M-'+rp+',-'+rp+aPart+'-'+rp+','+rp+
+                aPart+rp+','+rp+aPart+rp+',-'+rp+
+                aPart+'-'+rp+',-'+rp+'Z';
+        }
+    },
+    'star-diamond': {
+        n: 22,
+        f: function(r) {
+            var rp = d3.round(r*1.4,2),
+                rc = d3.round(r*1.9,2),
+                aPart = 'A '+rc+','+rc+' 0 0 1 ';
+            return 'M-'+rp+',0'+aPart+'0,'+rp+
+                aPart+rp+',0'+aPart+'0,-'+rp+
+                aPart+'-'+rp+',0'+'Z';
+        }
+    },
+    'diamond-tall': {
+        n: 23,
+        f: function(r) {
+            var x = d3.round(r*0.7,2),
+                y = d3.round(r*1.4,2);
+            return 'M0,'+y+'L'+x+',0L0,-'+y+'L-'+x+',0Z';
+        }
+    },
+    'diamond-wide': {
+        n: 24,
+        f: function(r) {
+            var x = d3.round(r*1.4,2),
+                y = d3.round(r*0.7,2);
+            return 'M0,'+y+'L'+x+',0L0,-'+y+'L-'+x+',0Z';
+        }
+    },
+    hourglass: {
+        n: 25,
+        f: function(r) {
+            var rs = d3.round(r,2);
+            return 'M'+rs+','+rs+'H-'+rs+'L'+rs+',-'+rs+'H-'+rs+'Z';
+        },
+        noDot: true
+    },
+    bowtie: {
+        n: 26,
+        f: function(r) {
+            var rs = d3.round(r,2);
+            return 'M'+rs+','+rs+'V-'+rs+'L-'+rs+','+rs+'V-'+rs+'Z';
+        },
+        noDot: true
+    },
+    'circle-cross': {
+        n: 27,
+        f: function(r) {
+            var rs = d3.round(r,2);
+            return 'M0,'+rs+'V-'+rs+'M'+rs+',0H-'+rs+
+                'M'+rs+',0A'+rs+','+rs+' 0 1,1 0,-'+rs+
+                'A'+rs+','+rs+' 0 0,1 '+rs+',0Z';
+        },
+        needLine: true,
+        noDot: true
+    },
+    'circle-x': {
+        n: 28,
+        f: function(r) {
+            var rs = d3.round(r,2),
+                rc = d3.round(r/Math.sqrt(2),2);
+            return 'M'+rc+','+rc+'L-'+rc+',-'+rc+
+                'M'+rc+',-'+rc+'L-'+rc+','+rc+
+                'M'+rs+',0A'+rs+','+rs+' 0 1,1 0,-'+rs+
+                'A'+rs+','+rs+' 0 0,1 '+rs+',0Z';
+        },
+        needLine: true,
+        noDot: true
+    },
+    'square-cross': {
+        n: 29,
+        f: function(r) {
+            var rs = d3.round(r,2);
+            return 'M0,'+rs+'V-'+rs+'M'+rs+',0H-'+rs+
+                'M'+rs+','+rs+'H-'+rs+'V-'+rs+'H'+rs+'Z';
+        },
+        needLine: true,
+        noDot: true
+    },
+    'square-x': {
+        n: 30,
+        f: function(r) {
+            var rs = d3.round(r,2);
+            return 'M'+rs+','+rs+'L-'+rs+',-'+rs+
+                'M'+rs+',-'+rs+'L-'+rs+','+rs+
+                'M'+rs+','+rs+'H-'+rs+'V-'+rs+'H'+rs+'Z';
+        },
+        needLine: true,
+        noDot: true
+    },
+    'diamond-cross': {
+        n: 31,
+        f: function(r) {
+            var rd = d3.round(r*1.3,2);
+            return 'M'+rd+',0L0,'+rd+'L-'+rd+',0L0,-'+rd+'Z'+
+                'M0,-'+rd+'V'+rd+'M-'+rd+',0H'+rd;
+        },
+        needLine: true,
+        noDot: true
+    },
+    'diamond-x': {
+        n: 32,
+        f: function(r) {
+            var rd = d3.round(r*1.3,2),
+                r2 = d3.round(r*0.65,2);
+            return 'M'+rd+',0L0,'+rd+'L-'+rd+',0L0,-'+rd+'Z'+
+                'M-'+r2+',-'+r2+'L'+r2+','+r2+
+                'M-'+r2+','+r2+'L'+r2+',-'+r2;
+        },
+        needLine: true,
+        noDot: true
+    },
+    'cross-thin': {
+        n: 33,
+        f: function(r) {
+            var rc = d3.round(r*1.4,2);
+            return 'M0,'+rc+'V-'+rc+'M'+rc+',0H-'+rc;
+        },
+        needLine: true,
+        noDot: true
+    },
+    'x-thin': {
+        n: 34,
+        f: function(r) {
+            var rx = d3.round(r,2);
+            return 'M'+rx+','+rx+'L-'+rx+',-'+rx+
+                'M'+rx+',-'+rx+'L-'+rx+','+rx;
+        },
+        needLine: true,
+        noDot: true
+    },
+    asterisk: {
+        n: 35,
+        f: function(r) {
+            var rc = d3.round(r*1.2,2);
+            var rs = d3.round(r*0.85,2);
+            return 'M0,'+rc+'V-'+rc+'M'+rc+',0H-'+rc+
+                'M'+rs+','+rs+'L-'+rs+',-'+rs+
+                'M'+rs+',-'+rs+'L-'+rs+','+rs;
+        },
+        needLine: true,
+        noDot: true
+    },
+    hash: {
+        n: 36,
+        f: function(r) {
+            var r1 = d3.round(r/2,2),
+                r2 = d3.round(r,2);
+            return 'M'+r1+','+r2+'V-'+r2+
+                'm-'+r2+',0V'+r2+
+                'M'+r2+','+r1+'H-'+r2+
+                'm0,-'+r2+'H'+r2;
+        },
+        needLine: true
+    },
+    'y-up': {
+        n: 37,
+        f: function(r) {
+            var x = d3.round(r*1.2,2),
+                y0 = d3.round(r*1.6,2),
+                y1 = d3.round(r*0.8,2);
+            return 'M-'+x+','+y1+'L0,0M'+x+','+y1+'L0,0M0,-'+y0+'L0,0';
+        },
+        needLine: true,
+        noDot: true
+    },
+    'y-down': {
+        n: 38,
+        f: function(r) {
+            var x = d3.round(r*1.2,2),
+                y0 = d3.round(r*1.6,2),
+                y1 = d3.round(r*0.8,2);
+            return 'M-'+x+',-'+y1+'L0,0M'+x+',-'+y1+'L0,0M0,'+y0+'L0,0';
+        },
+        needLine: true,
+        noDot: true
+    },
+    'y-left': {
+        n: 39,
+        f: function(r) {
+            var y = d3.round(r*1.2,2),
+                x0 = d3.round(r*1.6,2),
+                x1 = d3.round(r*0.8,2);
+            return 'M'+x1+','+y+'L0,0M'+x1+',-'+y+'L0,0M-'+x0+',0L0,0';
+        },
+        needLine: true,
+        noDot: true
+    },
+    'y-right': {
+        n: 40,
+        f: function(r) {
+            var y = d3.round(r*1.2,2),
+                x0 = d3.round(r*1.6,2),
+                x1 = d3.round(r*0.8,2);
+            return 'M-'+x1+','+y+'L0,0M-'+x1+',-'+y+'L0,0M'+x0+',0L0,0';
+        },
+        needLine: true,
+        noDot: true
+    },
+    'line-ew': {
+        n: 41,
+        f: function(r) {
+            var rc = d3.round(r*1.4,2);
+            return 'M'+rc+',0H-'+rc;
+        },
+        needLine: true,
+        noDot: true
+    },
+    'line-ns': {
+        n: 42,
+        f: function(r) {
+            var rc = d3.round(r*1.4,2);
+            return 'M0,'+rc+'V-'+rc;
+        },
+        needLine: true,
+        noDot: true
+    },
+    'line-ne': {
+        n: 43,
+        f: function(r) {
+            var rx = d3.round(r,2);
+            return 'M'+rx+',-'+rx+'L-'+rx+','+rx;
+        },
+        needLine: true,
+        noDot: true
+    },
+    'line-nw': {
+        n: 44,
+        f: function(r) {
+            var rx = d3.round(r,2);
+            return 'M'+rx+','+rx+'L-'+rx+',-'+rx;
+        },
+        needLine: true,
+        noDot: true
+    }
+};
+
+},{"d3":70}],319:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+module.exports = {
+    visible: {
+        valType: 'boolean',
+        
+        
+    },
+    type: {
+        valType: 'enumerated',
+        values: ['percent', 'constant', 'sqrt', 'data'],
+        
+        
+    },
+    symmetric: {
+        valType: 'boolean',
+        
+        
+    },
+    array: {
+        valType: 'data_array',
+        
+    },
+    arrayminus: {
+        valType: 'data_array',
+        
+    },
+    value: {
+        valType: 'number',
+        min: 0,
+        dflt: 10,
+        
+        
+    },
+    valueminus: {
+        valType: 'number',
+        min: 0,
+        dflt: 10,
+        
+        
+    },
+    traceref: {
+        valType: 'integer',
+        min: 0,
+        dflt: 0,
+        
+    },
+    tracerefminus: {
+        valType: 'integer',
+        min: 0,
+        dflt: 0,
+        
+    },
+    copy_ystyle: {
+        valType: 'boolean',
+        
+    },
+    copy_zstyle: {
+        valType: 'boolean',
+        
+    },
+    color: {
+        valType: 'color',
+        
+        
+    },
+    thickness: {
+        valType: 'number',
+        min: 0,
+        dflt: 2,
+        
+        
+    },
+    width: {
+        valType: 'number',
+        min: 0,
+        
+        
+    },
+
+    _deprecated: {
+        opacity: {
+            valType: 'number',
+            
+            
+        }
+    }
+};
+
+},{}],320:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Plots = require('../../plots/plots');
+var Axes = require('../../plots/cartesian/axes');
+
+var makeComputeError = require('./compute_error');
+
+
+module.exports = function calc(gd) {
+    var calcdata = gd.calcdata;
+
+    for(var i = 0; i < calcdata.length; i++) {
+        var calcTrace = calcdata[i],
+            trace = calcTrace[0].trace;
+
+        if(!Plots.traceIs(trace, 'errorBarsOK')) continue;
+
+        var xa = Axes.getFromId(gd, trace.xaxis),
+            ya = Axes.getFromId(gd, trace.yaxis);
+
+        calcOneAxis(calcTrace, trace, xa, 'x');
+        calcOneAxis(calcTrace, trace, ya, 'y');
+    }
+};
+
+function calcOneAxis(calcTrace, trace, axis, coord) {
+    var opts = trace['error_' + coord] || {},
+        isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1),
+        vals = [];
+
+    if(!isVisible) return;
+
+    var computeError = makeComputeError(opts);
+
+    for(var i = 0; i < calcTrace.length; i++) {
+        var calcPt = calcTrace[i],
+            calcCoord = calcPt[coord];
+
+        if(!isNumeric(axis.c2l(calcCoord))) continue;
+
+        var errors = computeError(calcCoord, i);
+        if(isNumeric(errors[0]) && isNumeric(errors[1])) {
+            var shoe = calcPt[coord + 's'] = calcCoord - errors[0],
+                hat = calcPt[coord + 'h'] = calcCoord + errors[1];
+            vals.push(shoe, hat);
+        }
+    }
+
+    Axes.expand(axis, vals, {padded: true});
+}
+
+},{"../../plots/cartesian/axes":369,"../../plots/plots":413,"./compute_error":321,"fast-isnumeric":74}],321:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+
+/**
+ * Error bar computing function generator
+ *
+ * N.B. The generated function does not clean the dataPt entries. Non-numeric
+ * entries result in undefined error magnitudes.
+ *
+ * @param {object} opts error bar attributes
+ *
+ * @return {function} :
+ *      @param {numeric} dataPt data point from where to compute the error magnitude
+ *      @param {number} index index of dataPt in its corresponding data array
+ *      @return {array}
+ *        - error[0] : error magnitude in the negative direction
+ *        - error[1] : " " " " positive "
+ */
+module.exports = function makeComputeError(opts) {
+    var type = opts.type,
+        symmetric = opts.symmetric;
+
+    if(type === 'data') {
+        var array = opts.array,
+            arrayminus = opts.arrayminus;
+
+        if(symmetric || arrayminus === undefined) {
+            return function computeError(dataPt, index) {
+                var val = +(array[index]);
+                return [val, val];
+            };
+        }
+        else {
+            return function computeError(dataPt, index) {
+                return [+arrayminus[index], +array[index]];
+            };
+        }
+    }
+    else {
+        var computeErrorValue = makeComputeErrorValue(type, opts.value),
+            computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus);
+
+        if(symmetric || opts.valueminus === undefined) {
+            return function computeError(dataPt) {
+                var val = computeErrorValue(dataPt);
+                return [val, val];
+            };
+        }
+        else {
+            return function computeError(dataPt) {
+                return [
+                    computeErrorValueMinus(dataPt),
+                    computeErrorValue(dataPt)
+                ];
+            };
+        }
+    }
+};
+
+/**
+ * Compute error bar magnitude (for all types except data)
+ *
+ * @param {string} type error bar type
+ * @param {numeric} value error bar value
+ *
+ * @return {function} :
+ *      @param {numeric} dataPt
+ */
+function makeComputeErrorValue(type, value) {
+    if(type === 'percent') {
+        return function(dataPt) {
+            return Math.abs(dataPt * value / 100);
+        };
+    }
+    if(type === 'constant') {
+        return function() {
+            return Math.abs(value);
+        };
+    }
+    if(type === 'sqrt') {
+        return function(dataPt) {
+            return Math.sqrt(Math.abs(dataPt));
+        };
+    }
+}
+
+},{}],322:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Plots = require('../../plots/plots');
+var Lib = require('../../lib');
+
+var attributes = require('./attributes');
+
+
+module.exports = function(traceIn, traceOut, defaultColor, opts) {
+    var objName = 'error_' + opts.axis,
+        containerOut = traceOut[objName] = {},
+        containerIn = traceIn[objName] || {};
+
+    function coerce(attr, dflt) {
+        return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
+    }
+
+    var hasErrorBars = (
+        containerIn.array !== undefined ||
+        containerIn.value !== undefined ||
+        containerIn.type === 'sqrt'
+    );
+
+    var visible = coerce('visible', hasErrorBars);
+
+    if(visible === false) return;
+
+    var type = coerce('type', 'array' in containerIn ? 'data' : 'percent'),
+        symmetric = true;
+
+    if(type !== 'sqrt') {
+        symmetric = coerce('symmetric',
+            !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn));
+    }
+
+    if(type === 'data') {
+        var array = coerce('array');
+        if(!array) containerOut.array = [];
+        coerce('traceref');
+        if(!symmetric) {
+            var arrayminus = coerce('arrayminus');
+            if(!arrayminus) containerOut.arrayminus = [];
+            coerce('tracerefminus');
+        }
+    }
+    else if(type==='percent' || type==='constant') {
+        coerce('value');
+        if(!symmetric) coerce('valueminus');
+    }
+
+    var copyAttr = 'copy_'+opts.inherit+'style';
+    if(opts.inherit) {
+        var inheritObj = traceOut['error_' + opts.inherit];
+        if((inheritObj||{}).visible) {
+            coerce(copyAttr, !(containerIn.color ||
+                               isNumeric(containerIn.thickness) ||
+                               isNumeric(containerIn.width)));
+        }
+    }
+    if(!opts.inherit || !containerOut[copyAttr]) {
+        coerce('color', defaultColor);
+        coerce('thickness');
+        coerce('width', Plots.traceIs(traceOut, 'gl3d') ? 0 : 4);
+    }
+};
+
+},{"../../lib":349,"../../plots/plots":413,"./attributes":319,"fast-isnumeric":74}],323:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+var Color = require('../color');
+var subTypes = require('../../traces/scatter/subtypes');
+
+
+var errorBars = module.exports = {};
+
+errorBars.attributes = require('./attributes');
+
+errorBars.supplyDefaults = require('./defaults');
+
+errorBars.calc = require('./calc');
+
+errorBars.calcFromTrace = function(trace, layout) {
+    var x = trace.x || [],
+        y = trace.y,
+        len = x.length || y.length;
+
+    var calcdataMock = new Array(len);
+
+    for(var i = 0; i < len; i++) {
+        calcdataMock[i] = {
+            x: x[i],
+            y: y[i]
+        };
+    }
+
+    calcdataMock[0].trace = trace;
+
+    errorBars.calc({
+        calcdata: [calcdataMock],
+        _fullLayout: layout
+    });
+
+    return calcdataMock;
+};
+
+// the main drawing function for errorbars
+errorBars.plot = function(gd, plotinfo, cd) {
+    //  ___   <-- "errorhats"
+    //   |
+    //   |    <-- "errorbars"
+    //   |
+    //  ___   <-- "errorshoes"
+
+    var xa = plotinfo.x(),
+        ya = plotinfo.y();
+
+    // first remove all existing errorbars
+    // TODO: use enter/exit instead
+    plotinfo.plot.select('.errorlayer').selectAll('g.errorbars').remove();
+    var coords;
+
+    // draw the errorbars
+    plotinfo.plot.select('.errorlayer').selectAll('g.errorbars')
+        .data(cd)
+      .enter().append('g')
+        .attr('class','errorbars')
+        .each(function(d) {
+            var trace = d[0].trace,
+                xObj = trace.error_x,
+                yObj = trace.error_y,
+                sparse = subTypes.hasMarkers(trace) &&
+                    trace.marker.maxdisplayed>0;
+
+            if(!yObj.visible && !xObj.visible) return;
+
+            d3.select(this).selectAll('g')
+                .data(Lib.identity)
+              .enter().append('g')
+                .each(function(d) {
+                    coords = errorcoords(d, xa, ya);
+                    var eb = d3.select(this),
+                        path;
+                    if(sparse && !d.vis) return;
+
+                    if(yObj.visible && isNumeric(coords.x) &&
+                            isNumeric(coords.yh) &&
+                            isNumeric(coords.ys)) {
+                        var yw = yObj.width;
+                        path = 'M'+(coords.x-yw)+','+coords.yh+'h'+(2*yw) + // hat
+                            'm-'+yw+',0V'+coords.ys; // bar
+                        if(!coords.noYS) path += 'm-'+yw+',0h'+(2*yw); // shoe
+
+                        eb.append('path')
+                            .classed('yerror', true)
+                            .attr('d', path);
+                    }
+                    if(xObj.visible && isNumeric(coords.y) &&
+                            isNumeric(coords.xh) &&
+                            isNumeric(coords.xs)) {
+                        var xw = (xObj.copy_ystyle ? yObj : xObj).width;
+                        path = 'M'+coords.xh+','+(coords.y-xw)+'v'+(2*xw) + // hat
+                            'm0,-'+xw+'H'+coords.xs; // bar
+                        if(!coords.noXS) path += 'm0,-'+xw+'v'+(2*xw); // shoe
+
+                        eb.append('path')
+                            .classed('xerror', true)
+                            .attr('d', path);
+                    }
+                });
+        });
+};
+
+errorBars.style = function(gd) {
+    d3.select(gd).selectAll('g.errorbars').each(function(d) {
+        var eb = d3.select(this),
+            trace = d[0].trace,
+            yObj = trace.error_y||{},
+            xObj = trace.error_x||{};
+
+        eb.selectAll('g path.yerror')
+            .style('stroke-width', yObj.thickness+'px')
+            .call(Color.stroke, yObj.color);
+
+        if(xObj.copy_ystyle) xObj = yObj;
+
+        eb.selectAll('g path.xerror')
+            .style('stroke-width', xObj.thickness+'px')
+            .call(Color.stroke, xObj.color);
+    });
+};
+
+function errorcoords(d, xa, ya) {
+    // compute the coordinates of the error-bar objects
+    var out = {
+        x: xa.c2p(d.x),
+        y: ya.c2p(d.y)
+    };
+
+    // calculate the error bar size and hat and shoe locations
+    if(d.yh!==undefined) {
+        out.yh = ya.c2p(d.yh);
+        out.ys = ya.c2p(d.ys);
+
+        // if the shoes go off-scale (ie log scale, error bars past zero)
+        // clip the bar and hide the shoes
+        if(!isNumeric(out.ys)) {
+            out.noYS = true;
+            out.ys = ya.c2p(d.ys, true);
+        }
+    }
+    if(d.xh!==undefined) {
+        out.xh = xa.c2p(d.xh);
+        out.xs = xa.c2p(d.xs);
+
+        if(!isNumeric(out.xs)) {
+            out.noXS = true;
+            out.xs = xa.c2p(d.xs, true);
+        }
+    }
+
+    return out;
+}
+
+errorBars.hoverInfo = function(calcPoint, trace, hoverPoint) {
+    if(trace.error_y.visible) {
+        hoverPoint.yerr = calcPoint.yh - calcPoint.y;
+        if(!trace.error_y.symmetric) hoverPoint.yerrneg = calcPoint.y - calcPoint.ys;
+    }
+    if(trace.error_x.visible) {
+        hoverPoint.xerr = calcPoint.xh - calcPoint.x;
+        if(!trace.error_x.symmetric) hoverPoint.xerrneg = calcPoint.x - calcPoint.xs;
+    }
+};
+
+},{"../../lib":349,"../../traces/scatter/subtypes":520,"../color":299,"./attributes":319,"./calc":320,"./defaults":322,"d3":70,"fast-isnumeric":74}],324:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var fontAttrs = require('../../plots/font_attributes');
+var colorAttrs = require('../color/attributes');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+
+module.exports = {
+    bgcolor: {
+        valType: 'color',
+        
+        
+    },
+    bordercolor: {
+        valType: 'color',
+        dflt: colorAttrs.defaultLine,
+        
+        
+    },
+    borderwidth: {
+        valType: 'number',
+        min: 0,
+        dflt: 0,
+        
+        
+    },
+    font: extendFlat({}, fontAttrs, {
+        
+    }),
+    traceorder: {
+        valType: 'flaglist',
+        flags: ['reversed', 'grouped'],
+        extras: ['normal'],
+        
+        
+    },
+    tracegroupgap: {
+        valType: 'number',
+        min: 0,
+        dflt: 10,
+        
+        
+    },
+    x: {
+        valType: 'number',
+        min: -2,
+        max: 3,
+        dflt: 1.02,
+        
+        
+    },
+    xanchor: {
+        valType: 'enumerated',
+        values: ['auto', 'left', 'center', 'right'],
+        dflt: 'left',
+        
+        
+    },
+    y: {
+        valType: 'number',
+        min: -2,
+        max: 3,
+        dflt: 1,
+        
+        
+    },
+    yanchor: {
+        valType: 'enumerated',
+        values: ['auto', 'top', 'middle', 'bottom'],
+        dflt: 'auto',
+        
+        
+    }
+};
+
+},{"../../lib/extend":345,"../../plots/font_attributes":383,"../color/attributes":298}],325:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+module.exports = {
+    scrollBarWidth: 4,
+    scrollBarHeight: 20,
+    scrollBarColor: '#808BA4',
+    scrollBarMargin: 4
+};
+
+},{}],326:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../../plotly');
+var d3 = require('d3');
+
+var Lib = require('../../lib');
+
+var Plots = require('../../plots/plots');
+var Fx = require('../../plots/cartesian/graph_interact');
+
+var Color = require('../color');
+var Drawing = require('../drawing');
+
+var subTypes = require('../../traces/scatter/subtypes');
+var styleOne = require('../../traces/pie/style_one');
+
+var legend = module.exports = {};
+
+var constants = require('./constants');
+legend.layoutAttributes = require('./attributes');
+
+legend.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) {
+    var containerIn = layoutIn.legend || {},
+        containerOut = layoutOut.legend = {};
+
+    var visibleTraces = 0,
+        defaultOrder = 'normal',
+        trace;
+
+    for(var i = 0; i < fullData.length; i++) {
+        trace = fullData[i];
+
+        if(legendGetsTrace(trace)) {
+            visibleTraces++;
+            // always show the legend by default if there's a pie
+            if(Plots.traceIs(trace, 'pie')) visibleTraces++;
+        }
+
+        if((Plots.traceIs(trace, 'bar') && layoutOut.barmode==='stack') ||
+                ['tonextx','tonexty'].indexOf(trace.fill)!==-1) {
+            defaultOrder = isGrouped({traceorder: defaultOrder}) ?
+                'grouped+reversed' : 'reversed';
+        }
+
+        if(trace.legendgroup !== undefined && trace.legendgroup !== '') {
+            defaultOrder = isReversed({traceorder: defaultOrder}) ?
+                'reversed+grouped' : 'grouped';
+        }
+    }
+
+    function coerce(attr, dflt) {
+        return Lib.coerce(containerIn, containerOut,
+            legend.layoutAttributes, attr, dflt);
+    }
+
+    var showLegend = Lib.coerce(layoutIn, layoutOut,
+        Plots.layoutAttributes, 'showlegend', visibleTraces > 1);
+
+    if(showLegend === false) return;
+
+    coerce('bgcolor', layoutOut.paper_bgcolor);
+    coerce('bordercolor');
+    coerce('borderwidth');
+    Lib.coerceFont(coerce, 'font', layoutOut.font);
+
+    coerce('traceorder', defaultOrder);
+    if(isGrouped(layoutOut.legend)) coerce('tracegroupgap');
+
+    coerce('x');
+    coerce('xanchor');
+    coerce('y');
+    coerce('yanchor');
+    Lib.noneOrAll(containerIn, containerOut, ['x', 'y']);
+};
+
+// -----------------------------------------------------
+// styling functions for traces in legends.
+// same functions for styling traces in the popovers
+// -----------------------------------------------------
+
+legend.lines = function(d) {
+    var trace = d[0].trace,
+        showFill = trace.visible && trace.fill && trace.fill!=='none',
+        showLine = subTypes.hasLines(trace);
+
+    var fill = d3.select(this).select('.legendfill').selectAll('path')
+        .data(showFill ? [d] : []);
+    fill.enter().append('path').classed('js-fill',true);
+    fill.exit().remove();
+    fill.attr('d', 'M5,0h30v6h-30z')
+        .call(Drawing.fillGroupStyle);
+
+    var line = d3.select(this).select('.legendlines').selectAll('path')
+        .data(showLine ? [d] : []);
+    line.enter().append('path').classed('js-line',true)
+        .attr('d', 'M5,0h30');
+    line.exit().remove();
+    line.call(Drawing.lineGroupStyle);
+};
+
+legend.points = function(d) {
+    var d0 = d[0],
+        trace = d0.trace,
+        showMarkers = subTypes.hasMarkers(trace),
+        showText = subTypes.hasText(trace),
+        showLines = subTypes.hasLines(trace);
+
+    var dMod, tMod;
+
+    // 'scatter3d' and 'scattergeo' don't use gd.calcdata yet;
+    // use d0.trace to infer arrayOk attributes
+
+    function boundVal(attrIn, arrayToValFn, bounds) {
+        var valIn = Lib.nestedProperty(trace, attrIn).get(),
+            valToBound = (Array.isArray(valIn) && arrayToValFn) ?
+                arrayToValFn(valIn) : valIn;
+
+        if(bounds) {
+            if(valToBound < bounds[0]) return bounds[0];
+            else if(valToBound > bounds[1]) return bounds[1];
+        }
+        return valToBound;
+    }
+
+    function pickFirst(array) { return array[0]; }
+
+    // constrain text, markers, etc so they'll fit on the legend
+    if(showMarkers || showText || showLines) {
+        var dEdit = {},
+            tEdit = {};
+
+        if(showMarkers) {
+            dEdit.mc = boundVal('marker.color', pickFirst);
+            dEdit.mo = boundVal('marker.opacity', Lib.mean, [0.2, 1]);
+            dEdit.ms = boundVal('marker.size', Lib.mean, [2, 16]);
+            dEdit.mlc = boundVal('marker.line.color', pickFirst);
+            dEdit.mlw = boundVal('marker.line.width', Lib.mean, [0, 5]);
+            tEdit.marker = {
+                sizeref: 1,
+                sizemin: 1,
+                sizemode: 'diameter'
+            };
+        }
+
+        if(showLines) {
+            tEdit.line = {
+                width: boundVal('line.width', pickFirst, [0, 10])
+            };
+        }
+
+        if(showText) {
+            dEdit.tx = 'Aa';
+            dEdit.tp = boundVal('textposition', pickFirst);
+            dEdit.ts = 10;
+            dEdit.tc = boundVal('textfont.color', pickFirst);
+            dEdit.tf = boundVal('textfont.family', pickFirst);
+        }
+
+        dMod = [Lib.minExtend(d0, dEdit)];
+        tMod = Lib.minExtend(trace, tEdit);
+    }
+
+    var ptgroup = d3.select(this).select('g.legendpoints');
+
+    var pts = ptgroup.selectAll('path.scatterpts')
+        .data(showMarkers ? dMod : []);
+    pts.enter().append('path').classed('scatterpts', true)
+        .attr('transform', 'translate(20,0)');
+    pts.exit().remove();
+    pts.call(Drawing.pointStyle, tMod);
+
+    // 'mrc' is set in pointStyle and used in textPointStyle:
+    // constrain it here
+    if(showMarkers) dMod[0].mrc = 3;
+
+    var txt = ptgroup.selectAll('g.pointtext')
+        .data(showText ? dMod : []);
+    txt.enter()
+        .append('g').classed('pointtext',true)
+            .append('text').attr('transform', 'translate(20,0)');
+    txt.exit().remove();
+    txt.selectAll('text').call(Drawing.textPointStyle, tMod);
+
+};
+
+legend.bars = function(d) {
+    var trace = d[0].trace,
+        marker = trace.marker||{},
+        markerLine = marker.line||{},
+        barpath = d3.select(this).select('g.legendpoints')
+            .selectAll('path.legendbar')
+            .data(Plots.traceIs(trace, 'bar') ? [d] : []);
+    barpath.enter().append('path').classed('legendbar',true)
+        .attr('d','M6,6H-6V-6H6Z')
+        .attr('transform','translate(20,0)');
+    barpath.exit().remove();
+    barpath.each(function(d) {
+        var w = (d.mlw+1 || markerLine.width+1) - 1,
+            p = d3.select(this);
+        p.style('stroke-width',w+'px')
+            .call(Color.fill, d.mc || marker.color);
+        if(w) {
+            p.call(Color.stroke, d.mlc || markerLine.color);
+        }
+    });
+};
+
+legend.boxes = function(d) {
+    var trace = d[0].trace,
+        pts = d3.select(this).select('g.legendpoints')
+            .selectAll('path.legendbox')
+            .data(Plots.traceIs(trace, 'box') && trace.visible ? [d] : []);
+    pts.enter().append('path').classed('legendbox', true)
+        // if we want the median bar, prepend M6,0H-6
+        .attr('d', 'M6,6H-6V-6H6Z')
+        .attr('transform', 'translate(20,0)');
+    pts.exit().remove();
+    pts.each(function(d) {
+        var w = (d.lw+1 || trace.line.width+1) - 1,
+            p = d3.select(this);
+        p.style('stroke-width', w+'px')
+            .call(Color.fill, d.fc || trace.fillcolor);
+        if(w) {
+            p.call(Color.stroke, d.lc || trace.line.color);
+        }
+    });
+};
+
+legend.pie = function(d) {
+    var trace = d[0].trace,
+        pts = d3.select(this).select('g.legendpoints')
+            .selectAll('path.legendpie')
+            .data(Plots.traceIs(trace, 'pie') && trace.visible ? [d] : []);
+    pts.enter().append('path').classed('legendpie', true)
+        .attr('d', 'M6,6H-6V-6H6Z')
+        .attr('transform', 'translate(20,0)');
+    pts.exit().remove();
+
+    if(pts.size()) pts.call(styleOne, d[0], trace);
+};
+
+legend.style = function(s) {
+    s.each(function(d) {
+        var traceGroup = d3.select(this);
+
+        var fill = traceGroup
+            .selectAll('g.legendfill')
+                .data([d]);
+        fill.enter().append('g')
+            .classed('legendfill',true);
+
+        var line = traceGroup
+            .selectAll('g.legendlines')
+                .data([d]);
+        line.enter().append('g')
+            .classed('legendlines',true);
+
+        var symbol = traceGroup
+            .selectAll('g.legendsymbols')
+                .data([d]);
+        symbol.enter().append('g')
+            .classed('legendsymbols',true);
+        symbol.style('opacity', d[0].trace.opacity);
+
+        symbol.selectAll('g.legendpoints')
+            .data([d])
+          .enter().append('g')
+            .classed('legendpoints',true);
+    })
+    .each(legend.bars)
+    .each(legend.boxes)
+    .each(legend.pie)
+    .each(legend.lines)
+    .each(legend.points);
+};
+
+legend.texts = function(context, td, d, i, traces) {
+    var fullLayout = td._fullLayout,
+        trace = d[0].trace,
+        isPie = Plots.traceIs(trace, 'pie'),
+        traceIndex = trace.index,
+        name = isPie ? d[0].label : trace.name;
+
+    var text = d3.select(context).selectAll('text.legendtext')
+        .data([0]);
+    text.enter().append('text').classed('legendtext', true);
+    text.attr({
+        x: 40,
+        y: 0,
+        'data-unformatted': name
+    })
+    .style({
+        'text-anchor': 'start',
+        '-webkit-user-select': 'none',
+        '-moz-user-select': 'none',
+        '-ms-user-select': 'none',
+        'user-select': 'none'
+    })
+    .call(Drawing.font, fullLayout.legend.font)
+    .text(name);
+
+    function textLayout(s) {
+        Plotly.util.convertToTspans(s, function() {
+            if(td.firstRender) legend.repositionLegend(td, traces);
+        });
+        s.selectAll('tspan.line').attr({x: s.attr('x')});
+    }
+
+    if(td._context.editable && !isPie) {
+        text.call(Plotly.util.makeEditable)
+            .call(textLayout)
+            .on('edit', function(text) {
+                this.attr({'data-unformatted': text});
+                this.text(text)
+                    .call(textLayout);
+                if(!this.text()) text = ' \u0020\u0020 ';
+                Plotly.restyle(td, 'name', text, traceIndex);
+            });
+    }
+    else text.call(textLayout);
+};
+
+// -----------------------------------------------------
+// legend drawing
+// -----------------------------------------------------
+
+function legendGetsTrace(trace) {
+    return trace.visible && Plots.traceIs(trace, 'showLegend');
+}
+
+function isGrouped(legendLayout) {
+    return (legendLayout.traceorder || '').indexOf('grouped') !== -1;
+}
+
+function isReversed(legendLayout) {
+    return (legendLayout.traceorder || '').indexOf('reversed') !== -1;
+}
+
+legend.getLegendData = function(calcdata, opts) {
+
+    // build an { legendgroup: [cd0, cd0], ... } object
+    var lgroupToTraces = {},
+        lgroups = [],
+        hasOneNonBlankGroup = false,
+        slicesShown = {},
+        lgroupi = 0;
+
+    var cd, cd0, trace, lgroup, i, j, labelj;
+
+    function addOneItem(legendGroup, legendItem) {
+        // each '' legend group is treated as a separate group
+        if(legendGroup==='' || !isGrouped(opts)) {
+            var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups?
+            lgroups.push(uniqueGroup);
+            lgroupToTraces[uniqueGroup] = [[legendItem]];
+            lgroupi++;
+        }
+        else if(lgroups.indexOf(legendGroup) === -1) {
+            lgroups.push(legendGroup);
+            hasOneNonBlankGroup = true;
+            lgroupToTraces[legendGroup] = [[legendItem]];
+        }
+        else lgroupToTraces[legendGroup].push([legendItem]);
+    }
+
+    for(i = 0; i < calcdata.length; i++) {
+        cd = calcdata[i];
+        cd0 = cd[0];
+        trace = cd0.trace;
+        lgroup = trace.legendgroup;
+
+        if(!legendGetsTrace(trace) || !trace.showlegend) continue;
+
+        if(Plots.traceIs(trace, 'pie')) {
+            if(!slicesShown[lgroup]) slicesShown[lgroup] = {};
+            for(j = 0; j < cd.length; j++) {
+                labelj = cd[j].label;
+                if(!slicesShown[lgroup][labelj]) {
+                    addOneItem(lgroup, {
+                        label: labelj,
+                        color: cd[j].color,
+                        i: cd[j].i,
+                        trace: trace
+                    });
+
+                    slicesShown[lgroup][labelj] = true;
+                }
+            }
+        }
+
+        else addOneItem(lgroup, cd0);
+    }
+
+    // won't draw a legend in this case
+    if(!lgroups.length) return [];
+
+    // rearrange lgroupToTraces into a d3-friendly array of arrays
+    var lgroupsLength = lgroups.length,
+        ltraces,
+        legendData;
+
+    if(hasOneNonBlankGroup && isGrouped(opts)) {
+        legendData = new Array(lgroupsLength);
+        for(i = 0; i < lgroupsLength; i++) {
+            ltraces = lgroupToTraces[lgroups[i]];
+            legendData[i] = isReversed(opts) ? ltraces.reverse() : ltraces;
+        }
+    }
+    else {
+        // collapse all groups into one if all groups are blank
+        legendData = [new Array(lgroupsLength)];
+        for(i = 0; i < lgroupsLength; i++) {
+            ltraces = lgroupToTraces[lgroups[i]][0];
+            legendData[0][isReversed(opts) ? lgroupsLength-i-1 : i] = ltraces;
+        }
+        lgroupsLength = 1;
+    }
+
+    // needed in repositionLegend
+    opts._lgroupsLength = lgroupsLength;
+    return legendData;
+};
+
+legend.draw = function(td) {
+    var fullLayout = td._fullLayout;
+
+    if(!fullLayout._infolayer || !td.calcdata) return;
+
+    var opts = fullLayout.legend,
+        legendData = fullLayout.showlegend && legend.getLegendData(td.calcdata, opts),
+        hiddenSlices = fullLayout.hiddenlabels || [];
+
+    if(!fullLayout.showlegend || !legendData.length) {
+        fullLayout._infolayer.selectAll('.legend').remove();
+        Plots.autoMargin(td, 'legend');
+        return;
+    }
+
+    if(typeof td.firstRender === 'undefined') td.firstRender = true;
+    else if(td.firstRender) td.firstRender = false;
+
+    var legendsvg = fullLayout._infolayer.selectAll('svg.legend')
+        .data([0]);
+    legendsvg.enter().append('svg')
+        .attr({
+            'class': 'legend',
+            'pointer-events': 'all'
+        });
+
+    var bg = legendsvg.selectAll('rect.bg')
+        .data([0]);
+    bg.enter().append('rect')
+        .attr({
+            'class': 'bg',
+            'shape-rendering': 'crispEdges'
+        })
+        .call(Color.stroke, opts.bordercolor)
+        .call(Color.fill, opts.bgcolor)
+        .style('stroke-width', opts.borderwidth + 'px');
+
+    var scrollBox = legendsvg.selectAll('g.scrollbox')
+        .data([0]);
+    scrollBox.enter().append('g')
+        .attr('class', 'scrollbox');
+    scrollBox.exit().remove();
+
+    var scrollBar = legendsvg.selectAll('rect.scrollbar')
+        .data([0]);
+    scrollBar.enter().append('rect')
+        .attr({
+            'class': 'scrollbar',
+            'rx': 20,
+            'ry': 2,
+            'width': 0,
+            'height': 0
+        })
+        .call(Color.fill, '#808BA4');
+
+    var groups = scrollBox.selectAll('g.groups')
+        .data(legendData);
+    groups.enter().append('g')
+        .attr('class', 'groups');
+    groups.exit().remove();
+
+    if(isGrouped(opts)) {
+        groups.attr('transform', function(d, i) {
+            return 'translate(0,' + i * opts.tracegroupgap + ')';
+        });
+    }
+
+    var traces = groups.selectAll('g.traces')
+        .data(Lib.identity);
+
+    traces.enter().append('g').attr('class', 'traces');
+    traces.exit().remove();
+
+    traces.call(legend.style)
+        .style('opacity', function(d) {
+            var trace = d[0].trace;
+            if(Plots.traceIs(trace, 'pie')) {
+                return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1;
+            } else {
+                return trace.visible === 'legendonly' ? 0.5 : 1;
+            }
+        })
+        .each(function(d, i) {
+            legend.texts(this, td, d, i, traces);
+
+            var traceToggle = d3.select(this).selectAll('rect')
+                .data([0]);
+            traceToggle.enter().append('rect')
+                .classed('legendtoggle', true)
+                .style('cursor', 'pointer')
+                .attr('pointer-events', 'all')
+                .call(Color.fill, 'rgba(0,0,0,0)');
+            traceToggle.on('click', function() {
+                if(td._dragged) return;
+
+                var fullData = td._fullData,
+                    trace = d[0].trace,
+                    legendgroup = trace.legendgroup,
+                    traceIndicesInGroup = [],
+                    tracei,
+                    newVisible;
+
+                if(Plots.traceIs(trace, 'pie')) {
+                    var thisLabel = d[0].label,
+                        newHiddenSlices = hiddenSlices.slice(),
+                        thisLabelIndex = newHiddenSlices.indexOf(thisLabel);
+
+                    if(thisLabelIndex === -1) newHiddenSlices.push(thisLabel);
+                    else newHiddenSlices.splice(thisLabelIndex, 1);
+
+                    Plotly.relayout(td, 'hiddenlabels', newHiddenSlices);
+                } else {
+                    if(legendgroup === '') {
+                        traceIndicesInGroup = [trace.index];
+                    } else {
+                        for(var i = 0; i < fullData.length; i++) {
+                            tracei = fullData[i];
+                            if(tracei.legendgroup === legendgroup) {
+                                traceIndicesInGroup.push(tracei.index);
+                            }
+                        }
+                    }
+
+                    newVisible = trace.visible === true ? 'legendonly' : true;
+                    Plotly.restyle(td, 'visible', newVisible, traceIndicesInGroup);
+                }
+            });
+        });
+
+    // Position and size the legend
+    legend.repositionLegend(td, traces);
+
+    // Scroll section must be executed after repositionLegend.
+    // It requires the legend width, height, x and y to position the scrollbox
+    // and these values are mutated in repositionLegend.
+    var gs = fullLayout._size,
+        lx = gs.l + gs.w * opts.x,
+        ly = gs.t + gs.h * (1-opts.y);
+
+    if(opts.xanchor === 'right' || (opts.xanchor === 'auto' && opts.x >= 2 / 3)) {
+        lx -= opts.width;
+    }
+    else if(opts.xanchor === 'center' || (opts.xanchor === 'auto' && opts.x > 1 / 3)) {
+        lx -= opts.width / 2;
+    }
+
+    if(opts.yanchor === 'bottom' || (opts.yanchor === 'auto' && opts.y <= 1 / 3)) {
+        ly -= opts.height;
+    }
+    else if(opts.yanchor === 'middle' || (opts.yanchor === 'auto' && opts.y < 2 / 3)) {
+        ly -= opts.height / 2;
+    }
+
+    // Deal with scrolling
+    var plotHeight = fullLayout.height - fullLayout.margin.b,
+        scrollheight = Math.min(plotHeight - ly, opts.height),
+        scrollPosition = scrollBox.attr('data-scroll') ? scrollBox.attr('data-scroll') : 0;
+
+    scrollBox.attr('transform', 'translate(0, ' + scrollPosition + ')');
+    bg.attr({
+        width: opts.width - 2 * opts.borderwidth,
+        height: scrollheight - 2 * opts.borderwidth,
+        x: opts.borderwidth,
+        y: opts.borderwidth
+    });
+
+    legendsvg.call(Drawing.setRect, lx, ly, opts.width, scrollheight);
+
+    // If scrollbar should be shown.
+    if(td.firstRender && opts.height - scrollheight > 0 && !td._context.staticPlot) {
+
+        bg.attr({ width: opts.width - 2 * opts.borderwidth + constants.scrollBarWidth });
+
+        legendsvg.node().addEventListener('wheel', function(e) {
+            e.preventDefault();
+            scrollHandler(e.deltaY / 20);
+        });
+
+        scrollBar.node().addEventListener('mousedown', function(e) {
+            e.preventDefault();
+
+            function mMove(e) {
+                if(e.buttons === 1) {
+                    scrollHandler(e.movementY);
+                }
+            }
+
+            function mUp() {
+                scrollBar.node().removeEventListener('mousemove', mMove);
+                window.removeEventListener('mouseup', mUp);
+            }
+
+            window.addEventListener('mousemove', mMove);
+            window.addEventListener('mouseup', mUp);
+        });
+
+        // Move scrollbar to starting position on the first render
+        scrollBar.call(
+            Drawing.setRect,
+            opts.width - (constants.scrollBarWidth + constants.scrollBarMargin),
+            constants.scrollBarMargin,
+            constants.scrollBarWidth,
+            constants.scrollBarHeight
+        );
+    }
+
+    function scrollHandler(delta) {
+
+        var scrollBarTrack = scrollheight - constants.scrollBarHeight - 2 * constants.scrollBarMargin,
+            translateY = scrollBox.attr('data-scroll'),
+            scrollBoxY = Lib.constrain(translateY - delta, Math.min(scrollheight - opts.height, 0), 0),
+            scrollBarY = -scrollBoxY / (opts.height - scrollheight) * scrollBarTrack + constants.scrollBarMargin;
+
+        scrollBox.attr('data-scroll', scrollBoxY);
+        scrollBox.attr('transform', 'translate(0, ' + scrollBoxY + ')');
+        scrollBar.call(
+            Drawing.setRect,
+            opts.width - (constants.scrollBarWidth + constants.scrollBarMargin),
+            scrollBarY,
+            constants.scrollBarWidth,
+            constants.scrollBarHeight
+        );
+    }
+
+    if(td._context.editable) {
+        var xf,
+            yf,
+            x0,
+            y0,
+            lw,
+            lh;
+
+        Fx.dragElement({
+            element: legendsvg.node(),
+            prepFn: function() {
+                x0 = Number(legendsvg.attr('x'));
+                y0 = Number(legendsvg.attr('y'));
+                lw = Number(legendsvg.attr('width'));
+                lh = Number(legendsvg.attr('height'));
+                Fx.setCursor(legendsvg);
+            },
+            moveFn: function(dx, dy) {
+                var gs = td._fullLayout._size;
+
+                legendsvg.call(Drawing.setPosition, x0+dx, y0+dy);
+
+                xf = Fx.dragAlign(x0+dx, lw, gs.l, gs.l+gs.w,
+                    opts.xanchor);
+                yf = Fx.dragAlign(y0+dy+lh, -lh, gs.t+gs.h, gs.t,
+                    opts.yanchor);
+
+                var csr = Fx.dragCursors(xf, yf,
+                    opts.xanchor, opts.yanchor);
+                Fx.setCursor(legendsvg, csr);
+            },
+            doneFn: function(dragged) {
+                Fx.setCursor(legendsvg);
+                if(dragged && xf !== undefined && yf !== undefined) {
+                    Plotly.relayout(td, {'legend.x': xf, 'legend.y': yf});
+                }
+            }
+        });
+    }
+};
+
+legend.repositionLegend = function(td, traces) {
+    var fullLayout = td._fullLayout,
+        gs = fullLayout._size,
+        opts = fullLayout.legend,
+        borderwidth = opts.borderwidth;
+
+    opts.width = 0,
+    opts.height = 0,
+
+    traces.each(function(d) {
+        var trace = d[0].trace,
+            g = d3.select(this),
+            bg = g.selectAll('.legendtoggle'),
+            text = g.selectAll('.legendtext'),
+            tspans = g.selectAll('.legendtext>tspan'),
+            tHeight = opts.font.size * 1.3,
+            tLines = tspans[0].length || 1,
+            tWidth = text.node() && Drawing.bBox(text.node()).width,
+            mathjaxGroup = g.select('g[class*=math-group]'),
+            textY,
+            tHeightFull;
+
+        if(!trace.showlegend) {
+            g.remove();
+            return;
+        }
+
+        if(mathjaxGroup.node()) {
+            var mathjaxBB = Drawing.bBox(mathjaxGroup.node());
+            tHeight = mathjaxBB.height;
+            tWidth = mathjaxBB.width;
+            mathjaxGroup.attr('transform','translate(0,' + (tHeight / 4) + ')');
+        }
+        else {
+            // approximation to height offset to center the font
+            // to avoid getBoundingClientRect
+            textY = tHeight * (0.3 + (1-tLines) / 2);
+            text.attr('y',textY);
+            tspans.attr('y',textY);
+        }
+
+        tHeightFull = Math.max(tHeight*tLines, 16) + 3;
+
+        g.attr('transform',
+            'translate(' + borderwidth + ',' +
+                (5 + borderwidth + opts.height + tHeightFull / 2) +
+            ')'
+        );
+        bg.attr({x: 0, y: -tHeightFull / 2, height: tHeightFull});
+
+        opts.height += tHeightFull;
+        opts.width = Math.max(opts.width, tWidth || 0);
+    });
+
+
+    opts.width += 45 + borderwidth * 2;
+    opts.height += 10 + borderwidth * 2;
+
+    if(isGrouped(opts)) opts.height += (opts._lgroupsLength-1) * opts.tracegroupgap;
+
+    traces.selectAll('.legendtoggle')
+        .attr('width', (td._context.editable ? 0 : opts.width) + 40);
+
+    // now position the legend. for both x,y the positions are recorded as
+    // fractions of the plot area (left, bottom = 0,0). Outside the plot
+    // area is allowed but position will be clipped to the page.
+    // values <1/3 align the low side at that fraction, 1/3-2/3 align the
+    // center at that fraction, >2/3 align the right at that fraction
+
+    var lx = gs.l + gs.w * opts.x,
+        ly = gs.t + gs.h * (1-opts.y);
+
+    var xanchor = 'left';
+    if(opts.xanchor === 'right' || (opts.xanchor === 'auto' && opts.x >= 2 / 3)) {
+        lx -= opts.width;
+        xanchor = 'right';
+    }
+    else if(opts.xanchor === 'center' || (opts.xanchor === 'auto' && opts.x > 1 / 3)) {
+        lx -= opts.width / 2;
+        xanchor = 'center';
+    }
+
+    var yanchor = 'top';
+    if(opts.yanchor === 'bottom' || (opts.yanchor === 'auto' && opts.y <= 1 / 3)) {
+        ly -= opts.height;
+        yanchor = 'bottom';
+    }
+    else if(opts.yanchor === 'middle' || (opts.yanchor === 'auto' && opts.y < 2 / 3)) {
+        ly -= opts.height / 2;
+        yanchor = 'middle';
+    }
+
+    // make sure we're only getting full pixels
+    opts.width = Math.ceil(opts.width);
+    opts.height = Math.ceil(opts.height);
+    lx = Math.round(lx);
+    ly = Math.round(ly);
+
+    // lastly check if the margin auto-expand has changed
+    Plots.autoMargin(td,'legend',{
+        x: opts.x,
+        y: opts.y,
+        l: opts.width * ({right: 1, center: 0.5}[xanchor] || 0),
+        r: opts.width * ({left: 1, center: 0.5}[xanchor] || 0),
+        b: opts.height * ({top: 1, middle: 0.5}[yanchor] || 0),
+        t: opts.height * ({bottom: 1, middle: 0.5}[yanchor] || 0)
+    });
+};
+
+},{"../../lib":349,"../../plotly":366,"../../plots/cartesian/graph_interact":374,"../../plots/plots":413,"../../traces/pie/style_one":500,"../../traces/scatter/subtypes":520,"../color":299,"../drawing":317,"./attributes":324,"./constants":325,"d3":70}],327:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../../plotly');
+var Lib = require('../../lib');
+var Snapshot = require('../../snapshot');
+var Icons = require('../../../build/ploticon');
+
+
+var modeBarButtons = module.exports = {};
+
+/**
+ * ModeBar buttons configuration
+ *
+ * @param {string} name
+ *      name / id of the buttons (for tracking)
+ * @param {string} title
+ *      text that appears while hovering over the button,
+ *      enter null, false or '' for no hover text
+ * @param {string} icon
+ *      svg icon object associated with the button
+ *      can be linked to Plotly.Icons to use the default plotly icons
+ * @param {string} [gravity]
+ *      icon positioning
+ * @param {function} click
+ *      click handler associated with the button, a function of
+ *      'gd' (the main graph object) and
+ *      'ev' (the event object)
+ * @param {string} [attr]
+ *      attribute associated with button,
+ *      use this with 'val' to keep track of the state
+ * @param {*} [val]
+ *      initial 'attr' value, can be a function of gd
+ * @param {boolean} [toggle]
+ *      is the button a toggle button?
+ */
+
+modeBarButtons.toImage = {
+    name: 'toImage',
+    title: 'Download plot as a png',
+    icon: Icons.camera,
+    click: function(gd) {
+        var format = 'png';
+
+        if(Lib.isIE()) {
+            Lib.notifier('Snapshotting is unavailable in Internet Explorer. ' +
+                         'Consider exporting your images using the Plotly Cloud', 'long');
+            return;
+        }
+
+        if(gd._snapshotInProgress) {
+            Lib.notifier('Snapshotting is still in progress - please hold', 'long');
+            return;
+        }
+
+        gd._snapshotInProgress = true;
+        Lib.notifier('Taking snapshot - this may take a few seconds', 'long');
+
+        var ev = Snapshot.toImage(gd, {format: format});
+
+        var filename = gd.fn || 'newplot';
+        filename += '.' + format;
+
+        ev.once('success', function(result) {
+            gd._snapshotInProgress = false;
+
+            var downloadLink = document.createElement('a');
+            downloadLink.href = result;
+            downloadLink.download = filename; // only supported by FF and Chrome
+
+            document.body.appendChild(downloadLink);
+            downloadLink.click();
+            document.body.removeChild(downloadLink);
+
+            ev.clean();
+        });
+
+        ev.once('error', function(err) {
+            gd._snapshotInProgress = false;
+
+            Lib.notifier('Sorry there was a problem downloading your ' + format, 'long');
+            console.error(err);
+
+            ev.clean();
+        });
+    }
+};
+
+modeBarButtons.sendDataToCloud = {
+    name: 'sendDataToCloud',
+    title: 'Save and edit plot in cloud',
+    icon: Icons.disk,
+    click: function(gd) {
+        Plotly.Plots.sendDataToCloud(gd);
+    }
+};
+
+modeBarButtons.zoom2d = {
+    name: 'zoom2d',
+    title: 'Zoom',
+    attr: 'dragmode',
+    val: 'zoom',
+    icon: Icons.zoombox,
+    click: handleCartesian
+};
+
+modeBarButtons.pan2d = {
+    name: 'pan2d',
+    title: 'Pan',
+    attr: 'dragmode',
+    val: 'pan',
+    icon: Icons.pan,
+    click: handleCartesian
+};
+
+modeBarButtons.select2d = {
+    name: 'select2d',
+    title: 'Box Select',
+    attr: 'dragmode',
+    val: 'select',
+    icon: Icons.selectbox,
+    click: handleCartesian
+};
+
+modeBarButtons.lasso2d = {
+    name: 'lasso2d',
+    title: 'Lasso Select',
+    attr: 'dragmode',
+    val: 'lasso',
+    icon: Icons.lasso,
+    click: handleCartesian
+};
+
+modeBarButtons.zoomIn2d = {
+    name: 'zoomIn2d',
+    title: 'Zoom in',
+    attr: 'zoom',
+    val: 'in',
+    icon: Icons.zoom_plus,
+    click: handleCartesian
+};
+
+modeBarButtons.zoomOut2d = {
+    name: 'zoomOut2d',
+    title: 'Zoom out',
+    attr: 'zoom',
+    val: 'out',
+    icon: Icons.zoom_minus,
+    click: handleCartesian
+};
+
+modeBarButtons.autoScale2d = {
+    name: 'autoScale2d',
+    title: 'Autoscale',
+    attr: 'zoom',
+    val: 'auto',
+    icon: Icons.autoscale,
+    click: handleCartesian
+};
+
+modeBarButtons.resetScale2d = {
+    name: 'resetScale2d',
+    title: 'Reset axes',
+    attr: 'zoom',
+    val: 'reset',
+    icon: Icons.home,
+    click: handleCartesian
+};
+
+modeBarButtons.hoverClosestCartesian = {
+    name: 'hoverClosestCartesian',
+    title: 'Show closest data on hover',
+    attr: 'hovermode',
+    val: 'closest',
+    icon: Icons.tooltip_basic,
+    gravity: 'ne',
+    click: handleCartesian
+};
+
+modeBarButtons.hoverCompareCartesian = {
+    name: 'hoverCompareCartesian',
+    title: 'Compare data on hover',
+    attr: 'hovermode',
+    val: function(gd) {
+        return gd._fullLayout._isHoriz ? 'y' : 'x';
+    },
+    icon: Icons.tooltip_compare,
+    gravity: 'ne',
+    click: handleCartesian
+};
+
+var DRAGCURSORS = {
+    pan: 'move',
+    zoom: 'crosshair',
+    select: 'crosshair',
+    lasso: 'crosshair'
+};
+
+function handleCartesian(gd, ev) {
+    var button = ev.currentTarget,
+        astr = button.getAttribute('data-attr'),
+        val = button.getAttribute('data-val') || true,
+        fullLayout = gd._fullLayout,
+        aobj = {};
+
+    if(astr === 'zoom') {
+        var mag = (val === 'in') ? 0.5 : 2,
+            r0 = (1 + mag) / 2,
+            r1 = (1 - mag) / 2,
+            axList = Plotly.Axes.list(gd, null, true);
+
+        var ax, axName, initialRange;
+
+        for(var i = 0; i < axList.length; i++) {
+            ax = axList[i];
+            if(!ax.fixedrange) {
+                axName = ax._name;
+                if(val === 'auto') aobj[axName + '.autorange'] = true;
+                else if(val === 'reset') {
+                    if(ax._rangeInitial === undefined) {
+                        aobj[axName + '.autorange'] = true;
+                    }
+                    else aobj[axName + '.range'] = ax._rangeInitial.slice();
+                }
+                else {
+                    initialRange = ax.range;
+                    aobj[axName + '.range'] = [
+                        r0 * initialRange[0] + r1 * initialRange[1],
+                        r0 * initialRange[1] + r1 * initialRange[0]
+                    ];
+                }
+            }
+        }
+    }
+    else {
+        // if ALL traces have orientation 'h', 'hovermode': 'x' otherwise: 'y'
+        if(astr==='hovermode' && (val==='x' || val==='y')) {
+            val = fullLayout._isHoriz ? 'y' : 'x';
+            button.setAttribute('data-val', val);
+        }
+
+        aobj[astr] = val;
+    }
+
+    Plotly.relayout(gd, aobj).then(function() {
+        if(astr === 'dragmode') {
+            if(fullLayout._hasCartesian) {
+                Plotly.Fx.setCursor(
+                    fullLayout._paper.select('.nsewdrag'),
+                    DRAGCURSORS[val]
+                );
+            }
+            Plotly.Fx.supplyLayoutDefaults(gd.layout, fullLayout, gd._fullData);
+            Plotly.Fx.init(gd);
+        }
+    });
+}
+
+modeBarButtons.zoom3d = {
+    name: 'zoom3d',
+    title: 'Zoom',
+    attr: 'scene.dragmode',
+    val: 'zoom',
+    icon: Icons.zoombox,
+    click: handleDrag3d
+};
+
+modeBarButtons.pan3d = {
+    name: 'pan3d',
+    title: 'Pan',
+    attr: 'scene.dragmode',
+    val: 'pan',
+    icon: Icons.pan,
+    click: handleDrag3d
+};
+
+modeBarButtons.orbitRotation = {
+    name: 'orbitRotation',
+    title: 'orbital rotation',
+    attr: 'scene.dragmode',
+    val: 'orbit',
+    icon: Icons['3d_rotate'],
+    click: handleDrag3d
+};
+
+modeBarButtons.tableRotation = {
+    name: 'tableRotation',
+    title: 'turntable rotation',
+    attr: 'scene.dragmode',
+    val: 'turntable',
+    icon: Icons['z-axis'],
+    click: handleDrag3d
+};
+
+function handleDrag3d(gd, ev) {
+    var button = ev.currentTarget,
+        attr = button.getAttribute('data-attr'),
+        val = button.getAttribute('data-val') || true,
+        fullLayout = gd._fullLayout,
+        sceneIds = Plotly.Plots.getSubplotIds(fullLayout, 'gl3d'),
+        layoutUpdate = {};
+
+    var parts = attr.split('.');
+
+    for(var i = 0; i < sceneIds.length; i++) {
+        layoutUpdate[sceneIds[i] + '.' + parts[1]] = val;
+    }
+
+    Plotly.relayout(gd, layoutUpdate);
+}
+
+modeBarButtons.resetCameraDefault3d = {
+    name: 'resetCameraDefault3d',
+    title: 'Reset camera to default',
+    attr: 'resetDefault',
+    icon: Icons.home,
+    click: handleCamera3d
+};
+
+modeBarButtons.resetCameraLastSave3d = {
+    name: 'resetCameraLastSave3d',
+    title: 'Reset camera to last save',
+    attr: 'resetLastSave',
+    icon: Icons.movie,
+    click: handleCamera3d
+};
+
+function handleCamera3d(gd, ev) {
+    var button = ev.currentTarget,
+        attr = button.getAttribute('data-attr'),
+        fullLayout = gd._fullLayout,
+        sceneIds = Plotly.Plots.getSubplotIds(fullLayout, 'gl3d');
+
+    for(var i = 0; i < sceneIds.length; i++) {
+        var sceneId = sceneIds[i],
+            fullSceneLayout = fullLayout[sceneId],
+            scene = fullSceneLayout._scene;
+
+        if(attr === 'resetDefault') scene.setCameraToDefault();
+        else if(attr === 'resetLastSave') {
+            scene.setCamera(fullSceneLayout.camera);
+        }
+    }
+}
+
+modeBarButtons.hoverClosest3d = {
+    name: 'hoverClosest3d',
+    title: 'Toggle show closest data on hover',
+    attr: 'hovermode',
+    val: null,
+    toggle: true,
+    icon: Icons.tooltip_basic,
+    gravity: 'ne',
+    click: handleHover3d
+};
+
+function handleHover3d(gd, ev) {
+    var button = ev.currentTarget,
+        val = button._previousVal || false,
+        layout = gd.layout,
+        fullLayout = gd._fullLayout,
+        sceneIds = Plotly.Plots.getSubplotIds(fullLayout, 'gl3d');
+
+    var axes = ['xaxis', 'yaxis', 'zaxis'],
+        spikeAttrs = ['showspikes', 'spikesides', 'spikethickness', 'spikecolor'];
+
+    // initialize 'current spike' object to be stored in the DOM
+    var currentSpikes = {},
+        axisSpikes = {},
+        layoutUpdate = {};
+
+    if(val) {
+        layoutUpdate = Lib.extendDeep(layout, val);
+        button._previousVal = null;
+    }
+    else {
+        layoutUpdate = {
+            'allaxes.showspikes': false
+        };
+
+        for(var i = 0; i < sceneIds.length; i++) {
+            var sceneId = sceneIds[i],
+                sceneLayout = fullLayout[sceneId],
+                sceneSpikes = currentSpikes[sceneId] = {};
+
+            sceneSpikes.hovermode = sceneLayout.hovermode;
+            layoutUpdate[sceneId + '.hovermode'] = false;
+
+            // copy all the current spike attrs
+            for(var j = 0; j < 3; j++) {
+                var axis = axes[j];
+                axisSpikes = sceneSpikes[axis] = {};
+
+                for(var k = 0; k < spikeAttrs.length; k++) {
+                    var spikeAttr = spikeAttrs[k];
+                    axisSpikes[spikeAttr] = sceneLayout[axis][spikeAttr];
+                }
+            }
+        }
+
+        button._previousVal = Lib.extendDeep({}, currentSpikes);
+    }
+
+    Plotly.relayout(gd, layoutUpdate);
+}
+
+modeBarButtons.zoomInGeo = {
+    name: 'zoomInGeo',
+    title: 'Zoom in',
+    attr: 'zoom',
+    val: 'in',
+    icon: Icons.zoom_plus,
+    click: handleGeo
+};
+
+modeBarButtons.zoomOutGeo = {
+    name: 'zoomOutGeo',
+    title: 'Zoom out',
+    attr: 'zoom',
+    val: 'out',
+    icon: Icons.zoom_minus,
+    click: handleGeo
+};
+
+modeBarButtons.resetGeo = {
+    name: 'resetGeo',
+    title: 'Reset',
+    attr: 'reset',
+    val: null,
+    icon: Icons.autoscale,
+    click: handleGeo
+};
+
+modeBarButtons.hoverClosestGeo = {
+    name: 'hoverClosestGeo',
+    title: 'Toggle show closest data on hover',
+    attr: 'hovermode',
+    val: null,
+    toggle: true,
+    icon: Icons.tooltip_basic,
+    gravity: 'ne',
+    click: toggleHover
+};
+
+function handleGeo(gd, ev) {
+    var button = ev.currentTarget,
+        attr = button.getAttribute('data-attr'),
+        val = button.getAttribute('data-val') || true,
+        fullLayout = gd._fullLayout,
+        geoIds = Plotly.Plots.getSubplotIds(fullLayout, 'geo');
+
+    for(var i = 0; i < geoIds.length; i++) {
+        var geo = fullLayout[geoIds[i]]._geo;
+
+        if(attr === 'zoom') {
+            var scale = geo.projection.scale();
+            var newScale = (val === 'in') ? 2 * scale : 0.5 * scale;
+            geo.projection.scale(newScale);
+            geo.zoom.scale(newScale);
+            geo.render();
+        }
+        else if(attr === 'reset') geo.zoomReset();
+    }
+}
+
+modeBarButtons.hoverClosestGl2d = {
+    name: 'hoverClosestGl2d',
+    title: 'Toggle show closest data on hover',
+    attr: 'hovermode',
+    val: null,
+    toggle: true,
+    icon: Icons.tooltip_basic,
+    gravity: 'ne',
+    click: toggleHover
+};
+
+modeBarButtons.hoverClosestPie = {
+    name: 'hoverClosestPie',
+    title: 'Toggle show closest data on hover',
+    attr: 'hovermode',
+    val: 'closest',
+    icon: Icons.tooltip_basic,
+    gravity: 'ne',
+    click: toggleHover
+};
+
+function toggleHover(gd) {
+    var fullLayout = gd._fullLayout;
+
+    var onHoverVal;
+    if(fullLayout._hasCartesian) {
+        onHoverVal = fullLayout._isHoriz ? 'y' : 'x';
+    }
+    else onHoverVal = 'closest';
+
+    var newHover = gd._fullLayout.hovermode ? false : onHoverVal;
+
+    Plotly.relayout(gd, 'hovermode', newHover);
+}
+
+// buttons when more then one plot types are present
+
+modeBarButtons.toggleHover = {
+    name: 'toggleHover',
+    title: 'Toggle show closest data on hover',
+    attr: 'hovermode',
+    val: null,
+    toggle: true,
+    icon: Icons.tooltip_basic,
+    gravity: 'ne',
+    click: function(gd, ev) {
+        toggleHover(gd);
+
+        // the 3d hovermode update must come
+        // last so that layout.hovermode update does not
+        // override scene?.hovermode?.layout.
+        handleHover3d(gd, ev);
+    }
+};
+
+modeBarButtons.resetViews = {
+    name: 'resetViews',
+    title: 'Reset views',
+    icon: Icons.home,
+    click: function(gd, ev) {
+        var button = ev.currentTarget;
+
+        button.setAttribute('data-attr', 'zoom');
+        button.setAttribute('data-val', 'reset');
+        handleCartesian(gd, ev);
+
+        button.setAttribute('data-attr', 'resetLastSave');
+        handleCamera3d(gd, ev);
+
+        // N.B handleCamera3d also triggers a replot for
+        // geo subplots.
+    }
+};
+
+},{"../../../build/ploticon":2,"../../lib":349,"../../plotly":366,"../../snapshot":420}],328:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var Lib = require('../../lib');
+var Icons = require('../../../build/ploticon');
+
+
+/**
+ * UI controller for interactive plots
+ * @Class
+ * @Param {object} opts
+ * @Param {object} opts.buttons    nested arrays of grouped buttons config objects
+ * @Param {object} opts.container  container div to append modeBar
+ * @Param {object} opts.graphInfo  primary plot object containing data and layout
+ */
+function ModeBar(opts) {
+    this.container = opts.container;
+    this.element = document.createElement('div');
+
+    this.update(opts.graphInfo, opts.buttons);
+
+    this.container.appendChild(this.element);
+}
+
+var proto = ModeBar.prototype;
+
+/**
+ * Update modeBar (buttons and logo)
+ *
+ * @param {object} graphInfo  primary plot object containing data and layout
+ * @param {array of arrays} buttons nested arrays of grouped buttons to initialize
+ *
+ */
+proto.update = function(graphInfo, buttons) {
+    this.graphInfo = graphInfo;
+
+    var context = this.graphInfo._context;
+
+    if(context.displayModeBar === 'hover') {
+        this.element.className = 'modebar modebar--hover';
+    }
+    else this.element.className = 'modebar';
+
+    // if buttons or logo have changed, redraw modebar interior
+    var needsNewButtons = !this.hasButtons(buttons),
+        needsNewLogo = (this.hasLogo !== context.displaylogo);
+
+    if(needsNewButtons || needsNewLogo) {
+        this.removeAllButtons();
+
+        this.updateButtons(buttons);
+
+        if(context.displaylogo) {
+            this.element.appendChild(this.getLogo());
+            this.hasLogo = true;
+        }
+    }
+
+    this.updateActiveButton();
+};
+
+proto.updateButtons = function(buttons) {
+    var _this = this;
+
+    this.buttons = buttons;
+    this.buttonElements = [];
+    this.buttonsNames = [];
+
+    this.buttons.forEach(function(buttonGroup) {
+        var group = _this.createGroup();
+
+        buttonGroup.forEach(function(buttonConfig) {
+            var buttonName = buttonConfig.name;
+            if(!buttonName) {
+                throw new Error('must provide button \'name\' in button config');
+            }
+            if(_this.buttonsNames.indexOf(buttonName) !== -1) {
+                throw new Error('button name \'' + buttonName + '\' is taken');
+            }
+            _this.buttonsNames.push(buttonName);
+
+            var button = _this.createButton(buttonConfig);
+            _this.buttonElements.push(button);
+            group.appendChild(button);
+        });
+
+        _this.element.appendChild(group);
+    });
+};
+
+/**
+ * Empty div for containing a group of buttons
+ * @Return {HTMLelement}
+ */
+proto.createGroup = function() {
+    var group = document.createElement('div');
+    group.className = 'modebar-group';
+
+    return group;
+};
+
+/**
+ * Create a new button div and set constant and configurable attributes
+ * @Param {object} config (see ./buttons.js for more info)
+ * @Return {HTMLelement}
+ */
+proto.createButton = function(config) {
+    var _this = this,
+        button = document.createElement('a');
+
+    button.setAttribute('rel', 'tooltip');
+    button.className = 'modebar-btn';
+
+    var title = config.title;
+    if(title === undefined) title = config.name;
+    if(title || title === 0) button.setAttribute('data-title', title);
+
+    if(config.attr !== undefined) button.setAttribute('data-attr', config.attr);
+
+    var val = config.val;
+    if(val !== undefined) {
+        if(typeof val === 'function') val = val(this.graphInfo);
+        button.setAttribute('data-val', val);
+    }
+
+    var click = config.click;
+    if(typeof click !== 'function') {
+        throw new Error('must provide button \'click\' function in button config');
+    }
+    else {
+        button.addEventListener('click', function(ev) {
+            config.click(_this.graphInfo, ev);
+
+            // only needed for 'hoverClosestGeo' which does not call relayout
+            _this.updateActiveButton(ev.currentTarget);
+        });
+    }
+
+    button.setAttribute('data-toggle', config.toggle || false);
+    if(config.toggle) button.classList.add('active');
+
+    button.appendChild(this.createIcon(config.icon || Icons.question));
+    button.setAttribute('data-gravity', config.gravity || 'n');
+
+    return button;
+};
+
+/**
+ * Add an icon to a button
+ * @Param {object} thisIcon
+ * @Param {number} thisIcon.width
+ * @Param {string} thisIcon.path
+ * @Return {HTMLelement}
+ */
+proto.createIcon = function(thisIcon) {
+    var iconHeight = thisIcon.ascent - thisIcon.descent,
+        svgNS = 'http://www.w3.org/2000/svg',
+        icon = document.createElementNS(svgNS, 'svg'),
+        path = document.createElementNS(svgNS, 'path');
+
+    icon.setAttribute('height', '1em');
+    icon.setAttribute('width', (thisIcon.width / iconHeight) + 'em');
+    icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' '));
+
+    path.setAttribute('d', thisIcon.path);
+    path.setAttribute('transform', 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')');
+    icon.appendChild(path);
+
+    return icon;
+};
+
+/**
+ * Updates active button with attribute specified in layout
+ * @Param {object} graphInfo plot object containing data and layout
+ * @Return {HTMLelement}
+ */
+proto.updateActiveButton = function(buttonClicked) {
+    var fullLayout = this.graphInfo._fullLayout,
+        dataAttrClicked = (buttonClicked !== undefined) ?
+            buttonClicked.getAttribute('data-attr') :
+            null;
+
+    this.buttonElements.forEach(function(button) {
+        var thisval = button.getAttribute('data-val') || true,
+            dataAttr = button.getAttribute('data-attr'),
+            isToggleButton = (button.getAttribute('data-toggle') === 'true'),
+            button3 = d3.select(button);
+
+        // Use 'data-toggle' and 'buttonClicked' to toggle buttons
+        // that have no one-to-one equivalent in fullLayout
+        if(isToggleButton) {
+            if(dataAttr === dataAttrClicked) {
+                button3.classed('active', !button3.classed('active'));
+            }
+        }
+        else {
+            var val = (dataAttr === null) ?
+                dataAttr :
+                Lib.nestedProperty(fullLayout, dataAttr).get();
+
+            button3.classed('active', val === thisval);
+        }
+
+    });
+};
+
+/**
+ * Check if modeBar is configured as button configuration argument
+ *
+ * @Param {object} buttons 2d array of grouped button config objects
+ * @Return {boolean}
+ */
+proto.hasButtons = function(buttons) {
+    var currentButtons = this.buttons;
+
+    if(!currentButtons) return false;
+
+    if(buttons.length !== currentButtons.length) return false;
+
+    for(var i = 0; i < buttons.length; ++i) {
+        if(buttons[i].length !== currentButtons[i].length) return false;
+        for(var j = 0; j < buttons[i].length; j++) {
+            if(buttons[i][j].name !== currentButtons[i][j].name) return false;
+        }
+    }
+
+    return true;
+};
+
+/**
+ * @return {HTMLDivElement} The logo image wrapped in a group
+ */
+proto.getLogo = function() {
+    var group = this.createGroup(),
+        a = document.createElement('a');
+
+    a.href = 'https://plot.ly/';
+    a.target = '_blank';
+    a.setAttribute('data-title', 'Produced with Plotly');
+    a.className = 'modebar-btn plotlyjsicon modebar-btn--logo';
+
+    a.appendChild(this.createIcon(Icons.plotlylogo));
+
+    group.appendChild(a);
+    return group;
+};
+
+proto.removeAllButtons = function() {
+    while(this.element.firstChild) {
+        this.element.removeChild(this.element.firstChild);
+    }
+
+    this.hasLogo = false;
+};
+
+proto.destroy = function() {
+    Lib.removeElement(this.container.querySelector('.modebar'));
+};
+
+function createModeBar(gd, buttons) {
+    var fullLayout = gd._fullLayout;
+
+    var modeBar = new ModeBar({
+        graphInfo: gd,
+        container: fullLayout._paperdiv.node(),
+        buttons: buttons
+    });
+
+    if(fullLayout._privateplot) {
+        d3.select(modeBar.element).append('span')
+            .classed('badge-private float--left', true)
+            .text('PRIVATE');
+    }
+
+    return modeBar;
+}
+
+module.exports = createModeBar;
+
+},{"../../../build/ploticon":2,"../../lib":349,"d3":70}],329:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../../plotly');
+var scatterSubTypes = require('../../traces/scatter/subtypes');
+
+var createModeBar = require('./');
+var modeBarButtons = require('./buttons');
+
+/**
+ * ModeBar wrapper around 'create' and 'update',
+ * chooses buttons to pass to ModeBar constructor based on
+ * plot type and plot config.
+ *
+ * @param {object} gd main plot object
+ *
+ */
+module.exports = function manageModeBar(gd) {
+    var fullLayout = gd._fullLayout,
+        context = gd._context,
+        modeBar = fullLayout._modeBar;
+
+    if(!context.displayModeBar) {
+        if(modeBar) {
+            modeBar.destroy();
+            delete fullLayout._modeBar;
+        }
+        return;
+    }
+
+    if(!Array.isArray(context.modeBarButtonsToRemove)) {
+        throw new Error([
+            '*modeBarButtonsToRemove* configuration options',
+            'must be an array.'
+        ].join(' '));
+    }
+
+    if(!Array.isArray(context.modeBarButtonsToAdd)) {
+        throw new Error([
+            '*modeBarButtonsToAdd* configuration options',
+            'must be an array.'
+        ].join(' '));
+    }
+
+    var customButtons = context.modeBarButtons;
+    var buttonGroups;
+
+    if(Array.isArray(customButtons) && customButtons.length) {
+        buttonGroups = fillCustomButton(customButtons);
+    }
+    else {
+        buttonGroups = getButtonGroups(
+            gd,
+            context.modeBarButtonsToRemove,
+            context.modeBarButtonsToAdd
+        );
+    }
+
+    if(modeBar) modeBar.update(gd, buttonGroups);
+    else fullLayout._modeBar = createModeBar(gd, buttonGroups);
+};
+
+// logic behind which buttons are displayed by default
+function getButtonGroups(gd, buttonsToRemove, buttonsToAdd) {
+    var fullLayout = gd._fullLayout,
+        fullData = gd._fullData;
+
+    var hasCartesian = fullLayout._hasCartesian,
+        hasGL3D = fullLayout._hasGL3D,
+        hasGeo = fullLayout._hasGeo,
+        hasPie = fullLayout._hasPie,
+        hasGL2D = fullLayout._hasGL2D;
+
+    var groups = [];
+
+    function addGroup(newGroup) {
+        var out = [];
+
+        for(var i = 0; i < newGroup.length; i++) {
+            var button = newGroup[i];
+            if(buttonsToRemove.indexOf(button) !== -1) continue;
+            out.push(modeBarButtons[button]);
+        }
+
+        groups.push(out);
+    }
+
+    // buttons common to all plot types
+    addGroup(['toImage', 'sendDataToCloud']);
+
+    // graphs with more than one plot types get 'union buttons'
+    // which reset the view or toggle hover labels across all subplots.
+    if((hasCartesian || hasGL2D || hasPie) + hasGeo + hasGL3D > 1) {
+        addGroup(['resetViews', 'toggleHover']);
+        return appendButtonsToGroups(groups, buttonsToAdd);
+    }
+
+    if(hasGL3D) {
+        addGroup(['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation']);
+        addGroup(['resetCameraDefault3d', 'resetCameraLastSave3d']);
+        addGroup(['hoverClosest3d']);
+    }
+
+    if(hasGeo) {
+        addGroup(['zoomInGeo', 'zoomOutGeo', 'resetGeo']);
+        addGroup(['hoverClosestGeo']);
+    }
+
+    var allAxesFixed = areAllAxesFixed(fullLayout),
+        dragModeGroup = [];
+
+    if((hasCartesian || hasGL2D) && !allAxesFixed) {
+        dragModeGroup = ['zoom2d', 'pan2d'];
+    }
+    if(hasCartesian && isSelectable(fullData)) {
+        dragModeGroup.push('select2d');
+        dragModeGroup.push('lasso2d');
+    }
+    if(dragModeGroup.length) addGroup(dragModeGroup);
+
+    if((hasCartesian || hasGL2D) && !allAxesFixed) {
+        addGroup(['zoomIn2d', 'zoomOut2d', 'autoScale2d', 'resetScale2d']);
+    }
+
+    if(hasCartesian && hasPie) {
+        addGroup(['toggleHover']);
+    }
+    else if(hasGL2D) {
+        addGroup(['hoverClosestGl2d']);
+    }
+    else if(hasCartesian) {
+        addGroup(['hoverClosestCartesian', 'hoverCompareCartesian']);
+    }
+    else if(hasPie) {
+        addGroup(['hoverClosestPie']);
+    }
+
+    return appendButtonsToGroups(groups, buttonsToAdd);
+}
+
+function areAllAxesFixed(fullLayout) {
+    var axList = Plotly.Axes.list({_fullLayout: fullLayout}, null, true);
+    var allFixed = true;
+
+    for(var i = 0; i < axList.length; i++) {
+        if(!axList[i].fixedrange) {
+            allFixed = false;
+            break;
+        }
+    }
+
+    return allFixed;
+}
+
+// look for traces that support selection
+// to be updated as we add more selectPoints handlers
+function isSelectable(fullData) {
+    var selectable = false;
+
+    for(var i = 0; i < fullData.length; i++) {
+        if(selectable) break;
+
+        var trace = fullData[i];
+
+        if(!trace._module || !trace._module.selectPoints) continue;
+
+        if(trace.type === 'scatter') {
+            if(scatterSubTypes.hasMarkers(trace) || scatterSubTypes.hasText(trace)) {
+                selectable = true;
+            }
+        }
+        // assume that in general if the trace module has selectPoints,
+        // then it's selectable. Scatter is an exception to this because it must
+        // have markers or text, not just be a scatter type.
+        else selectable = true;
+    }
+
+    return selectable;
+}
+
+function appendButtonsToGroups(groups, buttons) {
+    if(buttons.length) {
+        if(Array.isArray(buttons[0])) {
+            for(var i = 0; i < buttons.length; i++) {
+                groups.push(buttons[i]);
+            }
+        }
+        else groups.push(buttons);
+    }
+
+    return groups;
+}
+
+// fill in custom buttons referring to default mode bar buttons
+function fillCustomButton(customButtons) {
+    for(var i = 0; i < customButtons.length; i++) {
+        var buttonGroup = customButtons[i];
+
+        for(var j = 0; j < buttonGroup.length; j++) {
+            var button = buttonGroup[j];
+
+            if(typeof button === 'string') {
+                if(modeBarButtons[button] !== undefined) {
+                    customButtons[i][j] = modeBarButtons[button];
+                }
+                else {
+                    throw new Error([
+                        '*modeBarButtons* configuration options',
+                        'invalid button name'
+                    ].join(' '));
+                }
+            }
+        }
+    }
+
+    return customButtons;
+}
+
+},{"../../plotly":366,"../../traces/scatter/subtypes":520,"./":328,"./buttons":327}],330:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var annAttrs = require('../annotations/attributes');
+var scatterAttrs = require('../../traces/scatter/attributes');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+var scatterLineAttrs = scatterAttrs.line;
+
+module.exports = {
+    _isLinkedToArray: true,
+
+    type: {
+        valType: 'enumerated',
+        values: ['circle', 'rect', 'path', 'line'],
+        
+        
+    },
+
+    xref: extendFlat({}, annAttrs.xref, {
+        
+    }),
+    x0: {
+        valType: 'any',
+        
+        
+    },
+    x1: {
+        valType: 'any',
+        
+        
+    },
+
+    yref: extendFlat({}, annAttrs.yref, {
+        
+    }),
+    y0: {
+        valType: 'any',
+        
+        
+    },
+    y1: {
+        valType: 'any',
+        
+        
+    },
+
+    path: {
+        valType: 'string',
+        
+        
+    },
+
+    opacity: {
+        valType: 'number',
+        min: 0,
+        max: 1,
+        dflt: 1,
+        
+        
+    },
+    line: {
+        color: scatterLineAttrs.color,
+        width: scatterLineAttrs.width,
+        dash: scatterLineAttrs.dash,
+        
+    },
+    fillcolor: {
+        valType: 'color',
+        dflt: 'rgba(0,0,0,0)',
+        
+        
+    }
+};
+
+},{"../../lib/extend":345,"../../traces/scatter/attributes":502,"../annotations/attributes":296}],331:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../../plotly');
+var isNumeric = require('fast-isnumeric');
+
+var shapes = module.exports = {};
+
+shapes.layoutAttributes = require('./attributes');
+
+shapes.supplyLayoutDefaults = function(layoutIn, layoutOut) {
+    var containerIn = layoutIn.shapes || [],
+        containerOut = layoutOut.shapes = [];
+
+    for(var i = 0; i < containerIn.length; i++) {
+        containerOut.push(handleShapeDefaults(containerIn[i] || {}, layoutOut));
+    }
+};
+
+function handleShapeDefaults(shapeIn, fullLayout) {
+    var shapeOut = {};
+
+    function coerce(attr, dflt) {
+        return Plotly.Lib.coerce(shapeIn, shapeOut,
+                                 shapes.layoutAttributes,
+                                 attr, dflt);
+    }
+
+    coerce('opacity');
+    coerce('fillcolor');
+    coerce('line.color');
+    coerce('line.width');
+    coerce('line.dash');
+    var dfltType = shapeIn.path ? 'path' : 'rect',
+        shapeType = coerce('type', dfltType);
+
+    // positioning
+    var axLetters = ['x','y'];
+    for(var i = 0; i < 2; i++) {
+        var axLetter = axLetters[i],
+            tdMock = {_fullLayout: fullLayout};
+
+        // xref, yref
+        var axRef = Plotly.Axes.coerceRef(shapeIn, shapeOut, tdMock, axLetter);
+
+        if(shapeType !== 'path') {
+            var dflt0 = 0.25,
+                dflt1 = 0.75;
+            if(axRef !== 'paper') {
+                var ax = Plotly.Axes.getFromId(tdMock, axRef),
+                    convertFn = linearToData(ax);
+                dflt0 = convertFn(ax.range[0] + dflt0 * (ax.range[1] - ax.range[0]));
+                dflt1 = convertFn(ax.range[0] + dflt1 * (ax.range[1] - ax.range[0]));
+            }
+            // x0, x1 (and y0, y1)
+            coerce(axLetter + '0', dflt0);
+            coerce(axLetter + '1', dflt1);
+        }
+    }
+
+    if(shapeType === 'path') {
+        coerce('path');
+    } else {
+        Plotly.Lib.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']);
+    }
+
+    return shapeOut;
+}
+
+// special position conversion functions... category axis positions can't be
+// specified by their data values, because they don't make a continuous mapping.
+// so these have to be specified in terms of the category serial numbers,
+// but can take fractional values. Other axis types we specify position based on
+// the actual data values.
+// TODO: this should really be part of axes, but for now it's only used here.
+// eventually annotations and axis ranges will use this too.
+// what should we do, invent a new letter for "data except if it's category"?
+function dataToLinear(ax) { return ax.type === 'category' ? ax.c2l : ax.d2l; }
+
+function linearToData(ax) { return ax.type === 'category' ? ax.l2c : ax.l2d; }
+
+shapes.drawAll = function(gd) {
+    var fullLayout = gd._fullLayout;
+    fullLayout._shapelayer.selectAll('path').remove();
+    for(var i = 0; i < fullLayout.shapes.length; i++) {
+        shapes.draw(gd, i);
+    }
+    // may need to resurrect this if we put text (LaTeX) in shapes
+    // return Plotly.Plots.previousPromises(gd);
+};
+
+shapes.add = function(gd) {
+    var nextShape = gd._fullLayout.shapes.length;
+    Plotly.relayout(gd, 'shapes['+nextShape+']', 'add');
+};
+
+// -----------------------------------------------------
+// make or edit an annotation on the graph
+// -----------------------------------------------------
+
+// shapes are stored in gd.layout.shapes, an array of objects
+// index can point to one item in this array,
+//  or non-numeric to simply add a new one
+//  or -1 to modify all existing
+// opt can be the full options object, or one key (to be set to value)
+//  or undefined to simply redraw
+// if opt is blank, val can be 'add' or a full options object to add a new
+//  annotation at that point in the array, or 'remove' to delete this one
+shapes.draw = function(gd, index, opt, value) {
+    var layout = gd.layout,
+        fullLayout = gd._fullLayout,
+        i;
+
+    // TODO: abstract out these drawAll, add, and remove blocks for shapes and annotations
+    if(!isNumeric(index) || index===-1) {
+        // no index provided - we're operating on ALL shapes
+        if(!index && Array.isArray(value)) {
+            // a whole annotation array is passed in
+            // (as in, redo of delete all)
+            layout.shapes = value;
+            shapes.supplyLayoutDefaults(layout, fullLayout);
+            shapes.drawAll(gd);
+            return;
+        }
+        else if(value==='remove') {
+            // delete all
+            delete layout.shapes;
+            fullLayout.shapes = [];
+            shapes.drawAll(gd);
+            return;
+        }
+        else if(opt && value!=='add') {
+            // make the same change to all shapes
+            for(i = 0; i < fullLayout.shapes.length; i++) {
+                shapes.draw(gd, i, opt, value);
+            }
+            return;
+        }
+        else {
+            // add a new empty annotation
+            index = fullLayout.shapes.length;
+            fullLayout.shapes.push({});
+        }
+    }
+
+    if(!opt && value) {
+        if(value==='remove') {
+            fullLayout._shapelayer.selectAll('[data-index="'+index+'"]')
+                .remove();
+            fullLayout.shapes.splice(index,1);
+            layout.shapes.splice(index,1);
+            for(i=index; i<fullLayout.shapes.length; i++) {
+                fullLayout._shapelayer
+                    .selectAll('[data-index="'+(i+1)+'"]')
+                    .attr('data-index',String(i));
+
+                // redraw all shapes past the removed one,
+                // so they bind to the right events
+                shapes.draw(gd,i);
+            }
+            return;
+        }
+        else if(value==='add' || Plotly.Lib.isPlainObject(value)) {
+            fullLayout.shapes.splice(index,0,{});
+
+            var rule = Plotly.Lib.isPlainObject(value) ?
+                    Plotly.Lib.extendFlat({}, value) :
+                    {text: 'New text'};
+
+            if(layout.shapes) {
+                layout.shapes.splice(index, 0, rule);
+            } else {
+                layout.shapes = [rule];
+            }
+
+            for(i=fullLayout.shapes.length-1; i>index; i--) {
+                fullLayout._shapelayer
+                    .selectAll('[data-index="'+(i-1)+'"]')
+                    .attr('data-index',String(i));
+                shapes.draw(gd,i);
+            }
+        }
+    }
+
+    // remove the existing shape if there is one
+    fullLayout._shapelayer.selectAll('[data-index="'+index+'"]').remove();
+
+    // remember a few things about what was already there,
+    var optionsIn = layout.shapes[index];
+
+    // (from annos...) not sure how we're getting here... but C12 is seeing a bug
+    // where we fail here when they add/remove annotations
+    // TODO: clean this up and remove it.
+    if(!optionsIn) return;
+
+    var oldRef = {xref: optionsIn.xref, yref: optionsIn.yref};
+
+    // alter the input shape as requested
+    var optionsEdit = {};
+    if(typeof opt === 'string' && opt) optionsEdit[opt] = value;
+    else if(Plotly.Lib.isPlainObject(opt)) optionsEdit = opt;
+
+    var optionKeys = Object.keys(optionsEdit);
+    for(i = 0; i < optionsEdit.length; i++) {
+        var k = optionKeys[i];
+        Plotly.Lib.nestedProperty(optionsIn, k).set(optionsEdit[k]);
+    }
+
+    var posAttrs = ['x0', 'x1', 'y0', 'y1'];
+    for(i = 0; i < 4; i++) {
+        var posAttr = posAttrs[i];
+        // if we don't have an explicit position already,
+        // don't set one just because we're changing references
+        // or axis type.
+        // the defaults will be consistent most of the time anyway,
+        // except in log/linear changes
+        if(optionsEdit[posAttr]!==undefined ||
+                optionsIn[posAttr]===undefined) {
+            continue;
+        }
+
+        var axLetter = posAttr.charAt(0),
+            axOld = Plotly.Axes.getFromId(gd,
+                Plotly.Axes.coerceRef(oldRef, {}, gd, axLetter)),
+            axNew = Plotly.Axes.getFromId(gd,
+                Plotly.Axes.coerceRef(optionsIn, {}, gd, axLetter)),
+            position = optionsIn[posAttr],
+            linearizedPosition;
+
+        if(optionsEdit[axLetter + 'ref']!==undefined) {
+            // first convert to fraction of the axis
+            if(axOld) {
+                linearizedPosition = dataToLinear(axOld)(position);
+                position = (linearizedPosition - axOld.range[0]) /
+                    (axOld.range[1] - axOld.range[0]);
+            } else {
+                position = (position - axNew.domain[0]) /
+                    (axNew.domain[1] - axNew.domain[0]);
+            }
+
+            if(axNew) {
+                // then convert to new data coordinates at the same fraction
+                linearizedPosition = axNew.range[0] + position *
+                    (axNew.range[1] - axNew.range[0]);
+                position = linearToData(axNew)(linearizedPosition);
+            } else {
+                // or scale to the whole plot
+                position = axOld.domain[0] +
+                    position * (axOld.domain[1] - axOld.domain[0]);
+            }
+        }
+
+        optionsIn[posAttr] = position;
+    }
+
+    var options = handleShapeDefaults(optionsIn, fullLayout);
+    fullLayout.shapes[index] = options;
+
+    var attrs = {
+            'data-index': String(index),
+            'fill-rule': 'evenodd',
+            d: shapePath(gd, options)
+        },
+        clipAxes = (options.xref + options.yref).replace(/paper/g, '');
+
+    var lineColor = options.line.width ? options.line.color : 'rgba(0,0,0,0)';
+
+    var path = fullLayout._shapelayer.append('path')
+        .attr(attrs)
+        .style('opacity', options.opacity)
+        .call(Plotly.Color.stroke, lineColor)
+        .call(Plotly.Color.fill, options.fillcolor)
+        .call(Plotly.Drawing.dashLine, options.line.dash, options.line.width);
+
+    if(clipAxes) path.call(Plotly.Drawing.setClipUrl, 'clip' + fullLayout._uid + clipAxes);
+};
+
+function decodeDate(convertToPx) {
+    return function(v) { return convertToPx(v.replace('_', ' ')); };
+}
+
+function shapePath(gd, options) {
+    var type = options.type,
+        xa = Plotly.Axes.getFromId(gd, options.xref),
+        ya = Plotly.Axes.getFromId(gd, options.yref),
+        gs = gd._fullLayout._size,
+        x2l,
+        x2p,
+        y2l,
+        y2p;
+
+    if(xa) {
+        x2l = dataToLinear(xa);
+        x2p = function(v) { return xa._offset + xa.l2p(x2l(v, true)); };
+    }
+    else {
+        x2p = function(v) { return gs.l + gs.w * v; };
+    }
+
+    if(ya) {
+        y2l = dataToLinear(ya);
+        y2p = function(v) { return ya._offset + ya.l2p(y2l(v, true)); };
+    }
+    else {
+        y2p = function(v) { return gs.t + gs.h * (1 - v); };
+    }
+
+    if(type==='path') {
+        if(xa && xa.type==='date') x2p = decodeDate(x2p);
+        if(ya && ya.type==='date') y2p = decodeDate(y2p);
+        return shapes.convertPath(options.path, x2p, y2p);
+    }
+
+    var x0 = x2p(options.x0),
+        x1 = x2p(options.x1),
+        y0 = y2p(options.y0),
+        y1 = y2p(options.y1);
+
+    if(type==='line') return 'M'+x0+','+y0+'L'+x1+','+y1;
+    if(type==='rect') return 'M'+x0+','+y0+'H'+x1+'V'+y1+'H'+x0+'Z';
+    // circle
+    var cx = (x0 + x1) / 2,
+        cy = (y0 + y1) / 2,
+        rx = Math.abs(cx - x0),
+        ry = Math.abs(cy - y0),
+        rArc = 'A' + rx + ',' + ry,
+        rightPt = (cx + rx) + ',' + cy,
+        topPt = cx + ',' + (cy - ry);
+    return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt +
+        rArc + ' 0 0,1 ' + rightPt + 'Z';
+}
+
+var segmentRE = /[MLHVQCTSZ][^MLHVQCTSZ]*/g,
+    paramRE = /[^\s,]+/g,
+
+    // which numbers in each path segment are x (or y) values
+    // drawn is which param is a drawn point, as opposed to a
+    // control point (which doesn't count toward autorange.
+    // TODO: this means curved paths could extend beyond the
+    // autorange bounds. This is a bit tricky to get right
+    // unless we revert to bounding boxes, but perhaps there's
+    // a calculation we could do...)
+    paramIsX = {
+        M: {0: true, drawn: 0},
+        L: {0: true, drawn: 0},
+        H: {0: true, drawn: 0},
+        V: {},
+        Q: {0: true, 2: true, drawn: 2},
+        C: {0: true, 2: true, 4: true, drawn: 4},
+        T: {0: true, drawn: 0},
+        S: {0: true, 2: true, drawn: 2},
+        // A: {0: true, 5: true},
+        Z: {}
+    },
+
+    paramIsY = {
+        M: {1: true, drawn: 1},
+        L: {1: true, drawn: 1},
+        H: {},
+        V: {0: true, drawn: 0},
+        Q: {1: true, 3: true, drawn: 3},
+        C: {1: true, 3: true, 5: true, drawn: 5},
+        T: {1: true, drawn: 1},
+        S: {1: true, 3: true, drawn: 5},
+        // A: {1: true, 6: true},
+        Z: {}
+    },
+    numParams = {
+        M: 2,
+        L: 2,
+        H: 1,
+        V: 1,
+        Q: 4,
+        C: 6,
+        T: 2,
+        S: 4,
+        // A: 7,
+        Z: 0
+    };
+
+shapes.convertPath = function(pathIn, x2p, y2p) {
+    // convert an SVG path string from data units to pixels
+    return pathIn.replace(segmentRE, function(segment) {
+        var paramNumber = 0,
+            segmentType = segment.charAt(0),
+            xParams = paramIsX[segmentType],
+            yParams = paramIsY[segmentType],
+            nParams = numParams[segmentType];
+
+        var paramString = segment.substr(1).replace(paramRE, function(param) {
+            if(xParams[paramNumber]) param = x2p(param);
+            else if(yParams[paramNumber]) param = y2p(param);
+            paramNumber++;
+
+            if(paramNumber > nParams) param = 'X';
+            return param;
+        });
+
+        if(paramNumber > nParams) {
+            paramString = paramString.replace(/[\s,]*X.*/, '');
+            console.log('ignoring extra params in segment ' + segment);
+        }
+
+        return segmentType + paramString;
+    });
+};
+
+shapes.calcAutorange = function(gd) {
+    var fullLayout = gd._fullLayout,
+        shapeList = fullLayout.shapes,
+        i,
+        shape,
+        ppad,
+        ax,
+        bounds;
+
+    if(!shapeList.length || !gd._fullData.length) return;
+
+    for(i = 0; i < shapeList.length; i++) {
+        shape = shapeList[i];
+        ppad = shape.line.width / 2;
+        if(shape.xref !== 'paper') {
+            ax = Plotly.Axes.getFromId(gd, shape.xref);
+            bounds = shapeBounds(ax, shape.x0, shape.x1, shape.path, paramIsX);
+            if(bounds) Plotly.Axes.expand(ax, bounds, {ppad: ppad});
+        }
+        if(shape.yref !== 'paper') {
+            ax = Plotly.Axes.getFromId(gd, shape.yref);
+            bounds = shapeBounds(ax, shape.y0, shape.y1, shape.path, paramIsY);
+            if(bounds) Plotly.Axes.expand(ax, bounds, {ppad: ppad});
+        }
+    }
+};
+
+function shapeBounds(ax, v0, v1, path, paramsToUse) {
+    var convertVal = (ax.type==='category') ? Number : ax.d2c;
+
+    if(v0 !== undefined) return [convertVal(v0), convertVal(v1)];
+    if(!path) return;
+
+    var min = Infinity,
+        max = -Infinity,
+        segments = path.match(segmentRE),
+        i,
+        segment,
+        drawnParam,
+        params,
+        val;
+
+    if(ax.type==='date') convertVal = decodeDate(convertVal);
+
+    for(i = 0; i < segments.length; i++) {
+        segment = segments[i];
+        drawnParam = paramsToUse[segment.charAt(0)].drawn;
+        if(drawnParam === undefined) continue;
+
+        params = segments[i].substr(1).match(paramRE);
+        if(!params || params.length < drawnParam) continue;
+
+        val = convertVal(params[drawnParam]);
+        if(val < min) min = val;
+        if(val > max) max = val;
+    }
+    if(max >= min) return [min, max];
+}
+
+},{"../../plotly":366,"./attributes":330,"fast-isnumeric":74}],332:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var isNumeric = require('fast-isnumeric');
+
+var Plotly = require('../../plotly');
+var Plots = require('../../plots/plots');
+var Lib = require('../../lib');
+var Drawing = require('../drawing');
+var Color = require('../color');
+var svgTextUtils = require('../../lib/svg_text_utils');
+var axisIds = require('../../plots/cartesian/axis_ids');
+
+
+var Titles = module.exports = {};
+
+/**
+ * Titles - (re)draw titles on the axes and plot:
+ *  title can be 'xtitle', 'ytitle', 'gtitle'
+ */
+Titles.draw = function(gd, title) {
+    var fullLayout = gd._fullLayout,
+        gs = fullLayout._size,
+        axletter = title.charAt(0),
+        colorbar = (title.substr(1, 2) === 'cb');
+
+    var cbnum, cont, options;
+
+    if(colorbar) {
+        var uid = title.substr(3).replace('title', '');
+        gd._fullData.some(function(trace, i) {
+            if(trace.uid === uid) {
+                cbnum = i;
+                cont = gd.calcdata[i][0].t.cb.axis;
+                return true;
+            }
+        });
+    }
+    else cont = fullLayout[axisIds.id2name(title.replace('title', ''))] || fullLayout;
+
+    var prop = (cont === fullLayout) ? 'title' : cont._name+'.title',
+        name = colorbar ? 'colorscale' :
+            ((cont._id || axletter).toUpperCase()+' axis'),
+        font = cont.titlefont.family,
+        fontSize = cont.titlefont.size,
+        fontColor = cont.titlefont.color,
+        x,
+        y,
+        transform = '',
+        xa,
+        ya,
+        avoid = {
+            selection: d3.select(gd).selectAll('g.'+cont._id+'tick'),
+            side: cont.side
+        },
+        // multiples of fontsize to offset label from axis
+        offsetBase = colorbar ? 0 : 1.5,
+        avoidTransform;
+
+    // find the transform applied to the parents of the avoid selection
+    // which doesn't get picked up by Drawing.bBox
+    if(colorbar) {
+        avoid.offsetLeft = gs.l;
+        avoid.offsetTop = gs.t;
+    }
+    else if(avoid.selection.size()) {
+        avoidTransform = d3.select(avoid.selection.node().parentNode)
+            .attr('transform')
+            .match(/translate\(([-\.\d]+),([-\.\d]+)\)/);
+        if(avoidTransform) {
+            avoid.offsetLeft = +avoidTransform[1];
+            avoid.offsetTop = +avoidTransform[2];
+        }
+    }
+
+    if(colorbar && cont.titleside) {
+        // argh, we only make it here if the title is on top or bottom,
+        // not right
+        x = gs.l + cont.titlex * gs.w;
+        y = gs.t + (1 - cont.titley) * gs.h + ((cont.titleside === 'top') ?
+                3 + fontSize * 0.75 : - 3 - fontSize * 0.25);
+        options = {x: x, y: y, 'text-anchor': 'start'};
+        avoid = {};
+
+        // convertToTspans rotates any 'y...' by 90 degrees...
+        // TODO: need a better solution than this hack
+        title = 'h' + title;
+    }
+    else if(axletter === 'x') {
+        xa = cont;
+        ya = (xa.anchor === 'free') ?
+            {_offset: gs.t + (1 - (xa.position || 0)) * gs.h, _length: 0} :
+            axisIds.getFromId(gd, xa.anchor);
+
+        x = xa._offset + xa._length / 2;
+        y = ya._offset + ((xa.side === 'top') ?
+            -10 - fontSize*(offsetBase + (xa.showticklabels ? 1 : 0)) :
+            ya._length + 10 +
+                fontSize*(offsetBase + (xa.showticklabels ? 1.5 : 0.5)));
+
+        options = {x: x, y: y, 'text-anchor': 'middle'};
+        if(!avoid.side) avoid.side = 'bottom';
+    }
+    else if(axletter === 'y') {
+        ya = cont;
+        xa = (ya.anchor === 'free') ?
+            {_offset: gs.l + (ya.position || 0) * gs.w, _length: 0} :
+            axisIds.getFromId(gd, ya.anchor);
+
+        y = ya._offset + ya._length / 2;
+        x = xa._offset + ((ya.side === 'right') ?
+            xa._length + 10 +
+                fontSize*(offsetBase + (ya.showticklabels ? 1 : 0.5)) :
+            -10 - fontSize*(offsetBase + (ya.showticklabels ? 0.5 : 0)));
+
+        options = {x: x, y: y, 'text-anchor': 'middle'};
+        transform = {rotate: '-90', offset: 0};
+        if(!avoid.side) avoid.side = 'left';
+    }
+    else {
+        // plot title
+        name = 'Plot';
+        fontSize = fullLayout.titlefont.size;
+        x = fullLayout.width / 2;
+        y = fullLayout._size.t / 2;
+        options = {x: x, y: y, 'text-anchor': 'middle'};
+        avoid = {};
+    }
+
+    var opacity = 1,
+        isplaceholder = false,
+        txt = cont.title.trim();
+    if(txt === '') opacity = 0;
+    if(txt.match(/Click to enter .+ title/)) {
+        opacity = 0.2;
+        isplaceholder = true;
+    }
+
+    var group;
+    if(colorbar) {
+        group = d3.select(gd)
+            .selectAll('.' + cont._id.substr(1) + ' .cbtitle');
+        // this class-to-rotate thing with convertToTspans is
+        // getting hackier and hackier... delete groups with the
+        // wrong class
+        var otherClass = title.charAt(0) === 'h' ?
+            title.substr(1) : ('h' + title);
+        group.selectAll('.' + otherClass + ',.' + otherClass + '-math-group')
+            .remove();
+    }
+    else {
+        group = fullLayout._infolayer.selectAll('.g-' + title)
+            .data([0]);
+        group.enter().append('g')
+            .classed('g-' + title, true);
+    }
+
+    var el = group.selectAll('text')
+        .data([0]);
+    el.enter().append('text');
+    el.text(txt)
+        // this is hacky, but convertToTspans uses the class
+        // to determine whether to rotate mathJax...
+        // so we need to clear out any old class and put the
+        // correct one (only relevant for colorbars, at least
+        // for now) - ie don't use .classed
+        .attr('class', title);
+
+    function titleLayout(titleEl) {
+        Lib.syncOrAsync([drawTitle,scootTitle], titleEl);
+    }
+
+    function drawTitle(titleEl) {
+        titleEl.attr('transform', transform ?
+            'rotate(' + [transform.rotate, options.x, options.y] +
+                ') translate(0, ' + transform.offset + ')' :
+            null);
+
+        titleEl.style({
+            'font-family': font,
+            'font-size': d3.round(fontSize,2) + 'px',
+            fill: Color.rgb(fontColor),
+            opacity: opacity * Color.opacity(fontColor),
+            'font-weight': Plots.fontWeight
+        })
+        .attr(options)
+        .call(svgTextUtils.convertToTspans)
+        .attr(options);
+
+        titleEl.selectAll('tspan.line')
+            .attr(options);
+        return Plots.previousPromises(gd);
+    }
+
+    function scootTitle(titleElIn) {
+        var titleGroup = d3.select(titleElIn.node().parentNode);
+
+        if(avoid && avoid.selection && avoid.side && txt) {
+            titleGroup.attr('transform', null);
+
+            // move toward avoid.side (= left, right, top, bottom) if needed
+            // can include pad (pixels, default 2)
+            var shift = 0,
+                backside = {
+                    left: 'right',
+                    right: 'left',
+                    top: 'bottom',
+                    bottom: 'top'
+                }[avoid.side],
+                shiftSign = (['left','top'].indexOf(avoid.side) !== -1) ?
+                    -1 : 1,
+                pad = isNumeric(avoid.pad) ? avoid.pad : 2,
+                titlebb = Drawing.bBox(titleGroup.node()),
+                paperbb = {
+                    left: 0,
+                    top: 0,
+                    right: fullLayout.width,
+                    bottom: fullLayout.height
+                },
+                maxshift = colorbar ? fullLayout.width:
+                    (paperbb[avoid.side]-titlebb[avoid.side]) *
+                    ((avoid.side === 'left' || avoid.side === 'top') ? -1 : 1);
+            // Prevent the title going off the paper
+            if(maxshift < 0) shift = maxshift;
+            else {
+                // so we don't have to offset each avoided element,
+                // give the title the opposite offset
+                titlebb.left -= avoid.offsetLeft;
+                titlebb.right -= avoid.offsetLeft;
+                titlebb.top -= avoid.offsetTop;
+                titlebb.bottom -= avoid.offsetTop;
+
+                // iterate over a set of elements (avoid.selection)
+                // to avoid collisions with
+                avoid.selection.each(function() {
+                    var avoidbb = Drawing.bBox(this);
+
+                    if(Lib.bBoxIntersect(titlebb, avoidbb, pad)) {
+                        shift = Math.max(shift, shiftSign * (
+                            avoidbb[avoid.side] - titlebb[backside]) + pad);
+                    }
+                });
+                shift = Math.min(maxshift, shift);
+            }
+            if(shift > 0 || maxshift < 0) {
+                var shiftTemplate = {
+                    left: [-shift, 0],
+                    right: [shift, 0],
+                    top: [0, -shift],
+                    bottom: [0, shift]
+                }[avoid.side];
+                titleGroup.attr('transform',
+                    'translate(' + shiftTemplate + ')');
+            }
+        }
+    }
+
+    el.attr({'data-unformatted': txt})
+        .call(titleLayout);
+
+    var placeholderText = 'Click to enter ' + name.replace(/\d+/, '') + ' title';
+
+    function setPlaceholder() {
+        opacity = 0;
+        isplaceholder = true;
+        txt = placeholderText;
+        fullLayout._infolayer.select('.' + title)
+            .attr({'data-unformatted': txt})
+            .text(txt)
+            .on('mouseover.opacity', function() {
+                d3.select(this).transition()
+                    .duration(100).style('opacity', 1);
+            })
+            .on('mouseout.opacity',function() {
+                d3.select(this).transition()
+                    .duration(1000).style('opacity', 0);
+            });
+    }
+
+    if(gd._context.editable) {
+        if(!txt) setPlaceholder();
+
+        el.call(svgTextUtils.makeEditable)
+            .on('edit', function(text) {
+                if(colorbar) {
+                    var trace = gd._fullData[cbnum];
+                    if(Plots.traceIs(trace, 'markerColorscale')) {
+                        Plotly.restyle(gd, 'marker.colorbar.title', text, cbnum);
+                    }
+                    else Plotly.restyle(gd, 'colorbar.title', text, cbnum);
+                }
+                else Plotly.relayout(gd,prop,text);
+            })
+            .on('cancel', function() {
+                this.text(this.attr('data-unformatted'))
+                    .call(titleLayout);
+            })
+            .on('input', function(d) {
+                this.text(d || ' ').attr(options)
+                    .selectAll('tspan.line')
+                        .attr(options);
+            });
+    }
+    else if(!txt || txt.match(/Click to enter .+ title/)) {
+        el.remove();
+    }
+    el.classed('js-placeholder', isplaceholder);
+};
+
+},{"../../lib":349,"../../lib/svg_text_utils":360,"../../plotly":366,"../../plots/cartesian/axis_ids":371,"../../plots/plots":413,"../color":299,"../drawing":317,"d3":70,"fast-isnumeric":74}],333:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+module.exports = {
+    DZA: 'algeria',
+    AGO: 'angola',
+    EGY: 'egypt',
+    BGD: 'bangladesh|^(?=.*east).*paki?stan',
+    NER: '\\bniger(?!ia)',
+    LIE: 'liechtenstein',
+    NAM: 'namibia',
+    BGR: 'bulgaria',
+    BOL: 'bolivia',
+    GHA: 'ghana|gold.?coast',
+    CCK: '\\bcocos|keeling',
+    PAK: '^(?!.*east).*paki?stan',
+    CPV: 'verde',
+    JOR: 'jordan',
+    LBR: 'liberia',
+    LBY: 'libya',
+    MYS: 'malaysia',
+    IOT: 'british.?indian.?ocean',
+    PRI: 'puerto.?rico',
+    MYT: 'mayotte',
+    PRK: '^(?=.*democrat).*\\bkorea|^(?=.*people).*\\bkorea|^(?=.*north).*\\bkorea|\\bd\\.?p\\.?r\\.?k',
+    PSE: 'palestin|\\bgaza|west.?bank',
+    TZA: 'tanzania',
+    BWA: 'botswana|bechuana',
+    KHM: 'cambodia|kampuchea|khmer|^p\\.?r\\.?k\\.?$',
+    UMI: 'minor.?outlying.?is',
+    TTO: 'trinidad|tobago',
+    PRY: 'paraguay',
+    HKG: 'hong.?kong',
+    SAU: '\\bsa\\w*.?arabia',
+    LBN: 'lebanon',
+    SVN: 'slovenia',
+    BFA: 'burkina|\\bfaso|upper.?volta',
+    SVK: '^(?!.*cze).*slovak',
+    MRT: 'mauritania',
+    HRV: 'croatia',
+    CHL: '\\bchile',
+    CHN: '^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai).*china|^p\\.?r\\.?c\\.?$',
+    KNA: 'kitts|\\bnevis',
+    JAM: 'jamaica',
+    SMR: 'san.?marino',
+    GIB: 'gibraltar',
+    DJI: 'djibouti',
+    GIN: '^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea',
+    FIN: 'finland',
+    URY: 'uruguay',
+    VAT: 'holy.?see|vatican|papal.?st',
+    STP: '\\bs(a|Ã£)o.?tom(e|Ã©)',
+    SYC: 'seychell',
+    NPL: 'nepal',
+    CXR: 'christmas',
+    LAO: '\\blaos?\\b',
+    YEM: '^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen',
+    BVT: 'bouvet',
+    ZAF: '\\bs\\w*.?africa',
+    KIR: 'kiribati',
+    PHL: 'philippines',
+    SXM: '^(?!.*martin)(?!.*saba).*maarten',
+    ROU: 'r(o|u|ou)mania',
+    VIR: '^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin',
+    SYR: 'syria',
+    MAC: 'maca(o|u)',
+    NFK: 'norfolk',
+    NIC: 'nicaragua',
+    MLT: '\\bmalta',
+    KAZ: 'kazak',
+    TCA: 'turks',
+    PYF: 'french.?polynesia|tahiti',
+    NIU: 'niue',
+    DMA: 'dominica(?!n)',
+    GBR: 'united.?kingdom|britain|^u\\.?k\\.?$',
+    BEN: 'benin|dahome',
+    GUF: '^(?=.*french).*guiana',
+    BEL: '^(?!.*luxem).*belgium',
+    MSR: 'montserrat',
+    TGO: 'togo',
+    DEU: '^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german',
+    GUM: '\\bguam',
+    LKA: 'sri.?lanka|ceylon',
+    SSD: '\\bs\\w*.?sudan',
+    FLK: 'falkland|malvinas',
+    PCN: 'pitcairn',
+    BES: '^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands',
+    GUY: 'guyana|british.?guiana',
+    CRI: 'costa.?rica',
+    COK: '\\bcook',
+    MAR: 'morocco|\\bmaroc',
+    MNP: 'mariana',
+    LSO: 'lesotho|basuto',
+    HUN: '^(?!.*austr).*hungary',
+    TKM: 'turkmen',
+    SUR: 'surinam|dutch.?guiana',
+    NLD: '^(?!.*\\bant)(?!.*\\bcarib).*netherlands',
+    BMU: 'bermuda',
+    HMD: 'heard.*mcdonald',
+    TCD: '\\bchad',
+    GEO: '^(?!.*south).*georgia',
+    MNE: '^(?!.*serbia).*montenegro',
+    MNG: 'mongolia',
+    MHL: 'marshall',
+    MTQ: 'martinique',
+    CSK: 'czechoslovakia',
+    BLZ: 'belize|^(?=.*british).*honduras',
+    DDR: 'german.?democratic.?republic|^(d|g)\\.?d\\.?r\\.?$|^(?=.*east).*germany',
+    MMR: 'myanmar|burma',
+    AFG: 'afghan',
+    BDI: 'burundi',
+    VGB: '^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin',
+    BLR: 'belarus|byelo',
+    BLM: 'barth(e|Ã©)lemy',
+    GRD: 'grenada',
+    TKL: 'tokelau',
+    GRC: 'greece|hellenic|hellas',
+    GRL: 'greenland',
+    SHN: 'helena',
+    AND: 'andorra',
+    MOZ: 'mozambique',
+    TJK: 'tajik',
+    THA: 'thailand|\\bsiam',
+    HTI: 'haiti',
+    MEX: '\\bmexic',
+    ANT: '^(?=.*\\bant).*(nether|dutch)',
+    ZWE: 'zimbabwe|^(?!.*northern).*rhodesia',
+    LCA: '\\blucia',
+    IND: 'india(?!.*ocea)',
+    LVA: 'latvia',
+    BTN: 'bhutan',
+    VCT: 'vincent',
+    VNM: '^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam',
+    NOR: 'norway',
+    CZE: '^(?=.*rep).*czech|czechia|bohemia',
+    ATF: 'french.?southern|\\bfr.*\\bso.*\\ban.*\\b\\bt',
+    ATG: 'antigua',
+    FJI: 'fiji',
+    HND: '^(?!.*brit).*honduras',
+    MUS: 'mauritius',
+    DOM: 'dominican',
+    LUX: '^(?!.*belg).*luxem',
+    ISR: 'israel',
+    YUG: 'yugoslavia',
+    FSM: 'micronesia',
+    PER: 'peru',
+    REU: 'r(e|Ã©)union',
+    IDN: 'indonesia',
+    VUT: 'vanuatu|new.?hebrides',
+    MKD: 'macedonia|^f\\.?y\\.?r\\.?o\\.?m\\.?$',
+    COD: '\\bdem.*congo|congo.*\\bdem|congo.*\\bdr|\\bdr.*congo|\\bd\\.?r\\.?c|\\bd\\.?r\\.?o\\.?c|\\br\\.?d\\.?c|belgian.?congo|congo.?free.?state|kinshasa|zaire|l\\w{1,2}opoldville',
+    COG: '^(?!.*\\bdem)(?!.*\\bdr)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l\\w{1,2}opoldville)(?!.*free).*\\bcongo',
+    ISL: 'iceland',
+    GLP: 'guadeloupe',
+    ETH: 'ethiopia|abyssinia',
+    COM: 'comoro',
+    COL: 'colombia',
+    NGA: 'nigeria',
+    TLS: '^(?=.*leste).*timor|^(?=.*east).*timor',
+    TWN: 'taiwan|taipei|formosa',
+    PRT: 'portugal',
+    MDA: 'moldov|b(a|e)ssarabia',
+    GGY: 'guernsey',
+    MDG: 'madagascar|malagasy',
+    ATA: 'antarctica',
+    ECU: 'ecuador',
+    SEN: 'senegal',
+    ESH: 'sahara',
+    MDV: 'maldive',
+    ASM: '^(?=.*americ).*samoa',
+    SPM: 'miquelon',
+    CUW: '^(?!.*bonaire).*\\bcura(c|Ã§)ao',
+    FRA: '^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul',
+    LTU: 'lithuania',
+    RWA: 'rwanda',
+    ZMB: 'zambia|northern.?rhodesia',
+    GMB: 'gambia',
+    WLF: 'futuna|wallis',
+    JEY: 'jersey',
+    FRO: 'faroe|faeroe',
+    GTM: 'guatemala',
+    DNK: 'denmark',
+    IMN: '^(?=.*isle).*\\bman',
+    MAF: '^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)',
+    AUS: 'australia',
+    AUT: '^(?!.*hungary).*austria|\\baust.*\\bemp',
+    SJM: 'svalbard',
+    VEN: 'venezuela',
+    PLW: 'palau',
+    KEN: 'kenya|british.?east.?africa|east.?africa.?prot',
+    TUR: 'turkey',
+    ALB: 'albania',
+    OMN: '\\boman|trucial',
+    TUV: 'tuvalu',
+    ALA: '\\b(a|Ã¥)land',
+    BRN: 'brunei',
+    TUN: 'tunisia',
+    RUS: '\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics',
+    BRB: 'barbados',
+    BRA: 'brazil',
+    CIV: 'ivoire|ivory',
+    SRB: '^(?!.*monte).*serbia',
+    GNQ: 'guine.*eq|eq.*guine|^(?=.*span).*guinea',
+    USA: '^(?!.*islands).*united.?states|^u\\.?s\\.?a\\.?$|^u\\.?s\\.?$',
+    QAT: 'qatar',
+    WSM: '^(?!.*amer).*samoa',
+    AZE: 'azerbaijan',
+    GNB: 'bissau|^(?=.*portu).*guinea',
+    SWZ: 'swaziland',
+    TON: 'tonga',
+    CAN: 'canada',
+    UKR: 'ukrain',
+    KOR: '^(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea|\\br\\.?o\\.?k\\b',
+    AIA: 'anguill?a',
+    CAF: '\\bcen.*\\baf|^c\\.?a\\.?r\\.?$',
+    CHE: 'switz|swiss',
+    CYP: 'cyprus',
+    BIH: 'herzegovina|bosnia',
+    SGP: 'singapore',
+    SGS: 'south.?georgia|sandwich',
+    SOM: 'somali',
+    UZB: 'uzbek',
+    CMR: 'cameroon',
+    POL: 'poland',
+    EAZ: 'zanz',
+    KWT: 'kuwait',
+    ERI: 'eritrea',
+    GAB: 'gabon',
+    CYM: 'cayman',
+    ARE: 'emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em',
+    EST: 'estonia',
+    MWI: 'malawi|nyasa',
+    ESP: 'spain',
+    IRQ: '\\biraq|mesopotamia',
+    SLV: 'el.?salvador',
+    MLI: '\\bmali\\b',
+    YMD: '^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen',
+    IRL: 'ireland',
+    IRN: '\\biran|persia',
+    ABW: '^(?!.*bonaire).*\\baruba',
+    SLE: 'sierra',
+    PAN: 'panama',
+    SDN: '^(?!.*\\bs(?!u)).*sudan',
+    SLB: 'solomon',
+    NZL: 'new.?zealand',
+    MCO: 'monaco',
+    ITA: 'italy',
+    JPN: 'japan',
+    KGZ: 'kyrgyz|kirghiz',
+    UGA: 'uganda',
+    NCL: 'new.?caledonia',
+    PNG: 'papua|\\bp.*\\bn.*\\bguin.*|^p\\.?n\\.?g\\.?$|new.?guinea',
+    ARG: 'argentin',
+    SWE: 'sweden',
+    BHS: 'bahamas',
+    BHR: 'bahrain',
+    ARM: 'armenia',
+    NRU: 'nauru',
+    CUB: '\\bcuba'
+};
+
+},{}],334:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var params = module.exports = {};
+
+// projection names to d3 function name
+params.projNames = {
+    // d3.geo.projection
+    'equirectangular': 'equirectangular',
+    'mercator': 'mercator',
+    'orthographic': 'orthographic',
+    'natural earth': 'naturalEarth',
+    'kavrayskiy7': 'kavrayskiy7',
+    'miller': 'miller',
+    'robinson': 'robinson',
+    'eckert4': 'eckert4',
+    'azimuthal equal area': 'azimuthalEqualArea',
+    'azimuthal equidistant': 'azimuthalEquidistant',
+    'conic equal area': 'conicEqualArea',
+    'conic conformal': 'conicConformal',
+    'conic equidistant': 'conicEquidistant',
+    'gnomonic': 'gnomonic',
+    'stereographic': 'stereographic',
+    'mollweide': 'mollweide',
+    'hammer': 'hammer',
+    'transverse mercator': 'transverseMercator',
+    'albers usa': 'albersUsa'
+};
+
+// name of the axes
+params.axesNames = ['lonaxis', 'lataxis'];
+
+// max longitudinal angular span (EXPERIMENTAL)
+params.lonaxisSpan = {
+    'orthographic': 180,
+    'azimuthal equal area': 360,
+    'azimuthal equidistant': 360,
+    'conic conformal': 180,
+    'gnomonic': 160,
+    'stereographic': 180,
+    'transverse mercator': 180,
+    '*': 360
+};
+
+// max latitudinal angular span (EXPERIMENTAL)
+params.lataxisSpan = {
+    'conic conformal': 150,
+    'stereographic': 179.5,
+    '*': 180
+};
+
+// defaults for each scope
+params.scopeDefaults = {
+    world: {
+        lonaxisRange: [-180, 180],
+        lataxisRange: [-90, 90],
+        projType: 'equirectangular',
+        projRotate: [0, 0, 0]
+    },
+    usa: {
+        lonaxisRange: [-180, -50],
+        lataxisRange: [15, 80],
+        projType: 'albers usa'
+    },
+    europe: {
+        lonaxisRange: [-30, 60],
+        lataxisRange: [30, 80],
+        projType: 'conic conformal',
+        projRotate: [15, 0, 0],
+        projParallels: [0, 60]
+    },
+    asia: {
+        lonaxisRange: [22, 160],
+        lataxisRange: [-15, 55],
+        projType: 'mercator',
+        projRotate: [0, 0, 0]
+    },
+    africa: {
+        lonaxisRange: [-30, 60],
+        lataxisRange: [-40, 40],
+        projType: 'mercator',
+        projRotate: [0, 0, 0]
+    },
+    'north america': {
+        lonaxisRange: [-180, -45],
+        lataxisRange: [5, 85],
+        projType: 'conic conformal',
+        projRotate: [-100, 0, 0],
+        projParallels: [29.5, 45.5]
+    },
+    'south america': {
+        lonaxisRange: [-100, -30],
+        lataxisRange: [-60, 15],
+        projType: 'mercator',
+        projRotate: [0, 0, 0]
+    }
+};
+
+// angular pad to avoid rounding error around clip angles
+params.clipPad = 1e-3;
+
+// map projection precision
+params.precision = 0.1;
+
+// default land and water fill colors
+params.landColor = '#F0DC82';
+params.waterColor = '#3399FF';
+
+// locationmode to layer name
+params.locationmodeToLayer = {
+    'ISO-3': 'countries',
+    'USA-states': 'subunits',
+    'country names': 'countries'
+};
+
+// SVG element for a sphere (use to frame maps)
+params.sphereSVG = {type: 'Sphere'};
+
+// N.B. base layer names must be the same as in the topojson files
+
+// base layer with a fill color
+params.fillLayers = ['ocean', 'land', 'lakes'];
+
+// base layer with a only a line color
+params.lineLayers = ['subunits', 'countries', 'coastlines', 'rivers', 'frame'];
+
+// all base layers - in order
+params.baseLayers = [
+    'ocean', 'land', 'lakes',
+    'subunits', 'countries', 'coastlines', 'rivers',
+    'lataxis', 'lonaxis',
+    'frame'
+];
+
+params.layerNameToAdjective = {
+    ocean: 'ocean',
+    land: 'land',
+    lakes: 'lake',
+    subunits: 'subunit',
+    countries: 'country',
+    coastlines: 'coastline',
+    rivers: 'river',
+    frame: 'frame'
+};
+
+// base layers drawn over choropleth
+params.baseLayersOverChoropleth = ['rivers', 'lakes'];
+
+},{}],335:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+module.exports = {
+    solid: [1],
+    dot: [1, 1],
+    dash: [4, 1],
+    longdash: [8, 1],
+    dashdot: [4, 1, 1, 1],
+    longdashdot: [8, 1, 1, 1]
+};
+
+},{}],336:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+module.exports = {
+    solid: [[], 0],
+    dot: [[0.5, 1], 200],
+    dash: [[0.5, 1], 50],
+    longdash: [[0.5, 1], 10],
+    dashdot: [[0.5, 0.625, 0.875, 1], 50],
+    longdashdot: [[0.5, 0.7, 0.8, 1], 10]
+};
+
+},{}],337:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+module.exports = {
+    circle: 'â',
+    'circle-open': 'â',
+    square: 'â ',
+    'square-open': 'â¡',
+    diamond: 'â',
+    'diamond-open': 'â',
+    cross: '+',
+    x: 'â'
+};
+
+},{}],338:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+
+exports.xmlns = 'http://www.w3.org/2000/xmlns/';
+exports.svg = 'http://www.w3.org/2000/svg';
+exports.xlink = 'http://www.w3.org/1999/xlink';
+
+// the 'old' d3 quirk got fix in v3.5.7
+// https://github.com/mbostock/d3/commit/a6f66e9dd37f764403fc7c1f26be09ab4af24fed
+exports.svgAttrs = {
+    xmlns: exports.svg,
+    'xmlns:xlink': exports.xlink
+};
+
+},{}],339:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+/*
+ * Export the plotly.js API methods.
+ */
+
+var Plotly = require('./plotly');
+
+// package version injected by `npm run preprocess`
+exports.version = '1.6.3';
+
+// plot api
+exports.plot = Plotly.plot;
+exports.newPlot = Plotly.newPlot;
+exports.restyle = Plotly.restyle;
+exports.relayout = Plotly.relayout;
+exports.redraw = Plotly.redraw;
+exports.extendTraces = Plotly.extendTraces;
+exports.prependTraces = Plotly.prependTraces;
+exports.addTraces = Plotly.addTraces;
+exports.deleteTraces = Plotly.deleteTraces;
+exports.moveTraces = Plotly.moveTraces;
+exports.setPlotConfig = require('./plot_api/set_plot_config');
+exports.register = Plotly.register;
+
+// plot icons
+exports.Icons = require('../build/ploticon');
+
+// unofficial 'beta' plot methods, use at your own risk
+exports.Plots = Plotly.Plots;
+exports.Fx = Plotly.Fx;
+exports.Snapshot = Plotly.Snapshot;
+exports.PlotSchema = Plotly.PlotSchema;
+exports.Queue = Plotly.Queue;
+
+// export d3 used in the bundle
+exports.d3 = require('d3');
+
+},{"../build/ploticon":2,"./plot_api/set_plot_config":365,"./plotly":366,"d3":70}],340:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+/* global MathJax:false */
+
+/**
+ * Check and configure MathJax
+ */
+if(typeof MathJax !== 'undefined') {
+    exports.MathJax = true;
+
+    MathJax.Hub.Config({
+        messageStyle: 'none',
+        skipStartupTypeset: true,
+        displayAlign: 'left',
+        tex2jax: {
+            inlineMath: [['$','$'],['\\(','\\)']]
+        }
+    });
+
+    MathJax.Hub.Configured();
+} else {
+    exports.MathJax = false;
+}
+
+},{}],341:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+// similar to Lib.mergeArray, but using inside a loop
+module.exports = function arrayToCalcItem(traceAttr, calcItem, calcAttr, i) {
+    if(Array.isArray(traceAttr)) calcItem[calcAttr] = traceAttr[i];
+};
+
+},{}],342:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+var tinycolor = require('tinycolor2');
+var nestedProperty = require('./nested_property');
+
+var getColorscale = require('../components/colorscale/get_scale');
+var colorscaleNames = Object.keys(require('../components/colorscale/scales'));
+
+
+exports.valObjects = {
+    data_array: {
+        // You can use *dflt=[] to force said array to exist though.
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt) {
+            if(Array.isArray(v)) propOut.set(v);
+            else if(dflt!==undefined) propOut.set(dflt);
+        }
+    },
+    enumerated: {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt, opts) {
+            if(opts.coerceNumber) v = +v;
+            if(opts.values.indexOf(v)===-1) propOut.set(dflt);
+            else propOut.set(v);
+        }
+    },
+    'boolean': {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt) {
+            if(v===true || v===false) propOut.set(v);
+            else propOut.set(dflt);
+        }
+    },
+    number: {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt, opts) {
+            if(!isNumeric(v) ||
+                    (opts.min!==undefined && v<opts.min) ||
+                    (opts.max!==undefined && v>opts.max)) {
+                propOut.set(dflt);
+            }
+            else propOut.set(+v);
+        }
+    },
+    integer: {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt, opts) {
+            if(v%1 || !isNumeric(v) ||
+                    (opts.min!==undefined && v<opts.min) ||
+                    (opts.max!==undefined && v>opts.max)) {
+                propOut.set(dflt);
+            }
+            else propOut.set(+v);
+        }
+    },
+    string: {
+        
+        
+        // TODO 'values shouldn't be in there (edge case: 'dash' in Scatter)
+        
+        coerceFunction: function(v, propOut, dflt, opts) {
+            if(opts.strict===true && typeof v !== 'string') {
+                propOut.set(dflt);
+                return;
+            }
+
+            var s = String(v);
+            if(v===undefined || (opts.noBlank===true && !s)) {
+                propOut.set(dflt);
+            }
+            else propOut.set(s);
+        }
+    },
+    color: {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt) {
+            if(tinycolor(v).isValid()) propOut.set(v);
+            else propOut.set(dflt);
+        }
+    },
+    colorscale: {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt) {
+            propOut.set(getColorscale(v, dflt));
+        }
+    },
+    angle: {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt) {
+            if(v==='auto') propOut.set('auto');
+            else if(!isNumeric(v)) propOut.set(dflt);
+            else {
+                if(Math.abs(v)>180) v -= Math.round(v/360)*360;
+                propOut.set(+v);
+            }
+        }
+    },
+    axisid: {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt) {
+            if(typeof v === 'string' && v.charAt(0)===dflt) {
+                var axnum = Number(v.substr(1));
+                if(axnum%1 === 0 && axnum>1) {
+                    propOut.set(v);
+                    return;
+                }
+            }
+            propOut.set(dflt);
+        }
+    },
+    sceneid: {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt) {
+            if(typeof v === 'string' && v.substr(0,5)===dflt) {
+                var scenenum = Number(v.substr(5));
+                if(scenenum%1 === 0 && scenenum>1) {
+                    propOut.set(v);
+                    return;
+                }
+            }
+            propOut.set(dflt);
+        }
+    },
+    geoid: {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt) {
+            if(typeof v === 'string' && v.substr(0,3)===dflt) {
+                var geonum = Number(v.substr(3));
+                if(geonum%1 === 0 && geonum>1) {
+                    propOut.set(v);
+                    return;
+                }
+            }
+            propOut.set(dflt);
+        }
+    },
+    flaglist: {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt, opts) {
+            if(typeof v !== 'string') {
+                propOut.set(dflt);
+                return;
+            }
+            if(opts.extras.indexOf(v)!==-1) {
+                propOut.set(v);
+                return;
+            }
+            var vParts = v.split('+'),
+                i = 0;
+            while(i<vParts.length) {
+                var vi = vParts[i];
+                if(opts.flags.indexOf(vi)===-1 || vParts.indexOf(vi)<i) {
+                    vParts.splice(i,1);
+                }
+                else i++;
+            }
+            if(!vParts.length) propOut.set(dflt);
+            else propOut.set(vParts.join('+'));
+        }
+    },
+    any: {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt) {
+            if(v===undefined) propOut.set(dflt);
+            else propOut.set(v);
+        }
+    },
+    info_array: {
+        
+        
+        
+        coerceFunction: function(v, propOut, dflt, opts) {
+            if(!Array.isArray(v)) {
+                propOut.set(dflt);
+                return;
+            }
+
+            var items = opts.items,
+                vOut = [];
+            dflt = Array.isArray(dflt) ? dflt : [];
+
+            for(var i = 0; i < items.length; i++) {
+                exports.coerce(v, vOut, items, '[' + i + ']', dflt[i]);
+            }
+
+            propOut.set(vOut);
+        }
+    }
+};
+
+/**
+ * Ensures that container[attribute] has a valid value.
+ *
+ * attributes[attribute] is an object with possible keys:
+ * - valType: data_array, enumerated, boolean, ... as in valObjects
+ * - values: (enumerated only) array of allowed vals
+ * - min, max: (number, integer only) inclusive bounds on allowed vals
+ *      either or both may be omitted
+ * - dflt: if attribute is invalid or missing, use this default
+ *      if dflt is provided as an argument to lib.coerce it takes precedence
+ *      as a convenience, returns the value it finally set
+ */
+exports.coerce = function(containerIn, containerOut, attributes, attribute, dflt) {
+    var opts = nestedProperty(attributes, attribute).get(),
+        propIn = nestedProperty(containerIn, attribute),
+        propOut = nestedProperty(containerOut, attribute),
+        v = propIn.get();
+
+    if(dflt===undefined) dflt = opts.dflt;
+
+    /**
+     * arrayOk: value MAY be an array, then we do no value checking
+     * at this point, because it can be more complicated than the
+     * individual form (eg. some array vals can be numbers, even if the
+     * single values must be color strings)
+     */
+    if(opts.arrayOk && Array.isArray(v)) {
+        propOut.set(v);
+        return v;
+    }
+
+    exports.valObjects[opts.valType].coerceFunction(v, propOut, dflt, opts);
+
+    return propOut.get();
+};
+
+/**
+ * Variation on coerce
+ *
+ * Uses coerce to get attribute value if user input is valid,
+ * returns attribute default if user input it not valid or
+ * returns false if there is no user input.
+ */
+exports.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) {
+    var propIn = nestedProperty(containerIn, attribute),
+        propOut = exports.coerce(containerIn, containerOut, attributes, attribute, dflt);
+
+    return propIn.get() ? propOut : false;
+};
+
+/*
+ * Shortcut to coerce the three font attributes
+ *
+ * 'coerce' is a lib.coerce wrapper with implied first three arguments
+ */
+exports.coerceFont = function(coerce, attr, dfltObj) {
+    var out = {};
+
+    dfltObj = dfltObj || {};
+
+    out.family = coerce(attr + '.family', dfltObj.family);
+    out.size = coerce(attr + '.size', dfltObj.size);
+    out.color = coerce(attr + '.color', dfltObj.color);
+
+    return out;
+};
+
+},{"../components/colorscale/get_scale":310,"../components/colorscale/scales":316,"./nested_property":352,"fast-isnumeric":74,"tinycolor2":229}],343:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var isNumeric = require('fast-isnumeric');
+
+
+/**
+ * dateTime2ms - turn a date object or string s of the form
+ * YYYY-mm-dd HH:MM:SS.sss into milliseconds (relative to 1970-01-01,
+ * per javascript standard)
+ * may truncate after any full field, and sss can be any length
+ * even >3 digits, though javascript dates truncate to milliseconds
+ * returns false if it doesn't find a date
+ *
+ * 2-digit to 4-digit year conversion, where to cut off?
+ * from http://support.microsoft.com/kb/244664:
+ *   1930-2029 (the most retro of all...)
+ * but in my mac chrome from eg. d=new Date(Date.parse('8/19/50')):
+ *   1950-2049
+ * by Java, from http://stackoverflow.com/questions/2024273/:
+ *   now-80 - now+20
+ * or FileMaker Pro, from
+ *      http://www.filemaker.com/12help/html/add_view_data.4.21.html:
+ *   now-70 - now+30
+ * but python strptime etc, via
+ *      http://docs.python.org/py3k/library/time.html:
+ *   1969-2068 (super forward-looking, but static, not sliding!)
+ *
+ * lets go with now-70 to now+30, and if anyone runs into this problem
+ * they can learn the hard way not to use 2-digit years, as no choice we
+ * make now will cover all possibilities. mostly this will all be taken
+ * care of in initial parsing, should only be an issue for hand-entered data
+ * currently (2012) this range is:
+ *   1942-2041
+ */
+
+exports.dateTime2ms = function(s) {
+    // first check if s is a date object
+    try {
+        if(s.getTime) return +s;
+    }
+    catch(e) {
+        return false;
+    }
+
+    var y, m, d, h;
+    // split date and time parts
+    var datetime = String(s).split(' ');
+    if(datetime.length > 2) return false;
+
+    var p = datetime[0].split('-'); // date part
+    if(p.length > 3 || (p.length !== 3 && datetime[1])) return false;
+
+    // year
+    if(p[0].length === 4) y = Number(p[0]);
+    else if(p[0].length === 2) {
+        var yNow = new Date().getFullYear();
+        y = ((Number(p[0]) - yNow + 70)%100 + 200)%100 + yNow - 70;
+    }
+    else return false;
+    if(!isNumeric(y)) return false;
+    if(p.length === 1) return new Date(y,0,1).getTime(); // year only
+
+    // month
+    m = Number(p[1]) - 1; // new Date() uses zero-based months
+    if(p[1].length > 2 || !(m >= 0 && m <= 11)) return false;
+    if(p.length === 2) return new Date(y, m, 1).getTime(); // year-month
+
+    // day
+    d = Number(p[2]);
+    if(p[2].length > 2 || !(d >= 1 && d <= 31)) return false;
+
+    // now save the date part
+    d = new Date(y, m, d).getTime();
+    if(!datetime[1]) return d; // year-month-day
+    p = datetime[1].split(':');
+    if(p.length > 3) return false;
+
+    // hour
+    h = Number(p[0]);
+    if(p[0].length > 2 || !(h >= 0 && h <= 23)) return false;
+    d += 3600000*h;
+    if(p.length === 1) return d;
+
+    // minute
+    m = Number(p[1]);
+    if(p[1].length > 2 || !(m >= 0 && m <= 59)) return false;
+    d += 60000*m;
+    if(p.length === 2) return d;
+
+    // second
+    s = Number(p[2]);
+    if(!(s >= 0 && s < 60)) return false;
+    return d+s*1000;
+};
+
+// is string s a date? (see above)
+exports.isDateTime = function(s) {
+    return (exports.dateTime2ms(s) !== false);
+};
+
+// pad a number with zeroes, to given # of digits before the decimal point
+function lpad(val, digits) {
+    return String(val + Math.pow(10, digits)).substr(1);
+}
+
+/**
+ * Turn ms into string of the form YYYY-mm-dd HH:MM:SS.sss
+ * Crop any trailing zeros in time, but always leave full date
+ * (we could choose to crop '-01' from date too)...
+ * Optional range r is the data range that applies, also in ms.
+ * If rng is big, the later parts of time will be omitted
+ */
+exports.ms2DateTime = function(ms, r) {
+    if(typeof(d3)==='undefined') {
+        console.log('d3 is not defined');
+        return;
+    }
+
+    if(!r) r=0;
+    var d = new Date(ms),
+        s = d3.time.format('%Y-%m-%d')(d);
+    if(r<7776000000) {
+        // <90 days: add hours
+        s+=' '+lpad(d.getHours(),2);
+        if(r<432000000) {
+            // <5 days: add minutes
+            s+=':'+lpad(d.getMinutes(),2);
+            if(r<10800000) {
+                // <3 hours: add seconds
+                s+=':'+lpad(d.getSeconds(),2);
+                if(r<300000) {
+                    // <5 minutes: add ms
+                    s+='.'+lpad(d.getMilliseconds(),3);
+                }
+            }
+        }
+        // strip trailing zeros
+        return s.replace(/([:\s]00)*\.?[0]*$/,'');
+    }
+    return s;
+};
+
+/**
+ * parseDate: forgiving attempt to turn any date string
+ * into a javascript date object
+ *
+ * first collate all the date formats we want to support, precompiled
+ * to d3 format objects see below for the string cleaning that happens
+ * before this separate out 2-digit (y) and 4-digit-year (Y) formats,
+ * formats with month names (b), and formats with am/pm (I) or no time (D)
+ * (also includes hour only, as the test is really for a colon) so we can
+ * cut down the number of tests we need to run for any given string
+ * (right now all are between 15 and 32 tests)
+ */
+
+// TODO: this is way out of date vs. the server-side version
+var timeFormats = {
+    // 24 hour
+    H: ['%H:%M:%S~%L', '%H:%M:%S', '%H:%M'],
+    // with am/pm
+    I: ['%I:%M:%S~%L%p', '%I:%M:%S%p', '%I:%M%p'],
+    // no colon, ie only date or date with hour (could also support eg 12h34m?)
+    D: ['%H', '%I%p', '%Hh']
+};
+
+var dateFormats = {
+    Y: [
+        '%Y~%m~%d',
+        '%Y%m%d',
+        '%y%m%d', // YYMMDD, has 6 digits together so will match Y, not y
+        '%m~%d~%Y', // MM/DD/YYYY has first precedence
+        '%d~%m~%Y' // then DD/MM/YYYY
+    ],
+    Yb: [
+        '%b~%d~%Y', // eg nov 21 2013
+        '%d~%b~%Y', // eg 21 nov 2013
+        '%Y~%d~%b', // eg 2013 21 nov (or 2013 q3, after replacement)
+        '%Y~%b~%d' // eg 2013 nov 21
+    ],
+    /**
+     * the two-digit year cases have so many potential ambiguities
+     * it's not even funny, but we'll try them anyway.
+     */
+    y: [
+        '%m~%d~%y',
+        '%d~%m~%y',
+        '%y~%m~%d'
+    ],
+    yb: [
+        '%b~%d~%y',
+        '%d~%b~%y',
+        '%y~%d~%b',
+        '%y~%b~%d'
+    ]
+};
+
+// use utc formatter since we're ignoring timezone info
+var formatter = d3.time.format.utc;
+
+/**
+ * ISO8601 and YYYYMMDDHHMMSS are the only ones where date and time
+ * are not separated by a space, so they get inserted specially here.
+ * Also a couple formats with no day (so time makes no sense)
+ */
+var dateTimeFormats = {
+    Y: {
+        H: ['%Y~%m~%dT%H:%M:%S', '%Y~%m~%dT%H:%M:%S~%L'].map(formatter),
+        I: [],
+        D: ['%Y%m%d%H%M%S', '%Y~%m', '%m~%Y'].map(formatter)
+    },
+    Yb: {H: [], I: [], D: ['%Y~%b', '%b~%Y'].map(formatter)},
+    y: {H: [], I: [], D: []},
+    yb: {H: [], I: [], D: []}
+};
+// all others get inserted in all possible combinations from dateFormats and timeFormats
+['Y', 'Yb', 'y', 'yb'].forEach(function(dateType) {
+    dateFormats[dateType].forEach(function(dateFormat) {
+        // just a date (don't do just a time)
+        dateTimeFormats[dateType].D.push(formatter(dateFormat));
+        ['H', 'I', 'D'].forEach(function(timeType) {
+            timeFormats[timeType].forEach(function(timeFormat) {
+                var a = dateTimeFormats[dateType][timeType];
+
+                // 'date time', then 'time date'
+                a.push(formatter(dateFormat+'~'+timeFormat));
+                a.push(formatter(timeFormat+'~'+dateFormat));
+            });
+        });
+    });
+});
+
+// precompiled regexps for performance
+var matchword = /[a-z]*/g,
+    shortenword = function(m) { return m.substr(0,3); },
+    weekdaymatch = /(mon|tue|wed|thu|fri|sat|sun|the|of|st|nd|rd|th)/g,
+    separatormatch = /[\s,\/\-\.\(\)]+/g,
+    ampmmatch = /~?([ap])~?m(~|$)/,
+    replaceampm = function(m,ap) { return ap+'m '; },
+    match4Y = /\d\d\d\d/,
+    matchMonthName = /(^|~)[a-z]{3}/,
+    matchAMPM = /[ap]m/,
+    matchcolon = /:/,
+    matchquarter = /q([1-4])/,
+    quarters = ['31~mar','30~jun','30~sep','31~dec'],
+    replacequarter = function(m,n) { return quarters[n-1]; },
+    matchTZ = / ?([+\-]\d\d:?\d\d|Z)$/;
+
+function getDateType(v) {
+    var dateType;
+    dateType = (match4Y.test(v) ? 'Y' : 'y');
+    dateType = dateType + (matchMonthName.test(v) ? 'b' : '');
+    return dateType;
+}
+
+function getTimeType(v) {
+    var timeType;
+    timeType = matchcolon.test(v) ? (matchAMPM.test(v) ? 'I' : 'H') : 'D';
+    return timeType;
+}
+
+exports.parseDate = function(v) {
+    // is it already a date? just return it
+    if(v.getTime) return v;
+    /**
+     * otherwise, if it's not a string, return nothing
+     * the case of numbers that just have years will get
+     * dealt with elsewhere.
+     */
+    if(typeof v !== 'string') return false;
+
+    // first clean up the string a bit to reduce the number of formats we have to test
+    v = v.toLowerCase()
+        /**
+         * cut all words down to 3 characters - this will result in
+         * some spurious matches, ie whenever the first three characters
+         * of a word match a month or weekday but that seems more likely
+         * to fix typos than to make dates where they shouldn't be...
+         * and then we can omit the long form of months from our testing
+         */
+        .replace(matchword, shortenword)
+        /**
+         * remove weekday names, as they get overridden anyway if they're
+         * inconsistent also removes a few more words
+         * (ie "tuesday the 26th of november")
+         * TODO: language support?
+         * for months too, but these seem to be built into d3
+         */
+        .replace(weekdaymatch, '')
+        /**
+         * collapse all separators one ~ at a time, except : which seems
+         * pretty consistent for the time part use ~ instead of space or
+         * something since d3 can eat a space as padding on 1-digit numbers
+         */
+        .replace(separatormatch, '~')
+        // in case of a.m. or p.m. (also take off any space before am/pm)
+        .replace(ampmmatch, replaceampm)
+        // turn quarters Q1-4 into dates (quarter ends)
+        .replace(matchquarter, replacequarter)
+        .trim()
+        // also try to ignore timezone info, at least for now
+        .replace(matchTZ, '');
+
+    // now test against the various formats that might match
+    var out = null,
+        dateType = getDateType(v),
+        timeType = getTimeType(v),
+        formatList,
+        len;
+
+    formatList = dateTimeFormats[dateType][timeType];
+    len = formatList.length;
+
+    for(var i = 0; i < len; i++) {
+        out = formatList[i].parse(v);
+        if(out) break;
+    }
+
+    // If not an instance of Date at this point, just return it.
+    if(!(out instanceof Date)) return false;
+    // parse() method interprets arguments with local time zone.
+    var tzoff = out.getTimezoneOffset();
+    // In general (default) this is not what we want, so force into UTC:
+    out.setTime(out.getTime() + tzoff * 60 * 1000);
+    return out;
+};
+
+},{"d3":70,"fast-isnumeric":74}],344:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+/* global $:false */
+
+var EventEmitter = require('events').EventEmitter;
+
+var Events = {
+
+    init: function(plotObj) {
+
+        /*
+         * If we have already instantiated an emitter for this plot
+         * return early.
+         */
+        if(plotObj._ev instanceof EventEmitter) return plotObj;
+
+        var ev = new EventEmitter();
+
+        /*
+         * Assign to plot._ev while we still live in a land
+         * where plot is a DOM element with stuff attached to it.
+         * In the future we can make plot the event emitter itself.
+         */
+        plotObj._ev = ev;
+
+        /*
+         * Assign bound methods from the ev to the plot object. These methods
+         * will reference the 'this' of plot._ev even though they are methods
+         * of plot. This will keep the event machinery away from the plot object
+         * which currently is often a DOM element but presents an API that will
+         * continue to function when plot becomes an emitter. Not all EventEmitter
+         * methods have been bound to `plot` as some do not currently add value to
+         * the Plotly event API.
+         */
+        plotObj.on = ev.on.bind(ev);
+        plotObj.once = ev.once.bind(ev);
+        plotObj.removeListener = ev.removeListener.bind(ev);
+        plotObj.removeAllListeners = ev.removeAllListeners.bind(ev);
+
+        /*
+         * We must wrap emit to continue to support JQuery events. The idea
+         * is to check to see if the user is using JQuery events, if they are
+         * we emit JQuery events to trigger user handlers as well as the EventEmitter
+         * events.
+         */
+        plotObj.emit = function(event, data) {
+            if(typeof $ !== 'undefined') {
+                $(plotObj).trigger(event, data);
+            }
+
+            ev.emit(event, data);
+        };
+
+        return plotObj;
+    },
+
+    /*
+     * This function behaves like jQueries triggerHandler. It calls
+     * all handlers for a particular event and returns the return value
+     * of the LAST handler. This function also triggers jQuery's
+     * triggerHandler for backwards compatibility.
+     */
+    triggerHandler: function(plotObj, event, data) {
+        var jQueryHandlerValue;
+        var nodeEventHandlerValue;
+        /*
+         * If Jquery exists run all its handlers for this event and
+         * collect the return value of the LAST handler function
+         */
+        if(typeof $ !== 'undefined') {
+            jQueryHandlerValue = $(plotObj).triggerHandler(event, data);
+        }
+
+        /*
+         * Now run all the node style event handlers
+         */
+        var ev = plotObj._ev;
+        if(!ev) return jQueryHandlerValue;
+
+        var handlers = ev._events[event];
+        if(!handlers) return jQueryHandlerValue;
+
+        /*
+         * handlers can be function or an array of functions
+         */
+        if(typeof handlers === 'function') handlers = [handlers];
+        var lastHandler = handlers.pop();
+
+        /*
+         * Call all the handlers except the last one.
+         */
+        for(var i = 0; i < handlers.length; i++) {
+            handlers[i](data);
+        }
+
+        /*
+         * Now call the final handler and collect its value
+         */
+        nodeEventHandlerValue = lastHandler(data);
+
+        /*
+         * Return either the jquery handler value if it exists or the
+         * nodeEventHandler value. Jquery event value superceeds nodejs
+         * events for backwards compatability reasons.
+         */
+        return jQueryHandlerValue !== undefined ? jQueryHandlerValue :
+            nodeEventHandlerValue;
+    }
+};
+
+module.exports = Events;
+
+},{"events":54}],345:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isPlainObject = require('./is_plain_object.js');
+var isArray = Array.isArray;
+
+exports.extendFlat = function() {
+    return _extend(arguments, false, false);
+};
+
+exports.extendDeep = function() {
+    return _extend(arguments, true, false);
+};
+
+exports.extendDeepAll = function() {
+    return _extend(arguments, true, true);
+};
+
+/*
+ * Inspired by https://github.com/justmoon/node-extend/blob/master/index.js
+ * All credit to the jQuery authors for perfecting this amazing utility.
+ *
+ * API difference with jQuery version:
+ * - No optional boolean (true -> deep extend) first argument,
+ *   use `extendFlat` for first-level only extend and
+ *   use `extendDeep` for a deep extend.
+ *
+ * Other differences with jQuery version:
+ * - Uses a modern (and faster) isPlainObject routine.
+ * - Expected to work with object {} and array [] arguments only.
+ * - Does not check for circular structure.
+ *   FYI: jQuery only does a check across one level.
+ *   Warning: this might result in infinite loops.
+ *
+ */
+function _extend(inputs, isDeep, keepAllKeys) {
+    var target = inputs[0],
+        length = inputs.length;
+
+    var input, key, src, copy, copyIsArray, clone;
+
+    for(var i = 1; i < length; i++) {
+        input = inputs[i];
+
+        for(key in input) {
+            src = target[key];
+            copy = input[key];
+
+            // recurse if we're merging plain objects or arrays
+            if(isDeep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
+                if(copyIsArray) {
+                    copyIsArray = false;
+                    clone = src && isArray(src) ? src : [];
+                } else {
+                    clone = src && isPlainObject(src) ? src : {};
+                }
+
+                // never move original objects, clone them
+                target[key] = _extend([clone, copy], isDeep, keepAllKeys);
+            }
+
+            // don't bring in undefined values, except for extendDeepAll
+            else if(typeof copy !== 'undefined' || keepAllKeys) {
+                target[key] = copy;
+            }
+        }
+    }
+
+    return target;
+}
+
+},{"./is_plain_object.js":350}],346:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var locationUtils = module.exports = {};
+
+var Plotly = require('../plotly');
+
+// an hash object iso3 to regex string
+var countryNameData = require('../constants/country-name_to_iso3');
+
+// make list of all country iso3 ids from at runtime
+var countryIds = Object.keys(countryNameData);
+
+var locationmodeToIdFinder = {
+    'ISO-3': Plotly.Lib.identity,
+    'USA-states': Plotly.Lib.identity,
+    'country names': countryNameToISO3
+};
+
+locationUtils.locationToFeature = function(locationmode, location, features) {
+    var locationId = getLocationId(locationmode, location);
+    var feature;
+
+    for(var i = 0; i < features.length; i++) {
+        feature = features[i];
+
+        if(feature.id === locationId) return feature;
+    }
+
+    console.warn([
+        'location with id', locationId,
+        'does not have a matching topojson feature at this resolution.'
+    ].join(' '));
+};
+
+function getLocationId(locationmode, location) {
+    var idFinder = locationmodeToIdFinder[locationmode];
+    return idFinder(location);
+}
+
+function countryNameToISO3(countryName) {
+    var iso3, regex;
+
+    for(var i = 0; i < countryIds.length; i++) {
+        iso3 = countryIds[i];
+        regex = new RegExp(countryNameData[iso3]);
+
+        if(regex.test(countryName.toLowerCase())) return iso3;
+    }
+
+    console.warn('unrecognized country name: ' + countryName + '.');
+}
+
+},{"../constants/country-name_to_iso3":333,"../plotly":366}],347:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../plotly');
+var tinycolor = require('tinycolor2');
+var isNumeric = require('fast-isnumeric');
+var str2RgbaArray = require('./str2rgbarray');
+
+var colorDflt = require('../components/color/attributes').defaultLine;
+var opacityDflt = 1;
+
+function calculateColor(colorIn, opacityIn) {
+    var colorOut = str2RgbaArray(colorIn);
+    colorOut[3] *= opacityIn;
+    return colorOut;
+}
+
+function validateColor(colorIn) {
+    return tinycolor(colorIn).isValid() ? colorIn : colorDflt;
+}
+
+function validateOpacity(opacityIn) {
+    return isNumeric(opacityIn) ? opacityIn : opacityDflt;
+}
+
+function formatColor(containerIn, opacityIn, len) {
+    var colorIn = containerIn.color,
+        isArrayColorIn = Array.isArray(colorIn),
+        isArrayOpacityIn = Array.isArray(opacityIn),
+        colorOut = [];
+
+    var sclFunc, getColor, getOpacity, colori, opacityi;
+
+    if(containerIn.colorscale !== undefined) {
+        sclFunc = Plotly.Colorscale.makeScaleFunction(
+            containerIn.colorscale, containerIn.cmin, containerIn.cmax
+        );
+    }
+    else sclFunc = validateColor;
+
+    if(isArrayColorIn) {
+        getColor = function(c, i) {
+            return c[i]===undefined ? colorDflt : sclFunc(c[i]);
+        };
+    }
+    else getColor = validateColor;
+
+    if(isArrayOpacityIn) {
+        getOpacity = function(o, i) {
+            return o[i]===undefined ? opacityDflt : validateOpacity(o[i]);
+        };
+    }
+    else getOpacity = validateOpacity;
+
+    if(isArrayColorIn || isArrayOpacityIn) {
+        for(var i = 0; i < len; i++) {
+            colori = getColor(colorIn, i);
+            opacityi = getOpacity(opacityIn, i);
+            colorOut[i] = calculateColor(colori, opacityi);
+        }
+    }
+    else colorOut = calculateColor(colorIn, opacityIn);
+
+    return colorOut;
+}
+
+module.exports = formatColor;
+
+},{"../components/color/attributes":298,"../plotly":366,"./str2rgbarray":359,"fast-isnumeric":74,"tinycolor2":229}],348:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var toSuperScript = require('superscript-text');
+
+var ENTITIES = {
+    'mu': 'ÎŒ',
+    'amp': '&',
+    'lt': '<',
+    'gt': '>'
+};
+
+function fixSuperScript(x) {
+    var idx = 0;
+
+    while((idx = x.indexOf('<sup>', idx)) >= 0) {
+        var nidx = x.indexOf('</sup>', idx);
+        if(nidx < idx) break;
+
+        x = x.slice(0, idx) + toSuperScript(x.slice(idx+5, nidx)) + x.slice(nidx+6);
+    }
+
+    return x;
+}
+
+function fixBR(x) {
+    return x.replace(/\<br\>/g, '\n');
+}
+
+function stripTags(x) {
+    return x.replace(/\<.*\>/g, '');
+}
+
+function fixEntities(x) {
+    var idx = 0;
+
+    while((idx = x.indexOf('&', idx)) >= 0) {
+        var nidx = x.indexOf(';', idx);
+        if(nidx < idx) {
+            idx += 1;
+            continue;
+        }
+
+        var entity = ENTITIES[x.slice(idx+1, nidx)];
+        if(entity) {
+            x = x.slice(0, idx) + entity + x.slice(nidx+1);
+        } else {
+            x = x.slice(0, idx) + x.slice(nidx+1);
+        }
+    }
+
+    return x;
+}
+
+function convertHTMLToUnicode(html) {
+    return '' +
+        fixEntities(
+        stripTags(
+        fixSuperScript(
+        fixBR(
+          html))));
+}
+
+module.exports = convertHTMLToUnicode;
+
+},{"superscript-text":218}],349:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var lib = module.exports = {};
+
+lib.nestedProperty = require('./nested_property');
+lib.isPlainObject = require('./is_plain_object');
+
+var coerceModule = require('./coerce');
+lib.valObjects = coerceModule.valObjects;
+lib.coerce = coerceModule.coerce;
+lib.coerce2 = coerceModule.coerce2;
+lib.coerceFont = coerceModule.coerceFont;
+
+var datesModule = require('./dates');
+lib.dateTime2ms = datesModule.dateTime2ms;
+lib.isDateTime = datesModule.isDateTime;
+lib.ms2DateTime = datesModule.ms2DateTime;
+lib.parseDate = datesModule.parseDate;
+
+var searchModule = require('./search');
+lib.findBin = searchModule.findBin;
+lib.sorterAsc = searchModule.sorterAsc;
+lib.sorterDes = searchModule.sorterDes;
+lib.distinctVals = searchModule.distinctVals;
+lib.roundUp = searchModule.roundUp;
+
+var statsModule = require('./stats');
+lib.aggNums = statsModule.aggNums;
+lib.len = statsModule.len;
+lib.mean = statsModule.mean;
+lib.variance = statsModule.variance;
+lib.stdev = statsModule.stdev;
+lib.interp = statsModule.interp;
+
+var matrixModule = require('./matrix');
+lib.init2dArray = matrixModule.init2dArray;
+lib.transposeRagged = matrixModule.transposeRagged;
+lib.dot = matrixModule.dot;
+lib.translationMatrix = matrixModule.translationMatrix;
+lib.rotationMatrix = matrixModule.rotationMatrix;
+lib.rotationXYMatrix = matrixModule.rotationXYMatrix;
+lib.apply2DTransform = matrixModule.apply2DTransform;
+lib.apply2DTransform2 = matrixModule.apply2DTransform2;
+
+var extendModule = require('./extend');
+lib.extendFlat = extendModule.extendFlat;
+lib.extendDeep = extendModule.extendDeep;
+lib.extendDeepAll = extendModule.extendDeepAll;
+
+lib.notifier = require('./notifier');
+
+/**
+ * swap x and y of the same attribute in container cont
+ * specify attr with a ? in place of x/y
+ * you can also swap other things than x/y by providing part1 and part2
+ */
+lib.swapAttrs = function(cont, attrList, part1, part2) {
+    if(!part1) part1 = 'x';
+    if(!part2) part2 = 'y';
+    for(var i = 0; i < attrList.length; i++) {
+        var attr = attrList[i],
+            xp = lib.nestedProperty(cont, attr.replace('?', part1)),
+            yp = lib.nestedProperty(cont, attr.replace('?', part2)),
+            temp = xp.get();
+        xp.set(yp.get());
+        yp.set(temp);
+    }
+};
+
+/**
+ * to prevent event bubbling, in particular text selection during drag.
+ * see http://stackoverflow.com/questions/5429827/
+ *      how-can-i-prevent-text-element-selection-with-cursor-drag
+ * for maximum effect use:
+ *      return pauseEvent(e);
+ */
+lib.pauseEvent = function(e) {
+    if(e.stopPropagation) e.stopPropagation();
+    if(e.preventDefault) e.preventDefault();
+    e.cancelBubble = true;
+    return false;
+};
+
+/**
+ * ------------------------------------------
+ * debugging tools
+ * ------------------------------------------
+ */
+
+// set VERBOSE to true to get a lot more logging and tracing
+lib.VERBOSE = false;
+
+// first markTime call will return time from page load
+lib.TIMER = new Date().getTime();
+
+// console.log that only runs if VERBOSE is on
+lib.log = function() {
+    if(lib.VERBOSE) console.log.apply(console, arguments);
+};
+
+/**
+ * markTime - for debugging, mark the number of milliseconds
+ * since the previous call to markTime and log arbitrary info too
+ */
+lib.markTime = function(v) {
+    if(!lib.VERBOSE) return;
+    var t2 = new Date().getTime();
+    console.log(v, t2 - lib.TIMER, '(msec)');
+    if(lib.VERBOSE === 'trace') console.trace();
+    lib.TIMER = t2;
+};
+
+// constrain - restrict a number v to be between v0 and v1
+lib.constrain = function(v, v0, v1) {
+    if(v0 > v1) return Math.max(v1, Math.min(v0, v));
+    return Math.max(v0, Math.min(v1, v));
+};
+
+/**
+ * do two bounding boxes from getBoundingClientRect,
+ * ie {left,right,top,bottom,width,height}, overlap?
+ * takes optional padding pixels
+ */
+lib.bBoxIntersect = function(a, b, pad) {
+    pad = pad || 0;
+    return (a.left <= b.right + pad &&
+            b.left <= a.right + pad &&
+            a.top <= b.bottom + pad &&
+            b.top <= a.bottom + pad);
+};
+
+// minor convenience/performance booster for d3...
+lib.identity = function(d) { return d; };
+
+// random string generator
+lib.randstr = function randstr(existing, bits, base) {
+    /*
+     * Include number of bits, the base of the string you want
+     * and an optional array of existing strings to avoid.
+     */
+    if(!base) base = 16;
+    if(bits === undefined) bits = 24;
+    if(bits <= 0) return '0';
+
+    var digits = Math.log(Math.pow(2, bits)) / Math.log(base),
+        res = '',
+        i,
+        b,
+        x;
+
+    for(i = 2; digits === Infinity; i *= 2) {
+        digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;
+    }
+
+    var rem = digits - Math.floor(digits);
+
+    for(i = 0; i < Math.floor(digits); i++) {
+        x = Math.floor(Math.random() * base).toString(base);
+        res = x + res;
+    }
+
+    if(rem) {
+        b = Math.pow(base, rem);
+        x = Math.floor(Math.random() * b).toString(base);
+        res = x + res;
+    }
+
+    var parsed = parseInt(res, base);
+    if((existing && (existing.indexOf(res) > -1)) ||
+         (parsed !== Infinity && parsed >= Math.pow(2, bits))) {
+        return randstr(existing, bits, base);
+    }
+    else return res;
+};
+
+lib.OptionControl = function(opt, optname) {
+    /*
+     * An environment to contain all option setters and
+     * getters that collectively modify opts.
+     *
+     * You can call up opts from any function in new object
+     * as this.optname || this.opt
+     *
+     * See FitOpts for example of usage
+     */
+    if(!opt) opt = {};
+    if(!optname) optname = 'opt';
+
+    var self = {};
+    self.optionList = [];
+
+    self._newoption = function(optObj) {
+        optObj[optname] = opt;
+        self[optObj.name] = optObj;
+        self.optionList.push(optObj);
+    };
+
+    self['_'+optname] = opt;
+    return self;
+};
+
+/**
+ * lib.smooth: smooth arrayIn by convolving with
+ * a hann window with given full width at half max
+ * bounce the ends in, so the output has the same length as the input
+ */
+lib.smooth = function(arrayIn, FWHM) {
+    FWHM = Math.round(FWHM) || 0; // only makes sense for integers
+    if(FWHM < 2) return arrayIn;
+
+    var alen = arrayIn.length,
+        alen2 = 2 * alen,
+        wlen = 2 * FWHM - 1,
+        w = new Array(wlen),
+        arrayOut = new Array(alen),
+        i,
+        j,
+        k,
+        v;
+
+    // first make the window array
+    for(i = 0; i < wlen; i++) {
+        w[i] = (1 - Math.cos(Math.PI * (i + 1) / FWHM)) / (2 * FWHM);
+    }
+
+    // now do the convolution
+    for(i = 0; i < alen; i++) {
+        v = 0;
+        for(j = 0; j < wlen; j++) {
+            k = i + j + 1 - FWHM;
+
+            // multibounce
+            if(k < -alen) k -= alen2 * Math.round(k / alen2);
+            else if(k >= alen2) k -= alen2 * Math.floor(k / alen2);
+
+            // single bounce
+            if(k < 0) k = - 1 - k;
+            else if(k >= alen) k = alen2 - 1 - k;
+
+            v += arrayIn[k] * w[j];
+        }
+        arrayOut[i] = v;
+    }
+
+    return arrayOut;
+};
+
+// helpers for promises
+
+/**
+ * promiseError: log errors properly inside promises
+ * use:
+ * <promise>.then(undefined,Plotly.Lib.promiseError) (for IE compatibility)
+ * or <promise>.catch(Plotly.Lib.promiseError)
+ * TODO: I guess we need another step to send this error to Sentry?
+ */
+lib.promiseError = function(err) { console.log(err, err.stack); };
+
+/**
+ * syncOrAsync: run a sequence of functions synchronously
+ * as long as its returns are not promises (ie have no .then)
+ * includes one argument arg to send to all functions...
+ * this is mainly just to prevent us having to make wrapper functions
+ * when the only purpose of the wrapper is to reference gd / td
+ * and a final step to be executed at the end
+ * TODO: if there's an error and everything is sync,
+ * this doesn't happen yet because we want to make sure
+ * that it gets reported
+ */
+lib.syncOrAsync = function(sequence, arg, finalStep) {
+    var ret, fni;
+
+    function continueAsync() {
+        lib.markTime('async done ' + fni.name);
+        return lib.syncOrAsync(sequence, arg, finalStep);
+    }
+    while(sequence.length) {
+        fni = sequence.splice(0, 1)[0];
+        ret = fni(arg);
+        // lib.markTime('done calling '+fni.name)
+        if(ret && ret.then) {
+            return ret.then(continueAsync)
+                .then(undefined, lib.promiseError);
+        }
+        lib.markTime('sync done ' + fni.name);
+    }
+
+    return finalStep && finalStep(arg);
+};
+
+
+/**
+ * Helper to strip trailing slash, from
+ * http://stackoverflow.com/questions/6680825/return-string-without-trailing-slash
+ */
+lib.stripTrailingSlash = function(str) {
+    if(str.substr(-1) === '/') return str.substr(0, str.length - 1);
+    return str;
+};
+
+lib.noneOrAll = function(containerIn, containerOut, attrList) {
+    /**
+     * some attributes come together, so if you have one of them
+     * in the input, you should copy the default values of the others
+     * to the input as well.
+     */
+    if(!containerIn) return;
+
+    var hasAny = false,
+        hasAll = true,
+        i,
+        val;
+
+    for(i = 0; i < attrList.length; i++) {
+        val = containerIn[attrList[i]];
+        if(val !== undefined && val !== null) hasAny = true;
+        else hasAll = false;
+    }
+
+    if(hasAny && !hasAll) {
+        for(i = 0; i < attrList.length; i++) {
+            containerIn[attrList[i]] = containerOut[attrList[i]];
+        }
+    }
+};
+
+lib.mergeArray = function(traceAttr, cd, cdAttr) {
+    if(Array.isArray(traceAttr)) {
+        var imax = Math.min(traceAttr.length, cd.length);
+        for(var i=0; i<imax; i++) cd[i][cdAttr] = traceAttr[i];
+    }
+};
+
+/**
+ * modified version of jQuery's extend to strip out private objs and functions,
+ * and cut arrays down to first <arraylen> or 1 elements
+ * because extend-like algorithms are hella slow
+ * obj2 is assumed to already be clean of these things (including no arrays)
+ */
+lib.minExtend = function(obj1, obj2) {
+    var objOut = {};
+    if(typeof obj2 !== 'object') obj2 = {};
+    var arrayLen = 3,
+        keys = Object.keys(obj1),
+        i,
+        k,
+        v;
+    for(i = 0; i < keys.length; i++) {
+        k = keys[i];
+        v = obj1[k];
+        if(k.charAt(0)==='_' || typeof v === 'function') continue;
+        else if(k==='module') objOut[k] = v;
+        else if(Array.isArray(v)) objOut[k] = v.slice(0,arrayLen);
+        else if(v && (typeof v === 'object')) objOut[k] = lib.minExtend(obj1[k], obj2[k]);
+        else objOut[k] = v;
+    }
+
+    keys = Object.keys(obj2);
+    for(i = 0; i < keys.length; i++) {
+        k = keys[i];
+        v = obj2[k];
+        if(typeof v !== 'object' || !(k in objOut) || typeof objOut[k] !== 'object') {
+            objOut[k] = v;
+        }
+    }
+
+    return objOut;
+};
+
+lib.titleCase = function(s) {
+    return s.charAt(0).toUpperCase() + s.substr(1);
+};
+
+lib.containsAny = function(s, fragments) {
+    for(var i = 0; i < fragments.length; i++) {
+        if(s.indexOf(fragments[i])!== -1) return true;
+    }
+    return false;
+};
+
+// get the parent Plotly plot of any element. Whoo jquery-free tree climbing!
+lib.getPlotDiv = function(el) {
+    for(; el && el.removeAttribute; el = el.parentNode) {
+        if(lib.isPlotDiv(el)) return el;
+    }
+};
+
+lib.isPlotDiv = function(el) {
+    var el3 = d3.select(el);
+    return el3.size() && el3.classed('js-plotly-plot');
+};
+
+lib.removeElement = function(el) {
+    var elParent = el && el.parentNode;
+    if(elParent) elParent.removeChild(el);
+};
+
+/**
+ * for dynamically adding style rules
+ * makes one stylesheet that contains all rules added
+ * by all calls to this function
+ */
+lib.addStyleRule = function(selector, styleString) {
+    if(!lib.styleSheet) {
+        var style = document.createElement('style');
+        // WebKit hack :(
+        style.appendChild(document.createTextNode(''));
+        document.head.appendChild(style);
+        lib.styleSheet = style.sheet;
+    }
+    var styleSheet = lib.styleSheet;
+
+    if(styleSheet.insertRule) {
+        styleSheet.insertRule(selector+'{'+styleString+'}',0);
+    }
+    else if(styleSheet.addRule) {
+        styleSheet.addRule(selector,styleString,0);
+    }
+    else console.warn('addStyleRule failed');
+};
+
+lib.isIE = function() {
+    return typeof window.navigator.msSaveBlob !== 'undefined';
+};
+
+},{"./coerce":342,"./dates":343,"./extend":345,"./is_plain_object":350,"./matrix":351,"./nested_property":352,"./notifier":353,"./search":356,"./stats":358,"d3":70}],350:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+// more info: http://stackoverflow.com/questions/18531624/isplainobject-thing
+module.exports = function isPlainObject(obj) {
+    return (
+        Object.prototype.toString.call(obj) === '[object Object]' &&
+        Object.getPrototypeOf(obj) === Object.prototype
+    );
+};
+
+},{}],351:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+
+exports.init2dArray = function(rowLength, colLength) {
+    var array = new Array(rowLength);
+    for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength);
+    return array;
+};
+
+/**
+ * transpose a (possibly ragged) 2d array z. inspired by
+ * http://stackoverflow.com/questions/17428587/
+ * transposing-a-2d-array-in-javascript
+ */
+exports.transposeRagged = function(z) {
+    var maxlen = 0,
+        zlen = z.length,
+        i,
+        j;
+    // Maximum row length:
+    for(i = 0; i < zlen; i++) maxlen = Math.max(maxlen, z[i].length);
+
+    var t = new Array(maxlen);
+    for(i = 0; i < maxlen; i++) {
+        t[i] = new Array(zlen);
+        for(j = 0; j < zlen; j++) t[i][j] = z[j][i];
+    }
+
+    return t;
+};
+
+// our own dot function so that we don't need to include numeric
+exports.dot = function(x, y) {
+    if(!(x.length && y.length) || x.length !== y.length) return null;
+
+    var len = x.length,
+        out,
+        i;
+
+    if(x[0].length) {
+        // mat-vec or mat-mat
+        out = new Array(len);
+        for(i = 0; i < len; i++) out[i] = exports.dot(x[i], y);
+    }
+    else if(y[0].length) {
+        // vec-mat
+        var yTranspose = exports.transposeRagged(y);
+        out = new Array(yTranspose.length);
+        for(i = 0; i < yTranspose.length; i++) out[i] = exports.dot(x, yTranspose[i]);
+    }
+    else {
+        // vec-vec
+        out = 0;
+        for(i = 0; i < len; i++) out += x[i] * y[i];
+    }
+
+    return out;
+};
+
+// translate by (x,y)
+exports.translationMatrix = function(x, y) {
+    return [[1, 0, x], [0, 1, y], [0, 0, 1]];
+};
+
+// rotate by alpha around (0,0)
+exports.rotationMatrix = function(alpha) {
+    var a = alpha*Math.PI/180;
+    return [[Math.cos(a), -Math.sin(a), 0],
+            [Math.sin(a), Math.cos(a), 0],
+            [0, 0, 1]];
+};
+
+// rotate by alpha around (x,y)
+exports.rotationXYMatrix = function(a, x, y) {
+    return exports.dot(
+        exports.dot(exports.translationMatrix(x, y),
+                    exports.rotationMatrix(a)),
+        exports.translationMatrix(-x, -y));
+};
+
+// applies a 2D transformation matrix to either x and y params or an [x,y] array
+exports.apply2DTransform = function(transform) {
+    return function() {
+        var args = arguments;
+        if(args.length === 3) {
+            args = args[0];
+        }//from map
+        var xy = arguments.length === 1 ? args[0] : [args[0], args[1]];
+        return exports.dot(transform, [xy[0], xy[1], 1]).slice(0, 2);
+    };
+};
+
+// applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment)
+exports.apply2DTransform2 = function(transform) {
+    var at = exports.apply2DTransform(transform);
+    return function(xys) {
+        return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4)));
+    };
+};
+
+},{}],352:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+/**
+ * convert a string s (such as 'xaxis.range[0]')
+ * representing a property of nested object into set and get methods
+ * also return the string and object so we don't have to keep track of them
+ * allows [-1] for an array index, to set a property inside all elements
+ * of an array
+ * eg if obj = {arr: [{a: 1}, {a: 2}]}
+ * you can do p = nestedProperty(obj, 'arr[-1].a')
+ * but you cannot set the array itself this way, to do that
+ * just set the whole array.
+ * eg if obj = {arr: [1, 2, 3]}
+ * you can't do nestedProperty(obj, 'arr[-1]').set(5)
+ * but you can do nestedProperty(obj, 'arr').set([5, 5, 5])
+ */
+module.exports = function nestedProperty(container, propStr) {
+    if(isNumeric(propStr)) propStr = String(propStr);
+    else if(typeof propStr !== 'string' ||
+            propStr.substr(propStr.length - 4) === '[-1]') {
+        throw 'bad property string';
+    }
+
+    var j = 0,
+        propParts = propStr.split('.'),
+        indexed,
+        indices,
+        i;
+
+    // check for parts of the nesting hierarchy that are numbers (ie array elements)
+    while(j < propParts.length) {
+        // look for non-bracket chars, then any number of [##] blocks
+        indexed = String(propParts[j]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/);
+        if(indexed) {
+            if(indexed[1]) propParts[j] = indexed[1];
+            // allow propStr to start with bracketed array indices
+            else if(j === 0) propParts.splice(0,1);
+            else throw 'bad property string';
+
+            indices = indexed[2]
+                .substr(1,indexed[2].length-2)
+                .split('][');
+
+            for(i=0; i<indices.length; i++) {
+                j++;
+                propParts.splice(j,0,Number(indices[i]));
+            }
+        }
+        j++;
+    }
+
+    if(typeof container !== 'object') {
+        return badContainer(container, propStr, propParts);
+    }
+
+    return {
+        set: npSet(container, propParts),
+        get: npGet(container, propParts),
+        astr: propStr,
+        parts: propParts,
+        obj: container
+    };
+};
+
+function npGet(cont, parts) {
+    return function() {
+        var curCont = cont,
+            curPart,
+            allSame,
+            out,
+            i,
+            j;
+
+        for(i = 0; i < parts.length - 1; i++) {
+            curPart = parts[i];
+            if(curPart===-1) {
+                allSame = true;
+                out = [];
+                for(j = 0; j < curCont.length; j++) {
+                    out[j] = npGet(curCont[j], parts.slice(i + 1))();
+                    if(out[j]!==out[0]) allSame = false;
+                }
+                return allSame ? out[0] : out;
+            }
+            if(typeof curPart === 'number' && !Array.isArray(curCont)) {
+                return undefined;
+            }
+            curCont = curCont[curPart];
+            if(typeof curCont !== 'object' || curCont === null) {
+                return undefined;
+            }
+        }
+
+        // only hit this if parts.length === 1
+        if(typeof curCont !== 'object' || curCont === null) return undefined;
+
+        out = curCont[parts[i]];
+        if(out === null) return undefined;
+        return out;
+    };
+}
+
+/*
+ * Check known non-data-array arrays (containers). Data arrays only contain scalars,
+ * so parts[end] values, such as -1 or n, indicate we are not dealing with a dataArray.
+ * The ONLY case we are looking for is where the entire array is selected, parts[end] === 'x'
+ * AND the replacement value is an array.
+ */
+function isDataArray(val, key) {
+
+    var containers = ['annotations', 'shapes', 'range', 'domain'],
+        isNotAContainer = containers.indexOf(key) === -1;
+
+    return Array.isArray(val) && isNotAContainer;
+}
+
+function npSet(cont, parts) {
+    return function(val) {
+        var curCont = cont,
+            containerLevels = [cont],
+            toDelete = emptyObj(val) && !isDataArray(val, parts[parts.length-1]),
+            curPart,
+            i;
+
+        for(i = 0; i < parts.length - 1; i++) {
+            curPart = parts[i];
+
+            if(typeof curPart === 'number' && !Array.isArray(curCont)) {
+                throw 'array index but container is not an array';
+            }
+
+            // handle special -1 array index
+            if(curPart===-1) {
+                toDelete = !setArrayAll(curCont, parts.slice(i + 1), val);
+                if(toDelete) break;
+                else return;
+            }
+
+            if(!checkNewContainer(curCont, curPart, parts[i + 1], toDelete)) {
+                break;
+            }
+
+            curCont = curCont[curPart];
+
+            if(typeof curCont !== 'object' || curCont === null) {
+                throw 'container is not an object';
+            }
+
+            containerLevels.push(curCont);
+        }
+
+        if(toDelete) {
+            if(i === parts.length - 1) delete curCont[parts[i]];
+            pruneContainers(containerLevels);
+        }
+        else curCont[parts[i]] = val;
+    };
+}
+
+// handle special -1 array index
+function setArrayAll(containerArray, innerParts, val) {
+    var arrayVal = Array.isArray(val),
+        allSet = true,
+        thisVal = val,
+        deleteThis = arrayVal ? false : emptyObj(val),
+        firstPart = innerParts[0],
+        i;
+
+    for(i = 0; i < containerArray.length; i++) {
+        if(arrayVal) {
+            thisVal = val[i % val.length];
+            deleteThis = emptyObj(thisVal);
+        }
+        if(deleteThis) allSet = false;
+        if(!checkNewContainer(containerArray, i, firstPart, deleteThis)) {
+            continue;
+        }
+        npSet(containerArray[i], innerParts)(thisVal);
+    }
+    return allSet;
+}
+
+/**
+ * make new sub-container as needed.
+ * returns false if there's no container and none is needed
+ * because we're only deleting an attribute
+ */
+function checkNewContainer(container, part, nextPart, toDelete) {
+    if(container[part] === undefined) {
+        if(toDelete) return false;
+
+        if(typeof nextPart === 'number') container[part] = [];
+        else container[part] = {};
+    }
+    return true;
+}
+
+function pruneContainers(containerLevels) {
+    var i,
+        j,
+        curCont,
+        keys,
+        remainingKeys;
+    for(i = containerLevels.length - 1; i >= 0; i--) {
+        curCont = containerLevels[i];
+        remainingKeys = false;
+        if(Array.isArray(curCont)) {
+            for(j = curCont.length - 1; j >= 0; j--) {
+                if(emptyObj(curCont[j])) {
+                    if(remainingKeys) curCont[j] = undefined;
+                    else curCont.pop();
+                }
+                else remainingKeys = true;
+            }
+        }
+        else if(typeof curCont === 'object' && curCont !== null) {
+            keys = Object.keys(curCont);
+            remainingKeys = false;
+            for(j = keys.length - 1; j >= 0; j--) {
+                if(emptyObj(curCont[keys[j]]) && !isDataArray(curCont[keys[j]], keys[j])) delete curCont[keys[j]];
+                else remainingKeys = true;
+            }
+        }
+        if(remainingKeys) return;
+    }
+}
+
+function emptyObj(obj) {
+    if(obj===undefined || obj===null) return true;
+    if(typeof obj !== 'object') return false; // any plain value
+    if(Array.isArray(obj)) return !obj.length; // []
+    return !Object.keys(obj).length; // {}
+}
+
+function badContainer(container, propStr, propParts) {
+    return {
+        set: function() { throw 'bad container'; },
+        get: function() {},
+        astr: propStr,
+        parts: propParts,
+        obj: container
+    };
+}
+
+},{"fast-isnumeric":74}],353:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var isNumeric = require('fast-isnumeric');
+
+var NOTEDATA = [];
+
+/**
+ * notifier
+ * @param {String} text The person's user name
+ * @param {Number} [delay=1000] The delay time in milliseconds
+ *          or 'long' which provides 2000 ms delay time.
+ * @return {undefined} this function does not return a value
+ */
+module.exports = function(text, displayLength) {
+    if(NOTEDATA.indexOf(text) !== -1) return;
+
+    NOTEDATA.push(text);
+
+    var ts = 1000;
+    if(isNumeric(displayLength)) ts = displayLength;
+    else if(displayLength === 'long') ts = 3000;
+
+    var notifierContainer = d3.select('body')
+        .selectAll('.plotly-notifier')
+        .data([0]);
+    notifierContainer.enter()
+        .append('div')
+        .classed('plotly-notifier', true);
+
+    var notes = notifierContainer.selectAll('.notifier-note').data(NOTEDATA);
+
+    function killNote(transition) {
+        transition
+            .duration(700)
+            .style('opacity', 0)
+            .each('end', function(thisText) {
+                var thisIndex = NOTEDATA.indexOf(thisText);
+                if(thisIndex !== -1) NOTEDATA.splice(thisIndex, 1);
+                d3.select(this).remove();
+            });
+    }
+
+    notes.enter().append('div')
+        .classed('notifier-note', true)
+        .style('opacity', 0)
+        .each(function(thisText) {
+            var note = d3.select(this);
+
+            note.append('button')
+                .classed('notifier-close', true)
+                .html('&times;')
+                .on('click', function() {
+                    note.transition().call(killNote);
+                });
+
+            note.append('p').html(thisText);
+
+            note.transition()
+                    .duration(700)
+                    .style('opacity', 1)
+                .transition()
+                    .delay(ts)
+                    .call(killNote);
+        });
+};
+
+},{"d3":70,"fast-isnumeric":74}],354:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var dot = require('./matrix').dot;
+
+var polygon = module.exports = {};
+
+/**
+ * Turn an array of [x, y] pairs into a polygon object
+ * that can test if points are inside it
+ *
+ * @param ptsIn Array of [x, y] pairs
+ *
+ * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains}
+ *      (x|y)(min|max) are the bounding rect of the polygon
+ *      pts is the original array, with the first pair repeated at the end
+ *      contains is a function: (pt, omitFirstEdge)
+ *          pt is the [x, y] pair to test
+ *          omitFirstEdge truthy means points exactly on the first edge don't
+ *              count. This is for use adding one polygon to another so we
+ *              don't double-count the edge where they meet.
+ *          returns boolean: is pt inside the polygon (including on its edges)
+ */
+polygon.tester = function tester(ptsIn) {
+    var pts = ptsIn.slice(),
+        xmin = pts[0][0],
+        xmax = xmin,
+        ymin = pts[0][1],
+        ymax = ymin;
+
+    pts.push(pts[0]);
+    for(var i = 1; i < pts.length; i++) {
+        xmin = Math.min(xmin, pts[i][0]);
+        xmax = Math.max(xmax, pts[i][0]);
+        ymin = Math.min(ymin, pts[i][1]);
+        ymax = Math.max(ymax, pts[i][1]);
+    }
+
+    // do we have a rectangle? Handle this here, so we can use the same
+    // tester for the rectangular case without sacrificing speed
+
+    var isRect = false,
+        rectFirstEdgeTest;
+
+    if(pts.length === 5) {
+        if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz
+            if(pts[2][0] === pts[3][0] &&
+                    pts[0][1] === pts[3][1] &&
+                    pts[1][1] === pts[2][1]) {
+                isRect = true;
+                rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; };
+            }
+        }
+        else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert
+            if(pts[2][1] === pts[3][1] &&
+                    pts[0][0] === pts[3][0] &&
+                    pts[1][0] === pts[2][0]) {
+                isRect = true;
+                rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; };
+            }
+        }
+    }
+
+    function rectContains(pt, omitFirstEdge) {
+        var x = pt[0],
+            y = pt[1];
+
+        if(x < xmin || x > xmax || y < ymin || y > ymax) {
+            // pt is outside the bounding box of polygon
+            return false;
+        }
+        if(omitFirstEdge && rectFirstEdgeTest(pt)) return false;
+
+        return true;
+    }
+
+    function contains(pt, omitFirstEdge) {
+        var x = pt[0],
+            y = pt[1];
+
+        if(x < xmin || x > xmax || y < ymin || y > ymax) {
+            // pt is outside the bounding box of polygon
+            return false;
+        }
+
+        var imax = pts.length,
+            x1 = pts[0][0],
+            y1 = pts[0][1],
+            crossings = 0,
+            i,
+            x0,
+            y0,
+            xmini,
+            ycross;
+
+        for(i = 1; i < imax; i++) {
+            // find all crossings of a vertical line upward from pt with
+            // polygon segments
+            // crossings exactly at xmax don't count, unless the point is
+            // exactly on the segment, then it counts as inside.
+            x0 = x1;
+            y0 = y1;
+            x1 = pts[i][0];
+            y1 = pts[i][1];
+            xmini = Math.min(x0, x1);
+
+            // outside the bounding box of this segment, it's only a crossing
+            // if it's below the box.
+            if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) {
+                continue;
+            }
+            else if(y < Math.min(y0, y1)) {
+                // don't count the left-most point of the segment as a crossing
+                // because we don't want to double-count adjacent crossings
+                // UNLESS the polygon turns past vertical at exactly this x
+                // Note that this is repeated below, but we can't factor it out
+                // because
+                if(x !== xmini) crossings++;
+            }
+            // inside the bounding box, check the actual line intercept
+            else {
+                // vertical segment - we know already that the point is exactly
+                // on the segment, so mark the crossing as exactly at the point.
+                if(x1 === x0) ycross = y;
+                // any other angle
+                else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0);
+
+                // exactly on the edge: counts as inside the polygon, unless it's the
+                // first edge and we're omitting it.
+                if(y === ycross) {
+                    if(i === 1 && omitFirstEdge) return false;
+                    return true;
+                }
+
+                if(y <= ycross && x !== xmini) crossings++;
+            }
+        }
+
+        // if we've gotten this far, odd crossings means inside, even is outside
+        return crossings % 2 === 1;
+    }
+
+    return {
+        xmin: xmin,
+        xmax: xmax,
+        ymin: ymin,
+        ymax: ymax,
+        pts: pts,
+        contains: isRect ? rectContains : contains,
+        isRect: isRect
+    };
+};
+
+/**
+ * Test if a segment of a points array is bent or straight
+ *
+ * @param pts Array of [x, y] pairs
+ * @param start the index of the proposed start of the straight section
+ * @param end the index of the proposed end point
+ * @param tolerance the max distance off the line connecting start and end
+ *      before the line counts as bent
+ * @returns boolean: true means this segment is bent, false means straight
+ */
+var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) {
+    var startPt = pts[start],
+        segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]],
+        segmentSquared = dot(segment, segment),
+        segmentLen = Math.sqrt(segmentSquared),
+        unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen],
+        i,
+        part,
+        partParallel;
+
+    for(i = start + 1; i < end; i++) {
+        part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]];
+        partParallel = dot(part, segment);
+
+        if(partParallel < 0 || partParallel > segmentSquared ||
+            Math.abs(dot(part, unitPerp)) > tolerance) return true;
+    }
+    return false;
+};
+
+/**
+ * Make a filtering polygon, to minimize the number of segments
+ *
+ * @param pts Array of [x, y] pairs (must start with at least 1 pair)
+ * @param tolerance the maximum deviation from straight allowed for
+ *      removing points to simplify the polygon
+ *
+ * @returns Object {addPt, raw, filtered}
+ *      addPt is a function(pt: [x, y] pair) to add a raw point and
+ *          continue filtering
+ *      raw is all the input points
+ *      filtered is the resulting filtered Array of [x, y] pairs
+ */
+polygon.filter = function filter(pts, tolerance) {
+    var ptsFiltered = [pts[0]],
+        doneRawIndex = 0,
+        doneFilteredIndex = 0;
+
+    function addPt(pt) {
+        pts.push(pt);
+        var prevFilterLen = ptsFiltered.length,
+            iLast = doneRawIndex;
+        ptsFiltered.splice(doneFilteredIndex + 1);
+
+        for(var i = iLast + 1; i < pts.length; i++) {
+            if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) {
+                ptsFiltered.push(pts[i]);
+                if(ptsFiltered.length < prevFilterLen - 2) {
+                    doneRawIndex = i;
+                    doneFilteredIndex = ptsFiltered.length - 1;
+                }
+                iLast = i;
+            }
+        }
+    }
+
+    if(pts.length > 1) {
+        var lastPt = pts.pop();
+        addPt(lastPt);
+    }
+
+    return {
+        addPt: addPt,
+        raw: pts,
+        filtered: ptsFiltered
+    };
+};
+
+},{"./matrix":351}],355:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../plotly');
+
+/**
+ * Copy arg array *without* removing `undefined` values from objects.
+ *
+ * @param gd
+ * @param args
+ * @returns {Array}
+ */
+function copyArgArray(gd, args) {
+    var copy = [];
+    var arg;
+
+    for(var i = 0; i < args.length; i++) {
+        arg = args[i];
+
+        if(arg === gd) copy[i] = arg;
+        else if(typeof arg === 'object') {
+            copy[i] = Array.isArray(arg) ?
+                Plotly.Lib.extendDeep([], arg) :
+                Plotly.Lib.extendDeepAll({}, arg);
+        }
+        else copy[i] = arg;
+    }
+
+    return copy;
+}
+
+
+// -----------------------------------------------------
+// Undo/Redo queue for plots
+// -----------------------------------------------------
+
+
+var queue = {};
+
+// TODO: disable/enable undo and redo buttons appropriately
+
+/**
+ * Add an item to the undoQueue for a graphDiv
+ *
+ * @param gd
+ * @param undoFunc Function undo this operation
+ * @param undoArgs Args to supply undoFunc with
+ * @param redoFunc Function to redo this operation
+ * @param redoArgs Args to supply redoFunc with
+ */
+queue.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) {
+    var queueObj,
+        queueIndex;
+
+    // make sure we have the queue and our position in it
+    gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
+    queueIndex = gd.undoQueue.index;
+
+    // if we're already playing an undo or redo, or if this is an auto operation
+    // (like pane resize... any others?) then we don't save this to the undo queue
+    if(gd.autoplay) {
+        if(!gd.undoQueue.inSequence) gd.autoplay = false;
+        return;
+    }
+
+    // if we're not in a sequence or are just starting, we need a new queue item
+    if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) {
+        queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}};
+        gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj);
+        gd.undoQueue.index += 1;
+    } else {
+        queueObj = gd.undoQueue.queue[queueIndex - 1];
+    }
+    gd.undoQueue.beginSequence = false;
+
+    // we unshift to handle calls for undo in a forward for loop later
+    queueObj.undo.calls.unshift(undoFunc);
+    queueObj.undo.args.unshift(undoArgs);
+    queueObj.redo.calls.push(redoFunc);
+    queueObj.redo.args.push(redoArgs);
+
+};
+
+/**
+ * Begin a sequence of undoQueue changes
+ *
+ * @param gd
+ */
+queue.startSequence = function(gd) {
+    gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
+    gd.undoQueue.sequence = true;
+    gd.undoQueue.beginSequence = true;
+};
+
+/**
+ * Stop a sequence of undoQueue changes
+ *
+ * Call this *after* you're sure your undo chain has ended
+ *
+ * @param gd
+ */
+queue.stopSequence = function(gd) {
+    gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
+    gd.undoQueue.sequence = false;
+    gd.undoQueue.beginSequence = false;
+};
+
+/**
+ * Move one step back in the undo queue, and undo the object there.
+ *
+ * @param gd
+ */
+queue.undo = function undo(gd) {
+    var queueObj, i;
+
+    if(gd.framework && gd.framework.isPolar) {
+        gd.framework.undo();
+        return;
+    }
+    if(gd.undoQueue === undefined ||
+            isNaN(gd.undoQueue.index) ||
+            gd.undoQueue.index <= 0) {
+        return;
+    }
+
+    // index is pointing to next *forward* queueObj, point to the one we're undoing
+    gd.undoQueue.index--;
+
+    // get the queueObj for instructions on how to undo
+    queueObj = gd.undoQueue.queue[gd.undoQueue.index];
+
+    // this sequence keeps things from adding to the queue during undo/redo
+    gd.undoQueue.inSequence = true;
+    for(i = 0; i < queueObj.undo.calls.length; i++) {
+        queue.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]);
+    }
+    gd.undoQueue.inSequence = false;
+    gd.autoplay = false;
+};
+
+/**
+ * Redo the current object in the undo, then move forward in the queue.
+ *
+ * @param gd
+ */
+queue.redo = function redo(gd) {
+    var queueObj, i;
+
+    if(gd.framework && gd.framework.isPolar) {
+        gd.framework.redo();
+        return;
+    }
+    if(gd.undoQueue === undefined ||
+            isNaN(gd.undoQueue.index) ||
+            gd.undoQueue.index >= gd.undoQueue.queue.length) {
+        return;
+    }
+
+    // get the queueObj for instructions on how to undo
+    queueObj = gd.undoQueue.queue[gd.undoQueue.index];
+
+    // this sequence keeps things from adding to the queue during undo/redo
+    gd.undoQueue.inSequence = true;
+    for(i = 0; i < queueObj.redo.calls.length; i++) {
+        queue.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]);
+    }
+    gd.undoQueue.inSequence = false;
+    gd.autoplay = false;
+
+    // index is pointing to the thing we just redid, move it
+    gd.undoQueue.index++;
+};
+
+/**
+ * Called by undo/redo to make the actual changes.
+ *
+ * Not meant to be called publically, but included for mocking out in tests.
+ *
+ * @param gd
+ * @param func
+ * @param args
+ */
+queue.plotDo = function(gd, func, args) {
+    gd.autoplay = true;
+
+    // this *won't* copy gd and it preserves `undefined` properties!
+    args = copyArgArray(gd, args);
+
+    // call the supplied function
+    func.apply(null, args);
+};
+
+module.exports = queue;
+
+},{"../plotly":366}],356:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+
+/**
+ * findBin - find the bin for val - note that it can return outside the
+ * bin range any pos. or neg. integer for linear bins, or -1 or
+ * bins.length-1 for explicit.
+ * bins is either an object {start,size,end} or an array length #bins+1
+ * bins can be either increasing or decreasing but must be monotonic
+ * for linear bins, we can just calculate. For listed bins, run a binary
+ * search linelow (truthy) says the bin boundary should be attributed to
+ * the lower bin rather than the default upper bin
+ */
+exports.findBin = function(val, bins, linelow) {
+    if(isNumeric(bins.start)) {
+        return linelow ?
+            Math.ceil((val - bins.start) / bins.size) - 1 :
+            Math.floor((val - bins.start) / bins.size);
+    }
+    else {
+        var n1 = 0,
+            n2 = bins.length,
+            c = 0,
+            n,
+            test;
+        if(bins[bins.length - 1] >= bins[0]) {
+            test = linelow ? lessThan : lessOrEqual;
+        } else {
+            test = linelow ? greaterOrEqual : greaterThan;
+        }
+        // c is just to avoid infinite loops if there's an error
+        while(n1 < n2 && c++ < 100) {
+            n = Math.floor((n1 + n2) / 2);
+            if(test(bins[n], val)) n1 = n + 1;
+            else n2 = n;
+        }
+        if(c > 90) console.log('Long binary search...');
+        return n1 - 1;
+    }
+};
+
+function lessThan(a, b) { return a < b; }
+function lessOrEqual(a, b) { return a <= b; }
+function greaterThan(a, b) { return a > b; }
+function greaterOrEqual(a, b) { return a >= b; }
+
+exports.sorterAsc = function(a, b) { return a - b; };
+exports.sorterDes = function(a, b) { return b - a; };
+
+/**
+ * find distinct values in an array, lumping together ones that appear to
+ * just be off by a rounding error
+ * return the distinct values and the minimum difference between any two
+ */
+exports.distinctVals = function(valsIn) {
+    var vals = valsIn.slice();  // otherwise we sort the original array...
+    vals.sort(exports.sorterAsc);
+
+    var l = vals.length - 1,
+        minDiff = (vals[l] - vals[0]) || 1,
+        errDiff = minDiff / (l || 1) / 10000,
+        v2 = [vals[0]];
+
+    for(var i = 0; i < l; i++) {
+        // make sure values aren't just off by a rounding error
+        if(vals[i + 1] > vals[i] + errDiff) {
+            minDiff = Math.min(minDiff, vals[i + 1] - vals[i]);
+            v2.push(vals[i + 1]);
+        }
+    }
+
+    return {vals: v2, minDiff: minDiff};
+};
+
+/**
+ * return the smallest element from (sorted) array arrayIn that's bigger than val,
+ * or (reverse) the largest element smaller than val
+ * used to find the best tick given the minimum (non-rounded) tick
+ * particularly useful for date/time where things are not powers of 10
+ * binary search is probably overkill here...
+ */
+exports.roundUp = function(val, arrayIn, reverse) {
+    var low = 0,
+        high = arrayIn.length - 1,
+        mid,
+        c = 0,
+        dlow = reverse ? 0 : 1,
+        dhigh = reverse ? 1 : 0,
+        rounded = reverse ? Math.ceil : Math.floor;
+    // c is just to avoid infinite loops if there's an error
+    while(low < high && c++ < 100) {
+        mid = rounded((low + high) / 2);
+        if(arrayIn[mid] <= val) low = mid + dlow;
+        else high = mid - dhigh;
+    }
+    return arrayIn[low];
+};
+
+},{"fast-isnumeric":74}],357:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../plotly');
+
+var noop = function() {};
+
+
+/**
+ * Prints a no webgl error message into the scene container
+ * @param {scene instance} scene
+ *
+ * Expects 'scene' to have property 'container'
+ *
+ */
+module.exports = function showWebGlMsg(scene) {
+    for(var prop in scene) {
+        if(typeof scene[prop] === 'function') scene[prop] = noop;
+    }
+
+    scene.destroy = function() {
+        scene.container.parentNode.removeChild(scene.container);
+    };
+
+    var div = document.createElement('div');
+    div.textContent = 'Webgl is not supported by your browser - visit http://get.webgl.org for more info';
+    div.style.cursor = 'pointer';
+    div.style.fontSize = '24px';
+    div.style.color = Plotly.Color.defaults[0];
+
+    scene.container.appendChild(div);
+    scene.container.style.background = '#FFFFFF';
+    scene.container.onclick = function() {
+        window.open('http://get.webgl.org');
+    };
+
+    // return before setting up camera and onrender methods
+    return false;
+};
+
+},{"../plotly":366}],358:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+
+/**
+ * aggNums() returns the result of an aggregate function applied to an array of
+ * values, where non-numerical values have been tossed out.
+ *
+ * @param {function} f - aggregation function (e.g., Math.min)
+ * @param {Number} v - initial value (continuing from previous calls)
+ *      if there's no continuing value, use null for selector-type
+ *      functions (max,min), or 0 for summations
+ * @param {Array} a - array to aggregate (may be nested, we will recurse,
+ *                    but all elements must have the same dimension)
+ * @param {Number} len - maximum length of a to aggregate
+ * @return {Number} - result of f applied to a starting from v
+ */
+exports.aggNums = function(f, v, a, len) {
+    var i,
+        b;
+    if(!len) len = a.length;
+    if(!isNumeric(v)) v = false;
+    if(Array.isArray(a[0])) {
+        b = new Array(len);
+        for(i = 0; i < len; i++) b[i] = exports.aggNums(f, v, a[i]);
+        a = b;
+    }
+
+    for(i = 0; i < len; i++) {
+        if(!isNumeric(v)) v = a[i];
+        else if(isNumeric(a[i])) v = f(+v, +a[i]);
+    }
+    return v;
+};
+
+/**
+ * mean & std dev functions using aggNums, so it handles non-numerics nicely
+ * even need to use aggNums instead of .length, to toss out non-numerics
+ */
+exports.len = function(data) {
+    return exports.aggNums(function(a) { return a + 1; }, 0, data);
+};
+
+exports.mean = function(data, len) {
+    if(!len) len = exports.len(data);
+    return exports.aggNums(function(a, b) { return a + b; }, 0, data) / len;
+};
+
+exports.variance = function(data, len, mean) {
+    if(!len) len = exports.len(data);
+    if(!isNumeric(mean)) mean = exports.mean(data, len);
+
+    return exports.aggNums(function(a, b) {
+        return a + Math.pow(b - mean, 2);
+    }, 0, data)/len;
+};
+
+exports.stdev = function(data, len, mean) {
+    return Math.sqrt(exports.variance(data, len, mean));
+};
+
+/**
+ * interp() computes a percentile (quantile) for a given distribution.
+ * We interpolate the distribution (to compute quantiles, we follow method #10 here:
+ * http://www.amstat.org/publications/jse/v14n3/langford.html).
+ * Typically the index or rank (n * arr.length) may be non-integer.
+ * For reference: ends are clipped to the extreme values in the array;
+ * For box plots: index you get is half a point too high (see
+ * http://en.wikipedia.org/wiki/Percentile#Nearest_rank) but note that this definition
+ * indexes from 1 rather than 0, so we subtract 1/2 (instead of add).
+ *
+ * @param {Array} arr - This array contains the values that make up the distribution.
+ * @param {Number} n - Between 0 and 1, n = p/100 is such that we compute the p^th percentile.
+ * For example, the 50th percentile (or median) corresponds to n = 0.5
+ * @return {Number} - percentile
+ */
+exports.interp = function(arr, n) {
+    if(!isNumeric(n)) throw 'n should be a finite number';
+    n = n * arr.length - 0.5;
+    if(n < 0) return arr[0];
+    if(n > arr.length - 1) return arr[arr.length - 1];
+    var frac = n % 1;
+    return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)];
+};
+
+},{"fast-isnumeric":74}],359:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var tinycolor = require('tinycolor2');
+var arrtools = require('arraytools');
+
+function str2RgbaArray(color) {
+    color = tinycolor(color);
+    return arrtools.str2RgbaArray(color.toRgbString());
+}
+
+module.exports = str2RgbaArray;
+
+},{"arraytools":48,"tinycolor2":229}],360:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+/* global MathJax:false */
+
+var Plotly = require('../plotly');
+var d3 = require('d3');
+
+var xmlnsNamespaces = require('../constants/xmlns_namespaces');
+
+var util = module.exports = {};
+
+// Append SVG
+
+d3.selection.prototype.appendSVG = function(_svgString) {
+    var skeleton = [
+        '<svg xmlns="', xmlnsNamespaces.svg, '" ',
+        'xmlns:xlink="', xmlnsNamespaces.xlink, '">',
+        _svgString,
+        '</svg>'
+    ].join('');
+
+    var dom = new DOMParser().parseFromString(skeleton, 'application/xml'),
+        childNode = dom.documentElement.firstChild;
+
+    while(childNode) {
+        this.node().appendChild(this.node().ownerDocument.importNode(childNode, true));
+        childNode = childNode.nextSibling;
+    }
+    if(dom.querySelector('parsererror')) {
+        console.log(dom.querySelector('parsererror div').textContent);
+        return null;
+    }
+    return d3.select(this.node().lastChild);
+};
+
+// Text utilities
+
+util.html_entity_decode = function(s) {
+    var hiddenDiv = d3.select('body').append('div').style({display: 'none'}).html('');
+    var replaced = s.replace(/(&[^;]*;)/gi, function(d) {
+        if(d==='&lt;') { return '&#60;'; } // special handling for brackets
+        if(d==='&rt;') { return '&#62;'; }
+        return hiddenDiv.html(d).text(); // everything else, let the browser decode it to unicode
+    });
+    hiddenDiv.remove();
+    return replaced;
+};
+
+util.xml_entity_encode = function(str) {
+    return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,'&amp;');
+};
+
+// text converter
+
+function getSize(_selection, _dimension) {
+    return _selection.node().getBoundingClientRect()[_dimension];
+}
+
+util.convertToTspans = function(_context, _callback) {
+    var str = _context.text();
+    var converted = convertToSVG(str);
+    var that = _context;
+    // Until we get tex integrated more fully (so it can be used along with non-tex)
+    // allow some elements to prohibit it by attaching 'data-notex' to the original
+    var tex = (!that.attr('data-notex')) && converted.match(/([^$]*)([$]+[^$]*[$]+)([^$]*)/);
+    var result = str;
+    var parent = d3.select(that.node().parentNode);
+    if(parent.empty()) return;
+    var svgClass = (that.attr('class')) ? that.attr('class').split(' ')[0] : 'text';
+    svgClass += '-math';
+    parent.selectAll('svg.' + svgClass).remove();
+    parent.selectAll('g.' + svgClass + '-group').remove();
+    _context.style({visibility: null});
+    for(var up = _context.node(); up && up.removeAttribute; up = up.parentNode) {
+        up.removeAttribute('data-bb');
+    }
+
+    function showText() {
+        if(!parent.empty()) {
+            svgClass = that.attr('class') + '-math';
+            parent.select('svg.' + svgClass).remove();
+        }
+        _context.text('')
+            .style({
+                visibility: 'visible',
+                'white-space': 'pre'
+            });
+        result = _context.appendSVG(converted);
+        if(!result) _context.text(str);
+        if(_context.select('a').size()) {
+            // at least in Chrome, pointer-events does not seem
+            // to be honored in children of <text> elements
+            // so if we have an anchor, we have to make the
+            // whole element respond
+            _context.style('pointer-events', 'all');
+        }
+
+        if(_callback) _callback.call(that);
+    }
+
+    if(tex) {
+        var td = Plotly.Lib.getPlotDiv(that.node());
+        ((td && td._promises)||[]).push(new Promise(function(resolve) {
+            that.style({visibility: 'hidden'});
+            var config = {fontSize: parseInt(that.style('font-size'), 10)};
+
+            texToSVG(tex[2], config, function(_svgEl, _glyphDefs, _svgBBox) {
+                parent.selectAll('svg.' + svgClass).remove();
+                parent.selectAll('g.' + svgClass + '-group').remove();
+
+                var newSvg = _svgEl && _svgEl.select('svg');
+                if(!newSvg || !newSvg.node()) {
+                    showText();
+                    resolve();
+                    return;
+                }
+
+                var mathjaxGroup = parent.append('g')
+                    .classed(svgClass + '-group', true)
+                    .attr({'pointer-events': 'none'});
+
+                mathjaxGroup.node().appendChild(newSvg.node());
+
+                // stitch the glyph defs
+                if(_glyphDefs && _glyphDefs.node()) {
+                    newSvg.node().insertBefore(_glyphDefs.node().cloneNode(true),
+                                               newSvg.node().firstChild);
+                }
+
+                newSvg.attr({
+                    'class': svgClass,
+                    height: _svgBBox.height,
+                    preserveAspectRatio: 'xMinYMin meet'
+                })
+                .style({overflow: 'visible', 'pointer-events': 'none'});
+
+                var fill = that.style('fill') || 'black';
+                newSvg.select('g').attr({fill: fill, stroke: fill});
+
+                var newSvgW = getSize(newSvg, 'width'),
+                    newSvgH = getSize(newSvg, 'height'),
+                    newX = +that.attr('x') - newSvgW *
+                        {start: 0, middle: 0.5, end: 1}[that.attr('text-anchor') || 'start'],
+                    // font baseline is about 1/4 fontSize below centerline
+                    textHeight = parseInt(that.style('font-size'), 10) ||
+                        getSize(that, 'height'),
+                    dy = -textHeight/4;
+
+                if(svgClass[0] === 'y') {
+                    mathjaxGroup.attr({
+                        transform: 'rotate(' + [-90, +that.attr('x'), +that.attr('y')] +
+                        ') translate(' + [-newSvgW / 2, dy - newSvgH / 2] + ')'
+                    });
+                    newSvg.attr({x: +that.attr('x'), y: +that.attr('y')});
+                }
+                else if(svgClass[0] === 'l') {
+                    newSvg.attr({x: that.attr('x'), y: dy - (newSvgH / 2)});
+                }
+                else if(svgClass[0] === 'a') {
+                    newSvg.attr({x: 0, y: dy});
+                }
+                else {
+                    newSvg.attr({x: newX, y: (+that.attr('y') + dy - newSvgH / 2)});
+                }
+
+                if(_callback) _callback.call(that, mathjaxGroup);
+                resolve(mathjaxGroup);
+            });
+        }));
+    }
+    else showText();
+
+    return _context;
+};
+
+
+// MathJax
+
+function cleanEscapesForTex(s) {
+    return s.replace(/(<|&lt;|&#60;)/g, '\\lt ')
+        .replace(/(>|&gt;|&#62;)/g, '\\gt ');
+}
+
+function texToSVG(_texString, _config, _callback) {
+    var randomID = 'math-output-' + Plotly.Lib.randstr([],64);
+    var tmpDiv = d3.select('body').append('div')
+        .attr({id: randomID})
+        .style({visibility: 'hidden', position: 'absolute'})
+        .style({'font-size': _config.fontSize + 'px'})
+        .text(cleanEscapesForTex(_texString));
+
+    MathJax.Hub.Queue(['Typeset', MathJax.Hub, tmpDiv.node()], function() {
+        var glyphDefs = d3.select('body').select('#MathJax_SVG_glyphs');
+
+        if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) {
+            console.log('There was an error in the tex syntax.', _texString);
+            _callback();
+        }
+        else {
+            var svgBBox = tmpDiv.select('svg').node().getBoundingClientRect();
+            _callback(tmpDiv.select('.MathJax_SVG'), glyphDefs, svgBBox);
+        }
+
+        tmpDiv.remove();
+    });
+}
+
+var TAG_STYLES = {
+    // would like to use baseline-shift but FF doesn't support it yet
+    // so we need to use dy along with the uber hacky shift-back-to
+    // baseline below
+    sup: 'font-size:70%" dy="-0.6em',
+    sub: 'font-size:70%" dy="0.3em',
+    b: 'font-weight:bold',
+    i: 'font-style:italic',
+    a: '',
+    span: '',
+    br: '',
+    em: 'font-style:italic;font-weight:bold'
+};
+
+var PROTOCOLS = ['http:', 'https:', 'mailto:'];
+
+var STRIP_TAGS = new RegExp('</?(' + Object.keys(TAG_STYLES).join('|') + ')( [^>]*)?/?>', 'g');
+
+util.plainText = function(_str) {
+    // strip out our pseudo-html so we have a readable
+    // version to put into text fields
+    return (_str||'').replace(STRIP_TAGS, ' ');
+};
+
+function convertToSVG(_str) {
+    var htmlEntitiesDecoded = Plotly.util.html_entity_decode(_str);
+    var result = htmlEntitiesDecoded
+        .split(/(<[^<>]*>)/).map(function(d) {
+            var match = d.match(/<(\/?)([^ >]*)\s*(.*)>/i),
+                tag = match && match[2].toLowerCase(),
+                style = TAG_STYLES[tag];
+            if(style !== undefined) {
+                var close = match[1],
+                    extra = match[3],
+                    /**
+                     * extraStyle: any random extra css (that's supported by svg)
+                     * use this like <span style="font-family:Arial"> to change font in the middle
+                     *
+                     * at one point we supported <font family="..." size="..."> but as this isn't even
+                     * valid HTML anymore and we dropped it accidentally for many months, we will not
+                     * resurrect it.
+                     */
+                    extraStyle = extra.match(/^style\s*=\s*"([^"]+)"\s*/i);
+                // anchor and br are the only ones that don't turn into a tspan
+                if(tag === 'a') {
+                    if(close) return '</a>';
+                    else if(extra.substr(0,4).toLowerCase() !== 'href') return '<a>';
+                    else {
+                        var dummyAnchor = document.createElement('a');
+                        dummyAnchor.href = extra.substr(4).replace(/["'=]/g, '');
+
+                        if(PROTOCOLS.indexOf(dummyAnchor.protocol) === -1) return '<a>';
+
+                        return '<a xlink:show="new" xlink:href' + extra.substr(4) + '>';
+                    }
+                }
+                else if(tag === 'br') return '<br>';
+                else if(close) {
+                    // closing tag
+
+                    // sub/sup: extra tspan with zero-width space to get back to the right baseline
+                    if(tag === 'sup') return '</tspan><tspan dy="0.42em">&#x200b;</tspan>';
+                    if(tag === 'sub') return '</tspan><tspan dy="-0.21em">&#x200b;</tspan>';
+                    else return '</tspan>';
+                }
+                else {
+                    var tspanStart = '<tspan';
+
+                    if(tag === 'sup' || tag === 'sub') {
+                        // sub/sup: extra zero-width space, fixes problem if new line starts with sub/sup
+                        tspanStart = '&#x200b;' + tspanStart;
+                    }
+
+                    if(extraStyle) {
+                        // most of the svg css users will care about is just like html,
+                        // but font color is different. Let our users ignore this.
+                        extraStyle = extraStyle[1].replace(/(^|;)\s*color:/, '$1 fill:');
+                        style = (style ? style + ';' : '') + extraStyle;
+                    }
+
+                    return tspanStart + (style ? ' style="' + style + '"' : '') + '>';
+                }
+            }
+            else {
+                return Plotly.util.xml_entity_encode(d).replace(/</g, '&lt;');
+            }
+        });
+
+    var indices = [];
+    for(var index = result.indexOf('<br>'); index > 0; index = result.indexOf('<br>', index+1)) {
+        indices.push(index);
+    }
+    var count = 0;
+    indices.forEach(function(d) {
+        var brIndex = d + count;
+        var search = result.slice(0, brIndex);
+        var previousOpenTag = '';
+        for(var i2=search.length-1; i2>=0; i2--) {
+            var isTag = search[i2].match(/<(\/?).*>/i);
+            if(isTag && search[i2] !== '<br>') {
+                if(!isTag[1]) previousOpenTag = search[i2];
+                break;
+            }
+        }
+        if(previousOpenTag) {
+            result.splice(brIndex+1, 0, previousOpenTag);
+            result.splice(brIndex, 0, '</tspan>');
+            count += 2;
+        }
+    });
+
+    var joined = result.join('');
+    var splitted = joined.split(/<br>/gi);
+    if(splitted.length > 1) {
+        result = splitted.map(function(d, i) {
+            // TODO: figure out max font size of this line and alter dy
+            // this requires either:
+            // 1) bringing the base font size into convertToTspans, or
+            // 2) only allowing relative percentage font sizes.
+            // I think #2 is the way to go
+            return '<tspan class="line" dy="' + (i*1.3) + 'em">'+ d +'</tspan>';
+        });
+    }
+
+    return result.join('');
+}
+
+function alignHTMLWith(_base, container, options) {
+    var alignH = options.horizontalAlign,
+        alignV = options.verticalAlign || 'top',
+        bRect = _base.node().getBoundingClientRect(),
+        cRect = container.node().getBoundingClientRect(),
+        thisRect,
+        getTop,
+        getLeft;
+
+    if(alignV === 'bottom') {
+        getTop = function() { return bRect.bottom - thisRect.height; };
+    } else if(alignV === 'middle') {
+        getTop = function() { return bRect.top + (bRect.height - thisRect.height) / 2; };
+    } else { // default: top
+        getTop = function() { return bRect.top; };
+    }
+
+    if(alignH === 'right') {
+        getLeft = function() { return bRect.right - thisRect.width; };
+    } else if(alignH === 'center') {
+        getLeft = function() { return bRect.left + (bRect.width - thisRect.width) / 2; };
+    } else { // default: left
+        getLeft = function() { return bRect.left; };
+    }
+
+    return function() {
+        thisRect = this.node().getBoundingClientRect();
+        this.style({
+            top: (getTop() - cRect.top) + 'px',
+            left: (getLeft() - cRect.left) + 'px',
+            'z-index': 1000
+        });
+        return this;
+    };
+}
+
+// Editable title
+
+util.makeEditable = function(context, _delegate, options) {
+    if(!options) options = {};
+    var that = this;
+    var dispatch = d3.dispatch('edit', 'input', 'cancel');
+    var textSelection = d3.select(this.node())
+        .style({'pointer-events': 'all'});
+
+    var handlerElement = _delegate || textSelection;
+    if(_delegate) textSelection.style({'pointer-events': 'none'});
+
+    function handleClick() {
+        appendEditable();
+        that.style({opacity: 0});
+        // also hide any mathjax svg
+        var svgClass = handlerElement.attr('class'),
+            mathjaxClass;
+        if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group';
+        else mathjaxClass = '[class*=-math-group]';
+        if(mathjaxClass) {
+            d3.select(that.node().parentNode).select(mathjaxClass).style({opacity: 0});
+        }
+    }
+
+    function selectElementContents(_el) {
+        var el = _el.node();
+        var range = document.createRange();
+        range.selectNodeContents(el);
+        var sel = window.getSelection();
+        sel.removeAllRanges();
+        sel.addRange(range);
+        el.focus();
+    }
+
+    function appendEditable() {
+        var plotDiv = d3.select(Plotly.Lib.getPlotDiv(that.node())),
+            container = plotDiv.select('.svg-container'),
+            div = container.append('div');
+        div.classed('plugin-editable editable', true)
+            .style({
+                position: 'absolute',
+                'font-family': that.style('font-family') || 'Arial',
+                'font-size': that.style('font-size') || 12,
+                color: options.fill || that.style('fill') || 'black',
+                opacity: 1,
+                'background-color': options.background || 'transparent',
+                outline: '#ffffff33 1px solid',
+                margin: [-parseFloat(that.style('font-size'))/8+1, 0, 0, -1].join('px ') + 'px',
+                padding: '0',
+                'box-sizing': 'border-box'
+            })
+            .attr({contenteditable: true})
+            .text(options.text || that.attr('data-unformatted'))
+            .call(alignHTMLWith(that, container, options))
+            .on('blur', function() {
+                that.text(this.textContent)
+                    .style({opacity: 1});
+                var svgClass = d3.select(this).attr('class'),
+                    mathjaxClass;
+                if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group';
+                else mathjaxClass = '[class*=-math-group]';
+                if(mathjaxClass) {
+                    d3.select(that.node().parentNode).select(mathjaxClass).style({opacity: 0});
+                }
+                var text = this.textContent;
+                d3.select(this).transition().duration(0).remove();
+                d3.select(document).on('mouseup', null);
+                dispatch.edit.call(that, text);
+            })
+            .on('focus', function() {
+                var context = this;
+                d3.select(document).on('mouseup', function() {
+                    if(d3.event.target === context) return false;
+                    if(document.activeElement === div.node()) div.node().blur();
+                });
+            })
+            .on('keyup', function() {
+                if(d3.event.which === 27) {
+                    that.style({opacity: 1});
+                    d3.select(this)
+                        .style({opacity: 0})
+                        .on('blur', function() { return false; })
+                        .transition().remove();
+                    dispatch.cancel.call(that, this.textContent);
+                }
+                else {
+                    dispatch.input.call(that, this.textContent);
+                    d3.select(this).call(alignHTMLWith(that, container, options));
+                }
+            })
+            .on('keydown', function() {
+                if(d3.event.which === 13) this.blur();
+            })
+            .call(selectElementContents);
+    }
+
+    if(options.immediate) handleClick();
+    else handlerElement.on('click', handleClick);
+
+    return d3.rebind(this, dispatch, 'on');
+};
+
+},{"../constants/xmlns_namespaces":338,"../plotly":366,"d3":70}],361:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var topojsonUtils = module.exports = {};
+
+var locationmodeToLayer = require('../constants/geo_constants').locationmodeToLayer,
+    topojsonFeature = require('topojson').feature;
+
+
+topojsonUtils.getTopojsonName = function(geoLayout) {
+    return [
+        geoLayout.scope.replace(/ /g, '-'), '_',
+        geoLayout.resolution.toString(), 'm'
+    ].join('');
+};
+
+topojsonUtils.getTopojsonPath = function(topojsonURL, topojsonName) {
+    return topojsonURL + topojsonName + '.json';
+};
+
+topojsonUtils.getTopojsonFeatures = function(trace, topojson) {
+    var layer = locationmodeToLayer[trace.locationmode],
+        obj = topojson.objects[layer];
+
+    return topojsonFeature(topojson, obj).features;
+};
+
+},{"../constants/geo_constants":334,"topojson":230}],362:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var m4FromQuat = require('gl-mat4/fromQuat');
+var isNumeric = require('fast-isnumeric');
+
+var Plotly = require('../plotly');
+var Lib = require('../lib');
+var Events = require('../lib/events');
+var Queue = require('../lib/queue');
+
+var Plots = require('../plots/plots');
+var Fx = require('../plots/cartesian/graph_interact');
+
+var Color = require('../components/color');
+var Drawing = require('../components/drawing');
+var ErrorBars = require('../components/errorbars');
+var Legend = require('../components/legend');
+var Shapes = require('../components/shapes');
+var Titles = require('../components/titles');
+var manageModeBar = require('../components/modebar/manage');
+var xmlnsNamespaces = require('../constants/xmlns_namespaces');
+
+
+/**
+ * Main plot-creation function
+ *
+ * Note: will call makePlotFramework if necessary to create the framework
+ *
+ * @param {string id or DOM element} gd
+ *      the id or DOM element of the graph container div
+ * @param {array of objects} data
+ *      array of traces, containing the data and display information for each trace
+ * @param {object} layout
+ *      object describing the overall display of the plot,
+ *      all the stuff that doesn't pertain to any individual trace
+ * @param {object} config
+ *      configuration options (see ./plot_config.js for more info)
+ *
+ */
+Plotly.plot = function(gd, data, layout, config) {
+    Lib.markTime('in plot');
+
+    gd = getGraphDiv(gd);
+
+    // Events.init is idempotent and bails early if gd has already been init'd
+    Events.init(gd);
+
+    var okToPlot = Events.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]);
+    if(okToPlot === false) return Promise.reject();
+
+    // if there's no data or layout, and this isn't yet a plotly plot
+    // container, log a warning to help plotly.js users debug
+    if(!data && !layout && !Lib.isPlotDiv(gd)) {
+        console.log('Warning: calling Plotly.plot as if redrawing ' +
+            'but this container doesn\'t yet have a plot.', gd);
+    }
+
+    // transfer configuration options to gd until we move over to
+    // a more OO like model
+    setPlotContext(gd, config);
+
+    if(!layout) layout = {};
+
+    // hook class for plots main container (in case of plotly.js
+    // this won't be #embedded-graph or .js-tab-contents)
+    d3.select(gd).classed('js-plotly-plot', true);
+
+    // off-screen getBoundingClientRect testing space,
+    // in #js-plotly-tester (and stored as gd._tester)
+    // so we can share cached text across tabs
+    Drawing.makeTester(gd);
+
+    // collect promises for any async actions during plotting
+    // any part of the plotting code can push to gd._promises, then
+    // before we move to the next step, we check that they're all
+    // complete, and empty out the promise list again.
+    gd._promises = [];
+
+    var graphWasEmpty = ((gd.data || []).length === 0 && Array.isArray(data));
+
+    // if there is already data on the graph, append the new data
+    // if you only want to redraw, pass a non-array for data
+    if(Array.isArray(data)) {
+        cleanData(data, gd.data);
+
+        if(graphWasEmpty) gd.data = data;
+        else gd.data.push.apply(gd.data, data);
+
+        // for routines outside graph_obj that want a clean tab
+        // (rather than appending to an existing one) gd.empty
+        // is used to determine whether to make a new tab
+        gd.empty = false;
+    }
+
+    if(!gd.layout || graphWasEmpty) gd.layout = cleanLayout(layout);
+
+    // if the user is trying to drag the axes, allow new data and layout
+    // to come in but don't allow a replot.
+    if(gd._dragging) {
+        // signal to drag handler that after everything else is done
+        // we need to replot, because something has changed
+        gd._replotPending = true;
+        return Promise.reject();
+    } else {
+        // we're going ahead with a replot now
+        gd._replotPending = false;
+    }
+
+    Plots.supplyDefaults(gd);
+
+    // Polar plots
+    if(data && data[0] && data[0].r) return plotPolar(gd, data, layout);
+
+    // so we don't try to re-call Plotly.plot from inside
+    // legend and colorbar, if margins changed
+    gd._replotting = true;
+    var hasData = gd._fullData.length > 0;
+
+    var subplots = Plotly.Axes.getSubplots(gd).join(''),
+        oldSubplots = Object.keys(gd._fullLayout._plots || {}).join(''),
+        hasSameSubplots = (oldSubplots === subplots);
+
+    // Make or remake the framework (ie container and axes) if we need to
+    // note: if they container already exists and has data,
+    //  the new layout gets ignored (as it should)
+    //  but if there's no data there yet, it's just a placeholder...
+    //  then it should destroy and remake the plot
+    if(hasData) {
+        if(gd.framework !== makePlotFramework || graphWasEmpty || !hasSameSubplots) {
+            gd.framework = makePlotFramework;
+            makePlotFramework(gd);
+        }
+    }
+    else if(!hasSameSubplots) {
+        gd.framework = makePlotFramework;
+        makePlotFramework(gd);
+    }
+    else if(graphWasEmpty) makePlotFramework(gd);
+
+    var fullLayout = gd._fullLayout;
+
+    // prepare the data and find the autorange
+
+    // generate calcdata, if we need to
+    // to force redoing calcdata, just delete it before calling Plotly.plot
+    var recalc = !gd.calcdata || gd.calcdata.length!==(gd.data||[]).length;
+    if(recalc) {
+        doCalcdata(gd);
+
+        if(gd._context.doubleClick!==false || gd._context.displayModeBar!==false) {
+            Plotly.Axes.saveRangeInitial(gd);
+        }
+    }
+
+    // in case it has changed, attach fullData traces to calcdata
+    for(var i = 0; i < gd.calcdata.length; i++) {
+        gd.calcdata[i][0].trace = gd._fullData[i];
+    }
+
+    /*
+     * start async-friendly code - now we're actually drawing things
+     */
+
+    var oldmargins = JSON.stringify(fullLayout._size);
+
+    // draw anything that can affect margins.
+    // currently this is legend and colorbars
+    function marginPushers() {
+        var calcdata = gd.calcdata;
+        var i, cd, trace;
+
+        Legend.draw(gd);
+
+        for(i = 0; i < calcdata.length; i++) {
+            cd = calcdata[i];
+            trace = cd[0].trace;
+            if(trace.visible !== true || !trace._module.colorbar) {
+                Plots.autoMargin(gd, 'cb'+trace.uid);
+            }
+            else trace._module.colorbar(gd, cd);
+        }
+
+        Plots.doAutoMargin(gd);
+        return Plots.previousPromises(gd);
+    }
+
+    function marginPushersAgain() {
+        // in case the margins changed, draw margin pushers again
+        var seq = JSON.stringify(fullLayout._size)===oldmargins ?
+            [] : [marginPushers, layoutStyles];
+        return Lib.syncOrAsync(seq.concat(Fx.init),gd);
+    }
+
+    function positionAndAutorange() {
+        if(!recalc) return;
+
+        var subplots = Plots.getSubplotIds(fullLayout, 'cartesian'),
+            modules = gd._modules;
+
+        // position and range calculations for traces that
+        // depend on each other ie bars (stacked or grouped)
+        // and boxes (grouped) push each other out of the way
+
+        var subplotInfo, _module;
+
+        for(var i = 0; i < subplots.length; i++) {
+            subplotInfo = fullLayout._plots[subplots[i]];
+
+            for(var j = 0; j < modules.length; j++) {
+                _module = modules[j];
+                if(_module.setPositions) _module.setPositions(gd, subplotInfo);
+            }
+        }
+
+        Lib.markTime('done with bar/box adjustments');
+
+        // calc and autorange for errorbars
+        ErrorBars.calc(gd);
+        Lib.markTime('done ErrorBars.calc');
+
+        // TODO: autosize extra for text markers
+        return Lib.syncOrAsync([
+            Shapes.calcAutorange,
+            Plotly.Annotations.calcAutorange,
+            doAutoRange
+        ], gd);
+    }
+
+    function doAutoRange() {
+        var axList = Plotly.Axes.list(gd, '', true);
+        for(var i = 0; i < axList.length; i++) {
+            Plotly.Axes.doAutoRange(axList[i]);
+        }
+    }
+
+    function drawAxes() {
+        // draw ticks, titles, and calculate axis scaling (._b, ._m)
+        return Plotly.Axes.doTicks(gd, 'redraw');
+    }
+
+    // Now plot the data
+    function drawData() {
+        var calcdata = gd.calcdata;
+
+        // in case of traces that were heatmaps or contour maps
+        // previously, remove them and their colorbars explicitly
+        for(var i = 0; i < calcdata.length; i++) {
+            var trace = calcdata[i][0].trace,
+                isVisible = (trace.visible === true),
+                uid = trace.uid;
+
+            if(!isVisible || !Plots.traceIs(trace, '2dMap')) {
+                fullLayout._paper.selectAll(
+                    '.hm' + uid +
+                    ',.contour' + uid +
+                    ',#clip' + uid
+                ).remove();
+            }
+
+            if(!isVisible || !trace._module.colorbar) {
+                fullLayout._infolayer.selectAll('.cb' + uid).remove();
+            }
+        }
+
+        var plotRegistry = Plots.subplotsRegistry;
+
+        if(fullLayout._hasGL3D) plotRegistry.gl3d.plot(gd);
+        if(fullLayout._hasGeo) plotRegistry.geo.plot(gd);
+        if(fullLayout._hasGL2D) plotRegistry.gl2d.plot(gd);
+        if(fullLayout._hasCartesian || fullLayout._hasPie) {
+            plotRegistry.cartesian.plot(gd);
+        }
+
+        // clean up old scenes that no longer have associated data
+        // will this be a performance hit?
+
+        // styling separate from drawing
+        Plots.style(gd);
+        Lib.markTime('done Plots.style');
+
+        // show annotations and shapes
+        Shapes.drawAll(gd);
+        Plotly.Annotations.drawAll(gd);
+
+        // source links
+        Plots.addLinks(gd);
+
+        // Mark the first render as complete
+        gd._replotting = false;
+
+        return Plots.previousPromises(gd);
+    }
+
+    // An initial paint must be completed before these components can be
+    // correctly sized and the whole plot re-margined. gd._replotting must
+    // be set to false before these will work properly.
+    function finalDraw() {
+        Shapes.drawAll(gd);
+        Plotly.Annotations.drawAll(gd);
+        Legend.draw(gd);
+    }
+
+    function cleanUp() {
+        // now we're REALLY TRULY done plotting...
+        // so mark it as done and let other procedures call a replot
+        Lib.markTime('done plot');
+        gd.emit('plotly_afterplot');
+    }
+
+    var donePlotting = Lib.syncOrAsync([
+        Plots.previousPromises,
+        marginPushers,
+        layoutStyles,
+        marginPushersAgain,
+        positionAndAutorange,
+        drawAxes,
+        drawData,
+        finalDraw
+    ], gd, cleanUp);
+
+    // even if everything we did was synchronous, return a promise
+    // so that the caller doesn't care which route we took
+    return (donePlotting && donePlotting.then) ?
+        donePlotting : Promise.resolve(gd);
+};
+
+// Get the container div: we store all variables for this plot as
+// properties of this div
+// some callers send this in by DOM element, others by id (string)
+function getGraphDiv(gd) {
+    var gdElement;
+
+    if(typeof gd === 'string') {
+        gdElement = document.getElementById(gd);
+
+        if(gdElement === null) {
+            throw new Error('No DOM element with id \'' + gd + '\' exists on the page.');
+        }
+
+        return gdElement;
+    }
+    else if(gd===null || gd===undefined) {
+        throw new Error('DOM element provided is null or undefined');
+    }
+
+    return gd;  // otherwise assume that gd is a DOM element
+}
+
+function opaqueSetBackground(gd, bgColor) {
+    gd._fullLayout._paperdiv.style('background', 'white');
+    Plotly.defaultConfig.setBackground(gd, bgColor);
+}
+
+function setPlotContext(gd, config) {
+    if(!gd._context) gd._context = Lib.extendFlat({}, Plotly.defaultConfig);
+    var context = gd._context;
+
+    if(config) {
+        Object.keys(config).forEach(function(key) {
+            if(key in context) {
+                if(key === 'setBackground' && config[key] === 'opaque') {
+                    context[key] = opaqueSetBackground;
+                }
+                else context[key] = config[key];
+            }
+        });
+
+        // map plot3dPixelRatio to plotGlPixelRatio for backward compatibility
+        if(config.plot3dPixelRatio && !context.plotGlPixelRatio) {
+            context.plotGlPixelRatio = context.plot3dPixelRatio;
+        }
+    }
+
+    //staticPlot forces a bunch of others:
+    if(context.staticPlot) {
+        context.editable = false;
+        context.autosizable = false;
+        context.scrollZoom = false;
+        context.doubleClick = false;
+        context.showTips = false;
+        context.showLink = false;
+        context.displayModeBar = false;
+    }
+}
+
+function plotPolar(gd, data, layout) {
+    // build or reuse the container skeleton
+    var plotContainer = d3.select(gd).selectAll('.plot-container')
+        .data([0]);
+    plotContainer.enter()
+        .insert('div', ':first-child')
+        .classed('plot-container plotly', true);
+    var paperDiv = plotContainer.selectAll('.svg-container')
+        .data([0]);
+    paperDiv.enter().append('div')
+        .classed('svg-container',true)
+        .style('position','relative');
+
+    // empty it everytime for now
+    paperDiv.html('');
+
+    // fulfill gd requirements
+    if(data) gd.data = data;
+    if(layout) gd.layout = layout;
+    Plotly.micropolar.manager.fillLayout(gd);
+
+    if(gd._fullLayout.autosize === 'initial' && gd._context.autosizable) {
+        plotAutoSize(gd,{});
+        gd._fullLayout.autosize = layout.autosize = true;
+    }
+    // resize canvas
+    paperDiv.style({
+        width: gd._fullLayout.width + 'px',
+        height: gd._fullLayout.height + 'px'
+    });
+
+    // instantiate framework
+    gd.framework = Plotly.micropolar.manager.framework(gd);
+
+    // plot
+    gd.framework({data: gd.data, layout: gd.layout}, paperDiv.node());
+
+    // set undo point
+    gd.framework.setUndoPoint();
+
+    // get the resulting svg for extending it
+    var polarPlotSVG = gd.framework.svg();
+
+    // editable title
+    var opacity = 1;
+    var txt = gd._fullLayout.title;
+    if(txt === '' || !txt) opacity = 0;
+    var placeholderText = 'Click to enter title';
+
+    var titleLayout = function() {
+        this.call(Plotly.util.convertToTspans);
+        //TODO: html/mathjax
+        //TODO: center title
+    };
+
+    var title = polarPlotSVG.select('.title-group text')
+        .call(titleLayout);
+
+    if(gd._context.editable) {
+        title.attr({'data-unformatted': txt});
+        if(!txt || txt === placeholderText) {
+            opacity = 0.2;
+            title.attr({'data-unformatted': placeholderText})
+                .text(placeholderText)
+                .style({opacity: opacity})
+                .on('mouseover.opacity',function() {
+                    d3.select(this).transition().duration(100)
+                        .style('opacity',1);
+                })
+                .on('mouseout.opacity',function() {
+                    d3.select(this).transition().duration(1000)
+                        .style('opacity',0);
+                });
+        }
+
+        var setContenteditable = function() {
+            this.call(Plotly.util.makeEditable)
+                .on('edit', function(text) {
+                    gd.framework({layout: {title: text}});
+                    this.attr({'data-unformatted': text})
+                        .text(text)
+                        .call(titleLayout);
+                    this.call(setContenteditable);
+                })
+                .on('cancel', function() {
+                    var txt = this.attr('data-unformatted');
+                    this.text(txt).call(titleLayout);
+                });
+        };
+        title.call(setContenteditable);
+    }
+
+    gd._context.setBackground(gd, gd._fullLayout.paper_bgcolor);
+    Plots.addLinks(gd);
+
+    return Promise.resolve();
+}
+
+function cleanLayout(layout) {
+    // make a few changes to the layout right away
+    // before it gets used for anything
+    // backward compatibility and cleanup of nonstandard options
+    var i, j;
+
+    if(!layout) layout = {};
+
+    // cannot have (x|y)axis1, numbering goes axis, axis2, axis3...
+    if(layout.xaxis1) {
+        if(!layout.xaxis) layout.xaxis = layout.xaxis1;
+        delete layout.xaxis1;
+    }
+    if(layout.yaxis1) {
+        if(!layout.yaxis) layout.yaxis = layout.yaxis1;
+        delete layout.yaxis1;
+    }
+
+    var axList = Plotly.Axes.list({_fullLayout: layout});
+    for(i = 0; i < axList.length; i++) {
+        var ax = axList[i];
+        if(ax.anchor && ax.anchor !== 'free') {
+            ax.anchor = Plotly.Axes.cleanId(ax.anchor);
+        }
+        if(ax.overlaying) ax.overlaying = Plotly.Axes.cleanId(ax.overlaying);
+
+        // old method of axis type - isdate and islog (before category existed)
+        if(!ax.type) {
+            if(ax.isdate) ax.type='date';
+            else if(ax.islog) ax.type='log';
+            else if(ax.isdate===false && ax.islog===false) ax.type='linear';
+        }
+        if(ax.autorange==='withzero' || ax.autorange==='tozero') {
+            ax.autorange = true;
+            ax.rangemode = 'tozero';
+        }
+        delete ax.islog;
+        delete ax.isdate;
+        delete ax.categories; // replaced by _categories
+
+        // prune empty domain arrays made before the new nestedProperty
+        if(emptyContainer(ax, 'domain')) delete ax.domain;
+
+        // autotick -> tickmode
+        if(ax.autotick !== undefined) {
+            if(ax.tickmode === undefined) {
+                ax.tickmode = ax.autotick ? 'auto' : 'linear';
+            }
+            delete ax.autotick;
+        }
+    }
+
+    if(layout.annotations !== undefined && !Array.isArray(layout.annotations)) {
+        console.log('annotations must be an array');
+        delete layout.annotations;
+    }
+    var annotationsLen = (layout.annotations || []).length;
+    for(i = 0; i < annotationsLen; i++) {
+        var ann = layout.annotations[i];
+        if(ann.ref) {
+            if(ann.ref==='paper') {
+                ann.xref = 'paper';
+                ann.yref = 'paper';
+            }
+            else if(ann.ref==='data') {
+                ann.xref = 'x';
+                ann.yref = 'y';
+            }
+            delete ann.ref;
+        }
+        cleanAxRef(ann, 'xref');
+        cleanAxRef(ann, 'yref');
+    }
+
+    if(layout.shapes !== undefined && !Array.isArray(layout.shapes)) {
+        console.log('shapes must be an array');
+        delete layout.shapes;
+    }
+    var shapesLen = (layout.shapes||[]).length;
+    for(i = 0; i < shapesLen; i++) {
+        var shape = layout.shapes[i];
+        cleanAxRef(shape, 'xref');
+        cleanAxRef(shape, 'yref');
+    }
+
+    var legend = layout.legend;
+    if(legend) {
+        // check for old-style legend positioning (x or y is +/- 100)
+        if(legend.x > 3) {
+            legend.x = 1.02;
+            legend.xanchor = 'left';
+        }
+        else if(legend.x < -2) {
+            legend.x = -0.02;
+            legend.xanchor = 'right';
+        }
+
+        if(legend.y > 3) {
+            legend.y = 1.02;
+            legend.yanchor = 'bottom';
+        }
+        else if(legend.y < -2) {
+            legend.y = -0.02;
+            legend.yanchor = 'top';
+        }
+    }
+
+    /*
+     * Moved from rotate -> orbit for dragmode
+     */
+    if(layout.dragmode === 'rotate') layout.dragmode = 'orbit';
+
+    // cannot have scene1, numbering goes scene, scene2, scene3...
+    if(layout.scene1) {
+        if(!layout.scene) layout.scene = layout.scene1;
+        delete layout.scene1;
+    }
+
+    /*
+     * Clean up Scene layouts
+     */
+    var sceneIds = Plots.getSubplotIds(layout, 'gl3d');
+    for(i = 0; i < sceneIds.length; i++) {
+        var scene = layout[sceneIds[i]];
+
+        // clean old Camera coords
+        var cameraposition = scene.cameraposition;
+        if(Array.isArray(cameraposition) && cameraposition[0].length === 4) {
+            var rotation = cameraposition[0],
+                center = cameraposition[1],
+                radius = cameraposition[2],
+                mat = m4FromQuat([], rotation),
+                eye = [];
+
+            for(j = 0; j < 3; ++j) {
+                eye[j] = center[i] + radius * mat[2 + 4 * j];
+            }
+
+            scene.camera = {
+                eye: {x: eye[0], y: eye[1], z: eye[2]},
+                center: {x: center[0], y: center[1], z: center[2]},
+                up: {x: mat[1], y: mat[5], z: mat[9]}
+            };
+
+            delete scene.cameraposition;
+        }
+    }
+
+    // sanitize rgb(fractions) and rgba(fractions) that old tinycolor
+    // supported, but new tinycolor does not because they're not valid css
+    Lib.markTime('finished rest of cleanLayout, starting color');
+    Color.clean(layout);
+    Lib.markTime('finished cleanLayout color.clean');
+
+    return layout;
+}
+
+function cleanAxRef(container, attr) {
+    var valIn = container[attr],
+        axLetter = attr.charAt(0);
+    if(valIn && valIn !== 'paper') {
+        container[attr] = Plotly.Axes.cleanId(valIn, axLetter);
+    }
+}
+
+function cleanData(data, existingData) {
+    // make a few changes to the data right away
+    // before it gets used for anything
+
+    /*
+     * Enforce unique IDs
+     */
+    var suids = [], // seen uids --- so we can weed out incoming repeats
+        uids = data.concat(Array.isArray(existingData) ? existingData : [])
+               .filter(function(trace) { return 'uid' in trace; })
+               .map(function(trace) { return trace.uid; });
+
+    for(var tracei = 0; tracei < data.length; tracei++) {
+        var trace = data[tracei];
+
+        // assign uids to each trace and detect collisions.
+        if(!('uid' in trace) || suids.indexOf(trace.uid) !== -1) {
+            var newUid, i;
+            for(i=0; i<100; i++) {
+                newUid = Lib.randstr(uids);
+                if(suids.indexOf(newUid)===-1) break;
+            }
+            trace.uid = Lib.randstr(uids);
+            uids.push(trace.uid);
+        }
+        // keep track of already seen uids, so that if there are
+        // doubles we force the trace with a repeat uid to
+        // acquire a new one
+        suids.push(trace.uid);
+
+        // BACKWARD COMPATIBILITY FIXES
+
+        // use xbins to bin data in x, and ybins to bin data in y
+        if(trace.type==='histogramy' && 'xbins' in trace && !('ybins' in trace)) {
+            trace.ybins = trace.xbins;
+            delete trace.xbins;
+        }
+
+        // error_y.opacity is obsolete - merge into color
+        if(trace.error_y && 'opacity' in trace.error_y) {
+            var dc = Color.defaults,
+                yeColor = trace.error_y.color ||
+                (Plots.traceIs(trace, 'bar') ? Color.defaultLine : dc[tracei % dc.length]);
+            trace.error_y.color = Color.addOpacity(
+                Color.rgb(yeColor),
+                Color.opacity(yeColor) * trace.error_y.opacity);
+            delete trace.error_y.opacity;
+        }
+
+        // convert bardir to orientation, and put the data into
+        // the axes it's eventually going to be used with
+        if('bardir' in trace) {
+            if(trace.bardir==='h' && (Plots.traceIs(trace, 'bar') ||
+                     trace.type.substr(0,9)==='histogram')) {
+                trace.orientation = 'h';
+                swapXYData(trace);
+            }
+            delete trace.bardir;
+        }
+
+        // now we have only one 1D histogram type, and whether
+        // it uses x or y data depends on trace.orientation
+        if(trace.type==='histogramy') swapXYData(trace);
+        if(trace.type==='histogramx' || trace.type==='histogramy') {
+            trace.type = 'histogram';
+        }
+
+        // scl->scale, reversescl->reversescale
+        if('scl' in trace) {
+            trace.colorscale = trace.scl;
+            delete trace.scl;
+        }
+        if('reversescl' in trace) {
+            trace.reversescale = trace.reversescl;
+            delete trace.reversescl;
+        }
+
+        // axis ids x1 -> x, y1-> y
+        if(trace.xaxis) trace.xaxis = Plotly.Axes.cleanId(trace.xaxis, 'x');
+        if(trace.yaxis) trace.yaxis = Plotly.Axes.cleanId(trace.yaxis, 'y');
+
+        // scene ids scene1 -> scene
+        if(Plots.traceIs(trace, 'gl3d') && trace.scene) {
+            trace.scene = Plots.subplotsRegistry.gl3d.cleanId(trace.scene);
+        }
+
+        if(!Plots.traceIs(trace, 'pie')) {
+            if(Array.isArray(trace.textposition)) {
+                trace.textposition = trace.textposition.map(cleanTextPosition);
+            }
+            else if(trace.textposition) {
+                trace.textposition = cleanTextPosition(trace.textposition);
+            }
+        }
+
+        // fix typo in colorscale definition
+        if(Plots.traceIs(trace, '2dMap')) {
+            if(trace.colorscale === 'YIGnBu') trace.colorscale = 'YlGnBu';
+            if(trace.colorscale === 'YIOrRd') trace.colorscale = 'YlOrRd';
+        }
+        if(Plots.traceIs(trace, 'markerColorscale') && trace.marker) {
+            var cont = trace.marker;
+            if(cont.colorscale === 'YIGnBu') cont.colorscale = 'YlGnBu';
+            if(cont.colorscale === 'YIOrRd') cont.colorscale = 'YlOrRd';
+        }
+
+        // prune empty containers made before the new nestedProperty
+        if(emptyContainer(trace, 'line')) delete trace.line;
+        if('marker' in trace) {
+            if(emptyContainer(trace.marker, 'line')) delete trace.marker.line;
+            if(emptyContainer(trace, 'marker')) delete trace.marker;
+        }
+
+        // sanitize rgb(fractions) and rgba(fractions) that old tinycolor
+        // supported, but new tinycolor does not because they're not valid css
+        Lib.markTime('finished rest of cleanData, starting color');
+        Color.clean(trace);
+        Lib.markTime('finished cleanData color.clean');
+    }
+}
+
+// textposition - support partial attributes (ie just 'top')
+// and incorrect use of middle / center etc.
+function cleanTextPosition(textposition) {
+    var posY = 'middle',
+        posX = 'center';
+    if(textposition.indexOf('top')!==-1) posY = 'top';
+    else if(textposition.indexOf('bottom')!==-1) posY = 'bottom';
+
+    if(textposition.indexOf('left')!==-1) posX = 'left';
+    else if(textposition.indexOf('right')!==-1) posX = 'right';
+
+    return posY + ' ' + posX;
+}
+
+function emptyContainer(outer, innerStr) {
+    return (innerStr in outer) &&
+        (typeof outer[innerStr] === 'object') &&
+        (Object.keys(outer[innerStr]).length === 0);
+}
+
+// convenience function to force a full redraw, mostly for use by plotly.js
+Plotly.redraw = function(gd) {
+    gd = getGraphDiv(gd);
+
+    if(!Lib.isPlotDiv(gd)) {
+        console.log('This element is not a Plotly Plot', gd);
+        return;
+    }
+
+    gd.calcdata = undefined;
+    return Plotly.plot(gd).then(function() {
+        gd.emit('plotly_redraw');
+        return gd;
+    });
+};
+
+/**
+ * Convenience function to make idempotent plot option obvious to users.
+ *
+ * @param gd
+ * @param {Object[]} data
+ * @param {Object} layout
+ * @param {Object} config
+ */
+Plotly.newPlot = function(gd, data, layout, config) {
+    gd = getGraphDiv(gd);
+    Plots.purge(gd);
+    return Plotly.plot(gd, data, layout, config);
+};
+
+function doCalcdata(gd) {
+    var axList = Plotly.Axes.list(gd),
+        fullData = gd._fullData,
+        fullLayout = gd._fullLayout;
+
+    var i, trace, module, cd;
+
+    var calcdata = gd.calcdata = new Array(fullData.length);
+
+    // extra helper variables
+    // firstscatter: fill-to-next on the first trace goes to zero
+    gd.firstscatter = true;
+
+    // how many box plots do we have (in case they're grouped)
+    gd.numboxes = 0;
+
+    // for calculating avg luminosity of heatmaps
+    gd._hmpixcount = 0;
+    gd._hmlumcount = 0;
+
+    // for sharing colors across pies (and for legend)
+    fullLayout._piecolormap = {};
+    fullLayout._piedefaultcolorcount = 0;
+
+    // delete category list, if there is one, so we start over
+    // to be filled in later by ax.d2c
+    for(i = 0; i < axList.length; i++) {
+        axList[i]._categories = [];
+    }
+
+    for(i = 0; i < fullData.length; i++) {
+        trace = fullData[i];
+        module = trace._module;
+        cd = [];
+
+        if(module && trace.visible === true) {
+            if(module.calc) cd = module.calc(gd, trace);
+        }
+
+        // make sure there is a first point
+        // this ensures there is a calcdata item for every trace,
+        // even if cartesian logic doesn't handle it
+        if(!Array.isArray(cd) || !cd[0]) cd = [{x: false, y: false}];
+
+        // add the trace-wide properties to the first point,
+        // per point properties to every point
+        // t is the holder for trace-wide properties
+        if(!cd[0].t) cd[0].t = {};
+        cd[0].trace = trace;
+
+        Lib.markTime('done with calcdata for '+i);
+        calcdata[i] = cd;
+    }
+}
+
+/**
+ * Wrap negative indicies to their positive counterparts.
+ *
+ * @param {Number[]} indices An array of indices
+ * @param {Number} maxIndex The maximum index allowable (arr.length - 1)
+ */
+function positivifyIndices(indices, maxIndex) {
+    var parentLength = maxIndex + 1,
+        positiveIndices = [],
+        i,
+        index;
+
+    for(i = 0; i < indices.length; i++) {
+        index = indices[i];
+        if(index < 0) {
+            positiveIndices.push(parentLength + index);
+        } else {
+            positiveIndices.push(index);
+        }
+    }
+    return positiveIndices;
+}
+
+/**
+ * Ensures that an index array for manipulating gd.data is valid.
+ *
+ * Intended for use with addTraces, deleteTraces, and moveTraces.
+ *
+ * @param gd
+ * @param indices
+ * @param arrayName
+ */
+function assertIndexArray(gd, indices, arrayName) {
+    var i,
+        index;
+
+    for(i = 0; i < indices.length; i++) {
+        index = indices[i];
+
+        // validate that indices are indeed integers
+        if(index !== parseInt(index, 10)) {
+            throw new Error('all values in ' + arrayName + ' must be integers');
+        }
+
+        // check that all indices are in bounds for given gd.data array length
+        if(index >= gd.data.length || index < -gd.data.length) {
+            throw new Error(arrayName + ' must be valid indices for gd.data.');
+        }
+
+        // check that indices aren't repeated
+        if(indices.indexOf(index, i + 1) > -1 ||
+                index >= 0 && indices.indexOf(-gd.data.length + index) > -1 ||
+                index < 0 && indices.indexOf(gd.data.length + index) > -1) {
+            throw new Error('each index in ' + arrayName + ' must be unique.');
+        }
+    }
+}
+
+/**
+ * Private function used by Plotly.moveTraces to check input args
+ *
+ * @param gd
+ * @param currentIndices
+ * @param newIndices
+ */
+function checkMoveTracesArgs(gd, currentIndices, newIndices) {
+
+    // check that gd has attribute 'data' and 'data' is array
+    if(!Array.isArray(gd.data)) {
+        throw new Error('gd.data must be an array.');
+    }
+
+    // validate currentIndices array
+    if(typeof currentIndices === 'undefined') {
+        throw new Error('currentIndices is a required argument.');
+    } else if(!Array.isArray(currentIndices)) {
+        currentIndices = [currentIndices];
+    }
+    assertIndexArray(gd, currentIndices, 'currentIndices');
+
+    // validate newIndices array if it exists
+    if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
+        newIndices = [newIndices];
+    }
+    if(typeof newIndices !== 'undefined') {
+        assertIndexArray(gd, newIndices, 'newIndices');
+    }
+
+    // check currentIndices and newIndices are the same length if newIdices exists
+    if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {
+        throw new Error('current and new indices must be of equal length.');
+    }
+
+}
+/**
+ * A private function to reduce the type checking clutter in addTraces.
+ *
+ * @param gd
+ * @param traces
+ * @param newIndices
+ */
+function checkAddTracesArgs(gd, traces, newIndices) {
+    var i,
+        value;
+
+    // check that gd has attribute 'data' and 'data' is array
+    if(!Array.isArray(gd.data)) {
+        throw new Error('gd.data must be an array.');
+    }
+
+    // make sure traces exists
+    if(typeof traces === 'undefined') {
+        throw new Error('traces must be defined.');
+    }
+
+    // make sure traces is an array
+    if(!Array.isArray(traces)) {
+        traces = [traces];
+    }
+
+    // make sure each value in traces is an object
+    for(i = 0; i < traces.length; i++) {
+        value = traces[i];
+        if(typeof value !== 'object' || (Array.isArray(value) || value === null)) {
+            throw new Error('all values in traces array must be non-array objects');
+        }
+    }
+
+    // make sure we have an index for each trace
+    if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
+        newIndices = [newIndices];
+    }
+    if(typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {
+        throw new Error(
+            'if indices is specified, traces.length must equal indices.length'
+        );
+    }
+}
+
+/**
+ * A private function to reduce the type checking clutter in spliceTraces.
+ * Get all update Properties from gd.data. Validate inputs and outputs.
+ * Used by prependTrace and extendTraces
+ *
+ * @param gd
+ * @param update
+ * @param indices
+ * @param maxPoints
+ */
+function assertExtendTracesArgs(gd, update, indices, maxPoints) {
+
+    var maxPointsIsObject = Lib.isPlainObject(maxPoints);
+
+    if(!Array.isArray(gd.data)) {
+        throw new Error('gd.data must be an array');
+    }
+    if(!Lib.isPlainObject(update)) {
+        throw new Error('update must be a key:value object');
+    }
+
+    if(typeof indices === 'undefined') {
+        throw new Error('indices must be an integer or array of integers');
+    }
+
+    assertIndexArray(gd, indices, 'indices');
+
+    for(var key in update) {
+
+        /*
+         * Verify that the attribute to be updated contains as many trace updates
+         * as indices. Failure must result in throw and no-op
+         */
+        if(!Array.isArray(update[key]) || update[key].length !== indices.length) {
+            throw new Error('attribute ' + key + ' must be an array of length equal to indices array length');
+        }
+
+        /*
+         * if maxPoints is an object it must match keys and array lengths of 'update' 1:1
+         */
+        if(maxPointsIsObject &&
+            (!(key in maxPoints) || !Array.isArray(maxPoints[key]) ||
+            maxPoints[key].length !== update[key].length)) {
+            throw new Error('when maxPoints is set as a key:value object it must contain a 1:1 ' +
+                            'corrispondence with the keys and number of traces in the update object');
+        }
+    }
+}
+
+/**
+ * A private function to reduce the type checking clutter in spliceTraces.
+ *
+ * @param {Object|HTMLDivElement} gd
+ * @param {Object} update
+ * @param {Number[]} indices
+ * @param {Number||Object} maxPoints
+ * @return {Object[]}
+ */
+function getExtendProperties(gd, update, indices, maxPoints) {
+
+    var maxPointsIsObject = Lib.isPlainObject(maxPoints),
+        updateProps = [];
+    var trace, target, prop, insert, maxp;
+
+    // allow scalar index to represent a single trace position
+    if(!Array.isArray(indices)) indices = [indices];
+
+    // negative indices are wrapped around to their positive value. Equivalent to python indexing.
+    indices = positivifyIndices(indices, gd.data.length - 1);
+
+    // loop through all update keys and traces and harvest validated data.
+    for(var key in update) {
+
+        for(var j = 0; j < indices.length; j++) {
+
+            /*
+             * Choose the trace indexed by the indices map argument and get the prop setter-getter
+             * instance that references the key and value for this particular trace.
+             */
+            trace = gd.data[indices[j]];
+            prop = Lib.nestedProperty(trace, key);
+
+            /*
+             * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size"
+             * Target must exist as an Array to allow the extend operation to be performed.
+             */
+            target = prop.get();
+            insert = update[key][j];
+
+            if(!Array.isArray(insert)) {
+                throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array');
+            }
+            if(!Array.isArray(target)) {
+                throw new Error('cannot extend missing or non-array attribute: ' + key);
+            }
+
+            /*
+             * maxPoints may be an object map or a scalar. If object select the key:value, else
+             * Use the scalar maxPoints for all key and trace combinations.
+             */
+            maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints;
+
+            // could have chosen null here, -1 just tells us to not take a window
+            if(!isNumeric(maxp)) maxp = -1;
+
+            /*
+             * Wrap the nestedProperty in an object containing required data
+             * for lengthening and windowing this particular trace - key combination.
+             * Flooring maxp mirrors the behaviour of floats in the Array.slice JSnative function.
+             */
+            updateProps.push({
+                prop: prop,
+                target: target,
+                insert: insert,
+                maxp: Math.floor(maxp)
+            });
+        }
+    }
+
+    // all target and insertion data now validated
+    return updateProps;
+}
+
+/**
+ * A private function to key Extend and Prepend traces DRY
+ *
+ * @param {Object|HTMLDivElement} gd
+ * @param {Object} update
+ * @param {Number[]} indices
+ * @param {Number||Object} maxPoints
+ * @param {Function} lengthenArray
+ * @param {Function} spliceArray
+ * @return {Object}
+ */
+function spliceTraces(gd, update, indices, maxPoints, lengthenArray, spliceArray) {
+
+    assertExtendTracesArgs(gd, update, indices, maxPoints);
+
+    var updateProps = getExtendProperties(gd, update, indices, maxPoints),
+        remainder = [],
+        undoUpdate = {},
+        undoPoints = {};
+    var target, prop, maxp;
+
+    for(var i = 0; i < updateProps.length; i++) {
+
+        /*
+         * prop is the object returned by Lib.nestedProperties
+         */
+        prop = updateProps[i].prop;
+        maxp = updateProps[i].maxp;
+
+        target = lengthenArray(updateProps[i].target, updateProps[i].insert);
+
+        /*
+         * If maxp is set within post-extension trace.length, splice to maxp length.
+         * Otherwise skip function call as splice op will have no effect anyway.
+         */
+        if(maxp >= 0 && maxp < target.length) remainder = spliceArray(target, maxp);
+
+        /*
+         * to reverse this operation we need the size of the original trace as the reverse
+         * operation will need to window out any lengthening operation performed in this pass.
+         */
+        maxp = updateProps[i].target.length;
+
+        /*
+         * Magic happens here! update gd.data.trace[key] with new array data.
+         */
+        prop.set(target);
+
+        if(!Array.isArray(undoUpdate[prop.astr])) undoUpdate[prop.astr] = [];
+        if(!Array.isArray(undoPoints[prop.astr])) undoPoints[prop.astr] = [];
+
+        /*
+         * build the inverse update object for the undo operation
+         */
+        undoUpdate[prop.astr].push(remainder);
+
+        /*
+         * build the matching maxPoints undo object containing original trace lengths.
+         */
+        undoPoints[prop.astr].push(maxp);
+    }
+
+    return {update: undoUpdate, maxPoints: undoPoints};
+}
+
+/**
+ * extend && prepend traces at indices with update arrays, window trace lengths to maxPoints
+ *
+ * Extend and Prepend have identical APIs. Prepend inserts an array at the head while Extend
+ * inserts an array off the tail. Prepend truncates the tail of the array - counting maxPoints
+ * from the head, whereas Extend truncates the head of the array, counting backward maxPoints
+ * from the tail.
+ *
+ * If maxPoints is undefined, nonNumeric, negative or greater than extended trace length no
+ * truncation / windowing will be performed. If its zero, well the whole trace is truncated.
+ *
+ * @param {Object|HTMLDivElement} gd The graph div
+ * @param {Object} update The key:array map of target attributes to extend
+ * @param {Number|Number[]} indices The locations of traces to be extended
+ * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening.
+ *
+ */
+Plotly.extendTraces = function extendTraces(gd, update, indices, maxPoints) {
+    gd = getGraphDiv(gd);
+
+    var undo = spliceTraces(gd, update, indices, maxPoints,
+
+                           /*
+                            * The Lengthen operation extends trace from end with insert
+                            */
+                            function(target, insert) {
+                                return target.concat(insert);
+                            },
+
+                            /*
+                             * Window the trace keeping maxPoints, counting back from the end
+                             */
+                            function(target, maxPoints) {
+                                return target.splice(0, target.length - maxPoints);
+                            });
+
+    var promise = Plotly.redraw(gd);
+
+    var undoArgs = [gd, undo.update, indices, undo.maxPoints];
+    if(Queue) {
+        Queue.add(gd, Plotly.prependTraces, undoArgs, extendTraces, arguments);
+    }
+
+    return promise;
+};
+
+Plotly.prependTraces = function prependTraces(gd, update, indices, maxPoints) {
+    gd = getGraphDiv(gd);
+
+    var undo = spliceTraces(gd, update, indices, maxPoints,
+
+                           /*
+                            * The Lengthen operation extends trace by appending insert to start
+                            */
+                            function(target, insert) {
+                                return insert.concat(target);
+                            },
+
+                            /*
+                             * Window the trace keeping maxPoints, counting forward from the start
+                             */
+                            function(target, maxPoints) {
+                                return target.splice(maxPoints, target.length);
+                            });
+
+    var promise = Plotly.redraw(gd);
+
+    var undoArgs = [gd, undo.update, indices, undo.maxPoints];
+    if(Queue) {
+        Queue.add(gd, Plotly.extendTraces, undoArgs, prependTraces, arguments);
+    }
+
+    return promise;
+};
+
+/**
+ * Add data traces to an existing graph div.
+ *
+ * @param {Object|HTMLDivElement} gd The graph div
+ * @param {Object[]} gd.data The array of traces we're adding to
+ * @param {Object[]|Object} traces The object or array of objects to add
+ * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces
+ *
+ */
+Plotly.addTraces = function addTraces(gd, traces, newIndices) {
+    gd = getGraphDiv(gd);
+
+    var currentIndices = [],
+        undoFunc = Plotly.deleteTraces,
+        redoFunc = addTraces,
+        undoArgs = [gd, currentIndices],
+        redoArgs = [gd, traces],  // no newIndices here
+        i,
+        promise;
+
+    // all validation is done elsewhere to remove clutter here
+    checkAddTracesArgs(gd, traces, newIndices);
+
+    // make sure traces is an array
+    if(!Array.isArray(traces)) {
+        traces = [traces];
+    }
+    cleanData(traces, gd.data);
+
+    // add the traces to gd.data (no redrawing yet!)
+    for(i = 0; i < traces.length; i += 1) {
+        gd.data.push(traces[i]);
+    }
+
+    // to continue, we need to call moveTraces which requires currentIndices
+    for(i = 0; i < traces.length; i++) {
+        currentIndices.push(-traces.length + i);
+    }
+
+    // if the user didn't define newIndices, they just want the traces appended
+    // i.e., we can simply redraw and be done
+    if(typeof newIndices === 'undefined') {
+        promise = Plotly.redraw(gd);
+        if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
+        return promise;
+    }
+
+    // make sure indices is property defined
+    if(!Array.isArray(newIndices)) {
+        newIndices = [newIndices];
+    }
+
+    try {
+
+        // this is redundant, but necessary to not catch later possible errors!
+        checkMoveTracesArgs(gd, currentIndices, newIndices);
+    }
+    catch(error) {
+
+        // something went wrong, reset gd to be safe and rethrow error
+        gd.data.splice(gd.data.length - traces.length, traces.length);
+        throw error;
+    }
+
+    // if we're here, the user has defined specific places to place the new traces
+    // this requires some extra work that moveTraces will do
+    if(Queue) Queue.startSequence(gd);
+    if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
+    promise = Plotly.moveTraces(gd, currentIndices, newIndices);
+    if(Queue) Queue.stopSequence(gd);
+    return promise;
+};
+
+/**
+ * Delete traces at `indices` from gd.data array.
+ *
+ * @param {Object|HTMLDivElement} gd The graph div
+ * @param {Object[]} gd.data The array of traces we're removing from
+ * @param {Number|Number[]} indices The indices
+ */
+Plotly.deleteTraces = function deleteTraces(gd, indices) {
+    gd = getGraphDiv(gd);
+
+    var traces = [],
+        undoFunc = Plotly.addTraces,
+        redoFunc = deleteTraces,
+        undoArgs = [gd, traces, indices],
+        redoArgs = [gd, indices],
+        i,
+        deletedTrace;
+
+    // make sure indices are defined
+    if(typeof indices === 'undefined') {
+        throw new Error('indices must be an integer or array of integers.');
+    } else if(!Array.isArray(indices)) {
+        indices = [indices];
+    }
+    assertIndexArray(gd, indices, 'indices');
+
+    // convert negative indices to positive indices
+    indices = positivifyIndices(indices, gd.data.length - 1);
+
+    // we want descending here so that splicing later doesn't affect indexing
+    indices.sort(Lib.sorterDes);
+    for(i = 0; i < indices.length; i += 1) {
+        deletedTrace = gd.data.splice(indices[i], 1)[0];
+        traces.push(deletedTrace);
+    }
+
+    var promise = Plotly.redraw(gd);
+
+    if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
+
+    return promise;
+};
+
+/**
+ * Move traces at currentIndices array to locations in newIndices array.
+ *
+ * If newIndices is omitted, currentIndices will be moved to the end. E.g.,
+ * these are equivalent:
+ *
+ * Plotly.moveTraces(gd, [1, 2, 3], [-3, -2, -1])
+ * Plotly.moveTraces(gd, [1, 2, 3])
+ *
+ * @param {Object|HTMLDivElement} gd The graph div
+ * @param {Object[]} gd.data The array of traces we're removing from
+ * @param {Number|Number[]} currentIndices The locations of traces to be moved
+ * @param {Number|Number[]} [newIndices] The locations to move traces to
+ *
+ * Example calls:
+ *
+ *      // move trace i to location x
+ *      Plotly.moveTraces(gd, i, x)
+ *
+ *      // move trace i to end of array
+ *      Plotly.moveTraces(gd, i)
+ *
+ *      // move traces i, j, k to end of array (i != j != k)
+ *      Plotly.moveTraces(gd, [i, j, k])
+ *
+ *      // move traces [i, j, k] to [x, y, z] (i != j != k) (x != y != z)
+ *      Plotly.moveTraces(gd, [i, j, k], [x, y, z])
+ *
+ *      // reorder all traces (assume there are 5--a, b, c, d, e)
+ *      Plotly.moveTraces(gd, [b, d, e, a, c])  // same as 'move to end'
+ */
+Plotly.moveTraces = function moveTraces(gd, currentIndices, newIndices) {
+    gd = getGraphDiv(gd);
+
+    var newData = [],
+        movingTraceMap = [],
+        undoFunc = moveTraces,
+        redoFunc = moveTraces,
+        undoArgs = [gd, newIndices, currentIndices],
+        redoArgs = [gd, currentIndices, newIndices],
+        i;
+
+    // to reduce complexity here, check args elsewhere
+    // this throws errors where appropriate
+    checkMoveTracesArgs(gd, currentIndices, newIndices);
+
+    // make sure currentIndices is an array
+    currentIndices = Array.isArray(currentIndices) ? currentIndices : [currentIndices];
+
+    // if undefined, define newIndices to point to the end of gd.data array
+    if(typeof newIndices === 'undefined') {
+        newIndices = [];
+        for(i = 0; i < currentIndices.length; i++) {
+            newIndices.push(-currentIndices.length + i);
+        }
+    }
+
+    // make sure newIndices is an array if it's user-defined
+    newIndices = Array.isArray(newIndices) ? newIndices : [newIndices];
+
+    // convert negative indices to positive indices (they're the same length)
+    currentIndices = positivifyIndices(currentIndices, gd.data.length - 1);
+    newIndices = positivifyIndices(newIndices, gd.data.length - 1);
+
+    // at this point, we've coerced the index arrays into predictable forms
+
+    // get the traces that aren't being moved around
+    for(i = 0; i < gd.data.length; i++) {
+
+        // if index isn't in currentIndices, include it in ignored!
+        if(currentIndices.indexOf(i) === -1) {
+            newData.push(gd.data[i]);
+        }
+    }
+
+    // get a mapping of indices to moving traces
+    for(i = 0; i < currentIndices.length; i++) {
+        movingTraceMap.push({newIndex: newIndices[i], trace: gd.data[currentIndices[i]]});
+    }
+
+    // reorder this mapping by newIndex, ascending
+    movingTraceMap.sort(function(a, b) {
+        return a.newIndex - b.newIndex;
+    });
+
+    // now, add the moving traces back in, in order!
+    for(i = 0; i < movingTraceMap.length; i += 1) {
+        newData.splice(movingTraceMap[i].newIndex, 0, movingTraceMap[i].trace);
+    }
+
+    gd.data = newData;
+
+    var promise = Plotly.redraw(gd);
+
+    if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
+
+    return promise;
+};
+
+// -----------------------------------------------------
+// restyle and relayout: these two control all redrawing
+// for data (restyle) and everything else (relayout)
+// -----------------------------------------------------
+
+// restyle: change styling of an existing plot
+// can be called two ways:
+//
+// restyle(gd, astr, val [,traces])
+//      gd - graph div (string id or dom element)
+//      astr - attribute string (like 'marker.symbol')
+//      val - value to give this attribute
+//      traces - integer or array of integers for the traces
+//          to alter (all if omitted)
+//
+// restyle(gd, aobj [,traces])
+//      aobj - {astr1:val1, astr2:val2...} allows setting
+//          multiple attributes simultaneously
+//
+// val (or val1, val2... in the object form) can be an array,
+// to apply different values to each trace.
+// If the array is too short, it will wrap around (useful for
+// style files that want to specify cyclical default values).
+Plotly.restyle = function restyle(gd, astr, val, traces) {
+    gd = getGraphDiv(gd);
+
+    var i, fullLayout = gd._fullLayout,
+        aobj = {};
+
+    if(typeof astr === 'string') aobj[astr] = val;
+    else if(Lib.isPlainObject(astr)) {
+        aobj = astr;
+        if(traces===undefined) traces = val; // the 3-arg form
+    }
+    else {
+        console.log('restyle fail',astr,val,traces);
+        return Promise.reject();
+    }
+
+    if(Object.keys(aobj).length) gd.changed = true;
+
+    if(isNumeric(traces)) traces=[traces];
+    else if(!Array.isArray(traces) || !traces.length) {
+        traces=gd._fullData.map(function(v,i) { return i; });
+    }
+
+    // recalcAttrs attributes need a full regeneration of calcdata
+    // as well as a replot, because the right objects may not exist,
+    // or autorange may need recalculating
+    // in principle we generally shouldn't need to redo ALL traces... that's
+    // harder though.
+    var recalcAttrs = [
+        'mode','visible','type','orientation','fill',
+        'histfunc','histnorm','text',
+        'x', 'y', 'z',
+        'xtype','x0','dx','ytype','y0','dy','xaxis','yaxis',
+        'line.width',
+        'connectgaps', 'transpose', 'zsmooth',
+        'showscale', 'marker.showscale',
+        'zauto', 'marker.cauto',
+        'autocolorscale', 'marker.autocolorscale',
+        'colorscale', 'marker.colorscale',
+        'reversescale', 'marker.reversescale',
+        'autobinx','nbinsx','xbins','xbins.start','xbins.end','xbins.size',
+        'autobiny','nbinsy','ybins','ybins.start','ybins.end','ybins.size',
+        'autocontour','ncontours','contours','contours.coloring',
+        'error_y','error_y.visible','error_y.value','error_y.type',
+        'error_y.traceref','error_y.array','error_y.symmetric',
+        'error_y.arrayminus','error_y.valueminus','error_y.tracerefminus',
+        'error_x','error_x.visible','error_x.value','error_x.type',
+        'error_x.traceref','error_x.array','error_x.symmetric',
+        'error_x.arrayminus','error_x.valueminus','error_x.tracerefminus',
+        'swapxy','swapxyaxes','orientationaxes',
+        'marker.colors', 'values', 'labels', 'label0', 'dlabel', 'sort',
+        'textinfo', 'textposition', 'textfont.size', 'textfont.family', 'textfont.color',
+        'insidetextfont.size', 'insidetextfont.family', 'insidetextfont.color',
+        'outsidetextfont.size', 'outsidetextfont.family', 'outsidetextfont.color',
+        'hole', 'scalegroup', 'domain', 'domain.x', 'domain.y',
+        'domain.x[0]', 'domain.x[1]', 'domain.y[0]', 'domain.y[1]',
+        'tilt', 'tiltaxis', 'depth', 'direction', 'rotation', 'pull'
+    ];
+    for(i = 0; i < traces.length; i++) {
+        if(Plots.traceIs(gd._fullData[traces[i]], 'box')) {
+            recalcAttrs.push('name');
+            break;
+        }
+    }
+
+    // autorangeAttrs attributes need a full redo of calcdata
+    // only if an axis is autoranged,
+    // because .calc() is where the autorange gets determined
+    // TODO: could we break this out as well?
+    var autorangeAttrs = [
+        'marker', 'marker.size', 'textfont',
+        'boxpoints','jitter','pointpos','whiskerwidth','boxmean'
+    ];
+    // replotAttrs attributes need a replot (because different
+    // objects need to be made) but not a recalc
+    var replotAttrs = [
+        'zmin', 'zmax', 'zauto',
+        'marker.cmin', 'marker.cmax', 'marker.cauto',
+        'contours.start','contours.end','contours.size',
+        'contours.showlines',
+        'line','line.smoothing','line.shape',
+        'error_y.width','error_x.width','error_x.copy_ystyle',
+        'marker.maxdisplayed'
+    ];
+    // these ones show up in restyle because they make more sense
+    // in the style box, but they're graph-wide attributes, so set
+    // in gd.layout also axis scales and range show up here because
+    // we may need to undo them. These all trigger a recalc
+    // var layoutAttrs = [
+    //     'barmode', 'barnorm','bargap', 'bargroupgap',
+    //     'boxmode', 'boxgap', 'boxgroupgap',
+    //     '?axis.autorange', '?axis.range', '?axis.rangemode'
+    // ];
+
+    // these ones may alter the axis type
+    // (at least if the first trace is involved)
+    var axtypeAttrs = [
+        'type','x','y','x0','y0','orientation','xaxis','yaxis'
+    ];
+
+    // flags for which kind of update we need to do
+    var docalc = false,
+        docalcAutorange = false,
+        doplot = false,
+        dolayout = false,
+        dostyle = false,
+        docolorbars = false;
+    // copies of the change (and previous values of anything affected)
+    // for the undo / redo queue
+    var redoit = {},
+        undoit = {},
+        axlist,
+        flagAxForDelete = {};
+
+    // for now, if we detect gl or geo stuff, just re-do the plot
+    if(fullLayout._hasGL3D || fullLayout._hasGeo || fullLayout._hasGL2D) {
+        doplot = true;
+    }
+
+    // make a new empty vals array for undoit
+    function a0() { return traces.map(function() { return undefined; }); }
+
+    // for autoranging multiple axes
+    function addToAxlist(axid) {
+        var axName = Plotly.Axes.id2name(axid);
+        if(axlist.indexOf(axName)===-1) { axlist.push(axName); }
+    }
+    function autorangeAttr(axName) { return 'LAYOUT' + axName + '.autorange'; }
+    function rangeAttr(axName) { return 'LAYOUT' + axName + '.range'; }
+
+    // for attrs that interact (like scales & autoscales), save the
+    // old vals before making the change
+    // val=undefined will not set a value, just record what the value was.
+    // val=null will delete the attribute
+    // attr can be an array to set several at once (all to the same val)
+    function doextra(attr,val,i) {
+        if(Array.isArray(attr)) {
+            attr.forEach(function(a) { doextra(a,val,i); });
+            return;
+        }
+        // quit if explicitly setting this elsewhere
+        if(attr in aobj) return;
+
+        var extraparam;
+        if(attr.substr(0, 6) === 'LAYOUT') {
+            extraparam = Lib.nestedProperty(gd.layout, attr.replace('LAYOUT', ''));
+        } else {
+            extraparam = Lib.nestedProperty(gd.data[traces[i]], attr);
+        }
+
+        if(!(attr in undoit)) {
+            undoit[attr] = a0();
+        }
+        if(undoit[attr][i]===undefined) {
+            undoit[attr][i]=extraparam.get();
+        }
+        if(val!==undefined) {
+            extraparam.set(val);
+        }
+    }
+    var zscl = ['zmin', 'zmax'],
+        xbins = ['xbins.start', 'xbins.end', 'xbins.size'],
+        ybins = ['ybins.start', 'ybins.end', 'ybins.size'],
+        contourAttrs = ['contours.start', 'contours.end', 'contours.size'];
+
+    // now make the changes to gd.data (and occasionally gd.layout)
+    // and figure out what kind of graphics update we need to do
+    for(var ai in aobj) {
+        var vi = aobj[ai],
+            cont,
+            contFull,
+            param,
+            oldVal,
+            newVal;
+        redoit[ai] = vi;
+
+        if(ai.substr(0,6)==='LAYOUT') {
+            param = Lib.nestedProperty(gd.layout, ai.replace('LAYOUT', ''));
+            undoit[ai] = [param.get()];
+            // since we're allowing val to be an array, allow it here too,
+            // even though that's meaningless
+            param.set(Array.isArray(vi) ? vi[0] : vi);
+            // ironically, the layout attrs in restyle only require replot,
+            // not relayout
+            docalc = true;
+            continue;
+        }
+
+        // set attribute in gd.data
+        undoit[ai] = a0();
+        for(i=0; i<traces.length; i++) {
+            cont = gd.data[traces[i]];
+            contFull = gd._fullData[traces[i]];
+            param = Lib.nestedProperty(cont,ai);
+            oldVal = param.get();
+            newVal = Array.isArray(vi) ? vi[i%vi.length] : vi;
+
+            // setting bin or z settings should turn off auto
+            // and setting auto should save bin or z settings
+            if(zscl.indexOf(ai)!==-1) {
+                doextra('zauto', false, i);
+            }
+            else if(ai === 'colorscale') {
+                doextra('autocolorscale', false, i);
+            }
+            else if(ai === 'autocolorscale') {
+                doextra('colorscale', undefined, i);
+            }
+            else if(ai === 'marker.colorscale') {
+                doextra('marker.autocolorscale', false, i);
+            }
+            else if(ai === 'marker.autocolorscale') {
+                doextra('marker.colorscale', undefined, i);
+            }
+            else if(ai==='zauto') {
+                doextra(zscl, undefined, i);
+            }
+            else if(xbins.indexOf(ai)!==-1) {
+                doextra('autobinx', false, i);
+            }
+            else if(ai==='autobinx') {
+                doextra(xbins, undefined, i);
+            }
+            else if(ybins.indexOf(ai)!==-1) {
+                doextra('autobiny', false, i);
+            }
+            else if(ai==='autobiny') {
+                doextra(ybins, undefined, i);
+            }
+            else if(contourAttrs.indexOf(ai)!==-1) {
+                doextra('autocontour', false, i);
+            }
+            else if(ai==='autocontour') {
+                doextra(contourAttrs, undefined, i);
+            }
+            // heatmaps: setting x0 or dx, y0 or dy,
+            // should turn xtype/ytype to 'scaled' if 'array'
+            else if(['x0','dx'].indexOf(ai)!==-1 &&
+                    contFull.x && contFull.xtype!=='scaled') {
+                doextra('xtype', 'scaled', i);
+            }
+            else if(['y0','dy'].indexOf(ai)!==-1 &&
+                    contFull.y && contFull.ytype!=='scaled') {
+                doextra('ytype', 'scaled', i);
+            }
+            // changing colorbar size modes,
+            // make the resulting size not change
+            // note that colorbar fractional sizing is based on the
+            // original plot size, before anything (like a colorbar)
+            // increases the margins
+            else if(ai==='colorbar.thicknessmode' && param.get() !== newVal &&
+                        ['fraction','pixels'].indexOf(newVal) !== -1 &&
+                        contFull.colorbar) {
+                var thicknorm =
+                    ['top','bottom'].indexOf(contFull.colorbar.orient)!==-1 ?
+                        (fullLayout.height - fullLayout.margin.t - fullLayout.margin.b) :
+                        (fullLayout.width - fullLayout.margin.l - fullLayout.margin.r);
+                doextra('colorbar.thickness', contFull.colorbar.thickness *
+                    (newVal === 'fraction' ? 1/thicknorm : thicknorm), i);
+            }
+            else if(ai==='colorbar.lenmode' && param.get() !== newVal &&
+                        ['fraction','pixels'].indexOf(newVal) !== -1 &&
+                        contFull.colorbar) {
+                var lennorm =
+                    ['top','bottom'].indexOf(contFull.colorbar.orient)!==-1 ?
+                        (fullLayout.width - fullLayout.margin.l - fullLayout.margin.r) :
+                        (fullLayout.height - fullLayout.margin.t - fullLayout.margin.b);
+                doextra('colorbar.len', contFull.colorbar.len *
+                    (newVal === 'fraction' ? 1/lennorm : lennorm), i);
+            }
+            else if(ai === 'colorbar.tick0' || ai === 'colorbar.dtick') {
+                doextra('colorbar.tickmode', 'linear', i);
+            }
+            else if(ai === 'colorbar.tickmode') {
+                doextra(['colorbar.tick0', 'colorbar.dtick'], undefined, i);
+            }
+
+
+            if(ai === 'type' && (newVal === 'pie') !== (oldVal === 'pie')) {
+                var labelsTo = 'x',
+                    valuesTo = 'y';
+                if((newVal === 'bar' || oldVal === 'bar') && cont.orientation === 'h') {
+                    labelsTo = 'y';
+                    valuesTo = 'x';
+                }
+                Lib.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo);
+                Lib.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo);
+                Lib.swapAttrs(cont, ['?', '?src'], 'values', valuesTo);
+
+                if(oldVal === 'pie') {
+                    Lib.nestedProperty(cont, 'marker.color')
+                        .set(Lib.nestedProperty(cont, 'marker.colors').get());
+
+                    // super kludgy - but if all pies are gone we won't remove them otherwise
+                    fullLayout._pielayer.selectAll('g.trace').remove();
+                } else if(Plots.traceIs(cont, 'cartesian')) {
+                    Lib.nestedProperty(cont, 'marker.colors')
+                        .set(Lib.nestedProperty(cont, 'marker.color').get());
+                    //look for axes that are no longer in use and delete them
+                    flagAxForDelete[cont.xaxis || 'x'] = true;
+                    flagAxForDelete[cont.yaxis || 'y'] = true;
+                }
+            }
+
+            undoit[ai][i] = oldVal;
+            // set the new value - if val is an array, it's one el per trace
+            // first check for attributes that get more complex alterations
+            var swapAttrs = [
+                'swapxy','swapxyaxes','orientation','orientationaxes'
+            ];
+            if(swapAttrs.indexOf(ai)!==-1) {
+                // setting an orientation: make sure it's changing
+                // before we swap everything else
+                if(ai==='orientation') {
+                    param.set(newVal);
+                    if(param.get()===undoit[ai][i]) continue;
+                }
+                // orientationaxes has no value,
+                // it flips everything and the axes
+                else if(ai==='orientationaxes') {
+                    cont.orientation =
+                        {v: 'h', h: 'v'}[contFull.orientation];
+                }
+                swapXYData(cont);
+            }
+            // all the other ones, just modify that one attribute
+            else param.set(newVal);
+
+        }
+
+        // swap the data attributes of the relevant x and y axes?
+        if(['swapxyaxes','orientationaxes'].indexOf(ai)!==-1) {
+            Plotly.Axes.swap(gd, traces);
+        }
+
+        // swap hovermode if set to "compare x/y data"
+        if(ai === 'orientationaxes') {
+            var hovermode = Lib.nestedProperty(gd.layout, 'hovermode');
+            if(hovermode.get() === 'x') {
+                hovermode.set('y');
+            } else if(hovermode.get() === 'y') {
+                hovermode.set('x');
+            }
+        }
+
+        // check if we need to call axis type
+        if((traces.indexOf(0)!==-1) && (axtypeAttrs.indexOf(ai)!==-1)) {
+            Plotly.Axes.clearTypes(gd,traces);
+            docalc = true;
+        }
+
+        // switching from auto to manual binning or z scaling doesn't
+        // actually do anything but change what you see in the styling
+        // box. everything else at least needs to apply styles
+        if((['autobinx','autobiny','zauto'].indexOf(ai)===-1) ||
+                newVal!==false) {
+            dostyle = true;
+        }
+        if(['colorbar', 'line'].indexOf(param.parts[0])!==-1 ||
+            param.parts[0]==='marker' && param.parts[1]==='colorbar') {
+            docolorbars = true;
+        }
+
+        if(recalcAttrs.indexOf(ai)!==-1) {
+            // major enough changes deserve autoscale, autobin, and
+            // non-reversed axes so people don't get confused
+            if(['orientation','type'].indexOf(ai)!==-1) {
+                axlist = [];
+                for(i=0; i<traces.length; i++) {
+                    var trace = gd.data[traces[i]];
+
+                    if(Plots.traceIs(trace, 'cartesian')) {
+                        addToAxlist(trace.xaxis||'x');
+                        addToAxlist(trace.yaxis||'y');
+
+                        if(astr === 'type') {
+                            doextra(['autobinx','autobiny'], true, i);
+                        }
+                    }
+                }
+
+                doextra(axlist.map(autorangeAttr), true, 0);
+                doextra(axlist.map(rangeAttr), [0, 1], 0);
+            }
+            docalc = true;
+        }
+        else if(replotAttrs.indexOf(ai)!==-1) doplot = true;
+        else if(autorangeAttrs.indexOf(ai)!==-1) docalcAutorange = true;
+    }
+
+    // check axes we've flagged for possible deletion
+    // flagAxForDelete is a hash so we can make sure we only get each axis once
+    var axListForDelete = Object.keys(flagAxForDelete);
+    axisLoop:
+    for(i = 0; i < axListForDelete.length; i++) {
+        var axId = axListForDelete[i],
+            axLetter = axId.charAt(0),
+            axAttr = axLetter + 'axis';
+        for(var j = 0; j < gd.data.length; j++) {
+            if(Plots.traceIs(gd.data[j], 'cartesian') &&
+                    (gd.data[j][axAttr] || axLetter) === axId) {
+                continue axisLoop;
+            }
+        }
+
+        // no data on this axis - delete it.
+        doextra('LAYOUT' + Plotly.Axes.id2name(axId), null, 0);
+    }
+
+    // now all attribute mods are done, as are redo and undo
+    // so we can save them
+    if(Queue) {
+        Queue.add(gd, restyle, [gd, undoit, traces], restyle, [gd, redoit, traces]);
+    }
+
+    // do we need to force a recalc?
+    var autorangeOn = false;
+    Plotly.Axes.list(gd).forEach(function(ax) {
+        if(ax.autorange) autorangeOn = true;
+    });
+    if(docalc || dolayout || (docalcAutorange && autorangeOn)) {
+        gd.calcdata = undefined;
+    }
+
+    // now update the graphics
+    // a complete layout redraw takes care of plot and
+    var seq;
+    if(dolayout) {
+        seq = [function changeLayout() {
+            var copyLayout = gd.layout;
+            gd.layout = undefined;
+            return Plotly.plot(gd, '', copyLayout);
+        }];
+    }
+    else if(docalc || doplot || docalcAutorange) {
+        seq = [Plotly.plot];
+    }
+    else {
+        Plots.supplyDefaults(gd);
+        seq = [Plots.previousPromises];
+        if(dostyle) {
+            seq.push(function doStyle() {
+                // first see if we need to do arraysToCalcdata
+                // call it regardless of what change we made, in case
+                // supplyDefaults brought in an array that was already
+                // in gd.data but not in gd._fullData previously
+                var i, cdi, arraysToCalcdata;
+                for(i = 0; i < gd.calcdata.length; i++) {
+                    cdi = gd.calcdata[i];
+                    arraysToCalcdata = (((cdi[0]||{}).trace||{})._module||{}).arraysToCalcdata;
+                    if(arraysToCalcdata) arraysToCalcdata(cdi);
+                }
+                Plots.style(gd);
+                Legend.draw(gd);
+                return Plots.previousPromises(gd);
+            });
+        }
+        if(docolorbars) {
+            seq.push(function doColorBars() {
+                gd.calcdata.forEach(function(cd) {
+                    if((cd[0].t || {}).cb) {
+                        var trace = cd[0].trace,
+                            cb = cd[0].t.cb;
+
+                        if(Plots.traceIs(trace, 'contour')) {
+                            cb.line({
+                                width: trace.contours.showlines!==false ?
+                                    trace.line.width : 0,
+                                dash: trace.line.dash,
+                                color: trace.contours.coloring==='line' ?
+                                    cb._opts.line.color : trace.line.color
+                            });
+                        }
+                        if(Plots.traceIs(trace, 'markerColorscale')) {
+                            cb.options(trace.marker.colorbar)();
+                        }
+                        else cb.options(trace.colorbar)();
+                    }
+                });
+                return Plots.previousPromises(gd);
+            });
+        }
+    }
+
+    var plotDone = Lib.syncOrAsync(seq, gd);
+
+    if(!plotDone || !plotDone.then) plotDone = Promise.resolve();
+
+    return plotDone.then(function() {
+        gd.emit('plotly_restyle', Lib.extendDeep([], [redoit, traces]));
+        return gd;
+    });
+};
+
+// swap all the data and data attributes associated with x and y
+function swapXYData(trace) {
+    var i;
+    Lib.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']);
+    if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) {
+        if(trace.transpose) delete trace.transpose;
+        else trace.transpose = true;
+    }
+    if(trace.error_x && trace.error_y) {
+        var errorY = trace.error_y,
+            copyYstyle = ('copy_ystyle' in errorY) ? errorY.copy_ystyle :
+                !(errorY.color || errorY.thickness || errorY.width);
+        Lib.swapAttrs(trace, ['error_?.copy_ystyle']);
+        if(copyYstyle) {
+            Lib.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']);
+        }
+    }
+    if(trace.hoverinfo) {
+        var hoverInfoParts = trace.hoverinfo.split('+');
+        for(i=0; i<hoverInfoParts.length; i++) {
+            if(hoverInfoParts[i]==='x') hoverInfoParts[i] = 'y';
+            else if(hoverInfoParts[i]==='y') hoverInfoParts[i] = 'x';
+        }
+        trace.hoverinfo = hoverInfoParts.join('+');
+    }
+}
+
+// relayout: change layout in an existing plot
+// can be called two ways:
+//
+// relayout(gd, astr, val)
+//      gd - graph div (string id or dom element)
+//      astr - attribute string (like 'xaxis.range[0]')
+//      val - value to give this attribute
+//
+// relayout(gd,aobj)
+//      aobj - {astr1:val1, astr2:val2...}
+//          allows setting multiple attributes simultaneously
+Plotly.relayout = function relayout(gd, astr, val) {
+    gd = getGraphDiv(gd);
+
+    if(gd.framework && gd.framework.isPolar) {
+        return Promise.resolve(gd);
+    }
+
+    var layout = gd.layout,
+        fullLayout = gd._fullLayout,
+        aobj = {},
+        dolegend = false,
+        doticks = false,
+        dolayoutstyle = false,
+        doplot = false,
+        docalc = false,
+        domodebar = false,
+        newkey, axes, keys, xyref, scene, axisAttr, i;
+
+    if(typeof astr === 'string') aobj[astr] = val;
+    else if(Lib.isPlainObject(astr)) aobj = astr;
+    else {
+        console.log('relayout fail',astr,val);
+        return Promise.reject();
+    }
+
+    if(Object.keys(aobj).length) gd.changed = true;
+
+    keys = Object.keys(aobj);
+    axes = Plotly.Axes.list(gd);
+
+    for(i = 0; i < keys.length; i++) {
+        // look for 'allaxes', split out into all axes
+        if(keys[i].indexOf('allaxes')===0) {
+            for(var j=0; j<axes.length; j++) {
+                // in case of 3D the axis are nested within a scene which is held in _id
+                scene = axes[j]._id.substr(1);
+                axisAttr = (scene.indexOf('scene') !== -1) ? (scene + '.') : '';
+                newkey = keys[i].replace('allaxes', axisAttr + axes[j]._name);
+                if(!aobj[newkey]) { aobj[newkey] = aobj[keys[i]]; }
+            }
+            delete aobj[keys[i]];
+        }
+        // split annotation.ref into xref and yref
+        if(keys[i].match(/^annotations\[[0-9-]+\].ref$/)) {
+            xyref = aobj[keys[i]].split('y');
+            aobj[keys[i].replace('ref','xref')] = xyref[0];
+            aobj[keys[i].replace('ref','yref')] = xyref.length===2 ?
+                ('y'+xyref[1]) : 'paper';
+            delete aobj[keys[i]];
+        }
+    }
+
+    // copies of the change (and previous values of anything affected)
+    // for the undo / redo queue
+    var redoit = {},
+        undoit = {};
+
+    // for attrs that interact (like scales & autoscales), save the
+    // old vals before making the change
+    // val=undefined will not set a value, just record what the value was.
+    // attr can be an array to set several at once (all to the same val)
+    function doextra(attr,val) {
+        if(Array.isArray(attr)) {
+            attr.forEach(function(a) { doextra(a,val); });
+            return;
+        }
+        // quit if explicitly setting this elsewhere
+        if(attr in aobj) return;
+
+        var p = Lib.nestedProperty(layout,attr);
+        if(!(attr in undoit)) undoit[attr] = p.get();
+        if(val!==undefined) p.set(val);
+    }
+
+    // for editing annotations or shapes - is it on autoscaled axes?
+    function refAutorange(obj, axletter) {
+        var axName = Plotly.Axes.id2name(obj[axletter+'ref']||axletter);
+        return (fullLayout[axName]||{}).autorange;
+    }
+
+    var hw = ['height', 'width'];
+
+    // alter gd.layout
+    for(var ai in aobj) {
+        var p = Lib.nestedProperty(layout,ai),
+            vi = aobj[ai],
+            plen = p.parts.length,
+            // p.parts may end with an index integer if the property is an array
+            pend = typeof p.parts[plen-1] === 'string' ? (plen-1) : (plen-2),
+            // last property in chain (leaf node)
+            pleaf = p.parts[pend],
+            // leaf plus immediate parent
+            pleafPlus = p.parts[pend - 1] + '.' + pleaf,
+            // trunk nodes (everything except the leaf)
+            ptrunk = p.parts.slice(0, pend).join('.'),
+            parentIn = Lib.nestedProperty(gd.layout, ptrunk).get(),
+            parentFull = Lib.nestedProperty(fullLayout, ptrunk).get();
+
+        redoit[ai] = vi;
+
+        // axis reverse is special - it is its own inverse
+        // op and has no flag.
+        undoit[ai] = (pleaf === 'reverse') ? vi : p.get();
+
+        // check autosize or autorange vs size and range
+        if(hw.indexOf(ai) !== -1) {
+            doextra('autosize', false);
+        }
+        else if(ai === 'autosize') {
+            doextra(hw, undefined);
+        }
+        else if(pleafPlus.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)) {
+            doextra(ptrunk+'.autorange', false);
+        }
+        else if(pleafPlus.match(/^[xyz]axis[0-9]*\.autorange$/)) {
+            doextra([ptrunk + '.range[0]',ptrunk + '.range[1]'],
+                undefined);
+        }
+        else if(pleafPlus.match(/^aspectratio\.[xyz]$/)) {
+            doextra(p.parts[0]+'.aspectmode', 'manual');
+        }
+        else if(pleafPlus.match(/^aspectmode$/)) {
+            doextra([ptrunk + '.x', ptrunk + '.y', ptrunk + '.z'], undefined);
+        }
+        else if(pleaf === 'tick0' || pleaf === 'dtick') {
+            doextra(ptrunk + '.tickmode', 'linear');
+        }
+        else if(pleaf === 'tickmode') {
+            doextra([ptrunk + '.tick0', ptrunk + '.dtick'], undefined);
+        }
+        else if(/[xy]axis[0-9]*?$/.test(pleaf) && !Object.keys(vi || {}).length) {
+            docalc = true;
+        }
+
+        // toggling log without autorange: need to also recalculate ranges
+        // logical XOR (ie are we toggling log)
+        if(pleaf==='type' && ((parentFull.type === 'log') !== (vi === 'log'))) {
+            var ax = parentIn;
+            if(!ax || !ax.range) {
+                doextra(ptrunk+'.autorange', true);
+            }
+            else if(!parentFull.autorange) {
+                var r0 = ax.range[0],
+                    r1 = ax.range[1];
+                if(vi === 'log') {
+                    // if both limits are negative, autorange
+                    if(r0 <= 0 && r1 <= 0) {
+                        doextra(ptrunk+'.autorange', true);
+                    }
+                    // if one is negative, set it 6 orders below the other.
+                    if(r0 <= 0) r0 = r1/1e6;
+                    else if(r1 <= 0) r1 = r0/1e6;
+                    // now set the range values as appropriate
+                    doextra(ptrunk+'.range[0]', Math.log(r0) / Math.LN10);
+                    doextra(ptrunk+'.range[1]', Math.log(r1) / Math.LN10);
+                }
+                else {
+                    doextra(ptrunk+'.range[0]', Math.pow(10, r0));
+                    doextra(ptrunk+'.range[1]', Math.pow(10, r1));
+                }
+            }
+            else if(vi === 'log') {
+                // just make sure the range is positive and in the right
+                // order, it'll get recalculated later
+                ax.range = (ax.range[1] > ax.range[0]) ? [1, 2] : [2, 1];
+            }
+        }
+
+        // handle axis reversal explicitly, as there's no 'reverse' flag
+        if(pleaf ==='reverse') {
+            if(parentIn.range) parentIn.range.reverse();
+            else {
+                doextra(ptrunk+'.autorange', true);
+                parentIn.range = [1, 0];
+            }
+
+            if(parentFull.autorange) docalc = true;
+            else doplot = true;
+        }
+        // send annotation and shape mods one-by-one through Annotations.draw(),
+        // don't set via nestedProperty
+        // that's because add and remove are special
+        else if(p.parts[0] === 'annotations' || p.parts[0] === 'shapes') {
+            var objNum = p.parts[1],
+                objType = p.parts[0],
+                objList = layout[objType] || [],
+                objModule = Plotly[Lib.titleCase(objType)],
+                obji = objList[objNum] || {};
+            // if p.parts is just an annotation number, and val is either
+            // 'add' or an entire annotation to add, the undo is 'remove'
+            // if val is 'remove' then undo is the whole annotation object
+            if(p.parts.length === 2) {
+                if(aobj[ai] === 'add' || Lib.isPlainObject(aobj[ai])) {
+                    undoit[ai] = 'remove';
+                }
+                else if(aobj[ai] === 'remove') {
+                    if(objNum === -1) {
+                        undoit[objType] = objList;
+                        delete undoit[ai];
+                    }
+                    else undoit[ai] = obji;
+                }
+                else console.log('???', aobj);
+            }
+            if((refAutorange(obji, 'x') || refAutorange(obji, 'y')) &&
+                    !Lib.containsAny(ai, ['color', 'opacity', 'align', 'dash'])) {
+                docalc = true;
+            }
+            // TODO: combine all edits to a given annotation / shape into one call
+            // as it is we get separate calls for x and y (or ax and ay) on move
+            objModule.draw(gd, objNum, p.parts.slice(2).join('.'), aobj[ai]);
+            delete aobj[ai];
+        }
+        // alter gd.layout
+        else {
+            // check whether we can short-circuit a full redraw
+            // 3d or geo at this point just needs to redraw.
+            if(p.parts[0].indexOf('scene') === 0) doplot = true;
+            else if(p.parts[0].indexOf('geo') === 0) doplot = true;
+            else if(fullLayout._hasGL2D &&
+                (ai.indexOf('axis') !== -1 || p.parts[0] === 'plot_bgcolor')
+            ) doplot = true;
+            else if(ai === 'hiddenlabels') docalc = true;
+            else if(p.parts[0].indexOf('legend')!==-1) dolegend = true;
+            else if(ai.indexOf('title')!==-1) doticks = true;
+            else if(p.parts[0].indexOf('bgcolor')!==-1) dolayoutstyle = true;
+            else if(p.parts.length>1 &&
+                    Lib.containsAny(p.parts[1], ['tick', 'exponent', 'grid', 'zeroline'])) {
+                doticks = true;
+            }
+            else if(ai.indexOf('.linewidth')!==-1 &&
+                    ai.indexOf('axis')!==-1) {
+                doticks = dolayoutstyle = true;
+            }
+            else if(p.parts.length>1 && p.parts[1].indexOf('line')!==-1) {
+                dolayoutstyle = true;
+            }
+            else if(p.parts.length>1 && p.parts[1]==='mirror') {
+                doticks = dolayoutstyle = true;
+            }
+            else if(ai==='margin.pad') {
+                doticks = dolayoutstyle = true;
+            }
+            else if(p.parts[0]==='margin' ||
+                    p.parts[1]==='autorange' ||
+                    p.parts[1]==='rangemode' ||
+                    p.parts[1]==='type' ||
+                    p.parts[1]==='domain' ||
+                    ai.match(/^(bar|box|font)/)) {
+                docalc = true;
+            }
+            /*
+             * hovermode and dragmode don't need any redrawing, since they just
+             * affect reaction to user input. everything else, assume full replot.
+             * height, width, autosize get dealt with below. Except for the case of
+             * of subplots - scenes - which require scene.updateFx to be called.
+             */
+            else if(['hovermode', 'dragmode'].indexOf(ai) !== -1) domodebar = true;
+            else if(['hovermode','dragmode','height',
+                    'width','autosize'].indexOf(ai)===-1) {
+                doplot = true;
+            }
+
+            p.set(vi);
+        }
+    }
+    // now all attribute mods are done, as are
+    // redo and undo so we can save them
+    if(Queue) {
+        Queue.add(gd, relayout, [gd, undoit], relayout, [gd, redoit]);
+    }
+
+    // calculate autosizing - if size hasn't changed,
+    // will remove h&w so we don't need to redraw
+    if(aobj.autosize) aobj = plotAutoSize(gd,aobj);
+
+    if(aobj.height || aobj.width || aobj.autosize) docalc = true;
+
+    // redraw
+    // first check if there's still anything to do
+    var ak = Object.keys(aobj),
+        seq = [Plots.previousPromises];
+
+    if(doplot || docalc) {
+        seq.push(function layoutReplot() {
+            // force plot() to redo the layout
+            gd.layout = undefined;
+
+            // force it to redo calcdata?
+            if(docalc) gd.calcdata = undefined;
+
+            // replot with the modified layout
+            return Plotly.plot(gd, '', layout);
+        });
+    }
+    else if(ak.length) {
+        // if we didn't need to redraw entirely, just do the needed parts
+        Plots.supplyDefaults(gd);
+        fullLayout = gd._fullLayout;
+
+        if(dolegend) {
+            seq.push(function doLegend() {
+                Legend.draw(gd);
+                return Plots.previousPromises(gd);
+            });
+        }
+
+        if(dolayoutstyle) seq.push(layoutStyles);
+
+        if(doticks) {
+            seq.push(function() {
+                Plotly.Axes.doTicks(gd,'redraw');
+                Titles.draw(gd, 'gtitle');
+                return Plots.previousPromises(gd);
+            });
+        }
+
+        // this is decoupled enough it doesn't need async regardless
+        if(domodebar) {
+            var subplotIds;
+            manageModeBar(gd);
+
+            subplotIds = Plots.getSubplotIds(fullLayout, 'gl3d');
+            for(i = 0; i < subplotIds.length; i++) {
+                scene = fullLayout[subplotIds[i]]._scene;
+                scene.updateFx(fullLayout.dragmode, fullLayout.hovermode);
+            }
+
+            subplotIds = Plots.getSubplotIds(fullLayout, 'gl2d');
+            for(i = 0; i < subplotIds.length; i++) {
+                scene = fullLayout._plots[subplotIds[i]]._scene2d;
+                scene.updateFx(fullLayout);
+            }
+
+            subplotIds = Plots.getSubplotIds(fullLayout, 'geo');
+            for(i = 0; i < subplotIds.length; i++) {
+                var geo = fullLayout[subplotIds[i]]._geo;
+                geo.updateFx(fullLayout.hovermode);
+            }
+        }
+    }
+
+    var plotDone = Lib.syncOrAsync(seq, gd);
+
+    if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
+
+    return plotDone.then(function() {
+        gd.emit('plotly_relayout', Lib.extendDeep({}, redoit));
+        return gd;
+    });
+};
+
+/**
+ * Reduce all reserved margin objects to a single required margin reservation.
+ *
+ * @param {Object} margins
+ * @returns {{left: number, right: number, bottom: number, top: number}}
+ */
+function calculateReservedMargins(margins) {
+    var resultingMargin = {left: 0, right: 0, bottom: 0, top: 0},
+        marginName;
+
+    if(margins) {
+        for(marginName in margins) {
+            if(margins.hasOwnProperty(marginName)) {
+                resultingMargin.left += margins[marginName].left || 0;
+                resultingMargin.right += margins[marginName].right || 0;
+                resultingMargin.bottom += margins[marginName].bottom || 0;
+                resultingMargin.top += margins[marginName].top || 0;
+            }
+        }
+    }
+    return resultingMargin;
+}
+
+function plotAutoSize(gd, aobj) {
+    var fullLayout = gd._fullLayout,
+        context = gd._context,
+        computedStyle;
+
+    var newHeight, newWidth;
+
+    gd.emit('plotly_autosize');
+
+    // embedded in an iframe - just take the full iframe size
+    // if we get to this point, with no aspect ratio restrictions
+    if(gd._context.fillFrame) {
+        newWidth = window.innerWidth;
+        newHeight = window.innerHeight;
+
+        // somehow we get a few extra px height sometimes...
+        // just hide it
+        document.body.style.overflow = 'hidden';
+    }
+    else if(isNumeric(context.frameMargins) && context.frameMargins > 0) {
+        var reservedMargins = calculateReservedMargins(gd._boundingBoxMargins),
+            reservedWidth = reservedMargins.left + reservedMargins.right,
+            reservedHeight = reservedMargins.bottom + reservedMargins.top,
+            gdBB = fullLayout._container.node().getBoundingClientRect(),
+            factor = 1 - 2*context.frameMargins;
+
+        newWidth = Math.round(factor * (gdBB.width - reservedWidth));
+        newHeight = Math.round(factor * (gdBB.height - reservedHeight));
+    }
+    else {
+        // plotly.js - let the developers do what they want, either
+        // provide height and width for the container div,
+        // specify size in layout, or take the defaults,
+        // but don't enforce any ratio restrictions
+        computedStyle = window.getComputedStyle(gd);
+        newHeight = parseFloat(computedStyle.height) || fullLayout.height;
+        newWidth = parseFloat(computedStyle.width) || fullLayout.width;
+    }
+
+    if(Math.abs(fullLayout.width - newWidth) > 1 ||
+            Math.abs(fullLayout.height - newHeight) > 1) {
+        fullLayout.height = gd.layout.height = newHeight;
+        fullLayout.width = gd.layout.width = newWidth;
+    }
+    // if there's no size change, update layout but
+    // delete the autosize attr so we don't redraw
+    // but can't call layoutStyles for initial autosize
+    else if(fullLayout.autosize !== 'initial') {
+        delete(aobj.autosize);
+        fullLayout.autosize = gd.layout.autosize = true;
+    }
+
+    Plots.sanitizeMargins(fullLayout);
+
+    return aobj;
+}
+
+// -------------------------------------------------------
+// makePlotFramework: Create the plot container and axes
+// -------------------------------------------------------
+function makePlotFramework(gd) {
+    var gd3 = d3.select(gd),
+        fullLayout = gd._fullLayout;
+
+    // TODO - find a better place for 3D to initialize axes
+    if(fullLayout._hasGL3D) Plots.subplotsRegistry.gl3d.initAxes(gd);
+
+    // Plot container
+    fullLayout._container = gd3.selectAll('.plot-container').data([0]);
+    fullLayout._container.enter().insert('div', ':first-child')
+        .classed('plot-container', true)
+        .classed('plotly', true);
+
+    // Make the svg container
+    fullLayout._paperdiv = fullLayout._container.selectAll('.svg-container').data([0]);
+    fullLayout._paperdiv.enter().append('div')
+        .classed('svg-container',true)
+        .style('position','relative');
+
+    // Initial autosize
+    if(fullLayout.autosize === 'initial') {
+        plotAutoSize(gd, {});
+        fullLayout.autosize = true;
+        gd.layout.autosize = true;
+    }
+
+    // Make the graph containers
+    // start fresh each time we get here, so we know the order comes out
+    // right, rather than enter/exit which can muck up the order
+    // TODO: sort out all the ordering so we don't have to
+    // explicitly delete anything
+    fullLayout._glcontainer = fullLayout._paperdiv.selectAll('.gl-container')
+        .data([0]);
+    fullLayout._glcontainer.enter().append('div')
+        .classed('gl-container', true);
+
+    fullLayout._geocontainer = fullLayout._paperdiv.selectAll('.geo-container')
+        .data([0]);
+    fullLayout._geocontainer.enter().append('div')
+        .classed('geo-container', true);
+
+    fullLayout._paperdiv.selectAll('.main-svg').remove();
+
+    fullLayout._paper = fullLayout._paperdiv.insert('svg', ':first-child')
+        .classed('main-svg', true);
+
+    fullLayout._toppaper = fullLayout._paperdiv.append('svg')
+        .classed('main-svg', true);
+
+    if(!fullLayout._uid) {
+        var otherUids = [];
+        d3.selectAll('defs').each(function() {
+            if(this.id) otherUids.push(this.id.split('-')[1]);
+        });
+        fullLayout._uid = Lib.randstr(otherUids);
+    }
+
+    fullLayout._paperdiv.selectAll('.main-svg')
+        .attr(xmlnsNamespaces.svgAttrs);
+
+    fullLayout._defs = fullLayout._paper.append('defs')
+        .attr('id', 'defs-' + fullLayout._uid);
+
+    fullLayout._draggers = fullLayout._paper.append('g')
+        .classed('draglayer', true);
+
+    var subplots = Plotly.Axes.getSubplots(gd);
+    if(subplots.join('') !== Object.keys(gd._fullLayout._plots || {}).join('')) {
+        makeSubplots(gd, subplots);
+    }
+
+    if(fullLayout._hasCartesian) makeCartesianPlotFramwork(gd, subplots);
+
+    // single shape and pie layers for the whole plot
+    fullLayout._shapelayer = fullLayout._paper.append('g').classed('shapelayer', true);
+    fullLayout._pielayer = fullLayout._paper.append('g').classed('pielayer', true);
+
+    // fill in image server scrape-svg
+    fullLayout._glimages = fullLayout._paper.append('g').classed('glimages', true);
+    fullLayout._geoimages = fullLayout._paper.append('g').classed('geoimages', true);
+
+    // lastly info (legend, annotations) and hover layers go on top
+    // these are in a different svg element normally, but get collapsed into a single
+    // svg when exporting (after inserting 3D)
+    fullLayout._infolayer = fullLayout._toppaper.append('g').classed('infolayer', true);
+    fullLayout._hoverlayer = fullLayout._toppaper.append('g').classed('hoverlayer', true);
+
+    gd.emit('plotly_framework');
+
+    // position and style the containers, make main title
+    var frameWorkDone = Lib.syncOrAsync([
+        layoutStyles,
+        function goAxes() { return Plotly.Axes.doTicks(gd,'redraw'); },
+        Fx.init
+    ], gd);
+
+    if(frameWorkDone && frameWorkDone.then) {
+        gd._promises.push(frameWorkDone);
+    }
+
+    return frameWorkDone;
+}
+
+// create '_plots' object grouping x/y axes into subplots
+// to be better manage subplots
+function makeSubplots(gd, subplots) {
+    var _plots = gd._fullLayout._plots = {};
+    var subplot, plotinfo;
+
+    function getAxisFunc(subplot, axLetter) {
+        return function() {
+            return Plotly.Axes.getFromId(gd, subplot, axLetter);
+        };
+    }
+
+    for(var i = 0; i < subplots.length; i++) {
+        subplot = subplots[i];
+        plotinfo = _plots[subplot] = {};
+
+        plotinfo.id = subplot;
+
+        // references to the axis objects controlling this subplot
+        plotinfo.x = getAxisFunc(subplot, 'x');
+        plotinfo.y = getAxisFunc(subplot, 'y');
+
+        // TODO investigate why replacing calls to .x and .y
+        // for .xaxis and .yaxis makes the `pseudo_html`
+        // test image fail
+        plotinfo.xaxis = plotinfo.x();
+        plotinfo.yaxis = plotinfo.y();
+    }
+}
+
+function makeCartesianPlotFramwork(gd, subplots) {
+    var fullLayout = gd._fullLayout;
+
+    // Layers to keep plot types in the right order.
+    // from back to front:
+    // 1. heatmaps, 2D histos and contour maps
+    // 2. bars / 1D histos
+    // 3. errorbars for bars and scatter
+    // 4. scatter
+    // 5. box plots
+    function plotLayers(svg) {
+        svg.append('g').classed('imagelayer', true);
+        svg.append('g').classed('maplayer', true);
+        svg.append('g').classed('barlayer', true);
+        svg.append('g').classed('errorlayer', true);
+        svg.append('g').classed('boxlayer', true);
+        svg.append('g').classed('scatterlayer', true);
+    }
+
+    // create all the layers in order, so we know they'll stay in order
+    var overlays = [];
+
+    fullLayout._paper.selectAll('g.subplot').data(subplots)
+      .enter().append('g')
+        .classed('subplot', true)
+        .each(function(subplot) {
+            var plotinfo = fullLayout._plots[subplot],
+                plotgroup = plotinfo.plotgroup = d3.select(this).classed(subplot, true),
+                xa = plotinfo.xaxis,
+                ya = plotinfo.yaxis;
+
+            // references to any subplots overlaid on this one
+            plotinfo.overlays = [];
+
+            // is this subplot overlaid on another?
+            // ax.overlaying is the id of another axis of the same
+            // dimension that this one overlays to be an overlaid subplot,
+            // the main plot must exist make sure we're not trying to
+            // overlay on an axis that's already overlaying another
+            var xa2 = Plotly.Axes.getFromId(gd, xa.overlaying) || xa;
+            if(xa2 !== xa && xa2.overlaying) {
+                xa2 = xa;
+                xa.overlaying = false;
+            }
+
+            var ya2 = Plotly.Axes.getFromId(gd, ya.overlaying) || ya;
+            if(ya2 !== ya && ya2.overlaying) {
+                ya2 = ya;
+                ya.overlaying = false;
+            }
+
+            var mainplot = xa2._id+ya2._id;
+            if(mainplot!==subplot && subplots.indexOf(mainplot)!==-1) {
+                plotinfo.mainplot = mainplot;
+                overlays.push(plotinfo);
+
+                // for now force overlays to overlay completely... so they
+                // can drag together correctly and share backgrounds.
+                // Later perhaps we make separate axis domain and
+                // tick/line domain or something, so they can still share
+                // the (possibly larger) dragger and background but don't
+                // have to both be drawn over that whole domain
+                xa.domain = xa2.domain.slice();
+                ya.domain = ya2.domain.slice();
+            }
+            else {
+                // main subplot - make the components of
+                // the plot and containers for overlays
+                plotinfo.bg = plotgroup.append('rect')
+                    .style('stroke-width', 0);
+                plotinfo.gridlayer = plotgroup.append('g');
+                plotinfo.overgrid = plotgroup.append('g');
+                plotinfo.zerolinelayer = plotgroup.append('g');
+                plotinfo.overzero = plotgroup.append('g');
+                plotinfo.plot = plotgroup.append('svg').call(plotLayers);
+                plotinfo.overplot = plotgroup.append('g');
+                plotinfo.xlines = plotgroup.append('path');
+                plotinfo.ylines = plotgroup.append('path');
+                plotinfo.overlines = plotgroup.append('g');
+                plotinfo.xaxislayer = plotgroup.append('g');
+                plotinfo.yaxislayer = plotgroup.append('g');
+                plotinfo.overaxes = plotgroup.append('g');
+
+                // make separate drag layers for each subplot,
+                // but append them to paper rather than the plot groups,
+                // so they end up on top of the rest
+            }
+            plotinfo.draglayer = fullLayout._draggers.append('g');
+        });
+
+    // now make the components of overlaid subplots
+    // overlays don't have backgrounds, and append all
+    // their other components to the corresponding
+    // extra groups of their main Plots.
+    overlays.forEach(function(plotinfo) {
+        var mainplot = fullLayout._plots[plotinfo.mainplot];
+        mainplot.overlays.push(plotinfo);
+
+        plotinfo.gridlayer = mainplot.overgrid.append('g');
+        plotinfo.zerolinelayer = mainplot.overzero.append('g');
+        plotinfo.plot = mainplot.overplot.append('svg').call(plotLayers);
+        plotinfo.xlines = mainplot.overlines.append('path');
+        plotinfo.ylines = mainplot.overlines.append('path');
+        plotinfo.xaxislayer = mainplot.overaxes.append('g');
+        plotinfo.yaxislayer = mainplot.overaxes.append('g');
+    });
+
+    // common attributes for all subplots, overlays or not
+    subplots.forEach(function(subplot) {
+        var plotinfo = fullLayout._plots[subplot];
+
+        plotinfo.plot
+            .attr('preserveAspectRatio', 'none')
+            .style('fill', 'none');
+        plotinfo.xlines
+            .style('fill', 'none')
+            .classed('crisp', true);
+        plotinfo.ylines
+            .style('fill', 'none')
+            .classed('crisp', true);
+    });
+}
+
+// layoutStyles: styling for plot layout elements
+function layoutStyles(gd) {
+    return Lib.syncOrAsync([Plots.doAutoMargin, lsInner], gd);
+}
+
+function lsInner(gd) {
+    var fullLayout = gd._fullLayout,
+        gs = fullLayout._size,
+        axList = Plotly.Axes.list(gd),
+        i;
+
+    // clear axis line positions, to be set in the subplot loop below
+    for(i = 0; i < axList.length; i++) axList[i]._linepositions = {};
+
+    fullLayout._paperdiv
+        .style({
+            width: fullLayout.width + 'px',
+            height: fullLayout.height + 'px'
+        })
+        .selectAll('.main-svg')
+            .call(Drawing.setSize, fullLayout.width, fullLayout.height);
+
+    gd._context.setBackground(gd, fullLayout.paper_bgcolor);
+
+    var freefinished = [];
+    fullLayout._paper.selectAll('g.subplot').each(function(subplot) {
+        var plotinfo = fullLayout._plots[subplot],
+            xa = Plotly.Axes.getFromId(gd, subplot, 'x'),
+            ya = Plotly.Axes.getFromId(gd, subplot, 'y');
+        xa.setScale(); // this may already be done... not sure
+        ya.setScale();
+
+        if(plotinfo.bg) {
+            plotinfo.bg
+                .call(Drawing.setRect,
+                    xa._offset-gs.p, ya._offset-gs.p,
+                    xa._length+2*gs.p, ya._length+2*gs.p)
+                .call(Color.fill, fullLayout.plot_bgcolor);
+        }
+        plotinfo.plot
+            .call(Drawing.setRect,
+                xa._offset, ya._offset, xa._length, ya._length);
+
+        var xlw = Drawing.crispRound(gd, xa.linewidth, 1),
+            ylw = Drawing.crispRound(gd, ya.linewidth, 1),
+            xp = gs.p+ylw,
+            xpathPrefix = 'M'+(-xp)+',',
+            xpathSuffix = 'h'+(xa._length+2*xp),
+            showfreex = xa.anchor==='free' &&
+                freefinished.indexOf(xa._id)===-1,
+            freeposx = gs.h*(1-(xa.position||0))+((xlw/2)%1),
+            showbottom =
+                (xa.anchor===ya._id && (xa.mirror||xa.side!=='top')) ||
+                xa.mirror==='all' || xa.mirror==='allticks' ||
+                (xa.mirrors && xa.mirrors[ya._id+'bottom']),
+            bottompos = ya._length+gs.p+xlw/2,
+            showtop =
+                (xa.anchor===ya._id && (xa.mirror||xa.side==='top')) ||
+                xa.mirror==='all' || xa.mirror==='allticks' ||
+                (xa.mirrors && xa.mirrors[ya._id+'top']),
+            toppos = -gs.p-xlw/2,
+
+            // shorten y axis lines so they don't overlap x axis lines
+            yp = gs.p,
+            // except where there's no x line
+            // TODO: this gets more complicated with multiple x and y axes
+            ypbottom = showbottom ? 0 : xlw,
+            yptop = showtop ? 0 : xlw,
+            ypathSuffix = ','+(-yp-yptop)+
+                'v'+(ya._length+2*yp+yptop+ypbottom),
+            showfreey = ya.anchor==='free' &&
+                freefinished.indexOf(ya._id)===-1,
+            freeposy = gs.w*(ya.position||0)+((ylw/2)%1),
+            showleft =
+                (ya.anchor===xa._id && (ya.mirror||ya.side!=='right')) ||
+                ya.mirror==='all' || ya.mirror==='allticks' ||
+                (ya.mirrors && ya.mirrors[xa._id+'left']),
+            leftpos = -gs.p-ylw/2,
+            showright =
+                (ya.anchor===xa._id && (ya.mirror||ya.side==='right')) ||
+                ya.mirror==='all' || ya.mirror==='allticks' ||
+                (ya.mirrors && ya.mirrors[xa._id+'right']),
+            rightpos = xa._length+gs.p+ylw/2;
+
+        // save axis line positions for ticks, draggers, etc to reference
+        // each subplot gets an entry:
+        //    [left or bottom, right or top, free, main]
+        // main is the position at which to draw labels and draggers, if any
+        xa._linepositions[subplot] = [
+            showbottom ? bottompos : undefined,
+            showtop ? toppos : undefined,
+            showfreex ? freeposx : undefined
+        ];
+        if(xa.anchor===ya._id) {
+            xa._linepositions[subplot][3] = xa.side==='top' ?
+                toppos : bottompos;
+        }
+        else if(showfreex) {
+            xa._linepositions[subplot][3] = freeposx;
+        }
+
+        ya._linepositions[subplot] = [
+            showleft ? leftpos : undefined,
+            showright ? rightpos : undefined,
+            showfreey ? freeposy : undefined
+        ];
+        if(ya.anchor===xa._id) {
+            ya._linepositions[subplot][3] = ya.side==='right' ?
+                rightpos : leftpos;
+        }
+        else if(showfreey) {
+            ya._linepositions[subplot][3] = freeposy;
+        }
+
+        // translate all the extra stuff to have the
+        // same origin as the plot area or axes
+        var origin = 'translate('+xa._offset+','+ya._offset+')',
+            originx = origin,
+            originy = origin;
+        if(showfreex) {
+            originx = 'translate('+xa._offset+','+gs.t+')';
+            toppos += ya._offset - gs.t;
+            bottompos += ya._offset - gs.t;
+        }
+        if(showfreey) {
+            originy = 'translate('+gs.l+','+ya._offset+')';
+            leftpos += xa._offset - gs.l;
+            rightpos += xa._offset - gs.l;
+        }
+
+        plotinfo.xlines
+            .attr('transform', originx)
+            .attr('d',(
+                (showbottom ? (xpathPrefix+bottompos+xpathSuffix) : '') +
+                (showtop ? (xpathPrefix+toppos+xpathSuffix) : '') +
+                (showfreex ? (xpathPrefix+freeposx+xpathSuffix) : '')) ||
+                // so it doesn't barf with no lines shown
+                'M0,0')
+            .style('stroke-width',xlw+'px')
+            .call(Color.stroke, xa.showline ?
+                xa.linecolor : 'rgba(0,0,0,0)');
+        plotinfo.ylines
+            .attr('transform', originy)
+            .attr('d',(
+                (showleft ? ('M'+leftpos+ypathSuffix) : '') +
+                (showright ? ('M'+rightpos+ypathSuffix) : '') +
+                (showfreey ? ('M'+freeposy+ypathSuffix) : '')) ||
+                'M0,0')
+            .attr('stroke-width',ylw+'px')
+            .call(Color.stroke,ya.showline ?
+                ya.linecolor : 'rgba(0,0,0,0)');
+
+        plotinfo.xaxislayer.attr('transform',originx);
+        plotinfo.yaxislayer.attr('transform',originy);
+        plotinfo.gridlayer.attr('transform',origin);
+        plotinfo.zerolinelayer.attr('transform',origin);
+        plotinfo.draglayer.attr('transform',origin);
+
+        // mark free axes as displayed, so we don't draw them again
+        if(showfreex) { freefinished.push(xa._id); }
+        if(showfreey) { freefinished.push(ya._id); }
+    });
+
+    Plotly.Axes.makeClipPaths(gd);
+
+    Titles.draw(gd, 'gtitle');
+
+    manageModeBar(gd);
+
+    return gd._promises.length && Promise.all(gd._promises);
+}
+
+},{"../components/color":299,"../components/drawing":317,"../components/errorbars":323,"../components/legend":326,"../components/modebar/manage":329,"../components/shapes":331,"../components/titles":332,"../constants/xmlns_namespaces":338,"../lib":349,"../lib/events":344,"../lib/queue":355,"../plotly":366,"../plots/cartesian/graph_interact":374,"../plots/plots":413,"d3":70,"fast-isnumeric":74,"gl-mat4/fromQuat":91}],363:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+/**
+ * This will be transfered over to gd and overridden by
+ * config args to Plotly.plot.
+ *
+ * The defaults are the appropriate settings for plotly.js,
+ * so we get the right experience without any config argument.
+ */
+
+module.exports = {
+
+    // no interactivity, for export or image generation
+    staticPlot: false,
+
+    // we can edit titles, move annotations, etc
+    editable: false,
+
+    // plot will respect layout.autosize=true and infer its container size
+    autosizable: false,
+
+    // if we DO autosize, do we fill the container or the screen?
+    fillFrame: false,
+
+    // if we DO autosize, set the frame margins in percents of plot size
+    frameMargins: 0,
+
+    // mousewheel or two-finger scroll zooms the plot
+    scrollZoom: false,
+
+    // double click interaction (false, 'reset', 'autosize' or 'reset+autosize')
+    doubleClick: 'reset+autosize',
+
+    // new users see some hints about interactivity
+    showTips: true,
+
+    // link to open this plot in plotly
+    showLink: false,
+
+    // if we show a link, does it contain data or just link to a plotly file?
+    sendData: true,
+
+    // text appearing in the sendData link
+    linkText: 'Edit chart',
+
+    // false or function adding source(s) to linkText <text>
+    showSources: false,
+
+    // display the mode bar (true, false, or 'hover')
+    displayModeBar: 'hover',
+
+    // remove mode bar button by name
+    // (see ./components/modebar/buttons.js for the list of names)
+    modeBarButtonsToRemove: [],
+
+    // add mode bar button using config objects
+    // (see ./components/modebar/buttons.js for list of arguments)
+    modeBarButtonsToAdd: [],
+
+    // fully custom mode bar buttons as nested array,
+    // where the outer arrays represents button groups, and
+    // the inner arrays have buttons config objects or names of default buttons
+    // (see ./components/modebar/buttons.js for more info)
+    modeBarButtons: false,
+
+    // add the plotly logo on the end of the mode bar
+    displaylogo: true,
+
+    // increase the pixel ratio for Gl plot images
+    plotGlPixelRatio: 2,
+
+    // function to add the background color to a different container
+    // or 'opaque' to ensure there's white behind it
+    setBackground: defaultSetBackground,
+
+    // URL to topojson files used in geo charts
+    topojsonURL: 'https://cdn.plot.ly/'
+
+};
+
+// where and how the background gets set can be overridden by context
+// so we define the default (plotlyjs) behavior here
+function defaultSetBackground(gd, bgColor) {
+    try {
+        gd._fullLayout._paper.style('background', bgColor);
+    }
+    catch(e) { console.log(e); }
+}
+
+},{}],364:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../plotly');
+var Plots = require('../plots/plots');
+var Lib = require('../lib');
+
+var extendFlat = Lib.extendFlat;
+var extendDeep = Lib.extendDeep;
+var extendDeepAll = Lib.extendDeepAll;
+
+var NESTED_MODULE = '_nestedModules',
+    COMPOSED_MODULE = '_composedModules',
+    IS_SUBPLOT_OBJ = '_isSubplotObj',
+    IS_LINKED_TO_ARRAY = '_isLinkedToArray',
+    DEPRECATED = '_deprecated';
+
+// list of underscore attributes to keep in schema as is
+var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, DEPRECATED];
+
+var plotSchema = {
+    traces: {},
+    layout: {},
+    defs: {}
+};
+
+// FIXME polar attribute are not part of Plotly yet
+var polarAreaAttrs = require('../plots/polar/area_attributes'),
+    polarAxisAttrs = require('../plots/polar/axis_attributes');
+
+var PlotSchema = module.exports = {};
+
+
+PlotSchema.get = function() {
+    Plots.allTypes
+        .concat('area')  // FIXME polar 'area' attributes
+        .forEach(getTraceAttributes);
+
+    getLayoutAttributes();
+    getDefs();
+    return plotSchema;
+};
+
+PlotSchema.crawl = function(attrs, callback) {
+    Object.keys(attrs).forEach(function(attrName) {
+        var attr = attrs[attrName];
+
+        if(UNDERSCORE_ATTRS.indexOf(attrName) !== -1) return;
+
+        callback(attr, attrName, attrs);
+
+        if(PlotSchema.isValObject(attr)) return;
+        if(Lib.isPlainObject(attr)) PlotSchema.crawl(attr, callback);
+    });
+};
+
+PlotSchema.isValObject = function(obj) {
+    return obj && obj.valType !== undefined;
+};
+
+function getTraceAttributes(type) {
+    var globalAttributes = Plots.attributes,
+        _module = getModule({type: type}),
+        meta = getMeta(type),
+        subplotRegistry = getSubplotRegistry(type);
+
+    var attributes = {},
+        layoutAttributes = {};
+
+    // make 'type' the first attribute in the object
+    attributes.type = null;
+
+    // global attributes (same for all trace types)
+    extendDeep(attributes, globalAttributes);
+
+    // module attributes (+ nested + composed)
+    attributes = coupleAttrs(
+        _module.attributes, attributes, 'attributes', type
+    );
+
+    // subplot attributes
+    if(subplotRegistry.attributes !== undefined) {
+        extendDeep(attributes, subplotRegistry.attributes);
+    }
+
+    // 'type' gets overwritten by globalAttributes; reset it here
+    attributes.type = type;
+
+    attributes = removeUnderscoreAttrs(attributes);
+    mergeValTypeAndRole(attributes);
+    plotSchema.traces[type] = extendFlat({},
+        meta,
+        { attributes: attributes }
+    );
+
+    // trace-specific layout attributes
+    if(_module.layoutAttributes !== undefined) {
+        layoutAttributes = coupleAttrs(
+            _module.layoutAttributes, layoutAttributes, 'layoutAttributes', type
+        );
+
+        mergeValTypeAndRole(layoutAttributes);
+        plotSchema.traces[type].layoutAttributes = layoutAttributes;
+    }
+}
+
+function getLayoutAttributes() {
+    var globalLayoutAttributes = Plots.layoutAttributes,
+        layoutAttributes = {};
+
+    // layout module attributes (+ nested + composed)
+    layoutAttributes = coupleAttrs(
+        globalLayoutAttributes, layoutAttributes, 'layoutAttributes', '*'
+    );
+
+    // FIXME polar layout attributes
+    layoutAttributes = assignPolarLayoutAttrs(layoutAttributes);
+
+    // add IS_SUBPLOT_OBJ attribute
+    layoutAttributes = handleSubplotObjs(layoutAttributes);
+
+    layoutAttributes = removeUnderscoreAttrs(layoutAttributes);
+    mergeValTypeAndRole(layoutAttributes);
+
+    // generate IS_LINKED_TO_ARRAY structure
+    layoutAttributes = handleLinkedToArray(layoutAttributes);
+
+    plotSchema.layout = { layoutAttributes: layoutAttributes };
+}
+
+function getDefs() {
+    plotSchema.defs = {
+        valObjects: Lib.valObjects,
+        metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role'])
+    };
+}
+
+function coupleAttrs(attrsIn, attrsOut, whichAttrs, type) {
+    var nestedModule, nestedAttrs, nestedReference,
+        composedModule, composedAttrs;
+
+    Object.keys(attrsIn).forEach(function(k) {
+
+        if(k === NESTED_MODULE) {
+            Object.keys(attrsIn[k]).forEach(function(kk) {
+                nestedModule = getModule({module: attrsIn[k][kk]});
+                if(nestedModule === undefined) return;
+
+                nestedAttrs = nestedModule[whichAttrs];
+                nestedReference = coupleAttrs(
+                    nestedAttrs, {}, whichAttrs, type
+                );
+
+                Lib.nestedProperty(attrsOut, kk)
+                    .set(extendDeep({}, nestedReference));
+            });
+            return;
+        }
+
+        if(k === COMPOSED_MODULE) {
+            Object.keys(attrsIn[k]).forEach(function(kk) {
+                if(kk !== type) return;
+
+                composedModule = getModule({module: attrsIn[k][kk]});
+                if(composedModule === undefined) return;
+
+                composedAttrs = composedModule[whichAttrs];
+                composedAttrs = coupleAttrs(
+                    composedAttrs, {}, whichAttrs, type
+                );
+
+                extendDeepAll(attrsOut, composedAttrs);
+            });
+            return;
+        }
+
+        attrsOut[k] = Lib.isPlainObject(attrsIn[k]) ?
+            extendDeepAll({}, attrsIn[k]) :
+            attrsIn[k];
+    });
+
+    return attrsOut;
+}
+
+function mergeValTypeAndRole(attrs) {
+
+    function makeSrcAttr(attrName) {
+        return {
+            valType: 'string',
+            
+            
+        };
+    }
+
+    function callback(attr, attrName, attrs) {
+        if(PlotSchema.isValObject(attr)) {
+            if(attr.valType === 'data_array') {
+                // all 'data_array' attrs have role 'data'
+                attr.role = 'data';
+                // all 'data_array' attrs have a corresponding 'src' attr
+                attrs[attrName + 'src'] = makeSrcAttr(attrName);
+            }
+            else if(attr.arrayOk === true) {
+                // all 'arrayOk' attrs have a corresponding 'src' attr
+                attrs[attrName + 'src'] = makeSrcAttr(attrName);
+            }
+        }
+        else if(Lib.isPlainObject(attr)) {
+            // all attrs container objects get role 'object'
+            attr.role = 'object';
+        }
+    }
+
+    PlotSchema.crawl(attrs, callback);
+}
+
+// helper methods
+
+function getModule(arg) {
+    if('type' in arg) {
+        return (arg.type === 'area') ?  // FIXME
+            { attributes: polarAreaAttrs } :
+            Plots.getModule({type: arg.type});
+    }
+
+    var subplotsRegistry = Plots.subplotsRegistry,
+        _module = arg.module;
+
+    if(subplotsRegistry[_module]) return subplotsRegistry[_module];
+    else if('module' in arg) return Plotly[_module];
+}
+
+function removeUnderscoreAttrs(attributes) {
+    Object.keys(attributes).forEach(function(k) {
+        if(k.charAt(0) === '_' &&
+            UNDERSCORE_ATTRS.indexOf(k) === -1) delete attributes[k];
+    });
+    return attributes;
+}
+
+function getMeta(type) {
+    if(type === 'area') return {};  // FIXME
+    return Plots.modules[type].meta || {};
+}
+
+function assignPolarLayoutAttrs(layoutAttributes) {
+    extendFlat(layoutAttributes, {
+        radialaxis: polarAxisAttrs.radialaxis,
+        angularaxis: polarAxisAttrs.angularaxis
+    });
+
+    extendFlat(layoutAttributes, polarAxisAttrs.layout);
+
+    return layoutAttributes;  // FIXME
+}
+
+function getSubplotRegistry(traceType) {
+    if(traceType === 'area') return {};  // FIXME
+
+    var subplotsRegistry = Plots.subplotsRegistry,
+        subplotType = Object.keys(subplotsRegistry).filter(function(subplotType) {
+            return Plots.traceIs({type: traceType}, subplotType);
+        })[0];
+
+    if(subplotType === undefined) return {};
+
+    return subplotsRegistry[subplotType];
+}
+
+function handleSubplotObjs(layoutAttributes) {
+    var subplotsRegistry = Plots.subplotsRegistry;
+
+    Object.keys(layoutAttributes).forEach(function(k) {
+        Object.keys(subplotsRegistry).forEach(function(subplotType) {
+            var subplotRegistry = subplotsRegistry[subplotType],
+                isSubplotObj;
+
+            if(subplotType === 'cartesian' || subplotType === 'gl2d') {
+                isSubplotObj = (
+                    subplotRegistry.attrRegex.x.test(k) ||
+                    subplotRegistry.attrRegex.y.test(k)
+                );
+            }
+            else {
+                isSubplotObj = subplotRegistry.attrRegex.test(k);
+            }
+
+            if(isSubplotObj) layoutAttributes[k][IS_SUBPLOT_OBJ] = true;
+        });
+    });
+
+    return layoutAttributes;
+}
+
+function handleLinkedToArray(layoutAttributes) {
+    Object.keys(layoutAttributes).forEach(function(k) {
+        var attr = extendDeep({}, layoutAttributes[k]);
+
+        if(attr[IS_LINKED_TO_ARRAY] !== true) return;
+
+        var itemName = k.substr(0, k.length-1);  // TODO more robust logic
+
+        delete attr[IS_LINKED_TO_ARRAY];
+
+        layoutAttributes[k] = { items: {} };
+        layoutAttributes[k].items[itemName] = attr;
+        layoutAttributes[k].role = 'object';
+    });
+
+    return layoutAttributes;
+}
+
+},{"../lib":349,"../plotly":366,"../plots/plots":413,"../plots/polar/area_attributes":414,"../plots/polar/axis_attributes":415}],365:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../plotly');
+
+/**
+ * Extends the plot config
+ *
+ * @param {object} configObj partial plot configuration object
+ *      to extend the current plot configuration.
+ *
+ */
+module.exports = function setPlotConfig(configObj) {
+    return Plotly.Lib.extendFlat(Plotly.defaultConfig, configObj);
+};
+
+},{"../plotly":366}],366:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+/*
+ * Pack internal modules unto an object.
+ *
+ * This object is require'ed in as 'Plotly' in numerous src and test files.
+ * Require'ing 'Plotly' bypasses circular dependencies.
+ *
+ * Future development should move away from this pattern.
+ *
+ */
+
+// promise polyfill
+require('es6-promise').polyfill();
+
+// lib functions
+exports.Lib = require('./lib');
+exports.util = require('./lib/svg_text_utils');
+exports.Queue = require('./lib/queue');
+
+// plot css
+require('../build/plotcss');
+
+// configuration
+exports.MathJaxConfig = require('./fonts/mathjax_config');
+exports.defaultConfig = require('./plot_api/plot_config');
+
+// plots
+var Plots = exports.Plots = require('./plots/plots');
+
+exports.Axes = require('./plots/cartesian/axes');
+exports.Fx = require('./plots/cartesian/graph_interact');
+exports.micropolar = require('./plots/polar/micropolar');
+
+// components
+exports.Color = require('./components/color');
+exports.Drawing = require('./components/drawing');
+exports.Colorscale = require('./components/colorscale');
+exports.Colorbar = require('./components/colorbar');
+exports.ErrorBars = require('./components/errorbars');
+exports.Annotations = require('./components/annotations');
+exports.Shapes = require('./components/shapes');
+exports.Legend = require('./components/legend');
+exports.ModeBar = require('./components/modebar');
+
+exports.register = function register(_modules) {
+    if(!_modules) {
+        throw new Error('No argument passed to Plotly.register.');
+    } else if(_modules && !Array.isArray(_modules)) {
+        _modules = [_modules];
+    }
+
+    for(var i = 0; i < _modules.length; i++) {
+        var newModule = _modules[i];
+
+        if(newModule && newModule.moduleType !== 'trace') {
+            throw new Error('Invalid module was attempted to be registered!');
+        } else {
+            Plots.register(newModule, newModule.name, newModule.categories, newModule.meta);
+
+            if(!Plots.subplotsRegistry[newModule.basePlotModule.name]) {
+                Plots.registerSubplot(newModule.basePlotModule);
+            }
+        }
+    }
+};
+
+// Scatter is the only trace included by default
+exports.register(require('./traces/scatter'));
+
+// plot api
+require('./plot_api/plot_api');
+exports.PlotSchema = require('./plot_api/plot_schema');
+
+// imaging routines
+exports.Snapshot = require('./snapshot');
+
+},{"../build/plotcss":1,"./components/annotations":297,"./components/color":299,"./components/colorbar":304,"./components/colorscale":312,"./components/drawing":317,"./components/errorbars":323,"./components/legend":326,"./components/modebar":328,"./components/shapes":331,"./fonts/mathjax_config":340,"./lib":349,"./lib/queue":355,"./lib/svg_text_utils":360,"./plot_api/plot_api":362,"./plot_api/plot_config":363,"./plot_api/plot_schema":364,"./plots/cartesian/axes":369,"./plots/cartesian/graph_interact":374,"./plots/plots":413,"./plots/polar/micropolar":416,"./snapshot":420,"./traces/scatter":511,"es6-promise":73}],367:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+module.exports = {
+    type: {
+        valType: 'enumerated',
+        
+        values: [],     // listed dynamically
+        dflt: 'scatter'
+    },
+    visible: {
+        valType: 'enumerated',
+        values: [true, false, 'legendonly'],
+        
+        dflt: true,
+        
+    },
+    showlegend: {
+        valType: 'boolean',
+        
+        dflt: true,
+        
+    },
+    legendgroup: {
+        valType: 'string',
+        
+        dflt: '',
+        
+    },
+    opacity: {
+        valType: 'number',
+        
+        min: 0,
+        max: 1,
+        dflt: 1,
+        
+    },
+    name: {
+        valType: 'string',
+        
+        
+    },
+    uid: {
+        valType: 'string',
+        
+        dflt: ''
+    },
+    hoverinfo: {
+        valType: 'flaglist',
+        
+        flags: ['x', 'y', 'z', 'text', 'name'],
+        extras: ['all', 'none'],
+        dflt: 'all',
+        
+    },
+    stream: {
+        token: {
+            valType: 'string',
+            noBlank: true,
+            strict: true,
+            
+            
+        },
+        maxpoints: {
+            valType: 'number',
+            min: 0,
+            
+            
+        }
+    }
+};
+
+},{}],368:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+module.exports = {
+    xaxis: {
+        valType: 'axisid',
+        
+        dflt: 'x',
+        
+    },
+    yaxis: {
+        valType: 'axisid',
+        
+        dflt: 'y',
+        
+    }
+};
+
+},{}],369:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var isNumeric = require('fast-isnumeric');
+
+var Plotly = require('../../plotly');
+var Titles = require('../../components/titles');
+
+var axes = module.exports = {};
+
+axes.layoutAttributes = require('./layout_attributes');
+axes.supplyLayoutDefaults = require('./layout_defaults');
+
+axes.setConvert = require('./set_convert');
+
+var axisIds = require('./axis_ids');
+axes.id2name = axisIds.id2name;
+axes.cleanId = axisIds.cleanId;
+axes.list = axisIds.list;
+axes.listIds = axisIds.listIds;
+axes.getFromId = axisIds.getFromId;
+axes.getFromTrace = axisIds.getFromTrace;
+
+
+// find the list of possible axes to reference with an xref or yref attribute
+// and coerce it to that list
+axes.coerceRef = function(containerIn, containerOut, td, axLetter) {
+    var axlist = td._fullLayout._hasGL2D ? [] : axes.listIds(td, axLetter),
+        refAttr = axLetter + 'ref',
+        attrDef = {};
+
+    // data-ref annotations are not supported in gl2d yet
+
+    attrDef[refAttr] = {
+        valType: 'enumerated',
+        values: axlist.concat(['paper']),
+        dflt: axlist[0] || 'paper'
+    };
+
+    // xref, yref
+    return Plotly.Lib.coerce(containerIn, containerOut, attrDef, refAttr);
+};
+
+// empty out types for all axes containing these traces
+// so we auto-set them again
+axes.clearTypes = function(gd, traces) {
+    if(!Array.isArray(traces) || !traces.length) {
+        traces = (gd._fullData).map(function(d, i) { return i; });
+    }
+    traces.forEach(function(tracenum) {
+        var trace = gd.data[tracenum];
+        delete (axes.getFromId(gd, trace.xaxis) || {}).type;
+        delete (axes.getFromId(gd, trace.yaxis) || {}).type;
+    });
+};
+
+// get counteraxis letter for this axis (name or id)
+// this can also be used as the id for default counter axis
+axes.counterLetter = function(id) {
+    var axLetter = id.charAt(0);
+    if(axLetter === 'x') return 'y';
+    if(axLetter === 'y') return 'x';
+};
+
+// incorporate a new minimum difference and first tick into
+// forced
+axes.minDtick = function(ax,newDiff,newFirst,allow) {
+    // doesn't make sense to do forced min dTick on log or category axes,
+    // and the plot itself may decide to cancel (ie non-grouped bars)
+    if(['log','category'].indexOf(ax.type)!==-1 || !allow) {
+        ax._minDtick = 0;
+    }
+    // null means there's nothing there yet
+    else if(ax._minDtick===null) {
+        ax._minDtick = newDiff;
+        ax._forceTick0 = newFirst;
+    }
+    else if(ax._minDtick) {
+        // existing minDtick is an integer multiple of newDiff
+        // (within rounding err)
+        // and forceTick0 can be shifted to newFirst
+        if((ax._minDtick/newDiff+1e-6)%1 < 2e-6 &&
+                (((newFirst-ax._forceTick0)/newDiff%1) +
+                    1.000001) % 1 < 2e-6) {
+            ax._minDtick = newDiff;
+            ax._forceTick0 = newFirst;
+        }
+        // if the converse is true (newDiff is a multiple of minDtick and
+        // newFirst can be shifted to forceTick0) then do nothing - same
+        // forcing stands. Otherwise, cancel forced minimum
+        else if((newDiff/ax._minDtick+1e-6)%1 > 2e-6 ||
+                (((newFirst-ax._forceTick0)/ax._minDtick%1) +
+                    1.000001) % 1 > 2e-6) {
+            ax._minDtick = 0;
+        }
+    }
+};
+
+axes.doAutoRange = function(ax) {
+    if(!ax._length) ax.setScale();
+
+    if(ax.autorange && ax._min && ax._max &&
+            ax._min.length && ax._max.length) {
+        var minmin = ax._min[0].val,
+            maxmax = ax._max[0].val,
+            i;
+
+        for(i = 1; i < ax._min.length; i++) {
+            if(minmin !== maxmax) break;
+            minmin = Math.min(minmin, ax._min[i].val);
+        }
+        for(i = 1; i < ax._max.length; i++) {
+            if(minmin !== maxmax) break;
+            maxmax = Math.max(maxmax, ax._max[i].val);
+        }
+
+        var j,minpt,maxpt,minbest,maxbest,dp,dv,
+            mbest = 0,
+            axReverse = (ax.range && ax.range[1]<ax.range[0]);
+        // one-time setting to easily reverse the axis
+        // when plotting from code
+        if(ax.autorange==='reversed') {
+            axReverse = true;
+            ax.autorange = true;
+        }
+        for(i=0; i<ax._min.length; i++) {
+            minpt = ax._min[i];
+            for(j=0; j<ax._max.length; j++) {
+                maxpt = ax._max[j];
+                dv = maxpt.val-minpt.val;
+                dp = ax._length-minpt.pad-maxpt.pad;
+                if(dv>0 && dp>0 && dv/dp > mbest) {
+                    minbest = minpt;
+                    maxbest = maxpt;
+                    mbest = dv/dp;
+                }
+            }
+        }
+        if(minmin===maxmax) {
+            ax.range = axReverse ?
+                [minmin+1, ax.rangemode!=='normal' ? 0 : minmin-1] :
+                [ax.rangemode!=='normal' ? 0 : minmin-1, minmin+1];
+        }
+        else if(mbest) {
+            if(ax.type==='linear' || ax.type==='-') {
+                if(ax.rangemode==='tozero' && minbest.val>=0) {
+                    minbest = {val: 0, pad: 0};
+                }
+                else if(ax.rangemode==='nonnegative') {
+                    if(minbest.val - mbest*minbest.pad<0) {
+                        minbest = {val: 0, pad: 0};
+                    }
+                    if(maxbest.val<0) {
+                        maxbest = {val: 1, pad: 0};
+                    }
+                }
+
+                // in case it changed again...
+                mbest = (maxbest.val-minbest.val) /
+                    (ax._length-minbest.pad-maxbest.pad);
+            }
+
+            ax.range = [
+                minbest.val - mbest*minbest.pad,
+                maxbest.val + mbest*maxbest.pad
+            ];
+
+            // don't let axis have zero size
+            if(ax.range[0]===ax.range[1]) {
+                ax.range = [ax.range[0]-1, ax.range[0]+1];
+            }
+
+            // maintain reversal
+            if(axReverse) {
+                ax.range.reverse();
+            }
+        }
+
+        // doAutoRange will get called on fullLayout,
+        // but we want to report its results back to layout
+        var axIn = ax._td.layout[ax._name];
+        if(!axIn) ax._td.layout[ax._name] = axIn = {};
+        if(axIn!==ax) {
+            axIn.range = ax.range.slice();
+            axIn.autorange = ax.autorange;
+        }
+    }
+};
+
+// save a copy of the initial axis ranges in fullLayout
+// use them in mode bar and dblclick events
+axes.saveRangeInitial = function(gd, overwrite) {
+    var axList = axes.list(gd, '', true),
+        hasOneAxisChanged = false;
+
+    for(var i = 0; i < axList.length; i++) {
+        var ax = axList[i];
+
+        var isNew = (ax._rangeInitial === undefined);
+        var hasChanged = (
+            isNew || !(
+                ax.range[0] === ax._rangeInitial[0] &&
+                ax.range[1] === ax._rangeInitial[1]
+            )
+        );
+
+        if((isNew && ax.autorange === false) || (overwrite && hasChanged)) {
+            ax._rangeInitial = ax.range.slice();
+            hasOneAxisChanged = true;
+        }
+    }
+
+    return hasOneAxisChanged;
+};
+
+// axes.expand: if autoranging, include new data in the outer limits
+// for this axis
+// data is an array of numbers (ie already run through ax.d2c)
+// available options:
+//      vpad: (number or number array) pad values (data value +-vpad)
+//      ppad: (number or number array) pad pixels (pixel location +-ppad)
+//      ppadplus, ppadminus, vpadplus, vpadminus:
+//          separate padding for each side, overrides symmetric
+//      padded: (boolean) add 5% padding to both ends
+//          (unless one end is overridden by tozero)
+//      tozero: (boolean) make sure to include zero if axis is linear,
+//          and make it a tight bound if possible
+var FP_SAFE = Number.MAX_VALUE/2;
+axes.expand = function(ax, data, options) {
+    if(!ax.autorange || !data) return;
+    if(!ax._min) ax._min = [];
+    if(!ax._max) ax._max = [];
+    if(!options) options = {};
+    if(!ax._m) ax.setScale();
+
+    var len = data.length,
+        extrappad = options.padded ? ax._length*0.05 : 0,
+        tozero = options.tozero && (ax.type==='linear' || ax.type==='-'),
+        i, j, v, di, dmin, dmax,
+        ppadiplus, ppadiminus, includeThis, vmin, vmax;
+
+    function getPad(item) {
+        if(Array.isArray(item)) {
+            return function(i) { return Math.max(Number(item[i]||0),0); };
+        }
+        else {
+            var v = Math.max(Number(item||0),0);
+            return function() { return v; };
+        }
+    }
+    var ppadplus = getPad((ax._m>0 ?
+            options.ppadplus : options.ppadminus) || options.ppad || 0),
+        ppadminus = getPad((ax._m>0 ?
+            options.ppadminus : options.ppadplus) || options.ppad || 0),
+        vpadplus = getPad(options.vpadplus||options.vpad),
+        vpadminus = getPad(options.vpadminus||options.vpad);
+
+    function addItem(i) {
+        di = data[i];
+        if(!isNumeric(di)) return;
+        ppadiplus = ppadplus(i) + extrappad;
+        ppadiminus = ppadminus(i) + extrappad;
+        vmin = di-vpadminus(i);
+        vmax = di+vpadplus(i);
+        // special case for log axes: if vpad makes this object span
+        // more than an order of mag, clip it to one order. This is so
+        // we don't have non-positive errors or absurdly large lower
+        // range due to rounding errors
+        if(ax.type==='log' && vmin<vmax/10) { vmin = vmax/10; }
+
+        dmin = ax.c2l(vmin);
+        dmax = ax.c2l(vmax);
+
+        if(tozero) {
+            dmin = Math.min(0,dmin);
+            dmax = Math.max(0,dmax);
+        }
+
+        // In order to stop overflow errors, don't consider points
+        // too close to the limits of js floating point
+        function goodNumber(v) {
+            return isNumeric(v) && Math.abs(v)<FP_SAFE;
+        }
+
+        if(goodNumber(dmin)) {
+            includeThis = true;
+            // take items v from ax._min and compare them to the
+            // presently active point:
+            // - if the item supercedes the new point, set includethis false
+            // - if the new pt supercedes the item, delete it from ax._min
+            for(j=0; j<ax._min.length && includeThis; j++) {
+                v = ax._min[j];
+                if(v.val<=dmin && v.pad>=ppadiminus) {
+                    includeThis = false;
+                }
+                else if(v.val>=dmin && v.pad<=ppadiminus) {
+                    ax._min.splice(j,1);
+                    j--;
+                }
+            }
+            if(includeThis) {
+                ax._min.push({
+                    val: dmin,
+                    pad: (tozero && dmin===0) ? 0 : ppadiminus
+                });
+            }
+        }
+
+        if(goodNumber(dmax)) {
+            includeThis = true;
+            for(j=0; j<ax._max.length && includeThis; j++) {
+                v = ax._max[j];
+                if(v.val>=dmax && v.pad>=ppadiplus) {
+                    includeThis = false;
+                }
+                else if(v.val<=dmax && v.pad<=ppadiplus) {
+                    ax._max.splice(j,1);
+                    j--;
+                }
+            }
+            if(includeThis) {
+                ax._max.push({
+                    val: dmax,
+                    pad: (tozero && dmax===0) ? 0 : ppadiplus
+                });
+            }
+        }
+    }
+
+    // For efficiency covering monotonic or near-monotonic data,
+    // check a few points at both ends first and then sweep
+    // through the middle
+    for(i=0; i<6; i++) addItem(i);
+    for(i=len-1; i>5; i--) addItem(i);
+
+};
+
+axes.autoBin = function(data,ax,nbins,is2d) {
+    var datamin = Plotly.Lib.aggNums(Math.min, null, data),
+        datamax = Plotly.Lib.aggNums(Math.max, null, data);
+    if(ax.type==='category') {
+        return {
+            start: datamin - 0.5,
+            end: datamax + 0.5,
+            size: 1
+        };
+    }
+
+    var size0;
+    if(nbins) size0 = ((datamax-datamin)/nbins);
+    else {
+        // totally auto: scale off std deviation so the highest bin is
+        // somewhat taller than the total number of bins, but don't let
+        // the size get smaller than the 'nice' rounded down minimum
+        // difference between values
+        var distinctData = Plotly.Lib.distinctVals(data),
+            msexp = Math.pow(10, Math.floor(
+                Math.log(distinctData.minDiff) / Math.LN10)),
+            // TODO: there are some date cases where this will fail...
+            minSize = msexp*Plotly.Lib.roundUp(
+                distinctData.minDiff/msexp, [0.9, 1.9, 4.9, 9.9], true);
+        size0 = Math.max(minSize, 2*Plotly.Lib.stdev(data) /
+            Math.pow(data.length, is2d ? 0.25 : 0.4));
+    }
+
+    // piggyback off autotick code to make "nice" bin sizes
+    var dummyax = {
+        type: ax.type==='log' ? 'linear' : ax.type,
+        range: [datamin, datamax]
+    };
+    axes.autoTicks(dummyax, size0);
+    var binstart = axes.tickIncrement(
+            axes.tickFirst(dummyax), dummyax.dtick, 'reverse'),
+        binend;
+
+    function nearEdge(v) {
+        // is a value within 1% of a bin edge?
+        return (1 + (v-binstart)*100/dummyax.dtick)%100 < 2;
+    }
+
+    // check for too many data points right at the edges of bins
+    // (>50% within 1% of bin edges) or all data points integral
+    // and offset the bins accordingly
+    if(typeof dummyax.dtick === 'number') {
+        var edgecount = 0,
+            midcount = 0,
+            intcount = 0,
+            blankcount = 0;
+        for(var i=0; i<data.length; i++) {
+            if(data[i]%1===0) intcount++;
+            else if(!isNumeric(data[i])) blankcount++;
+
+            if(nearEdge(data[i])) edgecount++;
+            if(nearEdge(data[i] + dummyax.dtick/2)) midcount++;
+        }
+        var datacount = data.length - blankcount;
+
+        if(intcount===datacount && ax.type!=='date') {
+            // all integers: if bin size is <1, it's because
+            // that was specifically requested (large nbins)
+            // so respect that... but center the bins containing
+            // integers on those integers
+            if(dummyax.dtick<1) {
+                binstart = datamin - 0.5 * dummyax.dtick;
+            }
+            // otherwise start half an integer down regardless of
+            // the bin size, just enough to clear up endpoint
+            // ambiguity about which integers are in which bins.
+            else binstart -= 0.5;
+        }
+        else if(midcount < datacount * 0.1) {
+            if(edgecount > datacount * 0.3 ||
+                    nearEdge(datamin) || nearEdge(datamax)) {
+                // lots of points at the edge, not many in the middle
+                // shift half a bin
+                var binshift = dummyax.dtick / 2;
+                binstart += (binstart+binshift<datamin) ? binshift : -binshift;
+            }
+        }
+
+        var bincount = 1 + Math.floor((datamax - binstart) / dummyax.dtick);
+        binend = binstart + bincount * dummyax.dtick;
+    }
+    else {
+        // calculate the endpoint for nonlinear ticks - you have to
+        // just increment until you're done
+        binend = binstart;
+        while(binend<=datamax) {
+            binend = axes.tickIncrement(binend, dummyax.dtick);
+        }
+    }
+
+    return {
+        start: binstart,
+        end: binend,
+        size: dummyax.dtick
+    };
+};
+
+
+// ----------------------------------------------------
+// Ticks and grids
+// ----------------------------------------------------
+
+// calculate the ticks: text, values, positioning
+// if ticks are set to automatic, determine the right values (tick0,dtick)
+// in any case, set tickround to # of digits to round tick labels to,
+// or codes to this effect for log and date scales
+axes.calcTicks = function calcTicks(ax) {
+    if(ax.tickmode === 'array') return arrayTicks(ax);
+
+    // calculate max number of (auto) ticks to display based on plot size
+    if(ax.tickmode === 'auto' || !ax.dtick) {
+        var nt = ax.nticks,
+            minPx;
+        if(!nt) {
+            if(ax.type === 'category') {
+                minPx = ax.tickfont ? (ax.tickfont.size || 12) * 1.2 : 15;
+                nt = ax._length / minPx;
+            }
+            else {
+                minPx = ax._id.charAt(0) === 'y' ? 40 : 80;
+                nt = Plotly.Lib.constrain(ax._length / minPx, 4, 9) + 1;
+            }
+        }
+        axes.autoTicks(ax,Math.abs(ax.range[1]-ax.range[0])/nt);
+        // check for a forced minimum dtick
+        if(ax._minDtick>0 && ax.dtick<ax._minDtick*2) {
+            ax.dtick = ax._minDtick;
+            ax.tick0 = ax._forceTick0;
+        }
+    }
+
+    // check for missing tick0
+    if(!ax.tick0) {
+        ax.tick0 = (ax.type==='date') ?
+            new Date(2000,0,1).getTime() : 0;
+    }
+
+    // now figure out rounding of tick values
+    autoTickRound(ax);
+
+    // find the first tick
+    ax._tmin=axes.tickFirst(ax);
+
+    // check for reversed axis
+    var axrev = (ax.range[1]<ax.range[0]);
+
+    // return the full set of tick vals
+    var vals = [],
+        // add a tiny bit so we get ticks which may have rounded out
+        endtick = ax.range[1] * 1.0001 - ax.range[0]*0.0001;
+    if(ax.type==='category') {
+        endtick = (axrev) ? Math.max(-0.5,endtick) :
+            Math.min(ax._categories.length-0.5,endtick);
+    }
+    for(var x = ax._tmin;
+            (axrev)?(x>=endtick):(x<=endtick);
+            x = axes.tickIncrement(x,ax.dtick,axrev)) {
+        vals.push(x);
+
+        // prevent infinite loops
+        if(vals.length>1000) break;
+    }
+
+    // save the last tick as well as first, so we can
+    // show the exponent only on the last one
+    ax._tmax = vals[vals.length - 1];
+
+    var ticksOut = new Array(vals.length);
+    for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]);
+
+    return ticksOut;
+};
+
+function arrayTicks(ax) {
+    var vals = ax.tickvals,
+        text = ax.ticktext,
+        ticksOut = new Array(vals.length),
+        r0expanded = ax.range[0] * 1.0001 - ax.range[1] * 0.0001,
+        r1expanded = ax.range[1] * 1.0001 - ax.range[0] * 0.0001,
+        tickMin = Math.min(r0expanded, r1expanded),
+        tickMax = Math.max(r0expanded, r1expanded),
+        vali,
+        i,
+        j = 0;
+
+
+    // without a text array, just format the given values as any other ticks
+    // except with more precision to the numbers
+    if(!Array.isArray(text)) text = [];
+
+    for(i = 0; i < vals.length; i++) {
+        vali = ax.d2l(vals[i]);
+        if(vali > tickMin && vali < tickMax) {
+            if(text[i] === undefined) ticksOut[j] = axes.tickText(ax, vali);
+            else ticksOut[j] = tickTextObj(ax, vali, String(text[i]));
+            j++;
+        }
+    }
+
+    if(j < vals.length) ticksOut.splice(j, vals.length - j);
+
+    return ticksOut;
+}
+
+var roundBase10 = [2, 5, 10],
+    roundBase24 = [1, 2, 3, 6, 12],
+    roundBase60 = [1, 2, 5, 10, 15, 30],
+    // 2&3 day ticks are weird, but need something btwn 1&7
+    roundDays = [1, 2, 3, 7, 14],
+    // approx. tick positions for log axes, showing all (1) and just 1, 2, 5 (2)
+    // these don't have to be exact, just close enough to round to the right value
+    roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1],
+    roundLog2 = [-0.301, 0, 0.301, 0.699, 1];
+
+function roundDTick(roughDTick, base, roundingSet) {
+    return base * Plotly.Lib.roundUp(roughDTick / base, roundingSet);
+}
+
+// autoTicks: calculate best guess at pleasant ticks for this axis
+// inputs:
+//      ax - an axis object
+//      roughDTick - rough tick spacing (to be turned into a nice round number)
+// outputs (into ax):
+//   tick0: starting point for ticks (not necessarily on the graph)
+//      usually 0 for numeric (=10^0=1 for log) or jan 1, 2000 for dates
+//   dtick: the actual, nice round tick spacing, somewhat larger than roughDTick
+//      if the ticks are spaced linearly (linear scale, categories,
+//          log with only full powers, date ticks < month),
+//          this will just be a number
+//      months: M#
+//      years: M# where # is 12*number of years
+//      log with linear ticks: L# where # is the linear tick spacing
+//      log showing powers plus some intermediates:
+//          D1 shows all digits, D2 shows 2 and 5
+axes.autoTicks = function(ax, roughDTick) {
+    var base;
+
+    if(ax.type === 'date') {
+        ax.tick0 = new Date(2000, 0, 1).getTime();
+
+        if(roughDTick > 15778800000) {
+            // years if roughDTick > 6mo
+            roughDTick /= 31557600000;
+            base = Math.pow(10, Math.floor(Math.log(roughDTick) / Math.LN10));
+            ax.dtick = 'M' + (12 * roundDTick(roughDTick, base, roundBase10));
+        }
+        else if(roughDTick > 1209600000) {
+            // months if roughDTick > 2wk
+            roughDTick /= 2629800000;
+            ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24);
+        }
+        else if(roughDTick > 43200000) {
+            // days if roughDTick > 12h
+            ax.dtick = roundDTick(roughDTick, 86400000, roundDays);
+            // get week ticks on sunday
+            ax.tick0 = new Date(2000, 0, 2).getTime();
+        }
+        else if(roughDTick > 1800000) {
+            // hours if roughDTick > 30m
+            ax.dtick = roundDTick(roughDTick, 3600000, roundBase24);
+        }
+        else if(roughDTick > 30000) {
+            // minutes if roughDTick > 30sec
+            ax.dtick = roundDTick(roughDTick, 60000, roundBase60);
+        }
+        else if(roughDTick > 500) {
+            // seconds if roughDTick > 0.5sec
+            ax.dtick = roundDTick(roughDTick, 1000, roundBase60);
+        }
+        else {
+            //milliseconds
+            base = Math.pow(10, Math.floor(Math.log(roughDTick) / Math.LN10));
+            ax.dtick = roundDTick(roughDTick, base, roundBase10);
+        }
+    }
+    else if(ax.type === 'log') {
+        ax.tick0 = 0;
+
+        //only show powers of 10
+        if(roughDTick > 0.7) ax.dtick = Math.ceil(roughDTick);
+        else if(Math.abs(ax.range[1] - ax.range[0]) < 1) {
+            // span is less than one power of 10
+            var nt = 1.5 * Math.abs((ax.range[1] - ax.range[0]) / roughDTick);
+
+            // ticks on a linear scale, labeled fully
+            roughDTick = Math.abs(Math.pow(10, ax.range[1]) -
+                Math.pow(10, ax.range[0])) / nt;
+            base = Math.pow(10, Math.floor(Math.log(roughDTick) / Math.LN10));
+            ax.dtick = 'L' + roundDTick(roughDTick, base, roundBase10);
+        }
+        else {
+            // include intermediates between powers of 10,
+            // labeled with small digits
+            // ax.dtick = "D2" (show 2 and 5) or "D1" (show all digits)
+            ax.dtick = (roughDTick > 0.3) ? 'D2' : 'D1';
+        }
+    }
+    else if(ax.type==='category') {
+        ax.tick0 = 0;
+        ax.dtick = Math.ceil(Math.max(roughDTick, 1));
+    }
+    else {
+        // auto ticks always start at 0
+        ax.tick0 = 0;
+        base = Math.pow(10, Math.floor(Math.log(roughDTick) / Math.LN10));
+        ax.dtick = roundDTick(roughDTick, base, roundBase10);
+    }
+
+    // prevent infinite loops
+    if(ax.dtick === 0) ax.dtick = 1;
+
+    // TODO: this is from log axis histograms with autorange off
+    if(!isNumeric(ax.dtick) && typeof ax.dtick !=='string') {
+        var olddtick = ax.dtick;
+        ax.dtick = 1;
+        throw 'ax.dtick error: ' + String(olddtick);
+    }
+};
+
+// after dtick is already known, find tickround = precision
+// to display in tick labels
+//   for numeric ticks, integer # digits after . to round to
+//   for date ticks, the last date part to show (y,m,d,H,M,S)
+//      or an integer # digits past seconds
+function autoTickRound(ax) {
+    var dtick = ax.dtick,
+        maxend;
+
+    ax._tickexponent = 0;
+    if(!isNumeric(dtick) && typeof dtick !== 'string') dtick = 1;
+
+    if(ax.type === 'category') ax._tickround = null;
+    else if(isNumeric(dtick) || dtick.charAt(0) === 'L') {
+        if(ax.type === 'date') {
+            if(dtick >= 86400000) ax._tickround = 'd';
+            else if(dtick >= 3600000) ax._tickround = 'H';
+            else if(dtick >= 60000) ax._tickround = 'M';
+            else if(dtick >= 1000) ax._tickround = 'S';
+            else ax._tickround = 3 - Math.round(Math.log(dtick / 2) / Math.LN10);
+        }
+        else {
+            if(!isNumeric(dtick)) dtick = Number(dtick.substr(1));
+            // 2 digits past largest digit of dtick
+            ax._tickround = 2 - Math.floor(Math.log(dtick) / Math.LN10 + 0.01);
+
+            if(ax.type === 'log') {
+                maxend = Math.pow(10, Math.max(ax.range[0], ax.range[1]));
+            }
+            else maxend = Math.max(Math.abs(ax.range[0]), Math.abs(ax.range[1]));
+
+            var rangeexp = Math.floor(Math.log(maxend) / Math.LN10 + 0.01);
+            if(Math.abs(rangeexp) > 3) {
+                if(ax.exponentformat === 'SI' || ax.exponentformat === 'B') {
+                    ax._tickexponent = 3 * Math.round((rangeexp - 1) / 3);
+                }
+                else ax._tickexponent = rangeexp;
+            }
+        }
+    }
+    else if(dtick.charAt(0) === 'M') ax._tickround = (dtick.length===2) ? 'm' : 'y';
+    else ax._tickround = null;
+}
+
+// months and years don't have constant millisecond values
+// (but a year is always 12 months so we only need months)
+// log-scale ticks are also not consistently spaced, except
+// for pure powers of 10
+// numeric ticks always have constant differences, other datetime ticks
+// can all be calculated as constant number of milliseconds
+axes.tickIncrement = function(x, dtick, axrev) {
+    var axSign = axrev ? -1 : 1;
+
+    // includes all dates smaller than month, and pure 10^n in log
+    if(isNumeric(dtick)) return x + axSign * dtick;
+
+    var tType = dtick.charAt(0),
+        dtSigned = axSign * Number(dtick.substr(1));
+
+    // Dates: months (or years)
+    if(tType === 'M') {
+        var y = new Date(x);
+        // is this browser consistent? setMonth edits a date but
+        // returns that date's milliseconds
+        return y.setMonth(y.getMonth() + dtSigned);
+    }
+
+    // Log scales: Linear, Digits
+    else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10;
+
+    // log10 of 2,5,10, or all digits (logs just have to be
+    // close enough to round)
+    else if(tType === 'D') {
+        var tickset = (dtick === 'D2') ? roundLog2 : roundLog1,
+            x2 = x + axSign * 0.01,
+            frac = Plotly.Lib.roundUp(mod(x2, 1), tickset, axrev);
+
+        return Math.floor(x2) +
+            Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
+    }
+    else throw 'unrecognized dtick ' + String(dtick);
+};
+
+// calculate the first tick on an axis
+axes.tickFirst = function(ax) {
+    var axrev = ax.range[1] < ax.range[0],
+        sRound = axrev ? Math.floor : Math.ceil,
+        // add a tiny extra bit to make sure we get ticks
+        // that may have been rounded out
+        r0 = ax.range[0] * 1.0001 - ax.range[1] * 0.0001,
+        dtick = ax.dtick,
+        tick0 = ax.tick0;
+    if(isNumeric(dtick)) {
+        var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0;
+
+        // make sure no ticks outside the category list
+        if(ax.type === 'category') {
+            tmin = Plotly.Lib.constrain(tmin, 0, ax._categories.length - 1);
+        }
+        return tmin;
+    }
+
+    var tType = dtick.charAt(0),
+        dtNum = Number(dtick.substr(1)),
+        t0,
+        mdif,
+        t1;
+
+    // Dates: months (or years)
+    if(tType === 'M') {
+        t0 = new Date(tick0);
+        r0 = new Date(r0);
+        mdif = (r0.getFullYear() - t0.getFullYear()) * 12 +
+            r0.getMonth() - t0.getMonth();
+        t1 = t0.setMonth(t0.getMonth() +
+            (Math.round(mdif / dtNum) + (axrev ? 1 : -1)) * dtNum);
+
+        while(axrev ? t1 > r0 : t1 < r0) {
+            t1 = axes.tickIncrement(t1, dtick, axrev);
+        }
+        return t1;
+    }
+
+    // Log scales: Linear, Digits
+    else if(tType === 'L') {
+        return Math.log(sRound(
+            (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10;
+    }
+    else if(tType === 'D') {
+        var tickset = (dtick === 'D2') ? roundLog2 : roundLog1,
+            frac = Plotly.Lib.roundUp(mod(r0, 1), tickset, axrev);
+
+        return Math.floor(r0) +
+            Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
+    }
+    else throw 'unrecognized dtick ' + String(dtick);
+};
+
+var yearFormat = d3.time.format('%Y'),
+    monthFormat = d3.time.format('%b %Y'),
+    dayFormat = d3.time.format('%b %-d'),
+    hourFormat = d3.time.format('%b %-d %Hh'),
+    minuteFormat = d3.time.format('%H:%M'),
+    secondFormat = d3.time.format(':%S');
+
+// add one item to d3's vocabulary:
+// %{n}f where n is the max number of digits
+// of fractional seconds
+var fracMatch = /%(\d?)f/g;
+function modDateFormat(fmt,x) {
+    var fm = fmt.match(fracMatch),
+        d = new Date(x);
+    if(fm) {
+        var digits = Math.min(+fm[1]||6,6),
+            fracSecs = String((x/1000 % 1) + 2.0000005)
+                .substr(2,digits).replace(/0+$/,'')||'0';
+        return d3.time.format(fmt.replace(fracMatch,fracSecs))(d);
+    }
+    else {
+        return d3.time.format(fmt)(d);
+    }
+}
+
+// draw the text for one tick.
+// px,py are the location on td.paper
+// prefix is there so the x axis ticks can be dropped a line
+// ax is the axis layout, x is the tick value
+// hover is a (truthy) flag for whether to show numbers with a bit
+// more precision for hovertext
+axes.tickText = function(ax, x, hover) {
+    var out = tickTextObj(ax, x),
+        hideexp,
+        arrayMode = ax.tickmode === 'array',
+        extraPrecision = hover || arrayMode,
+        i;
+
+    if(arrayMode && Array.isArray(ax.ticktext)) {
+        var minDiff = Math.abs(ax.range[1] - ax.range[0]) / 10000;
+        for(i = 0; i < ax.ticktext.length; i++) {
+            if(Math.abs(x - ax.d2l(ax.tickvals[i])) < minDiff) break;
+        }
+        if(i < ax.ticktext.length) {
+            out.text = String(ax.ticktext[i]);
+            return out;
+        }
+    }
+
+    function isHidden(showAttr) {
+        var first_or_last;
+
+        if(showAttr === undefined) return true;
+        if(hover) return showAttr==='none';
+
+        first_or_last = {
+            first: ax._tmin,
+            last: ax._tmax
+        }[showAttr];
+
+        return showAttr!=='all' && x!==first_or_last;
+    }
+
+    hideexp = ax.exponentformat!=='none' && isHidden(ax.showexponent) ? 'hide' : '';
+
+    if(ax.type==='date') formatDate(ax, out, hover, extraPrecision);
+    else if(ax.type==='log') formatLog(ax, out, hover, extraPrecision, hideexp);
+    else if(ax.type==='category') formatCategory(ax, out);
+    else formatLinear(ax, out, hover, extraPrecision, hideexp);
+
+    // add prefix and suffix
+    if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text;
+    if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix;
+
+    return out;
+};
+
+function tickTextObj(ax, x, text) {
+    var tf = ax.tickfont || ax._td._fullLayout.font;
+
+    return {
+        x: x,
+        dx: 0,
+        dy: 0,
+        text: text || '',
+        fontSize: tf.size,
+        font: tf.family,
+        fontColor: tf.color
+    };
+}
+
+function formatDate(ax, out, hover, extraPrecision) {
+    var x = out.x,
+        tr = ax._tickround,
+        d = new Date(x),
+        // suffix completes the full date info, to be included
+        // with only the first tick
+        suffix = '',
+        tt;
+    if(hover && ax.hoverformat) {
+        tt = modDateFormat(ax.hoverformat,x);
+    }
+    else if(ax.tickformat) {
+        tt = modDateFormat(ax.tickformat,x);
+        // TODO: potentially hunt for ways to automatically add more
+        // precision to the hover text?
+    }
+    else {
+        if(extraPrecision) {
+            if(isNumeric(tr)) tr+=2;
+            else tr = {y: 'm', m: 'd', d: 'H', H: 'M', M: 'S', S: 2}[tr];
+        }
+        if(tr==='y') tt = yearFormat(d);
+        else if(tr==='m') tt = monthFormat(d);
+        else {
+            if(x===ax._tmin && !hover) {
+                suffix = '<br>'+yearFormat(d);
+            }
+
+            if(tr==='d') tt = dayFormat(d);
+            else if(tr==='H') tt = hourFormat(d);
+            else {
+                if(x===ax._tmin && !hover) {
+                    suffix = '<br>'+dayFormat(d)+', '+yearFormat(d);
+                }
+
+                tt = minuteFormat(d);
+                if(tr!=='M') {
+                    tt += secondFormat(d);
+                    if(tr!=='S') {
+                        tt += numFormat(mod(x/1000,1),ax,'none',hover)
+                            .substr(1);
+                    }
+                }
+            }
+        }
+    }
+    out.text = tt + suffix;
+}
+
+function formatLog(ax, out, hover, extraPrecision, hideexp) {
+    var dtick = ax.dtick,
+        x = out.x;
+    if(extraPrecision && ((typeof dtick !== 'string') || dtick.charAt(0)!=='L')) dtick = 'L3';
+
+    if(ax.tickformat || (typeof dtick === 'string' && dtick.charAt(0) === 'L')) {
+        out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision);
+    }
+    else if(isNumeric(dtick)||((dtick.charAt(0)==='D')&&(mod(x+0.01,1)<0.1))) {
+        if(['e','E','power'].indexOf(ax.exponentformat)!==-1) {
+            var p = Math.round(x);
+            if(p === 0) out.text = 1;
+            else if(p === 1) out.text = '10';
+            else if(p > 1) out.text = '10<sup>' + p + '</sup>';
+            else out.text = '10<sup>\u2212' + -p + '</sup>';
+
+            out.fontSize *= 1.25;
+        }
+        else {
+            out.text = numFormat(Math.pow(10,x), ax,'','fakehover');
+            if(dtick==='D1' && ax._id.charAt(0)==='y') {
+                out.dy -= out.fontSize/6;
+            }
+        }
+    }
+    else if(dtick.charAt(0) === 'D') {
+        out.text = String(Math.round(Math.pow(10, mod(x, 1))));
+        out.fontSize *= 0.75;
+    }
+    else throw 'unrecognized dtick ' + String(dtick);
+
+    // if 9's are printed on log scale, move the 10's away a bit
+    if(ax.dtick==='D1') {
+        var firstChar = String(out.text).charAt(0);
+        if(firstChar === '0' || firstChar === '1') {
+            if(ax._id.charAt(0) === 'y') {
+                out.dx -= out.fontSize / 4;
+            }
+            else {
+                out.dy += out.fontSize / 2;
+                out.dx += (ax.range[1] > ax.range[0] ? 1 : -1) *
+                    out.fontSize * (x < 0 ? 0.5 : 0.25);
+            }
+        }
+    }
+}
+
+function formatCategory(ax, out) {
+    var tt = ax._categories[Math.round(out.x)];
+    if(tt === undefined) tt = '';
+    out.text = String(tt);
+}
+
+function formatLinear(ax, out, hover, extraPrecision, hideexp) {
+    // don't add an exponent to zero if we're showing all exponents
+    // so the only reason you'd show an exponent on zero is if it's the
+    // ONLY tick to get an exponent (first or last)
+    if(ax.showexponent==='all' && Math.abs(out.x/ax.dtick)<1e-6) {
+        hideexp = 'hide';
+    }
+    out.text = numFormat(out.x, ax, hideexp, extraPrecision);
+}
+
+// format a number (tick value) according to the axis settings
+// new, more reliable procedure than d3.round or similar:
+// add half the rounding increment, then stringify and truncate
+// also automatically switch to sci. notation
+var SIPREFIXES = ['f', 'p', 'n', '&mu;', 'm', '', 'k', 'M', 'G', 'T'];
+function numFormat(v, ax, fmtoverride, hover) {
+        // negative?
+    var isNeg = v < 0,
+        // max number of digits past decimal point to show
+        tickRound = ax._tickround,
+        exponentFormat = fmtoverride || ax.exponentformat || 'B',
+        exponent = ax._tickexponent,
+        tickformat = ax.tickformat;
+
+    // special case for hover: set exponent just for this value, and
+    // add a couple more digits of precision over tick labels
+    if(hover) {
+        // make a dummy axis obj to get the auto rounding and exponent
+        var ah = {
+            exponentformat: ax.exponentformat,
+            dtick: ax.showexponent==='none' ? ax.dtick :
+                (isNumeric(v) ? Math.abs(v) || 1 : 1),
+            // if not showing any exponents, don't change the exponent
+            // from what we calculate
+            range: ax.showexponent === 'none' ? ax.range : [0, v || 1]
+        };
+        autoTickRound(ah);
+        tickRound = (Number(ah._tickround) || 0) + 4;
+        exponent = ah._tickexponent;
+        if(ax.hoverformat) tickformat = ax.hoverformat;
+    }
+
+    if(tickformat) return d3.format(tickformat)(v).replace(/-/g,'\u2212');
+
+    // 'epsilon' - rounding increment
+    var e = Math.pow(10, -tickRound) / 2;
+
+    // exponentFormat codes:
+    // 'e' (1.2e+6, default)
+    // 'E' (1.2E+6)
+    // 'SI' (1.2M)
+    // 'B' (same as SI except 10^9=B not G)
+    // 'none' (1200000)
+    // 'power' (1.2x10^6)
+    // 'hide' (1.2, use 3rd argument=='hide' to eg
+    //      only show exponent on last tick)
+    if(exponentFormat === 'none') exponent = 0;
+
+    // take the sign out, put it back manually at the end
+    // - makes cases easier
+    v = Math.abs(v);
+    if(v < e) {
+        // 0 is just 0, but may get exponent if it's the last tick
+        v = '0';
+        isNeg = false;
+    }
+    else {
+        v += e;
+        // take out a common exponent, if any
+        if(exponent) {
+            v *= Math.pow(10, -exponent);
+            tickRound += exponent;
+        }
+        // round the mantissa
+        if(tickRound === 0) v = String(Math.floor(v));
+        else if(tickRound < 0) {
+            v = String(Math.round(v));
+            v = v.substr(0, v.length + tickRound);
+            for(var i = tickRound; i < 0; i++) v += '0';
+        }
+        else {
+            v = String(v);
+            var dp = v.indexOf('.') + 1;
+            if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, '');
+        }
+        // insert appropriate decimal point and thousands separator
+        v = numSeparate(v, ax._td._fullLayout.separators);
+    }
+
+    // add exponent
+    if(exponent && exponentFormat !== 'hide') {
+        var signedExponent;
+        if(exponent < 0) signedExponent = '\u2212' + -exponent;
+        else if(exponentFormat !== 'power') signedExponent = '+' + exponent;
+        else signedExponent = String(exponent);
+
+        if(exponentFormat === 'e' ||
+                ((exponentFormat === 'SI' || exponentFormat === 'B') &&
+                 (exponent > 12 || exponent < -15))) {
+            v += 'e' + signedExponent;
+        }
+        else if(exponentFormat === 'E') {
+            v += 'E' + signedExponent;
+        }
+        else if(exponentFormat === 'power') {
+            v += '&times;10<sup>' + signedExponent + '</sup>';
+        }
+        else if(exponentFormat === 'B' && exponent === 9) {
+            v += 'B';
+        }
+        else if(exponentFormat === 'SI' || exponentFormat === 'B') {
+            v += SIPREFIXES[exponent / 3 + 5];
+        }
+    }
+
+    // put sign back in and return
+    // replace standard minus character (which is technically a hyphen)
+    // with a true minus sign
+    if(isNeg) return '\u2212' + v;
+    return v;
+}
+
+// add arbitrary decimal point and thousands separator
+var findThousands = /(\d+)(\d{3})/;
+function numSeparate(nStr, separators) {
+    // separators - first char is decimal point,
+    // next char is thousands separator if there is one
+
+    var dp = separators.charAt(0),
+        thou = separators.charAt(1),
+        x = nStr.split('.'),
+        x1 = x[0],
+        x2 = x.length > 1 ? dp + x[1] : '';
+    // even if there is a thousands separator, don't use it on
+    // 4-digit integers (like years)
+    if(thou && (x.length > 1 || x1.length>4)) {
+        while(findThousands.test(x1)) {
+            x1 = x1.replace(findThousands, '$1' + thou + '$2');
+        }
+    }
+    return x1 + x2;
+}
+
+
+axes.subplotMatch = /^x([0-9]*)y([0-9]*)$/;
+
+// getSubplots - extract all combinations of axes we need to make plots for
+// as an array of items like 'xy', 'x2y', 'x2y2'...
+// sorted by x (x,x2,x3...) then y
+// optionally restrict to only subplots containing axis object ax
+// looks both for combinations of x and y found in the data
+// and at axes and their anchors
+axes.getSubplots = function(gd, ax) {
+    var subplots = [];
+    var i, j, sp;
+
+    // look for subplots in the data
+    var data = gd.data || [];
+
+    for(i = 0; i < data.length; i++) {
+        var trace = data[i];
+
+        if(trace.visible === false || trace.visible === 'legendonly' ||
+            !(Plotly.Plots.traceIs(trace, 'cartesian') ||
+                Plotly.Plots.traceIs(trace, 'gl2d'))
+        ) continue;
+
+        var xId = trace.xaxis || 'x',
+            yId = trace.yaxis || 'y';
+        sp = xId + yId;
+
+        if(subplots.indexOf(sp) === -1) subplots.push(sp);
+    }
+
+    // look for subplots in the axes/anchors, so that we at least draw all axes
+    var axesList = axes.list(gd, '', true);
+
+    function hasAx2(sp, ax2) {
+        return sp.indexOf(ax2._id) !== -1;
+    }
+
+    for(i = 0; i < axesList.length; i++) {
+        var ax2 = axesList[i],
+            ax2Letter = ax2._id.charAt(0),
+            ax3Id = (ax2.anchor === 'free') ?
+                ((ax2Letter === 'x') ? 'y' : 'x') :
+                ax2.anchor,
+            ax3 = axes.getFromId(gd, ax3Id);
+
+        // look if ax2 is already represented in the data
+        var foundAx2 = false;
+        for(j = 0; j < subplots.length; j++) {
+            if(hasAx2(subplots[j], ax2)) {
+                foundAx2 = true;
+                break;
+            }
+        }
+
+        // ignore free axes that already represented in the data
+        if(ax2.anchor === 'free' && foundAx2) continue;
+
+        // ignore anchor-less axes
+        if(!ax3) continue;
+
+        sp = (ax2Letter === 'x') ?
+            ax2._id + ax3._id :
+            ax3._id + ax2._id;
+
+        if(subplots.indexOf(sp) === -1) subplots.push(sp);
+    }
+
+    // filter invalid subplots
+    var spMatch = axes.subplotMatch,
+        allSubplots = [];
+
+    for(i = 0; i < subplots.length; i++) {
+        sp = subplots[i];
+        if(spMatch.test(sp)) allSubplots.push(sp);
+    }
+
+    // sort the subplot ids
+    allSubplots.sort(function(a, b) {
+        var aMatch = a.match(spMatch),
+            bMatch = b.match(spMatch);
+
+        if(aMatch[1] === bMatch[1]) {
+            return +(aMatch[2]||1) - (bMatch[2]||1);
+        }
+
+        return +(aMatch[1]||0) - (bMatch[1]||0);
+    });
+
+    if(ax) return axes.findSubplotsWithAxis(allSubplots, ax);
+    return allSubplots;
+};
+
+// find all subplots with axis 'ax'
+axes.findSubplotsWithAxis = function(subplots, ax) {
+    var axMatch = new RegExp(
+        (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$')
+    );
+    var subplotsWithAxis = [];
+
+    for(var i = 0; i < subplots.length; i++) {
+        var sp = subplots[i];
+        if(axMatch.test(sp)) subplotsWithAxis.push(sp);
+    }
+
+    return subplotsWithAxis;
+};
+
+// makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings
+axes.makeClipPaths = function(td) {
+    var layout = td._fullLayout,
+        defs = layout._defs,
+        fullWidth = {_offset: 0, _length: layout.width, _id: ''},
+        fullHeight = {_offset: 0, _length: layout.height, _id: ''},
+        xaList = axes.list(td, 'x', true),
+        yaList = axes.list(td, 'y', true),
+        clipList = [],
+        i,
+        j;
+
+    for(i = 0; i < xaList.length; i++) {
+        clipList.push({x: xaList[i], y: fullHeight});
+        for(j = 0; j < yaList.length; j++) {
+            if(i===0) clipList.push({x: fullWidth, y: yaList[j]});
+            clipList.push({x: xaList[i], y: yaList[j]});
+        }
+    }
+
+    var defGroup = defs.selectAll('g.clips')
+        .data([0]);
+    defGroup.enter().append('g')
+        .classed('clips', true);
+
+    // selectors don't work right with camelCase tags,
+    // have to use class instead
+    // https://groups.google.com/forum/#!topic/d3-js/6EpAzQ2gU9I
+    var axClips = defGroup.selectAll('.axesclip')
+        .data(clipList, function(d) { return d.x._id + d.y._id; });
+    axClips.enter().append('clipPath')
+        .classed('axesclip', true)
+        .attr('id', function(d) { return 'clip' + layout._uid + d.x._id + d.y._id; })
+      .append('rect');
+    axClips.exit().remove();
+    axClips.each(function(d) {
+        d3.select(this).select('rect').attr({
+            x: d.x._offset || 0,
+            y: d.y._offset || 0,
+            width: d.x._length || 1,
+            height: d.y._length || 1
+        });
+    });
+};
+
+
+// doTicks: draw ticks, grids, and tick labels
+// axid: 'x', 'y', 'x2' etc,
+//     blank to do all,
+//     'redraw' to force full redraw, and reset ax._r
+//          (stored range for use by zoom/pan)
+//     or can pass in an axis object directly
+axes.doTicks = function(td, axid, skipTitle) {
+    var fullLayout = td._fullLayout,
+        ax,
+        independent = false;
+
+    // allow passing an independent axis object instead of id
+    if(typeof axid === 'object') {
+        ax = axid;
+        axid = ax._id;
+        independent = true;
+    }
+    else {
+        ax = axes.getFromId(td,axid);
+
+        if(axid==='redraw') {
+            fullLayout._paper.selectAll('g.subplot').each(function(subplot) {
+                var plotinfo = fullLayout._plots[subplot],
+                    xa = plotinfo.x(),
+                    ya = plotinfo.y();
+                plotinfo.plot.attr('viewBox',
+                    '0 0 '+xa._length+' '+ya._length);
+                plotinfo.xaxislayer
+                    .selectAll('.'+xa._id+'tick').remove();
+                plotinfo.yaxislayer
+                    .selectAll('.'+ya._id+'tick').remove();
+                plotinfo.gridlayer
+                    .selectAll('path').remove();
+                plotinfo.zerolinelayer
+                    .selectAll('path').remove();
+            });
+        }
+
+        if(!axid || axid==='redraw') {
+            return Plotly.Lib.syncOrAsync(axes.list(td, '', true).map(function(ax) {
+                return function() {
+                    if(!ax._id) return;
+                    var axDone = axes.doTicks(td,ax._id);
+                    if(axid==='redraw') ax._r = ax.range.slice();
+                    return axDone;
+                };
+            }));
+        }
+    }
+
+    // make sure we only have allowed options for exponents
+    // (others can make confusing errors)
+    if(!ax.tickformat) {
+        if(['none','e','E','power','SI','B'].indexOf(ax.exponentformat)===-1) {
+            ax.exponentformat = 'e';
+        }
+        if(['all','first','last','none'].indexOf(ax.showexponent)===-1) {
+            ax.showexponent = 'all';
+        }
+    }
+
+    // in case a val turns into string somehow
+    ax.range = [+ax.range[0], +ax.range[1]];
+
+    // set scaling to pixels
+    ax.setScale();
+
+    var axletter = axid.charAt(0),
+        counterLetter = axes.counterLetter(axid),
+        vals = axes.calcTicks(ax),
+        datafn = function(d) { return d.text + d.x + ax.mirror; },
+        tcls = axid+'tick',
+        gcls = axid+'grid',
+        zcls = axid+'zl',
+        pad = (ax.linewidth||1) / 2,
+        labelStandoff =
+            (ax.ticks==='outside' ? ax.ticklen : 1) + (ax.linewidth||0),
+        gridWidth = Plotly.Drawing.crispRound(td, ax.gridwidth, 1),
+        zeroLineWidth = Plotly.Drawing.crispRound(td, ax.zerolinewidth, gridWidth),
+        tickWidth = Plotly.Drawing.crispRound(td, ax.tickwidth, 1),
+        sides, transfn, tickprefix, tickmid,
+        i;
+
+    // positioning arguments for x vs y axes
+    if(axletter==='x') {
+        sides = ['bottom', 'top'];
+        transfn = function(d) {
+            return 'translate('+ax.l2p(d.x)+',0)';
+        };
+        // dumb templating with string concat
+        // would be better to use an actual template
+        tickprefix = 'M0,';
+        tickmid = 'v';
+    }
+    else if(axletter==='y') {
+        sides = ['left', 'right'];
+        transfn = function(d) {
+            return 'translate(0,'+ax.l2p(d.x)+')';
+        };
+        tickprefix = 'M';
+        tickmid = ',0h';
+    }
+    else {
+        console.log('unrecognized doTicks axis', axid);
+        return;
+    }
+    var axside = ax.side||sides[0],
+    // which direction do the side[0], side[1], and free ticks go?
+    // then we flip if outside XOR y axis
+        ticksign = [-1, 1, axside===sides[1] ? 1 : -1];
+    if((ax.ticks!=='inside') === (axletter==='x')) {
+        ticksign = ticksign.map(function(v) { return -v; });
+    }
+
+    // remove zero lines, grid lines, and inside ticks if they're within
+    // 1 pixel of the end
+    // The key case here is removing zero lines when the axis bound is zero.
+    function clipEnds(d) {
+        var p = ax.l2p(d.x);
+        return (p>1 && p<ax._length-1);
+    }
+    var valsClipped = vals.filter(clipEnds);
+
+    function drawTicks(container,tickpath) {
+        var ticks = container.selectAll('path.'+tcls)
+            .data(ax.ticks==='inside' ? valsClipped : vals, datafn);
+        if(tickpath && ax.ticks) {
+            ticks.enter().append('path').classed(tcls, 1).classed('ticks', 1)
+                .classed('crisp', 1)
+                .call(Plotly.Color.stroke, ax.tickcolor)
+                .style('stroke-width', tickWidth + 'px')
+                .attr('d',tickpath);
+            ticks.attr('transform', transfn);
+            ticks.exit().remove();
+        }
+        else ticks.remove();
+    }
+
+    function drawLabels(container, position) {
+        // tick labels - for now just the main labels.
+        // TODO: mirror labels, esp for subplots
+        var tickLabels=container.selectAll('g.'+tcls).data(vals, datafn);
+        if(!ax.showticklabels || !isNumeric(position)) {
+            tickLabels.remove();
+            Titles.draw(td, axid + 'title');
+            return;
+        }
+
+        var labelx, labely, labelanchor, labelpos0;
+        if(axletter==='x') {
+            var flipit = axside==='bottom' ? 1 : -1;
+            labelx = function(d) { return d.dx; };
+            labelpos0 = position + (labelStandoff+pad)*flipit;
+            labely = function(d) {
+                return d.dy+labelpos0+d.fontSize *
+                    (axside==='bottom' ? 1 : -0.5);
+            };
+            labelanchor = function(angle) {
+                if(!isNumeric(angle) || angle===0 || angle===180) {
+                    return 'middle';
+                }
+                return angle*flipit<0 ? 'end' : 'start';
+            };
+        }
+        else {
+            labely = function(d) { return d.dy+d.fontSize/2; };
+            labelx = function(d) {
+                return d.dx + position + (labelStandoff + pad +
+                    (Math.abs(ax.tickangle)===90 ? d.fontSize/2 : 0)) *
+                    (axside==='right' ? 1 : -1);
+            };
+            labelanchor = function(angle) {
+                if(isNumeric(angle) && Math.abs(angle)===90) {
+                    return 'middle';
+                }
+                return axside==='right' ? 'start' : 'end';
+            };
+        }
+        var maxFontSize = 0,
+            autoangle = 0,
+            labelsReady = [];
+        tickLabels.enter().append('g').classed(tcls,1)
+            .append('text')
+                // only so tex has predictable alignment that we can
+                // alter later
+                .attr('text-anchor', 'middle')
+                .each(function(d) {
+                    var thisLabel = d3.select(this),
+                        newPromise = td._promises.length;
+                    thisLabel
+                        .call(Plotly.Drawing.setPosition,
+                            labelx(d), labely(d))
+                        .call(Plotly.Drawing.font,
+                            d.font, d.fontSize, d.fontColor)
+                        .text(d.text)
+                        .call(Plotly.util.convertToTspans);
+                    newPromise = td._promises[newPromise];
+                    if(newPromise) {
+                        // if we have an async label, we'll deal with that
+                        // all here so take it out of td._promises and
+                        // instead position the label and promise this in
+                        // labelsReady
+                        labelsReady.push(td._promises.pop().then(function() {
+                            positionLabels(thisLabel, ax.tickangle);
+                        }));
+                    }
+                    else {
+                        // sync label: just position it now.
+                        positionLabels(thisLabel, ax.tickangle);
+                    }
+                });
+        tickLabels.exit().remove();
+
+        tickLabels.each(function(d) {
+            maxFontSize = Math.max(maxFontSize, d.fontSize);
+        });
+
+        function positionLabels(s,angle) {
+            s.each(function(d) {
+                var anchor = labelanchor(angle);
+                var thisLabel = d3.select(this),
+                    mathjaxGroup = thisLabel.select('.text-math-group'),
+                    transform = transfn(d) +
+                        ((isNumeric(angle) && +angle!==0) ?
+                        (' rotate('+angle+','+labelx(d)+','+
+                            (labely(d)-d.fontSize/2)+')') :
+                        '');
+                if(mathjaxGroup.empty()) {
+                    var txt = thisLabel.select('text').attr({
+                        transform: transform,
+                        'text-anchor': anchor
+                    });
+
+                    if(!txt.empty()) {
+                        txt.selectAll('tspan.line').attr({
+                            x: txt.attr('x'),
+                            y: txt.attr('y')
+                        });
+                    }
+                }
+                else {
+                    var mjShift =
+                        Plotly.Drawing.bBox(mathjaxGroup.node()).width *
+                            {end: -0.5, start: 0.5}[anchor];
+                    mathjaxGroup.attr('transform', transform +
+                        (mjShift ? 'translate(' + mjShift + ',0)' : ''));
+                }
+            });
+        }
+
+        // make sure all labels are correctly positioned at their base angle
+        // the positionLabels call above is only for newly drawn labels.
+        // do this without waiting, using the last calculated angle to
+        // minimize flicker, then do it again when we know all labels are
+        // there, putting back the prescribed angle to check for overlaps.
+        positionLabels(tickLabels,ax._lastangle || ax.tickangle);
+
+        function allLabelsReady() {
+            return labelsReady.length && Promise.all(labelsReady);
+        }
+
+        function fixLabelOverlaps() {
+            positionLabels(tickLabels,ax.tickangle);
+
+            // check for auto-angling if x labels overlap
+            // don't auto-angle at all for log axes with
+            // base and digit format
+            if(axletter==='x' && !isNumeric(ax.tickangle) &&
+                    (ax.type!=='log' || String(ax.dtick).charAt(0)!=='D')) {
+                var lbbArray = [];
+                tickLabels.each(function(d) {
+                    var s = d3.select(this),
+                        thisLabel = s.select('.text-math-group'),
+                        x = ax.l2p(d.x);
+                    if(thisLabel.empty()) { thisLabel = s.select('text'); }
+                    var bb = Plotly.Drawing.bBox(thisLabel.node());
+
+                    lbbArray.push({
+                        // ignore about y, just deal with x overlaps
+                        top: 0,
+                        bottom: 10,
+                        height: 10,
+                        left: x-bb.width/2,
+                        // impose a 2px gap
+                        right: x+bb.width/2 + 2,
+                        width: bb.width + 2
+                    });
+                });
+                for(i=0; i<lbbArray.length-1; i++) {
+                    if(Plotly.Lib.bBoxIntersect(
+                            lbbArray[i],lbbArray[i+1])) {
+                        // any overlap at all - set 30 degrees
+                        autoangle = 30;
+                        break;
+                    }
+                }
+                if(autoangle) {
+                    var tickspacing = Math.abs(
+                            (vals[vals.length-1].x-vals[0].x)*ax._m
+                        )/(vals.length-1);
+                    if(tickspacing<maxFontSize*2.5) {
+                        autoangle = 90;
+                    }
+                    positionLabels(tickLabels,autoangle);
+                }
+                ax._lastangle = autoangle;
+            }
+
+            // update the axis title
+            // (so it can move out of the way if needed)
+            // TODO: separate out scoot so we don't need to do
+            // a full redraw of the title (modtly relevant for MathJax)
+            if(!skipTitle) Titles.draw(td, axid + 'title');
+            return axid+' done';
+        }
+
+        var done = Plotly.Lib.syncOrAsync([
+            allLabelsReady,
+            fixLabelOverlaps
+        ]);
+        if(done && done.then) td._promises.push(done);
+        return done;
+    }
+
+    function traceHasBarsOrFill(trace, subplot) {
+        if(trace.visible !== true || trace.xaxis + trace.yaxis !== subplot) return false;
+        if(Plotly.Plots.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axletter]) return true;
+        return trace.fill && trace.fill.charAt(trace.fill.length - 1) === axletter;
+    }
+
+    function drawGrid(plotinfo, counteraxis, subplot) {
+        var gridcontainer = plotinfo.gridlayer,
+            zlcontainer = plotinfo.zerolinelayer,
+            gridvals = plotinfo['hidegrid'+axletter]?[]:valsClipped,
+            gridpath = 'M0,0'+((axletter==='x') ? 'v' : 'h') +
+                counteraxis._length,
+            grid = gridcontainer.selectAll('path.'+gcls)
+                .data(ax.showgrid===false ? [] : gridvals, datafn);
+        grid.enter().append('path').classed(gcls, 1)
+            .classed('crisp', 1)
+            .attr('d', gridpath)
+            .each(function(d) {
+                if(ax.zeroline && (ax.type==='linear'||ax.type==='-') &&
+                        Math.abs(d.x)<ax.dtick/100) {
+                    d3.select(this).remove();
+                }
+            });
+        grid.attr('transform',transfn)
+            .call(Plotly.Color.stroke, ax.gridcolor || '#ddd')
+            .style('stroke-width', gridWidth+'px');
+        grid.exit().remove();
+
+        // zero line
+        var hasBarsOrFill = false;
+        for(var i = 0; i < td._fullData.length; i++) {
+            if(traceHasBarsOrFill(td._fullData[i], subplot)) {
+                hasBarsOrFill = true;
+                break;
+            }
+        }
+        var showZl = (ax.range[0]*ax.range[1]<=0) && ax.zeroline &&
+            (ax.type==='linear' || ax.type==='-') && gridvals.length &&
+            (hasBarsOrFill || clipEnds({x: 0}) || !ax.showline);
+
+        var zl = zlcontainer.selectAll('path.'+zcls)
+            .data(showZl ? [{x: 0}] : []);
+        zl.enter().append('path').classed(zcls,1).classed('zl',1)
+            .classed('crisp',1)
+            .attr('d',gridpath);
+        zl.attr('transform',transfn)
+            .call(Plotly.Color.stroke, ax.zerolinecolor || Plotly.Color.defaultLine)
+            .style('stroke-width', zeroLineWidth+'px');
+        zl.exit().remove();
+    }
+
+    if(independent) {
+        drawTicks(ax._axislayer, tickprefix + (ax._pos+pad*ticksign[2]) +
+            tickmid + (ticksign[2]*ax.ticklen));
+        return drawLabels(ax._axislayer,ax._pos);
+    }
+    else {
+        var alldone = axes.getSubplots(td,ax).map(function(subplot) {
+            var plotinfo = fullLayout._plots[subplot];
+
+            if(!fullLayout._hasCartesian) return;
+
+            var container = plotinfo[axletter + 'axislayer'],
+
+                // [bottom or left, top or right, free, main]
+                linepositions = ax._linepositions[subplot]||[],
+                counteraxis = plotinfo[counterLetter](),
+                mainSubplot = counteraxis._id===ax.anchor,
+                ticksides = [false, false, false],
+                tickpath='';
+
+            // ticks
+            if(ax.mirror==='allticks') ticksides = [true, true, false];
+            else if(mainSubplot) {
+                if(ax.mirror==='ticks') ticksides = [true, true, false];
+                else ticksides[sides.indexOf(axside)] = true;
+            }
+            if(ax.mirrors) {
+                for(i=0; i<2; i++) {
+                    var thisMirror = ax.mirrors[counteraxis._id+sides[i]];
+                    if(thisMirror==='ticks' || thisMirror==='labels') {
+                        ticksides[i] = true;
+                    }
+                }
+            }
+
+            // free axis ticks
+            if(linepositions[2]!==undefined) ticksides[2] = true;
+
+            ticksides.forEach(function(showside, sidei) {
+                var pos = linepositions[sidei],
+                    tsign = ticksign[sidei];
+                if(showside && isNumeric(pos)) {
+                    tickpath += tickprefix + (pos+pad*tsign) +
+                        tickmid + (tsign*ax.ticklen);
+                }
+            });
+
+            drawTicks(container, tickpath);
+            drawGrid(plotinfo, counteraxis, subplot);
+            return drawLabels(container,linepositions[3]);
+        }).filter(function(onedone) { return onedone && onedone.then; });
+
+        return alldone.length ? Promise.all(alldone) : 0;
+    }
+};
+
+// swap all the presentation attributes of the axes showing these traces
+axes.swap = function(gd, traces) {
+    var axGroups = makeAxisGroups(gd, traces);
+
+    for(var i = 0; i < axGroups.length; i++) {
+        swapAxisGroup(gd, axGroups[i].x, axGroups[i].y);
+    }
+};
+
+function makeAxisGroups(gd, traces) {
+    var groups = [],
+        i,
+        j;
+
+    for(i = 0; i < traces.length; i++) {
+        var groupsi = [],
+            xi = gd._fullData[traces[i]].xaxis,
+            yi = gd._fullData[traces[i]].yaxis;
+        if(!xi || !yi) continue; // not a 2D cartesian trace?
+
+        for(j = 0; j < groups.length; j++) {
+            if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) {
+                groupsi.push(j);
+            }
+        }
+
+        if(!groupsi.length) {
+            groups.push({x: [xi], y: [yi]});
+            continue;
+        }
+
+        var group0 = groups[groupsi[0]],
+            groupj;
+
+        if(groupsi.length>1) {
+            for(j = 1; j < groupsi.length; j++) {
+                groupj = groups[groupsi[j]];
+                mergeAxisGroups(group0.x, groupj.x);
+                mergeAxisGroups(group0.y, groupj.y);
+            }
+        }
+        mergeAxisGroups(group0.x, [xi]);
+        mergeAxisGroups(group0.y, [yi]);
+    }
+
+    return groups;
+}
+
+function mergeAxisGroups(intoSet, fromSet) {
+    for(var i = 0; i < fromSet.length; i++) {
+        if(intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]);
+    }
+}
+
+function swapAxisGroup(gd, xIds, yIds) {
+    var i,
+        j,
+        xFullAxes = [],
+        yFullAxes = [],
+        layout = gd.layout;
+
+    for(i = 0; i < xIds.length; i++) xFullAxes.push(axes.getFromId(gd, xIds[i]));
+    for(i = 0; i < yIds.length; i++) yFullAxes.push(axes.getFromId(gd, yIds[i]));
+
+    var allAxKeys = Object.keys(xFullAxes[0]),
+        noSwapAttrs = [
+            'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle'
+        ],
+        numericTypes = ['linear', 'log'];
+
+    for(i = 0; i < allAxKeys.length; i++) {
+        var keyi = allAxKeys[i],
+            xVal = xFullAxes[0][keyi],
+            yVal = yFullAxes[0][keyi],
+            allEqual = true,
+            coerceLinearX = false,
+            coerceLinearY = false;
+        if(keyi.charAt(0) === '_' || typeof xVal === 'function' ||
+                noSwapAttrs.indexOf(keyi) !== -1) {
+            continue;
+        }
+        for(j = 1; j < xFullAxes.length && allEqual; j++) {
+            var xVali = xFullAxes[j][keyi];
+            if(keyi === 'type' && numericTypes.indexOf(xVal) !== -1 &&
+                    numericTypes.indexOf(xVali) !== -1 && xVal !== xVali) {
+                // type is special - if we find a mixture of linear and log,
+                // coerce them all to linear on flipping
+                coerceLinearX = true;
+            }
+            else if(xVali !== xVal) allEqual = false;
+        }
+        for(j = 1; j < yFullAxes.length && allEqual; j++) {
+            var yVali = yFullAxes[j][keyi];
+            if(keyi === 'type' && numericTypes.indexOf(yVal) !== -1 &&
+                    numericTypes.indexOf(yVali) !== -1 && yVal !== yVali) {
+                // type is special - if we find a mixture of linear and log,
+                // coerce them all to linear on flipping
+                coerceLinearY = true;
+            }
+            else if(yFullAxes[j][keyi] !== yVal) allEqual = false;
+        }
+        if(allEqual) {
+            if(coerceLinearX) layout[xFullAxes[0]._name].type = 'linear';
+            if(coerceLinearY) layout[yFullAxes[0]._name].type = 'linear';
+            swapAxisAttrs(layout, keyi, xFullAxes, yFullAxes);
+        }
+    }
+
+    // now swap x&y for any annotations anchored to these x & y
+    for(i = 0; i < gd._fullLayout.annotations.length; i++) {
+        var ann = gd._fullLayout.annotations[i];
+        if(xIds.indexOf(ann.xref) !== -1 &&
+                yIds.indexOf(ann.yref) !== -1) {
+            Plotly.Lib.swapAttrs(layout.annotations[i],['?']);
+        }
+    }
+}
+
+function swapAxisAttrs(layout, key, xFullAxes, yFullAxes) {
+    // in case the value is the default for either axis,
+    // look at the first axis in each list and see if
+    // this key's value is undefined
+    var np = Plotly.Lib.nestedProperty,
+        xVal = np(layout[xFullAxes[0]._name], key).get(),
+        yVal = np(layout[yFullAxes[0]._name], key).get(),
+        i;
+    if(key === 'title') {
+        // special handling of placeholder titles
+        if(xVal === 'Click to enter X axis title') {
+            xVal = 'Click to enter Y axis title';
+        }
+        if(yVal === 'Click to enter Y axis title') {
+            yVal = 'Click to enter X axis title';
+        }
+    }
+
+    for(i = 0; i < xFullAxes.length; i++) {
+        np(layout, xFullAxes[i]._name + '.' + key).set(yVal);
+    }
+    for(i = 0; i < yFullAxes.length; i++) {
+        np(layout, yFullAxes[i]._name + '.' + key).set(xVal);
+    }
+}
+
+// mod - version of modulus that always restricts to [0,divisor)
+// rather than built-in % which gives a negative value for negative v
+function mod(v,d) { return ((v%d) + d) % d; }
+
+},{"../../components/titles":332,"../../plotly":366,"./axis_ids":371,"./layout_attributes":376,"./layout_defaults":377,"./set_convert":380,"d3":70,"fast-isnumeric":74}],370:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+var Plots = require('../plots');
+
+var layoutAttributes = require('./layout_attributes');
+var handleTickValueDefaults = require('./tick_value_defaults');
+var handleTickDefaults = require('./tick_defaults');
+var setConvert = require('./set_convert');
+var cleanDatum = require('./clean_datum');
+var axisIds = require('./axis_ids');
+
+
+/**
+ * options: object containing:
+ *
+ *  letter: 'x' or 'y'
+ *  title: name of the axis (ie 'Colorbar') to go in default title
+ *  name: axis object name (ie 'xaxis') if one should be stored
+ *  font: the default font to inherit
+ *  outerTicks: boolean, should ticks default to outside?
+ *  showGrid: boolean, should gridlines be shown by default?
+ *  noHover: boolean, this axis doesn't support hover effects?
+ *  data: the plot data to use in choosing auto type
+ */
+module.exports = function handleAxisDefaults(containerIn, containerOut, coerce, options) {
+    var letter = options.letter,
+        font = options.font || {},
+        defaultTitle = 'Click to enter ' +
+            (options.title || (letter.toUpperCase() + ' axis')) +
+            ' title';
+
+    // set up some private properties
+    if(options.name) {
+        containerOut._name = options.name;
+        containerOut._id = axisIds.name2id(options.name);
+    }
+
+    // now figure out type and do some more initialization
+    var axType = coerce('type');
+    if(axType === '-') {
+        setAutoType(containerOut, options.data);
+
+        if(containerOut.type === '-') {
+            containerOut.type = 'linear';
+        }
+        else {
+            // copy autoType back to input axis
+            // note that if this object didn't exist
+            // in the input layout, we have to put it in
+            // this happens in the main supplyDefaults function
+            axType = containerIn.type = containerOut.type;
+        }
+    }
+
+    setConvert(containerOut);
+
+    coerce('title', defaultTitle);
+    Lib.coerceFont(coerce, 'titlefont', {
+        family: font.family,
+        size: Math.round(font.size * 1.2),
+        color: font.color
+    });
+
+    var validRange = (
+        (containerIn.range || []).length === 2 &&
+        isNumeric(containerIn.range[0]) &&
+        isNumeric(containerIn.range[1])
+    );
+    var autoRange = coerce('autorange', !validRange);
+
+    if(autoRange) coerce('rangemode');
+    var range = coerce('range', [-1, letter === 'x' ? 6 : 4]);
+    if(range[0] === range[1]) {
+        containerOut.range = [range[0] - 1, range[0] + 1];
+    }
+    Lib.noneOrAll(containerIn.range, containerOut.range, [0, 1]);
+
+    coerce('fixedrange');
+
+    handleTickValueDefaults(containerIn, containerOut, coerce, axType);
+    handleTickDefaults(containerIn, containerOut, coerce, axType, options);
+
+    var lineColor = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'linecolor'),
+        lineWidth = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'linewidth'),
+        showLine = coerce('showline', !!lineColor || !!lineWidth);
+
+    if(!showLine) {
+        delete containerOut.linecolor;
+        delete containerOut.linewidth;
+    }
+
+    if(showLine || containerOut.ticks) coerce('mirror');
+
+    var gridColor = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'gridcolor'),
+        gridWidth = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'gridwidth'),
+        showGridLines = coerce('showgrid', options.showGrid || !!gridColor || !!gridWidth);
+
+    if(!showGridLines) {
+        delete containerOut.gridcolor;
+        delete containerOut.gridwidth;
+    }
+
+    var zeroLineColor = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'zerolinecolor'),
+        zeroLineWidth = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'zerolinewidth'),
+        showZeroLine = coerce('zeroline', options.showGrid || !!zeroLineColor || !!zeroLineWidth);
+
+    if(!showZeroLine) {
+        delete containerOut.zerolinecolor;
+        delete containerOut.zerolinewidth;
+    }
+
+    return containerOut;
+};
+
+function setAutoType(ax, data) {
+    // new logic: let people specify any type they want,
+    // only autotype if type is '-'
+    if(ax.type!=='-') return;
+
+    var id = ax._id,
+        axLetter = id.charAt(0);
+
+    // support 3d
+    if(id.indexOf('scene') !== -1) id = axLetter;
+
+    var d0 = getFirstNonEmptyTrace(data, id, axLetter);
+    if(!d0) return;
+
+    // first check for histograms, as the count direction
+    // should always default to a linear axis
+    if(d0.type==='histogram' &&
+            axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) {
+        ax.type='linear';
+        return;
+    }
+
+    // check all boxes on this x axis to see
+    // if they're dates, numbers, or categories
+    if(isBoxWithoutPositionCoords(d0, axLetter)) {
+        var posLetter = getBoxPosLetter(d0),
+            boxPositions = [],
+            trace;
+
+        for(var i = 0; i < data.length; i++) {
+            trace = data[i];
+            if(!Plots.traceIs(trace, 'box') ||
+               (trace[axLetter + 'axis'] || axLetter) !== id) continue;
+
+            if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]);
+            else if(trace.name !== undefined) boxPositions.push(trace.name);
+            else boxPositions.push('text');
+        }
+
+        ax.type = autoType(boxPositions);
+    }
+    else {
+        ax.type = autoType(d0[axLetter] || [d0[axLetter+'0']]);
+    }
+}
+
+function getBoxPosLetter(trace) {
+    return {v: 'x', h: 'y'}[trace.orientation || 'v'];
+}
+
+function isBoxWithoutPositionCoords(trace, axLetter) {
+    var posLetter = getBoxPosLetter(trace);
+
+    return (
+        Plots.traceIs(trace, 'box') &&
+        axLetter === posLetter &&
+        trace[posLetter] === undefined &&
+        trace[posLetter + '0'] === undefined
+    );
+}
+
+function autoType(array) {
+    if(moreDates(array)) return 'date';
+    if(category(array)) return 'category';
+    if(linearOK(array)) return 'linear';
+    else return '-';
+}
+
+function getFirstNonEmptyTrace(data, id, axLetter) {
+    for(var i = 0; i < data.length; i++) {
+        var trace = data[i];
+
+        if((trace[axLetter + 'axis'] || axLetter) === id) {
+            if(isBoxWithoutPositionCoords(trace, axLetter)) {
+                return trace;
+            }
+            else if((trace[axLetter] || []).length || trace[axLetter + '0']) {
+                return trace;
+            }
+        }
+    }
+}
+
+// is there at least one number in array? If not, we should leave
+// ax.type empty so it can be autoset later
+function linearOK(array) {
+    if(!array) return false;
+
+    for(var i = 0; i < array.length; i++) {
+        if(isNumeric(array[i])) return true;
+    }
+
+    return false;
+}
+
+// does the array a have mostly dates rather than numbers?
+// note: some values can be neither (such as blanks, text)
+// 2- or 4-digit integers can be both, so require twice as many
+// dates as non-dates, to exclude cases with mostly 2 & 4 digit
+// numbers and a few dates
+function moreDates(a) {
+    var dcnt = 0,
+        ncnt = 0,
+        // test at most 1000 points, evenly spaced
+        inc = Math.max(1, (a.length - 1) / 1000),
+        ai;
+
+    for(var i = 0; i < a.length; i += inc) {
+        ai = a[Math.round(i)];
+        if(Lib.isDateTime(ai)) dcnt += 1;
+        if(isNumeric(ai)) ncnt += 1;
+    }
+
+    return (dcnt > ncnt * 2);
+}
+
+// are the (x,y)-values in td.data mostly text?
+// require twice as many categories as numbers
+function category(a) {
+    // test at most 1000 points
+    var inc = Math.max(1, (a.length - 1) / 1000),
+        curvenums = 0,
+        curvecats = 0,
+        ai;
+
+    for(var i = 0; i < a.length; i += inc) {
+        ai = cleanDatum(a[Math.round(i)]);
+        if(isNumeric(ai)) curvenums++;
+        else if(typeof ai === 'string' && ai !== '' && ai !== 'None') curvecats++;
+    }
+
+    return curvecats > curvenums * 2;
+}
+
+},{"../../lib":349,"../plots":413,"./axis_ids":371,"./clean_datum":372,"./layout_attributes":376,"./set_convert":380,"./tick_defaults":381,"./tick_value_defaults":382,"fast-isnumeric":74}],371:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Plots = require('../plots');
+var Lib = require('../../lib');
+
+var constants = require('./constants');
+
+
+// convert between axis names (xaxis, xaxis2, etc, elements of gd.layout)
+// and axis id's (x, x2, etc). Would probably have ditched 'xaxis'
+// completely in favor of just 'x' if it weren't ingrained in the API etc.
+exports.id2name = function id2name(id) {
+    if(typeof id !== 'string' || !id.match(constants.AX_ID_PATTERN)) return;
+    var axNum = id.substr(1);
+    if(axNum === '1') axNum = '';
+    return id.charAt(0) + 'axis' + axNum;
+};
+
+exports.name2id = function name2id(name) {
+    if(!name.match(constants.AX_NAME_PATTERN)) return;
+    var axNum = name.substr(5);
+    if(axNum === '1') axNum = '';
+    return name.charAt(0) + axNum;
+};
+
+exports.cleanId = function cleanId(id, axLetter) {
+    if(!id.match(constants.AX_ID_PATTERN)) return;
+    if(axLetter && id.charAt(0) !== axLetter) return;
+
+    var axNum = id.substr(1).replace(/^0+/,'');
+    if(axNum === '1') axNum = '';
+    return id.charAt(0) + axNum;
+};
+
+// get all axis object names
+// optionally restricted to only x or y or z by string axLetter
+// and optionally 2D axes only, not those inside 3D scenes
+function listNames(gd, axLetter, only2d) {
+    var fullLayout = gd._fullLayout;
+    if(!fullLayout) return [];
+
+    function filterAxis(obj, extra) {
+        var keys = Object.keys(obj),
+            axMatch = /^[xyz]axis[0-9]*/,
+            out = [];
+
+        for(var i = 0; i < keys.length; i++) {
+            var k = keys[i];
+            if(axLetter && k.charAt(0) !== axLetter) continue;
+            if(axMatch.test(k)) out.push(extra + k);
+        }
+
+        return out.sort();
+    }
+
+    var names = filterAxis(fullLayout, '');
+    if(only2d) return names;
+
+    var sceneIds3D = Plots.getSubplotIds(fullLayout, 'gl3d') || [];
+    for(var i = 0; i < sceneIds3D.length; i++) {
+        var sceneId = sceneIds3D[i];
+        names = names.concat(
+            filterAxis(fullLayout[sceneId], sceneId + '.')
+        );
+    }
+
+    return names;
+}
+
+// get all axis objects, as restricted in listNames
+exports.list = function(gd, axletter, only2d) {
+    return listNames(gd, axletter, only2d)
+        .map(function(axName) {
+            return Lib.nestedProperty(gd._fullLayout, axName).get();
+        });
+};
+
+// get all axis ids, optionally restricted by letter
+// this only makes sense for 2d axes
+exports.listIds = function(gd, axletter) {
+    return listNames(gd, axletter, true).map(exports.name2id);
+};
+
+// get an axis object from its id 'x','x2' etc
+// optionally, id can be a subplot (ie 'x2y3') and type gets x or y from it
+exports.getFromId = function(gd, id, type) {
+    var fullLayout = gd._fullLayout;
+
+    if(type === 'x') id = id.replace(/y[0-9]*/,'');
+    else if(type === 'y') id = id.replace(/x[0-9]*/,'');
+
+    return fullLayout[exports.id2name(id)];
+};
+
+// get an axis object of specified type from the containing trace
+exports.getFromTrace = function(gd, fullTrace, type) {
+    var fullLayout = gd._fullLayout;
+    var ax = null;
+
+    if(Plots.traceIs(fullTrace, 'gl3d')) {
+        var scene = fullTrace.scene;
+        if(scene.substr(0, 5) === 'scene') {
+            ax = fullLayout[scene][type + 'axis'];
+        }
+    }
+    else {
+        ax = exports.getFromId(gd, fullTrace[type + 'axis'] || type);
+    }
+
+    return ax;
+};
+
+},{"../../lib":349,"../plots":413,"./constants":373}],372:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+
+
+/**
+ * cleanDatum: removes characters
+ * same replace criteria used in the grid.js:scrapeCol
+ * but also handling dates, numbers, and NaN, null, Infinity etc
+ */
+module.exports = function cleanDatum(c) {
+    try {
+        if(typeof c === 'object' && c !== null && c.getTime) {
+            return Lib.ms2DateTime(c);
+        }
+        if(typeof c !== 'string' && !isNumeric(c)) {
+            return '';
+        }
+        c = c.toString().replace(/['"%,$# ]/g, '');
+    }
+    catch(e) {
+        console.log(e, c);
+    }
+
+    return c;
+};
+
+},{"../../lib":349,"fast-isnumeric":74}],373:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+module.exports = {
+    /**
+     * standardize all missing data in calcdata to use undefined
+     * never null or NaN.
+     * that way we can use !==undefined, or !== BADNUM,
+     * to test for real data
+     */
+    BADNUM: undefined,
+
+    // axis match regular expression
+    xAxisMatch: /^xaxis[0-9]*$/,
+    yAxisMatch: /^yaxis[0-9]*$/,
+
+    // pattern matching axis ids and names
+    AX_ID_PATTERN: /^[xyz][0-9]*$/,
+    AX_NAME_PATTERN: /^[xyz]axis[0-9]*$/,
+
+    // ms between first mousedown and 2nd mouseup to constitute dblclick...
+    // we don't seem to have access to the system setting
+    DBLCLICKDELAY: 600,
+
+    // pixels to move mouse before you stop clamping to starting point
+    MINDRAG: 8,
+
+    // smallest dimension allowed for a select box
+    MINSELECT: 12,
+
+    // smallest dimension allowed for a zoombox
+    MINZOOM: 20,
+
+    // width of axis drag regions
+    DRAGGERSIZE: 20,
+
+    // max pixels away from mouse to allow a point to highlight
+    MAXDIST: 20,
+
+    // hover labels for multiple horizontal bars get tilted by this angle
+    YANGLE: 60,
+
+    // size and display constants for hover text
+    HOVERARROWSIZE: 6, // pixel size of hover arrows
+    HOVERTEXTPAD: 3, // pixels padding around text
+    HOVERFONTSIZE: 13,
+    HOVERFONT: 'Arial, sans-serif',
+
+    // minimum time (msec) between hover calls
+    HOVERMINTIME: 100,
+
+    // max pixels off straight before a lasso select line counts as bent
+    BENDPX: 1.5
+};
+
+},{}],374:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var tinycolor = require('tinycolor2');
+var isNumeric = require('fast-isnumeric');
+
+var Plotly = require('../../plotly');
+var Lib = require('../../lib');
+var Events = require('../../lib/events');
+
+var prepSelect = require('./select');
+var constants = require('./constants');
+
+var fx = module.exports = {};
+
+fx.layoutAttributes = {
+    dragmode: {
+        valType: 'enumerated',
+        
+        values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable'],
+        dflt: 'zoom',
+        
+    },
+    hovermode: {
+        valType: 'enumerated',
+        
+        values: ['x', 'y', 'closest', false],
+        
+    }
+};
+
+fx.supplyLayoutDefaults = function(layoutIn, layoutOut, fullData) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(layoutIn, layoutOut, fx.layoutAttributes, attr, dflt);
+    }
+
+    coerce('dragmode');
+
+    var hovermodeDflt;
+    if(layoutOut._hasCartesian) {
+        // flag for 'horizontal' plots:
+        // determines the state of the mode bar 'compare' hovermode button
+        var isHoriz = layoutOut._isHoriz = fx.isHoriz(fullData);
+        hovermodeDflt = isHoriz ? 'y' : 'x';
+    }
+    else hovermodeDflt = 'closest';
+
+    coerce('hovermode', hovermodeDflt);
+};
+
+fx.isHoriz = function(fullData) {
+    var isHoriz = true;
+
+    for(var i = 0; i < fullData.length; i++) {
+        var trace = fullData[i];
+
+        if(trace.orientation !== 'h') {
+            isHoriz = false;
+            break;
+        }
+    }
+
+    return isHoriz;
+};
+
+fx.init = function(gd) {
+    var fullLayout = gd._fullLayout;
+
+    if(!fullLayout._hasCartesian || gd._context.staticPlot) return;
+
+    var subplots = Object.keys(fullLayout._plots || {}).sort(function(a,b) {
+        // sort overlays last, then by x axis number, then y axis number
+        if((fullLayout._plots[a].mainplot && true) ===
+            (fullLayout._plots[b].mainplot && true)) {
+            var aParts = a.split('y'),
+                bParts = b.split('y');
+            return (aParts[0]===bParts[0]) ?
+                (Number(aParts[1]||1) - Number(bParts[1]||1)) :
+                (Number(aParts[0]||1) - Number(bParts[0]||1));
+        }
+        return fullLayout._plots[a].mainplot ? 1 : -1;
+    });
+
+    subplots.forEach(function(subplot) {
+        var plotinfo = fullLayout._plots[subplot];
+
+        if(!fullLayout._hasCartesian) return;
+
+        var xa = plotinfo.x(),
+            ya = plotinfo.y(),
+
+            // the y position of the main x axis line
+            y0 = (xa._linepositions[subplot]||[])[3],
+
+            // the x position of the main y axis line
+            x0 = (ya._linepositions[subplot]||[])[3];
+
+        var DRAGGERSIZE = constants.DRAGGERSIZE;
+        if(isNumeric(y0) && xa.side==='top') y0 -= DRAGGERSIZE;
+        if(isNumeric(x0) && ya.side!=='right') x0 -= DRAGGERSIZE;
+
+        // main and corner draggers need not be repeated for
+        // overlaid subplots - these draggers drag them all
+        if(!plotinfo.mainplot) {
+            // main dragger goes over the grids and data, so we use its
+            // mousemove events for all data hover effects
+            var maindrag = dragBox(gd, plotinfo, 0, 0,
+                xa._length, ya._length,'ns','ew');
+
+            maindrag.onmousemove = function(evt) {
+                fx.hover(gd, evt, subplot);
+                fullLayout._lasthover = maindrag;
+                fullLayout._hoversubplot = subplot;
+            };
+
+            /*
+             * IMPORTANT:
+             * We must check for the presence of the drag cover here.
+             * If we don't, a 'mouseout' event is triggered on the
+             * maindrag before each 'click' event, which has the effect
+             * of clearing the hoverdata; thus, cancelling the click event.
+             */
+            maindrag.onmouseout = function(evt) {
+                if(gd._dragging) return;
+
+                fx.unhover(gd, evt);
+            };
+
+            maindrag.onclick = function(evt) {
+                fx.click(gd, evt);
+            };
+
+            // corner draggers
+            dragBox(gd, plotinfo, -DRAGGERSIZE, -DRAGGERSIZE,
+                DRAGGERSIZE, DRAGGERSIZE, 'n', 'w');
+            dragBox(gd, plotinfo, xa._length, -DRAGGERSIZE,
+                DRAGGERSIZE, DRAGGERSIZE, 'n', 'e');
+            dragBox(gd, plotinfo, -DRAGGERSIZE, ya._length,
+                DRAGGERSIZE, DRAGGERSIZE, 's', 'w');
+            dragBox(gd, plotinfo, xa._length, ya._length,
+                DRAGGERSIZE, DRAGGERSIZE, 's', 'e');
+        }
+
+        // x axis draggers - if you have overlaid plots,
+        // these drag each axis separately
+        if(isNumeric(y0)) {
+            if(xa.anchor==='free') y0 -= fullLayout._size.h*(1-ya.domain[1]);
+            dragBox(gd, plotinfo, xa._length*0.1, y0,
+                xa._length*0.8, DRAGGERSIZE, '', 'ew');
+            dragBox(gd, plotinfo, 0, y0,
+                xa._length*0.1, DRAGGERSIZE, '', 'w');
+            dragBox(gd, plotinfo, xa._length*0.9, y0,
+                xa._length*0.1, DRAGGERSIZE, '', 'e');
+        }
+        // y axis draggers
+        if(isNumeric(x0)) {
+            if(ya.anchor==='free') x0 -= fullLayout._size.w*xa.domain[0];
+            dragBox(gd, plotinfo, x0, ya._length*0.1,
+                DRAGGERSIZE, ya._length*0.8, 'ns', '');
+            dragBox(gd, plotinfo, x0, ya._length*0.9,
+                DRAGGERSIZE, ya._length*0.1, 's', '');
+            dragBox(gd, plotinfo, x0, 0,
+                DRAGGERSIZE, ya._length*0.1, 'n', '');
+        }
+    });
+
+    // In case you mousemove over some hovertext, send it to fx.hover too
+    // we do this so that we can put the hover text in front of everything,
+    // but still be able to interact with everything as if it isn't there
+    var hoverLayer = fullLayout._hoverlayer.node();
+
+    hoverLayer.onmousemove = function(evt) {
+        evt.target = fullLayout._lasthover;
+        fx.hover(gd, evt, fullLayout._hoversubplot);
+    };
+
+    hoverLayer.onclick = function(evt) {
+        evt.target = fullLayout._lasthover;
+        fx.click(gd, evt);
+    };
+
+    // also delegate mousedowns... TODO: does this actually work?
+    hoverLayer.onmousedown = function(evt) {
+        fullLayout._lasthover.onmousedown(evt);
+    };
+};
+
+// hover labels for multiple horizontal bars get tilted by some angle,
+// then need to be offset differently if they overlap
+var YANGLE = constants.YANGLE,
+    YA_RADIANS = Math.PI*YANGLE/180,
+
+    // expansion of projected height
+    YFACTOR = 1/Math.sin(YA_RADIANS),
+
+    // to make the appropriate post-rotation x offset,
+    // you need both x and y offsets
+    YSHIFTX = Math.cos(YA_RADIANS),
+    YSHIFTY = Math.sin(YA_RADIANS);
+
+// convenience functions for mapping all relevant axes
+function flat(subplots, v) {
+    var out = [];
+    for(var i=subplots.length; i>0; i--) out.push(v);
+    return out;
+}
+
+function p2c(axArray, v) {
+    var out = [];
+    for(var i=0; i<axArray.length; i++) out.push(axArray[i].p2c(v));
+    return out;
+}
+
+function quadrature(dx, dy) {
+    return function(di) {
+        var x = dx(di),
+            y = dy(di);
+        return Math.sqrt(x*x + y*y);
+    };
+}
+
+// size and display constants for hover text
+var HOVERARROWSIZE = constants.HOVERARROWSIZE,
+    HOVERTEXTPAD = constants.HOVERTEXTPAD,
+    HOVERFONTSIZE = constants.HOVERFONTSIZE,
+    HOVERFONT = constants.HOVERFONT;
+
+// fx.hover: highlight data on hover
+// evt can be a mousemove event, or an object with data about what points
+//   to hover on
+//      {xpx,ypx[,hovermode]} - pixel locations from top left
+//          (with optional overriding hovermode)
+//      {xval,yval[,hovermode]} - data values
+//      [{curveNumber,(pointNumber|xval and/or yval)}] -
+//              array of specific points to highlight
+//          pointNumber is a single integer if gd.data[curveNumber] is 1D,
+//              or a two-element array if it's 2D
+//          xval and yval are data values,
+//              1D data may specify either or both,
+//              2D data must specify both
+// subplot is an id string (default "xy")
+// makes use of gl.hovermode, which can be:
+//      x (find the points with the closest x values, ie a column),
+//      closest (find the single closest point)
+//    internally there are two more that occasionally get used:
+//      y (pick out a row - only used for multiple horizontal bar charts)
+//      array (used when the user specifies an explicit
+//          array of points to hover on)
+//
+// We wrap the hovers in a timer, to limit their frequency.
+// The actual rendering is done by private functions
+// hover() and unhover().
+
+fx.hover = function(gd, evt, subplot) {
+    if(typeof gd === 'string') gd = document.getElementById(gd);
+    if(gd._lastHoverTime === undefined) gd._lastHoverTime = 0;
+
+    // If we have an update queued, discard it now
+    if(gd._hoverTimer !== undefined) {
+        clearTimeout(gd._hoverTimer);
+        gd._hoverTimer = undefined;
+    }
+    // Is it more than 100ms since the last update?  If so, force
+    // an update now (synchronously) and exit
+    if(Date.now() > gd._lastHoverTime + constants.HOVERMINTIME) {
+        hover(gd,evt,subplot);
+        gd._lastHoverTime = Date.now();
+        return;
+    }
+    // Queue up the next hover for 100ms from now (if no further events)
+    gd._hoverTimer = setTimeout(function() {
+        hover(gd,evt,subplot);
+        gd._lastHoverTime = Date.now();
+        gd._hoverTimer = undefined;
+    }, constants.HOVERMINTIME);
+};
+
+fx.unhover = function(gd, evt, subplot) {
+    if(typeof gd === 'string') gd = document.getElementById(gd);
+    // Important, clear any queued hovers
+    if(gd._hoverTimer) {
+        clearTimeout(gd._hoverTimer);
+        gd._hoverTimer = undefined;
+    }
+    unhover(gd,evt,subplot);
+};
+
+// The actual implementation is here:
+
+function hover(gd, evt, subplot) {
+    if(subplot === 'pie') {
+        gd.emit('plotly_hover', {
+            points: [evt]
+        });
+        return;
+    }
+
+    if(!subplot) subplot = 'xy';
+
+    var fullLayout = gd._fullLayout,
+        plotinfo = fullLayout._plots[subplot],
+        // list of all overlaid subplots to look at
+        subplots = [subplot].concat(plotinfo.overlays
+            .map(function(pi) { return pi.id; })),
+        xaArray = subplots.map(function(spId) {
+            return Plotly.Axes.getFromId(gd, spId, 'x');
+        }),
+        yaArray = subplots.map(function(spId) {
+            return Plotly.Axes.getFromId(gd, spId, 'y');
+        }),
+        hovermode = evt.hovermode || fullLayout.hovermode;
+
+    if(['x','y','closest'].indexOf(hovermode)===-1 || !gd.calcdata ||
+            gd.querySelector('.zoombox') || gd._dragging) {
+        return unhover(gd, evt);
+    }
+
+        // hoverData: the set of candidate points we've found to highlight
+    var hoverData = [],
+
+        // searchData: the data to search in. Mostly this is just a copy of
+        // gd.calcdata, filtered to the subplot and overlays we're on
+        // but if a point array is supplied it will be a mapping
+        // of indicated curves
+        searchData = [],
+
+        // [x|y]valArray: the axis values of the hover event
+        // mapped onto each of the currently selected overlaid subplots
+        xvalArray,
+        yvalArray,
+
+        // used in loops
+        itemnum,
+        curvenum,
+        cd,
+        trace,
+        subploti,
+        mode,
+        xval,
+        yval,
+        pointData,
+        closedataPreviousLength;
+
+    // Figure out what we're hovering on:
+    // mouse location or user-supplied data
+
+    if(Array.isArray(evt)) {
+        // user specified an array of points to highlight
+        hovermode = 'array';
+        for(itemnum = 0; itemnum<evt.length; itemnum++) {
+            cd = gd.calcdata[evt[itemnum].curveNumber||0];
+            if(cd[0].trace.hoverinfo!=='none') searchData.push(cd);
+        }
+    }
+    else {
+        for(curvenum = 0; curvenum<gd.calcdata.length; curvenum++) {
+            cd = gd.calcdata[curvenum];
+            trace = cd[0].trace;
+            if(trace.hoverinfo!=='none' && subplots.indexOf(trace.xaxis + trace.yaxis)!==-1) {
+                searchData.push(cd);
+            }
+        }
+
+        // [x|y]px: the pixels (from top left) of the mouse location
+        // on the currently selected plot area
+        var xpx, ypx;
+
+        // mouse event? ie is there a target element with
+        // clientX and clientY values?
+        if(evt.target && ('clientX' in evt) && ('clientY' in evt)) {
+
+            // fire the beforehover event and quit if it returns false
+            // note that we're only calling this on real mouse events, so
+            // manual calls to fx.hover will always run.
+            if(Events.triggerHandler(gd, 'plotly_beforehover', evt)===false) {
+                return;
+            }
+
+            var dbb = evt.target.getBoundingClientRect();
+
+            xpx = evt.clientX - dbb.left;
+            ypx = evt.clientY - dbb.top;
+
+            // in case hover was called from mouseout into hovertext,
+            // it's possible you're not actually over the plot anymore
+            if(xpx<0 || xpx>dbb.width || ypx<0 || ypx>dbb.height) {
+                return unhover(gd,evt);
+            }
+        }
+        else {
+            if('xpx' in evt) xpx = evt.xpx;
+            else xpx = xaArray[0]._length/2;
+
+            if('ypx' in evt) ypx = evt.ypx;
+            else ypx = yaArray[0]._length/2;
+        }
+
+        if('xval' in evt) xvalArray = flat(subplots, evt.xval);
+        else xvalArray = p2c(xaArray, xpx);
+
+        if('yval' in evt) yvalArray = flat(subplots, evt.yval);
+        else yvalArray = p2c(yaArray, ypx);
+
+        if(!isNumeric(xvalArray[0]) || !isNumeric(yvalArray[0])) {
+            console.log('Plotly.Fx.hover failed', evt, gd);
+            return unhover(gd, evt);
+        }
+    }
+
+    // the pixel distance to beat as a matching point
+    // in 'x' or 'y' mode this resets for each trace
+    var distance = Infinity;
+
+    // find the closest point in each trace
+    // this is minimum dx and/or dy, depending on mode
+    // and the pixel position for the label (labelXpx, labelYpx)
+    for(curvenum = 0; curvenum<searchData.length; curvenum++) {
+        cd = searchData[curvenum];
+
+        // filter out invisible or broken data
+        if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue;
+
+        trace = cd[0].trace;
+        subploti = subplots.indexOf(trace.xaxis + trace.yaxis);
+
+        // within one trace mode can sometimes be overridden
+        mode = hovermode;
+
+        // container for new point, also used to pass info into module.hoverPoints
+        pointData = {
+            // trace properties
+            cd: cd,
+            trace: trace,
+            xa: xaArray[subploti],
+            ya: yaArray[subploti],
+            name: (gd.data.length>1 || trace.hoverinfo.indexOf('name')!==-1) ? trace.name : undefined,
+            // point properties - override all of these
+            index: false, // point index in trace - only used by plotly.js hoverdata consumers
+            distance: Math.min(distance, constants.MAXDIST), // pixel distance or pseudo-distance
+            color: Plotly.Color.defaultLine, // trace color
+            x0: undefined,
+            x1: undefined,
+            y0: undefined,
+            y1: undefined,
+            xLabelVal: undefined,
+            yLabelVal: undefined,
+            zLabelVal: undefined,
+            text: undefined
+        };
+
+        closedataPreviousLength = hoverData.length;
+
+        // for a highlighting array, figure out what
+        // we're searching for with this element
+        if(mode==='array') {
+            var selection = evt[curvenum];
+            if('pointNumber' in selection) {
+                pointData.index = selection.pointNumber;
+                mode = 'closest';
+            }
+            else {
+                mode = '';
+                if('xval' in selection) {
+                    xval = selection.xval;
+                    mode = 'x';
+                }
+                if('yval' in selection) {
+                    yval = selection.yval;
+                    mode = mode ? 'closest' : 'y';
+                }
+            }
+        }
+        else {
+            xval = xvalArray[subploti];
+            yval = yvalArray[subploti];
+        }
+
+        // Now find the points.
+        if(trace._module && trace._module.hoverPoints) {
+            var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode);
+            if(newPoints) {
+                var newPoint;
+                for(var newPointNum=0; newPointNum<newPoints.length; newPointNum++) {
+                    newPoint = newPoints[newPointNum];
+                    if(isNumeric(newPoint.x0) && isNumeric(newPoint.y0)) {
+                        hoverData.push(cleanPoint(newPoint, hovermode));
+                    }
+                }
+            }
+        }
+        else {
+            console.log('unrecognized trace type in hover', trace);
+        }
+
+        // in closest mode, remove any existing (farther) points
+        // and don't look any farther than this latest point (or points, if boxes)
+        if(hovermode==='closest' && hoverData.length > closedataPreviousLength) {
+            hoverData.splice(0, closedataPreviousLength);
+            distance = hoverData[0].distance;
+        }
+
+    }
+
+    // nothing left: remove all labels and quit
+    if(hoverData.length===0) return unhover(gd,evt);
+
+    // if there's more than one horz bar trace,
+    // rotate the labels so they don't overlap
+    var rotateLabels = hovermode==='y' && searchData.length>1;
+
+    hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; });
+
+    var labelOpts = {
+        hovermode: hovermode,
+        rotateLabels: rotateLabels,
+        bgColor: Plotly.Color.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor),
+        container: fullLayout._hoverlayer,
+        outerContainer: fullLayout._paperdiv
+    };
+    var hoverLabels = createHoverText(hoverData, labelOpts);
+
+    hoverAvoidOverlaps(hoverData, rotateLabels ? xaArray[0] : yaArray[0]);
+
+    alignHoverText(hoverLabels, rotateLabels);
+
+    // lastly, emit custom hover/unhover events
+    var oldhoverdata = gd._hoverdata,
+        newhoverdata = [];
+
+    // pull out just the data that's useful to
+    // other people and send it to the event
+    for(itemnum = 0; itemnum<hoverData.length; itemnum++) {
+        var pt = hoverData[itemnum];
+        var out = {
+            data: pt.trace._input,
+            fullData: pt.trace,
+            curveNumber: pt.trace.index,
+            pointNumber: pt.index,
+            x: pt.xVal,
+            y: pt.yVal,
+            xaxis: pt.xa,
+            yaxis: pt.ya
+        };
+        if(pt.zLabelVal!==undefined) out.z = pt.zLabelVal;
+        newhoverdata.push(out);
+    }
+    gd._hoverdata = newhoverdata;
+
+    if(!hoverChanged(gd, evt, oldhoverdata)) return;
+
+    /* Emit the custom hover handler. Bind this like:
+     *  gd.on('hover.plotly', function(extras) {
+     *      // do something with extras.data
+     *  });
+     */
+    if(oldhoverdata) {
+        gd.emit('plotly_unhover', { points: oldhoverdata });
+    }
+    gd.emit('plotly_hover', {
+        points: gd._hoverdata,
+        xaxes: xaArray,
+        yaxes: yaArray,
+        xvals: xvalArray,
+        yvals: yvalArray
+    });
+}
+
+fx.getDistanceFunction = function(mode, dx, dy, dxy) {
+    if(mode==='closest') return dxy || quadrature(dx, dy);
+    return mode==='x' ? dx : dy;
+};
+
+fx.getClosest = function(cd, distfn, pointData) {
+    // do we already have a point number? (array mode only)
+    if(pointData.index!==false) {
+        if(pointData.index>=0 && pointData.index<cd.length) {
+            pointData.distance = 0;
+        }
+        else pointData.index = false;
+    }
+    else {
+        // apply the distance function to each data point
+        // this is the longest loop... if this bogs down, we may need
+        // to create pre-sorted data (by x or y), not sure how to
+        // do this for 'closest'
+        for(var i=0; i<cd.length; i++) {
+            var newDistance = distfn(cd[i]);
+            if(newDistance < pointData.distance) {
+                pointData.index = i;
+                pointData.distance = newDistance;
+            }
+        }
+    }
+    return pointData;
+};
+
+function cleanPoint(d, hovermode) {
+    d.posref = hovermode==='y' ? (d.x0+d.x1)/2 : (d.y0+d.y1)/2;
+
+    // then constrain all the positions to be on the plot
+    d.x0 = Plotly.Lib.constrain(d.x0, 0, d.xa._length);
+    d.x1 = Plotly.Lib.constrain(d.x1, 0, d.xa._length);
+    d.y0 = Plotly.Lib.constrain(d.y0, 0, d.ya._length);
+    d.y1 = Plotly.Lib.constrain(d.y1, 0, d.ya._length);
+
+    // and convert the x and y label values into objects
+    // formatted as text, with font info
+    var logOffScale;
+    if(d.xLabelVal!==undefined) {
+        logOffScale = (d.xa.type==='log' && d.xLabelVal<=0);
+        var xLabelObj = Plotly.Axes.tickText(d.xa,
+                d.xa.c2l(logOffScale ? -d.xLabelVal : d.xLabelVal), 'hover');
+        if(logOffScale) {
+            if(d.xLabelVal===0) d.xLabel = '0';
+            else d.xLabel = '-' + xLabelObj.text;
+        }
+        else d.xLabel = xLabelObj.text;
+        d.xVal = d.xa.c2d(d.xLabelVal);
+    }
+
+    if(d.yLabelVal!==undefined) {
+        logOffScale = (d.ya.type==='log' && d.yLabelVal<=0);
+        var yLabelObj = Plotly.Axes.tickText(d.ya,
+                d.ya.c2l(logOffScale ? -d.yLabelVal : d.yLabelVal), 'hover');
+        if(logOffScale) {
+            if(d.yLabelVal===0) d.yLabel = '0';
+            else d.yLabel = '-' + yLabelObj.text;
+        }
+        else d.yLabel = yLabelObj.text;
+        d.yVal = d.ya.c2d(d.yLabelVal);
+    }
+
+    if(d.zLabelVal!==undefined) d.zLabel = String(d.zLabelVal);
+
+    // for box means and error bars, add the range to the label
+    if(d.xerr!==undefined) {
+        var xeText = Plotly.Axes.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text;
+        if(d.xerrneg!==undefined) {
+            d.xLabel += ' +' + xeText + ' / -' +
+                Plotly.Axes.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text;
+        }
+        else d.xLabel += ' &plusmn; ' + xeText;
+
+        // small distance penalty for error bars, so that if there are
+        // traces with errors and some without, the error bar label will
+        // hoist up to the point
+        if(hovermode==='x') d.distance += 1;
+    }
+    if(d.yerr!==undefined) {
+        var yeText = Plotly.Axes.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text;
+        if(d.yerrneg!==undefined) {
+            d.yLabel += ' +' + yeText + ' / -' +
+                Plotly.Axes.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text;
+        }
+        else d.yLabel += ' &plusmn; ' + yeText;
+
+        if(hovermode==='y') d.distance += 1;
+    }
+
+    var infomode = d.trace.hoverinfo;
+    if(infomode!=='all') {
+        infomode = infomode.split('+');
+        if(infomode.indexOf('x')===-1) d.xLabel = undefined;
+        if(infomode.indexOf('y')===-1) d.yLabel = undefined;
+        if(infomode.indexOf('z')===-1) d.zLabel = undefined;
+        if(infomode.indexOf('text')===-1) d.text = undefined;
+        if(infomode.indexOf('name')===-1) d.name = undefined;
+    }
+    return d;
+}
+
+fx.loneHover = function(hoverItem, opts) {
+    // draw a single hover item in a pre-existing svg container somewhere
+    // hoverItem should have keys:
+    //    - x and y (or x0, x1, y0, and y1):
+    //      the pixel position to mark, relative to opts.container
+    //    - xLabel, yLabel, zLabel, text, and name:
+    //      info to go in the label
+    //    - color:
+    //      the background color for the label. text & outline color will
+    //      be chosen black or white to contrast with this
+    // opts should have keys:
+    //    - bgColor:
+    //      the background color this is against, used if the trace is
+    //      non-opaque, and for the name, which goes outside the box
+    //    - container:
+    //      a dom <svg> element - must be big enough to contain the whole
+    //      hover label
+    var pointData = {
+        color: hoverItem.color || Plotly.Color.defaultLine,
+        x0: hoverItem.x0 || hoverItem.x || 0,
+        x1: hoverItem.x1 || hoverItem.x || 0,
+        y0: hoverItem.y0 || hoverItem.y || 0,
+        y1: hoverItem.y1 || hoverItem.y || 0,
+        xLabel: hoverItem.xLabel,
+        yLabel: hoverItem.yLabel,
+        zLabel: hoverItem.zLabel,
+        text: hoverItem.text,
+        name: hoverItem.name,
+        idealAlign: hoverItem.idealAlign,
+
+        // filler to make createHoverText happy
+        trace: {
+            index: 0,
+            hoverinfo: ''
+        },
+        xa: {_offset: 0},
+        ya: {_offset: 0},
+        index: 0
+    };
+
+    var container3 = d3.select(opts.container),
+        outerContainer3 = opts.outerContainer ?
+            d3.select(opts.outerContainer) : container3;
+
+    var fullOpts = {
+        hovermode: 'closest',
+        rotateLabels: false,
+        bgColor: opts.bgColor || Plotly.Color.background,
+        container: container3,
+        outerContainer: outerContainer3
+    };
+
+    var hoverLabel = createHoverText([pointData], fullOpts);
+    alignHoverText(hoverLabel, fullOpts.rotateLabels);
+
+    return hoverLabel.node();
+};
+
+fx.loneUnhover = function(containerOrSelection) {
+    var selection = containerOrSelection instanceof d3.selection ?
+            containerOrSelection :
+            d3.select(containerOrSelection);
+
+    selection.selectAll('g.hovertext').remove();
+};
+
+function createHoverText(hoverData, opts) {
+    var hovermode = opts.hovermode,
+        rotateLabels = opts.rotateLabels,
+        bgColor = opts.bgColor,
+        container = opts.container,
+        outerContainer = opts.outerContainer,
+
+        c0 = hoverData[0],
+        xa = c0.xa,
+        ya = c0.ya,
+        commonAttr = hovermode==='y' ? 'yLabel' : 'xLabel',
+        t0 = c0[commonAttr],
+        t00 = (String(t0)||'').split(' ')[0],
+        outerContainerBB = outerContainer.node().getBoundingClientRect(),
+        outerTop = outerContainerBB.top,
+        outerWidth = outerContainerBB.width,
+        outerHeight = outerContainerBB.height;
+
+    // show the common label, if any, on the axis
+    // never show a common label in array mode,
+    // even if sometimes there could be one
+    var showCommonLabel = c0.distance<=constants.MAXDIST &&
+                          (hovermode==='x' || hovermode==='y');
+
+    // all hover traces hoverinfo must contain the hovermode
+    // to have common labels
+    var i, traceHoverinfo;
+    for(i = 0; i < hoverData.length; i++) {
+        traceHoverinfo = hoverData[i].trace.hoverinfo;
+        var parts = traceHoverinfo.split('+');
+        if(parts.indexOf('all') === -1 &&
+            parts.indexOf(hovermode) === -1) {
+            showCommonLabel = false;
+            break;
+        }
+    }
+
+    var commonLabel = container.selectAll('g.axistext')
+        .data(showCommonLabel ? [0] : []);
+    commonLabel.enter().append('g')
+        .classed('axistext', true);
+    commonLabel.exit().remove();
+
+    commonLabel.each(function() {
+        var label = d3.select(this),
+            lpath = label.selectAll('path').data([0]),
+            ltext = label.selectAll('text').data([0]);
+
+        lpath.enter().append('path')
+            .style({fill: Plotly.Color.defaultLine, 'stroke-width': '1px', stroke: Plotly.Color.background});
+        ltext.enter().append('text')
+            .call(Plotly.Drawing.font, HOVERFONT, HOVERFONTSIZE, Plotly.Color.background)
+            // prohibit tex interpretation until we can handle
+            // tex and regular text together
+            .attr('data-notex',1);
+
+        ltext.text(t0)
+            .call(Plotly.util.convertToTspans)
+            .call(Plotly.Drawing.setPosition, 0, 0)
+          .selectAll('tspan.line')
+            .call(Plotly.Drawing.setPosition, 0, 0);
+        label.attr('transform','');
+
+        var tbb = ltext.node().getBoundingClientRect();
+        if(hovermode==='x') {
+            ltext.attr('text-anchor','middle')
+                .call(Plotly.Drawing.setPosition,0,(xa.side==='top' ?
+                    (outerTop-tbb.bottom-HOVERARROWSIZE-HOVERTEXTPAD) :
+                    (outerTop-tbb.top+HOVERARROWSIZE+HOVERTEXTPAD)))
+                .selectAll('tspan.line')
+                    .attr({
+                        x: ltext.attr('x'),
+                        y: ltext.attr('y')
+                    });
+
+            var topsign = xa.side==='top' ? '-' : '';
+            lpath.attr('d','M0,0'+
+                'L'+HOVERARROWSIZE+','+topsign+HOVERARROWSIZE+
+                'H'+(HOVERTEXTPAD+tbb.width/2)+
+                'v'+topsign+(HOVERTEXTPAD*2+tbb.height)+
+                'H-'+(HOVERTEXTPAD+tbb.width/2)+
+                'V'+topsign+HOVERARROWSIZE+'H-'+HOVERARROWSIZE+'Z');
+
+            label.attr('transform','translate(' +
+                (xa._offset+(c0.x0+c0.x1)/2)+',' +
+                (ya._offset + (xa.side==='top' ? 0 : ya._length))+')');
+        }
+        else {
+            ltext.attr('text-anchor',ya.side==='right' ? 'start' : 'end')
+                .call(Plotly.Drawing.setPosition,
+                    (ya.side==='right' ? 1 : -1)*(HOVERTEXTPAD+HOVERARROWSIZE),
+                    outerTop-tbb.top-tbb.height/2)
+                .selectAll('tspan.line')
+                    .attr({
+                        x: ltext.attr('x'),
+                        y: ltext.attr('y')
+                    });
+
+            var leftsign = ya.side==='right' ? '' : '-';
+            lpath.attr('d','M0,0'+
+                'L'+leftsign+HOVERARROWSIZE+','+HOVERARROWSIZE+
+                'V'+(HOVERTEXTPAD+tbb.height/2)+
+                'h'+leftsign+(HOVERTEXTPAD*2+tbb.width)+
+                'V-'+(HOVERTEXTPAD+tbb.height/2)+
+                'H'+leftsign+HOVERARROWSIZE+'V-'+HOVERARROWSIZE+'Z');
+
+            label.attr('transform','translate(' +
+                (xa._offset+(ya.side==='right' ? xa._length : 0))+',' +
+                (ya._offset+(c0.y0+c0.y1)/2)+')');
+        }
+        // remove the "close but not quite" points
+        // because of error bars, only take up to a space
+        hoverData = hoverData.filter(function(d) {
+            return (d.zLabelVal!==undefined) ||
+                (d[commonAttr]||'').split(' ')[0]===t00;
+        });
+    });
+
+    // show all the individual labels
+
+    // first create the objects
+    var hoverLabels = container.selectAll('g.hovertext')
+        .data(hoverData,function(d) {
+            return [d.trace.index,d.index,d.x0,d.y0,d.name,d.attr||''].join(',');
+        });
+    hoverLabels.enter().append('g')
+        .classed('hovertext',true)
+        .each(function() {
+            var g = d3.select(this);
+            // trace name label (rect and text.name)
+            g.append('rect')
+                .call(Plotly.Color.fill,
+                    Plotly.Color.addOpacity(bgColor, 0.8));
+            g.append('text').classed('name',true)
+                .call(Plotly.Drawing.font,HOVERFONT,HOVERFONTSIZE);
+            // trace data label (path and text.nums)
+            g.append('path')
+                .style('stroke-width','1px');
+            g.append('text').classed('nums',true)
+                .call(Plotly.Drawing.font,HOVERFONT,HOVERFONTSIZE);
+        });
+    hoverLabels.exit().remove();
+
+    // then put the text in, position the pointer to the data,
+    // and figure out sizes
+    hoverLabels.each(function(d) {
+        var g = d3.select(this).attr('transform', ''),
+            name = '',
+            text = '',
+            // combine possible non-opaque trace color with bgColor
+            baseColor = Plotly.Color.opacity(d.color) ?
+                d.color : Plotly.Color.defaultLine,
+            traceColor = Plotly.Color.combine(baseColor, bgColor),
+
+            // find a contrasting color for border and text
+            contrastColor = tinycolor(traceColor).getBrightness()>128 ?
+                '#000' : Plotly.Color.background;
+
+
+        if(d.name && d.zLabelVal===undefined) {
+            // strip out any html elements from d.name (if it exists at all)
+            // Note that this isn't an XSS vector, only because it never gets
+            // attached to the DOM
+            var tmp = document.createElement('p');
+            tmp.innerHTML = d.name;
+            name = tmp.textContent||'';
+
+            if(name.length>15) name = name.substr(0,12)+'...';
+        }
+
+        if(d.zLabel!==undefined) {
+            if(d.xLabel!==undefined) text += 'x: ' + d.xLabel + '<br>';
+            if(d.yLabel!==undefined) text += 'y: ' + d.yLabel + '<br>';
+            text += (text ? 'z: ' : '') + d.zLabel;
+        }
+        else if(showCommonLabel && d[hovermode+'Label']===t0) {
+            text = d[(hovermode==='x' ? 'y' : 'x') + 'Label'] || '';
+        }
+        else if(d.xLabel===undefined) {
+            if(d.yLabel!==undefined) text = d.yLabel;
+        }
+        else if(d.yLabel===undefined) text = d.xLabel;
+        else text = '('+d.xLabel+', '+d.yLabel+')';
+
+        if(d.text && !Array.isArray(d.text)) text += (text ? '<br>' : '') + d.text;
+
+        // if 'text' is empty at this point,
+        // put 'name' in main label and don't show secondary label
+        if(text === '') {
+            // if 'name' is also empty, remove entire label
+            if(name === '') g.remove();
+            text = name;
+        }
+
+        // main label
+        var tx = g.select('text.nums')
+            .style('fill',contrastColor)
+            .call(Plotly.Drawing.setPosition,0,0)
+            .text(text)
+            .attr('data-notex',1)
+            .call(Plotly.util.convertToTspans);
+        tx.selectAll('tspan.line')
+            .call(Plotly.Drawing.setPosition,0,0);
+
+        var tx2 = g.select('text.name'),
+            tx2width = 0;
+
+        // secondary label for non-empty 'name'
+        if(name && name!==text) {
+            tx2.style('fill',traceColor)
+                .text(name)
+                .call(Plotly.Drawing.setPosition,0,0)
+                .attr('data-notex',1)
+                .call(Plotly.util.convertToTspans);
+            tx2.selectAll('tspan.line')
+                .call(Plotly.Drawing.setPosition,0,0);
+            tx2width = tx2.node().getBoundingClientRect().width+2*HOVERTEXTPAD;
+        }
+        else {
+            tx2.remove();
+            g.select('rect').remove();
+        }
+
+        g.select('path')
+            .style({
+                fill: traceColor,
+                stroke: contrastColor
+            });
+        var tbb = tx.node().getBoundingClientRect(),
+            htx = xa._offset+(d.x0+d.x1)/2,
+            hty = ya._offset+(d.y0+d.y1)/2,
+            dx = Math.abs(d.x1-d.x0),
+            dy = Math.abs(d.y1-d.y0),
+            txTotalWidth = tbb.width+HOVERARROWSIZE+HOVERTEXTPAD+tx2width,
+            anchorStartOK,
+            anchorEndOK;
+
+        d.ty0 = outerTop-tbb.top;
+        d.bx = tbb.width+2*HOVERTEXTPAD;
+        d.by = tbb.height+2*HOVERTEXTPAD;
+        d.anchor = 'start';
+        d.txwidth = tbb.width;
+        d.tx2width = tx2width;
+        d.offset = 0;
+
+        if(rotateLabels) {
+            d.pos = htx;
+            anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight;
+            anchorEndOK = hty - dy / 2 - txTotalWidth >= 0;
+            if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) {
+                hty -= dy / 2;
+                d.anchor = 'end';
+            } else if(anchorStartOK) {
+                hty += dy / 2;
+                d.anchor = 'start';
+            } else d.anchor = 'middle';
+        }
+        else {
+            d.pos = hty;
+            anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth;
+            anchorEndOK = htx - dx / 2 - txTotalWidth >= 0;
+            if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) {
+                htx -= dx / 2;
+                d.anchor = 'end';
+            } else if(anchorStartOK) {
+                htx += dx / 2;
+                d.anchor = 'start';
+            } else d.anchor = 'middle';
+        }
+
+        tx.attr('text-anchor',d.anchor);
+        if(tx2width) tx2.attr('text-anchor',d.anchor);
+        g.attr('transform','translate('+htx+','+hty+')'+
+            (rotateLabels ? 'rotate('+YANGLE+')' : ''));
+    });
+
+    return hoverLabels;
+}
+
+// Make groups of touching points, and within each group
+// move each point so that no labels overlap, but the average
+// label position is the same as it was before moving. Indicentally,
+// this is equivalent to saying all the labels are on equal linear
+// springs about their initial position. Initially, each point is
+// its own group, but as we find overlaps we will clump the points.
+//
+// Also, there are hard constraints at the edges of the graphs,
+// that push all groups to the middle so they are visible. I don't
+// know what happens if the group spans all the way from one edge to
+// the other, though it hardly matters - there's just too much
+// information then.
+function hoverAvoidOverlaps(hoverData, ax) {
+    var nummoves = 0,
+        pmin = ax._offset,
+        pmax = ax._offset+ax._length,
+
+        // make groups of touching points
+        pointgroups = hoverData
+            .map(function(d,i) {
+                return [{
+                    i: i,
+                    dp: 0,
+                    pos: d.pos,
+                    posref: d.posref,
+                    size: d.by*(ax._id.charAt(0)==='x' ? YFACTOR : 1)/2
+                }];
+            })
+            .sort(function(a,b) { return a[0].posref-b[0].posref; }),
+        donepositioning,
+        topOverlap,
+        bottomOverlap,
+        i, j,
+        pti,
+        sumdp;
+
+    function constrainGroup(grp) {
+        var minPt = grp[0],
+            maxPt = grp[grp.length-1];
+
+        // overlap with the top - positive vals are overlaps
+        topOverlap = pmin-minPt.pos-minPt.dp+minPt.size;
+
+        // overlap with the bottom - positive vals are overlaps
+        bottomOverlap = maxPt.pos+maxPt.dp+maxPt.size-pmax;
+
+        // check for min overlap first, so that we always
+        // see the largest labels
+        // allow for .01px overlap, so we don't get an
+        // infinite loop from rounding errors
+        if(topOverlap>0.01) {
+            for(j=grp.length-1; j>=0; j--) grp[j].dp += topOverlap;
+            donepositioning = false;
+        }
+        if(bottomOverlap<0.01) return;
+        if(topOverlap<-0.01) {
+            // make sure we're not pushing back and forth
+            for(j=grp.length-1; j>=0; j--) grp[j].dp -= bottomOverlap;
+            donepositioning = false;
+        }
+        if(!donepositioning) return;
+
+        // no room to fix positioning, delete off-screen points
+
+        // first see how many points we need to delete
+        var deleteCount = 0;
+        for(i=0; i<grp.length; i++) {
+            pti = grp[i];
+            if(pti.pos+pti.dp+pti.size>pmax) deleteCount++;
+        }
+
+        // start by deleting points whose data is off screen
+        for(i=grp.length-1; i>=0; i--) {
+            if(deleteCount<=0) break;
+            pti = grp[i];
+
+            // pos has already been constrained to [pmin,pmax]
+            // so look for points close to that to delete
+            if(pti.pos>pmax-1) {
+                pti.del = true;
+                deleteCount--;
+            }
+        }
+        for(i=0; i<grp.length; i++) {
+            if(deleteCount<=0) break;
+            pti = grp[i];
+
+            // pos has already been constrained to [pmin,pmax]
+            // so look for points close to that to delete
+            if(pti.pos<pmin+1) {
+                pti.del = true;
+                deleteCount--;
+
+                // shift the whole group minus into this new space
+                bottomOverlap = pti.size*2;
+                for(j=grp.length-1; j>=0; j--) grp[j].dp -= bottomOverlap;
+            }
+        }
+        // then delete points that go off the bottom
+        for(i=grp.length-1; i>=0; i--) {
+            if(deleteCount<=0) break;
+            pti = grp[i];
+            if(pti.pos+pti.dp+pti.size>pmax) {
+                pti.del = true;
+                deleteCount--;
+            }
+        }
+    }
+
+    // loop through groups, combining them if they overlap,
+    // until nothing moves
+    while(!donepositioning && nummoves<=hoverData.length) {
+        // to avoid infinite loops, don't move more times
+        // than there are traces
+        nummoves++;
+
+        // assume nothing will move in this iteration,
+        // reverse this if it does
+        donepositioning = true;
+        i = 0;
+        while(i<pointgroups.length-1) {
+                // the higher (g0) and lower (g1) point group
+            var g0 = pointgroups[i],
+                g1 = pointgroups[i+1],
+
+                // the lowest point in the higher group (p0)
+                // the highest point in the lower group (p1)
+                p0 = g0[g0.length-1],
+                p1 = g1[0];
+            topOverlap = p0.pos+p0.dp+p0.size-p1.pos-p1.dp+p1.size;
+            if(topOverlap>0.01) {
+                // push the new point(s) added to this group out of the way
+                for(j=g1.length-1; j>=0; j--) g1[j].dp += topOverlap;
+
+                // add them to the group
+                g0.push.apply(g0,g1);
+                pointgroups.splice(i+1,1);
+
+                // adjust for minimum average movement
+                sumdp = 0;
+                for(j=g0.length-1; j>=0; j--) sumdp += g0[j].dp;
+                bottomOverlap = sumdp/g0.length;
+                for(j=g0.length-1; j>=0; j--) g0[j].dp -= bottomOverlap;
+                donepositioning = false;
+            }
+            else i++;
+        }
+
+        // check if we're going off the plot on either side and fix
+        pointgroups.forEach(constrainGroup);
+    }
+
+    // now put these offsets into hoverData
+    for(i=pointgroups.length-1; i>=0; i--) {
+        var grp = pointgroups[i];
+        for(j=grp.length-1; j>=0; j--) {
+            var pt = grp[j],
+                hoverPt = hoverData[pt.i];
+            hoverPt.offset = pt.dp;
+            hoverPt.del = pt.del;
+        }
+    }
+}
+
+function alignHoverText(hoverLabels, rotateLabels) {
+    // finally set the text positioning relative to the data and draw the
+    // box around it
+    hoverLabels.each(function(d) {
+        var g = d3.select(this);
+        if(d.del) {
+            g.remove();
+            return;
+        }
+        var horzSign = d.anchor==='end' ? -1 : 1,
+            tx = g.select('text.nums'),
+            alignShift = {start: 1, end: -1, middle: 0}[d.anchor],
+            txx = alignShift*(HOVERARROWSIZE+HOVERTEXTPAD),
+            tx2x = txx+alignShift*(d.txwidth+HOVERTEXTPAD),
+            offsetX = 0,
+            offsetY = d.offset;
+        if(d.anchor==='middle') {
+            txx-=d.tx2width/2;
+            tx2x-=d.tx2width/2;
+        }
+        if(rotateLabels) {
+            offsetY *= -YSHIFTY;
+            offsetX = d.offset*YSHIFTX;
+        }
+
+        g.select('path').attr('d',d.anchor==='middle' ?
+            // middle aligned: rect centered on data
+            ('M-'+(d.bx/2)+',-'+(d.by/2)+'h'+d.bx+'v'+d.by+'h-'+d.bx+'Z') :
+            // left or right aligned: side rect with arrow to data
+            ('M0,0L'+(horzSign*HOVERARROWSIZE+offsetX)+','+(HOVERARROWSIZE+offsetY)+
+                'v'+(d.by/2-HOVERARROWSIZE)+
+                'h'+(horzSign*d.bx)+
+                'v-'+d.by+
+                'H'+(horzSign*HOVERARROWSIZE+offsetX)+
+                'V'+(offsetY-HOVERARROWSIZE)+
+                'Z'));
+
+        tx.call(Plotly.Drawing.setPosition,
+                txx+offsetX, offsetY+d.ty0-d.by/2+HOVERTEXTPAD)
+            .selectAll('tspan.line')
+                .attr({
+                    x: tx.attr('x'),
+                    y: tx.attr('y')
+                });
+
+        if(d.tx2width) {
+            g.select('text.name, text.name tspan.line')
+                .call(Plotly.Drawing.setPosition,
+                    tx2x+alignShift*HOVERTEXTPAD+offsetX,
+                    offsetY+d.ty0-d.by/2+HOVERTEXTPAD);
+            g.select('rect')
+                .call(Plotly.Drawing.setRect,
+                    tx2x+(alignShift-1)*d.tx2width/2+offsetX,
+                    offsetY-d.by/2-1,
+                    d.tx2width, d.by+2);
+        }
+    });
+}
+
+function hoverChanged(gd, evt, oldhoverdata) {
+    // don't emit any events if nothing changed or
+    // if fx.hover was called manually
+    if(!evt.target) return false;
+    if(!oldhoverdata || oldhoverdata.length!==gd._hoverdata.length) return true;
+
+    for(var i = oldhoverdata.length-1; i>=0; i--) {
+        var oldPt = oldhoverdata[i],
+            newPt = gd._hoverdata[i];
+        if(oldPt.curveNumber!==newPt.curveNumber ||
+                String(oldPt.pointNumber)!==String(newPt.pointNumber)) {
+            return true;
+        }
+    }
+    return false;
+}
+
+// remove hover effects on mouse out, and emit unhover event
+function unhover(gd, evt) {
+    var fullLayout = gd._fullLayout;
+    if(!evt) evt = {};
+    if(evt.target &&
+       Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
+        return;
+    }
+    fullLayout._hoverlayer.selectAll('g').remove();
+    if(evt.target && gd._hoverdata) {
+        gd.emit('plotly_unhover', {points: gd._hoverdata});
+    }
+    gd._hoverdata = undefined;
+}
+
+// on click
+fx.click = function(gd,evt) {
+    if(gd._hoverdata && evt && evt.target) {
+        gd.emit('plotly_click', {points: gd._hoverdata});
+        // why do we get a double event without this???
+        if(evt.stopImmediatePropagation) evt.stopImmediatePropagation();
+    }
+};
+
+
+// ----------------------------------------------------
+// Axis dragging functions
+// ----------------------------------------------------
+
+function getDragCursor(nsew, dragmode) {
+    if(!nsew) return 'pointer';
+    if(nsew === 'nsew') {
+        if(dragmode === 'pan') return 'move';
+        return 'crosshair';
+    }
+    return nsew.toLowerCase() + '-resize';
+}
+
+// flag for showing "doubleclick to zoom out" only at the beginning
+var SHOWZOOMOUTTIP = true;
+
+// dragBox: create an element to drag one or more axis ends
+// inputs:
+//      plotinfo - which subplot are we making dragboxes on?
+//      x,y,w,h - left, top, width, height of the box
+//      ns - how does this drag the vertical axis?
+//          'n' - top only
+//          's' - bottom only
+//          'ns' - top and bottom together, difference unchanged
+//      ew - same for horizontal axis
+function dragBox(gd, plotinfo, x, y, w, h, ns, ew) {
+    // mouseDown stores ms of first mousedown event in the last
+    // DBLCLICKDELAY ms on the drag bars
+    // numClicks stores how many mousedowns have been seen
+    // within DBLCLICKDELAY so we can check for click or doubleclick events
+    // dragged stores whether a drag has occurred, so we don't have to
+    // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px
+    var fullLayout = gd._fullLayout,
+        // if we're dragging two axes at once, also drag overlays
+        subplots = [plotinfo].concat((ns && ew) ? plotinfo.overlays : []),
+        xa = [plotinfo.x()],
+        ya = [plotinfo.y()],
+        pw = xa[0]._length,
+        ph = ya[0]._length,
+        MINDRAG = constants.MINDRAG,
+        MINZOOM = constants.MINZOOM,
+        i,
+        subplotXa,
+        subplotYa;
+
+    for(i = 1; i < subplots.length; i++) {
+        subplotXa = subplots[i].x();
+        subplotYa = subplots[i].y();
+        if(xa.indexOf(subplotXa) === -1) xa.push(subplotXa);
+        if(ya.indexOf(subplotYa) === -1) ya.push(subplotYa);
+    }
+
+    function isDirectionActive(axList, activeVal) {
+        for(i = 0; i < axList.length; i++) {
+            if(!axList[i].fixedrange) return activeVal;
+        }
+        return '';
+    }
+
+    var allaxes = xa.concat(ya),
+        xActive = isDirectionActive(xa, ew),
+        yActive = isDirectionActive(ya, ns),
+        cursor = getDragCursor(yActive + xActive, fullLayout.dragmode),
+        dragClass = ns + ew + 'drag';
+
+    var dragger3 = plotinfo.draglayer.selectAll('.' + dragClass).data([0]);
+    dragger3.enter().append('rect')
+        .classed('drag', true)
+        .classed(dragClass, true)
+        .style({fill: 'transparent', 'stroke-width': 0})
+        .attr('data-subplot', plotinfo.id);
+    dragger3.call(Plotly.Drawing.setRect, x, y, w, h)
+        .call(fx.setCursor,cursor);
+    var dragger = dragger3.node();
+
+    // still need to make the element if the axes are disabled
+    // but nuke its events (except for maindrag which needs them for hover)
+    // and stop there
+    if(!yActive && !xActive) {
+        dragger.onmousedown = null;
+        dragger.style.pointerEvents = (ns + ew === 'nsew') ? 'all' : 'none';
+        return dragger;
+    }
+
+    function forceNumbers(axRange) {
+        axRange[0] = Number(axRange[0]);
+        axRange[1] = Number(axRange[1]);
+    }
+
+    var dragOptions = {
+        element: dragger,
+        gd: gd,
+        plotinfo: plotinfo,
+        xaxes: xa,
+        yaxes: ya,
+        doubleclick: doubleClick,
+        prepFn: function(e, startX, startY) {
+            var dragModeNow = gd._fullLayout.dragmode;
+            if(ns + ew === 'nsew') {
+                // main dragger handles all drag modes, and changes
+                // to pan (or to zoom if it already is pan) on shift
+                if(e.shiftKey) {
+                    if(dragModeNow === 'pan') dragModeNow = 'zoom';
+                    else dragModeNow = 'pan';
+                }
+            }
+            // all other draggers just pan
+            else dragModeNow = 'pan';
+
+            if(dragModeNow === 'lasso') dragOptions.minDrag = 1;
+            else dragOptions.minDrag = undefined;
+
+            if(dragModeNow === 'zoom') {
+                dragOptions.moveFn = zoomMove;
+                dragOptions.doneFn = zoomDone;
+                zoomPrep(e, startX, startY);
+            }
+            else if(dragModeNow === 'pan') {
+                dragOptions.moveFn = plotDrag;
+                dragOptions.doneFn = dragDone;
+                clearSelect();
+            }
+            else if(dragModeNow === 'select' || dragModeNow === 'lasso') {
+                prepSelect(e, startX, startY, dragOptions, dragModeNow);
+            }
+        }
+    };
+
+    fx.dragElement(dragOptions);
+
+    var x0,
+        y0,
+        box,
+        lum,
+        path0,
+        dimmed,
+        zoomMode,
+        zb,
+        corners;
+
+    function zoomPrep(e, startX, startY) {
+        var dragBBox = dragger.getBoundingClientRect();
+        x0 = startX - dragBBox.left;
+        y0 = startY - dragBBox.top;
+        box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0};
+        lum = gd._hmpixcount ?
+            (gd._hmlumcount / gd._hmpixcount) :
+            tinycolor(gd._fullLayout.plot_bgcolor).getLuminance();
+        path0 = path0 = 'M0,0H'+pw+'V'+ph+'H0V0';
+        dimmed = false;
+        zoomMode = 'xy';
+
+        zb = plotinfo.plot.append('path')
+            .attr('class', 'zoombox')
+            .style({
+                'fill': lum>0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)',
+                'stroke-width': 0
+            })
+            .attr('d', path0 + 'Z');
+
+        corners = plotinfo.plot.append('path')
+            .attr('class', 'zoombox-corners')
+            .style({
+                fill: Plotly.Color.background,
+                stroke: Plotly.Color.defaultLine,
+                'stroke-width': 1,
+                opacity: 0
+            })
+            .attr('d','M0,0Z');
+
+        clearSelect();
+        for(i = 0; i < allaxes.length; i++) forceNumbers(allaxes[i].range);
+    }
+
+    function clearSelect() {
+        // until we get around to persistent selections, remove the outline
+        // here. The selection itself will be removed when the plot redraws
+        // at the end.
+        plotinfo.plot.selectAll('.select-outline').remove();
+    }
+
+    function zoomMove(dx0, dy0) {
+        var x1 = Math.max(0, Math.min(pw, dx0 + x0)),
+            y1 = Math.max(0, Math.min(ph, dy0 + y0)),
+            dx = Math.abs(x1 - x0),
+            dy = Math.abs(y1 - y0),
+            clen = Math.floor(Math.min(dy, dx, MINZOOM) / 2);
+
+        box.l = Math.min(x0, x1);
+        box.r = Math.max(x0, x1);
+        box.t = Math.min(y0, y1);
+        box.b = Math.max(y0, y1);
+
+        // look for small drags in one direction or the other,
+        // and only drag the other axis
+        if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) {
+            if(dx < MINDRAG) {
+                zoomMode = '';
+                box.r = box.l;
+                box.t = box.b;
+                corners.attr('d', 'M0,0Z');
+            }
+            else {
+                box.t = 0;
+                box.b = ph;
+                zoomMode = 'x';
+                corners.attr('d',
+                    'M' + (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) +
+                    'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' +
+                    (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) +
+                    'h3v' + (2 * MINZOOM + 1) + 'h-3Z');
+            }
+        }
+        else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) {
+            box.l = 0;
+            box.r = pw;
+            zoomMode = 'y';
+            corners.attr('d',
+                'M' + (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) +
+                'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' +
+                (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) +
+                'v3h' + (2 * MINZOOM + 1) + 'v-3Z');
+        }
+        else {
+            zoomMode = 'xy';
+            corners.attr('d',
+                'M'+(box.l-3.5)+','+(box.t-0.5+clen)+'h3v'+(-clen)+
+                        'h'+clen+'v-3h-'+(clen+3)+'ZM'+
+                    (box.r+3.5)+','+(box.t-0.5+clen)+'h-3v'+(-clen)+
+                        'h'+(-clen)+'v-3h'+(clen+3)+'ZM'+
+                    (box.r+3.5)+','+(box.b+0.5-clen)+'h-3v'+clen+
+                        'h'+(-clen)+'v3h'+(clen+3)+'ZM'+
+                    (box.l-3.5)+','+(box.b+0.5-clen)+'h3v'+clen+
+                        'h'+clen+'v3h-'+(clen+3)+'Z');
+        }
+        box.w = box.r - box.l;
+        box.h = box.b - box.t;
+
+        // Not sure about the addition of window.scrollX/Y...
+        // seems to work but doesn't seem robust.
+        zb.attr('d',
+            path0+'M'+(box.l)+','+(box.t)+'v'+(box.h)+
+            'h'+(box.w)+'v-'+(box.h)+'h-'+(box.w)+'Z');
+        if(!dimmed) {
+            zb.transition()
+                .style('fill', lum>0.2 ? 'rgba(0,0,0,0.4)' :
+                    'rgba(255,255,255,0.3)')
+                .duration(200);
+            corners.transition()
+                .style('opacity',1)
+                .duration(200);
+            dimmed = true;
+        }
+    }
+
+    function zoomAxRanges(axList, r0Fraction, r1Fraction) {
+        var i,
+            axi,
+            axRange;
+
+        for(i = 0; i < axList.length; i++) {
+            axi = axList[i];
+            if(axi.fixedrange) continue;
+
+            axRange = axi.range;
+            axi.range = [
+                axRange[0] + (axRange[1] - axRange[0]) * r0Fraction,
+                axRange[0] + (axRange[1] - axRange[0]) * r1Fraction
+            ];
+        }
+    }
+
+    function zoomDone(dragged, numClicks) {
+        if(Math.min(box.h, box.w) < MINDRAG * 2) {
+            if(numClicks === 2) doubleClick();
+            else pauseForDrag(gd);
+
+            return removeZoombox(gd);
+        }
+
+        if(zoomMode === 'xy' || zoomMode === 'x') zoomAxRanges(xa, box.l / pw, box.r / pw);
+        if(zoomMode === 'xy' || zoomMode === 'y') zoomAxRanges(ya, (ph - box.b) / ph, (ph - box.t) / ph);
+
+        removeZoombox(gd);
+        dragTail(zoomMode);
+
+        if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) {
+            Plotly.Lib.notifier('Double-click to<br>zoom back out','long');
+            SHOWZOOMOUTTIP = false;
+        }
+    }
+
+    function dragDone(dragged, numClicks) {
+        var singleEnd = (ns + ew).length === 1;
+        if(dragged) dragTail();
+        else if(numClicks === 2 && !singleEnd) doubleClick();
+        else if(numClicks === 1 && singleEnd) {
+            var ax = ns ? ya[0] : xa[0],
+                end = (ns==='s' || ew==='w') ? 0 : 1,
+                attrStr = ax._name + '.range[' + end + ']',
+                initialText = getEndText(ax, end),
+                hAlign = 'left',
+                vAlign = 'middle';
+
+            if(ax.fixedrange) return;
+
+            if(ns) {
+                vAlign = (ns === 'n') ? 'top' : 'bottom';
+                if(ax.side === 'right') hAlign = 'right';
+            }
+            else if(ew === 'e') hAlign = 'right';
+
+            dragger3
+                .call(Plotly.util.makeEditable, null, {
+                    immediate: true,
+                    background: fullLayout.paper_bgcolor,
+                    text: String(initialText),
+                    fill: ax.tickfont ? ax.tickfont.color : '#444',
+                    horizontalAlign: hAlign,
+                    verticalAlign: vAlign
+                })
+                .on('edit', function(text) {
+                    var v = ax.type==='category' ? ax.c2l(text) : ax.d2l(text);
+                    if(v !== undefined) {
+                        Plotly.relayout(gd, attrStr, v);
+                    }
+                });
+        }
+        else pauseForDrag(gd);
+    }
+
+    // scroll zoom, on all draggers except corners
+    var scrollViewBox = [0,0,pw,ph],
+        // wait a little after scrolling before redrawing
+        redrawTimer = null,
+        REDRAWDELAY = 300,
+        mainplot = plotinfo.mainplot ?
+            fullLayout._plots[plotinfo.mainplot] : plotinfo;
+
+    function zoomWheel(e) {
+        // deactivate mousewheel scrolling on embedded graphs
+        // devs can override this with layout._enablescrollzoom,
+        // but _ ensures this setting won't leave their page
+        if(!gd._context.scrollZoom && !fullLayout._enablescrollzoom) {
+            return;
+        }
+        var pc = gd.querySelector('.plotly');
+
+        // if the plot has scrollbars (more than a tiny excess)
+        // disable scrollzoom too.
+        if(pc.scrollHeight-pc.clientHeight>10 ||
+                pc.scrollWidth-pc.clientWidth>10) {
+            return;
+        }
+
+        clearTimeout(redrawTimer);
+
+        var wheelDelta = -e.deltaY;
+        if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10;
+        if(!isFinite(wheelDelta)) {
+            console.log('did not find wheel motion attributes', e);
+            return;
+        }
+
+        var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 100),
+            gbb = mainplot.draglayer.select('.nsewdrag')
+                .node().getBoundingClientRect(),
+            xfrac = (e.clientX - gbb.left) / gbb.width,
+            vbx0 = scrollViewBox[0] + scrollViewBox[2]*xfrac,
+            yfrac = (gbb.bottom - e.clientY)/gbb.height,
+            vby0 = scrollViewBox[1]+scrollViewBox[3]*(1-yfrac),
+            i;
+
+        function zoomWheelOneAxis(ax, centerFraction, zoom) {
+            if(ax.fixedrange) return;
+            forceNumbers(ax.range);
+            var axRange = ax.range,
+                v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction;
+            ax.range = [v0 + (axRange[0] - v0) * zoom, v0 + (axRange[1] - v0) * zoom];
+        }
+
+        if(ew) {
+            for(i = 0; i < xa.length; i++) zoomWheelOneAxis(xa[i], xfrac, zoom);
+            scrollViewBox[2] *= zoom;
+            scrollViewBox[0] = vbx0 - scrollViewBox[2] * xfrac;
+        }
+        if(ns) {
+            for(i = 0; i < ya.length; i++) zoomWheelOneAxis(ya[i], yfrac, zoom);
+            scrollViewBox[3] *= zoom;
+            scrollViewBox[1] = vby0 - scrollViewBox[3] * (1 - yfrac);
+        }
+
+        // viewbox redraw at first
+        updateViewBoxes(scrollViewBox);
+        ticksAndAnnotations(ns,ew);
+
+        // then replot after a delay to make sure
+        // no more scrolling is coming
+        redrawTimer = setTimeout(function() {
+            scrollViewBox = [0,0,pw,ph];
+            dragTail();
+        }, REDRAWDELAY);
+
+        return Plotly.Lib.pauseEvent(e);
+    }
+
+    // everything but the corners gets wheel zoom
+    if(ns.length*ew.length!==1) {
+        // still seems to be some confusion about onwheel vs onmousewheel...
+        if(dragger.onwheel!==undefined) dragger.onwheel = zoomWheel;
+        else if(dragger.onmousewheel!==undefined) dragger.onmousewheel = zoomWheel;
+    }
+
+    // plotDrag: move the plot in response to a drag
+    function plotDrag(dx,dy) {
+        function dragAxList(axList, pix) {
+            for(var i = 0; i < axList.length; i++) {
+                var axi = axList[i];
+                if(!axi.fixedrange) {
+                    axi.range = [axi._r[0] - pix / axi._m, axi._r[1] - pix / axi._m];
+                }
+            }
+        }
+
+        if(xActive === 'ew' || yActive === 'ns') {
+            if(xActive) dragAxList(xa, dx);
+            if(yActive) dragAxList(ya, dy);
+            updateViewBoxes([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]);
+            ticksAndAnnotations(yActive, xActive);
+            return;
+        }
+
+        // common transform for dragging one end of an axis
+        // d>0 is compressing scale (cursor is over the plot,
+        //  the axis end should move with the cursor)
+        // d<0 is expanding (cursor is off the plot, axis end moves
+        //  nonlinearly so you can expand far)
+        function dZoom(d) {
+            return 1-((d>=0) ? Math.min(d,0.9) :
+                1/(1/Math.max(d,-0.3)+3.222));
+        }
+
+        // dz: set a new value for one end (0 or 1) of an axis array ax,
+        // and return a pixel shift for that end for the viewbox
+        // based on pixel drag distance d
+        // TODO: this makes (generally non-fatal) errors when you get
+        // near floating point limits
+        function dz(ax, end, d) {
+            var otherEnd = 1 - end,
+                movedi = 0;
+            for(var i = 0; i < ax.length; i++) {
+                var axi = ax[i];
+                if(axi.fixedrange) continue;
+                movedi = i;
+                axi.range[end] = axi._r[otherEnd] +
+                    (axi._r[end] - axi._r[otherEnd]) / dZoom(d / axi._length);
+            }
+            return ax[movedi]._length * (ax[movedi]._r[end] - ax[movedi].range[end]) /
+                (ax[movedi]._r[end] - ax[movedi]._r[otherEnd]);
+        }
+
+        if(xActive === 'w') dx = dz(xa, 0, dx);
+        else if(xActive === 'e') dx = dz(xa, 1, -dx);
+        else if(!xActive) dx = 0;
+
+        if(yActive === 'n') dy = dz(ya, 1, dy);
+        else if(yActive === 's') dy = dz(ya, 0, -dy);
+        else if(!yActive) dy = 0;
+
+        updateViewBoxes([
+            (xActive === 'w') ? dx : 0,
+            (yActive === 'n') ? dy : 0,
+            pw - dx,
+            ph - dy
+        ]);
+        ticksAndAnnotations(yActive, xActive);
+    }
+
+    function ticksAndAnnotations(ns, ew) {
+        var activeAxIds = [],
+            i;
+
+        function pushActiveAxIds(axList) {
+            for(i = 0; i < axList.length; i++) {
+                if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id);
+            }
+        }
+
+        if(ew) pushActiveAxIds(xa);
+        if(ns) pushActiveAxIds(ya);
+
+        for(i = 0; i < activeAxIds.length; i++) {
+            Plotly.Axes.doTicks(gd, activeAxIds[i], true);
+        }
+
+        function redrawObjs(objArray, module) {
+            var obji;
+            for(i = 0; i < objArray.length; i++) {
+                obji = objArray[i];
+                if((ew && activeAxIds.indexOf(obji.xref) !== -1) ||
+                    (ns && activeAxIds.indexOf(obji.yref) !== -1)) {
+                    module.draw(gd, i);
+                }
+            }
+        }
+
+        redrawObjs(fullLayout.annotations || [], Plotly.Annotations);
+        redrawObjs(fullLayout.shapes || [], Plotly.Shapes);
+    }
+
+    function doubleClick() {
+        var doubleClickConfig = gd._context.doubleClick,
+            axList = (xActive ? xa : []).concat(yActive ? ya : []),
+            attrs = {};
+
+        var ax, i;
+
+        if(doubleClickConfig === 'autosize') {
+            for(i = 0; i < axList.length; i++) {
+                ax = axList[i];
+                if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true;
+            }
+        }
+        else if(doubleClickConfig === 'reset') {
+            for(i = 0; i < axList.length; i++) {
+                ax = axList[i];
+
+                if(!ax._rangeInitial) {
+                    attrs[ax._name + '.autorange'] = true;
+                }
+                else {
+                    attrs[ax._name + '.range'] = ax._rangeInitial.slice();
+                }
+            }
+        }
+        else if(doubleClickConfig === 'reset+autosize') {
+            for(i = 0; i < axList.length; i++) {
+                ax = axList[i];
+
+                if(ax.fixedrange) continue;
+                if(ax._rangeInitial === undefined ||
+                    ax.range[0] === ax._rangeInitial[0] &&
+                    ax.range[1] === ax._rangeInitial[1]
+                ) {
+                    attrs[ax._name + '.autorange'] = true;
+                }
+                else attrs[ax._name + '.range'] = ax._rangeInitial.slice();
+            }
+        }
+
+        gd.emit('plotly_doubleclick', null);
+        Plotly.relayout(gd, attrs);
+    }
+
+    // dragTail - finish a drag event with a redraw
+    function dragTail(zoommode) {
+        var attrs = {};
+        // revert to the previous axis settings, then apply the new ones
+        // through relayout - this lets relayout manage undo/redo
+        for(var i = 0; i < allaxes.length; i++) {
+            var axi = allaxes[i];
+            if(zoommode && zoommode.indexOf(axi._id.charAt(0))===-1) {
+                continue;
+            }
+            if(axi._r[0] !== axi.range[0]) attrs[axi._name+'.range[0]'] = axi.range[0];
+            if(axi._r[1] !== axi.range[1]) attrs[axi._name+'.range[1]'] = axi.range[1];
+
+            axi.range=axi._r.slice();
+        }
+
+        updateViewBoxes([0,0,pw,ph]);
+        Plotly.relayout(gd,attrs);
+    }
+
+    // updateViewBoxes - find all plot viewboxes that should be
+    // affected by this drag, and update them. look for all plots
+    // sharing an affected axis (including the one being dragged)
+    function updateViewBoxes(viewBox) {
+        var plotinfos = fullLayout._plots,
+            subplots = Object.keys(plotinfos),
+            i,
+            plotinfo2,
+            xa2,
+            ya2,
+            editX,
+            editY;
+
+        for(i = 0; i < subplots.length; i++) {
+            plotinfo2 = plotinfos[subplots[i]];
+            xa2 = plotinfo2.x();
+            ya2 = plotinfo2.y();
+            editX = ew && xa.indexOf(xa2)!==-1 && !xa2.fixedrange;
+            editY = ns && ya.indexOf(ya2)!==-1 && !ya2.fixedrange;
+
+            if(editX || editY) {
+                var newVB = [0,0,xa2._length,ya2._length];
+                if(editX) {
+                    newVB[0] = viewBox[0];
+                    newVB[2] = viewBox[2];
+                }
+                if(editY) {
+                    newVB[1] = viewBox[1];
+                    newVB[3] = viewBox[3];
+                }
+                plotinfo2.plot.attr('viewBox',newVB.join(' '));
+            }
+        }
+    }
+
+    return dragger;
+}
+
+function getEndText(ax, end) {
+    var initialVal = ax.range[end],
+        diff = Math.abs(initialVal - ax.range[1 - end]),
+        dig;
+
+    if(ax.type === 'date') {
+        return Plotly.Lib.ms2DateTime(initialVal, diff);
+    }
+    else if(ax.type==='log') {
+        dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3;
+        return d3.format('.' + dig + 'g')(Math.pow(10, initialVal));
+    }
+    else { // linear numeric (or category... but just show numbers here)
+        dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) -
+            Math.floor(Math.log(diff) / Math.LN10) + 4;
+        return d3.format('.'+String(dig)+'g')(initialVal);
+    }
+}
+
+function pauseForDrag(gd) {
+    // prevent more redraws until we know if a doubleclick
+    // has occurred
+    gd._dragging = true;
+    var deferredReplot = gd._replotPending;
+    gd._replotPending = false;
+
+    setTimeout(function() {
+        gd._replotPending = deferredReplot;
+        finishDrag(gd);
+    },
+        constants.DBLCLICKDELAY
+    );
+}
+
+function finishDrag(gd) {
+    gd._dragging = false;
+    if(gd._replotPending) Plotly.plot(gd);
+}
+
+function removeZoombox(gd) {
+    d3.select(gd)
+        .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners')
+        .remove();
+}
+
+// for automatic alignment on dragging, <1/3 means left align,
+// >2/3 means right, and between is center. Pick the right fraction
+// based on where you are, and return the fraction corresponding to
+// that position on the object
+fx.dragAlign = function(v, dv, v0, v1, anchor) {
+    var vmin = (v-v0)/(v1-v0),
+        vmax = vmin+dv/(v1-v0),
+        vc = (vmin+vmax)/2;
+
+    // explicitly specified anchor
+    if(anchor==='left' || anchor==='bottom') return vmin;
+    if(anchor==='center' || anchor==='middle') return vc;
+    if(anchor==='right' || anchor==='top') return vmax;
+
+    // automatic based on position
+    if(vmin<(2/3)-vc) return vmin;
+    if(vmax>(4/3)-vc) return vmax;
+    return vc;
+};
+
+
+// set cursors pointing toward the closest corner/side,
+// to indicate alignment
+// x and y are 0-1, fractions of the plot area
+var cursorset = [['sw-resize','s-resize','se-resize'],
+            ['w-resize','move','e-resize'],
+            ['nw-resize','n-resize','ne-resize']];
+fx.dragCursors = function(x,y,xanchor,yanchor) {
+    if(xanchor==='left') x=0;
+    else if(xanchor==='center') x=1;
+    else if(xanchor==='right') x=2;
+    else x = Plotly.Lib.constrain(Math.floor(x*3),0,2);
+
+    if(yanchor==='bottom') y=0;
+    else if(yanchor==='middle') y=1;
+    else if(yanchor==='top') y=2;
+    else y = Plotly.Lib.constrain(Math.floor(y*3),0,2);
+
+    return cursorset[y][x];
+};
+
+/**
+ * Abstracts click & drag interactions
+ * @param {object} options with keys:
+ *      element (required) the DOM element to drag
+ *      prepFn (optional) function(event, startX, startY)
+ *          executed on mousedown
+ *          startX and startY are the clientX and clientY pixel position
+ *          of the mousedown event
+ *      moveFn (optional) function(dx, dy, dragged)
+ *          executed on move
+ *          dx and dy are the net pixel offset of the drag,
+ *          dragged is true/false, has the mouse moved enough to
+ *          constitute a drag
+ *      doneFn (optional) function(dragged, numClicks)
+ *          executed on mouseup, or mouseout of window since
+ *          we don't get events after that
+ *          dragged is as in moveFn
+ *          numClicks is how many clicks we've registered within
+ *          a doubleclick time
+ */
+fx.dragElement = function(options) {
+    var gd = Plotly.Lib.getPlotDiv(options.element) || {},
+        numClicks = 1,
+        DBLCLICKDELAY = constants.DBLCLICKDELAY,
+        startX,
+        startY,
+        newMouseDownTime,
+        dragCover,
+        initialTarget;
+
+    if(!gd._mouseDownTime) gd._mouseDownTime = 0;
+
+    function onStart(e) {
+        // because we cancel event bubbling,
+        // explicitly trigger input blur event.
+        var inputBox = document.querySelector('.plugin-editable');
+        if(inputBox) d3.select(inputBox).on('blur').call(inputBox);
+
+        // make dragging and dragged into properties of gd
+        // so that others can look at and modify them
+        gd._dragged = false;
+        gd._dragging = true;
+        startX = e.clientX;
+        startY = e.clientY;
+        initialTarget = e.target;
+
+        newMouseDownTime = (new Date()).getTime();
+        if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) {
+            // in a click train
+            numClicks += 1;
+        }
+        else {
+            // new click train
+            numClicks = 1;
+            gd._mouseDownTime = newMouseDownTime;
+        }
+
+        if(options.prepFn) options.prepFn(e, startX, startY);
+
+        dragCover = coverSlip();
+
+        dragCover.onmousemove = onMove;
+        dragCover.onmouseup = onDone;
+        dragCover.onmouseout = onDone;
+
+        dragCover.style.cursor = window.getComputedStyle(options.element).cursor;
+
+        return Plotly.Lib.pauseEvent(e);
+    }
+
+    function onMove(e) {
+        var dx = e.clientX - startX,
+            dy = e.clientY - startY,
+            minDrag = options.minDrag || constants.MINDRAG;
+
+        if(Math.abs(dx) < minDrag) dx = 0;
+        if(Math.abs(dy) < minDrag) dy = 0;
+        if(dx||dy) {
+            gd._dragged = true;
+            fx.unhover(gd);
+        }
+
+        if(options.moveFn) options.moveFn(dx, dy, gd._dragged);
+
+        return Plotly.Lib.pauseEvent(e);
+    }
+
+    function onDone(e) {
+        dragCover.onmousemove = null;
+        dragCover.onmouseup = null;
+        dragCover.onmouseout = null;
+        Plotly.Lib.removeElement(dragCover);
+
+        if(!gd._dragging) {
+            gd._dragged = false;
+            return;
+        }
+        gd._dragging = false;
+
+        // don't count as a dblClick unless the mouseUp is also within
+        // the dblclick delay
+        if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) {
+            numClicks = Math.max(numClicks - 1, 1);
+        }
+
+        if(options.doneFn) options.doneFn(gd._dragged, numClicks);
+
+        if(!gd._dragged) {
+            var e2 = document.createEvent('MouseEvents');
+            e2.initEvent('click', true, true);
+            initialTarget.dispatchEvent(e2);
+        }
+
+        finishDrag(gd);
+
+        gd._dragged = false;
+
+        return Plotly.Lib.pauseEvent(e);
+    }
+
+    options.element.onmousedown = onStart;
+    options.element.style.pointerEvents = 'all';
+};
+
+function coverSlip() {
+    var cover = document.createElement('div');
+
+    cover.className = 'dragcover';
+    var cStyle = cover.style;
+    cStyle.position = 'fixed';
+    cStyle.left = 0;
+    cStyle.right = 0;
+    cStyle.top = 0;
+    cStyle.bottom = 0;
+    cStyle.zIndex = 999999999;
+    cStyle.background = 'none';
+
+    document.body.appendChild(cover);
+
+    return cover;
+}
+
+fx.setCursor = function(el3,csr) {
+    (el3.attr('class')||'').split(' ').forEach(function(cls) {
+        if(cls.indexOf('cursor-')===0) { el3.classed(cls,false); }
+    });
+    if(csr) { el3.classed('cursor-'+csr, true); }
+};
+
+// for bar charts and others with finite-size objects: you must be inside
+// it to see its hover info, so distance is infinite outside.
+// But make distance inside be at least 1/4 MAXDIST, and a little bigger
+// for bigger bars, to prioritize scatter and smaller bars over big bars
+
+// note that for closest mode, two inbox's will get added in quadrature
+// args are (signed) difference from the two opposite edges
+// count one edge as in, so that over continuous ranges you never get a gap
+fx.inbox = function(v0,v1) {
+    if(v0*v1<0 || v0===0) {
+        return constants.MAXDIST*(0.6-0.3/Math.max(3,Math.abs(v0-v1)));
+    }
+    return Infinity;
+};
+
+},{"../../lib":349,"../../lib/events":344,"../../plotly":366,"./constants":373,"./select":379,"d3":70,"fast-isnumeric":74,"tinycolor2":229}],375:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+var Plots = require('../plots');
+var ErrorBars = require('../../components/errorbars');
+
+
+exports.name = 'cartesian';
+
+exports.attr = ['xaxis', 'yaxis'];
+
+exports.idRoot = ['x', 'y'];
+
+exports.attributes = require('./attributes');
+
+exports.idRegex = {
+    x: /^x([2-9]|[1-9][0-9]+)?$/,
+    y: /^y([2-9]|[1-9][0-9]+)?$/
+};
+
+exports.attrRegex = {
+    x: /^xaxis([2-9]|[1-9][0-9]+)?$/,
+    y: /^yaxis([2-9]|[1-9][0-9]+)?$/
+};
+
+exports.plot = function(gd) {
+    var fullLayout = gd._fullLayout,
+        subplots = Plots.getSubplotIds(fullLayout, 'cartesian'),
+        calcdata = gd.calcdata,
+        modules = gd._modules;
+
+    function getCdSubplot(calcdata, subplot) {
+        var cdSubplot = [];
+
+        for(var i = 0; i < calcdata.length; i++) {
+            var cd = calcdata[i];
+            var trace = cd[0].trace;
+
+            if(trace.xaxis + trace.yaxis === subplot) {
+                cdSubplot.push(cd);
+            }
+        }
+
+        return cdSubplot;
+    }
+
+    function getCdModule(cdSubplot, _module) {
+        var cdModule = [];
+
+        for(var i = 0; i < cdSubplot.length; i++) {
+            var cd = cdSubplot[i];
+            var trace = cd[0].trace;
+
+            if((trace._module === _module) && (trace.visible === true)) {
+                cdModule.push(cd);
+            }
+        }
+
+        return cdModule;
+    }
+
+    for(var i = 0; i < subplots.length; i++) {
+        var subplot = subplots[i],
+            subplotInfo = fullLayout._plots[subplot],
+            cdSubplot = getCdSubplot(calcdata, subplot),
+            cdError = [];
+
+        // remove old traces, then redraw everything
+        // TODO: use enter/exit appropriately in the plot functions
+        // so we don't need this - should sometimes be a big speedup
+        if(subplotInfo.plot) subplotInfo.plot.selectAll('g.trace').remove();
+
+        for(var j = 0; j < modules.length; j++) {
+            var _module = modules[j];
+
+            // skip over non-cartesian trace modules
+            if(_module.basePlotModule.name !== 'cartesian') continue;
+
+            // skip over pies, there are drawn below
+            if(_module.name === 'pie') continue;
+
+            // plot all traces of this type on this subplot at once
+            var cdModule = getCdModule(cdSubplot, _module);
+            _module.plot(gd, subplotInfo, cdModule);
+            Lib.markTime('done ' + (cdModule[0] && cdModule[0][0].trace.type));
+
+            // collect the traces that may have error bars
+            if(cdModule[0] && cdModule[0][0].trace && Plots.traceIs(cdModule[0][0].trace, 'errorBarsOK')) {
+                cdError = cdError.concat(cdModule);
+            }
+        }
+
+        // finally do all error bars at once
+        ErrorBars.plot(gd, subplotInfo, cdError);
+        Lib.markTime('done ErrorBars');
+    }
+
+    // now draw stuff not on subplots (ie, only pies at the moment)
+    if(fullLayout._hasPie) {
+        var Pie = Plots.getModule('pie');
+        var cdPie = getCdModule(calcdata, Pie);
+
+        if(cdPie.length) Pie.plot(gd, cdPie);
+    }
+};
+
+exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
+    if(oldFullLayout._hasPie && !newFullLayout._hasPie) {
+        oldFullLayout._pielayer.selectAll('g.trace').remove();
+    }
+};
+
+},{"../../components/errorbars":323,"../../lib":349,"../plots":413,"./attributes":368}],376:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+var Cartesian = require('./index');
+var fontAttrs = require('../font_attributes');
+var colorAttrs = require('../../components/color/attributes');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+module.exports = {
+    title: {
+        valType: 'string',
+        
+        
+    },
+    titlefont: extendFlat({}, fontAttrs, {
+        
+    }),
+    type: {
+        valType: 'enumerated',
+        // '-' means we haven't yet run autotype or couldn't find any data
+        // it gets turned into linear in td._fullLayout but not copied back
+        // to td.data like the others are.
+        values: ['-', 'linear', 'log', 'date', 'category'],
+        dflt: '-',
+        
+        
+    },
+    autorange: {
+        valType: 'enumerated',
+        values: [true, false, 'reversed'],
+        dflt: true,
+        
+        
+    },
+    rangemode: {
+        valType: 'enumerated',
+        values: ['normal', 'tozero', 'nonnegative'],
+        dflt: 'normal',
+        
+        
+    },
+    range: {
+        valType: 'info_array',
+        
+        items: [
+            {valType: 'number'},
+            {valType: 'number'}
+        ],
+        
+    },
+    fixedrange: {
+        valType: 'boolean',
+        dflt: false,
+        
+        
+    },
+    // ticks
+    tickmode: {
+        valType: 'enumerated',
+        values: ['auto', 'linear', 'array'],
+        
+        
+    },
+    nticks: {
+        valType: 'integer',
+        min: 0,
+        dflt: 0,
+        
+        
+    },
+    tick0: {
+        valType: 'number',
+        dflt: 0,
+        
+        
+    },
+    dtick: {
+        valType: 'any',
+        dflt: 1,
+        
+        
+    },
+    tickvals: {
+        valType: 'data_array',
+        
+    },
+    ticktext: {
+        valType: 'data_array',
+        
+    },
+    ticks: {
+        valType: 'enumerated',
+        values: ['outside', 'inside', ''],
+        
+        
+    },
+    mirror: {
+        valType: 'enumerated',
+        values: [true, 'ticks', false, 'all', 'allticks'],
+        dflt: false,
+        
+        
+    },
+    ticklen: {
+        valType: 'number',
+        min: 0,
+        dflt: 5,
+        
+        
+    },
+    tickwidth: {
+        valType: 'number',
+        min: 0,
+        dflt: 1,
+        
+        
+    },
+    tickcolor: {
+        valType: 'color',
+        dflt: colorAttrs.defaultLine,
+        
+        
+    },
+    showticklabels: {
+        valType: 'boolean',
+        dflt: true,
+        
+        
+    },
+    tickfont: extendFlat({}, fontAttrs, {
+        
+    }),
+    tickangle: {
+        valType: 'angle',
+        dflt: 'auto',
+        
+        
+    },
+    tickprefix: {
+        valType: 'string',
+        dflt: '',
+        
+        
+    },
+    showtickprefix: {
+        valType: 'enumerated',
+        values: ['all', 'first', 'last', 'none'],
+        dflt: 'all',
+        
+        
+    },
+    ticksuffix: {
+        valType: 'string',
+        dflt: '',
+        
+        
+    },
+    showticksuffix: {
+        valType: 'enumerated',
+        values: ['all', 'first', 'last', 'none'],
+        dflt: 'all',
+        
+        
+    },
+    showexponent: {
+        valType: 'enumerated',
+        values: ['all', 'first', 'last', 'none'],
+        dflt: 'all',
+        
+        
+    },
+    exponentformat: {
+        valType: 'enumerated',
+        values: ['none', 'e', 'E', 'power', 'SI', 'B'],
+        dflt: 'B',
+        
+        
+    },
+    tickformat: {
+        valType: 'string',
+        dflt: '',
+        
+        
+    },
+    hoverformat: {
+        valType: 'string',
+        dflt: '',
+        
+        
+    },
+    // lines and grids
+    showline: {
+        valType: 'boolean',
+        dflt: false,
+        
+        
+    },
+    linecolor: {
+        valType: 'color',
+        dflt: colorAttrs.defaultLine,
+        
+        
+    },
+    linewidth: {
+        valType: 'number',
+        min: 0,
+        dflt: 1,
+        
+        
+    },
+    showgrid: {
+        valType: 'boolean',
+        
+        
+    },
+    gridcolor: {
+        valType: 'color',
+        dflt: colorAttrs.lightLine,
+        
+        
+    },
+    gridwidth: {
+        valType: 'number',
+        min: 0,
+        dflt: 1,
+        
+        
+    },
+    zeroline: {
+        valType: 'boolean',
+        
+        
+    },
+    zerolinecolor: {
+        valType: 'color',
+        dflt: colorAttrs.defaultLine,
+        
+        
+    },
+    zerolinewidth: {
+        valType: 'number',
+        dflt: 1,
+        
+        
+    },
+    // positioning attributes
+    // anchor: not used directly, just put here for reference
+    // values are any opposite-letter axis id
+    anchor: {
+        valType: 'enumerated',
+        values: [
+            'free',
+            Cartesian.idRegex.x.toString(),
+            Cartesian.idRegex.y.toString()
+        ],
+        
+        
+    },
+    // side: not used directly, as values depend on direction
+    // values are top, bottom for x axes, and left, right for y
+    side: {
+        valType: 'enumerated',
+        values: ['top', 'bottom', 'left', 'right'],
+        
+        
+    },
+    // overlaying: not used directly, just put here for reference
+    // values are false and any other same-letter axis id that's not
+    // itself overlaying anything
+    overlaying: {
+        valType: 'enumerated',
+        values: [
+            'free',
+            Cartesian.idRegex.x.toString(),
+            Cartesian.idRegex.y.toString()
+        ],
+        
+        
+    },
+    domain: {
+        valType: 'info_array',
+        
+        items: [
+            {valType: 'number', min: 0, max: 1},
+            {valType: 'number', min: 0, max: 1}
+        ],
+        dflt: [0, 1],
+        
+    },
+    position: {
+        valType: 'number',
+        min: 0,
+        max: 1,
+        dflt: 0,
+        
+        
+    },
+
+    _deprecated: {
+        autotick: {
+            valType: 'boolean',
+            
+            
+        }
+    }
+};
+
+},{"../../components/color/attributes":298,"../../lib/extend":345,"../font_attributes":383,"./index":375}],377:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+var Plots = require('../plots');
+
+var constants = require('./constants');
+var layoutAttributes = require('./layout_attributes');
+var handleAxisDefaults = require('./axis_defaults');
+var handlePositionDefaults = require('./position_defaults');
+var axisIds = require('./axis_ids');
+
+
+module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
+    var layoutKeys = Object.keys(layoutIn),
+        xaListCartesian = [],
+        yaListCartesian = [],
+        xaListGl2d = [],
+        yaListGl2d = [],
+        outerTicks = {},
+        noGrids = {},
+        i;
+
+    // look for axes in the data
+    for(i = 0; i < fullData.length; i++) {
+        var trace = fullData[i];
+        var listX, listY;
+
+        if(Plots.traceIs(trace, 'cartesian')) {
+            listX = xaListCartesian;
+            listY = yaListCartesian;
+        }
+        else if(Plots.traceIs(trace, 'gl2d')) {
+            listX = xaListGl2d;
+            listY = yaListGl2d;
+        }
+        else continue;
+
+        var xaName = axisIds.id2name(trace.xaxis),
+            yaName = axisIds.id2name(trace.yaxis);
+
+        // add axes implied by traces
+        if(xaName && listX.indexOf(xaName) === -1) listX.push(xaName);
+        if(yaName && listY.indexOf(yaName) === -1) listY.push(yaName);
+
+        // check for default formatting tweaks
+        if(Plots.traceIs(trace, '2dMap')) {
+            outerTicks[xaName] = true;
+            outerTicks[yaName] = true;
+        }
+
+        if(Plots.traceIs(trace, 'oriented')) {
+            var positionAxis = trace.orientation === 'h' ? yaName : xaName;
+            noGrids[positionAxis] = true;
+        }
+    }
+
+    // N.B. Ignore orphan axes (i.e. axes that have no data attached to them)
+    // if gl3d or geo is present on graph. This is retain backward compatible.
+    //
+    // TODO drop this in version 2.0
+    var ignoreOrphan = (layoutOut._hasGL3D || layoutOut._hasGeo);
+
+    if(!ignoreOrphan) {
+        for(i = 0; i < layoutKeys.length; i++) {
+            var key = layoutKeys[i];
+
+            // orphan layout axes are considered cartesian subplots
+
+            if(xaListGl2d.indexOf(key) === -1 &&
+                xaListCartesian.indexOf(key) === -1 &&
+                    constants.xAxisMatch.test(key)) {
+                xaListCartesian.push(key);
+            }
+            else if(yaListGl2d.indexOf(key) === -1 &&
+                yaListCartesian.indexOf(key) === -1 &&
+                    constants.yAxisMatch.test(key)) {
+                yaListCartesian.push(key);
+            }
+        }
+    }
+
+    // make sure that plots with orphan cartesian axes
+    // are considered 'cartesian'
+    if(xaListCartesian.length && yaListCartesian.length) {
+        layoutOut._hasCartesian = true;
+    }
+
+    function axSort(a, b) {
+        var aNum = Number(a.substr(5) || 1),
+            bNum = Number(b.substr(5) || 1);
+        return aNum - bNum;
+    }
+
+    var xaList = xaListCartesian.concat(xaListGl2d).sort(axSort),
+        yaList = yaListCartesian.concat(yaListGl2d).sort(axSort);
+
+    xaList.concat(yaList).forEach(function(axName) {
+        var axLetter = axName.charAt(0),
+            axLayoutIn = layoutIn[axName] || {},
+            axLayoutOut = {},
+            defaultOptions = {
+                letter: axLetter,
+                font: layoutOut.font,
+                outerTicks: outerTicks[axName],
+                showGrid: !noGrids[axName],
+                name: axName,
+                data: fullData
+            },
+            positioningOptions = {
+                letter: axLetter,
+                counterAxes: {x: yaList, y: xaList}[axLetter].map(axisIds.name2id),
+                overlayableAxes: {x: xaList, y: yaList}[axLetter].filter(function(axName2) {
+                    return axName2!==axName && !(layoutIn[axName2]||{}).overlaying;
+                }).map(axisIds.name2id)
+            };
+
+        function coerce(attr, dflt) {
+            return Lib.coerce(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
+        }
+
+        handleAxisDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions);
+        handlePositionDefaults(axLayoutIn, axLayoutOut, coerce, positioningOptions);
+        layoutOut[axName] = axLayoutOut;
+
+        // so we don't have to repeat autotype unnecessarily,
+        // copy an autotype back to layoutIn
+        if(!layoutIn[axName] && axLayoutIn.type !== '-') {
+            layoutIn[axName] = {type: axLayoutIn.type};
+        }
+
+    });
+
+    // plot_bgcolor only makes sense if there's a (2D) plot!
+    // TODO: bgcolor for each subplot, to inherit from the main one
+    if(xaList.length && yaList.length) {
+        Lib.coerce(layoutIn, layoutOut, Plots.layoutAttributes, 'plot_bgcolor');
+    }
+};
+
+},{"../../lib":349,"../plots":413,"./axis_defaults":370,"./axis_ids":371,"./constants":373,"./layout_attributes":376,"./position_defaults":378}],378:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+
+
+module.exports = function handlePositionDefaults(containerIn, containerOut, coerce, options) {
+    var counterAxes = options.counterAxes || [],
+        overlayableAxes = options.overlayableAxes || [],
+        letter = options.letter;
+
+    var anchor = Lib.coerce(containerIn, containerOut, {
+        anchor: {
+            valType: 'enumerated',
+            values: ['free'].concat(counterAxes),
+            dflt: isNumeric(containerIn.position) ? 'free' :
+                (counterAxes[0] || 'free')
+        }
+    }, 'anchor');
+
+    if(anchor === 'free') coerce('position');
+
+    Lib.coerce(containerIn, containerOut, {
+        side: {
+            valType: 'enumerated',
+            values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'],
+            dflt: letter === 'x' ? 'bottom' : 'left'
+        }
+    }, 'side');
+
+    var overlaying = false;
+    if(overlayableAxes.length) {
+        overlaying = Lib.coerce(containerIn, containerOut, {
+            overlaying: {
+                valType: 'enumerated',
+                values: [false].concat(overlayableAxes),
+                dflt: false
+            }
+        }, 'overlaying');
+    }
+
+    if(!overlaying) {
+        // TODO: right now I'm copying this domain over to overlaying axes
+        // in ax.setscale()... but this means we still need (imperfect) logic
+        // in the axes popover to hide domain for the overlaying axis.
+        // perhaps I should make a private version _domain that all axes get???
+        var domain = coerce('domain');
+        if(domain[0] > domain[1] - 0.01) containerOut.domain = [0, 1];
+        Lib.noneOrAll(containerIn.domain, containerOut.domain, [0, 1]);
+    }
+
+    return containerOut;
+};
+
+},{"../../lib":349,"fast-isnumeric":74}],379:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var polygon = require('../../lib/polygon');
+var color = require('../../components/color');
+
+var axes = require('./axes');
+var constants = require('./constants');
+
+var filteredPolygon = polygon.filter;
+var polygonTester = polygon.tester;
+var MINSELECT = constants.MINSELECT;
+
+function getAxId(ax) { return ax._id; }
+
+module.exports = function prepSelect(e, startX, startY, dragOptions, mode) {
+    var plot = dragOptions.plotinfo.plot,
+        dragBBox = dragOptions.element.getBoundingClientRect(),
+        x0 = startX - dragBBox.left,
+        y0 = startY - dragBBox.top,
+        x1 = x0,
+        y1 = y0,
+        path0 = 'M' + x0 + ',' + y0,
+        pw = dragOptions.xaxes[0]._length,
+        ph = dragOptions.yaxes[0]._length,
+        xAxisIds = dragOptions.xaxes.map(getAxId),
+        yAxisIds = dragOptions.yaxes.map(getAxId),
+        allAxes = dragOptions.xaxes.concat(dragOptions.yaxes),
+        pts;
+
+    if(mode === 'lasso') {
+        pts = filteredPolygon([[x0, y0]], constants.BENDPX);
+    }
+
+    var outlines = plot.selectAll('path.select-outline').data([1,2]);
+
+    outlines.enter()
+        .append('path')
+        .attr('class', function(d) { return 'select-outline select-outline-' + d; })
+        .attr('d', path0 + 'Z');
+
+    var corners = plot.append('path')
+        .attr('class', 'zoombox-corners')
+        .style({
+            fill: color.background,
+            stroke: color.defaultLine,
+            'stroke-width': 1
+        })
+        .attr('d','M0,0Z');
+
+
+    // find the traces to search for selection points
+    var searchTraces = [],
+        gd = dragOptions.gd,
+        i,
+        cd,
+        trace,
+        searchInfo,
+        selection = [],
+        eventData;
+    for(i = 0; i < gd.calcdata.length; i++) {
+        cd = gd.calcdata[i];
+        trace = cd[0].trace;
+        if(!trace._module || !trace._module.selectPoints) continue;
+
+        if(xAxisIds.indexOf(trace.xaxis) === -1) continue;
+        if(yAxisIds.indexOf(trace.yaxis) === -1) continue;
+
+        searchTraces.push({
+            selectPoints: trace._module.selectPoints,
+            cd: cd,
+            xaxis: axes.getFromId(gd, trace.xaxis),
+            yaxis: axes.getFromId(gd, trace.yaxis)
+        });
+    }
+
+    function axValue(ax) {
+        var index = (ax._id.charAt(0) === 'y') ? 1 : 0;
+        return function(v) { return ax.p2d(v[index]); };
+    }
+
+    function ascending(a, b) { return a - b; }
+
+    dragOptions.moveFn = function(dx0, dy0) {
+        var poly,
+            ax;
+        x1 = Math.max(0, Math.min(pw, dx0 + x0));
+        y1 = Math.max(0, Math.min(ph, dy0 + y0));
+
+        var dx = Math.abs(x1 - x0),
+            dy = Math.abs(y1 - y0);
+
+        if(mode === 'select') {
+            if(dy < Math.min(dx * 0.6, MINSELECT)) {
+                // horizontal motion: make a vertical box
+                poly = polygonTester([[x0, 0], [x0, ph], [x1, ph], [x1, 0]]);
+                // extras to guide users in keeping a straight selection
+                corners.attr('d', 'M' + poly.xmin + ',' + (y0 - MINSELECT) +
+                    'h-4v' + (2 * MINSELECT) + 'h4Z' +
+                    'M' + (poly.xmax - 1) + ',' + (y0 - MINSELECT) +
+                    'h4v' + (2 * MINSELECT) + 'h-4Z');
+
+            }
+            else if(dx < Math.min(dy * 0.6, MINSELECT)) {
+                // vertical motion: make a horizontal box
+                poly = polygonTester([[0, y0], [0, y1], [pw, y1], [pw, y0]]);
+                corners.attr('d', 'M' + (x0 - MINSELECT) + ',' + poly.ymin +
+                    'v-4h' + (2 * MINSELECT) + 'v4Z' +
+                    'M' + (x0 - MINSELECT) + ',' + (poly.ymax - 1) +
+                    'v4h' + (2 * MINSELECT) + 'v-4Z');
+            }
+            else {
+                // diagonal motion
+                poly = polygonTester([[x0, y0], [x0, y1], [x1, y1], [x1, y0]]);
+                corners.attr('d','M0,0Z');
+            }
+            outlines.attr('d', 'M' + poly.xmin + ',' + poly.ymin +
+                'H' + (poly.xmax - 1) + 'V' + (poly.ymax - 1) +
+                'H' + poly.xmin + 'Z');
+        }
+        else if(mode === 'lasso') {
+            pts.addPt([x1, y1]);
+            poly = polygonTester(pts.filtered);
+            outlines.attr('d', 'M' + pts.filtered.join('L') + 'Z');
+        }
+
+        selection = [];
+        for(i = 0; i < searchTraces.length; i++) {
+            searchInfo = searchTraces[i];
+            [].push.apply(selection, searchInfo.selectPoints(searchInfo, poly));
+        }
+
+        eventData = {points: selection};
+
+        if(mode === 'select') {
+            var ranges = eventData.range = {},
+                axLetter;
+
+            for(i = 0; i < allAxes.length; i++) {
+                ax = allAxes[i];
+                axLetter = ax._id.charAt(0);
+                ranges[ax._id] = [
+                    ax.p2d(poly[axLetter + 'min']),
+                    ax.p2d(poly[axLetter + 'max'])].sort(ascending);
+            }
+        }
+        else {
+            var dataPts = eventData.lassoPoints = {};
+
+            for(i = 0; i < allAxes.length; i++) {
+                ax = allAxes[i];
+                dataPts[ax._id] = pts.filtered.map(axValue(ax));
+            }
+        }
+        dragOptions.gd.emit('plotly_selecting', eventData);
+    };
+
+    dragOptions.doneFn = function(dragged, numclicks) {
+        if(!dragged && numclicks === 2) {
+            // clear selection on doubleclick
+            outlines.remove();
+            for(i = 0; i < searchTraces.length; i++) {
+                searchInfo = searchTraces[i];
+                searchInfo.selectPoints(searchInfo, false);
+            }
+
+            gd.emit('plotly_deselect', null);
+        }
+        else {
+            dragOptions.gd.emit('plotly_selected', eventData);
+        }
+        corners.remove();
+    };
+};
+
+},{"../../components/color":299,"../../lib/polygon":354,"./axes":369,"./constants":373}],380:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+
+var constants = require('./constants');
+var cleanDatum = require('./clean_datum');
+var axisIds = require('./axis_ids');
+
+
+/**
+ * Define the conversion functions for an axis data is used in 4 ways:
+ *
+ *  d: data, in whatever form it's provided
+ *  c: calcdata: turned into numbers, but not linearized
+ *  l: linearized - same as c except for log axes (and other
+ *      mappings later?) this is used by ranges, and when we
+ *      need to know if it's *possible* to show some data on
+ *      this axis, without caring about the current range
+ *  p: pixel value - mapped to the screen with current size and zoom
+ *
+ * Creates/updates these conversion functions
+ * also clears the autorange bounds ._min and ._max
+ * and the autotick constraints ._minDtick, ._forceTick0,
+ * and looks for date ranges that aren't yet in numeric format
+ */
+module.exports = function setConvert(ax) {
+
+    // clipMult: how many axis lengths past the edge do we render?
+    // for panning, 1-2 would suffice, but for zooming more is nice.
+    // also, clipping can affect the direction of lines off the edge...
+    var clipMult = 10;
+
+    function toLog(v, clip) {
+        if(v>0) return Math.log(v)/Math.LN10;
+
+        else if(v<=0 && clip && ax.range && ax.range.length===2) {
+            // clip NaN (ie past negative infinity) to clipMult axis
+            // length past the negative edge
+            var r0 = ax.range[0],
+                r1 = ax.range[1];
+            return 0.5*(r0 + r1 - 3 * clipMult * Math.abs(r0 - r1));
+        }
+
+        else return constants.BADNUM;
+    }
+    function fromLog(v) { return Math.pow(10,v); }
+    function num(v) { return isNumeric(v) ? Number(v) : constants.BADNUM; }
+
+    ax.c2l = (ax.type==='log') ? toLog : num;
+    ax.l2c = (ax.type==='log') ? fromLog : num;
+    ax.l2d = function(v) { return ax.c2d(ax.l2c(v)); };
+    ax.p2d = function(v) { return ax.l2d(ax.p2l(v)); };
+
+    // set scaling to pixels
+    ax.setScale = function() {
+        var gs = ax._td._fullLayout._size,
+            i;
+
+        // TODO cleaner way to handle this case
+        if(!ax._categories) ax._categories = [];
+
+        // make sure we have a domain (pull it in from the axis
+        // this one is overlaying if necessary)
+        if(ax.overlaying) {
+            var ax2 = axisIds.getFromId(ax._td, ax.overlaying);
+            ax.domain = ax2.domain;
+        }
+
+        // make sure we have a range (linearized data values)
+        // and that it stays away from the limits of javascript numbers
+        if(!ax.range || ax.range.length!==2 || ax.range[0]===ax.range[1]) {
+            ax.range = [-1,1];
+        }
+        for(i=0; i<2; i++) {
+            if(!isNumeric(ax.range[i])) {
+                ax.range[i] = isNumeric(ax.range[1-i]) ?
+                    (ax.range[1-i] * (i ? 10 : 0.1)) :
+                    (i ? 1 : -1);
+            }
+
+            if(ax.range[i]<-(Number.MAX_VALUE/2)) {
+                ax.range[i] = -(Number.MAX_VALUE/2);
+            }
+            else if(ax.range[i]>Number.MAX_VALUE/2) {
+                ax.range[i] = Number.MAX_VALUE/2;
+            }
+
+        }
+
+        if(ax._id.charAt(0)==='y') {
+            ax._offset = gs.t+(1-ax.domain[1])*gs.h;
+            ax._length = gs.h*(ax.domain[1]-ax.domain[0]);
+            ax._m = ax._length/(ax.range[0]-ax.range[1]);
+            ax._b = -ax._m*ax.range[1];
+        }
+        else {
+            ax._offset = gs.l+ax.domain[0]*gs.w;
+            ax._length = gs.w*(ax.domain[1]-ax.domain[0]);
+            ax._m = ax._length/(ax.range[1]-ax.range[0]);
+            ax._b = -ax._m*ax.range[0];
+        }
+
+        if(!isFinite(ax._m) || !isFinite(ax._b)) {
+            Lib.notifier(
+                'Something went wrong with axis scaling',
+                'long');
+            ax._td._replotting = false;
+            throw new Error('axis scaling');
+        }
+    };
+
+    ax.l2p = function(v) {
+        if(!isNumeric(v)) return constants.BADNUM;
+        // include 2 fractional digits on pixel, for PDF zooming etc
+        return d3.round(Lib.constrain(ax._b + ax._m*v,
+            -clipMult*ax._length, (1+clipMult)*ax._length), 2);
+    };
+
+    ax.p2l = function(px) { return (px-ax._b)/ax._m; };
+
+    ax.c2p = function(v, clip) { return ax.l2p(ax.c2l(v, clip)); };
+    ax.p2c = function(px) { return ax.l2c(ax.p2l(px)); };
+
+    if(['linear','log','-'].indexOf(ax.type)!==-1) {
+        ax.c2d = num;
+        ax.d2c = function(v) {
+            v = cleanDatum(v);
+            return isNumeric(v) ? Number(v) : constants.BADNUM;
+        };
+        ax.d2l = function(v, clip) {
+            if(ax.type === 'log') return ax.c2l(ax.d2c(v), clip);
+            else return ax.d2c(v);
+        };
+    }
+    else if(ax.type==='date') {
+        ax.c2d = function(v) {
+            return isNumeric(v) ? Lib.ms2DateTime(v) : constants.BADNUM;
+        };
+
+        ax.d2c = function(v) {
+            return (isNumeric(v)) ? Number(v) : Lib.dateTime2ms(v);
+        };
+
+        ax.d2l = ax.d2c;
+
+        // check if date strings or js date objects are provided for range
+        // and convert to ms
+        if(ax.range && ax.range.length>1) {
+            try {
+                var ar1 = ax.range.map(Lib.dateTime2ms);
+                if(!isNumeric(ax.range[0]) && isNumeric(ar1[0])) {
+                    ax.range[0] = ar1[0];
+                }
+                if(!isNumeric(ax.range[1]) && isNumeric(ar1[1])) {
+                    ax.range[1] = ar1[1];
+                }
+            }
+            catch(e) { console.log(e, ax.range); }
+        }
+    }
+    else if(ax.type==='category') {
+
+        ax.c2d = function(v) {
+            return ax._categories[Math.round(v)];
+        };
+
+        ax.d2c = function(v) {
+            // create the category list
+            // this will enter the categories in the order it
+            // encounters them, ie all the categories from the
+            // first data set, then all the ones from the second
+            // that aren't in the first etc.
+            // TODO: sorting options - do the sorting
+            // progressively here as we insert?
+
+            if(v !== null && v !== undefined && ax._categories.indexOf(v) === -1) {
+                ax._categories.push(v);
+            }
+
+            var c = ax._categories.indexOf(v);
+            return c === -1 ? constants.BADNUM : c;
+        };
+
+        ax.d2l = ax.d2c;
+    }
+
+    // makeCalcdata: takes an x or y array and converts it
+    // to a position on the axis object "ax"
+    // inputs:
+    //      tdc - a data object from td.data
+    //      axletter - a string, either 'x' or 'y', for which item
+    //          to convert (TODO: is this now always the same as
+    //          the first letter of ax._id?)
+    // in case the expected data isn't there, make a list of
+    // integers based on the opposite data
+    ax.makeCalcdata = function(tdc, axletter) {
+        var arrayIn, arrayOut, i;
+
+        if(axletter in tdc) {
+            arrayIn = tdc[axletter];
+            arrayOut = new Array(arrayIn.length);
+
+            for(i = 0; i < arrayIn.length; i++) arrayOut[i] = ax.d2c(arrayIn[i]);
+        }
+        else {
+            var v0 = ((axletter+'0') in tdc) ?
+                    ax.d2c(tdc[axletter+'0']) : 0,
+                dv = (tdc['d'+axletter]) ?
+                    Number(tdc['d'+axletter]) : 1;
+
+            // the opposing data, for size if we have x and dx etc
+            arrayIn = tdc[{x: 'y',y: 'x'}[axletter]];
+            arrayOut = new Array(arrayIn.length);
+
+            for(i = 0; i < arrayIn.length; i++) arrayOut[i] = v0+i*dv;
+        }
+        return arrayOut;
+    };
+
+    // for autoranging: arrays of objects:
+    //      {val: axis value, pad: pixel padding}
+    // on the low and high sides
+    ax._min = [];
+    ax._max = [];
+
+    // and for bar charts and box plots: reset forced minimum tick spacing
+    ax._minDtick = null;
+    ax._forceTick0 = null;
+};
+
+},{"../../lib":349,"./axis_ids":371,"./clean_datum":372,"./constants":373,"d3":70,"fast-isnumeric":74}],381:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var layoutAttributes = require('./layout_attributes');
+
+
+/**
+ * options: inherits font, outerTicks, noHover from axes.handleAxisDefaults
+ */
+module.exports = function handleTickDefaults(containerIn, containerOut, coerce, axType, options) {
+    var tickLen = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'ticklen'),
+        tickWidth = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'tickwidth'),
+        tickColor = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'tickcolor'),
+        showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : '');
+
+    if(!showTicks) {
+        delete containerOut.ticklen;
+        delete containerOut.tickwidth;
+        delete containerOut.tickcolor;
+    }
+
+    var showAttrDflt = getShowAttrDflt(containerIn);
+
+    var tickPrefix = coerce('tickprefix');
+    if(tickPrefix) coerce('showtickprefix', showAttrDflt);
+
+    var tickSuffix = coerce('ticksuffix');
+    if(tickSuffix) coerce('showticksuffix', showAttrDflt);
+
+    var showTickLabels = coerce('showticklabels');
+    if(showTickLabels) {
+        Lib.coerceFont(coerce, 'tickfont', options.font || {});
+        coerce('tickangle');
+
+        if(axType !== 'category') {
+            var tickFormat = coerce('tickformat');
+            if(!tickFormat && axType !== 'date') {
+                coerce('showexponent', showAttrDflt);
+                coerce('exponentformat');
+            }
+        }
+    }
+
+    if(axType !== 'category' && !options.noHover) coerce('hoverformat');
+};
+
+/*
+ * Attributes 'showexponent', 'showtickprefix' and 'showticksuffix'
+ * share values.
+ *
+ * If only 1 attribute is set,
+ * the remaining attributes inherit that value.
+ *
+ * If 2 attributes are set to the same value,
+ * the remaining attribute inherits that value.
+ *
+ * If 2 attributes are set to different values,
+ * the remaining is set to its dflt value.
+ *
+ */
+function getShowAttrDflt(containerIn) {
+    var showAttrsAll = ['showexponent',
+                        'showtickprefix',
+                        'showticksuffix'],
+        showAttrs = showAttrsAll.filter(function(a) {
+            return containerIn[a]!==undefined;
+        }),
+        sameVal = function(a) {
+            return containerIn[a]===containerIn[showAttrs[0]];
+        };
+
+    if(showAttrs.every(sameVal) || showAttrs.length===1) {
+        return containerIn[showAttrs[0]];
+    }
+}
+
+},{"../../lib":349,"./layout_attributes":376}],382:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+
+module.exports = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) {
+    var tickmodeDefault = 'auto';
+
+    if(containerIn.tickmode === 'array' &&
+            (axType === 'log' || axType === 'date')) {
+        containerIn.tickmode = 'auto';
+    }
+
+    if(Array.isArray(containerIn.tickvals)) tickmodeDefault = 'array';
+    else if(containerIn.dtick && isNumeric(containerIn.dtick)) {
+        tickmodeDefault = 'linear';
+    }
+    var tickmode = coerce('tickmode', tickmodeDefault);
+
+    if(tickmode === 'auto') coerce('nticks');
+    else if(tickmode === 'linear') {
+        coerce('tick0');
+        coerce('dtick');
+    }
+    else {
+        var tickvals = coerce('tickvals');
+        if(tickvals === undefined) containerOut.tickmode = 'auto';
+        else coerce('ticktext');
+    }
+};
+
+},{"fast-isnumeric":74}],383:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+module.exports = {
+    family: {
+        valType: 'string',
+        
+        noBlank: true,
+        strict: true,
+        
+    },
+    size: {
+        valType: 'number',
+        
+        min: 1
+    },
+    color: {
+        valType: 'color',
+        
+    }
+};
+
+},{}],384:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+/* global PlotlyGeoAssets:false */
+
+var d3 = require('d3');
+
+var Color = require('../../components/color');
+var Drawing = require('../../components/drawing');
+var Axes = require('../../plots/cartesian/axes');
+
+var addProjectionsToD3 = require('./projections');
+var createGeoScale = require('./set_scale');
+var createGeoZoom = require('./zoom');
+var createGeoZoomReset = require('./zoom_reset');
+
+var xmlnsNamespaces = require('../../constants/xmlns_namespaces');
+var constants = require('../../constants/geo_constants');
+var topojsonUtils = require('../../lib/topojson_utils');
+var topojsonFeature = require('topojson').feature;
+
+
+function Geo(options, fullLayout) {
+
+    this.id = options.id;
+    this.graphDiv = options.graphDiv;
+    this.container = options.container;
+    this.topojsonURL = options.topojsonURL;
+
+    // add a few projection types to d3.geo,
+    // a subset of https://github.com/d3/d3-geo-projection
+    addProjectionsToD3();
+
+    this.hoverContainer = null;
+
+    this.topojsonName = null;
+    this.topojson = null;
+
+    this.projectionType = null;
+    this.projection = null;
+
+    this.clipAngle = null;
+    this.setScale = null;
+    this.path = null;
+
+    this.zoom = null;
+    this.zoomReset = null;
+
+    this.makeFramework();
+    this.updateFx(fullLayout.hovermode);
+
+    this.traceHash = {};
+}
+
+module.exports = Geo;
+
+var proto = Geo.prototype;
+
+proto.plot = function(geoData, fullLayout, promises) {
+    var _this = this,
+        geoLayout = fullLayout[_this.id],
+        graphSize = fullLayout._size;
+
+    var topojsonNameNew, topojsonPath;
+
+    // N.B. 'geoLayout' is unambiguous, no need for 'user' geo layout here
+
+    // TODO don't reset projection on all graph edits
+    _this.projection = null;
+
+    _this.setScale = createGeoScale(geoLayout, graphSize);
+    _this.makeProjection(geoLayout);
+    _this.makePath();
+    _this.adjustLayout(geoLayout, graphSize);
+
+    _this.zoom = createGeoZoom(_this, geoLayout);
+    _this.zoomReset = createGeoZoomReset(_this, geoLayout);
+    _this.mockAxis = createMockAxis(fullLayout);
+
+    _this.framework
+        .call(_this.zoom)
+        .on('dblclick.zoom', _this.zoomReset);
+
+    topojsonNameNew = topojsonUtils.getTopojsonName(geoLayout);
+
+    if(_this.topojson===null || topojsonNameNew!==_this.topojsonName) {
+        _this.topojsonName = topojsonNameNew;
+
+        if(PlotlyGeoAssets.topojson[_this.topojsonName] !== undefined) {
+            _this.topojson = PlotlyGeoAssets.topojson[_this.topojsonName];
+            _this.onceTopojsonIsLoaded(geoData, geoLayout);
+        }
+        else {
+            topojsonPath = topojsonUtils.getTopojsonPath(
+                _this.topojsonURL,
+                _this.topojsonName
+            );
+
+            promises.push(new Promise(function(resolve, reject) {
+                d3.json(topojsonPath, function(error, topojson) {
+                    if(error) {
+                        if(error.status === 404) {
+                            reject(new Error([
+                                'plotly.js could not find topojson file at',
+                                topojsonPath, '.',
+                                'Make sure the *topojsonURL* plot config option',
+                                'is set properly.'
+                            ].join(' ')));
+                        }
+                        else {
+                            reject(new Error([
+                                'unexpected error while fetching topojson file at',
+                                topojsonPath
+                            ].join(' ')));
+                        }
+                        return;
+                    }
+
+                    _this.topojson = topojson;
+                    PlotlyGeoAssets.topojson[_this.topojsonName] = topojson;
+
+                    _this.onceTopojsonIsLoaded(geoData, geoLayout);
+                    resolve();
+                });
+            }));
+        }
+    }
+    else _this.onceTopojsonIsLoaded(geoData, geoLayout);
+
+    // TODO handle topojson-is-loading case
+    // to avoid making multiple request while streaming
+};
+
+// filter out non-visible trace
+// geo plot routine use the classic join/enter/exit pattern to update traces
+function filterData(dataIn) {
+    var dataOut = [];
+
+    for(var i = 0; i < dataIn.length; i++) {
+        var trace = dataIn[i];
+
+        if(trace.visible === true) dataOut.push(trace);
+    }
+
+    return dataOut;
+}
+
+proto.onceTopojsonIsLoaded = function(geoData, geoLayout) {
+    var i;
+
+    this.drawLayout(geoLayout);
+
+    var traceHashOld = this.traceHash;
+    var traceHash = {};
+
+    for(i = 0; i < geoData.length; i++) {
+        var trace = geoData[i];
+
+        traceHash[trace.type] = traceHash[trace.type] || [];
+        traceHash[trace.type].push(trace);
+    }
+
+    var moduleNamesOld = Object.keys(traceHashOld);
+    var moduleNames = Object.keys(traceHash);
+
+    // when a trace gets deleted, make sure that its module's
+    // plot method is called so that it is properly
+    // removed from the DOM.
+    for(i = 0; i < moduleNamesOld.length; i++) {
+        var moduleName = moduleNamesOld[i];
+
+        if(moduleNames.indexOf(moduleName) === -1) {
+            var fakeModule = traceHashOld[moduleName][0];
+            fakeModule.visible = false;
+            traceHash[moduleName] = [fakeModule];
+        }
+    }
+
+    moduleNames = Object.keys(traceHash);
+
+    for(i = 0; i < moduleNames.length; i++) {
+        var moduleData = traceHash[moduleNames[i]];
+        var _module = moduleData[0]._module;
+
+        _module.plot(this, filterData(moduleData), geoLayout);
+    }
+
+    this.traceHash = traceHash;
+
+    this.render();
+};
+
+proto.updateFx = function(hovermode) {
+    this.showHover = (hovermode !== false);
+
+    // TODO should more strict, any layout.hovermode other
+    // then false will make all geo subplot display hover text.
+    // Instead each geo should have its own geo.hovermode
+    // to control hover visibility independently of other subplots.
+};
+
+proto.makeProjection = function(geoLayout) {
+    var projLayout = geoLayout.projection,
+        projType = projLayout.type,
+        isNew = this.projection===null || projType!==this.projectionType,
+        projection;
+
+    if(isNew) {
+        this.projectionType = projType;
+        projection = this.projection = d3.geo[constants.projNames[projType]]();
+    }
+    else projection = this.projection;
+
+    projection
+        .translate(projLayout._translate0)
+        .precision(constants.precision);
+
+    if(!geoLayout._isAlbersUsa) {
+        projection
+            .rotate(projLayout._rotate)
+            .center(projLayout._center);
+    }
+
+    if(geoLayout._clipAngle) {
+        this.clipAngle = geoLayout._clipAngle;  // needed in proto.render
+        projection
+            .clipAngle(geoLayout._clipAngle - constants.clipPad);
+    }
+    else this.clipAngle = null;  // for graph edits
+
+    if(projLayout.parallels) {
+        projection
+            .parallels(projLayout.parallels);
+    }
+
+    if(isNew) this.setScale(projection);
+
+    projection
+        .translate(projLayout._translate)
+        .scale(projLayout._scale);
+};
+
+proto.makePath = function() {
+    this.path = d3.geo.path().projection(this.projection);
+};
+
+/*
+ * <div this.container>
+ *   <div this.geoDiv>
+ *     <svg this.hoverContainer>
+ *     <svg this.framework>
+ */
+proto.makeFramework = function() {
+    var geoDiv = this.geoDiv = d3.select(this.container).append('div');
+    geoDiv
+        .attr('id', this.id)
+        .style('position', 'absolute');
+
+    var hoverContainer = this.hoverContainer = geoDiv.append('svg');
+    hoverContainer
+        .attr(xmlnsNamespaces.svgAttrs)
+        .style({
+            'position': 'absolute',
+            'z-index': 20,
+            'pointer-events': 'none'
+        });
+
+    var framework = this.framework = geoDiv.append('svg');
+    framework
+        .attr(xmlnsNamespaces.svgAttrs)
+        .attr({
+            'position': 'absolute',
+            'preserveAspectRatio': 'none'
+        });
+
+    framework.append('g').attr('class', 'bglayer')
+        .append('rect');
+
+    framework.append('g').attr('class', 'baselayer');
+    framework.append('g').attr('class', 'choroplethlayer');
+    framework.append('g').attr('class', 'baselayeroverchoropleth');
+    framework.append('g').attr('class', 'scattergeolayer');
+
+    // N.B. disable dblclick zoom default
+    framework.on('dblclick.zoom', null);
+
+    // TODO use clip paths instead of nested SVG
+};
+
+proto.adjustLayout = function(geoLayout, graphSize) {
+    var domain = geoLayout.domain;
+
+    this.geoDiv.style({
+        left: graphSize.l + graphSize.w * domain.x[0] + geoLayout._marginX + 'px',
+        top: graphSize.t + graphSize.h * (1 - domain.y[1]) + geoLayout._marginY + 'px',
+        width: geoLayout._width + 'px',
+        height: geoLayout._height + 'px'
+    });
+
+    this.hoverContainer.attr({
+        width: geoLayout._width,
+        height: geoLayout._height
+    });
+
+    this.framework.attr({
+        width: geoLayout._width,
+        height: geoLayout._height
+    });
+
+    this.framework.select('.bglayer').select('rect')
+        .attr({
+            width: geoLayout._width,
+            height: geoLayout._height
+        })
+        .style({
+            'fill': geoLayout.bgcolor,
+            'stroke-width': 0
+        });
+};
+
+proto.drawTopo = function(selection, layerName, geoLayout) {
+    if(geoLayout['show' + layerName] !== true) return;
+
+    var topojson = this.topojson,
+        datum = layerName==='frame' ?
+            constants.sphereSVG :
+            topojsonFeature(topojson, topojson.objects[layerName]);
+
+    selection.append('g')
+        .datum(datum)
+        .attr('class', layerName)
+          .append('path')
+            .attr('class', 'basepath');
+};
+
+function makeGraticule(lonaxisRange, lataxisRange, step) {
+    return d3.geo.graticule()
+        .extent([
+            [lonaxisRange[0], lataxisRange[0]],
+            [lonaxisRange[1], lataxisRange[1]]
+        ])
+        .step(step);
+}
+
+proto.drawGraticule = function(selection, axisName, geoLayout) {
+    var axisLayout = geoLayout[axisName];
+
+    if(axisLayout.showgrid !== true) return;
+
+    var scopeDefaults = constants.scopeDefaults[geoLayout.scope],
+        lonaxisRange = scopeDefaults.lonaxisRange,
+        lataxisRange = scopeDefaults.lataxisRange,
+        step = axisName==='lonaxis' ?
+            [axisLayout.dtick] :
+            [0, axisLayout.dtick],
+        graticule = makeGraticule(lonaxisRange, lataxisRange, step);
+
+    selection.append('g')
+        .datum(graticule)
+        .attr('class', axisName + 'graticule')
+            .append('path')
+                .attr('class', 'graticulepath');
+};
+
+proto.drawLayout = function(geoLayout) {
+    var gBaseLayer = this.framework.select('g.baselayer'),
+        baseLayers = constants.baseLayers,
+        axesNames = constants.axesNames,
+        layerName;
+
+    // TODO move to more d3-idiomatic pattern (that's work on replot)
+    // N.B. html('') does not work in IE11
+    gBaseLayer.selectAll('*').remove();
+
+    for(var i = 0; i < baseLayers.length; i++) {
+        layerName = baseLayers[i];
+
+        if(axesNames.indexOf(layerName)!==-1) {
+            this.drawGraticule(gBaseLayer, layerName, geoLayout);
+        }
+        else this.drawTopo(gBaseLayer, layerName, geoLayout);
+    }
+
+    this.styleLayout(geoLayout);
+};
+
+function styleFillLayer(selection, layerName, geoLayout) {
+    var layerAdj = constants.layerNameToAdjective[layerName];
+
+    selection.select('.' + layerName)
+        .selectAll('path')
+            .attr('stroke', 'none')
+            .call(Color.fill, geoLayout[layerAdj + 'color']);
+}
+
+function styleLineLayer(selection, layerName, geoLayout) {
+    var layerAdj = constants.layerNameToAdjective[layerName];
+
+    selection.select('.' + layerName)
+        .selectAll('path')
+            .attr('fill', 'none')
+            .call(Color.stroke, geoLayout[layerAdj + 'color'])
+            .call(Drawing.dashLine, '', geoLayout[layerAdj + 'width']);
+}
+
+function styleGraticule(selection, axisName, geoLayout) {
+    selection.select('.' + axisName + 'graticule')
+        .selectAll('path')
+            .attr('fill', 'none')
+            .call(Color.stroke, geoLayout[axisName].gridcolor)
+            .call(Drawing.dashLine, '', geoLayout[axisName].gridwidth);
+}
+
+proto.styleLayer = function(selection, layerName, geoLayout) {
+    var fillLayers = constants.fillLayers,
+        lineLayers = constants.lineLayers;
+
+    if(fillLayers.indexOf(layerName)!==-1) {
+        styleFillLayer(selection, layerName, geoLayout);
+    }
+    else if(lineLayers.indexOf(layerName)!==-1) {
+        styleLineLayer(selection, layerName, geoLayout);
+    }
+};
+
+proto.styleLayout = function(geoLayout) {
+    var gBaseLayer = this.framework.select('g.baselayer'),
+        baseLayers = constants.baseLayers,
+        axesNames = constants.axesNames,
+        layerName;
+
+    for(var i = 0; i < baseLayers.length; i++) {
+        layerName = baseLayers[i];
+
+        if(axesNames.indexOf(layerName)!==-1) {
+            styleGraticule(gBaseLayer, layerName, geoLayout);
+        }
+        else this.styleLayer(gBaseLayer, layerName, geoLayout);
+    }
+};
+
+// [hot code path] (re)draw all paths which depend on the projection
+proto.render = function() {
+    var framework = this.framework,
+        gChoropleth = framework.select('g.choroplethlayer'),
+        gScatterGeo = framework.select('g.scattergeolayer'),
+        projection = this.projection,
+        path = this.path,
+        clipAngle = this.clipAngle;
+
+    function translatePoints(d) {
+        var lonlat = projection([d.lon, d.lat]);
+        if(!lonlat) return null;
+        return 'translate(' + lonlat[0] + ',' + lonlat[1] + ')';
+    }
+
+    // hide paths over edges of clipped projections
+    function hideShowPoints(d) {
+        var p = projection.rotate(),
+            angle = d3.geo.distance([d.lon, d.lat], [-p[0], -p[1]]),
+            maxAngle = clipAngle * Math.PI / 180;
+        return (angle > maxAngle) ? '0' : '1.0';
+    }
+
+    framework.selectAll('path.basepath').attr('d', path);
+    framework.selectAll('path.graticulepath').attr('d', path);
+
+    gChoropleth.selectAll('path.choroplethlocation').attr('d', path);
+    gChoropleth.selectAll('path.basepath').attr('d', path);
+
+    gScatterGeo.selectAll('path.js-line').attr('d', path);
+
+    if(clipAngle !== null) {
+        gScatterGeo.selectAll('path.point')
+            .style('opacity', hideShowPoints)
+            .attr('transform', translatePoints);
+        gScatterGeo.selectAll('text')
+            .style('opacity', hideShowPoints)
+            .attr('transform', translatePoints);
+    }
+    else {
+        gScatterGeo.selectAll('path.point')
+            .attr('transform', translatePoints);
+        gScatterGeo.selectAll('text')
+            .attr('transform', translatePoints);
+    }
+};
+
+// create a mock axis used to format hover text
+function createMockAxis(fullLayout) {
+    var mockAxis = {
+        type: 'linear',
+        showexponent: 'all',
+        exponentformat: Axes.layoutAttributes.exponentformat.dflt,
+        _td: { _fullLayout: fullLayout }
+    };
+
+    Axes.setConvert(mockAxis);
+    return mockAxis;
+}
+
+},{"../../components/color":299,"../../components/drawing":317,"../../constants/geo_constants":334,"../../constants/xmlns_namespaces":338,"../../lib/topojson_utils":361,"../../plots/cartesian/axes":369,"./projections":391,"./set_scale":392,"./zoom":393,"./zoom_reset":394,"d3":70,"topojson":230}],385:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Geo = require('./geo');
+
+var Plots = require('../../plots/plots');
+
+
+exports.name = 'geo';
+
+exports.attr = 'geo';
+
+exports.idRoot = 'geo';
+
+exports.idRegex = /^geo([2-9]|[1-9][0-9]+)?$/;
+
+exports.attrRegex = /^geo([2-9]|[1-9][0-9]+)?$/;
+
+exports.attributes = require('./layout/attributes');
+
+exports.layoutAttributes = require('./layout/layout_attributes');
+
+exports.supplyLayoutDefaults = require('./layout/defaults');
+
+exports.plot = function plotGeo(gd) {
+    var fullLayout = gd._fullLayout,
+        fullData = gd._fullData,
+        geoIds = Plots.getSubplotIds(fullLayout, 'geo');
+
+    /**
+     * If 'plotly-geo-assets.js' is not included,
+     * initialize object to keep reference to every loaded topojson
+     */
+    if(window.PlotlyGeoAssets === undefined) {
+        window.PlotlyGeoAssets = { topojson: {} };
+    }
+
+    for(var i = 0; i < geoIds.length; i++) {
+        var geoId = geoIds[i],
+            fullGeoData = Plots.getSubplotData(fullData, 'geo', geoId),
+            geo = fullLayout[geoId]._geo;
+
+        // If geo is not instantiated, create one!
+        if(geo === undefined) {
+            geo = new Geo({
+                id: geoId,
+                graphDiv: gd,
+                container: fullLayout._geocontainer.node(),
+                topojsonURL: gd._context.topojsonURL
+            },
+                fullLayout
+            );
+
+            fullLayout[geoId]._geo = geo;
+        }
+
+        geo.plot(fullGeoData, fullLayout, gd._promises);
+    }
+};
+
+exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
+    var oldGeoKeys = Plots.getSubplotIds(oldFullLayout, 'geo');
+
+    for(var i = 0; i < oldGeoKeys.length; i++) {
+        var oldGeoKey = oldGeoKeys[i];
+        var oldGeo = oldFullLayout[oldGeoKey]._geo;
+
+        if(!newFullLayout[oldGeoKey] && !!oldGeo) {
+            oldGeo.geoDiv.remove();
+        }
+    }
+};
+
+},{"../../plots/plots":413,"./geo":384,"./layout/attributes":386,"./layout/defaults":389,"./layout/layout_attributes":390}],386:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+module.exports = {
+    geo: {
+        valType: 'geoid',
+        
+        dflt: 'geo',
+        
+    }
+};
+
+},{}],387:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var colorAttrs = require('../../../components/color/attributes');
+
+
+module.exports = {
+    range: {
+        valType: 'info_array',
+        
+        items: [
+            {valType: 'number'},
+            {valType: 'number'}
+        ],
+        
+    },
+    showgrid: {
+        valType: 'boolean',
+        
+        dflt: false,
+        
+    },
+    tick0: {
+        valType: 'number',
+        
+        
+    },
+    dtick: {
+        valType: 'number',
+        
+        
+    },
+    gridcolor: {
+        valType: 'color',
+        
+        dflt: colorAttrs.lightLine,
+        
+    },
+    gridwidth: {
+        valType: 'number',
+        
+        min: 0,
+        dflt: 1,
+        
+    }
+};
+
+},{"../../../components/color/attributes":298}],388:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../../lib');
+var constants = require('../../../constants/geo_constants');
+var axisAttributes = require('./axis_attributes');
+
+
+module.exports = function supplyGeoAxisLayoutDefaults(geoLayoutIn, geoLayoutOut) {
+    var axesNames = constants.axesNames;
+
+    var axisIn, axisOut;
+
+    function coerce(attr, dflt) {
+        return Lib.coerce(axisIn, axisOut, axisAttributes, attr, dflt);
+    }
+
+    function getRangeDflt(axisName) {
+        var scope = geoLayoutOut.scope;
+
+        var projLayout, projType, projRotation, rotateAngle, dfltSpans, halfSpan;
+
+        if(scope === 'world') {
+            projLayout = geoLayoutOut.projection;
+            projType = projLayout.type;
+            projRotation = projLayout.rotation;
+            dfltSpans = constants[axisName + 'Span'];
+
+            halfSpan = dfltSpans[projType]!==undefined ?
+                dfltSpans[projType] / 2 :
+                dfltSpans['*'] / 2;
+            rotateAngle = axisName==='lonaxis' ?
+                projRotation.lon :
+                projRotation.lat;
+
+            return [rotateAngle - halfSpan, rotateAngle + halfSpan];
+        }
+        else return constants.scopeDefaults[scope][axisName + 'Range'];
+    }
+
+    for(var i = 0; i < axesNames.length; i++) {
+        var axisName = axesNames[i];
+        axisIn = geoLayoutIn[axisName] || {};
+        axisOut = {};
+
+        var rangeDflt = getRangeDflt(axisName);
+
+        var range = coerce('range', rangeDflt);
+
+        Lib.noneOrAll(axisIn.range, axisOut.range, [0, 1]);
+
+        coerce('tick0', range[0]);
+        coerce('dtick', axisName==='lonaxis' ? 30 : 10);
+
+        var show = coerce('showgrid');
+        if(show) {
+            coerce('gridcolor');
+            coerce('gridwidth');
+        }
+
+        geoLayoutOut[axisName] = axisOut;
+        geoLayoutOut[axisName]._fullRange = rangeDflt;
+    }
+};
+
+},{"../../../constants/geo_constants":334,"../../../lib":349,"./axis_attributes":387}],389:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../../lib');
+var Plots = require('../../plots');
+var constants = require('../../../constants/geo_constants');
+var layoutAttributes = require('./layout_attributes');
+var supplyGeoAxisLayoutDefaults = require('./axis_defaults');
+
+
+module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
+    if(!layoutOut._hasGeo) return;
+
+    var geos = Plots.findSubplotIds(fullData, 'geo'),
+        geosLength = geos.length;
+
+    var geoLayoutIn, geoLayoutOut;
+
+    function coerce(attr, dflt) {
+        return Lib.coerce(geoLayoutIn, geoLayoutOut, layoutAttributes, attr, dflt);
+    }
+
+    for(var i = 0; i < geosLength; i++) {
+        var geo = geos[i];
+
+        // geo traces get a layout geo for free!
+        if(layoutIn[geo]) geoLayoutIn = layoutIn[geo];
+        else geoLayoutIn = layoutIn[geo] = {};
+
+        geoLayoutIn = layoutIn[geo];
+        geoLayoutOut = {};
+
+        coerce('domain.x');
+        coerce('domain.y', [i / geosLength, (i + 1) / geosLength]);
+
+        handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce);
+        layoutOut[geo] = geoLayoutOut;
+    }
+};
+
+function handleGeoDefaults(geoLayoutIn, geoLayoutOut, coerce) {
+    var show;
+
+    var scope = coerce('scope');
+    var isScoped = (scope !== 'world');
+    var scopeParams = constants.scopeDefaults[scope];
+
+    var resolution = coerce('resolution');
+
+    var projType = coerce('projection.type', scopeParams.projType);
+    var isAlbersUsa = projType==='albers usa';
+    var isConic = projType.indexOf('conic')!==-1;
+
+    if(isConic) {
+        var dfltProjParallels = scopeParams.projParallels || [0, 60];
+        coerce('projection.parallels', dfltProjParallels);
+    }
+
+    if(!isAlbersUsa) {
+        var dfltProjRotate = scopeParams.projRotate || [0, 0, 0];
+        coerce('projection.rotation.lon', dfltProjRotate[0]);
+        coerce('projection.rotation.lat', dfltProjRotate[1]);
+        coerce('projection.rotation.roll', dfltProjRotate[2]);
+
+        show = coerce('showcoastlines', !isScoped);
+        if(show) {
+            coerce('coastlinecolor');
+            coerce('coastlinewidth');
+        }
+
+        show = coerce('showocean');
+        if(show) coerce('oceancolor');
+    }
+    else geoLayoutOut.scope = 'usa';
+
+    coerce('projection.scale');
+
+    show = coerce('showland');
+    if(show) coerce('landcolor');
+
+    show = coerce('showlakes');
+    if(show) coerce('lakecolor');
+
+    show = coerce('showrivers');
+    if(show) {
+        coerce('rivercolor');
+        coerce('riverwidth');
+    }
+
+    show = coerce('showcountries', isScoped);
+    if(show) {
+        coerce('countrycolor');
+        coerce('countrywidth');
+    }
+
+    if(scope==='usa' || (scope==='north america' && resolution===50)) {
+        // Only works for:
+        //   USA states at 110m
+        //   USA states + Canada provinces at 50m
+        coerce('showsubunits', true);
+        coerce('subunitcolor');
+        coerce('subunitwidth');
+    }
+
+    if(!isScoped) {
+        // Does not work in non-world scopes
+        show = coerce('showframe', true);
+        if(show) {
+            coerce('framecolor');
+            coerce('framewidth');
+        }
+    }
+
+    coerce('bgcolor');
+
+    supplyGeoAxisLayoutDefaults(geoLayoutIn, geoLayoutOut);
+
+    // bind a few helper variables
+    geoLayoutOut._isHighRes = resolution===50;
+    geoLayoutOut._clipAngle = constants.lonaxisSpan[projType] / 2;
+    geoLayoutOut._isAlbersUsa = isAlbersUsa;
+    geoLayoutOut._isConic = isConic;
+    geoLayoutOut._isScoped = isScoped;
+
+    var rotation = geoLayoutOut.projection.rotation || {};
+    geoLayoutOut.projection._rotate = [
+        -rotation.lon || 0,
+        -rotation.lat || 0,
+        rotation.roll || 0
+    ];
+}
+
+},{"../../../constants/geo_constants":334,"../../../lib":349,"../../plots":413,"./axis_defaults":388,"./layout_attributes":390}],390:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var colorAttrs = require('../../../components/color/attributes');
+var constants = require('../../../constants/geo_constants');
+var geoAxesAttrs = require('./axis_attributes');
+
+
+module.exports = {
+    domain: {
+        x: {
+            valType: 'info_array',
+            
+            items: [
+                {valType: 'number', min: 0, max: 1},
+                {valType: 'number', min: 0, max: 1}
+            ],
+            dflt: [0, 1],
+            
+        },
+        y: {
+            valType: 'info_array',
+            
+            items: [
+                {valType: 'number', min: 0, max: 1},
+                {valType: 'number', min: 0, max: 1}
+            ],
+            dflt: [0, 1],
+            
+        }
+    },
+    resolution: {
+        valType: 'enumerated',
+        values: [110, 50],
+        
+        dflt: 110,
+        coerceNumber: true,
+        
+    },
+    scope: {
+        valType: 'enumerated',
+        
+        values: Object.keys(constants.scopeDefaults),
+        dflt: 'world',
+        
+    },
+    projection: {
+        type: {
+            valType: 'enumerated',
+            
+            values: Object.keys(constants.projNames),
+            
+        },
+        rotation: {
+            lon: {
+                valType: 'number',
+                
+                
+            },
+            lat: {
+                valType: 'number',
+                
+                
+            },
+            roll: {
+                valType: 'number',
+                
+                
+            }
+        },
+        parallels: {
+            valType: 'info_array',
+            
+            items: [
+                {valType: 'number'},
+                {valType: 'number'}
+            ],
+            
+        },
+        scale: {
+            valType: 'number',
+            
+            min: 0,
+            max: 10,
+            dflt: 1,
+            
+        }
+    },
+    showcoastlines: {
+        valType: 'boolean',
+        
+        
+    },
+    coastlinecolor: {
+        valType: 'color',
+        
+        dflt: colorAttrs.defaultLine,
+        
+    },
+    coastlinewidth: {
+        valType: 'number',
+        
+        min: 0,
+        dflt: 1,
+        
+    },
+    showland: {
+        valType: 'boolean',
+        
+        dflt: false,
+        
+    },
+    landcolor: {
+        valType: 'color',
+        
+        dflt: constants.landColor,
+        
+    },
+    showocean: {
+        valType: 'boolean',
+        
+        dflt: false,
+        
+    },
+    oceancolor: {
+        valType: 'color',
+        
+        dflt: constants.waterColor,
+        
+    },
+    showlakes: {
+        valType: 'boolean',
+        
+        dflt: false,
+        
+    },
+    lakecolor: {
+        valType: 'color',
+        
+        dflt: constants.waterColor,
+        
+    },
+    showrivers: {
+        valType: 'boolean',
+        
+        dflt: false,
+        
+    },
+    rivercolor: {
+        valType: 'color',
+        
+        dflt: constants.waterColor,
+        
+    },
+    riverwidth: {
+        valType: 'number',
+        
+        min: 0,
+        dflt: 1,
+        
+    },
+    showcountries: {
+        valType: 'boolean',
+        
+        
+    },
+    countrycolor: {
+        valType: 'color',
+        
+        dflt: colorAttrs.defaultLine,
+        
+    },
+    countrywidth: {
+        valType: 'number',
+        
+        min: 0,
+        dflt: 1,
+        
+    },
+    showsubunits: {
+        valType: 'boolean',
+        
+        
+    },
+    subunitcolor: {
+        valType: 'color',
+        
+        dflt: colorAttrs.defaultLine,
+        
+    },
+    subunitwidth: {
+        valType: 'number',
+        
+        min: 0,
+        dflt: 1,
+        
+    },
+    showframe: {
+        valType: 'boolean',
+        
+        
+    },
+    framecolor: {
+        valType: 'color',
+        
+        dflt: colorAttrs.defaultLine,
+        
+    },
+    framewidth: {
+        valType: 'number',
+        
+        min: 0,
+        dflt: 1,
+        
+    },
+    bgcolor: {
+        valType: 'color',
+        
+        dflt: colorAttrs.background,
+        
+    },
+    lonaxis: geoAxesAttrs,
+    lataxis: geoAxesAttrs
+};
+
+},{"../../../components/color/attributes":298,"../../../constants/geo_constants":334,"./axis_attributes":387}],391:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+/**
+ * Forked from https://github.com/d3/d3-geo-projection
+ * Pasted from https://github.com/etpinard/d3-geo-projection
+ *
+ * Containing only the 'most useful' projection types
+ * and compatible with CommonJs
+ *
+ */
+
+var d3 = require('d3');
+
+function addProjectionToD3() {
+  d3.geo.project = function(object, projection) {
+    var stream = projection.stream;
+    if (!stream) throw new Error("not yet supported");
+    return (object && d3_geo_projectObjectType.hasOwnProperty(object.type) ? d3_geo_projectObjectType[object.type] : d3_geo_projectGeometry)(object, stream);
+  };
+  function d3_geo_projectFeature(object, stream) {
+    return {
+      type: "Feature",
+      id: object.id,
+      properties: object.properties,
+      geometry: d3_geo_projectGeometry(object.geometry, stream)
+    };
+  }
+  function d3_geo_projectGeometry(geometry, stream) {
+    if (!geometry) return null;
+    if (geometry.type === "GeometryCollection") return {
+      type: "GeometryCollection",
+      geometries: object.geometries.map(function(geometry) {
+        return d3_geo_projectGeometry(geometry, stream);
+      })
+    };
+    if (!d3_geo_projectGeometryType.hasOwnProperty(geometry.type)) return null;
+    var sink = d3_geo_projectGeometryType[geometry.type];
+    d3.geo.stream(geometry, stream(sink));
+    return sink.result();
+  }
+  var d3_geo_projectObjectType = {
+    Feature: d3_geo_projectFeature,
+    FeatureCollection: function(object, stream) {
+      return {
+        type: "FeatureCollection",
+        features: object.features.map(function(feature) {
+          return d3_geo_projectFeature(feature, stream);
+        })
+      };
+    }
+  };
+  var d3_geo_projectPoints = [], d3_geo_projectLines = [];
+  var d3_geo_projectPoint = {
+    point: function(x, y) {
+      d3_geo_projectPoints.push([ x, y ]);
+    },
+    result: function() {
+      var result = !d3_geo_projectPoints.length ? null : d3_geo_projectPoints.length < 2 ? {
+        type: "Point",
+        coordinates: d3_geo_projectPoints[0]
+      } : {
+        type: "MultiPoint",
+        coordinates: d3_geo_projectPoints
+      };
+      d3_geo_projectPoints = [];
+      return result;
+    }
+  };
+  var d3_geo_projectLine = {
+    lineStart: d3_geo_projectNoop,
+    point: function(x, y) {
+      d3_geo_projectPoints.push([ x, y ]);
+    },
+    lineEnd: function() {
+      if (d3_geo_projectPoints.length) d3_geo_projectLines.push(d3_geo_projectPoints),
+      d3_geo_projectPoints = [];
+    },
+    result: function() {
+      var result = !d3_geo_projectLines.length ? null : d3_geo_projectLines.length < 2 ? {
+        type: "LineString",
+        coordinates: d3_geo_projectLines[0]
+      } : {
+        type: "MultiLineString",
+        coordinates: d3_geo_projectLines
+      };
+      d3_geo_projectLines = [];
+      return result;
+    }
+  };
+  var d3_geo_projectPolygon = {
+    polygonStart: d3_geo_projectNoop,
+    lineStart: d3_geo_projectNoop,
+    point: function(x, y) {
+      d3_geo_projectPoints.push([ x, y ]);
+    },
+    lineEnd: function() {
+      var n = d3_geo_projectPoints.length;
+      if (n) {
+        do d3_geo_projectPoints.push(d3_geo_projectPoints[0].slice()); while (++n < 4);
+        d3_geo_projectLines.push(d3_geo_projectPoints), d3_geo_projectPoints = [];
+      }
+    },
+    polygonEnd: d3_geo_projectNoop,
+    result: function() {
+      if (!d3_geo_projectLines.length) return null;
+      var polygons = [], holes = [];
+      d3_geo_projectLines.forEach(function(ring) {
+        if (d3_geo_projectClockwise(ring)) polygons.push([ ring ]); else holes.push(ring);
+      });
+      holes.forEach(function(hole) {
+        var point = hole[0];
+        polygons.some(function(polygon) {
+          if (d3_geo_projectContains(polygon[0], point)) {
+            polygon.push(hole);
+            return true;
+          }
+        }) || polygons.push([ hole ]);
+      });
+      d3_geo_projectLines = [];
+      return !polygons.length ? null : polygons.length > 1 ? {
+        type: "MultiPolygon",
+        coordinates: polygons
+      } : {
+        type: "Polygon",
+        coordinates: polygons[0]
+      };
+    }
+  };
+  var d3_geo_projectGeometryType = {
+    Point: d3_geo_projectPoint,
+    MultiPoint: d3_geo_projectPoint,
+    LineString: d3_geo_projectLine,
+    MultiLineString: d3_geo_projectLine,
+    Polygon: d3_geo_projectPolygon,
+    MultiPolygon: d3_geo_projectPolygon,
+    Sphere: d3_geo_projectPolygon
+  };
+  function d3_geo_projectNoop() {}
+  function d3_geo_projectClockwise(ring) {
+    if ((n = ring.length) < 4) return false;
+    var i = 0, n, area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1];
+    while (++i < n) area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1];
+    return area <= 0;
+  }
+  function d3_geo_projectContains(ring, point) {
+    var x = point[0], y = point[1], contains = false;
+    for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) {
+      var pi = ring[i], xi = pi[0], yi = pi[1], pj = ring[j], xj = pj[0], yj = pj[1];
+      if (yi > y ^ yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi) contains = !contains;
+    }
+    return contains;
+  }
+  var Îµ = 1e-6, Îµ2 = Îµ * Îµ, Ï = Math.PI, halfÏ = Ï / 2, sqrtÏ = Math.sqrt(Ï), radians = Ï / 180, degrees = 180 / Ï;
+  function sinci(x) {
+    return x ? x / Math.sin(x) : 1;
+  }
+  function sgn(x) {
+    return x > 0 ? 1 : x < 0 ? -1 : 0;
+  }
+  function asin(x) {
+    return x > 1 ? halfÏ : x < -1 ? -halfÏ : Math.asin(x);
+  }
+  function acos(x) {
+    return x > 1 ? 0 : x < -1 ? Ï : Math.acos(x);
+  }
+  function asqrt(x) {
+    return x > 0 ? Math.sqrt(x) : 0;
+  }
+  var projection = d3.geo.projection, projectionMutator = d3.geo.projectionMutator;
+  d3.geo.interrupt = function(project) {
+    var lobes = [ [ [ [ -Ï, 0 ], [ 0, halfÏ ], [ Ï, 0 ] ] ], [ [ [ -Ï, 0 ], [ 0, -halfÏ ], [ Ï, 0 ] ] ] ];
+    var bounds;
+    function forward(Î», Ï) {
+      var sign = Ï < 0 ? -1 : +1, hemilobes = lobes[+(Ï < 0)];
+      for (var i = 0, n = hemilobes.length - 1; i < n && Î» > hemilobes[i][2][0]; ++i) ;
+      var coordinates = project(Î» - hemilobes[i][1][0], Ï);
+      coordinates[0] += project(hemilobes[i][1][0], sign * Ï > sign * hemilobes[i][0][1] ? hemilobes[i][0][1] : Ï)[0];
+      return coordinates;
+    }
+    function reset() {
+      bounds = lobes.map(function(hemilobes) {
+        return hemilobes.map(function(lobe) {
+          var x0 = project(lobe[0][0], lobe[0][1])[0], x1 = project(lobe[2][0], lobe[2][1])[0], y0 = project(lobe[1][0], lobe[0][1])[1], y1 = project(lobe[1][0], lobe[1][1])[1], t;
+          if (y0 > y1) t = y0, y0 = y1, y1 = t;
+          return [ [ x0, y0 ], [ x1, y1 ] ];
+        });
+      });
+    }
+    if (project.invert) forward.invert = function(x, y) {
+      var hemibounds = bounds[+(y < 0)], hemilobes = lobes[+(y < 0)];
+      for (var i = 0, n = hemibounds.length; i < n; ++i) {
+        var b = hemibounds[i];
+        if (b[0][0] <= x && x < b[1][0] && b[0][1] <= y && y < b[1][1]) {
+          var coordinates = project.invert(x - project(hemilobes[i][1][0], 0)[0], y);
+          coordinates[0] += hemilobes[i][1][0];
+          return pointEqual(forward(coordinates[0], coordinates[1]), [ x, y ]) ? coordinates : null;
+        }
+      }
+    };
+    var projection = d3.geo.projection(forward), stream_ = projection.stream;
+    projection.stream = function(stream) {
+      var rotate = projection.rotate(), rotateStream = stream_(stream), sphereStream = (projection.rotate([ 0, 0 ]),
+      stream_(stream));
+      projection.rotate(rotate);
+      rotateStream.sphere = function() {
+        d3.geo.stream(sphere(), sphereStream);
+      };
+      return rotateStream;
+    };
+    projection.lobes = function(_) {
+      if (!arguments.length) return lobes.map(function(lobes) {
+        return lobes.map(function(lobe) {
+          return [ [ lobe[0][0] * 180 / Ï, lobe[0][1] * 180 / Ï ], [ lobe[1][0] * 180 / Ï, lobe[1][1] * 180 / Ï ], [ lobe[2][0] * 180 / Ï, lobe[2][1] * 180 / Ï ] ];
+        });
+      });
+      lobes = _.map(function(lobes) {
+        return lobes.map(function(lobe) {
+          return [ [ lobe[0][0] * Ï / 180, lobe[0][1] * Ï / 180 ], [ lobe[1][0] * Ï / 180, lobe[1][1] * Ï / 180 ], [ lobe[2][0] * Ï / 180, lobe[2][1] * Ï / 180 ] ];
+        });
+      });
+      reset();
+      return projection;
+    };
+    function sphere() {
+      var Îµ = 1e-6, coordinates = [];
+      for (var i = 0, n = lobes[0].length; i < n; ++i) {
+        var lobe = lobes[0][i], Î»0 = lobe[0][0] * 180 / Ï, Ï0 = lobe[0][1] * 180 / Ï, Ï1 = lobe[1][1] * 180 / Ï, Î»2 = lobe[2][0] * 180 / Ï, Ï2 = lobe[2][1] * 180 / Ï;
+        coordinates.push(resample([ [ Î»0 + Îµ, Ï0 + Îµ ], [ Î»0 + Îµ, Ï1 - Îµ ], [ Î»2 - Îµ, Ï1 - Îµ ], [ Î»2 - Îµ, Ï2 + Îµ ] ], 30));
+      }
+      for (var i = lobes[1].length - 1; i >= 0; --i) {
+        var lobe = lobes[1][i], Î»0 = lobe[0][0] * 180 / Ï, Ï0 = lobe[0][1] * 180 / Ï, Ï1 = lobe[1][1] * 180 / Ï, Î»2 = lobe[2][0] * 180 / Ï, Ï2 = lobe[2][1] * 180 / Ï;
+        coordinates.push(resample([ [ Î»2 - Îµ, Ï2 - Îµ ], [ Î»2 - Îµ, Ï1 + Îµ ], [ Î»0 + Îµ, Ï1 + Îµ ], [ Î»0 + Îµ, Ï0 - Îµ ] ], 30));
+      }
+      return {
+        type: "Polygon",
+        coordinates: [ d3.merge(coordinates) ]
+      };
+    }
+    function resample(coordinates, m) {
+      var i = -1, n = coordinates.length, p0 = coordinates[0], p1, dx, dy, resampled = [];
+      while (++i < n) {
+        p1 = coordinates[i];
+        dx = (p1[0] - p0[0]) / m;
+        dy = (p1[1] - p0[1]) / m;
+        for (var j = 0; j < m; ++j) resampled.push([ p0[0] + j * dx, p0[1] + j * dy ]);
+        p0 = p1;
+      }
+      resampled.push(p1);
+      return resampled;
+    }
+    function pointEqual(a, b) {
+      return Math.abs(a[0] - b[0]) < Îµ && Math.abs(a[1] - b[1]) < Îµ;
+    }
+    return projection;
+  };
+  function eckert4(Î», Ï) {
+    var k = (2 + halfÏ) * Math.sin(Ï);
+    Ï /= 2;
+    for (var i = 0, ÎŽ = Infinity; i < 10 && Math.abs(ÎŽ) > Îµ; i++) {
+      var cosÏ = Math.cos(Ï);
+      Ï -= ÎŽ = (Ï + Math.sin(Ï) * (cosÏ + 2) - k) / (2 * cosÏ * (1 + cosÏ));
+    }
+    return [ 2 / Math.sqrt(Ï * (4 + Ï)) * Î» * (1 + Math.cos(Ï)), 2 * Math.sqrt(Ï / (4 + Ï)) * Math.sin(Ï) ];
+  }
+  eckert4.invert = function(x, y) {
+    var A = .5 * y * Math.sqrt((4 + Ï) / Ï), k = asin(A), c = Math.cos(k);
+    return [ x / (2 / Math.sqrt(Ï * (4 + Ï)) * (1 + c)), asin((k + A * (c + 2)) / (2 + halfÏ)) ];
+  };
+  (d3.geo.eckert4 = function() {
+    return projection(eckert4);
+  }).raw = eckert4;
+  var hammerAzimuthalEqualArea = d3.geo.azimuthalEqualArea.raw;
+  function hammer(A, B) {
+    if (arguments.length < 2) B = A;
+    if (B === 1) return hammerAzimuthalEqualArea;
+    if (B === Infinity) return hammerQuarticAuthalic;
+    function forward(Î», Ï) {
+      var coordinates = hammerAzimuthalEqualArea(Î» / B, Ï);
+      coordinates[0] *= A;
+      return coordinates;
+    }
+    forward.invert = function(x, y) {
+      var coordinates = hammerAzimuthalEqualArea.invert(x / A, y);
+      coordinates[0] *= B;
+      return coordinates;
+    };
+    return forward;
+  }
+  function hammerProjection() {
+    var B = 2, m = projectionMutator(hammer), p = m(B);
+    p.coefficient = function(_) {
+      if (!arguments.length) return B;
+      return m(B = +_);
+    };
+    return p;
+  }
+  function hammerQuarticAuthalic(Î», Ï) {
+    return [ Î» * Math.cos(Ï) / Math.cos(Ï /= 2), 2 * Math.sin(Ï) ];
+  }
+  hammerQuarticAuthalic.invert = function(x, y) {
+    var Ï = 2 * asin(y / 2);
+    return [ x * Math.cos(Ï / 2) / Math.cos(Ï), Ï ];
+  };
+  (d3.geo.hammer = hammerProjection).raw = hammer;
+  function kavrayskiy7(Î», Ï) {
+    return [ 3 * Î» / (2 * Ï) * Math.sqrt(Ï * Ï / 3 - Ï * Ï), Ï ];
+  }
+  kavrayskiy7.invert = function(x, y) {
+    return [ 2 / 3 * Ï * x / Math.sqrt(Ï * Ï / 3 - y * y), y ];
+  };
+  (d3.geo.kavrayskiy7 = function() {
+    return projection(kavrayskiy7);
+  }).raw = kavrayskiy7;
+  function miller(Î», Ï) {
+    return [ Î», 1.25 * Math.log(Math.tan(Ï / 4 + .4 * Ï)) ];
+  }
+  miller.invert = function(x, y) {
+    return [ x, 2.5 * Math.atan(Math.exp(.8 * y)) - .625 * Ï ];
+  };
+  (d3.geo.miller = function() {
+    return projection(miller);
+  }).raw = miller;
+  function mollweideBromleyÎž(Cp) {
+    return function(Îž) {
+      var CpsinÎž = Cp * Math.sin(Îž), i = 30, ÎŽ;
+      do Îž -= ÎŽ = (Îž + Math.sin(Îž) - CpsinÎž) / (1 + Math.cos(Îž)); while (Math.abs(ÎŽ) > Îµ && --i > 0);
+      return Îž / 2;
+    };
+  }
+  function mollweideBromley(Cx, Cy, Cp) {
+    var Îž = mollweideBromleyÎž(Cp);
+    function forward(Î», Ï) {
+      return [ Cx * Î» * Math.cos(Ï = Îž(Ï)), Cy * Math.sin(Ï) ];
+    }
+    forward.invert = function(x, y) {
+      var Îž = asin(y / Cy);
+      return [ x / (Cx * Math.cos(Îž)), asin((2 * Îž + Math.sin(2 * Îž)) / Cp) ];
+    };
+    return forward;
+  }
+  var mollweideÎž = mollweideBromleyÎž(Ï), mollweide = mollweideBromley(Math.SQRT2 / halfÏ, Math.SQRT2, Ï);
+  (d3.geo.mollweide = function() {
+    return projection(mollweide);
+  }).raw = mollweide;
+  function naturalEarth(Î», Ï) {
+    var Ï2 = Ï * Ï, Ï4 = Ï2 * Ï2;
+    return [ Î» * (.8707 - .131979 * Ï2 + Ï4 * (-.013791 + Ï4 * (.003971 * Ï2 - .001529 * Ï4))), Ï * (1.007226 + Ï2 * (.015085 + Ï4 * (-.044475 + .028874 * Ï2 - .005916 * Ï4))) ];
+  }
+  naturalEarth.invert = function(x, y) {
+    var Ï = y, i = 25, ÎŽ;
+    do {
+      var Ï2 = Ï * Ï, Ï4 = Ï2 * Ï2;
+      Ï -= ÎŽ = (Ï * (1.007226 + Ï2 * (.015085 + Ï4 * (-.044475 + .028874 * Ï2 - .005916 * Ï4))) - y) / (1.007226 + Ï2 * (.015085 * 3 + Ï4 * (-.044475 * 7 + .028874 * 9 * Ï2 - .005916 * 11 * Ï4)));
+    } while (Math.abs(ÎŽ) > Îµ && --i > 0);
+    return [ x / (.8707 + (Ï2 = Ï * Ï) * (-.131979 + Ï2 * (-.013791 + Ï2 * Ï2 * Ï2 * (.003971 - .001529 * Ï2)))), Ï ];
+  };
+  (d3.geo.naturalEarth = function() {
+    return projection(naturalEarth);
+  }).raw = naturalEarth;
+  var robinsonConstants = [ [ .9986, -.062 ], [ 1, 0 ], [ .9986, .062 ], [ .9954, .124 ], [ .99, .186 ], [ .9822, .248 ], [ .973, .31 ], [ .96, .372 ], [ .9427, .434 ], [ .9216, .4958 ], [ .8962, .5571 ], [ .8679, .6176 ], [ .835, .6769 ], [ .7986, .7346 ], [ .7597, .7903 ], [ .7186, .8435 ], [ .6732, .8936 ], [ .6213, .9394 ], [ .5722, .9761 ], [ .5322, 1 ] ];
+  robinsonConstants.forEach(function(d) {
+    d[1] *= 1.0144;
+  });
+  function robinson(Î», Ï) {
+    var i = Math.min(18, Math.abs(Ï) * 36 / Ï), i0 = Math.floor(i), di = i - i0, ax = (k = robinsonConstants[i0])[0], ay = k[1], bx = (k = robinsonConstants[++i0])[0], by = k[1], cx = (k = robinsonConstants[Math.min(19, ++i0)])[0], cy = k[1], k;
+    return [ Î» * (bx + di * (cx - ax) / 2 + di * di * (cx - 2 * bx + ax) / 2), (Ï > 0 ? halfÏ : -halfÏ) * (by + di * (cy - ay) / 2 + di * di * (cy - 2 * by + ay) / 2) ];
+  }
+  robinson.invert = function(x, y) {
+    var yy = y / halfÏ, Ï = yy * 90, i = Math.min(18, Math.abs(Ï / 5)), i0 = Math.max(0, Math.floor(i));
+    do {
+      var ay = robinsonConstants[i0][1], by = robinsonConstants[i0 + 1][1], cy = robinsonConstants[Math.min(19, i0 + 2)][1], u = cy - ay, v = cy - 2 * by + ay, t = 2 * (Math.abs(yy) - by) / u, c = v / u, di = t * (1 - c * t * (1 - 2 * c * t));
+      if (di >= 0 || i0 === 1) {
+        Ï = (y >= 0 ? 5 : -5) * (di + i);
+        var j = 50, ÎŽ;
+        do {
+          i = Math.min(18, Math.abs(Ï) / 5);
+          i0 = Math.floor(i);
+          di = i - i0;
+          ay = robinsonConstants[i0][1];
+          by = robinsonConstants[i0 + 1][1];
+          cy = robinsonConstants[Math.min(19, i0 + 2)][1];
+          Ï -= (ÎŽ = (y >= 0 ? halfÏ : -halfÏ) * (by + di * (cy - ay) / 2 + di * di * (cy - 2 * by + ay) / 2) - y) * degrees;
+        } while (Math.abs(ÎŽ) > Îµ2 && --j > 0);
+        break;
+      }
+    } while (--i0 >= 0);
+    var ax = robinsonConstants[i0][0], bx = robinsonConstants[i0 + 1][0], cx = robinsonConstants[Math.min(19, i0 + 2)][0];
+    return [ x / (bx + di * (cx - ax) / 2 + di * di * (cx - 2 * bx + ax) / 2), Ï * radians ];
+  };
+  (d3.geo.robinson = function() {
+    return projection(robinson);
+  }).raw = robinson;
+  function sinusoidal(Î», Ï) {
+    return [ Î» * Math.cos(Ï), Ï ];
+  }
+  sinusoidal.invert = function(x, y) {
+    return [ x / Math.cos(y), y ];
+  };
+  (d3.geo.sinusoidal = function() {
+    return projection(sinusoidal);
+  }).raw = sinusoidal;
+}
+
+module.exports = addProjectionToD3;
+
+},{"d3":70}],392:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var clipPad = require('../../constants/geo_constants').clipPad;
+
+function createGeoScale(geoLayout, graphSize) {
+    var projLayout = geoLayout.projection,
+        lonaxisLayout = geoLayout.lonaxis,
+        lataxisLayout = geoLayout.lataxis,
+        geoDomain = geoLayout.domain,
+        frameWidth = geoLayout.framewidth || 0;
+
+    // width & height the geo div
+    var geoWidth = graphSize.w * (geoDomain.x[1] - geoDomain.x[0]),
+        geoHeight = graphSize.h * (geoDomain.y[1] - geoDomain.y[0]);
+
+    // add padding around range to avoid aliasing
+    var lon0 = lonaxisLayout.range[0] + clipPad,
+        lon1 = lonaxisLayout.range[1] - clipPad,
+        lat0 = lataxisLayout.range[0] + clipPad,
+        lat1 = lataxisLayout.range[1] - clipPad,
+        lonfull0 = lonaxisLayout._fullRange[0] + clipPad,
+        lonfull1 = lonaxisLayout._fullRange[1] - clipPad,
+        latfull0 = lataxisLayout._fullRange[0] + clipPad,
+        latfull1 = lataxisLayout._fullRange[1] - clipPad;
+
+    // initial translation (makes the math easier)
+    projLayout._translate0 = [
+        graphSize.l + geoWidth / 2, graphSize.t + geoHeight / 2
+    ];
+
+
+    // center of the projection is given by
+    // the lon/lat ranges and the rotate angle
+    var dlon = lon1 - lon0,
+        dlat = lat1 - lat0,
+        c0 = [lon0 + dlon / 2, lat0 + dlat / 2],
+        r = projLayout._rotate;
+
+    projLayout._center = [c0[0] + r[0], c0[1] + r[1]];
+
+    // needs a initial projection; it is called from makeProjection
+    var setScale = function(projection) {
+        var scale0 = projection.scale(),
+            translate0 = projLayout._translate0,
+            rangeBox = makeRangeBox(lon0, lat0, lon1, lat1),
+            fullRangeBox = makeRangeBox(lonfull0, latfull0, lonfull1, latfull1);
+
+        var scale, translate, bounds, fullBounds;
+
+        // Inspired by: http://stackoverflow.com/a/14654988/4068492
+        // using the path determine the bounds of the current map and use
+        // these to determine better values for the scale and translation
+
+        function getScale(bounds) {
+            return Math.min(
+                scale0 * geoWidth / (bounds[1][0] - bounds[0][0]),
+                scale0 * geoHeight / (bounds[1][1] - bounds[0][1])
+            );
+        }
+
+        // scale projection given how range box get deformed
+        // by the projection
+        bounds = getBounds(projection, rangeBox);
+        scale = getScale(bounds);
+
+        // similarly, get scale at full range
+        fullBounds = getBounds(projection, fullRangeBox);
+        projLayout._fullScale = getScale(fullBounds);
+
+        projection.scale(scale);
+
+        // translate the projection so that the top-left corner
+        // of the range box is at the top-left corner of the viewbox
+        bounds = getBounds(projection, rangeBox);
+        translate = [
+            translate0[0] - bounds[0][0] + frameWidth,
+            translate0[1] - bounds[0][1] + frameWidth
+        ];
+        projLayout._translate = translate;
+        projection.translate(translate);
+
+        // clip regions out of the range box
+        // (these are clipping along horizontal/vertical lines)
+        bounds = getBounds(projection, rangeBox);
+        if(!geoLayout._isAlbersUsa) projection.clipExtent(bounds);
+
+        // adjust scale one more time with the 'scale' attribute
+        scale = projLayout.scale * scale;
+
+        // set projection scale and save it
+        projLayout._scale = scale;
+
+        // save the effective width & height of the geo framework
+        geoLayout._width = Math.round(bounds[1][0]) + frameWidth;
+        geoLayout._height = Math.round(bounds[1][1]) + frameWidth;
+
+        // save the margin length induced by the map scaling
+        geoLayout._marginX = (geoWidth - Math.round(bounds[1][0])) / 2;
+        geoLayout._marginY = (geoHeight - Math.round(bounds[1][1])) / 2;
+    };
+
+    return setScale;
+}
+
+module.exports = createGeoScale;
+
+// polygon GeoJSON corresponding to lon/lat range box
+// with well-defined direction
+function makeRangeBox(lon0, lat0, lon1, lat1) {
+    var dlon4 = (lon1 - lon0) / 4;
+
+    // TODO is this enough to handle ALL cases?
+    // -- this makes scaling less precise than using d3.geo.graticule
+    //    as great circles can overshoot the boundary
+    //    (that's not a big deal I think)
+    return {
+        type: 'Polygon',
+        coordinates: [
+          [ [lon0, lat0],
+            [lon0 , lat1],
+            [lon0 + dlon4, lat1],
+            [lon0 + 2 * dlon4, lat1],
+            [lon0 + 3 * dlon4, lat1],
+            [lon1, lat1],
+            [lon1, lat0],
+            [lon1 - dlon4, lat0],
+            [lon1 - 2 * dlon4, lat0],
+            [lon1 - 3 * dlon4, lat0],
+            [lon0, lat0] ]
+        ]
+    };
+}
+
+// bounds array [[top, left], [bottom, right]]
+// of the lon/lat range box
+function getBounds(projection, rangeBox) {
+    return d3.geo.path().projection(projection).bounds(rangeBox);
+}
+
+},{"../../constants/geo_constants":334,"d3":70}],393:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var radians = Math.PI / 180,
+    degrees = 180 / Math.PI,
+    zoomstartStyle = { cursor: 'pointer' },
+    zoomendStyle = { cursor: 'auto' };
+
+
+function createGeoZoom(geo, geoLayout) {
+    var zoomConstructor;
+
+    if(geoLayout._isScoped) zoomConstructor = zoomScoped;
+    else if(geoLayout._clipAngle) zoomConstructor = zoomClipped;
+    else zoomConstructor = zoomNonClipped;
+
+    // TODO add a conic-specific zoom
+
+    return zoomConstructor(geo, geoLayout.projection);
+}
+
+module.exports = createGeoZoom;
+
+// common to all zoom types
+function initZoom(projection, projLayout) {
+    var fullScale = projLayout._fullScale;
+
+    return d3.behavior.zoom()
+        .translate(projection.translate())
+        .scale(projection.scale())
+        .scaleExtent([0.5 * fullScale, 100 * fullScale]);
+}
+
+// zoom for scoped projections
+function zoomScoped(geo, projLayout) {
+    var projection = geo.projection,
+        zoom = initZoom(projection, projLayout);
+
+    function handleZoomstart() {
+        d3.select(this).style(zoomstartStyle);
+    }
+
+    function handleZoom() {
+        projection
+            .scale(d3.event.scale)
+            .translate(d3.event.translate);
+
+        geo.render();
+    }
+
+    function handleZoomend() {
+        d3.select(this).style(zoomendStyle);
+    }
+
+    zoom
+        .on('zoomstart', handleZoomstart)
+        .on('zoom', handleZoom)
+        .on('zoomend', handleZoomend);
+
+    return zoom;
+}
+
+// zoom for non-clipped projections
+function zoomNonClipped(geo, projLayout) {
+    var projection = geo.projection,
+        zoom = initZoom(projection, projLayout);
+
+    var INSIDETOLORANCEPXS = 2;
+
+    var mouse0, rotate0, translate0, lastRotate, zoomPoint,
+        mouse1, rotate1, point1;
+
+    function position(x) { return projection.invert(x); }
+
+    function outside(x) {
+        var pt = projection(position(x));
+        return (Math.abs(pt[0] - x[0]) > INSIDETOLORANCEPXS ||
+                Math.abs(pt[1] - x[1]) > INSIDETOLORANCEPXS);
+    }
+
+    function handleZoomstart() {
+        d3.select(this).style(zoomstartStyle);
+
+        mouse0 = d3.mouse(this);
+        rotate0 = projection.rotate();
+        translate0 = projection.translate();
+        lastRotate = rotate0;
+        zoomPoint = position(mouse0);
+    }
+
+    function handleZoom() {
+        mouse1 = d3.mouse(this);
+
+        if(outside(mouse0)) {
+            zoom.scale(projection.scale());
+            zoom.translate(projection.translate());
+            return;
+        }
+
+        projection.scale(d3.event.scale);
+
+        projection.translate([translate0[0], d3.event.translate[1]]);
+
+        if(!zoomPoint) {
+            mouse0 = mouse1;
+            zoomPoint = position(mouse0);
+        }
+        else if(position(mouse1)) {
+            point1 = position(mouse1);
+            rotate1 = [lastRotate[0] + (point1[0] - zoomPoint[0]), rotate0[1], rotate0[2]];
+            projection.rotate(rotate1);
+            lastRotate = rotate1;
+        }
+
+        geo.render();
+    }
+
+    function handleZoomend() {
+        d3.select(this).style(zoomendStyle);
+
+        // or something like
+        // http://www.jasondavies.com/maps/gilbert/
+        // ... a little harder with multiple base layers
+    }
+
+    zoom
+        .on('zoomstart', handleZoomstart)
+        .on('zoom', handleZoom)
+        .on('zoomend', handleZoomend);
+
+    return zoom;
+}
+
+// zoom for clipped projections
+// inspired by https://www.jasondavies.com/maps/d3.geo.zoom.js
+function zoomClipped(geo, projLayout) {
+    var projection = geo.projection,
+        view = {r: projection.rotate(), k: projection.scale()},
+        zoom = initZoom(projection, projLayout),
+        event = d3_eventDispatch(zoom, 'zoomstart', 'zoom', 'zoomend'),
+        zooming = 0,
+        zoomOn = zoom.on;
+
+    var zoomPoint;
+
+    zoom.on('zoomstart', function() {
+        d3.select(this).style(zoomstartStyle);
+
+        var mouse0 = d3.mouse(this),
+            rotate0 = projection.rotate(),
+            lastRotate = rotate0,
+            translate0 = projection.translate(),
+            q = quaternionFromEuler(rotate0);
+
+        zoomPoint = position(projection, mouse0);
+
+        zoomOn.call(zoom, 'zoom', function() {
+            var mouse1 = d3.mouse(this);
+
+            projection.scale(view.k = d3.event.scale);
+
+            if(!zoomPoint) {
+                // if no zoomPoint, the mouse wasn't over the actual geography yet
+                // maybe this point is the start... we'll find out next time!
+                mouse0 = mouse1;
+                zoomPoint = position(projection, mouse0);
+            }
+            // check if the point is on the map
+            // if not, don't do anything new but scale
+            // if it is, then we can assume between will exist below
+            // so we don't need the 'bank' function, whatever that is.
+            // TODO: is this right?
+            else if(position(projection, mouse1)) {
+                // go back to original projection temporarily
+                // except for scale... that's kind of independent?
+                projection
+                    .rotate(rotate0)
+                    .translate(translate0);
+
+                // calculate the new params
+                var point1 = position(projection, mouse1),
+                    between = rotateBetween(zoomPoint, point1),
+                    newEuler = eulerFromQuaternion(multiply(q, between)),
+                    rotateAngles = view.r = unRoll(newEuler, zoomPoint, lastRotate);
+
+                if(!isFinite(rotateAngles[0]) || !isFinite(rotateAngles[1]) ||
+                   !isFinite(rotateAngles[2])) {
+                    rotateAngles = lastRotate;
+                }
+
+                // update the projection
+                projection.rotate(rotateAngles);
+                lastRotate = rotateAngles;
+            }
+
+            zoomed(event.of(this, arguments));
+        });
+
+        zoomstarted(event.of(this, arguments));
+    })
+    .on('zoomend', function() {
+        d3.select(this).style(zoomendStyle);
+        zoomOn.call(zoom, 'zoom', null);
+        zoomended(event.of(this, arguments));
+    })
+    .on('zoom.redraw', function() {
+        geo.render();
+    });
+
+    function zoomstarted(dispatch) {
+        if(!zooming++) dispatch({type: 'zoomstart'});
+    }
+
+    function zoomed(dispatch) {
+        dispatch({type: 'zoom'});
+    }
+
+    function zoomended(dispatch) {
+        if(!--zooming) dispatch({type: 'zoomend'});
+    }
+
+    return d3.rebind(zoom, event, 'on');
+}
+
+// -- helper functions for zoomClipped
+
+function position(projection, point) {
+    var spherical = projection.invert(point);
+    return spherical && isFinite(spherical[0]) && isFinite(spherical[1]) && cartesian(spherical);
+}
+
+function quaternionFromEuler(euler) {
+    var lambda = 0.5 * euler[0] * radians,
+        phi = 0.5 * euler[1] * radians,
+        gamma = 0.5 * euler[2] * radians,
+        sinLambda = Math.sin(lambda), cosLambda = Math.cos(lambda),
+        sinPhi = Math.sin(phi), cosPhi = Math.cos(phi),
+        sinGamma = Math.sin(gamma), cosGamma = Math.cos(gamma);
+    return [
+        cosLambda * cosPhi * cosGamma + sinLambda * sinPhi * sinGamma,
+        sinLambda * cosPhi * cosGamma - cosLambda * sinPhi * sinGamma,
+        cosLambda * sinPhi * cosGamma + sinLambda * cosPhi * sinGamma,
+        cosLambda * cosPhi * sinGamma - sinLambda * sinPhi * cosGamma
+    ];
+}
+
+function multiply(a, b) {
+    var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3],
+        b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
+    return [
+        a0 * b0 - a1 * b1 - a2 * b2 - a3 * b3,
+        a0 * b1 + a1 * b0 + a2 * b3 - a3 * b2,
+        a0 * b2 - a1 * b3 + a2 * b0 + a3 * b1,
+        a0 * b3 + a1 * b2 - a2 * b1 + a3 * b0
+    ];
+}
+
+function rotateBetween(a, b) {
+    if(!a || !b) return;
+    var axis = cross(a, b),
+        norm = Math.sqrt(dot(axis, axis)),
+        halfgamma = 0.5 * Math.acos(Math.max(-1, Math.min(1, dot(a, b)))),
+        k = Math.sin(halfgamma) / norm;
+    return norm && [Math.cos(halfgamma), axis[2] * k, -axis[1] * k, axis[0] * k];
+}
+
+// input:
+//   rotateAngles: a calculated set of Euler angles
+//   pt: a point (cartesian in 3-space) to keep fixed
+//   roll0: an initial roll, to be preserved
+// output:
+//   a set of Euler angles that preserve the projection of pt
+//     but set roll (output[2]) equal to roll0
+//     note that this doesn't depend on the particular projection,
+//     just on the rotation angles
+function unRoll(rotateAngles, pt, lastRotate) {
+    // calculate the fixed point transformed by these Euler angles
+    // but with the desired roll undone
+    var ptRotated = rotateCartesian(pt, 2, rotateAngles[0]);
+    ptRotated = rotateCartesian(ptRotated, 1, rotateAngles[1]);
+    ptRotated = rotateCartesian(ptRotated, 0, rotateAngles[2] - lastRotate[2]);
+
+    var x = pt[0],
+        y = pt[1],
+        z = pt[2],
+        f = ptRotated[0],
+        g = ptRotated[1],
+        h = ptRotated[2],
+
+        // the following essentially solves:
+        // ptRotated = rotateCartesian(rotateCartesian(pt, 2, newYaw), 1, newPitch)
+        // for newYaw and newPitch, as best it can
+        theta = Math.atan2(y, x) * degrees,
+        a = Math.sqrt(x * x + y * y),
+        b,
+        newYaw1;
+
+    if(Math.abs(g) > a) {
+        newYaw1 = (g > 0 ? 90 : -90) - theta;
+        b = 0;
+    } else {
+        newYaw1 = Math.asin(g / a) * degrees - theta;
+        b = Math.sqrt(a * a - g * g);
+    }
+
+    var newYaw2 = 180 - newYaw1 - 2*theta,
+        newPitch1 = (Math.atan2(h, f) - Math.atan2(z, b)) * degrees,
+        newPitch2 = (Math.atan2(h, f) - Math.atan2(z, -b)) * degrees;
+
+    // which is closest to lastRotate[0,1]: newYaw/Pitch or newYaw2/Pitch2?
+    var dist1 = angleDistance(lastRotate[0], lastRotate[1], newYaw1, newPitch1),
+        dist2 = angleDistance(lastRotate[0], lastRotate[1], newYaw2, newPitch2);
+
+    if(dist1 <= dist2) return [newYaw1, newPitch1, lastRotate[2]];
+    else return [newYaw2, newPitch2, lastRotate[2]];
+}
+
+function angleDistance(yaw0, pitch0, yaw1, pitch1) {
+    var dYaw = angleMod(yaw1 - yaw0),
+        dPitch = angleMod(pitch1 - pitch0);
+    return Math.sqrt(dYaw * dYaw + dPitch * dPitch);
+}
+
+// reduce an angle in degrees to [-180,180]
+function angleMod(angle) {
+    return (angle % 360 + 540) %360 - 180;
+}
+
+// rotate a cartesian vector
+// axis is 0 (x), 1 (y), or 2 (z)
+// angle is in degrees
+function rotateCartesian(vector, axis, angle) {
+    var angleRads = angle * radians,
+        vectorOut = vector.slice(),
+        ax1 = (axis===0) ? 1 : 0,
+        ax2 = (axis===2) ? 1 : 2,
+        cosa = Math.cos(angleRads),
+        sina = Math.sin(angleRads);
+
+    vectorOut[ax1] = vector[ax1] * cosa - vector[ax2] * sina;
+    vectorOut[ax2] = vector[ax2] * cosa + vector[ax1] * sina;
+
+    return vectorOut;
+}
+function eulerFromQuaternion(q) {
+    return [
+        Math.atan2(2 * (q[0] * q[1] + q[2] * q[3]), 1 - 2 * (q[1] * q[1] + q[2] * q[2])) * degrees,
+        Math.asin(Math.max(-1, Math.min(1, 2 * (q[0] * q[2] - q[3] * q[1])))) * degrees,
+        Math.atan2(2 * (q[0] * q[3] + q[1] * q[2]), 1 - 2 * (q[2] * q[2] + q[3] * q[3])) * degrees
+    ];
+}
+
+function cartesian(spherical) {
+    var lambda = spherical[0] * radians,
+        phi = spherical[1] * radians,
+        cosPhi = Math.cos(phi);
+    return [
+        cosPhi * Math.cos(lambda),
+        cosPhi * Math.sin(lambda),
+        Math.sin(phi)
+    ];
+}
+
+function dot(a, b) {
+    var s = 0;
+    for(var i = 0, n = a.length; i < n; ++i) s += a[i] * b[i];
+    return s;
+}
+
+function cross(a, b) {
+    return [
+        a[1] * b[2] - a[2] * b[1],
+        a[2] * b[0] - a[0] * b[2],
+        a[0] * b[1] - a[1] * b[0]
+    ];
+}
+
+// Like d3.dispatch, but for custom events abstracting native UI events. These
+// events have a target component (such as a brush), a target element (such as
+// the svg:g element containing the brush) and the standard arguments `d` (the
+// target element's data) and `i` (the selection index of the target element).
+function d3_eventDispatch(target) {
+    var i = 0,
+        n = arguments.length,
+        argumentz = [];
+
+    while(++i < n) argumentz.push(arguments[i]);
+
+    var dispatch = d3.dispatch.apply(null, argumentz);
+
+    // Creates a dispatch context for the specified `thiz` (typically, the target
+    // DOM element that received the source event) and `argumentz` (typically, the
+    // data `d` and index `i` of the target element). The returned function can be
+    // used to dispatch an event to any registered listeners; the function takes a
+    // single argument as input, being the event to dispatch. The event must have
+    // a "type" attribute which corresponds to a type registered in the
+    // constructor. This context will automatically populate the "sourceEvent" and
+    // "target" attributes of the event, as well as setting the `d3.event` global
+    // for the duration of the notification.
+    dispatch.of = function(thiz, argumentz) {
+        return function(e1) {
+            var e0;
+            try {
+                e0 = e1.sourceEvent = d3.event;
+                e1.target = target;
+                d3.event = e1;
+                dispatch[e1.type].apply(thiz, argumentz);
+            } finally {
+                d3.event = e0;
+            }
+        };
+    };
+
+    return dispatch;
+}
+
+},{"d3":70}],394:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Fx = require('../cartesian/graph_interact');
+
+function createGeoZoomReset(geo, geoLayout) {
+    var projection = geo.projection,
+        zoom = geo.zoom;
+
+    var zoomReset = function() {
+        geo.makeProjection(geoLayout);
+        geo.makePath();
+
+        zoom.scale(projection.scale());
+        zoom.translate(projection.translate());
+
+        Fx.loneUnhover(geo.hoverContainer);
+
+        geo.render();
+    };
+
+    return zoomReset;
+}
+
+module.exports = createGeoZoomReset;
+
+},{"../cartesian/graph_interact":374}],395:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var mouseChange = require('mouse-change');
+var mouseWheel = require('mouse-wheel');
+
+module.exports = createCamera;
+
+function Camera2D(element, plot) {
+    this.element = element;
+    this.plot = plot;
+    this.mouseListener = null;
+    this.wheelListener = null;
+    this.lastInputTime = Date.now();
+    this.lastPos = [0, 0];
+    this.boxEnabled = false;
+    this.boxStart = [0, 0];
+    this.boxEnd = [0, 0];
+}
+
+
+function createCamera(scene) {
+    var element = scene.mouseContainer,
+        plot = scene.glplot,
+        result = new Camera2D(element, plot);
+
+    result.mouseListener = mouseChange(element, function(buttons, x, y) {
+        var xrange = scene.xaxis.range,
+            yrange = scene.yaxis.range,
+            viewBox = plot.viewBox;
+
+        var lastX = result.lastPos[0],
+            lastY = result.lastPos[1];
+
+        x *= plot.pixelRatio;
+        y *= plot.pixelRatio;
+
+        // mouseChange gives y about top; convert to about bottom
+        y = (viewBox[3] - viewBox[1]) - y;
+
+        function updateRange(range, start, end) {
+            var range0 = Math.min(start, end),
+                range1 = Math.max(start, end);
+
+            if(range0 !== range1) {
+                range[0] = range0;
+                range[1] = range1;
+                result.dataBox = range;
+            }
+            else {
+                scene.selectBox.selectBox = [0, 0, 1, 1];
+                scene.glplot.setDirty();
+            }
+        }
+
+        switch(scene.fullLayout.dragmode) {
+            case 'zoom':
+                if(buttons) {
+                    var dataX = x /
+                            (viewBox[2] - viewBox[0]) * (xrange[1] - xrange[0]) +
+                        xrange[0];
+                    var dataY = y /
+                            (viewBox[3] - viewBox[1]) * (yrange[1] - yrange[0]) +
+                        yrange[0];
+
+                    if(!result.boxEnabled) {
+                        result.boxStart[0] = dataX;
+                        result.boxStart[1] = dataY;
+                    }
+
+                    result.boxEnd[0] = dataX;
+                    result.boxEnd[1] = dataY;
+
+                    result.boxEnabled = true;
+                }
+                else if(result.boxEnabled) {
+                    updateRange(xrange, result.boxStart[0], result.boxEnd[0]);
+                    updateRange(yrange, result.boxStart[1], result.boxEnd[1]);
+
+                    result.boxEnabled = false;
+                }
+                break;
+
+            case 'pan':
+                result.boxEnabled = false;
+
+                if(buttons) {
+                    var dx = (lastX - x) * (xrange[1] - xrange[0]) /
+                        (plot.viewBox[2] - plot.viewBox[0]);
+                    var dy = (lastY - y) * (yrange[1] - yrange[0]) /
+                        (plot.viewBox[3] - plot.viewBox[1]);
+
+                    xrange[0] += dx;
+                    xrange[1] += dx;
+                    yrange[0] += dy;
+                    yrange[1] += dy;
+
+                    result.lastInputTime = Date.now();
+
+                    scene.cameraChanged();
+                }
+                break;
+        }
+
+        result.lastPos[0] = x;
+        result.lastPos[1] = y;
+    });
+
+    result.wheelListener = mouseWheel(element, function(dx, dy) {
+        var xrange = scene.xaxis.range,
+            yrange = scene.yaxis.range,
+            viewBox = plot.viewBox;
+
+        var lastX = result.lastPos[0],
+            lastY = result.lastPos[1];
+
+        switch(scene.fullLayout.dragmode) {
+            case 'zoom':
+                break;
+
+            case 'pan':
+                var scale = Math.exp(0.1 * dy / (viewBox[3] - viewBox[1]));
+
+                var cx = lastX /
+                        (viewBox[2] - viewBox[0]) * (xrange[1] - xrange[0]) +
+                    xrange[0];
+                var cy = lastY /
+                        (viewBox[3] - viewBox[1]) * (yrange[1] - yrange[0]) +
+                    yrange[0];
+
+                xrange[0] = (xrange[0] - cx) * scale + cx;
+                xrange[1] = (xrange[1] - cx) * scale + cx;
+                yrange[0] = (yrange[0] - cy) * scale + cy;
+                yrange[1] = (yrange[1] - cy) * scale + cy;
+
+                result.lastInputTime = Date.now();
+                scene.cameraChanged();
+                break;
+        }
+
+        return true;
+    });
+
+    return result;
+}
+
+},{"mouse-change":196,"mouse-wheel":200}],396:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../../plotly');
+
+var htmlToUnicode = require('../../lib/html2unicode');
+var str2RGBArray = require('../../lib/str2rgbarray');
+
+function Axes2DOptions(scene) {
+    this.scene = scene;
+    this.gl = scene.gl;
+    this.pixelRatio = scene.pixelRatio;
+
+    this.screenBox = [0, 0, 1, 1];
+    this.viewBox = [0 ,0, 1, 1];
+    this.dataBox = [-1, -1, 1, 1];
+
+    this.borderLineEnable = [false, false, false, false];
+    this.borderLineWidth = [1, 1, 1, 1];
+    this.borderLineColor = [
+        [0, 0, 0, 1],
+        [0, 0, 0, 1],
+        [0, 0, 0, 1],
+        [0, 0, 0, 1]
+    ];
+
+    this.ticks = [[], []];
+    this.tickEnable = [true, true, false, false];
+    this.tickPad = [15, 15, 15, 15];
+    this.tickAngle = [0, 0, 0, 0];
+    this.tickColor = [
+        [0, 0, 0, 1],
+        [0, 0, 0, 1],
+        [0, 0, 0, 1],
+        [0, 0, 0, 1]
+    ];
+    this.tickMarkLength = [0, 0, 0, 0];
+    this.tickMarkWidth = [0, 0, 0, 0];
+    this.tickMarkColor = [
+        [0, 0, 0, 1],
+        [0, 0, 0, 1],
+        [0, 0, 0, 1],
+        [0, 0, 0, 1]
+    ];
+
+    this.labels = ['x', 'y'];
+    this.labelEnable = [true, true, false, false];
+    this.labelAngle = [0, Math.PI/2, 0, 3.0*Math.PI/2];
+    this.labelPad = [15, 15, 15, 15];
+    this.labelSize = [12, 12];
+    this.labelFont = ['sans-serif', 'sans-serif'];
+    this.labelColor = [
+        [0, 0, 0, 1],
+        [0, 0, 0, 1],
+        [0, 0, 0, 1],
+        [0, 0, 0, 1]
+    ];
+
+    this.title = '';
+    this.titleEnable = true;
+    this.titleCenter = [0, 0, 0, 0];
+    this.titleAngle = 0;
+    this.titleColor = [0, 0, 0, 1];
+    this.titleFont = 'sans-serif';
+    this.titleSize = 18;
+
+    this.gridLineEnable = [true, true];
+    this.gridLineColor = [
+        [0, 0, 0, 0.5],
+        [0, 0, 0, 0.5]
+    ];
+    this.gridLineWidth = [1, 1];
+
+    this.zeroLineEnable = [true, true];
+    this.zeroLineWidth = [1, 1];
+    this.zeroLineColor = [
+        [0, 0, 0, 1],
+        [0, 0, 0, 1]
+    ];
+
+    this.borderColor = [0, 0, 0, 0];
+    this.backgroundColor = [0, 0, 0, 0];
+}
+
+var proto = Axes2DOptions.prototype;
+
+var AXES = ['xaxis', 'yaxis'];
+
+proto.merge = function(options) {
+
+    // titles are rendered in SVG
+    this.titleEnable = false;
+    this.backgroundColor = str2RGBArray(options.plot_bgcolor);
+
+    var axisName, ax, axTitle, axMirror;
+    var hasAxisInDfltPos, hasAxisInAltrPos, hasSharedAxis, mirrorLines, mirrorTicks;
+    var i, j;
+
+    for(i = 0; i < 2; ++i) {
+        axisName = AXES[i];
+
+        // get options relevant to this subplot,
+        // '_name' is e.g. xaxis, xaxis2, yaxis, yaxis4 ...
+        ax = options[this.scene[axisName]._name];
+
+        axTitle = /Click to enter .+ title/.test(ax.title) ? '' : ax.title;
+
+        for(j = 0; j <= 2; j += 2) {
+            this.labelEnable[i+j] = false;
+            this.labels[i+j] = htmlToUnicode(axTitle);
+            this.labelColor[i+j] = str2RGBArray(ax.titlefont.color);
+            this.labelFont[i+j] = ax.titlefont.family;
+            this.labelSize[i+j] = ax.titlefont.size;
+            this.labelPad[i+j] = this.getLabelPad(axisName, ax);
+
+            this.tickEnable[i+j] = false;
+            this.tickColor[i+j] = str2RGBArray((ax.tickfont || {}).color);
+            this.tickAngle[i+j] = (ax.tickangle === 'auto') ?
+                0 :
+                Math.PI * -ax.tickangle / 180;
+            this.tickPad[i+j] = this.getTickPad(ax);
+
+            this.tickMarkLength[i+j] = 0;
+            this.tickMarkWidth[i+j] = ax.tickwidth || 0;
+            this.tickMarkColor[i+j] = str2RGBArray(ax.tickcolor);
+
+            this.borderLineEnable[i+j] = false;
+            this.borderLineColor[i+j] = str2RGBArray(ax.linecolor);
+            this.borderLineWidth[i+j] = ax.linewidth || 0;
+        }
+
+        hasSharedAxis = this.hasSharedAxis(ax);
+        hasAxisInDfltPos = this.hasAxisInDfltPos(axisName, ax) && !hasSharedAxis;
+        hasAxisInAltrPos = this.hasAxisInAltrPos(axisName, ax) && !hasSharedAxis;
+
+        axMirror = ax.mirror || false;
+        mirrorLines = hasSharedAxis ?
+            (String(axMirror).indexOf('all') !== -1) :  // 'all' or 'allticks'
+            !!axMirror;                                 // all but false
+        mirrorTicks = hasSharedAxis ?
+            (axMirror === 'allticks') :
+            (String(axMirror).indexOf('ticks') !== -1); // 'ticks' or 'allticks'
+
+        // Axis titles and tick labels can only appear of one side of the scene
+        //  and are never show on subplots that share existing axes.
+
+        if(hasAxisInDfltPos) this.labelEnable[i] = true;
+        else if(hasAxisInAltrPos) this.labelEnable[i+2] = true;
+
+        if(hasAxisInDfltPos) this.tickEnable[i] = ax.showticklabels;
+        else if(hasAxisInAltrPos) this.tickEnable[i+2] = ax.showticklabels;
+
+        // Grid lines and ticks can appear on both sides of the scene
+        //  and can appear on subplot that share existing axes via `ax.mirror`.
+
+        if(hasAxisInDfltPos || mirrorLines) this.borderLineEnable[i] = ax.showline;
+        if(hasAxisInAltrPos || mirrorLines) this.borderLineEnable[i+2] = ax.showline;
+
+        if(hasAxisInDfltPos || mirrorTicks) this.tickMarkLength[i] = this.getTickMarkLength(ax);
+        if(hasAxisInAltrPos || mirrorTicks) this.tickMarkLength[i+2] = this.getTickMarkLength(ax);
+
+        this.gridLineEnable[i] = ax.showgrid;
+        this.gridLineColor[i] = str2RGBArray(ax.gridcolor);
+        this.gridLineWidth[i] = ax.gridwidth;
+
+        this.zeroLineEnable[i] = ax.zeroline;
+        this.zeroLineColor[i] = str2RGBArray(ax.zerolinecolor);
+        this.zeroLineWidth[i] = ax.zerolinewidth;
+    }
+};
+
+// is an axis shared with an already-drawn subplot ?
+proto.hasSharedAxis = function(ax) {
+    var scene = this.scene,
+        subplotIds = Plotly.Plots.getSubplotIds(scene.fullLayout, 'gl2d'),
+        list = Plotly.Axes.findSubplotsWithAxis(subplotIds, ax);
+
+    // if index === 0, then the subplot is already drawn as subplots
+    // are drawn in order.
+    return (list.indexOf(scene.id) !== 0);
+};
+
+// has an axis in default position (i.e. bottom/left) ?
+proto.hasAxisInDfltPos = function(axisName, ax) {
+    var axSide = ax.side;
+
+    if(axisName === 'xaxis') return (axSide === 'bottom');
+    else if(axisName === 'yaxis') return (axSide === 'left');
+};
+
+// has an axis in alternate position (i.e. top/right) ?
+proto.hasAxisInAltrPos = function(axisName, ax) {
+    var axSide = ax.side;
+
+    if(axisName === 'xaxis') return (axSide === 'top');
+    else if(axisName === 'yaxis') return (axSide === 'right');
+};
+
+proto.getLabelPad = function(axisName, ax) {
+    var offsetBase = 1.5,
+        fontSize = ax.titlefont.size,
+        showticklabels = ax.showticklabels;
+
+    if(axisName === 'xaxis') {
+        return (ax.side === 'top') ?
+            -10 + fontSize * (offsetBase + (showticklabels ? 1 : 0)) :
+            -10 + fontSize * (offsetBase + (showticklabels ? 0.5 : 0));
+    }
+    else if(axisName === 'yaxis') {
+        return (ax.side === 'right') ?
+            10 + fontSize * (offsetBase + (showticklabels ? 1 : 0.5)) :
+            10 + fontSize * (offsetBase + (showticklabels ? 0.5 : 0));
+    }
+};
+
+proto.getTickPad = function(ax) {
+    return (ax.ticks === 'outside') ? 10 + ax.ticklen : 15;
+};
+
+proto.getTickMarkLength = function(ax) {
+    if(!ax.ticks) return 0;
+
+    var ticklen = ax.ticklen;
+
+    return (ax.ticks === 'inside') ? -ticklen : ticklen;
+};
+
+
+function createAxes2D(scene) {
+    return new Axes2DOptions(scene);
+}
+
+module.exports = createAxes2D;
+
+},{"../../lib/html2unicode":348,"../../lib/str2rgbarray":359,"../../plotly":366}],397:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../../plotly');
+
+var Scene2D = require('./scene2d');
+
+var Plots = Plotly.Plots;
+
+
+exports.name = 'gl2d';
+
+exports.attr = ['xaxis', 'yaxis'];
+
+exports.idRoot = ['x', 'y'];
+
+exports.idRegex = {
+    x: /^x([2-9]|[1-9][0-9]+)?$/,
+    y: /^y([2-9]|[1-9][0-9]+)?$/
+};
+
+exports.attrRegex = {
+    x: /^xaxis([2-9]|[1-9][0-9]+)?$/,
+    y: /^yaxis([2-9]|[1-9][0-9]+)?$/
+};
+
+exports.attributes = require('../cartesian/attributes');
+
+exports.plot = function plotGl2d(gd) {
+    var fullLayout = gd._fullLayout,
+        fullData = gd._fullData,
+        subplotIds = Plots.getSubplotIds(fullLayout, 'gl2d');
+
+    for(var i = 0; i < subplotIds.length; i++) {
+        var subplotId = subplotIds[i],
+            subplotObj = fullLayout._plots[subplotId],
+            fullSubplotData = Plots.getSubplotData(fullData, 'gl2d', subplotId);
+
+        // ref. to corresp. Scene instance
+        var scene = subplotObj._scene2d;
+
+        // If Scene is not instantiated, create one!
+        if(scene === undefined) {
+            scene = new Scene2D({
+                container: gd.querySelector('.gl-container'),
+                id: subplotId,
+                staticPlot: gd._context.staticPlot,
+                plotGlPixelRatio: gd._context.plotGlPixelRatio
+            },
+                fullLayout
+            );
+
+            // set ref to Scene instance
+            subplotObj._scene2d = scene;
+        }
+
+        scene.plot(fullSubplotData, fullLayout, gd.layout);
+    }
+};
+
+},{"../../plotly":366,"../cartesian/attributes":368,"./scene2d":398}],398:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plots = require('../../plots/plots');
+var Axes = require('../../plots/cartesian/axes');
+var Fx = require('../../plots/cartesian/graph_interact');
+
+var createPlot2D = require('gl-plot2d');
+var createSpikes = require('gl-spikes2d');
+var createSelectBox = require('gl-select-box');
+
+var createOptions = require('./convert');
+var createCamera = require('./camera');
+
+var htmlToUnicode = require('../../lib/html2unicode');
+var showNoWebGlMsg = require('../../lib/show_no_webgl_msg');
+
+var AXES = ['xaxis', 'yaxis'];
+var STATIC_CANVAS, STATIC_CONTEXT;
+
+
+function Scene2D(options, fullLayout) {
+    this.container = options.container;
+    this.pixelRatio = options.plotGlPixelRatio || window.devicePixelRatio;
+    this.id = options.id;
+    this.staticPlot = !!options.staticPlot;
+
+    this.fullLayout = fullLayout;
+    this.updateAxes(fullLayout);
+
+    this.makeFramework();
+
+    // update options
+    this.glplotOptions = createOptions(this);
+    this.glplotOptions.merge(fullLayout);
+
+    // create the plot
+    this.glplot = createPlot2D(this.glplotOptions);
+
+    // create camera
+    this.camera = createCamera(this);
+
+    // trace set
+    this.traces = {};
+
+    // create axes spikes
+    this.spikes = createSpikes(this.glplot);
+
+    this.selectBox = createSelectBox(this.glplot, {
+        innerFill: false,
+        outerFill: true
+    });
+
+    // last pick result
+    this.pickResult = null;
+
+    this.bounds = [Infinity, Infinity, -Infinity, -Infinity];
+
+    // flag to stop render loop
+    this.stopped = false;
+
+    // redraw the plot
+    this.redraw = this.draw.bind(this);
+    this.redraw();
+}
+
+module.exports = Scene2D;
+
+var proto = Scene2D.prototype;
+
+proto.makeFramework = function() {
+
+    // create canvas and gl context
+    if(this.staticPlot) {
+        if(!STATIC_CONTEXT) {
+            STATIC_CANVAS = document.createElement('canvas');
+
+            try {
+                STATIC_CONTEXT = STATIC_CANVAS.getContext('webgl', {
+                    preserveDrawingBuffer: true,
+                    premultipliedAlpha: true,
+                    antialias: true
+                });
+            } catch(e) {
+                throw new Error([
+                    'Error creating static canvas/context for image server'
+                ].join(' '));
+            }
+        }
+
+        this.canvas = STATIC_CANVAS;
+        this.gl = STATIC_CONTEXT;
+    }
+    else {
+        var liveCanvas = document.createElement('canvas'),
+            glOpts = { premultipliedAlpha: true };
+        var gl;
+
+        try {
+            gl = liveCanvas.getContext('webgl', glOpts);
+        } catch(e) {
+            //
+        }
+
+        if(!gl) {
+            try {
+                gl = liveCanvas.getContext('experimental-webgl', glOpts);
+            } catch(e) {
+                //
+            }
+        }
+
+        if(!gl) showNoWebGlMsg(this);
+
+        this.canvas = liveCanvas;
+        this.gl = gl;
+    }
+
+    // position the canvas
+    var canvas = this.canvas,
+        pixelRatio = this.pixelRatio,
+        fullLayout = this.fullLayout;
+
+    canvas.width = Math.ceil(pixelRatio * fullLayout.width) |0;
+    canvas.height = Math.ceil(pixelRatio * fullLayout.height) |0;
+    canvas.style.width = '100%';
+    canvas.style.height = '100%';
+    canvas.style.position = 'absolute';
+    canvas.style.top = '0px';
+    canvas.style.left = '0px';
+    canvas.style['pointer-events'] = 'none';
+
+    // create SVG container for hover text
+    var svgContainer = this.svgContainer = document.createElementNS(
+        'http://www.w3.org/2000/svg',
+        'svg');
+    svgContainer.style.position = 'absolute';
+    svgContainer.style.top = svgContainer.style.left = '0px';
+    svgContainer.style.width = svgContainer.style.height = '100%';
+    svgContainer.style['z-index'] = 20;
+    svgContainer.style['pointer-events'] = 'none';
+
+    // create div to catch the mouse event
+    var mouseContainer = this.mouseContainer = document.createElement('div');
+    mouseContainer.style.position = 'absolute';
+
+    // append canvas, hover svg and mouse div to container
+    var container = this.container;
+    container.appendChild(canvas);
+    container.appendChild(svgContainer);
+    container.appendChild(mouseContainer);
+};
+
+proto.toImage = function(format) {
+    if(!format) format = 'png';
+
+    this.stopped = true;
+    if(this.staticPlot) this.container.appendChild(STATIC_CANVAS);
+
+    // force redraw
+    this.glplot.setDirty(true);
+    this.glplot.draw();
+
+    // grab context and yank out pixels
+    var gl = this.glplot.gl,
+        w = gl.drawingBufferWidth,
+        h = gl.drawingBufferHeight;
+
+    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+
+    var pixels = new Uint8Array(w * h * 4);
+    gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
+
+    // flip pixels
+    for(var j=0,k=h-1; j<k; ++j, --k) {
+        for(var i=0; i<w; ++i) {
+            for(var l=0; l<4; ++l) {
+                var tmp = pixels[4*(w*j+i)+l];
+                pixels[4*(w*j+i)+l] = pixels[4*(w*k+i)+l];
+                pixels[4*(w*k+i)+l] = tmp;
+            }
+        }
+    }
+
+    var canvas = document.createElement('canvas');
+    canvas.width = w;
+    canvas.height = h;
+
+    var context = canvas.getContext('2d');
+    var imageData = context.createImageData(w, h);
+    imageData.data.set(pixels);
+    context.putImageData(imageData, 0, 0);
+
+    var dataURL;
+
+    switch(format) {
+        case 'jpeg':
+            dataURL = canvas.toDataURL('image/jpeg');
+            break;
+        case 'webp':
+            dataURL = canvas.toDataURL('image/webp');
+            break;
+        default:
+            dataURL = canvas.toDataURL('image/png');
+    }
+
+    if(this.staticPlot) this.container.removeChild(STATIC_CANVAS);
+
+    return dataURL;
+};
+
+proto.computeTickMarks = function() {
+    this.xaxis._length =
+        this.glplot.viewBox[2] - this.glplot.viewBox[0];
+    this.yaxis._length =
+        this.glplot.viewBox[3] - this.glplot.viewBox[1];
+
+    var nextTicks = [
+        Axes.calcTicks(this.xaxis),
+        Axes.calcTicks(this.yaxis)
+    ];
+
+    for(var j = 0; j < 2; ++j) {
+        for(var i = 0; i < nextTicks[j].length; ++i) {
+            // TODO add support for '\n' in gl-plot2d,
+            // For now, replace '\n' with ' '
+            nextTicks[j][i].text = htmlToUnicode(nextTicks[j][i].text + '').replace(/\n/g, ' ');
+        }
+    }
+
+    return nextTicks;
+};
+
+function compareTicks(a, b) {
+    for(var i = 0; i < 2; ++i) {
+        var aticks = a[i],
+            bticks = b[i];
+
+        if(aticks.length !== bticks.length) return true;
+
+        for(var j = 0; j < aticks.length; ++j) {
+            if(aticks[j].x !== bticks[j].x) return true;
+        }
+    }
+
+    return false;
+}
+
+proto.updateAxes = function(options) {
+    var spmatch = Axes.subplotMatch,
+        xaxisName = 'xaxis' + this.id.match(spmatch)[1],
+        yaxisName = 'yaxis' + this.id.match(spmatch)[2];
+
+    this.xaxis = options[xaxisName];
+    this.yaxis = options[yaxisName];
+};
+
+proto.updateFx = function(options) {
+    var fullLayout = this.fullLayout;
+
+    fullLayout.dragmode = options.dragmode;
+    fullLayout.hovermode = options.hovermode;
+};
+
+proto.cameraChanged = function() {
+    var camera = this.camera,
+        xrange = this.xaxis.range,
+        yrange = this.yaxis.range;
+
+    this.glplot.setDataBox([
+        xrange[0], yrange[0],
+        xrange[1], yrange[1]
+    ]);
+
+    var nextTicks = this.computeTickMarks();
+    var curTicks = this.glplotOptions.ticks;
+
+    if(compareTicks(nextTicks, curTicks)) {
+        this.glplotOptions.ticks = nextTicks;
+        this.glplotOptions.dataBox = camera.dataBox;
+        this.glplot.update(this.glplotOptions);
+    }
+};
+
+proto.destroy = function() {
+    this.glplot.dispose();
+};
+
+proto.plot = function(fullData, fullLayout) {
+    var glplot = this.glplot,
+        pixelRatio = this.pixelRatio;
+
+    var i, j;
+
+    this.fullLayout = fullLayout;
+    this.updateAxes(fullLayout);
+
+    var width = fullLayout.width,
+        height = fullLayout.height,
+        pixelWidth = Math.ceil(pixelRatio * width) |0,
+        pixelHeight = Math.ceil(pixelRatio * height) |0;
+
+    // check for resize
+    var canvas = this.canvas;
+    if(canvas.width !== pixelWidth || canvas.height !== pixelHeight) {
+        canvas.width = pixelWidth;
+        canvas.height = pixelHeight;
+    }
+
+    if(!fullData) fullData = [];
+    else if(!Array.isArray(fullData)) fullData = [fullData];
+
+    // update traces
+    var traceData, trace;
+    for(i = 0; i < fullData.length; ++i) {
+        traceData = fullData[i];
+        trace = this.traces[traceData.uid];
+
+        if(trace) trace.update(traceData);
+        else {
+            var traceModule = Plots.getModule(traceData.type);
+            trace = traceModule.plot(this, traceData);
+        }
+        this.traces[traceData.uid] = trace;
+    }
+
+    // remove empty traces
+    var traceIds = Object.keys(this.traces);
+
+    trace_id_loop:
+    for(i = 0; i < traceIds.length; ++i) {
+        for(j = 0; j < fullData.length; ++j) {
+            if(fullData[j].uid === traceIds[i]) continue trace_id_loop;
+        }
+
+        trace = this.traces[traceIds[i]];
+        trace.dispose();
+        delete this.traces[traceIds[i]];
+    }
+
+    var options = this.glplotOptions;
+    options.merge(fullLayout);
+    options.screenBox = [0, 0, width, height];
+
+    var size = fullLayout._size,
+        domainX = this.xaxis.domain,
+        domainY = this.yaxis.domain;
+
+    options.viewBox = [
+        size.l + domainX[0] * size.w,
+        size.b + domainY[0] * size.h,
+        (width - size.r) - (1 - domainX[1]) * size.w,
+        (height - size.t) - (1 - domainY[1]) * size.h
+    ];
+
+    this.mouseContainer.style.width = size.w * (domainX[1] - domainX[0]) + 'px';
+    this.mouseContainer.style.height = size.h * (domainY[1] - domainY[0]) + 'px';
+    this.mouseContainer.height = size.h * (domainY[1] - domainY[0]);
+    this.mouseContainer.style.left = size.l + domainX[0] * size.w + 'px';
+    this.mouseContainer.style.top = size.t + (1-domainY[1]) * size.h + 'px';
+
+    var bounds = this.bounds;
+    bounds[0] = bounds[1] = Infinity;
+    bounds[2] = bounds[3] = -Infinity;
+
+    traceIds = Object.keys(this.traces);
+    for(i = 0; i < traceIds.length; ++i) {
+        trace = this.traces[traceIds[i]];
+        for(var k = 0; k < 2; ++k) {
+            bounds[k] = Math.min(bounds[k], trace.bounds[k]);
+            bounds[k+2] = Math.max(bounds[k+2], trace.bounds[k+2]);
+        }
+    }
+
+    var ax;
+    for(i = 0; i < 2; ++i) {
+        if(bounds[i] > bounds[i+2]) {
+            bounds[i] = -1;
+            bounds[i+2] = 1;
+        }
+
+        ax = this[AXES[i]];
+        ax._length = options.viewBox[i+2] - options.viewBox[i];
+
+        Axes.doAutoRange(ax);
+    }
+
+    options.ticks = this.computeTickMarks();
+
+    var xrange = this.xaxis.range;
+    var yrange = this.yaxis.range;
+    options.dataBox = [xrange[0], yrange[0], xrange[1], yrange[1]];
+
+    options.merge(fullLayout);
+    glplot.update(options);
+};
+
+proto.draw = function() {
+    if(this.stopped) return;
+    requestAnimationFrame(this.redraw);
+
+    var glplot = this.glplot,
+        camera = this.camera,
+        mouseListener = camera.mouseListener,
+        fullLayout = this.fullLayout;
+
+    this.cameraChanged();
+
+    var x = mouseListener.x * glplot.pixelRatio;
+    var y = this.canvas.height - glplot.pixelRatio * mouseListener.y;
+
+    if(camera.boxEnabled && fullLayout.dragmode === 'zoom') {
+        this.selectBox.enabled = true;
+
+        this.selectBox.selectBox = [
+            Math.min(camera.boxStart[0], camera.boxEnd[0]),
+            Math.min(camera.boxStart[1], camera.boxEnd[1]),
+            Math.max(camera.boxStart[0], camera.boxEnd[0]),
+            Math.max(camera.boxStart[1], camera.boxEnd[1])
+        ];
+
+        glplot.setDirty();
+    }
+    else {
+        this.selectBox.enabled = false;
+
+        var size = fullLayout._size,
+            domainX = this.xaxis.domain,
+            domainY = this.yaxis.domain;
+
+        var result = glplot.pick(
+            (x / glplot.pixelRatio) + size.l + domainX[0] * size.w,
+            (y / glplot.pixelRatio) - (size.t + (1-domainY[1]) * size.h)
+        );
+
+        if(result && fullLayout.hovermode) {
+            var nextSelection = result.object._trace.handlePick(result);
+
+            if(nextSelection && (
+                !this.lastPickResult ||
+                this.lastPickResult.trace !== nextSelection.trace ||
+                this.lastPickResult.dataCoord[0] !== nextSelection.dataCoord[0] ||
+                this.lastPickResult.dataCoord[1] !== nextSelection.dataCoord[1])
+            ) {
+                var selection = this.lastPickResult = nextSelection;
+                this.spikes.update({ center: result.dataCoord });
+
+                selection.screenCoord = [
+                    ((glplot.viewBox[2] - glplot.viewBox[0]) *
+                    (result.dataCoord[0] - glplot.dataBox[0]) /
+                        (glplot.dataBox[2] - glplot.dataBox[0]) + glplot.viewBox[0]) /
+                            glplot.pixelRatio,
+                    (this.canvas.height - (glplot.viewBox[3] - glplot.viewBox[1]) *
+                    (result.dataCoord[1] - glplot.dataBox[1]) /
+                        (glplot.dataBox[3] - glplot.dataBox[1]) - glplot.viewBox[1]) /
+                            glplot.pixelRatio
+                ];
+
+                var hoverinfo = selection.hoverinfo;
+                if(hoverinfo !== 'all') {
+                    var parts = hoverinfo.split('+');
+                    if(parts.indexOf('x') === -1) selection.traceCoord[0] = undefined;
+                    if(parts.indexOf('y') === -1) selection.traceCoord[1] = undefined;
+                    if(parts.indexOf('text') === -1) selection.textLabel = undefined;
+                    if(parts.indexOf('name') === -1) selection.name = undefined;
+                }
+
+                Fx.loneHover({
+                    x: selection.screenCoord[0],
+                    y: selection.screenCoord[1],
+                    xLabel: this.hoverFormatter('xaxis', selection.traceCoord[0]),
+                    yLabel: this.hoverFormatter('yaxis', selection.traceCoord[1]),
+                    text: selection.textLabel,
+                    name: selection.name,
+                    color: selection.color
+                }, {
+                    container: this.svgContainer
+                });
+
+                this.lastPickResult = { dataCoord: result.dataCoord };
+            }
+        }
+        else if(!result && this.lastPickResult) {
+            this.spikes.update({});
+            this.lastPickResult = null;
+            Fx.loneUnhover(this.svgContainer);
+        }
+    }
+
+    glplot.draw();
+};
+
+proto.hoverFormatter = function(axisName, val) {
+    if(val === undefined) return undefined;
+
+    var axis = this[axisName];
+    return Axes.tickText(axis, axis.c2l(val), 'hover').text;
+};
+
+},{"../../lib/html2unicode":348,"../../lib/show_no_webgl_msg":357,"../../plots/cartesian/axes":369,"../../plots/cartesian/graph_interact":374,"../../plots/plots":413,"./camera":395,"./convert":396,"gl-plot2d":122,"gl-select-box":152,"gl-spikes2d":178}],399:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+module.exports = createCamera;
+
+var now = require('right-now');
+var createView = require('3d-view');
+var mouseChange = require('mouse-change');
+var mouseWheel = require('mouse-wheel');
+
+function createCamera(element, options) {
+    element = element || document.body;
+    options = options || {};
+
+    var limits = [ 0.01, Infinity ];
+    if('distanceLimits' in options) {
+        limits[0] = options.distanceLimits[0];
+        limits[1] = options.distanceLimits[1];
+    }
+    if('zoomMin' in options) {
+        limits[0] = options.zoomMin;
+    }
+    if('zoomMax' in options) {
+        limits[1] = options.zoomMax;
+    }
+
+    var view = createView({
+        center: options.center || [0, 0, 0],
+        up: options.up || [0, 1, 0],
+        eye: options.eye || [0, 0, 10],
+        mode: options.mode || 'orbit',
+        distanceLimits: limits
+    });
+
+    var pmatrix = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
+    var distance = 0.0;
+    var width = element.clientWidth;
+    var height = element.clientHeight;
+
+    var camera = {
+        keyBindingMode: 'rotate',
+        view: view,
+        element: element,
+        delay: options.delay || 16,
+        rotateSpeed: options.rotateSpeed || 1,
+        zoomSpeed: options.zoomSpeed || 1,
+        translateSpeed: options.translateSpeed || 1,
+        flipX: !!options.flipX,
+        flipY: !!options.flipY,
+        modes: view.modes,
+        tick: function() {
+            var t = now();
+            var delay = this.delay;
+            var ctime = t - 2 * delay;
+            view.idle(t-delay);
+            view.recalcMatrix(ctime);
+            view.flush(t - (100+delay * 2));
+            var allEqual = true;
+            var matrix = view.computedMatrix;
+            for(var i = 0; i < 16; ++i) {
+                allEqual = allEqual && (pmatrix[i] === matrix[i]);
+                pmatrix[i] = matrix[i];
+            }
+            var sizeChanged =
+                element.clientWidth === width &&
+                element.clientHeight === height;
+            width = element.clientWidth;
+            height = element.clientHeight;
+            if(allEqual) return !sizeChanged;
+            distance = Math.exp(view.computedRadius[0]);
+            return true;
+        },
+        lookAt: function(center, eye, up) {
+            view.lookAt(view.lastT(), center, eye, up);
+        },
+        rotate: function(pitch, yaw, roll) {
+            view.rotate(view.lastT(), pitch, yaw, roll);
+        },
+        pan: function(dx, dy, dz) {
+            view.pan(view.lastT(), dx, dy, dz);
+        },
+        translate: function(dx, dy, dz) {
+            view.translate(view.lastT(), dx, dy, dz);
+        }
+    };
+
+    Object.defineProperties(camera, {
+        matrix: {
+            get: function() {
+                return view.computedMatrix;
+            },
+            set: function(mat) {
+                view.setMatrix(view.lastT(), mat);
+                return view.computedMatrix;
+            },
+            enumerable: true
+        },
+        mode: {
+            get: function() {
+                return view.getMode();
+            },
+            set: function(mode) {
+                var curUp = view.computedUp.slice();
+                var curEye = view.computedEye.slice();
+                var curCenter = view.computedCenter.slice();
+                view.setMode(mode);
+                if(mode === 'turntable') {
+                    //Hacky time warping stuff to generate smooth animation
+                    var t0 = now();
+                    view._active.lookAt(t0, curEye, curCenter, curUp);
+                    view._active.lookAt(t0 + 500, curEye, curCenter, [0,0,1]);
+                    view._active.flush(t0);
+                }
+                return view.getMode();
+            },
+            enumerable: true
+        },
+        center: {
+            get: function() {
+                return view.computedCenter;
+            },
+            set: function(ncenter) {
+                view.lookAt(view.lastT(), null, ncenter);
+                return view.computedCenter;
+            },
+            enumerable: true
+        },
+        eye: {
+            get: function() {
+                return view.computedEye;
+            },
+            set: function(neye) {
+                view.lookAt(view.lastT(), neye);
+                return view.computedEye;
+            },
+            enumerable: true
+        },
+        up: {
+            get: function() {
+                return view.computedUp;
+            },
+            set: function(nup) {
+                view.lookAt(view.lastT(), null, null, nup);
+                return view.computedUp;
+            },
+            enumerable: true
+        },
+        distance: {
+            get: function() {
+                return distance;
+            },
+            set: function(d) {
+                view.setDistance(view.lastT(), d);
+                return d;
+            },
+            enumerable: true
+        },
+        distanceLimits: {
+            get: function() {
+                return view.getDistanceLimits(limits);
+            },
+            set: function(v) {
+                view.setDistanceLimits(v);
+                return v;
+            },
+            enumerable: true
+        }
+    });
+
+    element.addEventListener('contextmenu', function(ev) {
+        ev.preventDefault();
+        return false;
+    });
+
+    var lastX = 0, lastY = 0;
+    mouseChange(element, function(buttons, x, y, mods) {
+        var rotate = camera.keyBindingMode === 'rotate';
+        var pan = camera.keyBindingMode === 'pan';
+        var zoom = camera.keyBindingMode === 'zoom';
+
+        var ctrl = !!mods.control;
+        var alt = !!mods.alt;
+        var shift = !!mods.shift;
+        var left = !!(buttons&1);
+        var right = !!(buttons&2);
+        var middle = !!(buttons&4);
+
+        var scale = 1.0 / element.clientHeight;
+        var dx = scale * (x - lastX);
+        var dy = scale * (y - lastY);
+
+        var flipX = camera.flipX ? 1 : -1;
+        var flipY = camera.flipY ? 1 : -1;
+
+        var t = now();
+
+        var drot = Math.PI * camera.rotateSpeed;
+
+        if((rotate && left && !ctrl && !alt && !shift) || (left && !ctrl && !alt && shift)) {
+            //Rotate
+            view.rotate(t, flipX * drot * dx, -flipY * drot * dy, 0);
+        }
+
+        if((pan && left && !ctrl && !alt && !shift) || right || (left && ctrl && !alt && !shift)) {
+            //Pan
+            view.pan(t, -camera.translateSpeed * dx * distance, camera.translateSpeed * dy * distance, 0);
+        }
+
+        if((zoom && left && !ctrl && !alt && !shift) || middle || (left && !ctrl && alt && !shift)) {
+            //Zoom
+            var kzoom = -camera.zoomSpeed * dy / window.innerHeight * (t - view.lastT()) * 100;
+            view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1));
+        }
+
+        lastX = x;
+        lastY = y;
+
+        return true;
+    });
+
+    mouseWheel(element, function(dx, dy) {
+        var flipX = camera.flipX ? 1 : -1;
+        var flipY = camera.flipY ? 1 : -1;
+        var t = now();
+        if(Math.abs(dx) > Math.abs(dy)) {
+            view.rotate(t, 0, 0, -dx * flipX * Math.PI * camera.rotateSpeed / window.innerWidth);
+        } else {
+            var kzoom = -camera.zoomSpeed * flipY * dy / window.innerHeight * (t - view.lastT()) / 100.0;
+            view.pan(t, 0, 0, distance * (Math.exp(kzoom) - 1));
+        }
+    }, true);
+
+    return camera;
+}
+
+},{"3d-view":38,"mouse-change":196,"mouse-wheel":200,"right-now":210}],400:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Scene = require('./scene');
+var Plots = require('../plots');
+
+var axesNames = ['xaxis', 'yaxis', 'zaxis'];
+
+
+exports.name = 'gl3d';
+
+exports.attr = 'scene';
+
+exports.idRoot = 'scene';
+
+exports.idRegex = /^scene([2-9]|[1-9][0-9]+)?$/;
+
+exports.attrRegex = /^scene([2-9]|[1-9][0-9]+)?$/;
+
+exports.attributes = require('./layout/attributes');
+
+exports.layoutAttributes = require('./layout/layout_attributes');
+
+exports.supplyLayoutDefaults = require('./layout/defaults');
+
+exports.plot = function plotGl3d(gd) {
+    var fullLayout = gd._fullLayout,
+        fullData = gd._fullData,
+        sceneIds = Plots.getSubplotIds(fullLayout, 'gl3d');
+
+    fullLayout._paperdiv.style({
+        width: fullLayout.width + 'px',
+        height: fullLayout.height + 'px'
+    });
+
+    gd._context.setBackground(gd, fullLayout.paper_bgcolor);
+
+    for(var i = 0; i < sceneIds.length; i++) {
+        var sceneId = sceneIds[i],
+            fullSceneData = Plots.getSubplotData(fullData, 'gl3d', sceneId),
+            scene = fullLayout[sceneId]._scene;  // ref. to corresp. Scene instance
+
+        // If Scene is not instantiated, create one!
+        if(scene === undefined) {
+            scene = new Scene({
+                id: sceneId,
+                graphDiv: gd,
+                container: gd.querySelector('.gl-container'),
+                staticPlot: gd._context.staticPlot,
+                plotGlPixelRatio: gd._context.plotGlPixelRatio
+            },
+                fullLayout
+            );
+
+            fullLayout[sceneId]._scene = scene;  // set ref to Scene instance
+        }
+
+        scene.plot(fullSceneData, fullLayout, gd.layout);  // takes care of business
+    }
+};
+
+exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
+    var oldSceneKeys = Plots.getSubplotIds(oldFullLayout, 'gl3d');
+
+    for(var i = 0; i < oldSceneKeys.length; i++) {
+        var oldSceneKey = oldSceneKeys[i];
+
+        if(!newFullLayout[oldSceneKey] && !!oldFullLayout[oldSceneKey]._scene) {
+            oldFullLayout[oldSceneKey]._scene.destroy();
+        }
+    }
+};
+
+// clean scene ids, 'scene1' -> 'scene'
+exports.cleanId = function cleanId(id) {
+    if(!id.match(/^scene[0-9]*$/)) return;
+
+    var sceneNum = id.substr(5);
+    if(sceneNum === '1') sceneNum = '';
+
+    return 'scene' + sceneNum;
+};
+
+exports.setConvert = require('./set_convert');
+
+exports.initAxes = function(gd) {
+    var fullLayout = gd._fullLayout;
+    var sceneIds = Plots.getSubplotIds(fullLayout, 'gl3d');
+
+    for(var i = 0; i < sceneIds.length; ++i) {
+        var sceneId = sceneIds[i];
+        var sceneLayout = fullLayout[sceneId];
+
+        for(var j = 0; j < 3; ++j) {
+            var axisName = axesNames[j];
+            var ax = sceneLayout[axisName];
+            ax._td = gd;
+        }
+    }
+};
+
+},{"../plots":413,"./layout/attributes":401,"./layout/defaults":405,"./layout/layout_attributes":406,"./scene":410,"./set_convert":411}],401:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+module.exports = {
+    scene: {
+        valType: 'sceneid',
+        
+        dflt: 'scene',
+        
+    }
+};
+
+},{}],402:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+var axesAttrs = require('../../cartesian/layout_attributes');
+var extendFlat = require('../../../lib/extend').extendFlat;
+
+
+module.exports = {
+    showspikes: {
+        valType: 'boolean',
+        
+        dflt: true,
+        
+    },
+    spikesides: {
+        valType: 'boolean',
+        
+        dflt: true,
+        
+    },
+    spikethickness: {
+        valType: 'number',
+        
+        min: 0,
+        dflt: 2,
+        
+    },
+    spikecolor: {
+        valType: 'color',
+        
+        dflt: 'rgb(0,0,0)',
+        
+    },
+    showbackground: {
+        valType: 'boolean',
+        
+        dflt: false,
+        
+    },
+    backgroundcolor: {
+        valType: 'color',
+        
+        dflt: 'rgba(204, 204, 204, 0.5)',
+        
+    },
+    showaxeslabels: {
+        valType: 'boolean',
+        
+        dflt: true,
+        
+    },
+    title: axesAttrs.title,
+    titlefont: axesAttrs.titlefont,
+    type: axesAttrs.type,
+    autorange: axesAttrs.autorange,
+    rangemode: axesAttrs.rangemode,
+    range: axesAttrs.range,
+    fixedrange: axesAttrs.fixedrange,
+    // ticks
+    tickmode: axesAttrs.tickmode,
+    nticks: axesAttrs.nticks,
+    tick0: axesAttrs.tick0,
+    dtick: axesAttrs.dtick,
+    tickvals: axesAttrs.tickvals,
+    ticktext: axesAttrs.ticktext,
+    ticks: axesAttrs.ticks,
+    mirror: axesAttrs.mirror,
+    ticklen: axesAttrs.ticklen,
+    tickwidth: axesAttrs.tickwidth,
+    tickcolor: axesAttrs.tickcolor,
+    showticklabels: axesAttrs.showticklabels,
+    tickfont: axesAttrs.tickfont,
+    tickangle: axesAttrs.tickangle,
+    tickprefix: axesAttrs.tickprefix,
+    showtickprefix: axesAttrs.showtickprefix,
+    ticksuffix: axesAttrs.ticksuffix,
+    showticksuffix: axesAttrs.showticksuffix,
+    showexponent: axesAttrs.showexponent,
+    exponentformat: axesAttrs.exponentformat,
+    tickformat: axesAttrs.tickformat,
+    hoverformat: axesAttrs.hoverformat,
+    // lines and grids
+    showline: axesAttrs.showline,
+    linecolor: axesAttrs.linecolor,
+    linewidth: axesAttrs.linewidth,
+    showgrid: axesAttrs.showgrid,
+    gridcolor: extendFlat({}, axesAttrs.gridcolor,  // shouldn't this be on-par with 2D?
+        {dflt: 'rgb(204, 204, 204)'}),
+    gridwidth: axesAttrs.gridwidth,
+    zeroline: axesAttrs.zeroline,
+    zerolinecolor: axesAttrs.zerolinecolor,
+    zerolinewidth: axesAttrs.zerolinewidth
+};
+
+},{"../../../lib/extend":345,"../../cartesian/layout_attributes":376}],403:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../../lib');
+var layoutAttributes = require('./axis_attributes');
+var handleAxisDefaults = require('../../cartesian/axis_defaults');
+
+var axesNames = ['xaxis', 'yaxis', 'zaxis'];
+var noop = function() {};
+
+
+module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, options) {
+    var containerIn, containerOut;
+
+    function coerce(attr, dflt) {
+        return Lib.coerce(containerIn, containerOut, layoutAttributes, attr, dflt);
+    }
+
+    for(var j = 0; j < axesNames.length; j++) {
+        var axName = axesNames[j];
+        containerIn = layoutIn[axName] || {};
+
+        containerOut = {
+            _id: axName[0] + options.scene,
+            _name: axName
+        };
+
+        layoutOut[axName] = containerOut = handleAxisDefaults(
+            containerIn,
+            containerOut,
+            coerce, {
+                font: options.font,
+                letter: axName[0],
+                data: options.data,
+                showGrid: true
+            });
+
+        coerce('gridcolor');
+        coerce('title', axName[0]);  // shouldn't this be on-par with 2D?
+
+        containerOut.setScale = noop;
+
+        if(coerce('showspikes')) {
+            coerce('spikesides');
+            coerce('spikethickness');
+            coerce('spikecolor');
+        }
+        if(coerce('showbackground')) coerce('backgroundcolor');
+
+        coerce('showaxeslabels');
+    }
+};
+
+},{"../../../lib":349,"../../cartesian/axis_defaults":370,"./axis_attributes":402}],404:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var arrtools = require('arraytools');
+var convertHTML = require('../../../lib/html2unicode');
+var str2RgbaArray = require('../../../lib/str2rgbarray');
+
+var arrayCopy1D = arrtools.copy1D;
+
+var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis'];
+
+function AxesOptions() {
+    this.bounds = [
+        [-10, -10, -10],
+        [10, 10, 10]
+    ];
+
+    this.ticks = [ [], [], [] ];
+    this.tickEnable = [ true, true, true ];
+    this.tickFont = [ 'sans-serif', 'sans-serif', 'sans-serif' ];
+    this.tickSize = [ 12, 12, 12 ];
+    this.tickAngle = [ 0, 0, 0 ];
+    this.tickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ];
+    this.tickPad = [ 18, 18, 18 ];
+
+    this.labels = [ 'x', 'y', 'z' ];
+    this.labelEnable = [ true, true, true ];
+    this.labelFont = ['Open Sans','Open Sans','Open Sans'];
+    this.labelSize = [ 20, 20, 20 ];
+    this.labelAngle = [ 0, 0, 0 ];
+    this.labelColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ];
+    this.labelPad = [ 30, 30, 30 ];
+
+    this.lineEnable = [ true, true, true ];
+    this.lineMirror = [ false, false, false ];
+    this.lineWidth = [ 1, 1, 1 ];
+    this.lineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ];
+
+    this.lineTickEnable = [ true, true, true ];
+    this.lineTickMirror = [ false, false, false ];
+    this.lineTickLength = [ 10, 10, 10 ];
+    this.lineTickWidth = [ 1, 1, 1 ];
+    this.lineTickColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ];
+
+    this.gridEnable = [ true, true, true ];
+    this.gridWidth = [ 1, 1, 1 ];
+    this.gridColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ];
+
+    this.zeroEnable = [ true, true, true ];
+    this.zeroLineColor = [ [0,0,0,1], [0,0,0,1], [0,0,0,1] ];
+    this.zeroLineWidth = [ 2, 2, 2 ];
+
+    this.backgroundEnable = [ true, true, true ];
+    this.backgroundColor = [ [0.8, 0.8, 0.8, 0.5],
+                              [0.8, 0.8, 0.8, 0.5],
+                              [0.8, 0.8, 0.8, 0.5] ];
+
+    // some default values are stored for applying model transforms
+    this._defaultTickPad = arrayCopy1D(this.tickPad);
+    this._defaultLabelPad = arrayCopy1D(this.labelPad);
+    this._defaultLineTickLength = arrayCopy1D(this.lineTickLength);
+}
+
+var proto = AxesOptions.prototype;
+
+proto.merge = function(sceneLayout) {
+    var opts = this;
+    for(var i = 0; i < 3; ++i) {
+        var axes = sceneLayout[AXES_NAMES[i]];
+
+        /////// Axes labels //
+        opts.labels[i] = convertHTML(axes.title);
+        if('titlefont' in axes) {
+            if(axes.titlefont.color) opts.labelColor[i] = str2RgbaArray(axes.titlefont.color);
+            if(axes.titlefont.family) opts.labelFont[i] = axes.titlefont.family;
+            if(axes.titlefont.size) opts.labelSize[i] = axes.titlefont.size;
+        }
+
+        /////// LINES ////////
+        if('showline' in axes) opts.lineEnable[i] = axes.showline;
+        if('linecolor' in axes) opts.lineColor[i] = str2RgbaArray(axes.linecolor);
+        if('linewidth' in axes) opts.lineWidth[i] = axes.linewidth;
+
+        if('showgrid' in axes) opts.gridEnable[i] = axes.showgrid;
+        if('gridcolor' in axes) opts.gridColor[i] = str2RgbaArray(axes.gridcolor);
+        if('gridwidth' in axes) opts.gridWidth[i] = axes.gridwidth;
+
+        // Remove zeroline if axis type is log
+        // otherwise the zeroline is incorrectly drawn at 1 on log axes
+        if(axes.type === 'log') opts.zeroEnable[i] = false;
+        else if('zeroline' in axes) opts.zeroEnable[i] = axes.zeroline;
+        if('zerolinecolor' in axes) opts.zeroLineColor[i] = str2RgbaArray(axes.zerolinecolor);
+        if('zerolinewidth' in axes) opts.zeroLineWidth[i] = axes.zerolinewidth;
+
+        //////// TICKS /////////
+        /// tick lines
+        if('ticks' in axes && !!axes.ticks) opts.lineTickEnable[i] = true;
+        else opts.lineTickEnable[i] = false;
+
+        if('ticklen' in axes) {
+            opts.lineTickLength[i] = opts._defaultLineTickLength[i] = axes.ticklen;
+        }
+        if('tickcolor' in axes) opts.lineTickColor[i] = str2RgbaArray(axes.tickcolor);
+        if('tickwidth' in axes) opts.lineTickWidth[i] = axes.tickwidth;
+        if('tickangle' in axes) {
+            opts.tickAngle[i] = (axes.tickangle === 'auto') ?
+                0 :
+                Math.PI * -axes.tickangle / 180;
+        }
+        // tick labels
+        if('showticklabels' in axes) opts.tickEnable[i] = axes.showticklabels;
+        if('tickfont' in axes) {
+            if(axes.tickfont.color) opts.tickColor[i] = str2RgbaArray(axes.tickfont.color);
+            if(axes.tickfont.family) opts.tickFont[i] = axes.tickfont.family;
+            if(axes.tickfont.size) opts.tickSize[i] = axes.tickfont.size;
+        }
+
+        if('mirror' in axes) {
+            if(['ticks','all','allticks'].indexOf(axes.mirror) !== -1) {
+                opts.lineTickMirror[i] = true;
+                opts.lineMirror[i] = true;
+            } else if(axes.mirror === true) {
+                opts.lineTickMirror[i] = false;
+                opts.lineMirror[i] = true;
+            } else {
+                opts.lineTickMirror[i] = false;
+                opts.lineMirror[i] = false;
+            }
+        } else opts.lineMirror[i] = false;
+
+        // grid background
+        if('showbackground' in axes && axes.showbackground !== false) {
+            opts.backgroundEnable[i] = true;
+            opts.backgroundColor[i] = str2RgbaArray(axes.backgroundcolor);
+        } else opts.backgroundEnable[i] = false;
+    }
+};
+
+
+function createAxesOptions(plotlyOptions) {
+    var result = new AxesOptions();
+    result.merge(plotlyOptions);
+    return result;
+}
+
+module.exports = createAxesOptions;
+
+},{"../../../lib/html2unicode":348,"../../../lib/str2rgbarray":359,"arraytools":48}],405:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../../lib');
+var Plots = require('../../plots');
+var layoutAttributes = require('./layout_attributes');
+var supplyGl3dAxisLayoutDefaults = require('./axis_defaults');
+
+
+module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
+    if(!layoutOut._hasGL3D) return;
+
+    var scenes = Plots.findSubplotIds(fullData, 'gl3d'),
+        scenesLength = scenes.length;
+
+    var sceneLayoutIn, sceneLayoutOut;
+
+    function coerce(attr, dflt) {
+        return Lib.coerce(sceneLayoutIn, sceneLayoutOut, layoutAttributes, attr, dflt);
+    }
+
+    // some layout-wide attribute are used in all scenes
+    // if 3D is the only visible plot type
+    function getDfltFromLayout(attr) {
+        var isOnlyGL3D = !(
+            layoutOut._hasCartesian ||
+            layoutOut._hasGeo ||
+            layoutOut._hasGL2D ||
+            layoutOut._hasPie
+        );
+
+        var isValid = layoutAttributes[attr].values.indexOf(layoutIn[attr]) !== -1;
+
+        if(isOnlyGL3D && isValid) return layoutIn[attr];
+    }
+
+    for(var i = 0; i < scenesLength; i++) {
+        var scene = scenes[i];
+
+        /*
+         * Scene numbering proceeds as follows
+         * scene
+         * scene2
+         * scene3
+         *
+         * and d.scene will be undefined or some number or number string
+         *
+         * Also write back a blank scene object to user layout so that some
+         * attributes like aspectratio can be written back dynamically.
+         */
+
+        // gl3d traces get a layout scene for free!
+        if(layoutIn[scene]) sceneLayoutIn = layoutIn[scene];
+        else layoutIn[scene] = sceneLayoutIn = {};
+
+        sceneLayoutOut = layoutOut[scene] || {};
+
+        coerce('bgcolor');
+
+        var cameraKeys = Object.keys(layoutAttributes.camera);
+
+        for(var j = 0; j < cameraKeys.length; j++) {
+            coerce('camera.' + cameraKeys[j] + '.x');
+            coerce('camera.' + cameraKeys[j] + '.y');
+            coerce('camera.' + cameraKeys[j] + '.z');
+        }
+
+        coerce('domain.x', [i / scenesLength, (i+1) / scenesLength]);
+        coerce('domain.y');
+
+        /*
+         * coerce to positive number (min 0) but also do not accept 0 (>0 not >=0)
+         * note that 0's go false with the !! call
+         */
+        var hasAspect = !!coerce('aspectratio.x') &&
+                        !!coerce('aspectratio.y') &&
+                        !!coerce('aspectratio.z');
+
+        var defaultAspectMode = hasAspect ? 'manual' : 'auto';
+        var aspectMode = coerce('aspectmode', defaultAspectMode);
+
+        /*
+         * We need aspectratio object in all the Layouts as it is dynamically set
+         * in the calculation steps, ie, we cant set the correct data now, it happens later.
+         * We must also account for the case the user sends bad ratio data with 'manual' set
+         * for the mode. In this case we must force change it here as the default coerce
+         * misses it above.
+         */
+        if(!hasAspect) {
+            sceneLayoutIn.aspectratio = sceneLayoutOut.aspectratio = {x: 1, y: 1, z: 1};
+
+            if(aspectMode === 'manual') sceneLayoutOut.aspectmode = 'auto';
+        }
+
+        /*
+         * scene arrangements need to be implemented: For now just splice
+         * along the horizontal direction. ie.
+         * x:[0,1] -> x:[0,0.5], x:[0.5,1] ->
+         *     x:[0, 0.333] x:[0.333,0.666] x:[0.666, 1]
+         */
+        supplyGl3dAxisLayoutDefaults(sceneLayoutIn, sceneLayoutOut, {
+            font: layoutOut.font,
+            scene: scene,
+            data: fullData
+        });
+
+        coerce('dragmode', getDfltFromLayout('dragmode'));
+        coerce('hovermode', getDfltFromLayout('hovermode'));
+
+        layoutOut[scene] = sceneLayoutOut;
+    }
+};
+
+},{"../../../lib":349,"../../plots":413,"./axis_defaults":403,"./layout_attributes":406}],406:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var gl3dAxisAttrs = require('./axis_attributes');
+var extendFlat = require('../../../lib/extend').extendFlat;
+
+function makeVector(x, y, z) {
+    return {
+        x: {
+            valType: 'number',
+            
+            dflt: x
+        },
+        y: {
+            valType: 'number',
+            
+            dflt: y
+        },
+        z: {
+            valType: 'number',
+            
+            dflt: z
+        }
+    };
+}
+
+module.exports = {
+    bgcolor: {
+        valType: 'color',
+        
+        dflt: 'rgba(0,0,0,0)'
+    },
+    camera: {
+        up: extendFlat(makeVector(0, 0, 1), {
+            
+        }),
+        center: extendFlat(makeVector(0, 0, 0), {
+            
+        }),
+        eye: extendFlat(makeVector(1.25, 1.25, 1.25), {
+            
+        })
+    },
+    domain: {
+        x: {
+            valType: 'info_array',
+            
+            items: [
+                {valType: 'number', min: 0, max: 1},
+                {valType: 'number', min: 0, max: 1}
+            ],
+            dflt: [0, 1],
+            
+        },
+        y: {
+            valType: 'info_array',
+            
+            items: [
+                {valType: 'number', min: 0, max: 1},
+                {valType: 'number', min: 0, max: 1}
+            ],
+            dflt: [0, 1],
+            
+        }
+    },
+    aspectmode: {
+        valType: 'enumerated',
+        
+        values: ['auto', 'cube', 'data', 'manual'],
+        dflt: 'auto',
+        
+    },
+    aspectratio: { // must be positive (0's are coerced to 1)
+        x: {
+            valType: 'number',
+            
+            min: 0
+        },
+        y: {
+            valType: 'number',
+            
+            min: 0
+        },
+        z: {
+            valType: 'number',
+            
+            min: 0
+        },
+        
+    },
+
+    xaxis: gl3dAxisAttrs,
+    yaxis: gl3dAxisAttrs,
+    zaxis: gl3dAxisAttrs,
+
+    dragmode: {
+        valType: 'enumerated',
+        
+        values: ['orbit', 'turntable', 'zoom', 'pan'],
+        dflt: 'turntable',
+        
+    },
+    hovermode: {
+        valType: 'enumerated',
+        
+        values: ['closest', false],
+        dflt: 'closest',
+        
+    },
+
+    _deprecated: {
+        cameraposition: {
+            valType: 'info_array',
+            
+            
+        }
+    }
+};
+
+},{"../../../lib/extend":345,"./axis_attributes":402}],407:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var str2RGBArray = require('../../../lib/str2rgbarray');
+
+var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis'];
+
+function SpikeOptions() {
+    this.enabled = [true, true, true];
+    this.colors = [[0,0,0,1],
+                   [0,0,0,1],
+                   [0,0,0,1]];
+    this.drawSides = [true, true, true];
+    this.lineWidth = [1,1,1];
+}
+
+var proto = SpikeOptions.prototype;
+
+proto.merge = function(sceneLayout) {
+    for(var i = 0; i < 3; ++i) {
+        var axes = sceneLayout[AXES_NAMES[i]];
+
+        this.enabled[i] = axes.showspikes;
+        this.colors[i] = str2RGBArray(axes.spikecolor);
+        this.drawSides[i] = axes.spikesides;
+        this.lineWidth[i] = axes.spikethickness;
+    }
+};
+
+function createSpikeOptions(layout) {
+    var result = new SpikeOptions();
+    result.merge(layout);
+    return result;
+}
+
+module.exports = createSpikeOptions;
+
+},{"../../../lib/str2rgbarray":359}],408:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+/*eslint block-scoped-var: 0*/
+/*eslint no-redeclare: 0*/
+
+'use strict';
+
+module.exports = computeTickMarks;
+
+var Plotly = require('../../../plotly');
+var convertHTML = require('../../../lib/html2unicode');
+
+var AXES_NAMES = ['xaxis', 'yaxis', 'zaxis'];
+
+var centerPoint = [0,0,0];
+
+function contourLevelsFromTicks(ticks) {
+    var result = new Array(3);
+    for(var i=0; i<3; ++i) {
+        var tlevel = ticks[i];
+        var clevel = new Array(tlevel.length);
+        for(var j=0; j<tlevel.length; ++j) {
+            clevel[j] = tlevel[j].x;
+        }
+        result[i] = clevel;
+    }
+    return result;
+}
+
+function computeTickMarks(scene) {
+    var axesOptions = scene.axesOptions;
+    var glRange = scene.glplot.axesPixels;
+    var sceneLayout = scene.fullSceneLayout;
+
+    var ticks = [[],[],[]];
+
+    for(var i = 0; i < 3; ++i) {
+        var axes = sceneLayout[AXES_NAMES[i]];
+
+        axes._length = (glRange[i].hi - glRange[i].lo) *
+            glRange[i].pixelsPerDataUnit / scene.dataScale[i];
+
+        if(Math.abs(axes._length) === Infinity) {
+            ticks[i] = [];
+        } else {
+            axes.range[0] = (glRange[i].lo) / scene.dataScale[i];
+            axes.range[1] = (glRange[i].hi) / scene.dataScale[i];
+            axes._m = 1.0 / (scene.dataScale[i] * glRange[i].pixelsPerDataUnit);
+
+            if(axes.range[0] === axes.range[1]) {
+                axes.range[0] -= 1;
+                axes.range[1] += 1;
+            }
+            // this is necessary to short-circuit the 'y' handling
+            // in autotick part of calcTicks... Treating all axes as 'y' in this case
+            // running the autoticks here, then setting
+            // autoticks to false to get around the 2D handling in calcTicks.
+            var tickModeCached = axes.tickmode;
+            if(axes.tickmode === 'auto') {
+                axes.tickmode = 'linear';
+                var nticks = axes.nticks || Plotly.Lib.constrain((axes._length/40), 4, 9);
+                Plotly.Axes.autoTicks(axes, Math.abs(axes.range[1]-axes.range[0])/nticks);
+            }
+            var dataTicks = Plotly.Axes.calcTicks(axes);
+            for(var j=0; j<dataTicks.length; ++j) {
+                dataTicks[j].x = dataTicks[j].x * scene.dataScale[i];
+                dataTicks[j].text = convertHTML(dataTicks[j].text);
+            }
+            ticks[i] = dataTicks;
+
+
+            axes.tickmode = tickModeCached;
+        }
+    }
+
+    axesOptions.ticks = ticks;
+
+    //Calculate tick lengths dynamically
+    for(var i=0; i<3; ++i) {
+        centerPoint[i] = 0.5 * (scene.glplot.bounds[0][i] + scene.glplot.bounds[1][i]);
+        for(var j=0; j<2; ++j) {
+            axesOptions.bounds[j][i] = scene.glplot.bounds[j][i];
+        }
+    }
+
+    scene.contourLevels = contourLevelsFromTicks(ticks);
+}
+
+},{"../../../lib/html2unicode":348,"../../../plotly":366}],409:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+function xformMatrix(m, v) {
+    var out = [0,0,0,0];
+    var i, j;
+
+    for(i = 0; i < 4; ++i) {
+        for(j = 0; j < 4; ++j) {
+            out[j] += m[4*i + j] * v[i];
+        }
+    }
+
+    return out;
+}
+
+function project(camera, v) {
+    var p = xformMatrix(camera.projection,
+        xformMatrix(camera.view,
+        xformMatrix(camera.model, [v[0], v[1], v[2], 1])));
+    return p;
+}
+
+module.exports = project;
+
+},{}],410:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+/*eslint block-scoped-var: 0*/
+/*eslint no-redeclare: 0*/
+
+'use strict';
+
+var createPlot = require('gl-plot3d');
+
+var Lib = require('../../lib');
+
+var Plots = require('../../plots/plots');
+var Axes = require('../../plots/cartesian/axes');
+var Fx = require('../../plots/cartesian/graph_interact');
+
+var str2RGBAarray = require('../../lib/str2rgbarray');
+var showNoWebGlMsg = require('../../lib/show_no_webgl_msg');
+
+var createCamera = require('./camera');
+var project = require('./project');
+var setConvert = require('./set_convert');
+var createAxesOptions = require('./layout/convert');
+var createSpikeOptions = require('./layout/spikes');
+var computeTickMarks = require('./layout/tick_marks');
+
+var STATIC_CANVAS, STATIC_CONTEXT;
+
+function render(scene) {
+
+    // update size of svg container
+    var svgContainer = scene.svgContainer;
+    var clientRect = scene.container.getBoundingClientRect();
+    var width = clientRect.width, height = clientRect.height;
+    svgContainer.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height);
+    svgContainer.setAttributeNS(null, 'width', width);
+    svgContainer.setAttributeNS(null, 'height', height);
+
+    computeTickMarks(scene);
+    scene.glplot.axes.update(scene.axesOptions);
+
+    // check if pick has changed
+    var keys = Object.keys(scene.traces);
+    var lastPicked = null;
+    var selection = scene.glplot.selection;
+    for(var i = 0; i < keys.length; ++i) {
+        var trace = scene.traces[keys[i]];
+        if(trace.handlePick(selection)) {
+            lastPicked = trace;
+        }
+
+        if(trace.setContourLevels) trace.setContourLevels();
+    }
+
+    function formatter(axisName, val) {
+        if(typeof val === 'string') return val;
+
+        var axis = scene.fullSceneLayout[axisName];
+        return Axes.tickText(axis, axis.c2l(val), 'hover').text;
+    }
+
+    var oldEventData;
+
+    if(lastPicked !== null) {
+        var pdata = project(scene.glplot.cameraParams, selection.dataCoordinate),
+            trace = lastPicked.data,
+            hoverinfo = trace.hoverinfo;
+
+        var xVal = formatter('xaxis', selection.traceCoordinate[0]),
+            yVal = formatter('yaxis', selection.traceCoordinate[1]),
+            zVal = formatter('zaxis', selection.traceCoordinate[2]);
+
+        if(hoverinfo !== 'all') {
+            var hoverinfoParts = hoverinfo.split('+');
+            if(hoverinfoParts.indexOf('x') === -1) xVal = undefined;
+            if(hoverinfoParts.indexOf('y') === -1) yVal = undefined;
+            if(hoverinfoParts.indexOf('z') === -1) zVal = undefined;
+            if(hoverinfoParts.indexOf('text') === -1) selection.textLabel = undefined;
+            if(hoverinfoParts.indexOf('name') === -1) lastPicked.name = undefined;
+        }
+
+        if(scene.fullSceneLayout.hovermode) {
+            Fx.loneHover({
+                x: (0.5 + 0.5 * pdata[0] / pdata[3]) * width,
+                y: (0.5 - 0.5 * pdata[1] / pdata[3]) * height,
+                xLabel: xVal,
+                yLabel: yVal,
+                zLabel: zVal,
+                text: selection.textLabel,
+                name: lastPicked.name,
+                color: lastPicked.color
+            }, {
+                container: svgContainer
+            });
+        }
+
+        var eventData = {
+            points: [{
+                x: xVal,
+                y: yVal,
+                z: zVal,
+                data: trace._input,
+                fullData: trace,
+                curveNumber: trace.index,
+                pointNumber: selection.data.index
+            }]
+        };
+
+        if(selection.buttons && selection.distance < 5) {
+            scene.graphDiv.emit('plotly_click', eventData);
+        }
+        else {
+            scene.graphDiv.emit('plotly_hover', eventData);
+        }
+
+        oldEventData = eventData;
+    }
+    else {
+        Fx.loneUnhover(svgContainer);
+        scene.graphDiv.emit('plotly_unhover', oldEventData);
+    }
+}
+
+function initializeGLPlot(scene, fullLayout, canvas, gl) {
+    var glplotOptions = {
+        canvas: canvas,
+        gl: gl,
+        container: scene.container,
+        axes: scene.axesOptions,
+        spikes: scene.spikeOptions,
+        pickRadius: 10,
+        snapToData: true,
+        autoScale: true,
+        autoBounds: false
+    };
+
+    // for static plots, we reuse the WebGL context
+    //  as WebKit doesn't collect them reliably
+    if(scene.staticMode) {
+        if(!STATIC_CONTEXT) {
+            STATIC_CANVAS = document.createElement('canvas');
+            try {
+                STATIC_CONTEXT = STATIC_CANVAS.getContext('webgl', {
+                    preserveDrawingBuffer: true,
+                    premultipliedAlpha: true
+                });
+            } catch(e) {
+                throw new Error('error creating static canvas/context for image server');
+            }
+        }
+        glplotOptions.pixelRatio = scene.pixelRatio;
+        glplotOptions.gl = STATIC_CONTEXT;
+        glplotOptions.canvas = STATIC_CANVAS;
+    }
+
+    try {
+        scene.glplot = createPlot(glplotOptions);
+    }
+    catch(e) {
+        /*
+        * createPlot will throw when webgl is not enabled in the client.
+        * Lets return an instance of the module with all functions noop'd.
+        * The destroy method - which will remove the container from the DOM
+        * is overridden with a function that removes the container only.
+        */
+        showNoWebGlMsg(scene);
+    }
+
+    if(!scene.staticMode) {
+        scene.glplot.canvas.addEventListener('webglcontextlost', function(ev) {
+            console.log('lost context');
+            ev.preventDefault();
+        });
+    }
+
+    if(!scene.camera) {
+        var cameraData = scene.fullSceneLayout.camera;
+        scene.camera = createCamera(scene.container, {
+            center: [cameraData.center.x, cameraData.center.y, cameraData.center.z],
+            eye: [cameraData.eye.x, cameraData.eye.y, cameraData.eye.z],
+            up: [cameraData.up.x, cameraData.up.y, cameraData.up.z],
+            zoomMin: 0.1,
+            zoomMax: 100,
+            mode: 'orbit'
+        });
+    }
+
+    scene.glplot.mouseListener.enabled = false;
+    scene.glplot.camera = scene.camera;
+
+    scene.glplot.oncontextloss = function() {
+        scene.recoverContext();
+    };
+
+    scene.glplot.onrender = render.bind(null, scene);
+
+    //List of scene objects
+    scene.traces = {};
+
+    return true;
+}
+
+function Scene(options, fullLayout) {
+
+    // create sub container for plot
+    var sceneContainer = document.createElement('div');
+    var plotContainer = options.container;
+
+    // keep a ref to the graph div to fire hover+click events
+    this.graphDiv = options.graphDiv;
+
+    // create SVG container for hover text
+    var svgContainer = document.createElementNS(
+        'http://www.w3.org/2000/svg',
+        'svg');
+    svgContainer.style.position = 'absolute';
+    svgContainer.style.top = svgContainer.style.left = '0px';
+    svgContainer.style.width = svgContainer.style.height = '100%';
+    svgContainer.style['z-index'] = 20;
+    svgContainer.style['pointer-events'] = 'none';
+    sceneContainer.appendChild(svgContainer);
+    this.svgContainer = svgContainer;
+
+    // Tag the container with the sceneID
+    sceneContainer.id = options.id;
+    sceneContainer.style.position = 'absolute';
+    sceneContainer.style.top = sceneContainer.style.left = '0px';
+    sceneContainer.style.width = sceneContainer.style.height = '100%';
+    plotContainer.appendChild(sceneContainer);
+
+    this.fullLayout = fullLayout;
+    this.id = options.id || 'scene';
+    this.fullSceneLayout = fullLayout[this.id];
+
+    //Saved from last call to plot()
+    this.plotArgs = [ [], {}, {} ];
+
+    /*
+     * Move this to calc step? Why does it work here?
+     */
+    this.axesOptions = createAxesOptions(fullLayout[this.id]);
+    this.spikeOptions = createSpikeOptions(fullLayout[this.id]);
+    this.container = sceneContainer;
+    this.staticMode = !!options.staticPlot;
+    this.pixelRatio = options.plotGlPixelRatio || 2;
+
+    //Coordinate rescaling
+    this.dataScale = [1,1,1];
+
+    this.contourLevels = [ [], [], [] ];
+
+    if(!initializeGLPlot(this, fullLayout)) return;
+}
+
+var proto = Scene.prototype;
+
+proto.recoverContext = function() {
+    var scene = this;
+    var gl = this.glplot.gl;
+    var canvas = this.glplot.canvas;
+    this.glplot.dispose();
+
+    function tryRecover() {
+        if(gl.isContextLost()) {
+            requestAnimationFrame(tryRecover);
+            return;
+        }
+        if(!initializeGLPlot(scene, scene.fullLayout, canvas, gl)) {
+            console.error('catastrophic/unrecoverable webgl error.  context lost.');
+            return;
+        }
+        scene.plot.apply(scene, scene.plotArgs);
+    }
+    requestAnimationFrame(tryRecover);
+};
+
+var axisProperties = [ 'xaxis', 'yaxis', 'zaxis' ];
+
+function coordinateBound(axis, coord, d, bounds) {
+    for(var i=0; i<coord.length; ++i) {
+        if(Array.isArray(coord[i])) {
+            for(var j=0; j<coord[i].length; ++j) {
+                var x = axis.d2l(coord[i][j]);
+                if(!isNaN(x) && isFinite(x)) {
+                    bounds[0][d] = Math.min(bounds[0][d], x);
+                    bounds[1][d] = Math.max(bounds[1][d], x);
+                }
+            }
+        }
+        else {
+            var x = axis.d2l(coord[i]);
+            if(!isNaN(x) && isFinite(x)) {
+                bounds[0][d] = Math.min(bounds[0][d], x);
+                bounds[1][d] = Math.max(bounds[1][d], x);
+            }
+        }
+    }
+}
+
+function computeTraceBounds(scene, trace, bounds) {
+    var sceneLayout = scene.fullSceneLayout;
+    coordinateBound(sceneLayout.xaxis, trace.x, 0, bounds);
+    coordinateBound(sceneLayout.yaxis, trace.y, 1, bounds);
+    coordinateBound(sceneLayout.zaxis, trace.z, 2, bounds);
+}
+
+proto.plot = function(sceneData, fullLayout, layout) {
+    //Save parameters
+    this.plotArgs = [sceneData, fullLayout, layout];
+
+    if(this.glplot.contextLost) return;
+
+    var data, trace;
+    var i, j;
+    var fullSceneLayout = fullLayout[this.id];
+    var sceneLayout = layout[this.id];
+
+    if(fullSceneLayout.bgcolor) this.glplot.clearColor = str2RGBAarray(fullSceneLayout.bgcolor);
+    else this.glplot.clearColor = [0, 0, 0, 0];
+
+    this.glplot.snapToData = true;
+
+    //Update layout
+    this.fullSceneLayout = fullSceneLayout;
+
+    this.glplotLayout = fullSceneLayout;
+    this.axesOptions.merge(fullSceneLayout);
+    this.spikeOptions.merge(fullSceneLayout);
+
+    // Update camera mode
+    this.updateFx(fullSceneLayout.dragmode, fullSceneLayout.hovermode);
+
+    //Update scene
+    this.glplot.update({});
+
+    // Update axes functions BEFORE updating traces
+    for(i = 0; i < 3; ++i) {
+        var axis = fullSceneLayout[axisProperties[i]];
+        setConvert(axis);
+    }
+
+    //Convert scene data
+    if(!sceneData) sceneData = [];
+    else if(!Array.isArray(sceneData)) sceneData = [sceneData];
+
+    //Compute trace bounding box
+    var dataBounds = [
+        [Infinity, Infinity, Infinity],
+        [-Infinity, -Infinity, -Infinity]
+    ];
+    for(var i=0; i<sceneData.length; ++i) {
+        var data = sceneData[i];
+        if(data.visible !== true) continue;
+
+        computeTraceBounds(this, data, dataBounds);
+    }
+    var dataScale = [1,1,1];
+    for(var j=0; j<3; ++j) {
+        if(dataBounds[0][j] > dataBounds[1][j]) {
+            dataScale[j] = 1.0;
+        }
+        else {
+            if(dataBounds[1][j] === dataBounds[0][j]) {
+                dataScale[j] = 1.0;
+            }
+            else {
+                dataScale[j] = 1.0/(dataBounds[1][j] - dataBounds[0][j]);
+            }
+        }
+    }
+
+    //Save scale
+    this.dataScale = dataScale;
+
+    //Update traces
+    for(var i = 0; i < sceneData.length; ++i) {
+        data = sceneData[i];
+        if(data.visible!==true) {
+            continue;
+        }
+        trace = this.traces[data.uid];
+        if(trace) {
+            trace.update(data);
+        } else {
+            var traceModule = Plots.getModule(data.type);
+            trace = traceModule.plot(this, data);
+            this.traces[data.uid] = trace;
+        }
+        trace.name = data.name;
+    }
+
+    //Remove empty traces
+    var traceIds = Object.keys(this.traces);
+
+    trace_id_loop:
+    for(i = 0; i<traceIds.length; ++i) {
+        for(j = 0; j<sceneData.length; ++j) {
+            if(sceneData[j].uid === traceIds[i] && sceneData[j].visible===true) {
+                continue trace_id_loop;
+            }
+        }
+        trace = this.traces[traceIds[i]];
+        trace.dispose();
+        delete this.traces[traceIds[i]];
+    }
+
+    //Update ranges (needs to be called *after* objects are added due to updates)
+    var sceneBounds = [[0,0,0], [0,0,0]],
+        axisDataRange = [],
+        axisTypeRatios = {};
+
+    for(i = 0; i < 3; ++i) {
+        var axis = fullSceneLayout[axisProperties[i]];
+        var axisType = axis.type;
+
+        if(axisType in axisTypeRatios) {
+            axisTypeRatios[axisType].acc *= dataScale[i];
+            axisTypeRatios[axisType].count += 1;
+        }
+        else {
+            axisTypeRatios[axisType] = {
+                acc: dataScale[i],
+                count: 1
+            };
+        }
+
+        if(axis.autorange) {
+            sceneBounds[0][i] = Infinity;
+            sceneBounds[1][i] = -Infinity;
+            for(j = 0; j < this.glplot.objects.length; ++j) {
+                var objBounds = this.glplot.objects[j].bounds;
+                sceneBounds[0][i] = Math.min(sceneBounds[0][i],
+                  objBounds[0][i] / dataScale[i]);
+                sceneBounds[1][i] = Math.max(sceneBounds[1][i],
+                  objBounds[1][i] / dataScale[i]);
+            }
+            if('rangemode' in axis && axis.rangemode === 'tozero') {
+                sceneBounds[0][i] = Math.min(sceneBounds[0][i], 0);
+                sceneBounds[1][i] = Math.max(sceneBounds[1][i], 0);
+            }
+            if(sceneBounds[0][i] > sceneBounds[1][i]) {
+                sceneBounds[0][i] = -1;
+                sceneBounds[1][i] = 1;
+            } else {
+                var d = sceneBounds[1][i] - sceneBounds[0][i];
+                sceneBounds[0][i] -= d/32.0;
+                sceneBounds[1][i] += d/32.0;
+            }
+        } else {
+            var range = fullSceneLayout[axisProperties[i]].range;
+            sceneBounds[0][i] = range[0];
+            sceneBounds[1][i] = range[1];
+        }
+        if(sceneBounds[0][i] === sceneBounds[1][i]) {
+            sceneBounds[0][i] -= 1;
+            sceneBounds[1][i] += 1;
+        }
+        axisDataRange[i] = sceneBounds[1][i] - sceneBounds[0][i];
+
+        //Update plot bounds
+        this.glplot.bounds[0][i] = sceneBounds[0][i] * dataScale[i];
+        this.glplot.bounds[1][i] = sceneBounds[1][i] * dataScale[i];
+    }
+
+    var axesScaleRatio = [1, 1, 1];
+
+    //Compute axis scale per category
+    for(var i=0; i<3; ++i) {
+        var axis = fullSceneLayout[axisProperties[i]];
+        var axisType = axis.type;
+        var axisRatio = axisTypeRatios[axisType];
+        axesScaleRatio[i] = Math.pow(axisRatio.acc, 1.0/axisRatio.count) / dataScale[i];
+    }
+
+    /*
+     * Dynamically set the aspect ratio depending on the users aspect settings
+     */
+    var axisAutoScaleFactor = 4;
+    var aspectRatio;
+
+    if(fullSceneLayout.aspectmode === 'auto') {
+
+        if(Math.max.apply(null, axesScaleRatio)/Math.min.apply(null, axesScaleRatio) <= axisAutoScaleFactor) {
+
+            /*
+             * USE DATA MODE WHEN AXIS RANGE DIMENSIONS ARE RELATIVELY EQUAL
+             */
+
+            aspectRatio = axesScaleRatio;
+        } else {
+
+            /*
+             * USE EQUAL MODE WHEN AXIS RANGE DIMENSIONS ARE HIGHLY UNEQUAL
+             */
+            aspectRatio = [1, 1, 1];
+        }
+
+    } else if(fullSceneLayout.aspectmode === 'cube') {
+        aspectRatio = [1, 1, 1];
+
+    } else if(fullSceneLayout.aspectmode === 'data') {
+        aspectRatio = axesScaleRatio;
+
+    } else if(fullSceneLayout.aspectmode === 'manual') {
+        var userRatio = fullSceneLayout.aspectratio;
+        aspectRatio = [userRatio.x, userRatio.y, userRatio.z];
+
+    } else {
+        throw new Error('scene.js aspectRatio was not one of the enumerated types');
+    }
+
+    /*
+     * Write aspect Ratio back to user data and fullLayout so that it is modifies as user
+     * manipulates the aspectmode settings and the fullLayout is up-to-date.
+     */
+    fullSceneLayout.aspectratio.x = sceneLayout.aspectratio.x = aspectRatio[0];
+    fullSceneLayout.aspectratio.y = sceneLayout.aspectratio.y = aspectRatio[1];
+    fullSceneLayout.aspectratio.z = sceneLayout.aspectratio.z = aspectRatio[2];
+
+    /*
+     * Finally assign the computed aspecratio to the glplot module. This will have an effect
+     * on the next render cycle.
+     */
+    this.glplot.aspect = aspectRatio;
+
+
+    //Update frame position for multi plots
+    var domain = fullSceneLayout.domain || null,
+        size = fullLayout._size || null;
+
+    if(domain && size) {
+        var containerStyle = this.container.style;
+        containerStyle.position = 'absolute';
+        containerStyle.left = (size.l + domain.x[0] * size.w) + 'px';
+        containerStyle.top = (size.t + (1 - domain.y[1]) * size.h) + 'px';
+        containerStyle.width = (size.w * (domain.x[1] - domain.x[0])) + 'px';
+        containerStyle.height = (size.h * (domain.y[1] - domain.y[0])) + 'px';
+    }
+};
+
+proto.destroy = function() {
+    this.glplot.dispose();
+    this.container.parentNode.removeChild(this.container);
+
+    //Remove reference to glplot
+    this.glplot = null;
+};
+
+
+// for reset camera button in mode bar
+proto.setCameraToDefault = function setCameraToDefault() {
+    // as in Gl3d.layoutAttributes
+    this.glplot.camera.lookAt(
+        [1.25, 1.25, 1.25],
+        [0, 0, 0],
+        [0, 0, 1]
+    );
+};
+
+// get camera position in plotly coords from 'orbit-camera' coords
+proto.getCamera = function getCamera() {
+    this.glplot.camera.view.recalcMatrix(this.camera.view.lastT());
+
+    var up = this.glplot.camera.up;
+    var center = this.glplot.camera.center;
+    var eye = this.glplot.camera.eye;
+
+    return {
+        up: {x: up[0], y: up[1], z: up[2]},
+        center: {x: center[0], y: center[1], z: center[2]},
+        eye: {x: eye[0], y: eye[1], z: eye[2]}
+    };
+};
+
+// set camera position with a set of plotly coords
+proto.setCamera = function setCamera(cameraData) {
+    var up = cameraData.up;
+    var center = cameraData.center;
+    var eye = cameraData.eye;
+    this.glplot.camera.lookAt(
+        [eye.x, eye.y, eye.z],
+        [center.x, center.y, center.z],
+        [up.x, up.y, up.z]
+    );
+};
+
+// save camera to user layout (i.e. gd.layout)
+proto.saveCamera = function saveCamera(layout) {
+    var cameraData = this.getCamera(),
+        cameraNestedProp = Lib.nestedProperty(layout, this.id + '.camera'),
+        cameraDataLastSave = cameraNestedProp.get(),
+        hasChanged = false;
+
+    function same(x, y, i, j) {
+        var vectors = ['up', 'center', 'eye'],
+            components = ['x', 'y', 'z'];
+        return x[vectors[i]][components[j]] === y[vectors[i]][components[j]];
+    }
+
+    if(cameraDataLastSave === undefined) hasChanged = true;
+    else {
+        for(var i = 0; i < 3; i++) {
+            for(var j = 0; j < 3; j++) {
+                if(!same(cameraData, cameraDataLastSave, i, j)) {
+                    hasChanged = true;
+                    break;
+                }
+            }
+        }
+    }
+
+    if(hasChanged) cameraNestedProp.set(cameraData);
+
+    return hasChanged;
+};
+
+proto.updateFx = function(dragmode, hovermode) {
+    var camera = this.camera;
+
+    if(camera) {
+        // rotate and orbital are synonymous
+        if(dragmode === 'orbit') {
+            camera.mode = 'orbit';
+            camera.keyBindingMode = 'rotate';
+
+        } else if(dragmode === 'turntable') {
+            camera.up = [0, 0, 1];
+            camera.mode = 'turntable';
+            camera.keyBindingMode = 'rotate';
+
+        } else {
+
+            // none rotation modes [pan or zoom]
+            camera.keyBindingMode = dragmode;
+        }
+    }
+
+    // to put dragmode and hovermode on the same grounds from relayout
+    this.fullSceneLayout.hovermode = hovermode;
+};
+
+proto.toImage = function(format) {
+    if(!format) format = 'png';
+
+    if(this.staticMode) this.container.appendChild(STATIC_CANVAS);
+
+    //Force redraw
+    this.glplot.redraw();
+
+    //Grab context and yank out pixels
+    var gl = this.glplot.gl;
+    var w = gl.drawingBufferWidth;
+    var h = gl.drawingBufferHeight;
+
+    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
+
+    var pixels = new Uint8Array(w * h * 4);
+    gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
+
+    //Flip pixels
+    for(var j=0,k=h-1; j<k; ++j, --k) {
+        for(var i=0; i<w; ++i) {
+            for(var l=0; l<4; ++l) {
+                var tmp = pixels[4*(w*j+i)+l];
+                pixels[4*(w*j+i)+l] = pixels[4*(w*k+i)+l];
+                pixels[4*(w*k+i)+l] = tmp;
+            }
+        }
+    }
+
+    var canvas = document.createElement('canvas');
+    canvas.width = w;
+    canvas.height = h;
+    var context = canvas.getContext('2d');
+    var imageData = context.createImageData(w, h);
+    imageData.data.set(pixels);
+    context.putImageData(imageData, 0, 0);
+
+    var dataURL;
+
+    switch(format) {
+        case 'jpeg':
+            dataURL = canvas.toDataURL('image/jpeg');
+            break;
+        case 'webp':
+            dataURL = canvas.toDataURL('image/webp');
+            break;
+        default:
+            dataURL = canvas.toDataURL('image/png');
+    }
+
+    if(this.staticMode) this.container.removeChild(STATIC_CANVAS);
+
+    return dataURL;
+};
+
+module.exports = Scene;
+
+},{"../../lib":349,"../../lib/show_no_webgl_msg":357,"../../lib/str2rgbarray":359,"../../plots/cartesian/axes":369,"../../plots/cartesian/graph_interact":374,"../../plots/plots":413,"./camera":399,"./layout/convert":404,"./layout/spikes":407,"./layout/tick_marks":408,"./project":409,"./set_convert":411,"gl-plot3d":140}],411:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Axes = require('../cartesian/axes');
+
+var noop = function() {};
+
+
+module.exports = function setConvert(containerOut) {
+    Axes.setConvert(containerOut);
+    containerOut.setScale = noop;
+};
+
+},{"../cartesian/axes":369}],412:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Plotly = require('../plotly');
+
+var fontAttrs = require('./font_attributes');
+var colorAttrs = require('../components/color/attributes');
+
+var extendFlat = Plotly.Lib.extendFlat;
+
+
+module.exports = {
+    font: {
+        family: extendFlat({}, fontAttrs.family, {
+            dflt: '"Open Sans", verdana, arial, sans-serif'
+        }),
+        size: extendFlat({}, fontAttrs.size, {
+            dflt: 12
+        }),
+        color: extendFlat({}, fontAttrs.color, {
+            dflt: colorAttrs.defaultLine
+        }),
+        
+    },
+    title: {
+        valType: 'string',
+        
+        dflt: 'Click to enter Plot title',
+        
+    },
+    titlefont: extendFlat({}, fontAttrs, {
+        
+    }),
+    autosize: {
+        valType: 'enumerated',
+        
+        // TODO: better handling of 'initial'
+        values: [true, false, 'initial'],
+        
+    },
+    width: {
+        valType: 'number',
+        
+        min: 10,
+        dflt: 700,
+        
+    },
+    height: {
+        valType: 'number',
+        
+        min: 10,
+        dflt: 450,
+        
+    },
+    margin: {
+        l: {
+            valType: 'number',
+            
+            min: 0,
+            dflt: 80,
+            
+        },
+        r: {
+            valType: 'number',
+            
+            min: 0,
+            dflt: 80,
+            
+        },
+        t: {
+            valType: 'number',
+            
+            min: 0,
+            dflt: 100,
+            
+        },
+        b: {
+            valType: 'number',
+            
+            min: 0,
+            dflt: 80,
+            
+        },
+        pad: {
+            valType: 'number',
+            
+            min: 0,
+            dflt: 0,
+            
+        },
+        autoexpand: {
+            valType: 'boolean',
+            
+            dflt: true
+        }
+    },
+    paper_bgcolor: {
+        valType: 'color',
+        
+        dflt: colorAttrs.background,
+        
+    },
+    plot_bgcolor: {
+        // defined here, but set in Axes.supplyLayoutDefaults
+        // because it needs to know if there are (2D) axes or not
+        valType: 'color',
+        
+        dflt: colorAttrs.background,
+        
+    },
+    separators: {
+        valType: 'string',
+        
+        dflt: '.,',
+        
+    },
+    hidesources: {
+        valType: 'boolean',
+        
+        dflt: false,
+        
+    },
+    smith: {
+        // will become a boolean if/when we implement this
+        valType: 'enumerated',
+        
+        values: [false],
+        dflt: false
+    },
+    showlegend: {
+        // handled in legend.supplyLayoutDefaults
+        // but included here because it's not in the legend object
+        valType: 'boolean',
+        
+        
+    },
+    _hasCartesian: {
+        valType: 'boolean',
+        dflt: false
+    },
+    _hasGL3D: {
+        valType: 'boolean',
+        dflt: false
+    },
+    _hasGeo: {
+        valType: 'boolean',
+        dflt: false
+    },
+    _hasPie: {
+        valType: 'boolean',
+        dflt: false
+    },
+    _hasGL2D: {
+        valType: 'boolean',
+        dflt: false
+    },
+    _composedModules: {
+        '*': 'Fx'
+    },
+
+    // TODO merge with moduleLayoutDefaults in plots.js
+    _nestedModules: {
+        'xaxis': 'Axes',
+        'yaxis': 'Axes',
+        'scene': 'gl3d',
+        'geo': 'geo',
+        'legend': 'Legend',
+        'annotations': 'Annotations',
+        'shapes': 'Shapes'
+    }
+};
+
+},{"../components/color/attributes":298,"../plotly":366,"./font_attributes":383}],413:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../plotly');
+var d3 = require('d3');
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../lib');
+
+var plots = module.exports = {};
+
+var modules = plots.modules = {},
+    allTypes = plots.allTypes = [],
+    allCategories = plots.allCategories = {},
+    subplotsRegistry = plots.subplotsRegistry = {};
+
+plots.attributes = require('./attributes');
+plots.attributes.type.values = allTypes;
+plots.fontAttrs = require('./font_attributes');
+plots.layoutAttributes = require('./layout_attributes');
+
+// TODO make this a plot attribute?
+plots.fontWeight = 'normal';
+
+/**
+ * plots.register: register a module as the handler for a trace type
+ *
+ * @param {object} _module the module that will handle plotting this trace type
+ * @param {string} thisType
+ * @param {array of strings} categoriesIn all the categories this type is in,
+ *     tested by calls: Plotly.Plots.traceIs(trace, oneCategory)
+ * @param {object} meta meta information about the trace type
+ */
+plots.register = function(_module, thisType, categoriesIn, meta) {
+    if(modules[thisType]) {
+        console.log('type ' + thisType + ' already registered');
+        return;
+    }
+
+    var categoryObj = {};
+    for(var i = 0; i < categoriesIn.length; i++) {
+        categoryObj[categoriesIn[i]] = true;
+        allCategories[categoriesIn[i]] = true;
+    }
+
+    modules[thisType] = {
+        _module: _module,
+        categories: categoryObj
+    };
+
+    if(meta && Object.keys(meta).length) {
+        modules[thisType].meta = meta;
+    }
+
+    allTypes.push(thisType);
+};
+
+function getTraceType(traceType) {
+    if(typeof traceType === 'object') traceType = traceType.type;
+    return traceType;
+}
+
+plots.getModule = function(trace) {
+    if(trace.r !== undefined) {
+        console.log('Oops, tried to put a polar trace ' +
+            'on an incompatible graph of cartesian ' +
+            'data. Ignoring this dataset.', trace
+        );
+        return false;
+    }
+
+    var _module = modules[getTraceType(trace)];
+    if(!_module) return false;
+    return _module._module;
+};
+
+
+/**
+ * plots.traceIs: is this trace type in this category?
+ *
+ * traceType: a trace (object) or trace type (string)
+ * category: a category (string)
+ */
+plots.traceIs = function traceIs(traceType, category) {
+    traceType = getTraceType(traceType);
+
+    if(traceType === 'various') return false;  // FIXME
+
+    var _module = modules[traceType];
+
+    if(!_module) {
+        if(traceType !== undefined) {
+            console.warn('unrecognized trace type ' + traceType);
+        }
+        _module = modules[plots.attributes.type.dflt];
+    }
+
+    return !!_module.categories[category];
+};
+
+
+/**
+ * plots.registerSubplot: register a subplot type
+ *
+ * @param {object} _module subplot module:
+ *
+ *      @param {string or array of strings} attr
+ *          attribute name in traces and layout
+ *      @param {string or array of strings} idRoot
+ *          root of id (setting the possible value for attrName)
+ *      @param {object} attributes
+ *          attribute(s) for traces of this subplot type
+ *
+ * In trace objects `attr` is the object key taking a valid `id` as value
+ * (the set of all valid ids is generated below and stored in idRegex).
+ *
+ * In the layout object, a or several valid `attr` name(s) can be keys linked
+ * to a nested attribute objects
+ * (the set of all valid attr names is generated below and stored in attrRegex).
+ *
+ * TODO use these in Lib.coerce
+ */
+plots.registerSubplot = function(_module) {
+    var plotType = _module.name;
+
+    if(subplotsRegistry[plotType]) {
+        console.log('plot type ' + plotType + ' already registered');
+        return;
+    }
+
+    // not sure what's best for the 'cartesian' type at this point
+    subplotsRegistry[plotType] = _module;
+};
+
+/**
+ * Find subplot ids in data.
+ * Meant to be used in the defaults step.
+ *
+ * Use plots.getSubplotIds to grab the current
+ * subplot ids later on in Plotly.plot.
+ *
+ * @param {array} data plotly data array
+ *      (intended to be _fullData, but does not have to be).
+ * @param {string} type subplot type to look for.
+ *
+ * @return {array} list of subplot ids (strings).
+ *      N.B. these ids possibly un-ordered.
+ *
+ * TODO incorporate cartesian/gl2d axis finders in this paradigm.
+ */
+plots.findSubplotIds = function findSubplotIds(data, type) {
+    var subplotIds = [];
+
+    if(plots.subplotsRegistry[type] === undefined) return subplotIds;
+
+    var attr = plots.subplotsRegistry[type].attr;
+
+    for(var i = 0; i < data.length; i++) {
+        var trace = data[i];
+
+        if(plots.traceIs(trace, type) && subplotIds.indexOf(trace[attr]) === -1) {
+            subplotIds.push(trace[attr]);
+        }
+    }
+
+    return subplotIds;
+};
+
+/**
+ * Get the ids of the current subplots.
+ *
+ * @param {object} layout plotly full layout object.
+ * @param {string} type subplot type to look for.
+ *
+ * @return {array} list of ordered subplot ids (strings).
+ *
+ */
+plots.getSubplotIds = function getSubplotIds(layout, type) {
+    var _module = plots.subplotsRegistry[type];
+
+    if(_module === undefined) return [];
+
+    // layout must be 'fullLayout' here
+    if(type === 'cartesian' && !layout._hasCartesian) return [];
+    if(type === 'gl2d' && !layout._hasGL2D) return [];
+    if(type === 'cartesian' || type === 'gl2d') {
+        return Object.keys(layout._plots);
+    }
+
+    var idRegex = _module.idRegex,
+        layoutKeys = Object.keys(layout),
+        subplotIds = [];
+
+    for(var i = 0; i < layoutKeys.length; i++) {
+        var layoutKey = layoutKeys[i];
+
+        if(idRegex.test(layoutKey)) subplotIds.push(layoutKey);
+    }
+
+    // order the ids
+    var idLen = _module.idRoot.length;
+    subplotIds.sort(function(a, b) {
+        var aNum = +(a.substr(idLen) || 1),
+            bNum = +(b.substr(idLen) || 1);
+        return aNum - bNum;
+    });
+
+    return subplotIds;
+};
+
+/**
+ * Get the data trace(s) associated with a given subplot.
+ *
+ * @param {array} data  plotly full data array.
+ * @param {object} layout plotly full layout object.
+ * @param {string} subplotId subplot ids to look for.
+ *
+ * @return {array} list of trace objects.
+ *
+ */
+plots.getSubplotData = function getSubplotData(data, type, subplotId) {
+    if(plots.subplotsRegistry[type] === undefined) return [];
+
+    var attr = plots.subplotsRegistry[type].attr,
+        subplotData = [],
+        trace;
+
+    for(var i = 0; i < data.length; i++) {
+        trace = data[i];
+
+        if(type === 'gl2d' && plots.traceIs(trace, 'gl2d')) {
+            var spmatch = Plotly.Axes.subplotMatch,
+                subplotX = 'x' + subplotId.match(spmatch)[1],
+                subplotY = 'y' + subplotId.match(spmatch)[2];
+
+            if(trace[attr[0]]===subplotX && trace[attr[1]]===subplotY) {
+                subplotData.push(trace);
+            }
+        }
+        else {
+            if(trace[attr] === subplotId) subplotData.push(trace);
+        }
+    }
+
+    return subplotData;
+};
+
+// in some cases the browser doesn't seem to know how big
+// the text is at first, so it needs to draw it,
+// then wait a little, then draw it again
+plots.redrawText = function(gd) {
+
+    // doesn't work presently (and not needed) for polar or 3d
+    if(gd._fullLayout._hasGL3D || (gd.data && gd.data[0] && gd.data[0].r)) {
+        return;
+    }
+
+    return new Promise(function(resolve) {
+        setTimeout(function() {
+            Plotly.Annotations.drawAll(gd);
+            Plotly.Legend.draw(gd);
+            (gd.calcdata||[]).forEach(function(d) {
+                if(d[0]&&d[0].t&&d[0].t.cb) d[0].t.cb();
+            });
+            resolve(plots.previousPromises(gd));
+        },300);
+    });
+};
+
+// resize plot about the container size
+plots.resize = function(gd) {
+    return new Promise(function(resolve, reject) {
+
+        if(!gd || d3.select(gd).style('display') === 'none') {
+            reject(new Error('Resize must be passed a plot div element.'));
+        }
+
+        if(gd._redrawTimer) clearTimeout(gd._redrawTimer);
+
+        gd._redrawTimer = setTimeout(function() {
+            if((gd._fullLayout || {}).autosize) {
+                // autosizing doesn't count as a change that needs saving
+                var oldchanged = gd.changed;
+
+                // nor should it be included in the undo queue
+                gd.autoplay = true;
+
+                Plotly.relayout(gd, { autosize: true });
+                gd.changed = oldchanged;
+                resolve(gd);
+            }
+        }, 100);
+    });
+};
+
+
+// for use in Lib.syncOrAsync, check if there are any
+// pending promises in this plot and wait for them
+plots.previousPromises = function(gd) {
+    if((gd._promises || []).length) {
+        return Promise.all(gd._promises)
+            .then(function() { gd._promises=[]; });
+    }
+};
+
+/**
+ * Adds the 'Edit chart' link.
+ * Note that now Plotly.plot() calls this so it can regenerate whenever it replots
+ *
+ * Add source links to your graph inside the 'showSources' config argument.
+ */
+plots.addLinks = function(gd) {
+    var fullLayout = gd._fullLayout;
+
+    var linkContainer = fullLayout._paper
+        .selectAll('text.js-plot-link-container').data([0]);
+
+    linkContainer.enter().append('text')
+        .classed('js-plot-link-container', true)
+        .style({
+            'font-family': '"Open Sans", Arial, sans-serif',
+            'font-size': '12px',
+            'fill': Plotly.Color.defaultLine,
+            'pointer-events': 'all'
+        })
+        .each(function() {
+            var links = d3.select(this);
+            links.append('tspan').classed('js-link-to-tool', true);
+            links.append('tspan').classed('js-link-spacer', true);
+            links.append('tspan').classed('js-sourcelinks', true);
+        });
+
+    // The text node inside svg
+    var text = linkContainer.node(),
+        attrs = {
+            y: fullLayout._paper.attr('height') - 9
+        };
+
+    // If text's width is bigger than the layout
+    // IE doesn't like getComputedTextLength if an element
+    // isn't visible, which it (sometimes?) isn't
+    // apparently offsetParent is null for invisibles.
+    if(text && text.getComputedTextLength() >= (fullLayout.width - 20)) {
+        // Align the text at the left
+        attrs['text-anchor'] = 'start';
+        attrs.x = 5;
+    }
+    else {
+        // Align the text at the right
+        attrs['text-anchor'] = 'end';
+        attrs.x = fullLayout._paper.attr('width') - 7;
+    }
+
+    linkContainer.attr(attrs);
+
+    var toolspan = linkContainer.select('.js-link-to-tool'),
+        spacespan = linkContainer.select('.js-link-spacer'),
+        sourcespan = linkContainer.select('.js-sourcelinks');
+
+    if(gd._context.showSources) gd._context.showSources(gd);
+
+    // 'view in plotly' link for embedded plots
+    if(gd._context.showLink) positionPlayWithData(gd, toolspan);
+
+    // separator if we have both sources and tool link
+    spacespan.text((toolspan.text() && sourcespan.text()) ? ' - ' : '');
+};
+
+// note that now this function is only adding the brand in
+// iframes and 3rd-party apps
+function positionPlayWithData(gd, container) {
+    container.text('');
+    var link = container.append('a')
+        .attr({
+            'xlink:xlink:href': '#',
+            'class': 'link--impt link--embedview',
+            'font-weight': 'bold'
+        })
+        .text(gd._context.linkText + ' ' + String.fromCharCode(187));
+
+    if(gd._context.sendData) {
+        link.on('click', function() {
+            plots.sendDataToCloud(gd);
+        });
+    }
+    else {
+        var path = window.location.pathname.split('/');
+        var query = window.location.search;
+        link.attr({
+            'xlink:xlink:show': 'new',
+            'xlink:xlink:href': '/' + path[2].split('.')[0] + '/' + path[1] + query
+        });
+    }
+}
+plots.sendDataToCloud = function(gd) {
+    gd.emit('plotly_beforeexport');
+
+    var baseUrl = (window.PLOTLYENV && window.PLOTLYENV.BASE_URL) || 'https://plot.ly';
+
+    var hiddenformDiv = d3.select(gd)
+        .append('div')
+        .attr('id', 'hiddenform')
+        .style('display', 'none');
+
+    var hiddenform = hiddenformDiv
+        .append('form')
+        .attr({
+            action: baseUrl + '/external',
+            method: 'post',
+            target: '_blank'
+        });
+
+    var hiddenformInput = hiddenform
+        .append('input')
+        .attr({
+            type: 'text',
+            name: 'data'
+        });
+
+    hiddenformInput.node().value = plots.graphJson(gd, false, 'keepdata');
+    hiddenform.node().submit();
+    hiddenformDiv.remove();
+
+    gd.emit('plotly_afterexport');
+    return false;
+};
+
+plots.supplyDefaults = function(gd) {
+    // fill in default values:
+    // gd.data, gd.layout:
+    //   are precisely what the user specified
+    // gd._fullData, gd._fullLayout:
+    //   are complete descriptions of how to draw the plot
+    var oldFullLayout = gd._fullLayout || {},
+        newFullLayout = gd._fullLayout = {},
+        newLayout = gd.layout || {},
+        oldFullData = gd._fullData || [],
+        newFullData = gd._fullData = [],
+        newData = gd.data || [],
+        modules = gd._modules = [];
+
+    var i, trace, fullTrace, _module, axList, ax;
+
+
+    // first fill in what we can of layout without looking at data
+    // because fullData needs a few things from layout
+    plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout);
+
+    // keep track of how many traces are inputted
+    newFullLayout._dataLength = newData.length;
+
+    // then do the data
+    for(i = 0; i < newData.length; i++) {
+        trace = newData[i];
+
+        fullTrace = plots.supplyDataDefaults(trace, i, newFullLayout);
+        newFullData.push(fullTrace);
+
+        // detect plot type
+        if(plots.traceIs(fullTrace, 'cartesian')) newFullLayout._hasCartesian = true;
+        else if(plots.traceIs(fullTrace, 'gl3d')) newFullLayout._hasGL3D = true;
+        else if(plots.traceIs(fullTrace, 'geo')) newFullLayout._hasGeo = true;
+        else if(plots.traceIs(fullTrace, 'pie')) newFullLayout._hasPie = true;
+        else if(plots.traceIs(fullTrace, 'gl2d')) newFullLayout._hasGL2D = true;
+        else if('r' in fullTrace) newFullLayout._hasPolar = true;
+
+        _module = fullTrace._module;
+        if(_module && modules.indexOf(_module)===-1) modules.push(_module);
+    }
+
+    // special cases that introduce interactions between traces
+    for(i = 0; i < modules.length; i++) {
+        _module = modules[i];
+        if(_module.cleanData) _module.cleanData(newFullData);
+    }
+
+    if(oldFullData.length === newData.length) {
+        for(i = 0; i < newFullData.length; i++) {
+            relinkPrivateKeys(newFullData[i], oldFullData[i]);
+        }
+    }
+
+    // finally, fill in the pieces of layout that may need to look at data
+    plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData);
+
+    // clean subplots and other artifacts from previous plot calls
+    cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout);
+
+    /*
+     * Relink functions and underscore attributes to promote consistency between
+     * plots.
+     */
+    relinkPrivateKeys(newFullLayout, oldFullLayout);
+
+    plots.doAutoMargin(gd);
+
+    // can't quite figure out how to get rid of this... each axis needs
+    // a reference back to the DOM object for just a few purposes
+    axList = Plotly.Axes.list(gd);
+    for(i = 0; i < axList.length; i++) {
+        ax = axList[i];
+        ax._td = gd;
+        ax.setScale();
+    }
+
+    // update object references in calcdata
+    if((gd.calcdata || []).length === newFullData.length) {
+        for(i = 0; i < newFullData.length; i++) {
+            trace = newFullData[i];
+            (gd.calcdata[i][0] || {}).trace = trace;
+        }
+    }
+};
+
+function cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout) {
+    var i, j;
+
+    var plotTypes = Object.keys(subplotsRegistry);
+    for(i = 0; i < plotTypes.length; i++) {
+        var _module = subplotsRegistry[plotTypes[i]];
+
+        if(_module.clean) {
+            _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout);
+        }
+    }
+
+    var hasPaper = !!oldFullLayout._paper;
+    var hasInfoLayer = !!oldFullLayout._infolayer;
+
+    oldLoop:
+    for(i = 0; i < oldFullData.length; i++) {
+        var oldTrace = oldFullData[i],
+            oldUid = oldTrace.uid;
+
+        for(j = 0; j < newFullData.length; j++) {
+            var newTrace = newFullData[j];
+
+            if(oldUid === newTrace.uid) continue oldLoop;
+        }
+
+        // clean old heatmap and contour traces
+        if(hasPaper) {
+            oldFullLayout._paper.selectAll(
+                '.hm' + oldUid +
+                ',.contour' + oldUid +
+                ',#clip' + oldUid
+            ).remove();
+        }
+
+        // clean old colorbars
+        if(hasInfoLayer) {
+            oldFullLayout._infolayer.selectAll('.cb' + oldUid).remove();
+        }
+    }
+}
+
+/**
+ * Relink private _keys and keys with a function value from one layout
+ * (usually cached) to the new fullLayout.
+ * relink means copying if object is pass-by-value and adding a reference
+ * if object is pass-by-ref. This prevents deepCopying massive structures like
+ * a webgl context.
+ */
+function relinkPrivateKeys(toLayout, fromLayout) {
+    var keys = Object.keys(fromLayout);
+    var j;
+
+    for(var i = 0; i < keys.length; ++i) {
+        var k = keys[i];
+        if(k.charAt(0)==='_' || typeof fromLayout[k]==='function') {
+            // if it already exists at this point, it's something
+            // that we recreate each time around, so ignore it
+            if(k in toLayout) continue;
+
+            toLayout[k] = fromLayout[k];
+        }
+        else if(Array.isArray(fromLayout[k]) &&
+                 Array.isArray(toLayout[k]) &&
+                 fromLayout[k].length &&
+                 Lib.isPlainObject(fromLayout[k][0])) {
+            if(fromLayout[k].length !== toLayout[k].length) {
+                // this should be handled elsewhere, it causes
+                // ambiguity if we try to deal with it here.
+                throw new Error('relinkPrivateKeys needs equal ' +
+                                'length arrays');
+            }
+
+            for(j = 0; j < fromLayout[k].length; j++) {
+                relinkPrivateKeys(toLayout[k][j], fromLayout[k][j]);
+            }
+        }
+        else if(Lib.isPlainObject(fromLayout[k]) &&
+                 Lib.isPlainObject(toLayout[k])) {
+            // recurse into objects, but only if they still exist
+            relinkPrivateKeys(toLayout[k], fromLayout[k]);
+            if(!Object.keys(toLayout[k]).length) delete toLayout[k];
+        }
+    }
+}
+
+plots.supplyDataDefaults = function(traceIn, i, layout) {
+    var traceOut = {},
+        defaultColor = Plotly.Color.defaults[i % Plotly.Color.defaults.length];
+
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, plots.attributes, attr, dflt);
+    }
+
+    function coerceSubplotAttr(subplotType, subplotAttr) {
+        if(!plots.traceIs(traceOut, subplotType)) return;
+        return Lib.coerce(traceIn, traceOut,
+            plots.subplotsRegistry[subplotType].attributes, subplotAttr);
+    }
+
+    // module-independent attributes
+    traceOut.index = i;
+    var visible = coerce('visible'),
+        scene,
+        _module;
+
+    coerce('type');
+    coerce('uid');
+
+    // this is necessary otherwise we lose references to scene objects when
+    // the traces of a scene are invisible. Also we handle visible/unvisible
+    // differently for 3D cases.
+    coerceSubplotAttr('gl3d', 'scene');
+    coerceSubplotAttr('geo', 'geo');
+
+    // module-specific attributes --- note: we need to send a trace into
+    // the 3D modules to have it removed from the webgl context.
+    if(visible || scene) {
+        _module = plots.getModule(traceOut);
+        traceOut._module = _module;
+    }
+
+    // gets overwritten in pie and geo
+    if(visible) coerce('hoverinfo', (layout._dataLength === 1) ? 'x+y+z+text' : undefined);
+
+    if(_module && visible) _module.supplyDefaults(traceIn, traceOut, defaultColor, layout);
+
+    if(visible) {
+        coerce('name', 'trace ' + i);
+
+        if(!plots.traceIs(traceOut, 'noOpacity')) coerce('opacity');
+
+        coerceSubplotAttr('cartesian', 'xaxis');
+        coerceSubplotAttr('cartesian', 'yaxis');
+
+        coerceSubplotAttr('gl2d', 'xaxis');
+        coerceSubplotAttr('gl2d', 'yaxis');
+
+        if(plots.traceIs(traceOut, 'showLegend')) {
+            coerce('showlegend');
+            coerce('legendgroup');
+        }
+    }
+
+    // NOTE: I didn't include fit info at all... for now I think it can stay
+    // just in gd.data, as this info isn't involved in creating plots at all,
+    // only in pulling back up the fit popover
+
+    // reference back to the input object for convenience
+    traceOut._input = traceIn;
+
+    return traceOut;
+};
+
+plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt);
+    }
+
+    var globalFont = Lib.coerceFont(coerce, 'font');
+
+    coerce('title');
+
+    Lib.coerceFont(coerce, 'titlefont', {
+        family: globalFont.family,
+        size: Math.round(globalFont.size * 1.4),
+        color: globalFont.color
+    });
+
+    var autosize = coerce('autosize',
+        (layoutIn.width && layoutIn.height) ? false : 'initial');
+    coerce('width');
+    coerce('height');
+
+    coerce('margin.l');
+    coerce('margin.r');
+    coerce('margin.t');
+    coerce('margin.b');
+    coerce('margin.pad');
+    coerce('margin.autoexpand');
+
+    // called in plotAutoSize otherwise
+    if(autosize!=='initial') plots.sanitizeMargins(layoutOut);
+
+    coerce('paper_bgcolor');
+
+    coerce('separators');
+    coerce('hidesources');
+    coerce('smith');
+    coerce('_hasCartesian');
+    coerce('_hasGL3D');
+    coerce('_hasGeo');
+    coerce('_hasPie');
+    coerce('_hasGL2D');
+};
+
+plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData) {
+    var i, _module;
+
+    // TODO incorporate into subplotRegistry
+    Plotly.Axes.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
+
+    // plot module layout defaults
+    var plotTypes = Object.keys(subplotsRegistry);
+    for(i = 0; i < plotTypes.length; i++) {
+        _module = subplotsRegistry[plotTypes[i]];
+
+        // e.g. gl2d does not have a layout-defaults step
+        if(_module.supplyLayoutDefaults) {
+            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
+        }
+    }
+
+    // trace module layout defaults
+    var traceTypes = Object.keys(modules);
+    for(i = 0; i < traceTypes.length; i++) {
+        _module = modules[allTypes[i]]._module;
+
+        if(_module.supplyLayoutDefaults) {
+            _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
+        }
+    }
+
+    // TODO register these
+    // Legend must come after traces (e.g. it depends on 'barmode')
+    var moduleLayoutDefaults = ['Fx', 'Annotations', 'Shapes', 'Legend'];
+    for(i = 0; i < moduleLayoutDefaults.length; i++) {
+        _module = moduleLayoutDefaults[i];
+
+        if(Plotly[_module]) {
+            Plotly[_module].supplyLayoutDefaults(layoutIn, layoutOut, fullData);
+        }
+    }
+};
+
+plots.purge = function(gd) {
+    // remove all plotly attributes from a div so it can be replotted fresh
+    // TODO: these really need to be encapsulated into a much smaller set...
+
+    // note: we DO NOT remove _context because it doesn't change when we insert
+    // a new plot, and may have been set outside of our scope.
+
+    // clean up the gl and geo containers
+    // TODO unify subplot creation/update with d3.selection.order
+    // and/or subplot ids
+    var fullLayout = gd._fullLayout || {};
+    if(fullLayout._glcontainer !== undefined) fullLayout._glcontainer.remove();
+    if(fullLayout._geocontainer !== undefined) fullLayout._geocontainer.remove();
+
+    // remove modebar
+    if(fullLayout._modeBar) fullLayout._modeBar.destroy();
+
+    // data and layout
+    delete gd.data;
+    delete gd.layout;
+    delete gd._fullData;
+    delete gd._fullLayout;
+    delete gd.calcdata;
+    delete gd.framework;
+    delete gd.empty;
+
+    delete gd.fid;
+
+    delete gd.undoqueue; // action queue
+    delete gd.undonum;
+    delete gd.autoplay; // are we doing an action that doesn't go in undo queue?
+    delete gd.changed;
+
+    // these get recreated on Plotly.plot anyway, but just to be safe
+    // (and to have a record of them...)
+    delete gd._modules;
+    delete gd._tester;
+    delete gd._testref;
+    delete gd._promises;
+    delete gd._redrawTimer;
+    delete gd._replotting;
+    delete gd.firstscatter;
+    delete gd.hmlumcount;
+    delete gd.hmpixcount;
+    delete gd.numboxes;
+    delete gd._hoverTimer;
+    delete gd._lastHoverTime;
+
+    // remove all event listeners
+    if(gd.removeAllListeners) gd.removeAllListeners();
+};
+
+plots.style = function(gd) {
+    var modulesWithErrorBars = gd._modules.concat(Plotly.ErrorBars);
+
+    for(var i = 0; i < modulesWithErrorBars.length; i++) {
+        var _module = modulesWithErrorBars[i];
+        if(_module.style) _module.style(gd);
+    }
+};
+
+plots.sanitizeMargins = function(fullLayout) {
+    // polar doesn't do margins...
+    if(!fullLayout || !fullLayout.margin) return;
+
+    var width = fullLayout.width,
+        height = fullLayout.height,
+        margin = fullLayout.margin,
+        plotWidth = width - (margin.l + margin.r),
+        plotHeight = height - (margin.t + margin.b),
+        correction;
+
+    // if margin.l + margin.r = 0 then plotWidth > 0
+    // as width >= 10 by supplyDefaults
+    // similarly for margin.t + margin.b
+
+    if(plotWidth < 0) {
+        correction = (width - 1) / (margin.l + margin.r);
+        margin.l = Math.floor(correction * margin.l);
+        margin.r = Math.floor(correction * margin.r);
+    }
+
+    if(plotHeight < 0) {
+        correction = (height - 1) / (margin.t + margin.b);
+        margin.t = Math.floor(correction * margin.t);
+        margin.b = Math.floor(correction * margin.b);
+    }
+};
+// called by legend and colorbar routines to see if we need to
+// expand the margins to show them
+// o is {x,l,r,y,t,b} where x and y are plot fractions,
+// the rest are pixels in each direction
+// or leave o out to delete this entry (like if it's hidden)
+plots.autoMargin = function(gd,id,o) {
+    var fullLayout = gd._fullLayout;
+    if(!fullLayout._pushmargin) fullLayout._pushmargin = {};
+    if(fullLayout.margin.autoexpand!==false) {
+        if(!o) delete fullLayout._pushmargin[id];
+        else {
+            var pad = o.pad||12;
+
+            // if the item is too big, just give it enough automargin to
+            // make sure you can still grab it and bring it back
+            if(o.l+o.r > fullLayout.width*0.5) o.l = o.r = 0;
+            if(o.b+o.t > fullLayout.height*0.5) o.b = o.t = 0;
+
+            fullLayout._pushmargin[id] = {
+                l: {val: o.x, size: o.l+pad},
+                r: {val: o.x, size: o.r+pad},
+                b: {val: o.y, size: o.b+pad},
+                t: {val: o.y, size: o.t+pad}
+            };
+        }
+
+        if(!gd._replotting) plots.doAutoMargin(gd);
+    }
+};
+
+plots.doAutoMargin = function(gd) {
+    var fullLayout = gd._fullLayout;
+    if(!fullLayout._size) fullLayout._size = {};
+    if(!fullLayout._pushmargin) fullLayout._pushmargin = {};
+    var gs = fullLayout._size,
+        oldmargins = JSON.stringify(gs);
+
+    // adjust margins for outside legends and colorbars
+    // fullLayout.margin is the requested margin,
+    // fullLayout._size has margins and plotsize after adjustment
+    var ml = Math.max(fullLayout.margin.l||0,0),
+        mr = Math.max(fullLayout.margin.r||0,0),
+        mt = Math.max(fullLayout.margin.t||0,0),
+        mb = Math.max(fullLayout.margin.b||0,0),
+        pm = fullLayout._pushmargin;
+    if(fullLayout.margin.autoexpand!==false) {
+        // fill in the requested margins
+        pm.base = {
+            l: {val: 0, size: ml},
+            r: {val: 1, size: mr},
+            t: {val: 1, size: mt},
+            b: {val: 0, size: mb}
+        };
+        // now cycle through all the combinations of l and r
+        // (and t and b) to find the required margins
+        Object.keys(pm).forEach(function(k1) {
+            var pushleft = pm[k1].l||{},
+                pushbottom = pm[k1].b||{},
+                fl = pushleft.val,
+                pl = pushleft.size,
+                fb = pushbottom.val,
+                pb = pushbottom.size;
+            Object.keys(pm).forEach(function(k2) {
+                if(isNumeric(pl) && pm[k2].r) {
+                    var fr = pm[k2].r.val,
+                        pr = pm[k2].r.size;
+                    if(fr>fl) {
+                        var newl = (pl*fr +
+                                (pr-fullLayout.width)*fl) / (fr-fl),
+                            newr = (pr*(1-fl) +
+                                (pl-fullLayout.width)*(1-fr)) / (fr-fl);
+                        if(newl>=0 && newr>=0 && newl+newr>ml+mr) {
+                            ml = newl;
+                            mr = newr;
+                        }
+                    }
+                }
+                if(isNumeric(pb) && pm[k2].t) {
+                    var ft = pm[k2].t.val,
+                        pt = pm[k2].t.size;
+                    if(ft>fb) {
+                        var newb = (pb*ft +
+                                (pt-fullLayout.height)*fb) / (ft-fb),
+                            newt = (pt*(1-fb) +
+                                (pb-fullLayout.height)*(1-ft)) / (ft-fb);
+                        if(newb>=0 && newt>=0 && newb+newt>mb+mt) {
+                            mb = newb;
+                            mt = newt;
+                        }
+                    }
+                }
+            });
+        });
+    }
+
+    gs.l = Math.round(ml);
+    gs.r = Math.round(mr);
+    gs.t = Math.round(mt);
+    gs.b = Math.round(mb);
+    gs.p = Math.round(fullLayout.margin.pad);
+    gs.w = Math.round(fullLayout.width)-gs.l-gs.r;
+    gs.h = Math.round(fullLayout.height)-gs.t-gs.b;
+
+    // if things changed and we're not already redrawing, trigger a redraw
+    if(!gd._replotting && oldmargins!=='{}' &&
+            oldmargins!==JSON.stringify(fullLayout._size)) {
+        return Plotly.plot(gd);
+    }
+};
+
+/**
+ * JSONify the graph data and layout
+ *
+ * This function needs to recurse because some src can be inside
+ * sub-objects.
+ *
+ * It also strips out functions and private (starts with _) elements.
+ * Therefore, we can add temporary things to data and layout that don't
+ * get saved.
+ *
+ * @param gd The graphDiv
+ * @param {Boolean} dataonly If true, don't return layout.
+ * @param {'keepref'|'keepdata'|'keepall'} [mode='keepref'] Filter what's kept
+ *      keepref: remove data for which there's a src present
+ *          eg if there's xsrc present (and xsrc is well-formed,
+ *          ie has : and some chars before it), strip out x
+ *      keepdata: remove all src tags, don't remove the data itself
+ *      keepall: keep data and src
+ * @param {String} output If you specify 'object', the result will not be stringified
+ * @param {Boolean} useDefaults If truthy, use _fullLayout and _fullData
+ * @returns {Object|String}
+ */
+plots.graphJson = function(gd, dataonly, mode, output, useDefaults) {
+    // if the defaults aren't supplied yet, we need to do that...
+    if((useDefaults && dataonly && !gd._fullData) ||
+            (useDefaults && !dataonly && !gd._fullLayout)) {
+        plots.supplyDefaults(gd);
+    }
+
+    var data = (useDefaults) ? gd._fullData : gd.data,
+        layout = (useDefaults) ? gd._fullLayout : gd.layout;
+
+    function stripObj(d) {
+        if(typeof d === 'function') {
+            return null;
+        }
+        if(Lib.isPlainObject(d)) {
+            var o={}, v, src;
+            for(v in d) {
+                // remove private elements and functions
+                // _ is for private, [ is a mistake ie [object Object]
+                if(typeof d[v]==='function' ||
+                        ['_','['].indexOf(v.charAt(0))!==-1) {
+                    continue;
+                }
+
+                // look for src/data matches and remove the appropriate one
+                if(mode==='keepdata') {
+                    // keepdata: remove all ...src tags
+                    if(v.substr(v.length-3)==='src') {
+                        continue;
+                    }
+                }
+                else if(mode==='keepstream') {
+                    // keep sourced data if it's being streamed.
+                    // similar to keepref, but if the 'stream' object exists
+                    // in a trace, we will keep the data array.
+                    src = d[v+'src'];
+                    if(typeof src==='string' && src.indexOf(':')>0) {
+                        if(!Lib.isPlainObject(d.stream)) {
+                            continue;
+                        }
+                    }
+                }
+                else if(mode!=='keepall') {
+                    // keepref: remove sourced data but only
+                    // if the source tag is well-formed
+                    src = d[v+'src'];
+                    if(typeof src==='string' && src.indexOf(':')>0) {
+                        continue;
+                    }
+                }
+
+                // OK, we're including this... recurse into it
+                o[v] = stripObj(d[v]);
+            }
+            return o;
+        }
+
+        if(Array.isArray(d)) {
+            return d.map(stripObj);
+        }
+
+        // convert native dates to date strings...
+        // mostly for external users exporting to plotly
+        if(d && d.getTime) {
+            return Lib.ms2DateTime(d);
+        }
+
+        return d;
+    }
+
+    var obj = {
+        data: (data || []).map(function(v) {
+            var d = stripObj(v);
+            // fit has some little arrays in it that don't contain data,
+            // just fit params and meta
+            if(dataonly) { delete d.fit; }
+            return d;
+        })
+    };
+    if(!dataonly) { obj.layout = stripObj(layout); }
+
+    if(gd.framework && gd.framework.isPolar) obj = gd.framework.getConfig();
+
+    return (output==='object') ? obj : JSON.stringify(obj);
+};
+
+},{"../lib":349,"../plotly":366,"./attributes":367,"./font_attributes":383,"./layout_attributes":412,"d3":70,"fast-isnumeric":74}],414:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var scatterAttrs = require('../../traces/scatter/attributes');
+var scatterMarkerAttrs = scatterAttrs.marker;
+
+module.exports = {
+    r: scatterAttrs.r,
+    t: scatterAttrs.t,
+    marker: {
+        color: scatterMarkerAttrs.color,
+        size: scatterMarkerAttrs.size,
+        symbol: scatterMarkerAttrs.symbol,
+        opacity: scatterMarkerAttrs.opacity
+    }
+};
+
+},{"../../traces/scatter/attributes":502}],415:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var axesAttrs = require('../cartesian/layout_attributes');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+var domainAttr = extendFlat({}, axesAttrs.domain, {
+    
+});
+
+function mergeAttrs(axisName, nonCommonAttrs) {
+    var commonAttrs = {
+        showline: {
+            valType: 'boolean',
+            
+            
+        },
+        showticklabels: {
+            valType: 'boolean',
+            
+            
+        },
+        tickorientation: {
+            valType: 'enumerated',
+            values: ['horizontal', 'vertical'],
+            
+            
+        },
+        ticklen: {
+            valType: 'number',
+            min: 0,
+            
+            
+        },
+        tickcolor: {
+            valType: 'color',
+            
+            
+        },
+        ticksuffix: {
+            valType: 'string',
+            
+            
+        },
+        endpadding: {
+            valType: 'number',
+            
+        },
+        visible: {
+            valType: 'boolean',
+            
+            
+        }
+    };
+
+    return extendFlat({}, nonCommonAttrs, commonAttrs);
+}
+
+module.exports = {
+    radialaxis: mergeAttrs('radial', {
+        range: {
+            valType: 'info_array',
+            
+            items: [
+                { valType: 'number' },
+                { valType: 'number' }
+            ],
+            
+        },
+        domain: domainAttr,
+        orientation: {
+            valType: 'number',
+            
+            
+        }
+    }),
+
+    angularaxis: mergeAttrs('angular', {
+        range: {
+            valType: 'info_array',
+            
+            items: [
+                { valType: 'number', dflt: 0 },
+                { valType: 'number', dflt: 360 }
+            ],
+            
+        },
+        domain: domainAttr
+    }),
+
+    // attributes that appear at layout root
+    layout: {
+        direction: {
+            valType: 'enumerated',
+            values: ['clockwise', 'counterclockwise'],
+            
+            
+        },
+        orientation: {
+            valType: 'angle',
+            
+            
+        }
+    }
+};
+
+},{"../../lib/extend":345,"../cartesian/layout_attributes":376}],416:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+var Plotly = require('../../plotly');
+var d3 = require('d3');
+
+var Âµ = module.exports = {
+    version: '0.2.2',
+    manager: require('./micropolar_manager')
+};
+
+var extendDeepAll = Plotly.Lib.extendDeepAll;
+
+Âµ.Axis = function module() {
+    var config = {
+        data: [],
+        layout: {}
+    }, inputConfig = {}, liveConfig = {};
+    var svg, container, dispatch = d3.dispatch('hover'), radialScale, angularScale;
+    var exports = {};
+    function render(_container) {
+        container = _container || container;
+        var data = config.data;
+        var axisConfig = config.layout;
+        if (typeof container == 'string' || container.nodeName) container = d3.select(container);
+        container.datum(data).each(function(_data, _index) {
+            var dataOriginal = _data.slice();
+            liveConfig = {
+                data: Âµ.util.cloneJson(dataOriginal),
+                layout: Âµ.util.cloneJson(axisConfig)
+            };
+            var colorIndex = 0;
+            dataOriginal.forEach(function(d, i) {
+                if (!d.color) {
+                    d.color = axisConfig.defaultColorRange[colorIndex];
+                    colorIndex = (colorIndex + 1) % axisConfig.defaultColorRange.length;
+                }
+                if (!d.strokeColor) {
+                    d.strokeColor = d.geometry === 'LinePlot' ? d.color : d3.rgb(d.color).darker().toString();
+                }
+                liveConfig.data[i].color = d.color;
+                liveConfig.data[i].strokeColor = d.strokeColor;
+                liveConfig.data[i].strokeDash = d.strokeDash;
+                liveConfig.data[i].strokeSize = d.strokeSize;
+            });
+            var data = dataOriginal.filter(function(d, i) {
+                var visible = d.visible;
+                return typeof visible === 'undefined' || visible === true;
+            });
+            var isStacked = false;
+            var dataWithGroupId = data.map(function(d, i) {
+                isStacked = isStacked || typeof d.groupId !== 'undefined';
+                return d;
+            });
+            if (isStacked) {
+                var grouped = d3.nest().key(function(d, i) {
+                    return typeof d.groupId != 'undefined' ? d.groupId : 'unstacked';
+                }).entries(dataWithGroupId);
+                var dataYStack = [];
+                var stacked = grouped.map(function(d, i) {
+                    if (d.key === 'unstacked') return d.values; else {
+                        var prevArray = d.values[0].r.map(function(d, i) {
+                            return 0;
+                        });
+                        d.values.forEach(function(d, i, a) {
+                            d.yStack = [ prevArray ];
+                            dataYStack.push(prevArray);
+                            prevArray = Âµ.util.sumArrays(d.r, prevArray);
+                        });
+                        return d.values;
+                    }
+                });
+                data = d3.merge(stacked);
+            }
+            data.forEach(function(d, i) {
+                d.t = Array.isArray(d.t[0]) ? d.t : [ d.t ];
+                d.r = Array.isArray(d.r[0]) ? d.r : [ d.r ];
+            });
+            var radius = Math.min(axisConfig.width - axisConfig.margin.left - axisConfig.margin.right, axisConfig.height - axisConfig.margin.top - axisConfig.margin.bottom) / 2;
+            radius = Math.max(10, radius);
+            var chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ];
+            var extent;
+            if (isStacked) {
+                var highestStackedValue = d3.max(Âµ.util.sumArrays(Âµ.util.arrayLast(data).r[0], Âµ.util.arrayLast(dataYStack)));
+                extent = [ 0, highestStackedValue ];
+            } else extent = d3.extent(Âµ.util.flattenArray(data.map(function(d, i) {
+                return d.r;
+            })));
+            if (axisConfig.radialAxis.domain != Âµ.DATAEXTENT) extent[0] = 0;
+            radialScale = d3.scale.linear().domain(axisConfig.radialAxis.domain != Âµ.DATAEXTENT && axisConfig.radialAxis.domain ? axisConfig.radialAxis.domain : extent).range([ 0, radius ]);
+            liveConfig.layout.radialAxis.domain = radialScale.domain();
+            var angularDataMerged = Âµ.util.flattenArray(data.map(function(d, i) {
+                return d.t;
+            }));
+            var isOrdinal = typeof angularDataMerged[0] === 'string';
+            var ticks;
+            if (isOrdinal) {
+                angularDataMerged = Âµ.util.deduplicate(angularDataMerged);
+                ticks = angularDataMerged.slice();
+                angularDataMerged = d3.range(angularDataMerged.length);
+                data = data.map(function(d, i) {
+                    var result = d;
+                    d.t = [ angularDataMerged ];
+                    if (isStacked) result.yStack = d.yStack;
+                    return result;
+                });
+            }
+            var hasOnlyLineOrDotPlot = data.filter(function(d, i) {
+                return d.geometry === 'LinePlot' || d.geometry === 'DotPlot';
+            }).length === data.length;
+            var needsEndSpacing = axisConfig.needsEndSpacing === null ? isOrdinal || !hasOnlyLineOrDotPlot : axisConfig.needsEndSpacing;
+            var useProvidedDomain = axisConfig.angularAxis.domain && axisConfig.angularAxis.domain != Âµ.DATAEXTENT && !isOrdinal && axisConfig.angularAxis.domain[0] >= 0;
+            var angularDomain = useProvidedDomain ? axisConfig.angularAxis.domain : d3.extent(angularDataMerged);
+            var angularDomainStep = Math.abs(angularDataMerged[1] - angularDataMerged[0]);
+            if (hasOnlyLineOrDotPlot && !isOrdinal) angularDomainStep = 0;
+            var angularDomainWithPadding = angularDomain.slice();
+            if (needsEndSpacing && isOrdinal) angularDomainWithPadding[1] += angularDomainStep;
+            var tickCount = axisConfig.angularAxis.ticksCount || 4;
+            if (tickCount > 8) tickCount = tickCount / (tickCount / 8) + tickCount % 8;
+            if (axisConfig.angularAxis.ticksStep) {
+                tickCount = (angularDomainWithPadding[1] - angularDomainWithPadding[0]) / tickCount;
+            }
+            var angularTicksStep = axisConfig.angularAxis.ticksStep || (angularDomainWithPadding[1] - angularDomainWithPadding[0]) / (tickCount * (axisConfig.minorTicks + 1));
+            if (ticks) angularTicksStep = Math.max(Math.round(angularTicksStep), 1);
+            if (!angularDomainWithPadding[2]) angularDomainWithPadding[2] = angularTicksStep;
+            var angularAxisRange = d3.range.apply(this, angularDomainWithPadding);
+            angularAxisRange = angularAxisRange.map(function(d, i) {
+                return parseFloat(d.toPrecision(12));
+            });
+            angularScale = d3.scale.linear().domain(angularDomainWithPadding.slice(0, 2)).range(axisConfig.direction === 'clockwise' ? [ 0, 360 ] : [ 360, 0 ]);
+            liveConfig.layout.angularAxis.domain = angularScale.domain();
+            liveConfig.layout.angularAxis.endPadding = needsEndSpacing ? angularDomainStep : 0;
+            svg = d3.select(this).select('svg.chart-root');
+            if (typeof svg === 'undefined' || svg.empty()) {
+                var skeleton = "<svg xmlns='http://www.w3.org/2000/svg' class='chart-root'>' + '<g class='outer-group'>' + '<g class='chart-group'>' + '<circle class='background-circle'></circle>' + '<g class='geometry-group'></g>' + '<g class='radial axis-group'>' + '<circle class='outside-circle'></circle>' + '</g>' + '<g class='angular axis-group'></g>' + '<g class='guides-group'><line></line><circle r='0'></circle></g>' + '</g>' + '<g class='legend-group'></g>' + '<g class='tooltips-group'></g>' + '<g class='title-group'><text></text></g>' + '</g>' + '</svg>";
+                var doc = new DOMParser().parseFromString(skeleton, 'application/xml');
+                var newSvg = this.appendChild(this.ownerDocument.importNode(doc.documentElement, true));
+                svg = d3.select(newSvg);
+            }
+            svg.select('.guides-group').style({
+                'pointer-events': 'none'
+            });
+            svg.select('.angular.axis-group').style({
+                'pointer-events': 'none'
+            });
+            svg.select('.radial.axis-group').style({
+                'pointer-events': 'none'
+            });
+            var chartGroup = svg.select('.chart-group');
+            var lineStyle = {
+                fill: 'none',
+                stroke: axisConfig.tickColor
+            };
+            var fontStyle = {
+                'font-size': axisConfig.font.size,
+                'font-family': axisConfig.font.family,
+                fill: axisConfig.font.color,
+                'text-shadow': [ '-1px 0px', '1px -1px', '-1px 1px', '1px 1px' ].map(function(d, i) {
+                    return ' ' + d + ' 0 ' + axisConfig.font.outlineColor;
+                }).join(',')
+            };
+            var legendContainer;
+            if (axisConfig.showLegend) {
+                legendContainer = svg.select('.legend-group').attr({
+                    transform: 'translate(' + [ radius, axisConfig.margin.top ] + ')'
+                }).style({
+                    display: 'block'
+                });
+                var elements = data.map(function(d, i) {
+                    var datumClone = Âµ.util.cloneJson(d);
+                    datumClone.symbol = d.geometry === 'DotPlot' ? d.dotType || 'circle' : d.geometry != 'LinePlot' ? 'square' : 'line';
+                    datumClone.visibleInLegend = typeof d.visibleInLegend === 'undefined' || d.visibleInLegend;
+                    datumClone.color = d.geometry === 'LinePlot' ? d.strokeColor : d.color;
+                    return datumClone;
+                });
+
+                Âµ.Legend().config({
+                    data: data.map(function(d, i) {
+                        return d.name || 'Element' + i;
+                    }),
+                    legendConfig: extendDeepAll({},
+                        Âµ.Legend.defaultConfig().legendConfig,
+                        {
+                            container: legendContainer,
+                            elements: elements,
+                            reverseOrder: axisConfig.legend.reverseOrder
+                        }
+                    )
+                })();
+
+                var legendBBox = legendContainer.node().getBBox();
+                radius = Math.min(axisConfig.width - legendBBox.width - axisConfig.margin.left - axisConfig.margin.right, axisConfig.height - axisConfig.margin.top - axisConfig.margin.bottom) / 2;
+                radius = Math.max(10, radius);
+                chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ];
+                radialScale.range([ 0, radius ]);
+                liveConfig.layout.radialAxis.domain = radialScale.domain();
+                legendContainer.attr('transform', 'translate(' + [ chartCenter[0] + radius, chartCenter[1] - radius ] + ')');
+            } else {
+                legendContainer = svg.select('.legend-group').style({
+                    display: 'none'
+                });
+            }
+            svg.attr({
+                width: axisConfig.width,
+                height: axisConfig.height
+            }).style({
+                opacity: axisConfig.opacity
+            });
+            chartGroup.attr('transform', 'translate(' + chartCenter + ')').style({
+                cursor: 'crosshair'
+            });
+            var centeringOffset = [ (axisConfig.width - (axisConfig.margin.left + axisConfig.margin.right + radius * 2 + (legendBBox ? legendBBox.width : 0))) / 2, (axisConfig.height - (axisConfig.margin.top + axisConfig.margin.bottom + radius * 2)) / 2 ];
+            centeringOffset[0] = Math.max(0, centeringOffset[0]);
+            centeringOffset[1] = Math.max(0, centeringOffset[1]);
+            svg.select('.outer-group').attr('transform', 'translate(' + centeringOffset + ')');
+            if (axisConfig.title) {
+                var title = svg.select('g.title-group text').style(fontStyle).text(axisConfig.title);
+                var titleBBox = title.node().getBBox();
+                title.attr({
+                    x: chartCenter[0] - titleBBox.width / 2,
+                    y: chartCenter[1] - radius - 20
+                });
+            }
+            var radialAxis = svg.select('.radial.axis-group');
+            if (axisConfig.radialAxis.gridLinesVisible) {
+                var gridCircles = radialAxis.selectAll('circle.grid-circle').data(radialScale.ticks(5));
+                gridCircles.enter().append('circle').attr({
+                    'class': 'grid-circle'
+                }).style(lineStyle);
+                gridCircles.attr('r', radialScale);
+                gridCircles.exit().remove();
+            }
+            radialAxis.select('circle.outside-circle').attr({
+                r: radius
+            }).style(lineStyle);
+            var backgroundCircle = svg.select('circle.background-circle').attr({
+                r: radius
+            }).style({
+                fill: axisConfig.backgroundColor,
+                stroke: axisConfig.stroke
+            });
+            function currentAngle(d, i) {
+                return angularScale(d) % 360 + axisConfig.orientation;
+            }
+            if (axisConfig.radialAxis.visible) {
+                var axis = d3.svg.axis().scale(radialScale).ticks(5).tickSize(5);
+                radialAxis.call(axis).attr({
+                    transform: 'rotate(' + axisConfig.radialAxis.orientation + ')'
+                });
+                radialAxis.selectAll('.domain').style(lineStyle);
+                radialAxis.selectAll('g>text').text(function(d, i) {
+                    return this.textContent + axisConfig.radialAxis.ticksSuffix;
+                }).style(fontStyle).style({
+                    'text-anchor': 'start'
+                }).attr({
+                    x: 0,
+                    y: 0,
+                    dx: 0,
+                    dy: 0,
+                    transform: function(d, i) {
+                        if (axisConfig.radialAxis.tickOrientation === 'horizontal') {
+                            return 'rotate(' + -axisConfig.radialAxis.orientation + ') translate(' + [ 0, fontStyle['font-size'] ] + ')';
+                        } else return 'translate(' + [ 0, fontStyle['font-size'] ] + ')';
+                    }
+                });
+                radialAxis.selectAll('g>line').style({
+                    stroke: 'black'
+                });
+            }
+            var angularAxis = svg.select('.angular.axis-group').selectAll('g.angular-tick').data(angularAxisRange);
+            var angularAxisEnter = angularAxis.enter().append('g').classed('angular-tick', true);
+            angularAxis.attr({
+                transform: function(d, i) {
+                    return 'rotate(' + currentAngle(d, i) + ')';
+                }
+            }).style({
+                display: axisConfig.angularAxis.visible ? 'block' : 'none'
+            });
+            angularAxis.exit().remove();
+            angularAxisEnter.append('line').classed('grid-line', true).classed('major', function(d, i) {
+                return i % (axisConfig.minorTicks + 1) == 0;
+            }).classed('minor', function(d, i) {
+                return !(i % (axisConfig.minorTicks + 1) == 0);
+            }).style(lineStyle);
+            angularAxisEnter.selectAll('.minor').style({
+                stroke: axisConfig.minorTickColor
+            });
+            angularAxis.select('line.grid-line').attr({
+                x1: axisConfig.tickLength ? radius - axisConfig.tickLength : 0,
+                x2: radius
+            }).style({
+                display: axisConfig.angularAxis.gridLinesVisible ? 'block' : 'none'
+            });
+            angularAxisEnter.append('text').classed('axis-text', true).style(fontStyle);
+            var ticksText = angularAxis.select('text.axis-text').attr({
+                x: radius + axisConfig.labelOffset,
+                dy: '.35em',
+                transform: function(d, i) {
+                    var angle = currentAngle(d, i);
+                    var rad = radius + axisConfig.labelOffset;
+                    var orient = axisConfig.angularAxis.tickOrientation;
+                    if (orient == 'horizontal') return 'rotate(' + -angle + ' ' + rad + ' 0)'; else if (orient == 'radial') return angle < 270 && angle > 90 ? 'rotate(180 ' + rad + ' 0)' : null; else return 'rotate(' + (angle <= 180 && angle > 0 ? -90 : 90) + ' ' + rad + ' 0)';
+                }
+            }).style({
+                'text-anchor': 'middle',
+                display: axisConfig.angularAxis.labelsVisible ? 'block' : 'none'
+            }).text(function(d, i) {
+                if (i % (axisConfig.minorTicks + 1) != 0) return '';
+                if (ticks) {
+                    return ticks[d] + axisConfig.angularAxis.ticksSuffix;
+                } else return d + axisConfig.angularAxis.ticksSuffix;
+            }).style(fontStyle);
+            if (axisConfig.angularAxis.rewriteTicks) ticksText.text(function(d, i) {
+                if (i % (axisConfig.minorTicks + 1) != 0) return '';
+                return axisConfig.angularAxis.rewriteTicks(this.textContent, i);
+            });
+            var rightmostTickEndX = d3.max(chartGroup.selectAll('.angular-tick text')[0].map(function(d, i) {
+                return d.getCTM().e + d.getBBox().width;
+            }));
+            legendContainer.attr({
+                transform: 'translate(' + [ radius + rightmostTickEndX, axisConfig.margin.top ] + ')'
+            });
+            var hasGeometry = svg.select('g.geometry-group').selectAll('g').size() > 0;
+            var geometryContainer = svg.select('g.geometry-group').selectAll('g.geometry').data(data);
+            geometryContainer.enter().append('g').attr({
+                'class': function(d, i) {
+                    return 'geometry geometry' + i;
+                }
+            });
+            geometryContainer.exit().remove();
+            if (data[0] || hasGeometry) {
+                var geometryConfigs = [];
+                data.forEach(function(d, i) {
+                    var geometryConfig = {};
+                    geometryConfig.radialScale = radialScale;
+                    geometryConfig.angularScale = angularScale;
+                    geometryConfig.container = geometryContainer.filter(function(dB, iB) {
+                        return iB == i;
+                    });
+                    geometryConfig.geometry = d.geometry;
+                    geometryConfig.orientation = axisConfig.orientation;
+                    geometryConfig.direction = axisConfig.direction;
+                    geometryConfig.index = i;
+                    geometryConfigs.push({
+                        data: d,
+                        geometryConfig: geometryConfig
+                    });
+                });
+                var geometryConfigsGrouped = d3.nest().key(function(d, i) {
+                    return typeof d.data.groupId != 'undefined' || 'unstacked';
+                }).entries(geometryConfigs);
+                var geometryConfigsGrouped2 = [];
+                geometryConfigsGrouped.forEach(function(d, i) {
+                    if (d.key === 'unstacked') geometryConfigsGrouped2 = geometryConfigsGrouped2.concat(d.values.map(function(d, i) {
+                        return [ d ];
+                    })); else geometryConfigsGrouped2.push(d.values);
+                });
+                geometryConfigsGrouped2.forEach(function(d, i) {
+                    var geometry;
+                    if (Array.isArray(d)) geometry = d[0].geometryConfig.geometry; else geometry = d.geometryConfig.geometry;
+                    var finalGeometryConfig = d.map(function(dB, iB) {
+                        return extendDeepAll(Âµ[geometry].defaultConfig(), dB);
+                    });
+                    Âµ[geometry]().config(finalGeometryConfig)();
+                });
+            }
+            var guides = svg.select('.guides-group');
+            var tooltipContainer = svg.select('.tooltips-group');
+            var angularTooltip = Âµ.tooltipPanel().config({
+                container: tooltipContainer,
+                fontSize: 8
+            })();
+            var radialTooltip = Âµ.tooltipPanel().config({
+                container: tooltipContainer,
+                fontSize: 8
+            })();
+            var geometryTooltip = Âµ.tooltipPanel().config({
+                container: tooltipContainer,
+                hasTick: true
+            })();
+            var angularValue, radialValue;
+            if (!isOrdinal) {
+                var angularGuideLine = guides.select('line').attr({
+                    x1: 0,
+                    y1: 0,
+                    y2: 0
+                }).style({
+                    stroke: 'grey',
+                    'pointer-events': 'none'
+                });
+                chartGroup.on('mousemove.angular-guide', function(d, i) {
+                    var mouseAngle = Âµ.util.getMousePos(backgroundCircle).angle;
+                    angularGuideLine.attr({
+                        x2: -radius,
+                        transform: 'rotate(' + mouseAngle + ')'
+                    }).style({
+                        opacity: .5
+                    });
+                    var angleWithOriginOffset = (mouseAngle + 180 + 360 - axisConfig.orientation) % 360;
+                    angularValue = angularScale.invert(angleWithOriginOffset);
+                    var pos = Âµ.util.convertToCartesian(radius + 12, mouseAngle + 180);
+                    angularTooltip.text(Âµ.util.round(angularValue)).move([ pos[0] + chartCenter[0], pos[1] + chartCenter[1] ]);
+                }).on('mouseout.angular-guide', function(d, i) {
+                    guides.select('line').style({
+                        opacity: 0
+                    });
+                });
+            }
+            var angularGuideCircle = guides.select('circle').style({
+                stroke: 'grey',
+                fill: 'none'
+            });
+            chartGroup.on('mousemove.radial-guide', function(d, i) {
+                var r = Âµ.util.getMousePos(backgroundCircle).radius;
+                angularGuideCircle.attr({
+                    r: r
+                }).style({
+                    opacity: .5
+                });
+                radialValue = radialScale.invert(Âµ.util.getMousePos(backgroundCircle).radius);
+                var pos = Âµ.util.convertToCartesian(r, axisConfig.radialAxis.orientation);
+                radialTooltip.text(Âµ.util.round(radialValue)).move([ pos[0] + chartCenter[0], pos[1] + chartCenter[1] ]);
+            }).on('mouseout.radial-guide', function(d, i) {
+                angularGuideCircle.style({
+                    opacity: 0
+                });
+                geometryTooltip.hide();
+                angularTooltip.hide();
+                radialTooltip.hide();
+            });
+            svg.selectAll('.geometry-group .mark').on('mouseover.tooltip', function(d, i) {
+                var el = d3.select(this);
+                var color = el.style('fill');
+                var newColor = 'black';
+                var opacity = el.style('opacity') || 1;
+                el.attr({
+                    'data-opacity': opacity
+                });
+                if (color != 'none') {
+                    el.attr({
+                        'data-fill': color
+                    });
+                    newColor = d3.hsl(color).darker().toString();
+                    el.style({
+                        fill: newColor,
+                        opacity: 1
+                    });
+                    var textData = {
+                        t: Âµ.util.round(d[0]),
+                        r: Âµ.util.round(d[1])
+                    };
+                    if (isOrdinal) textData.t = ticks[d[0]];
+                    var text = 't: ' + textData.t + ', r: ' + textData.r;
+                    var bbox = this.getBoundingClientRect();
+                    var svgBBox = svg.node().getBoundingClientRect();
+                    var pos = [ bbox.left + bbox.width / 2 - centeringOffset[0] - svgBBox.left, bbox.top + bbox.height / 2 - centeringOffset[1] - svgBBox.top ];
+                    geometryTooltip.config({
+                        color: newColor
+                    }).text(text);
+                    geometryTooltip.move(pos);
+                } else {
+                    color = el.style('stroke');
+                    el.attr({
+                        'data-stroke': color
+                    });
+                    newColor = d3.hsl(color).darker().toString();
+                    el.style({
+                        stroke: newColor,
+                        opacity: 1
+                    });
+                }
+            }).on('mousemove.tooltip', function(d, i) {
+                if (d3.event.which != 0) return false;
+                if (d3.select(this).attr('data-fill')) geometryTooltip.show();
+            }).on('mouseout.tooltip', function(d, i) {
+                geometryTooltip.hide();
+                var el = d3.select(this);
+                var fillColor = el.attr('data-fill');
+                if (fillColor) el.style({
+                    fill: fillColor,
+                    opacity: el.attr('data-opacity')
+                }); else el.style({
+                    stroke: el.attr('data-stroke'),
+                    opacity: el.attr('data-opacity')
+                });
+            });
+        });
+        return exports;
+    }
+    exports.render = function(_container) {
+        render(_container);
+        return this;
+    };
+    exports.config = function(_x) {
+        if (!arguments.length) return config;
+        var xClone = Âµ.util.cloneJson(_x);
+        xClone.data.forEach(function(d, i) {
+            if (!config.data[i]) config.data[i] = {};
+            extendDeepAll(config.data[i], Âµ.Axis.defaultConfig().data[0]);
+            extendDeepAll(config.data[i], d);
+        });
+        extendDeepAll(config.layout, Âµ.Axis.defaultConfig().layout);
+        extendDeepAll(config.layout, xClone.layout);
+        return this;
+    };
+    exports.getLiveConfig = function() {
+        return liveConfig;
+    };
+    exports.getinputConfig = function() {
+        return inputConfig;
+    };
+    exports.radialScale = function(_x) {
+        return radialScale;
+    };
+    exports.angularScale = function(_x) {
+        return angularScale;
+    };
+    exports.svg = function() {
+        return svg;
+    };
+    d3.rebind(exports, dispatch, 'on');
+    return exports;
+};
+
+Âµ.Axis.defaultConfig = function(d, i) {
+    var config = {
+        data: [ {
+            t: [ 1, 2, 3, 4 ],
+            r: [ 10, 11, 12, 13 ],
+            name: 'Line1',
+            geometry: 'LinePlot',
+            color: null,
+            strokeDash: 'solid',
+            strokeColor: null,
+            strokeSize: '1',
+            visibleInLegend: true,
+            opacity: 1
+        } ],
+        layout: {
+            defaultColorRange: d3.scale.category10().range(),
+            title: null,
+            height: 450,
+            width: 500,
+            margin: {
+                top: 40,
+                right: 40,
+                bottom: 40,
+                left: 40
+            },
+            font: {
+                size: 12,
+                color: 'gray',
+                outlineColor: 'white',
+                family: 'Tahoma, sans-serif'
+            },
+            direction: 'clockwise',
+            orientation: 0,
+            labelOffset: 10,
+            radialAxis: {
+                domain: null,
+                orientation: -45,
+                ticksSuffix: '',
+                visible: true,
+                gridLinesVisible: true,
+                tickOrientation: 'horizontal',
+                rewriteTicks: null
+            },
+            angularAxis: {
+                domain: [ 0, 360 ],
+                ticksSuffix: '',
+                visible: true,
+                gridLinesVisible: true,
+                labelsVisible: true,
+                tickOrientation: 'horizontal',
+                rewriteTicks: null,
+                ticksCount: null,
+                ticksStep: null
+            },
+            minorTicks: 0,
+            tickLength: null,
+            tickColor: 'silver',
+            minorTickColor: '#eee',
+            backgroundColor: 'none',
+            needsEndSpacing: null,
+            showLegend: true,
+            legend: {
+                reverseOrder: false
+            },
+            opacity: 1
+        }
+    };
+    return config;
+};
+
+Âµ.util = {};
+
+Âµ.DATAEXTENT = 'dataExtent';
+
+Âµ.AREA = 'AreaChart';
+
+Âµ.LINE = 'LinePlot';
+
+Âµ.DOT = 'DotPlot';
+
+Âµ.BAR = 'BarChart';
+
+Âµ.util._override = function(_objA, _objB) {
+    for (var x in _objA) if (x in _objB) _objB[x] = _objA[x];
+};
+
+Âµ.util._extend = function(_objA, _objB) {
+    for (var x in _objA) _objB[x] = _objA[x];
+};
+
+Âµ.util._rndSnd = function() {
+    return Math.random() * 2 - 1 + (Math.random() * 2 - 1) + (Math.random() * 2 - 1);
+};
+
+Âµ.util.dataFromEquation2 = function(_equation, _step) {
+    var step = _step || 6;
+    var data = d3.range(0, 360 + step, step).map(function(deg, index) {
+        var theta = deg * Math.PI / 180;
+        var radius = _equation(theta);
+        return [ deg, radius ];
+    });
+    return data;
+};
+
+Âµ.util.dataFromEquation = function(_equation, _step, _name) {
+    var step = _step || 6;
+    var t = [], r = [];
+    d3.range(0, 360 + step, step).forEach(function(deg, index) {
+        var theta = deg * Math.PI / 180;
+        var radius = _equation(theta);
+        t.push(deg);
+        r.push(radius);
+    });
+    var result = {
+        t: t,
+        r: r
+    };
+    if (_name) result.name = _name;
+    return result;
+};
+
+Âµ.util.ensureArray = function(_val, _count) {
+    if (typeof _val === 'undefined') return null;
+    var arr = [].concat(_val);
+    return d3.range(_count).map(function(d, i) {
+        return arr[i] || arr[0];
+    });
+};
+
+Âµ.util.fillArrays = function(_obj, _valueNames, _count) {
+    _valueNames.forEach(function(d, i) {
+        _obj[d] = Âµ.util.ensureArray(_obj[d], _count);
+    });
+    return _obj;
+};
+
+Âµ.util.cloneJson = function(json) {
+    return JSON.parse(JSON.stringify(json));
+};
+
+Âµ.util.validateKeys = function(obj, keys) {
+    if (typeof keys === 'string') keys = keys.split('.');
+    var next = keys.shift();
+    return obj[next] && (!keys.length || objHasKeys(obj[next], keys));
+};
+
+Âµ.util.sumArrays = function(a, b) {
+    return d3.zip(a, b).map(function(d, i) {
+        return d3.sum(d);
+    });
+};
+
+Âµ.util.arrayLast = function(a) {
+    return a[a.length - 1];
+};
+
+Âµ.util.arrayEqual = function(a, b) {
+    var i = Math.max(a.length, b.length, 1);
+    while (i-- >= 0 && a[i] === b[i]) ;
+    return i === -2;
+};
+
+Âµ.util.flattenArray = function(arr) {
+    var r = [];
+    while (!Âµ.util.arrayEqual(r, arr)) {
+        r = arr;
+        arr = [].concat.apply([], arr);
+    }
+    return arr;
+};
+
+Âµ.util.deduplicate = function(arr) {
+    return arr.filter(function(v, i, a) {
+        return a.indexOf(v) == i;
+    });
+};
+
+Âµ.util.convertToCartesian = function(radius, theta) {
+    var thetaRadians = theta * Math.PI / 180;
+    var x = radius * Math.cos(thetaRadians);
+    var y = radius * Math.sin(thetaRadians);
+    return [ x, y ];
+};
+
+Âµ.util.round = function(_value, _digits) {
+    var digits = _digits || 2;
+    var mult = Math.pow(10, digits);
+    return Math.round(_value * mult) / mult;
+};
+
+Âµ.util.getMousePos = function(_referenceElement) {
+    var mousePos = d3.mouse(_referenceElement.node());
+    var mouseX = mousePos[0];
+    var mouseY = mousePos[1];
+    var mouse = {};
+    mouse.x = mouseX;
+    mouse.y = mouseY;
+    mouse.pos = mousePos;
+    mouse.angle = (Math.atan2(mouseY, mouseX) + Math.PI) * 180 / Math.PI;
+    mouse.radius = Math.sqrt(mouseX * mouseX + mouseY * mouseY);
+    return mouse;
+};
+
+Âµ.util.duplicatesCount = function(arr) {
+    var uniques = {}, val;
+    var dups = {};
+    for (var i = 0, len = arr.length; i < len; i++) {
+        val = arr[i];
+        if (val in uniques) {
+            uniques[val]++;
+            dups[val] = uniques[val];
+        } else {
+            uniques[val] = 1;
+        }
+    }
+    return dups;
+};
+
+Âµ.util.duplicates = function(arr) {
+    return Object.keys(Âµ.util.duplicatesCount(arr));
+};
+
+Âµ.util.translator = function(obj, sourceBranch, targetBranch, reverse) {
+    if (reverse) {
+        var targetBranchCopy = targetBranch.slice();
+        targetBranch = sourceBranch;
+        sourceBranch = targetBranchCopy;
+    }
+    var value = sourceBranch.reduce(function(previousValue, currentValue) {
+        if (typeof previousValue != 'undefined') return previousValue[currentValue];
+    }, obj);
+    if (typeof value === 'undefined') return;
+    sourceBranch.reduce(function(previousValue, currentValue, index) {
+        if (typeof previousValue == 'undefined') return;
+        if (index === sourceBranch.length - 1) delete previousValue[currentValue];
+        return previousValue[currentValue];
+    }, obj);
+    targetBranch.reduce(function(previousValue, currentValue, index) {
+        if (typeof previousValue[currentValue] === 'undefined') previousValue[currentValue] = {};
+        if (index === targetBranch.length - 1) previousValue[currentValue] = value;
+        return previousValue[currentValue];
+    }, obj);
+};
+
+Âµ.PolyChart = function module() {
+    var config = [ Âµ.PolyChart.defaultConfig() ];
+    var dispatch = d3.dispatch('hover');
+    var dashArray = {
+        solid: 'none',
+        dash: [ 5, 2 ],
+        dot: [ 2, 5 ]
+    };
+    var colorScale;
+    function exports() {
+        var geometryConfig = config[0].geometryConfig;
+        var container = geometryConfig.container;
+        if (typeof container == 'string') container = d3.select(container);
+        container.datum(config).each(function(_config, _index) {
+            var isStack = !!_config[0].data.yStack;
+            var data = _config.map(function(d, i) {
+                if (isStack) return d3.zip(d.data.t[0], d.data.r[0], d.data.yStack[0]); else return d3.zip(d.data.t[0], d.data.r[0]);
+            });
+            var angularScale = geometryConfig.angularScale;
+            var domainMin = geometryConfig.radialScale.domain()[0];
+            var generator = {};
+            generator.bar = function(d, i, pI) {
+                var dataConfig = _config[pI].data;
+                var h = geometryConfig.radialScale(d[1]) - geometryConfig.radialScale(0);
+                var stackTop = geometryConfig.radialScale(d[2] || 0);
+                var w = dataConfig.barWidth;
+                d3.select(this).attr({
+                    'class': 'mark bar',
+                    d: 'M' + [ [ h + stackTop, -w / 2 ], [ h + stackTop, w / 2 ], [ stackTop, w / 2 ], [ stackTop, -w / 2 ] ].join('L') + 'Z',
+                    transform: function(d, i) {
+                        return 'rotate(' + (geometryConfig.orientation + angularScale(d[0])) + ')';
+                    }
+                });
+            };
+            generator.dot = function(d, i, pI) {
+                var stackedData = d[2] ? [ d[0], d[1] + d[2] ] : d;
+                var symbol = d3.svg.symbol().size(_config[pI].data.dotSize).type(_config[pI].data.dotType)(d, i);
+                d3.select(this).attr({
+                    'class': 'mark dot',
+                    d: symbol,
+                    transform: function(d, i) {
+                        var coord = convertToCartesian(getPolarCoordinates(stackedData));
+                        return 'translate(' + [ coord.x, coord.y ] + ')';
+                    }
+                });
+            };
+            var line = d3.svg.line.radial().interpolate(_config[0].data.lineInterpolation).radius(function(d) {
+                return geometryConfig.radialScale(d[1]);
+            }).angle(function(d) {
+                return geometryConfig.angularScale(d[0]) * Math.PI / 180;
+            });
+            generator.line = function(d, i, pI) {
+                var lineData = d[2] ? data[pI].map(function(d, i) {
+                    return [ d[0], d[1] + d[2] ];
+                }) : data[pI];
+                d3.select(this).each(generator['dot']).style({
+                    opacity: function(dB, iB) {
+                        return +_config[pI].data.dotVisible;
+                    },
+                    fill: markStyle.stroke(d, i, pI)
+                }).attr({
+                    'class': 'mark dot'
+                });
+                if (i > 0) return;
+                var lineSelection = d3.select(this.parentNode).selectAll('path.line').data([ 0 ]);
+                lineSelection.enter().insert('path');
+                lineSelection.attr({
+                    'class': 'line',
+                    d: line(lineData),
+                    transform: function(dB, iB) {
+                        return 'rotate(' + (geometryConfig.orientation + 90) + ')';
+                    },
+                    'pointer-events': 'none'
+                }).style({
+                    fill: function(dB, iB) {
+                        return markStyle.fill(d, i, pI);
+                    },
+                    'fill-opacity': 0,
+                    stroke: function(dB, iB) {
+                        return markStyle.stroke(d, i, pI);
+                    },
+                    'stroke-width': function(dB, iB) {
+                        return markStyle['stroke-width'](d, i, pI);
+                    },
+                    'stroke-dasharray': function(dB, iB) {
+                        return markStyle['stroke-dasharray'](d, i, pI);
+                    },
+                    opacity: function(dB, iB) {
+                        return markStyle.opacity(d, i, pI);
+                    },
+                    display: function(dB, iB) {
+                        return markStyle.display(d, i, pI);
+                    }
+                });
+            };
+            var angularRange = geometryConfig.angularScale.range();
+            var triangleAngle = Math.abs(angularRange[1] - angularRange[0]) / data[0].length * Math.PI / 180;
+            var arc = d3.svg.arc().startAngle(function(d) {
+                return -triangleAngle / 2;
+            }).endAngle(function(d) {
+                return triangleAngle / 2;
+            }).innerRadius(function(d) {
+                return geometryConfig.radialScale(domainMin + (d[2] || 0));
+            }).outerRadius(function(d) {
+                return geometryConfig.radialScale(domainMin + (d[2] || 0)) + geometryConfig.radialScale(d[1]);
+            });
+            generator.arc = function(d, i, pI) {
+                d3.select(this).attr({
+                    'class': 'mark arc',
+                    d: arc,
+                    transform: function(d, i) {
+                        return 'rotate(' + (geometryConfig.orientation + angularScale(d[0]) + 90) + ')';
+                    }
+                });
+            };
+            var markStyle = {
+                fill: function(d, i, pI) {
+                    return _config[pI].data.color;
+                },
+                stroke: function(d, i, pI) {
+                    return _config[pI].data.strokeColor;
+                },
+                'stroke-width': function(d, i, pI) {
+                    return _config[pI].data.strokeSize + 'px';
+                },
+                'stroke-dasharray': function(d, i, pI) {
+                    return dashArray[_config[pI].data.strokeDash];
+                },
+                opacity: function(d, i, pI) {
+                    return _config[pI].data.opacity;
+                },
+                display: function(d, i, pI) {
+                    return typeof _config[pI].data.visible === 'undefined' || _config[pI].data.visible ? 'block' : 'none';
+                }
+            };
+            var geometryLayer = d3.select(this).selectAll('g.layer').data(data);
+            geometryLayer.enter().append('g').attr({
+                'class': 'layer'
+            });
+            var geometry = geometryLayer.selectAll('path.mark').data(function(d, i) {
+                return d;
+            });
+            geometry.enter().append('path').attr({
+                'class': 'mark'
+            });
+            geometry.style(markStyle).each(generator[geometryConfig.geometryType]);
+            geometry.exit().remove();
+            geometryLayer.exit().remove();
+            function getPolarCoordinates(d, i) {
+                var r = geometryConfig.radialScale(d[1]);
+                var t = (geometryConfig.angularScale(d[0]) + geometryConfig.orientation) * Math.PI / 180;
+                return {
+                    r: r,
+                    t: t
+                };
+            }
+            function convertToCartesian(polarCoordinates) {
+                var x = polarCoordinates.r * Math.cos(polarCoordinates.t);
+                var y = polarCoordinates.r * Math.sin(polarCoordinates.t);
+                return {
+                    x: x,
+                    y: y
+                };
+            }
+        });
+    }
+    exports.config = function(_x) {
+        if (!arguments.length) return config;
+        _x.forEach(function(d, i) {
+            if (!config[i]) config[i] = {};
+            extendDeepAll(config[i], Âµ.PolyChart.defaultConfig());
+            extendDeepAll(config[i], d);
+        });
+        return this;
+    };
+    exports.getColorScale = function() {
+        return colorScale;
+    };
+    d3.rebind(exports, dispatch, 'on');
+    return exports;
+};
+
+Âµ.PolyChart.defaultConfig = function() {
+    var config = {
+        data: {
+            name: 'geom1',
+            t: [ [ 1, 2, 3, 4 ] ],
+            r: [ [ 1, 2, 3, 4 ] ],
+            dotType: 'circle',
+            dotSize: 64,
+            dotVisible: false,
+            barWidth: 20,
+            color: '#ffa500',
+            strokeSize: 1,
+            strokeColor: 'silver',
+            strokeDash: 'solid',
+            opacity: 1,
+            index: 0,
+            visible: true,
+            visibleInLegend: true
+        },
+        geometryConfig: {
+            geometry: 'LinePlot',
+            geometryType: 'arc',
+            direction: 'clockwise',
+            orientation: 0,
+            container: 'body',
+            radialScale: null,
+            angularScale: null,
+            colorScale: d3.scale.category20()
+        }
+    };
+    return config;
+};
+
+Âµ.BarChart = function module() {
+    return Âµ.PolyChart();
+};
+
+Âµ.BarChart.defaultConfig = function() {
+    var config = {
+        geometryConfig: {
+            geometryType: 'bar'
+        }
+    };
+    return config;
+};
+
+Âµ.AreaChart = function module() {
+    return Âµ.PolyChart();
+};
+
+Âµ.AreaChart.defaultConfig = function() {
+    var config = {
+        geometryConfig: {
+            geometryType: 'arc'
+        }
+    };
+    return config;
+};
+
+Âµ.DotPlot = function module() {
+    return Âµ.PolyChart();
+};
+
+Âµ.DotPlot.defaultConfig = function() {
+    var config = {
+        geometryConfig: {
+            geometryType: 'dot',
+            dotType: 'circle'
+        }
+    };
+    return config;
+};
+
+Âµ.LinePlot = function module() {
+    return Âµ.PolyChart();
+};
+
+Âµ.LinePlot.defaultConfig = function() {
+    var config = {
+        geometryConfig: {
+            geometryType: 'line'
+        }
+    };
+    return config;
+};
+
+Âµ.Legend = function module() {
+    var config = Âµ.Legend.defaultConfig();
+    var dispatch = d3.dispatch('hover');
+    function exports() {
+        var legendConfig = config.legendConfig;
+        var flattenData = config.data.map(function(d, i) {
+            return [].concat(d).map(function(dB, iB) {
+                var element = extendDeepAll({}, legendConfig.elements[i]);
+                element.name = dB;
+                element.color = [].concat(legendConfig.elements[i].color)[iB];
+                return element;
+            });
+        });
+        var data = d3.merge(flattenData);
+        data = data.filter(function(d, i) {
+            return legendConfig.elements[i] && (legendConfig.elements[i].visibleInLegend || typeof legendConfig.elements[i].visibleInLegend === 'undefined');
+        });
+        if (legendConfig.reverseOrder) data = data.reverse();
+        var container = legendConfig.container;
+        if (typeof container == 'string' || container.nodeName) container = d3.select(container);
+        var colors = data.map(function(d, i) {
+            return d.color;
+        });
+        var lineHeight = legendConfig.fontSize;
+        var isContinuous = legendConfig.isContinuous == null ? typeof data[0] === 'number' : legendConfig.isContinuous;
+        var height = isContinuous ? legendConfig.height : lineHeight * data.length;
+        var legendContainerGroup = container.classed('legend-group', true);
+        var svg = legendContainerGroup.selectAll('svg').data([ 0 ]);
+        var svgEnter = svg.enter().append('svg').attr({
+            width: 300,
+            height: height + lineHeight,
+            xmlns: 'http://www.w3.org/2000/svg',
+            'xmlns:xlink': 'http://www.w3.org/1999/xlink',
+            version: '1.1'
+        });
+        svgEnter.append('g').classed('legend-axis', true);
+        svgEnter.append('g').classed('legend-marks', true);
+        var dataNumbered = d3.range(data.length);
+        var colorScale = d3.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered).range(colors);
+        var dataScale = d3.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered)[isContinuous ? 'range' : 'rangePoints']([ 0, height ]);
+        var shapeGenerator = function(_type, _size) {
+            var squareSize = _size * 3;
+            if (_type === 'line') {
+                return 'M' + [ [ -_size / 2, -_size / 12 ], [ _size / 2, -_size / 12 ], [ _size / 2, _size / 12 ], [ -_size / 2, _size / 12 ] ] + 'Z';
+            } else if (d3.svg.symbolTypes.indexOf(_type) != -1) return d3.svg.symbol().type(_type).size(squareSize)(); else return d3.svg.symbol().type('square').size(squareSize)();
+        };
+        if (isContinuous) {
+            var gradient = svg.select('.legend-marks').append('defs').append('linearGradient').attr({
+                id: 'grad1',
+                x1: '0%',
+                y1: '0%',
+                x2: '0%',
+                y2: '100%'
+            }).selectAll('stop').data(colors);
+            gradient.enter().append('stop');
+            gradient.attr({
+                offset: function(d, i) {
+                    return i / (colors.length - 1) * 100 + '%';
+                }
+            }).style({
+                'stop-color': function(d, i) {
+                    return d;
+                }
+            });
+            svg.append('rect').classed('legend-mark', true).attr({
+                height: legendConfig.height,
+                width: legendConfig.colorBandWidth,
+                fill: 'url(#grad1)'
+            });
+        } else {
+            var legendElement = svg.select('.legend-marks').selectAll('path.legend-mark').data(data);
+            legendElement.enter().append('path').classed('legend-mark', true);
+            legendElement.attr({
+                transform: function(d, i) {
+                    return 'translate(' + [ lineHeight / 2, dataScale(i) + lineHeight / 2 ] + ')';
+                },
+                d: function(d, i) {
+                    var symbolType = d.symbol;
+                    return shapeGenerator(symbolType, lineHeight);
+                },
+                fill: function(d, i) {
+                    return colorScale(i);
+                }
+            });
+            legendElement.exit().remove();
+        }
+        var legendAxis = d3.svg.axis().scale(dataScale).orient('right');
+        var axis = svg.select('g.legend-axis').attr({
+            transform: 'translate(' + [ isContinuous ? legendConfig.colorBandWidth : lineHeight, lineHeight / 2 ] + ')'
+        }).call(legendAxis);
+        axis.selectAll('.domain').style({
+            fill: 'none',
+            stroke: 'none'
+        });
+        axis.selectAll('line').style({
+            fill: 'none',
+            stroke: isContinuous ? legendConfig.textColor : 'none'
+        });
+        axis.selectAll('text').style({
+            fill: legendConfig.textColor,
+            'font-size': legendConfig.fontSize
+        }).text(function(d, i) {
+            return data[i].name;
+        });
+        return exports;
+    }
+    exports.config = function(_x) {
+        if (!arguments.length) return config;
+        extendDeepAll(config, _x);
+        return this;
+    };
+    d3.rebind(exports, dispatch, 'on');
+    return exports;
+};
+
+Âµ.Legend.defaultConfig = function(d, i) {
+    var config = {
+        data: [ 'a', 'b', 'c' ],
+        legendConfig: {
+            elements: [ {
+                symbol: 'line',
+                color: 'red'
+            }, {
+                symbol: 'square',
+                color: 'yellow'
+            }, {
+                symbol: 'diamond',
+                color: 'limegreen'
+            } ],
+            height: 150,
+            colorBandWidth: 30,
+            fontSize: 12,
+            container: 'body',
+            isContinuous: null,
+            textColor: 'grey',
+            reverseOrder: false
+        }
+    };
+    return config;
+};
+
+Âµ.tooltipPanel = function() {
+    var tooltipEl, tooltipTextEl, backgroundEl;
+    var config = {
+        container: null,
+        hasTick: false,
+        fontSize: 12,
+        color: 'white',
+        padding: 5
+    };
+    var id = 'tooltip-' + Âµ.tooltipPanel.uid++;
+    var tickSize = 10;
+    var exports = function() {
+        tooltipEl = config.container.selectAll('g.' + id).data([ 0 ]);
+        var tooltipEnter = tooltipEl.enter().append('g').classed(id, true).style({
+            'pointer-events': 'none',
+            display: 'none'
+        });
+        backgroundEl = tooltipEnter.append('path').style({
+            fill: 'white',
+            'fill-opacity': .9
+        }).attr({
+            d: 'M0 0'
+        });
+        tooltipTextEl = tooltipEnter.append('text').attr({
+            dx: config.padding + tickSize,
+            dy: +config.fontSize * .3
+        });
+        return exports;
+    };
+    exports.text = function(_text) {
+        var l = d3.hsl(config.color).l;
+        var strokeColor = l >= .5 ? '#aaa' : 'white';
+        var fillColor = l >= .5 ? 'black' : 'white';
+        var text = _text || '';
+        tooltipTextEl.style({
+            fill: fillColor,
+            'font-size': config.fontSize + 'px'
+        }).text(text);
+        var padding = config.padding;
+        var bbox = tooltipTextEl.node().getBBox();
+        var boxStyle = {
+            fill: config.color,
+            stroke: strokeColor,
+            'stroke-width': '2px'
+        };
+        var backGroundW = bbox.width + padding * 2 + tickSize;
+        var backGroundH = bbox.height + padding * 2;
+        backgroundEl.attr({
+            d: 'M' + [ [ tickSize, -backGroundH / 2 ], [ tickSize, -backGroundH / 4 ], [ config.hasTick ? 0 : tickSize, 0 ], [ tickSize, backGroundH / 4 ], [ tickSize, backGroundH / 2 ], [ backGroundW, backGroundH / 2 ], [ backGroundW, -backGroundH / 2 ] ].join('L') + 'Z'
+        }).style(boxStyle);
+        tooltipEl.attr({
+            transform: 'translate(' + [ tickSize, -backGroundH / 2 + padding * 2 ] + ')'
+        });
+        tooltipEl.style({
+            display: 'block'
+        });
+        return exports;
+    };
+    exports.move = function(_pos) {
+        if (!tooltipEl) return;
+        tooltipEl.attr({
+            transform: 'translate(' + [ _pos[0], _pos[1] ] + ')'
+        }).style({
+            display: 'block'
+        });
+        return exports;
+    };
+    exports.hide = function() {
+        if (!tooltipEl) return;
+        tooltipEl.style({
+            display: 'none'
+        });
+        return exports;
+    };
+    exports.show = function() {
+        if (!tooltipEl) return;
+        tooltipEl.style({
+            display: 'block'
+        });
+        return exports;
+    };
+    exports.config = function(_x) {
+        extendDeepAll(config, _x);
+        return exports;
+    };
+    return exports;
+};
+
+Âµ.tooltipPanel.uid = 1;
+
+Âµ.adapter = {};
+
+Âµ.adapter.plotly = function module() {
+    var exports = {};
+    exports.convert = function(_inputConfig, reverse) {
+        var outputConfig = {};
+        if (_inputConfig.data) {
+            outputConfig.data = _inputConfig.data.map(function(d, i) {
+                var r = extendDeepAll({}, d);
+                var toTranslate = [
+                    [ r, [ 'marker', 'color' ], [ 'color' ] ],
+                    [ r, [ 'marker', 'opacity' ], [ 'opacity' ] ],
+                    [ r, [ 'marker', 'line', 'color' ], [ 'strokeColor' ] ],
+                    [ r, [ 'marker', 'line', 'dash' ], [ 'strokeDash' ] ],
+                    [ r, [ 'marker', 'line', 'width' ], [ 'strokeSize' ] ],
+                    [ r, [ 'marker', 'symbol' ], [ 'dotType' ] ],
+                    [ r, [ 'marker', 'size' ], [ 'dotSize' ] ],
+                    [ r, [ 'marker', 'barWidth' ], [ 'barWidth' ] ],
+                    [ r, [ 'line', 'interpolation' ], [ 'lineInterpolation' ] ],
+                    [ r, [ 'showlegend' ], [ 'visibleInLegend' ] ]
+                ];
+                toTranslate.forEach(function(d, i) {
+                    Âµ.util.translator.apply(null, d.concat(reverse));
+                });
+
+                if (!reverse) delete r.marker;
+                if (reverse) delete r.groupId;
+                if (!reverse) {
+                    if (r.type === 'scatter') {
+                        if (r.mode === 'lines') r.geometry = 'LinePlot'; else if (r.mode === 'markers') r.geometry = 'DotPlot'; else if (r.mode === 'lines+markers') {
+                            r.geometry = 'LinePlot';
+                            r.dotVisible = true;
+                        }
+                    } else if (r.type === 'area') r.geometry = 'AreaChart'; else if (r.type === 'bar') r.geometry = 'BarChart';
+                    delete r.mode;
+                    delete r.type;
+                } else {
+                    if (r.geometry === 'LinePlot') {
+                        r.type = 'scatter';
+                        if (r.dotVisible === true) {
+                            delete r.dotVisible;
+                            r.mode = 'lines+markers';
+                        } else r.mode = 'lines';
+                    } else if (r.geometry === 'DotPlot') {
+                        r.type = 'scatter';
+                        r.mode = 'markers';
+                    } else if (r.geometry === 'AreaChart') r.type = 'area'; else if (r.geometry === 'BarChart') r.type = 'bar';
+                    delete r.geometry;
+                }
+                return r;
+            });
+            if (!reverse && _inputConfig.layout && _inputConfig.layout.barmode === 'stack') {
+                var duplicates = Âµ.util.duplicates(outputConfig.data.map(function(d, i) {
+                    return d.geometry;
+                }));
+                outputConfig.data.forEach(function(d, i) {
+                    var idx = duplicates.indexOf(d.geometry);
+                    if (idx != -1) outputConfig.data[i].groupId = idx;
+                });
+            }
+        }
+        if (_inputConfig.layout) {
+            var r = extendDeepAll({}, _inputConfig.layout);
+            var toTranslate = [
+                [ r, [ 'plot_bgcolor' ], [ 'backgroundColor' ] ],
+                [ r, [ 'showlegend' ], [ 'showLegend' ] ],
+                [ r, [ 'radialaxis' ], [ 'radialAxis' ] ],
+                [ r, [ 'angularaxis' ], [ 'angularAxis' ] ],
+                [ r.angularaxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
+                [ r.angularaxis, [ 'showticklabels' ], [ 'labelsVisible' ] ],
+                [ r.angularaxis, [ 'nticks' ], [ 'ticksCount' ] ],
+                [ r.angularaxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
+                [ r.angularaxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
+                [ r.angularaxis, [ 'range' ], [ 'domain' ] ],
+                [ r.angularaxis, [ 'endpadding' ], [ 'endPadding' ] ],
+                [ r.radialaxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
+                [ r.radialaxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
+                [ r.radialaxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
+                [ r.radialaxis, [ 'range' ], [ 'domain' ] ],
+                [ r.angularAxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
+                [ r.angularAxis, [ 'showticklabels' ], [ 'labelsVisible' ] ],
+                [ r.angularAxis, [ 'nticks' ], [ 'ticksCount' ] ],
+                [ r.angularAxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
+                [ r.angularAxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
+                [ r.angularAxis, [ 'range' ], [ 'domain' ] ],
+                [ r.angularAxis, [ 'endpadding' ], [ 'endPadding' ] ],
+                [ r.radialAxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
+                [ r.radialAxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
+                [ r.radialAxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
+                [ r.radialAxis, [ 'range' ], [ 'domain' ] ],
+                [ r.font, [ 'outlinecolor' ], [ 'outlineColor' ] ],
+                [ r.legend, [ 'traceorder' ], [ 'reverseOrder' ] ],
+                [ r, [ 'labeloffset' ], [ 'labelOffset' ] ],
+                [ r, [ 'defaultcolorrange' ], [ 'defaultColorRange' ] ]
+            ];
+            toTranslate.forEach(function(d, i) {
+                Âµ.util.translator.apply(null, d.concat(reverse));
+            });
+
+            if (!reverse) {
+                if (r.angularAxis && typeof r.angularAxis.ticklen !== 'undefined') r.tickLength = r.angularAxis.ticklen;
+                if (r.angularAxis && typeof r.angularAxis.tickcolor !== 'undefined') r.tickColor = r.angularAxis.tickcolor;
+            } else {
+                if (typeof r.tickLength !== 'undefined') {
+                    r.angularaxis.ticklen = r.tickLength;
+                    delete r.tickLength;
+                }
+                if (r.tickColor) {
+                    r.angularaxis.tickcolor = r.tickColor;
+                    delete r.tickColor;
+                }
+            }
+            if (r.legend && typeof r.legend.reverseOrder != 'boolean') {
+                r.legend.reverseOrder = r.legend.reverseOrder != 'normal';
+            }
+            if (r.legend && typeof r.legend.traceorder == 'boolean') {
+                r.legend.traceorder = r.legend.traceorder ? 'reversed' : 'normal';
+                delete r.legend.reverseOrder;
+            }
+            if (r.margin && typeof r.margin.t != 'undefined') {
+                var source = [ 't', 'r', 'b', 'l', 'pad' ];
+                var target = [ 'top', 'right', 'bottom', 'left', 'pad' ];
+                var margin = {};
+                d3.entries(r.margin).forEach(function(dB, iB) {
+                    margin[target[source.indexOf(dB.key)]] = dB.value;
+                });
+                r.margin = margin;
+            }
+            if (reverse) {
+                delete r.needsEndSpacing;
+                delete r.minorTickColor;
+                delete r.minorTicks;
+                delete r.angularaxis.ticksCount;
+                delete r.angularaxis.ticksCount;
+                delete r.angularaxis.ticksStep;
+                delete r.angularaxis.rewriteTicks;
+                delete r.angularaxis.nticks;
+                delete r.radialaxis.ticksCount;
+                delete r.radialaxis.ticksCount;
+                delete r.radialaxis.ticksStep;
+                delete r.radialaxis.rewriteTicks;
+                delete r.radialaxis.nticks;
+            }
+            outputConfig.layout = r;
+        }
+        return outputConfig;
+    };
+    return exports;
+};
+
+},{"../../plotly":366,"./micropolar_manager":417,"d3":70}],417:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../../plotly');
+var d3 = require('d3');
+var UndoManager = require('./undo_manager');
+
+var manager = module.exports = {};
+
+var extendDeepAll = Plotly.Lib.extendDeepAll;
+
+manager.framework = function(_gd) {
+    var config, previousConfigClone, plot, convertedInput, container;
+    var undoManager = new UndoManager();
+
+    function exports(_inputConfig, _container) {
+        if(_container) container = _container;
+        d3.select(d3.select(container).node().parentNode).selectAll('.svg-container>*:not(.chart-root)').remove();
+
+        config = (!config) ?
+            _inputConfig :
+            extendDeepAll(config, _inputConfig);
+
+        if(!plot) plot = Plotly.micropolar.Axis();
+        convertedInput = Plotly.micropolar.adapter.plotly().convert(config);
+        plot.config(convertedInput).render(container);
+        _gd.data = config.data;
+        _gd.layout = config.layout;
+        manager.fillLayout(_gd);
+        return config;
+    }
+    exports.isPolar = true;
+    exports.svg = function() { return plot.svg(); };
+    exports.getConfig = function() { return config; };
+    exports.getLiveConfig = function() {
+        return Plotly.micropolar.adapter.plotly().convert(plot.getLiveConfig(), true);
+    };
+    exports.getLiveScales = function() { return {t: plot.angularScale(), r: plot.radialScale()}; };
+    exports.setUndoPoint = function() {
+        var that = this;
+        var configClone = Plotly.micropolar.util.cloneJson(config);
+        (function(_configClone, _previousConfigClone) {
+            undoManager.add({
+                undo: function() {
+                    //console.log('undo', _previousConfigClone);
+                    if(_previousConfigClone) that(_previousConfigClone);
+                },
+                redo: function() {
+                    //console.log('redo', _configClone);
+                    that(_configClone);
+                }
+            });
+        })(configClone, previousConfigClone);
+        previousConfigClone = Plotly.micropolar.util.cloneJson(configClone);
+    };
+    exports.undo = function() { undoManager.undo(); };
+    exports.redo = function() { undoManager.redo(); };
+    return exports;
+};
+
+manager.fillLayout = function(_gd) {
+    var container = d3.select(_gd).selectAll('.plot-container'),
+        paperDiv = container.selectAll('.svg-container'),
+        paper = _gd.framework && _gd.framework.svg && _gd.framework.svg(),
+        dflts = {
+            width: 800,
+            height: 600,
+            paper_bgcolor: Plotly.Color.background,
+            _container: container,
+            _paperdiv: paperDiv,
+            _paper: paper
+        };
+
+    _gd._fullLayout = extendDeepAll(dflts, _gd.layout);
+};
+
+},{"../../plotly":366,"./undo_manager":418,"d3":70}],418:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+//Modified from https://github.com/ArthurClemens/Javascript-Undo-Manager
+//Copyright (c) 2010-2013 Arthur Clemens, arthur@visiblearea.com
+module.exports = function UndoManager() {
+    var undoCommands = [],
+        index = -1,
+        isExecuting = false,
+        callback;
+
+    function execute(command, action) {
+        if(!command) return this;
+
+        isExecuting = true;
+        command[action]();
+        isExecuting = false;
+
+        return this;
+    }
+
+    return {
+        add: function(command) {
+            if(isExecuting) return this;
+            undoCommands.splice(index + 1, undoCommands.length - index);
+            undoCommands.push(command);
+            index = undoCommands.length - 1;
+            return this;
+        },
+        setCallback: function(callbackFunc) { callback = callbackFunc; },
+        undo: function() {
+            var command = undoCommands[index];
+            if(!command) return this;
+            execute(command, 'undo');
+            index -= 1;
+            if(callback) callback(command.undo);
+            return this;
+        },
+        redo: function() {
+            var command = undoCommands[index + 1];
+            if(!command) return this;
+            execute(command, 'redo');
+            index += 1;
+            if(callback) callback(command.redo);
+            return this;
+        },
+        clear: function() {
+            undoCommands = [];
+            index = -1;
+        },
+        hasUndo: function() { return index !== -1; },
+        hasRedo: function() { return index < (undoCommands.length - 1); },
+        getCommands: function() { return undoCommands; },
+        getPreviousCommand: function() { return undoCommands[index-1]; },
+        getIndex: function() { return index; }
+    };
+};
+
+},{}],419:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../plotly');
+
+var extendFlat = Plotly.Lib.extendFlat;
+var extendDeep = Plotly.Lib.extendDeep;
+
+// Put default plotTile layouts here
+function cloneLayoutOverride(tileClass) {
+    var override;
+
+    switch(tileClass) {
+        case 'themes__thumb':
+            override = {
+                autosize: true,
+                width: 150,
+                height: 150,
+                title: '',
+                showlegend: false,
+                margin: {l: 5, r: 5, t: 5, b: 5, pad: 0},
+                annotations: []
+            };
+            break;
+
+        case 'thumbnail':
+            override = {
+                title: '',
+                hidesources: true,
+                showlegend: false,
+                borderwidth: 0,
+                bordercolor: '',
+                margin: {l: 1, r: 1, t: 1, b: 1, pad: 0},
+                annotations: []
+            };
+            break;
+
+        default:
+            override = {};
+    }
+
+
+    return override;
+}
+
+function keyIsAxis(keyName) {
+    var types = ['xaxis', 'yaxis', 'zaxis'];
+    return (types.indexOf(keyName.slice(0, 5)) > -1);
+}
+
+
+module.exports = function clonePlot(graphObj, options) {
+
+    // Polar plot compatibility
+    if(graphObj.framework && graphObj.framework.isPolar) {
+        graphObj = graphObj.framework.getConfig();
+    }
+
+    var i;
+    var oldData = graphObj.data;
+    var oldLayout = graphObj.layout;
+    var newData = extendDeep([], oldData);
+    var newLayout = extendDeep({}, oldLayout, cloneLayoutOverride(options.tileClass));
+
+    if(options.width) newLayout.width = options.width;
+    if(options.height) newLayout.height = options.height;
+
+    if(options.tileClass === 'thumbnail' || options.tileClass === 'themes__thumb') {
+        // kill annotations
+        newLayout.annotations = [];
+        var keys = Object.keys(newLayout);
+
+        for(i = 0; i < keys.length; i++) {
+            if(keyIsAxis(keys[i])) {
+                newLayout[keys[i]].title = '';
+            }
+        }
+
+        // kill colorbar and pie labels
+        for(i = 0; i < newData.length; i++) {
+            var trace = newData[i];
+            trace.showscale = false;
+            if(trace.marker) trace.marker.showscale = false;
+            if(trace.type === 'pie') trace.textposition = 'none';
+        }
+    }
+
+    if(Array.isArray(options.annotations)) {
+        for(i = 0; i < options.annotations.length; i++) {
+            newLayout.annotations.push(options.annotations[i]);
+        }
+    }
+
+    var sceneIds = Plotly.Plots.getSubplotIds(newLayout, 'gl3d');
+
+    if(sceneIds.length) {
+        var axesImageOverride = {};
+        if(options.tileClass === 'thumbnail') {
+            axesImageOverride = {
+                title: '',
+                showaxeslabels: false,
+                showticklabels: false,
+                linetickenable: false
+            };
+        }
+        for(i = 0; i < sceneIds.length; i++) {
+            var sceneId = sceneIds[i];
+
+            extendFlat(newLayout[sceneId].xaxis, axesImageOverride);
+            extendFlat(newLayout[sceneId].yaxis, axesImageOverride);
+            extendFlat(newLayout[sceneId].zaxis, axesImageOverride);
+
+            // TODO what does this do?
+            newLayout[sceneId]._scene = null;
+        }
+    }
+
+    var td = document.createElement('div');
+    if(options.tileClass) td.className = options.tileClass;
+
+    var plotTile = {
+        td: td,
+        layout: newLayout,
+        data: newData,
+        config: {
+            staticPlot: (options.staticPlot === undefined) ?
+                true :
+                options.staticPlot,
+            plotGlPixelRatio: (options.plotGlPixelRatio === undefined) ?
+                2 :
+                options.plotGlPixelRatio,
+            displaylogo: options.displaylogo || false,
+            showLink: options.showLink || false,
+            showTips: options.showTips || false
+        }
+    };
+
+    if(options.setBackground !== 'transparent') {
+        plotTile.config.setBackground = options.setBackground || 'opaque';
+    }
+
+    // attaching the default Layout the td, so you can grab it later
+    plotTile.td.defaultLayout = cloneLayoutOverride(options.tileClass);
+
+    return plotTile;
+};
+
+},{"../plotly":366}],420:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+function getDelay(fullLayout) {
+    return (fullLayout._hasGL3D || fullLayout._hasGL2D) ? 500 : 0;
+}
+
+function getRedrawFunc(gd) {
+    return function() {
+        var fullLayout = gd._fullLayout;
+
+        // doesn't work presently (and not needed) for polar or gl
+        if(fullLayout._hasGL3D || fullLayout._hasGL2D ||
+            (gd.data && gd.data[0] && gd.data[0].r)
+        ) return;
+
+        (gd.calcdata || []).forEach(function(d) {
+            if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb();
+        });
+    };
+}
+
+var Snapshot = {
+    getDelay: getDelay,
+    getRedrawFunc: getRedrawFunc,
+    clone: require('./cloneplot'),
+    toSVG: require('./tosvg'),
+    svgToImg: require('./svgtoimg'),
+    toImage: require('./toimage')
+};
+
+module.exports = Snapshot;
+
+},{"./cloneplot":419,"./svgtoimg":421,"./toimage":422,"./tosvg":423}],421:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var EventEmitter = require('events').EventEmitter;
+
+function svgToImg(opts) {
+
+    var ev = opts.emitter ? opts.emitter : new EventEmitter();
+
+    var Image = window.Image;
+    var Blob = window.Blob;
+
+    var svg = opts.svg;
+    var format = opts.format || 'png';
+    var canvas = opts.canvas;
+
+    var ctx = canvas.getContext('2d');
+    var img = new Image();
+    var DOMURL = window.URL || window.webkitURL;
+    var svgBlob = new Blob([svg], {type: 'image/svg+xml;charset=utf-8'});
+    var url = DOMURL.createObjectURL(svgBlob);
+
+    canvas.height = opts.height || 150;
+    canvas.width = opts.width || 300;
+
+    img.onload = function() {
+        var imgData;
+
+        DOMURL.revokeObjectURL(url);
+        ctx.drawImage(img, 0, 0);
+
+        switch(format) {
+            case 'jpeg':
+                imgData = canvas.toDataURL('image/jpeg');
+                break;
+            case 'png':
+                imgData = canvas.toDataURL('image/png');
+                break;
+            case 'webp':
+                imgData = canvas.toDataURL('image/webp');
+                break;
+            case 'svg':
+                imgData = svg;
+                break;
+            default:
+                return ev.emit('error', 'Image format is not jpeg, png or svg');
+        }
+
+        ev.emit('success', imgData);
+    };
+
+    img.onerror = function(err) {
+        DOMURL.revokeObjectURL(url);
+        return ev.emit('error', err);
+    };
+
+    img.src = url;
+
+    return ev;
+}
+
+module.exports = svgToImg;
+
+},{"events":54}],422:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+/*eslint dot-notation: [2, {"allowPattern": "^catch$"}]*/
+
+'use strict';
+
+var EventEmitter = require('events').EventEmitter;
+var Plotly = require('../plotly');
+
+/**
+ * @param {object} gd figure Object
+ * @param {object} opts option object
+ * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg'
+ */
+function toImage(gd, opts) {
+
+    // first clone the GD so we can operate in a clean environment
+    var Snapshot = Plotly.Snapshot;
+    var ev = new EventEmitter();
+
+    var clone = Snapshot.clone(gd, {format: 'png'});
+    var clonedGd = clone.td;
+
+    // put the cloned div somewhere off screen before attaching to DOM
+    clonedGd.style.position = 'absolute';
+    clonedGd.style.left = '-5000px';
+    document.body.appendChild(clonedGd);
+
+    function wait() {
+        var delay = Snapshot.getDelay(clonedGd._fullLayout);
+
+        setTimeout(function() {
+            var svg = Plotly.Snapshot.toSVG(clonedGd);
+
+            var canvasContainer = window.document.createElement('div');
+            var canvas = window.document.createElement('canvas');
+
+            // window.document.body.appendChild(canvasContainer);
+            canvasContainer.appendChild(canvas);
+
+            canvasContainer.id = Plotly.Lib.randstr();
+            canvas.id = Plotly.Lib.randstr();
+
+            ev = Plotly.Snapshot.svgToImg({
+                format: opts.format,
+                width: clonedGd._fullLayout.width,
+                height: clonedGd._fullLayout.height,
+                canvas: canvas,
+                emitter: ev,
+                svg: svg
+            });
+
+            ev.clean = function() {
+                if(clonedGd) clonedGd.remove();
+            };
+
+        }, delay);
+    }
+
+    var redrawFunc = Snapshot.getRedrawFunc(clonedGd);
+
+    Plotly.plot(clonedGd, clone.data, clone.layout, clone.config)
+        // TODO: the following is Plotly.Plots.redrawText but without the waiting.
+        // we shouldn't need to do this, but in *occasional* cases we do. Figure
+        // out why and take it out.
+        .then(redrawFunc)
+        .then(wait)
+        .catch(function(err) {
+            ev.emit('error', err);
+        });
+
+
+    return ev;
+}
+
+module.exports = toImage;
+
+},{"../plotly":366,"events":54}],423:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plotly = require('../plotly');
+var d3 = require('d3');
+
+var xmlnsNamespaces = require('../constants/xmlns_namespaces');
+
+
+module.exports = function toSVG(gd, format) {
+
+    // make background color a rect in the svg, then revert after scraping
+    // all other alterations have been dealt with by properly preparing the svg
+    // in the first place... like setting cursors with css classes so we don't
+    // have to remove them, and providing the right namespaces in the svg to
+    // begin with
+    var fullLayout = gd._fullLayout,
+        svg = fullLayout._paper,
+        size = fullLayout._size,
+        domain,
+        i;
+
+    svg.insert('rect', ':first-child')
+        .call(Plotly.Drawing.setRect, 0, 0, fullLayout.width, fullLayout.height)
+        .call(Plotly.Color.fill, fullLayout.paper_bgcolor);
+
+    /* Grab the 3d scenes and rasterize em. Calculate their positions,
+     * then insert them into the SVG element as images */
+    var sceneIds = Plotly.Plots.getSubplotIds(fullLayout, 'gl3d'),
+        scene;
+
+    for(i = 0; i < sceneIds.length; i++) {
+        scene = fullLayout[sceneIds[i]];
+        domain = scene.domain;
+        insertGlImage(fullLayout, scene._scene, {
+            x: size.l + size.w * domain.x[0],
+            y: size.t + size.h * (1 - domain.y[1]),
+            width: size.w * (domain.x[1] - domain.x[0]),
+            height: size.h * (domain.y[1] - domain.y[0])
+        });
+    }
+
+    // similarly for 2d scenes
+    var subplotIds = Plotly.Plots.getSubplotIds(fullLayout, 'gl2d'),
+        subplot;
+
+    for(i = 0; i < subplotIds.length; i++) {
+        subplot = fullLayout._plots[subplotIds[i]];
+        insertGlImage(fullLayout, subplot._scene2d, {
+            x: size.l,
+            y: size.t,
+            width: size.w,
+            height: size.h
+        });
+    }
+
+    // Grab the geos off the geo-container and place them in geoimages
+    var geoIds = Plotly.Plots.getSubplotIds(fullLayout, 'geo'),
+        geoLayout,
+        geoFramework;
+
+    for(i = 0; i < geoIds.length; i++) {
+        geoLayout = fullLayout[geoIds[i]];
+        domain = geoLayout.domain;
+        geoFramework = geoLayout._geo.framework;
+
+        geoFramework.attr('style', null);
+        geoFramework
+            .attr({
+                x: size.l + size.w * domain.x[0] + geoLayout._marginX,
+                y: size.t + size.h * (1 - domain.y[1]) + geoLayout._marginY,
+                width: geoLayout._width,
+                height: geoLayout._height
+            });
+
+        fullLayout._geoimages.node()
+            .appendChild(geoFramework.node());
+    }
+
+    // now that we've got the 3d images in the right layer, add top items above them
+    // assumes everything in toppaper is a group, and if it's empty (like hoverlayer)
+    // we can ignore it
+    if(fullLayout._toppaper) {
+        var topGroups = fullLayout._toppaper.node().childNodes,
+            topGroup;
+        for(i = 0; i < topGroups.length; i++) {
+            topGroup = topGroups[i];
+            if(topGroup.childNodes.length) svg.node().appendChild(topGroup);
+        }
+    }
+
+    // in case the svg element had an explicit background color, remove this
+    // we want the rect to get the color so it's the right size; svg bg will
+    // fill whatever container it's displayed in regardless of plot size.
+    svg.node().style.background = '';
+
+    svg.selectAll('text')
+        .attr({'data-unformatted': null})
+        .style({
+            '-webkit-user-select': null,
+            '-moz-user-select': null,
+            '-ms-user-select': null
+        })
+        .each(function() {
+            // hidden text is pre-formatting mathjax, the browser ignores it but it can still confuse batik
+            var txt = d3.select(this);
+            if(txt.style('visibility') === 'hidden') {
+                txt.remove();
+                return;
+            }
+
+            // I've seen font-family styles with non-escaped double quotes in them - breaks the
+            // serialized svg because the style attribute itself is double-quoted!
+            // Is this an IE thing? Any other attributes or style elements that can have quotes in them?
+            // TODO: this looks like a noop right now - what happened to it?
+
+            /*
+             * Font-family styles with double quotes in them breaks the to-image
+             * step in FF42 because the style attribute itself is wrapped in
+             * double quotes. See:
+             *
+             * - http://codepen.io/etpinard/pen/bEdQWK
+             * - https://github.com/plotly/plotly.js/pull/104
+             *
+             * for more info.
+             */
+            var ff = txt.style('font-family');
+            if(ff && ff.indexOf('"') !== -1) {
+                txt.style('font-family', ff.replace(/"/g, '\\\''));
+            }
+        });
+
+    if(format === 'pdf' || format === 'eps') {
+        // these formats make the extra line MathJax adds around symbols look super thick in some cases
+        // it looks better if this is removed entirely.
+        svg.selectAll('#MathJax_SVG_glyphs path')
+            .attr('stroke-width', 0);
+    }
+
+    // fix for IE namespacing quirk?
+    // http://stackoverflow.com/questions/19610089/unwanted-namespaces-on-svg-markup-when-using-xmlserializer-in-javascript-with-ie
+    svg.node().setAttributeNS(xmlnsNamespaces.xmlns, 'xmlns', xmlnsNamespaces.svg);
+    svg.node().setAttributeNS(xmlnsNamespaces.xmlns, 'xmlns:xlink', xmlnsNamespaces.xlink);
+
+    var s = new window.XMLSerializer().serializeToString(svg.node());
+    s = Plotly.util.html_entity_decode(s);
+    s = Plotly.util.xml_entity_encode(s);
+
+    return s;
+};
+
+function insertGlImage(fullLayout, scene, opts) {
+    var imageData = scene.toImage('png');
+
+    fullLayout._glimages.append('svg:image')
+        .attr({
+            xmlns: xmlnsNamespaces.svg,
+            'xlink:href': imageData,
+            x: opts.x,
+            y: opts.y,
+            width: opts.width,
+            height: opts.height,
+            preserveAspectRatio: 'none'
+        });
+
+    scene.destroy();
+}
+
+},{"../constants/xmlns_namespaces":338,"../plotly":366,"d3":70}],424:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var mergeArray = require('../../lib').mergeArray;
+
+
+// arrayOk attributes, merge them into calcdata array
+module.exports = function arraysToCalcdata(cd) {
+    var trace = cd[0].trace,
+        marker = trace.marker,
+        markerLine = marker.line;
+
+    mergeArray(trace.text, cd, 'tx');
+    mergeArray(marker.opacity, cd, 'mo');
+    mergeArray(marker.color, cd, 'mc');
+    mergeArray(markerLine.color, cd, 'mlc');
+    mergeArray(markerLine.width, cd, 'mlw');
+};
+
+},{"../../lib":349}],425:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var scatterAttrs = require('../scatter/attributes'),
+    scatterMarkerAttrs = scatterAttrs.marker,
+    scatterMarkerLineAttrs = scatterMarkerAttrs.line;
+
+
+module.exports = {
+    x: scatterAttrs.x,
+    x0: scatterAttrs.x0,
+    dx: scatterAttrs.dx,
+    y: scatterAttrs.y,
+    y0: scatterAttrs.y0,
+    dy: scatterAttrs.dy,
+    text: scatterAttrs.text,
+    orientation: {
+        valType: 'enumerated',
+        
+        values: ['v', 'h'],
+        
+    },
+    marker: {
+        color: scatterMarkerAttrs.color,
+        colorscale: scatterMarkerAttrs.colorscale,
+        cauto: scatterMarkerAttrs.cauto,
+        cmax: scatterMarkerAttrs.cmax,
+        cmin: scatterMarkerAttrs.cmin,
+        autocolorscale: scatterMarkerAttrs.autocolorscale,
+        reversescale: scatterMarkerAttrs.reversescale,
+        showscale: scatterMarkerAttrs.showscale,
+        line: {
+            color: scatterMarkerLineAttrs.color,
+            colorscale: scatterMarkerLineAttrs.colorscale,
+            cauto: scatterMarkerLineAttrs.cauto,
+            cmax: scatterMarkerLineAttrs.cmax,
+            cmin: scatterMarkerLineAttrs.cmin,
+            width: scatterMarkerLineAttrs.width,
+            autocolorscale: scatterMarkerLineAttrs.autocolorscale,
+            reversescale: scatterMarkerLineAttrs.reversescale
+        }
+    },
+
+    r: scatterAttrs.r,
+    t: scatterAttrs.t,
+
+    _nestedModules: {  // nested module coupling
+        'error_y': 'ErrorBars',
+        'error_x': 'ErrorBars',
+        'marker.colorbar': 'Colorbar'
+    },
+
+    _deprecated: {
+        bardir: {
+            valType: 'enumerated',
+            
+            values: ['v', 'h'],
+            
+        }
+    }
+};
+
+},{"../scatter/attributes":502}],426:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Axes = require('../../plots/cartesian/axes');
+var hasColorscale = require('../../components/colorscale/has_colorscale');
+var colorscaleCalc = require('../../components/colorscale/calc');
+
+
+module.exports = function calc(gd, trace) {
+    // depending on bar direction, set position and size axes
+    // and data ranges
+    // note: this logic for choosing orientation is
+    // duplicated in graph_obj->setstyles
+
+    var xa = Axes.getFromId(gd, trace.xaxis||'x'),
+        ya = Axes.getFromId(gd, trace.yaxis||'y'),
+        orientation = trace.orientation || ((trace.x && !trace.y) ? 'h' : 'v'),
+        pos, size, i;
+
+    if(orientation==='h') {
+        size = xa.makeCalcdata(trace, 'x');
+        pos = ya.makeCalcdata(trace, 'y');
+    }
+    else {
+        size = ya.makeCalcdata(trace, 'y');
+        pos = xa.makeCalcdata(trace, 'x');
+    }
+
+    // create the "calculated data" to plot
+    var serieslen = Math.min(pos.length, size.length),
+        cd = [];
+    for(i=0; i<serieslen; i++) {
+        if((isNumeric(pos[i]) && isNumeric(size[i]))) {
+            cd.push({p: pos[i], s: size[i], b: 0});
+        }
+    }
+
+    // auto-z and autocolorscale if applicable
+    if(hasColorscale(trace, 'marker')) {
+        colorscaleCalc(trace, trace.marker.color, 'marker', 'c');
+    }
+    if(hasColorscale(trace, 'marker.line')) {
+        colorscaleCalc(trace, trace.marker.line.color, 'marker.line', 'c');
+    }
+
+    return cd;
+};
+
+},{"../../components/colorscale/calc":306,"../../components/colorscale/has_colorscale":311,"../../plots/cartesian/axes":369,"fast-isnumeric":74}],427:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+var Color = require('../../components/color');
+
+var handleXYDefaults = require('../scatter/xy_defaults');
+var handleStyleDefaults = require('../bar/style_defaults');
+var errorBarsSupplyDefaults = require('../../components/errorbars/defaults');
+var attributes = require('./attributes');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    var len = handleXYDefaults(traceIn, traceOut, coerce);
+    if(!len) {
+        traceOut.visible = false;
+        return;
+    }
+
+    coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v');
+    coerce('text');
+
+    handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);
+
+    // override defaultColor for error bars with defaultLine
+    errorBarsSupplyDefaults(traceIn, traceOut, Color.defaultLine, {axis: 'y'});
+    errorBarsSupplyDefaults(traceIn, traceOut, Color.defaultLine, {axis: 'x', inherit: 'y'});
+};
+
+},{"../../components/color":299,"../../components/errorbars/defaults":322,"../../lib":349,"../bar/style_defaults":435,"../scatter/xy_defaults":522,"./attributes":425}],428:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Fx = require('../../plots/cartesian/graph_interact');
+var ErrorBars = require('../../components/errorbars');
+var Color = require('../../components/color');
+
+
+module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
+    var cd = pointData.cd,
+        trace = cd[0].trace,
+        t = cd[0].t,
+        xa = pointData.xa,
+        ya = pointData.ya,
+        barDelta = (hovermode==='closest') ?
+            t.barwidth/2 : t.dbar*(1-xa._td._fullLayout.bargap)/2,
+        barPos;
+
+    if(hovermode!=='closest') barPos = function(di) { return di.p; };
+    else if(trace.orientation==='h') barPos = function(di) { return di.y; };
+    else barPos = function(di) { return di.x; };
+
+    var dx, dy;
+    if(trace.orientation==='h') {
+        dx = function(di) {
+            // add a gradient so hovering near the end of a
+            // bar makes it a little closer match
+            return Fx.inbox(di.b-xval, di.x-xval) + (di.x-xval)/(di.x-di.b);
+        };
+        dy = function(di) {
+            var centerPos = barPos(di) - yval;
+            return Fx.inbox(centerPos - barDelta, centerPos + barDelta);
+        };
+    }
+    else {
+        dy = function(di) {
+            return Fx.inbox(di.b-yval, di.y-yval) + (di.y-yval)/(di.y-di.b);
+        };
+        dx = function(di) {
+            var centerPos = barPos(di) - xval;
+            return Fx.inbox(centerPos - barDelta, centerPos + barDelta);
+        };
+    }
+
+    var distfn = Fx.getDistanceFunction(hovermode, dx, dy);
+    Fx.getClosest(cd, distfn, pointData);
+
+    // skip the rest (for this trace) if we didn't find a close point
+    if(pointData.index===false) return;
+
+    // the closest data point
+    var di = cd[pointData.index],
+        mc = di.mcc || trace.marker.color,
+        mlc = di.mlcc || trace.marker.line.color,
+        mlw = di.mlw || trace.marker.line.width;
+    if(Color.opacity(mc)) pointData.color = mc;
+    else if(Color.opacity(mlc) && mlw) pointData.color = mlc;
+
+    if(trace.orientation==='h') {
+        pointData.x0 = pointData.x1 = xa.c2p(di.x, true);
+        pointData.xLabelVal = di.s;
+
+        pointData.y0 = ya.c2p(barPos(di) - barDelta, true);
+        pointData.y1 = ya.c2p(barPos(di) + barDelta, true);
+        pointData.yLabelVal = di.p;
+    }
+    else {
+        pointData.y0 = pointData.y1 = ya.c2p(di.y,true);
+        pointData.yLabelVal = di.s;
+
+        pointData.x0 = xa.c2p(barPos(di) - barDelta, true);
+        pointData.x1 = xa.c2p(barPos(di) + barDelta, true);
+        pointData.xLabelVal = di.p;
+    }
+
+    if(di.tx) pointData.text = di.tx;
+
+    ErrorBars.hoverInfo(di, trace, pointData);
+
+    return [pointData];
+};
+
+},{"../../components/color":299,"../../components/errorbars":323,"../../plots/cartesian/graph_interact":374}],429:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Bar = {};
+
+Bar.attributes = require('./attributes');
+Bar.layoutAttributes = require('./layout_attributes');
+Bar.supplyDefaults = require('./defaults');
+Bar.supplyLayoutDefaults = require('./layout_defaults');
+Bar.calc = require('./calc');
+Bar.setPositions = require('./set_positions');
+Bar.colorbar = require('../scatter/colorbar');
+Bar.arraysToCalcdata = require('./arrays_to_calcdata');
+Bar.plot = require('./plot');
+Bar.style = require('./style');
+Bar.hoverPoints = require('./hover');
+
+Bar.moduleType = 'trace';
+Bar.name = 'bar';
+Bar.basePlotModule = require('../../plots/cartesian');
+Bar.categories = ['cartesian', 'bar', 'oriented', 'markerColorscale', 'errorBarsOK', 'showLegend'];
+Bar.meta = {
+    
+};
+
+module.exports = Bar;
+
+},{"../../plots/cartesian":375,"../scatter/colorbar":505,"./arrays_to_calcdata":424,"./attributes":425,"./calc":426,"./defaults":427,"./hover":428,"./layout_attributes":430,"./layout_defaults":431,"./plot":432,"./set_positions":433,"./style":434}],430:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+module.exports = {
+    barmode: {
+        valType: 'enumerated',
+        values: ['stack', 'group', 'overlay'],
+        dflt: 'group',
+        
+        
+    },
+    barnorm: {
+        valType: 'enumerated',
+        values: ['', 'fraction', 'percent'],
+        dflt: '',
+        
+        
+    },
+    bargap: {
+        valType: 'number',
+        min: 0,
+        max: 1,
+        
+        
+    },
+    bargroupgap: {
+        valType: 'number',
+        min: 0,
+        max: 1,
+        dflt: 0,
+        
+        
+    }
+};
+
+},{}],431:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Plots = require('../../plots/plots');
+var Axes = require('../../plots/cartesian/axes');
+var Lib = require('../../lib');
+
+var layoutAttributes = require('./layout_attributes');
+
+
+module.exports = function(layoutIn, layoutOut, fullData) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
+    }
+
+    var hasBars = false,
+        shouldBeGapless = false,
+        gappedAnyway = false,
+        usedSubplots = {};
+
+    for(var i = 0; i < fullData.length; i++) {
+        var trace = fullData[i];
+        if(Plots.traceIs(trace, 'bar')) hasBars = true;
+        else continue;
+
+        // if we have at least 2 grouped bar traces on the same subplot,
+        // we should default to a gap anyway, even if the data is histograms
+        if(layoutIn.barmode !== 'overlay' && layoutIn.barmode !== 'stack') {
+            var subploti = trace.xaxis + trace.yaxis;
+            if(usedSubplots[subploti]) gappedAnyway = true;
+            usedSubplots[subploti] = true;
+        }
+
+        if(trace.visible && trace.type === 'histogram') {
+            var pa = Axes.getFromId({_fullLayout: layoutOut},
+                        trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']);
+            if(pa.type !== 'category') shouldBeGapless = true;
+        }
+    }
+
+    if(!hasBars) return;
+
+    var mode = coerce('barmode');
+    if(mode !== 'overlay') coerce('barnorm');
+
+    coerce('bargap', (shouldBeGapless && !gappedAnyway) ? 0 : 0.2);
+    coerce('bargroupgap');
+};
+
+},{"../../lib":349,"../../plots/cartesian/axes":369,"../../plots/plots":413,"./layout_attributes":430}],432:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+var Color = require('../../components/color');
+
+var arraysToCalcdata = require('./arrays_to_calcdata');
+
+
+module.exports = function plot(gd, plotinfo, cdbar) {
+    var xa = plotinfo.x(),
+        ya = plotinfo.y(),
+        fullLayout = gd._fullLayout;
+
+    var bartraces = plotinfo.plot.select('.barlayer')
+        .selectAll('g.trace.bars')
+            .data(cdbar)
+      .enter().append('g')
+        .attr('class','trace bars');
+
+    bartraces.append('g')
+        .attr('class','points')
+        .each(function(d) {
+            var t = d[0].t,
+                trace = d[0].trace;
+
+            arraysToCalcdata(d);
+
+            d3.select(this).selectAll('path')
+                .data(Lib.identity)
+              .enter().append('path')
+                .each(function(di) {
+                    // now display the bar
+                    // clipped xf/yf (2nd arg true): non-positive
+                    // log values go off-screen by plotwidth
+                    // so you see them continue if you drag the plot
+                    var x0,x1,y0,y1;
+                    if(trace.orientation==='h') {
+                        y0 = ya.c2p(t.poffset+di.p, true);
+                        y1 = ya.c2p(t.poffset+di.p+t.barwidth, true);
+                        x0 = xa.c2p(di.b, true);
+                        x1 = xa.c2p(di.s+di.b, true);
+                    }
+                    else {
+                        x0 = xa.c2p(t.poffset+di.p, true);
+                        x1 = xa.c2p(t.poffset+di.p+t.barwidth, true);
+                        y1 = ya.c2p(di.s+di.b, true);
+                        y0 = ya.c2p(di.b, true);
+                    }
+
+                    if(!isNumeric(x0) || !isNumeric(x1) ||
+                            !isNumeric(y0) || !isNumeric(y1) ||
+                            x0===x1 || y0===y1) {
+                        d3.select(this).remove();
+                        return;
+                    }
+                    var lw = (di.mlw+1 || trace.marker.line.width+1 ||
+                            (di.trace ? di.trace.marker.line.width : 0)+1)-1,
+                        offset = d3.round((lw/2)%1,2);
+                    function roundWithLine(v) {
+                        // if there are explicit gaps, don't round,
+                        // it can make the gaps look crappy
+                        return (fullLayout.bargap===0 && fullLayout.bargroupgap===0) ?
+                            d3.round(Math.round(v)-offset, 2) : v;
+                    }
+                    function expandToVisible(v,vc) {
+                        // if it's not in danger of disappearing entirely,
+                        // round more precisely
+                        return Math.abs(v-vc)>=2 ? roundWithLine(v) :
+                        // but if it's very thin, expand it so it's
+                        // necessarily visible, even if it might overlap
+                        // its neighbor
+                        (v>vc ? Math.ceil(v) : Math.floor(v));
+                    }
+                    if(!gd._context.staticPlot) {
+                        // if bars are not fully opaque or they have a line
+                        // around them, round to integer pixels, mainly for
+                        // safari so we prevent overlaps from its expansive
+                        // pixelation. if the bars ARE fully opaque and have
+                        // no line, expand to a full pixel to make sure we
+                        // can see them
+                        var op = Color.opacity(di.mc || trace.marker.color),
+                            fixpx = (op<1 || lw>0.01) ?
+                                roundWithLine : expandToVisible;
+                        x0 = fixpx(x0,x1);
+                        x1 = fixpx(x1,x0);
+                        y0 = fixpx(y0,y1);
+                        y1 = fixpx(y1,y0);
+                    }
+                    d3.select(this).attr('d',
+                        'M'+x0+','+y0+'V'+y1+'H'+x1+'V'+y0+'Z');
+                });
+        });
+};
+
+},{"../../components/color":299,"../../lib":349,"./arrays_to_calcdata":424,"d3":70,"fast-isnumeric":74}],433:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Plots = require('../../plots/plots');
+var Axes = require('../../plots/cartesian/axes');
+var Lib = require('../../lib');
+
+/*
+ * Bar chart stacking/grouping positioning and autoscaling calculations
+ * for each direction separately calculate the ranges and positions
+ * note that this handles histograms too
+ * now doing this one subplot at a time
+ */
+
+module.exports = function setPositions(gd, plotinfo) {
+    var fullLayout = gd._fullLayout,
+        xa = plotinfo.x(),
+        ya = plotinfo.y(),
+        i, j;
+
+    ['v', 'h'].forEach(function(dir) {
+        var bl = [],
+            pLetter = {v: 'x', h: 'y'}[dir],
+            sLetter = {v: 'y', h: 'x'}[dir],
+            pa = plotinfo[pLetter](),
+            sa = plotinfo[sLetter]();
+
+        gd._fullData.forEach(function(trace,i) {
+            if(trace.visible === true &&
+                    Plots.traceIs(trace, 'bar') &&
+                    trace.orientation === dir &&
+                    trace.xaxis === xa._id &&
+                    trace.yaxis === ya._id) {
+                bl.push(i);
+            }
+        });
+
+        if(!bl.length) return;
+
+        // bar position offset and width calculation
+        // bl1 is a list of traces (in calcdata) to look at together
+        // to find the maximum size bars that won't overlap
+        // for stacked or grouped bars, this is all vertical or horizontal
+        // bars for overlaid bars, call this individually on each trace.
+        function barposition(bl1) {
+            // find the min. difference between any points
+            // in any traces in bl1
+            var pvals = [];
+            bl1.forEach(function(i) {
+                gd.calcdata[i].forEach(function(v) { pvals.push(v.p); });
+            });
+            var dv = Lib.distinctVals(pvals),
+                pv2 = dv.vals,
+                barDiff = dv.minDiff;
+
+            // check if all the traces have only independent positions
+            // if so, let them have full width even if mode is group
+            var overlap = false,
+                comparelist = [];
+
+            if(fullLayout.barmode === 'group') {
+                bl1.forEach(function(i) {
+                    if(overlap) return;
+                    gd.calcdata[i].forEach(function(v) {
+                        if(overlap) return;
+                        comparelist.forEach(function(cp) {
+                            if(Math.abs(v.p-cp) < barDiff) overlap = true;
+                        });
+                    });
+                    if(overlap) return;
+                    gd.calcdata[i].forEach(function(v) {
+                        comparelist.push(v.p);
+                    });
+                });
+            }
+
+            // check forced minimum dtick
+            Axes.minDtick(pa, barDiff, pv2[0], overlap);
+
+            // position axis autorange - always tight fitting
+            Axes.expand(pa, pv2, {vpad: barDiff / 2});
+
+            // bar widths and position offsets
+            barDiff *= 1 - fullLayout.bargap;
+            if(overlap) barDiff /= bl.length;
+
+            var barCenter;
+            function setBarCenter(v) { v[pLetter] = v.p + barCenter; }
+
+            for(var i = 0; i < bl1.length; i++) {
+                var t = gd.calcdata[bl1[i]][0].t;
+                t.barwidth = barDiff * (1 - fullLayout.bargroupgap);
+                t.poffset = ((overlap ? (2 * i + 1 - bl1.length) * barDiff : 0) -
+                    t.barwidth) / 2;
+                t.dbar = dv.minDiff;
+
+                // store the bar center in each calcdata item
+                barCenter = t.poffset + t.barwidth / 2;
+                gd.calcdata[bl1[i]].forEach(setBarCenter);
+            }
+        }
+
+        if(fullLayout.barmode === 'overlay') {
+            bl.forEach(function(bli) { barposition([bli]); });
+        }
+        else barposition(bl);
+
+        var stack = (fullLayout.barmode === 'stack'),
+            norm = fullLayout.barnorm;
+
+        // bar size range and stacking calculation
+        if(stack || norm) {
+            // for stacked bars, we need to evaluate every step in every
+            // stack, because negative bars mean the extremes could be
+            // anywhere
+            // also stores the base (b) of each bar in calcdata
+            // so we don't have to redo this later
+            var sMax = sa.l2c(sa.c2l(0)),
+                sMin = sMax,
+                sums={},
+
+                // make sure if p is different only by rounding,
+                // we still stack
+                sumround = gd.calcdata[bl[0]][0].t.barwidth / 100,
+                sv = 0,
+                padded = true,
+                barEnd,
+                ti,
+                scale;
+
+            for(i = 0; i < bl.length; i++) { // trace index
+                ti = gd.calcdata[bl[i]];
+                for(j = 0; j < ti.length; j++) {
+                    sv = Math.round(ti[j].p / sumround);
+                    var previousSum = sums[sv] || 0;
+                    if(stack) ti[j].b = previousSum;
+                    barEnd = ti[j].b + ti[j].s;
+                    sums[sv] = previousSum + ti[j].s;
+
+                    // store the bar top in each calcdata item
+                    if(stack) {
+                        ti[j][sLetter] = barEnd;
+                        if(!norm && isNumeric(sa.c2l(barEnd))) {
+                            sMax = Math.max(sMax,barEnd);
+                            sMin = Math.min(sMin,barEnd);
+                        }
+                    }
+                }
+            }
+
+            if(norm) {
+                padded = false;
+                var top = norm==='fraction' ? 1 : 100,
+                    tiny = top/1e9; // in case of rounding error in sum
+                sMin = 0;
+                sMax = stack ? top : 0;
+                for(i = 0; i < bl.length; i++) { // trace index
+                    ti = gd.calcdata[bl[i]];
+                    for(j = 0; j < ti.length; j++) {
+                        scale = top / sums[Math.round(ti[j].p/sumround)];
+                        ti[j].b *= scale;
+                        ti[j].s *= scale;
+                        barEnd = ti[j].b + ti[j].s;
+                        ti[j][sLetter] = barEnd;
+
+                        if(isNumeric(sa.c2l(barEnd))) {
+                            if(barEnd < sMin - tiny) {
+                                padded = true;
+                                sMin = barEnd;
+                            }
+                            if(barEnd > sMax + tiny) {
+                                padded = true;
+                                sMax = barEnd;
+                            }
+                        }
+                    }
+                }
+            }
+
+            Axes.expand(sa, [sMin, sMax], {tozero: true, padded: padded});
+        }
+        else {
+            // for grouped or overlaid bars, just make sure zero is
+            // included, along with the tops of each bar, and store
+            // these bar tops in calcdata
+            var fs = function(v) { v[sLetter] = v.s; return v.s; };
+
+            for(i = 0; i < bl.length; i++) {
+                Axes.expand(sa, gd.calcdata[bl[i]].map(fs),
+                    {tozero: true, padded: true});
+            }
+        }
+    });
+};
+
+},{"../../lib":349,"../../plots/cartesian/axes":369,"../../plots/plots":413,"fast-isnumeric":74}],434:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var Color = require('../../components/color');
+var Drawing = require('../../components/drawing');
+
+
+module.exports = function style(gd) {
+    var s = d3.select(gd).selectAll('g.trace.bars'),
+        barcount = s.size(),
+        fullLayout = gd._fullLayout;
+
+    // trace styling
+    s.style('opacity', function(d) { return d[0].trace.opacity; })
+
+    // for gapless (either stacked or neighboring grouped) bars use
+    // crispEdges to turn off antialiasing so an artificial gap
+    // isn't introduced.
+    .each(function(d) {
+        if((fullLayout.barmode==='stack' && barcount>1) ||
+                (fullLayout.bargap===0 &&
+                 fullLayout.bargroupgap===0 &&
+                 !d[0].trace.marker.line.width)) {
+            d3.select(this).attr('shape-rendering','crispEdges');
+        }
+    });
+
+    // then style the individual bars
+    s.selectAll('g.points').each(function(d) {
+        var trace = d[0].trace,
+            marker = trace.marker,
+            markerLine = marker.line,
+            markerIn = (trace._input||{}).marker||{},
+            markerScale = Drawing.tryColorscale(marker, markerIn, ''),
+            lineScale = Drawing.tryColorscale(marker, markerIn, 'line.');
+
+        d3.select(this).selectAll('path').each(function(d) {
+            // allow all marker and marker line colors to be scaled
+            // by given max and min to colorscales
+            var fillColor,
+                lineColor,
+                lineWidth = (d.mlw+1 || markerLine.width+1) - 1,
+                p = d3.select(this);
+
+            if('mc' in d) fillColor = d.mcc = markerScale(d.mc);
+            else if(Array.isArray(marker.color)) fillColor = Color.defaultLine;
+            else fillColor = marker.color;
+
+            p.style('stroke-width', lineWidth + 'px')
+                .call(Color.fill, fillColor);
+            if(lineWidth) {
+                if('mlc' in d) lineColor = d.mlcc = lineScale(d.mlc);
+                // weird case: array wasn't long enough to apply to every point
+                else if(Array.isArray(markerLine.color)) lineColor = Color.defaultLine;
+                else lineColor = markerLine.color;
+
+                p.call(Color.stroke, lineColor);
+            }
+        });
+        // TODO: text markers on bars, either extra text or just bar values
+        // d3.select(this).selectAll('text')
+        //     .call(Plotly.Drawing.textPointStyle,d.t||d[0].t);
+    });
+};
+
+},{"../../components/color":299,"../../components/drawing":317,"d3":70}],435:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Color = require('../../components/color');
+var hasColorscale = require('../../components/colorscale/has_colorscale');
+var colorscaleDefaults = require('../../components/colorscale/defaults');
+
+
+module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) {
+    coerce('marker.color', defaultColor);
+
+    if(hasColorscale(traceIn, 'marker')) {
+        colorscaleDefaults(
+            traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'}
+        );
+    }
+
+    coerce('marker.line.color', Color.defaultLine);
+
+    if(hasColorscale(traceIn, 'marker.line')) {
+        colorscaleDefaults(
+            traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'}
+        );
+    }
+
+    coerce('marker.line.width');
+};
+
+},{"../../components/color":299,"../../components/colorscale/defaults":308,"../../components/colorscale/has_colorscale":311}],436:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var scatterAttrs = require('../scatter/attributes');
+var colorAttrs = require('../../components/color/attributes');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+var scatterMarkerAttrs = scatterAttrs.marker,
+    scatterMarkerLineAttrs = scatterMarkerAttrs.line;
+
+
+module.exports = {
+    y: {
+        valType: 'data_array',
+        
+    },
+    x: {
+        valType: 'data_array',
+        
+    },
+    x0: {
+        valType: 'any',
+        
+        
+    },
+    y0: {
+        valType: 'any',
+        
+        
+    },
+    whiskerwidth: {
+        valType: 'number',
+        min: 0,
+        max: 1,
+        dflt: 0.5,
+        
+        
+    },
+    boxpoints: {
+        valType: 'enumerated',
+        values: ['all', 'outliers', 'suspectedoutliers', false],
+        dflt: 'outliers',
+        
+        
+    },
+    boxmean: {
+        valType: 'enumerated',
+        values: [true, 'sd', false],
+        dflt: false,
+        
+        
+    },
+    jitter: {
+        valType: 'number',
+        min: 0,
+        max: 1,
+        
+        
+    },
+    pointpos: {
+        valType: 'number',
+        min: -2,
+        max: 2,
+        
+        
+    },
+    orientation: {
+        valType: 'enumerated',
+        values: ['v', 'h'],
+        
+        
+    },
+    marker: {
+        outliercolor: {
+            valType: 'color',
+            dflt: 'rgba(0, 0, 0, 0)',
+            
+            
+        },
+        symbol: extendFlat({}, scatterMarkerAttrs.symbol,
+            {arrayOk: false}),
+        opacity: extendFlat({}, scatterMarkerAttrs.opacity,
+            {arrayOk: false, dflt: 1}),
+        size: extendFlat({}, scatterMarkerAttrs.size,
+            {arrayOk: false}),
+        color: extendFlat({}, scatterMarkerAttrs.color,
+            {arrayOk: false}),
+        line: {
+            color: extendFlat({}, scatterMarkerLineAttrs.color,
+                {arrayOk: false, dflt: colorAttrs.defaultLine}),
+            width: extendFlat({}, scatterMarkerLineAttrs.width,
+                {arrayOk: false, dflt: 0}),
+            outliercolor: {
+                valType: 'color',
+                
+                
+            },
+            outlierwidth: {
+                valType: 'number',
+                min: 0,
+                dflt: 1,
+                
+                
+            }
+        }
+    },
+    line: {
+        color: {
+            valType: 'color',
+            
+            
+        },
+        width: {
+            valType: 'number',
+            
+            min: 0,
+            dflt: 2,
+            
+        }
+    },
+    fillcolor: scatterAttrs.fillcolor
+};
+
+},{"../../components/color/attributes":298,"../../lib/extend":345,"../scatter/attributes":502}],437:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+var Axes = require('../../plots/cartesian/axes');
+
+
+// outlier definition based on http://www.physics.csbsju.edu/stats/box2.html
+module.exports = function calc(gd, trace) {
+    var xa = Axes.getFromId(gd, trace.xaxis || 'x'),
+        ya = Axes.getFromId(gd, trace.yaxis || 'y'),
+        orientation = trace.orientation,
+        cd = [],
+        valAxis, valLetter, val, valBinned,
+        posAxis, posLetter, pos, posDistinct, dPos;
+
+    // Set value (val) and position (pos) keys via orientation
+    if(orientation==='h') {
+        valAxis = xa;
+        valLetter = 'x';
+        posAxis = ya;
+        posLetter = 'y';
+    } else {
+        valAxis = ya;
+        valLetter = 'y';
+        posAxis = xa;
+        posLetter = 'x';
+    }
+
+    val = valAxis.makeCalcdata(trace, valLetter);  // get val
+
+    // size autorange based on all source points
+    // position happens afterward when we know all the pos
+    Axes.expand(valAxis, val, {padded: true});
+
+    // In vertical (horizontal) box plots:
+    // if no x (y) data, use x0 (y0), or name
+    // so if you want one box
+    // per trace, set x0 (y0) to the x (y) value or category for this trace
+    // (or set x (y) to a constant array matching y (x))
+    function getPos(gd, trace, posLetter, posAxis, val) {
+        var pos0;
+        if(posLetter in trace) pos = posAxis.makeCalcdata(trace, posLetter);
+        else {
+            if(posLetter+'0' in trace) pos0 = trace[posLetter+'0'];
+            else if('name' in trace && (
+                        posAxis.type==='category' ||
+                        (isNumeric(trace.name) &&
+                            ['linear','log'].indexOf(posAxis.type)!==-1) ||
+                        (Lib.isDateTime(trace.name) &&
+                         posAxis.type==='date')
+                    )) {
+                pos0 = trace.name;
+            }
+            else pos0 = gd.numboxes;
+            pos0 = posAxis.d2c(pos0);
+            pos = val.map(function() { return pos0; });
+        }
+        return pos;
+    }
+
+    pos = getPos(gd, trace, posLetter, posAxis, val);
+
+    // get distinct positions and min difference
+    var dv = Lib.distinctVals(pos);
+    posDistinct = dv.vals;
+    dPos = dv.minDiff/2;
+
+    function binVal(cd, val, pos, posDistinct, dPos) {
+        var posDistinctLength = posDistinct.length,
+            valLength = val.length,
+            valBinned = [],
+            bins = [],
+            i, p, n, v;
+
+        // store distinct pos in cd, find bins, init. valBinned
+        for(i = 0; i < posDistinctLength; ++i) {
+            p = posDistinct[i];
+            cd[i] = {pos: p};
+            bins[i] = p - dPos;
+            valBinned[i] = [];
+        }
+        bins.push(posDistinct[posDistinctLength-1] + dPos);
+
+        // bin the values
+        for(i = 0; i < valLength; ++i) {
+            v = val[i];
+            if(!isNumeric(v)) continue;
+            n = Lib.findBin(pos[i], bins);
+            if(n>=0 && n<valLength) valBinned[n].push(v);
+        }
+
+        return valBinned;
+    }
+
+    valBinned = binVal(cd, val, pos, posDistinct, dPos);
+
+    // sort the bins and calculate the stats
+    function calculateStats(cd, valBinned) {
+        var v, l, cdi, i;
+
+        for(i = 0; i < valBinned.length; ++i) {
+            v = valBinned[i].sort(Lib.sorterAsc);
+            l = v.length;
+            cdi = cd[i];
+
+            cdi.val = v;  // put all values into calcdata
+            cdi.min = v[0];
+            cdi.max = v[l-1];
+            cdi.mean = Lib.mean(v,l);
+            cdi.sd = Lib.stdev(v,l,cdi.mean);
+            cdi.q1 = Lib.interp(v, 0.25);  // first quartile
+            cdi.med = Lib.interp(v, 0.5);  // median
+            cdi.q3 = Lib.interp(v, 0.75);  // third quartile
+            // lower and upper fences - last point inside
+            // 1.5 interquartile ranges from quartiles
+            cdi.lf = Math.min(cdi.q1, v[
+                Math.min(Lib.findBin(2.5*cdi.q1-1.5*cdi.q3,v,true)+1, l-1)]);
+            cdi.uf = Math.max(cdi.q3,v[
+                Math.max(Lib.findBin(2.5*cdi.q3-1.5*cdi.q1,v), 0)]);
+            // lower and upper outliers - 3 IQR out (don't clip to max/min,
+            // this is only for discriminating suspected & far outliers)
+            cdi.lo = 4*cdi.q1-3*cdi.q3;
+            cdi.uo = 4*cdi.q3-3*cdi.q1;
+        }
+    }
+
+    calculateStats(cd, valBinned);
+
+    // remove empty bins
+    cd = cd.filter(function(cdi) { return cdi.val && cdi.val.length; });
+    if(!cd.length) return [{t: {emptybox: true}}];
+
+    // add numboxes and dPos to cd
+    cd[0].t = {boxnum: gd.numboxes, dPos: dPos};
+    gd.numboxes++;
+    return cd;
+};
+
+},{"../../lib":349,"../../plots/cartesian/axes":369,"fast-isnumeric":74}],438:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Lib = require('../../lib');
+var Color = require('../../components/color');
+
+var attributes = require('./attributes');
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    var y = coerce('y'),
+        x = coerce('x'),
+        defaultOrientation;
+
+    if(y && y.length) {
+        defaultOrientation = 'v';
+        if(!x) coerce('x0');
+    } else if(x && x.length) {
+        defaultOrientation = 'h';
+        coerce('y0');
+    } else {
+        traceOut.visible = false;
+        return;
+    }
+
+    coerce('orientation', defaultOrientation);
+
+    coerce('line.color', (traceIn.marker||{}).color || defaultColor);
+    coerce('line.width', 2);
+    coerce('fillcolor', Color.addOpacity(traceOut.line.color, 0.5));
+
+    coerce('whiskerwidth');
+    coerce('boxmean');
+
+    var outlierColorDflt = Lib.coerce2(traceIn, traceOut, attributes, 'marker.outliercolor'),
+        lineoutliercolor = coerce('marker.line.outliercolor'),
+        boxpoints = outlierColorDflt ||
+                    lineoutliercolor ? coerce('boxpoints', 'suspectedoutliers') :
+                    coerce('boxpoints');
+
+    if(boxpoints) {
+        coerce('jitter', boxpoints==='all' ? 0.3 : 0);
+        coerce('pointpos', boxpoints==='all' ? -1.5 : 0);
+
+        coerce('marker.symbol');
+        coerce('marker.opacity');
+        coerce('marker.size');
+        coerce('marker.color', traceOut.line.color);
+        coerce('marker.line.color');
+        coerce('marker.line.width');
+
+        if(boxpoints==='suspectedoutliers') {
+            coerce('marker.line.outliercolor', traceOut.marker.color);
+            coerce('marker.line.outlierwidth');
+        }
+    }
+};
+
+},{"../../components/color":299,"../../lib":349,"./attributes":436}],439:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Axes = require('../../plots/cartesian/axes');
+var Fx = require('../../plots/cartesian/graph_interact');
+var Lib = require('../../lib');
+var Color = require('../../components/color');
+
+module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
+    // closest mode: handicap box plots a little relative to others
+    var cd = pointData.cd,
+        trace = cd[0].trace,
+        t = cd[0].t,
+        xa = pointData.xa,
+        ya = pointData.ya,
+        closeData = [],
+        dx, dy, distfn, boxDelta,
+        posLetter, posAxis,
+        val, valLetter, valAxis;
+
+    // adjust inbox w.r.t. to calculate box size
+    boxDelta = (hovermode==='closest') ? 2.5*t.bdPos : t.bdPos;
+
+    if(trace.orientation === 'h') {
+        dx = function(di) {
+            return Fx.inbox(di.min - xval, di.max - xval);
+        };
+        dy = function(di) {
+            var pos = di.pos + t.bPos - yval;
+            return Fx.inbox(pos - boxDelta, pos + boxDelta);
+        };
+        posLetter = 'y';
+        posAxis = ya;
+        valLetter = 'x';
+        valAxis = xa;
+    } else {
+        dx = function(di) {
+            var pos = di.pos + t.bPos - xval;
+            return Fx.inbox(pos - boxDelta, pos + boxDelta);
+        };
+        dy = function(di) {
+            return Fx.inbox(di.min - yval, di.max - yval);
+        };
+        posLetter = 'x';
+        posAxis = xa;
+        valLetter = 'y';
+        valAxis = ya;
+    }
+
+    distfn = Fx.getDistanceFunction(hovermode, dx, dy);
+    Fx.getClosest(cd, distfn, pointData);
+
+    // skip the rest (for this trace) if we didn't find a close point
+    if(pointData.index===false) return;
+
+    // create the item(s) in closedata for this point
+
+    // the closest data point
+    var di = cd[pointData.index],
+        lc = trace.line.color,
+        mc = (trace.marker||{}).color;
+    if(Color.opacity(lc) && trace.line.width) pointData.color = lc;
+    else if(Color.opacity(mc) && trace.boxpoints) pointData.color = mc;
+    else pointData.color = trace.fillcolor;
+
+    pointData[posLetter+'0'] = posAxis.c2p(di.pos + t.bPos - t.bdPos, true);
+    pointData[posLetter+'1'] = posAxis.c2p(di.pos + t.bPos + t.bdPos, true);
+
+    Axes.tickText(posAxis, posAxis.c2l(di.pos), 'hover').text;
+    pointData[posLetter+'LabelVal'] = di.pos;
+
+    // box plots: each "point" gets many labels
+    var usedVals = {},
+        attrs = ['med','min','q1','q3','max'],
+        attr,
+        pointData2;
+    if(trace.boxmean) attrs.push('mean');
+    if(trace.boxpoints) [].push.apply(attrs,['lf', 'uf']);
+
+    for(var i = 0; i < attrs.length; i++) {
+        attr = attrs[i];
+
+        if(!(attr in di) || (di[attr] in usedVals)) continue;
+        usedVals[di[attr]] = true;
+
+        // copy out to a new object for each value to label
+        val = valAxis.c2p(di[attr], true);
+        pointData2 = Lib.extendFlat({}, pointData);
+        pointData2[valLetter+'0'] = pointData2[valLetter+'1'] = val;
+        pointData2[valLetter+'LabelVal'] = di[attr];
+        pointData2.attr = attr;
+
+        if(attr==='mean' && ('sd' in di) && trace.boxmean==='sd') {
+            pointData2[valLetter+'err'] = di.sd;
+        }
+        pointData.name = ''; // only keep name on the first item (median)
+        closeData.push(pointData2);
+    }
+    return closeData;
+};
+
+},{"../../components/color":299,"../../lib":349,"../../plots/cartesian/axes":369,"../../plots/cartesian/graph_interact":374}],440:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Box = {};
+
+Box.attributes = require('./attributes');
+Box.layoutAttributes = require('./layout_attributes');
+Box.supplyDefaults = require('./defaults');
+Box.supplyLayoutDefaults = require('./layout_defaults');
+Box.calc = require('./calc');
+Box.setPositions = require('./set_positions');
+Box.plot = require('./plot');
+Box.style = require('./style');
+Box.hoverPoints = require('./hover');
+
+Box.moduleType = 'trace';
+Box.name = 'box';
+Box.basePlotModule = require('../../plots/cartesian');
+Box.categories = ['cartesian', 'symbols', 'oriented', 'box', 'showLegend'];
+Box.meta = {
+    
+};
+
+module.exports = Box;
+
+},{"../../plots/cartesian":375,"./attributes":436,"./calc":437,"./defaults":438,"./hover":439,"./layout_attributes":441,"./layout_defaults":442,"./plot":443,"./set_positions":444,"./style":445}],441:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+
+module.exports = {
+    boxmode: {
+        valType: 'enumerated',
+        values: ['group', 'overlay'],
+        dflt: 'overlay',
+        
+        
+    },
+    boxgap: {
+        valType: 'number',
+        min: 0,
+        max: 1,
+        dflt: 0.3,
+        
+        
+    },
+    boxgroupgap: {
+        valType: 'number',
+        min: 0,
+        max: 1,
+        dflt: 0.3,
+        
+        
+    }
+};
+
+},{}],442:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Plots = require('../../plots/plots');
+var Lib = require('../../lib');
+var layoutAttributes = require('./layout_attributes');
+
+module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
+    }
+
+    var hasBoxes;
+    for(var i = 0; i < fullData.length; i++) {
+        if(Plots.traceIs(fullData[i], 'box')) {
+            hasBoxes = true;
+            break;
+        }
+    }
+    if(!hasBoxes) return;
+
+    coerce('boxmode');
+    coerce('boxgap');
+    coerce('boxgroupgap');
+};
+
+},{"../../lib":349,"../../plots/plots":413,"./layout_attributes":441}],443:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var d3 = require('d3');
+
+var Lib = require('../../lib');
+var Drawing = require('../../components/drawing');
+
+
+// repeatable pseudorandom generator
+var randSeed = 2000000000;
+
+function seed() {
+    randSeed = 2000000000;
+}
+
+function rand() {
+    var lastVal = randSeed;
+    randSeed = (69069*randSeed + 1)%4294967296;
+    // don't let consecutive vals be too close together
+    // gets away from really trying to be random, in favor of better local uniformity
+    if(Math.abs(randSeed - lastVal) < 429496729) return rand();
+    return randSeed/4294967296;
+}
+
+// constants for dynamic jitter (ie less jitter for sparser points)
+var JITTERCOUNT = 5, // points either side of this to include
+    JITTERSPREAD = 0.01; // fraction of IQR to count as "dense"
+
+
+module.exports = function plot(gd, plotinfo, cdbox) {
+    var fullLayout = gd._fullLayout,
+        xa = plotinfo.x(),
+        ya = plotinfo.y(),
+        posAxis, valAxis;
+
+    var boxtraces = plotinfo.plot.select('.boxlayer')
+        .selectAll('g.trace.boxes')
+            .data(cdbox)
+      .enter().append('g')
+        .attr('class','trace boxes');
+
+    boxtraces.each(function(d) {
+        var t = d[0].t,
+            trace = d[0].trace,
+            group = (fullLayout.boxmode==='group' && gd.numboxes>1),
+            // box half width
+            bdPos = t.dPos*(1-fullLayout.boxgap)*(1-fullLayout.boxgroupgap)/(group ? gd.numboxes : 1),
+            // box center offset
+            bPos = group ? 2*t.dPos*(-0.5+(t.boxnum+0.5)/gd.numboxes)*(1-fullLayout.boxgap) : 0,
+            // whisker width
+            wdPos = bdPos*trace.whiskerwidth;
+        if(trace.visible !== true || t.emptybox) {
+            d3.select(this).remove();
+            return;
+        }
+
+        // set axis via orientation
+        if(trace.orientation==='h') {
+            posAxis = ya;
+            valAxis = xa;
+        } else {
+            posAxis = xa;
+            valAxis = ya;
+        }
+
+        // save the box size and box position for use by hover
+        t.bPos = bPos;
+        t.bdPos = bdPos;
+
+        // repeatable pseudorandom number generator
+        seed();
+
+        // boxes and whiskers
+        d3.select(this).selectAll('path.box')
+            .data(Lib.identity)
+            .enter().append('path')
+            .attr('class','box')
+            .each(function(d) {
+                var posc = posAxis.c2p(d.pos + bPos, true),
+                    pos0 = posAxis.c2p(d.pos + bPos - bdPos, true),
+                    pos1 = posAxis.c2p(d.pos + bPos + bdPos, true),
+                    posw0 = posAxis.c2p(d.pos + bPos - wdPos, true),
+                    posw1 = posAxis.c2p(d.pos + bPos + wdPos, true),
+                    q1 = valAxis.c2p(d.q1, true),
+                    q3 = valAxis.c2p(d.q3, true),
+                    // make sure median isn't identical to either of the
+                    // quartiles, so we can see it
+                    m = Lib.constrain(valAxis.c2p(d.med, true),
+                        Math.min(q1, q3)+1, Math.max(q1, q3)-1),
+                    lf = valAxis.c2p(trace.boxpoints===false ? d.min : d.lf, true),
+                    uf = valAxis.c2p(trace.boxpoints===false ? d.max : d.uf, true);
+                if(trace.orientation === 'h') {
+                    d3.select(this).attr('d',
+                        'M'+m+','+pos0+'V'+pos1+ // median line
+                        'M'+q1+','+pos0+'V'+pos1+'H'+q3+'V'+pos0+'Z'+ // box
+                        'M'+q1+','+posc+'H'+lf+'M'+q3+','+posc+'H'+uf+ // whiskers
+                        ((trace.whiskerwidth===0) ? '' : // whisker caps
+                            'M'+lf+','+posw0+'V'+posw1+'M'+uf+','+posw0+'V'+posw1));
+                } else {
+                    d3.select(this).attr('d',
+                        'M'+pos0+','+m+'H'+pos1+ // median line
+                        'M'+pos0+','+q1+'H'+pos1+'V'+q3+'H'+pos0+'Z'+ // box
+                        'M'+posc+','+q1+'V'+lf+'M'+posc+','+q3+'V'+uf+ // whiskers
+                        ((trace.whiskerwidth===0) ? '' : // whisker caps
+                            'M'+posw0+','+lf+'H'+posw1+'M'+posw0+','+uf+'H'+posw1));
+                }
+            });
+
+        // draw points, if desired
+        if(trace.boxpoints) {
+            d3.select(this).selectAll('g.points')
+                // since box plot points get an extra level of nesting, each
+                // box needs the trace styling info
+                .data(function(d) {
+                    d.forEach(function(v) {
+                        v.t = t;
+                        v.trace = trace;
+                    });
+                    return d;
+                })
+                .enter().append('g')
+                .attr('class','points')
+              .selectAll('path')
+                .data(function(d) {
+                    var pts = (trace.boxpoints==='all') ? d.val :
+                            d.val.filter(function(v) { return (v<d.lf || v>d.uf); }),
+                        spreadLimit = (d.q3 - d.q1) * JITTERSPREAD,
+                        jitterFactors = [],
+                        maxJitterFactor = 0,
+                        i,
+                        i0, i1,
+                        pmin,
+                        pmax,
+                        jitterFactor,
+                        newJitter;
+
+                    // dynamic jitter
+                    if(trace.jitter) {
+                        for(i=0; i<pts.length; i++) {
+                            i0 = Math.max(0, i-JITTERCOUNT);
+                            pmin = pts[i0];
+                            i1 = Math.min(pts.length-1, i+JITTERCOUNT);
+                            pmax = pts[i1];
+
+                            if(trace.boxpoints!=='all') {
+                                if(pts[i]<d.lf) pmax = Math.min(pmax, d.lf);
+                                else pmin = Math.max(pmin, d.uf);
+                            }
+
+                            jitterFactor = Math.sqrt(spreadLimit * (i1-i0) / (pmax-pmin)) || 0;
+                            jitterFactor = Lib.constrain(Math.abs(jitterFactor), 0, 1);
+
+                            jitterFactors.push(jitterFactor);
+                            maxJitterFactor = Math.max(jitterFactor, maxJitterFactor);
+                        }
+                        newJitter = trace.jitter * 2 / maxJitterFactor;
+                    }
+
+                    return pts.map(function(v, i) {
+                        var posOffset = trace.pointpos,
+                            p;
+                        if(trace.jitter) {
+                            posOffset += newJitter * jitterFactors[i] * (rand()-0.5);
+                        }
+
+                        if(trace.orientation === 'h') {
+                            p = {
+                                y: d.pos + posOffset*bdPos + bPos,
+                                x: v
+                            };
+                        } else {
+                            p = {
+                                x: d.pos + posOffset*bdPos + bPos,
+                                y: v
+                            };
+                        }
+
+                        // tag suspected outliers
+                        if(trace.boxpoints==='suspectedoutliers' && v<d.uo && v>d.lo) {
+                            p.so=true;
+                        }
+                        return p;
+                    });
+                })
+                .enter().append('path')
+                .call(Drawing.translatePoints, xa, ya);
+        }
+        // draw mean (and stdev diamond) if desired
+        if(trace.boxmean) {
+            d3.select(this).selectAll('path.mean')
+                .data(Lib.identity)
+                .enter().append('path')
+                .attr('class','mean')
+                .style('fill','none')
+                .each(function(d) {
+                    var posc = posAxis.c2p(d.pos + bPos, true),
+                        pos0 = posAxis.c2p(d.pos + bPos - bdPos, true),
+                        pos1 = posAxis.c2p(d.pos + bPos + bdPos, true),
+                        m = valAxis.c2p(d.mean, true),
+                        sl = valAxis.c2p(d.mean-d.sd, true),
+                        sh = valAxis.c2p(d.mean+d.sd, true);
+                    if(trace.orientation==='h') {
+                        d3.select(this).attr('d',
+                            'M'+m+','+pos0+'V'+pos1+
+                            ((trace.boxmean!=='sd') ? '' :
+                                'm0,0L'+sl+','+posc+'L'+m+','+pos0+'L'+sh+','+posc+'Z'));
+                    }
+                    else {
+                        d3.select(this).attr('d',
+                            'M'+pos0+','+m+'H'+pos1+
+                            ((trace.boxmean!=='sd') ? '' :
+                                'm0,0L'+posc+','+sl+'L'+pos0+','+m+'L'+posc+','+sh+'Z'));
+                    }
+                });
+        }
+    });
+};
+
+},{"../../components/drawing":317,"../../lib":349,"d3":70}],444:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Plots = require('../../plots/plots');
+var Axes = require('../../plots/cartesian/axes');
+var Lib = require('../../lib');
+
+
+module.exports = function setPositions(gd, plotinfo) {
+    var fullLayout = gd._fullLayout,
+        xa = plotinfo.x(),
+        ya = plotinfo.y(),
+        orientations = ['v', 'h'];
+    var posAxis, i, j, k;
+
+    for(i = 0; i < orientations.length; ++i) {
+        var orientation = orientations[i],
+            boxlist = [],
+            boxpointlist = [],
+            minPad = 0,
+            maxPad = 0,
+            cd,
+            t,
+            trace;
+
+        // set axis via orientation
+        if(orientation === 'h') posAxis = ya;
+        else posAxis = xa;
+
+        // make list of boxes
+        for(j = 0; j < gd.calcdata.length; ++j) {
+            cd = gd.calcdata[j];
+            t = cd[0].t;
+            trace = cd[0].trace;
+
+            if(trace.visible === true && Plots.traceIs(trace, 'box') &&
+                    !t.emptybox &&
+                    trace.orientation === orientation &&
+                    trace.xaxis === xa._id &&
+                    trace.yaxis === ya._id) {
+                boxlist.push(j);
+                if(trace.boxpoints !== false) {
+                    minPad = Math.max(minPad, trace.jitter-trace.pointpos-1);
+                    maxPad = Math.max(maxPad, trace.jitter+trace.pointpos-1);
+                }
+            }
+        }
+
+        // make list of box points
+        for(j = 0; j < boxlist.length; j++) {
+            cd = gd.calcdata[boxlist[j]];
+            for(k = 0; k < cd.length; k++) boxpointlist.push(cd[k].pos);
+        }
+        if(!boxpointlist.length) continue;
+
+        // box plots - update dPos based on multiple traces
+        // and then use for posAxis autorange
+
+        var boxdv = Lib.distinctVals(boxpointlist),
+            dPos = boxdv.minDiff/2;
+
+        // if there's no duplication of x points,
+        // disable 'group' mode by setting numboxes=1
+        if(boxpointlist.length===boxdv.vals.length) gd.numboxes = 1;
+
+        // check for forced minimum dtick
+        Axes.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true);
+
+        // set the width of all boxes
+        for(i = 0; i < boxlist.length; ++i) {
+            gd.calcdata[i][0].t.dPos = dPos;
+        }
+
+        // autoscale the x axis - including space for points if they're off the side
+        // TODO: this will overdo it if the outermost boxes don't have
+        // their points as far out as the other boxes
+        var padfactor = (1-fullLayout.boxgap) * (1-fullLayout.boxgroupgap) *
+                dPos / gd.numboxes;
+        Axes.expand(posAxis, boxdv.vals, {
+            vpadminus: dPos+minPad*padfactor,
+            vpadplus: dPos+maxPad*padfactor
+        });
+    }
+};
+
+},{"../../lib":349,"../../plots/cartesian/axes":369,"../../plots/plots":413}],445:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var d3 = require('d3');
+
+var Color = require('../../components/color');
+var Drawing = require('../../components/drawing');
+
+
+module.exports = function style(gd) {
+    var s = d3.select(gd).selectAll('g.trace.boxes');
+
+    s.style('opacity', function(d) { return d[0].trace.opacity; })
+        .each(function(d) {
+            var trace = d[0].trace,
+                lineWidth = trace.line.width;
+            d3.select(this).selectAll('path.box')
+                .style('stroke-width', lineWidth+'px')
+                .call(Color.stroke, trace.line.color)
+                .call(Color.fill, trace.fillcolor);
+            d3.select(this).selectAll('path.mean')
+                .style({
+                    'stroke-width': lineWidth,
+                    'stroke-dasharray': (2*lineWidth)+'px,'+lineWidth+'px'
+                })
+                .call(Color.stroke, trace.line.color);
+            d3.select(this).selectAll('g.points path')
+                .call(Drawing.pointStyle, trace);
+        });
+};
+
+},{"../../components/color":299,"../../components/drawing":317,"d3":70}],446:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var ScatterGeoAttrs = require('../scattergeo/attributes');
+var colorscaleAttrs = require('../../components/colorscale/attributes');
+var plotAttrs = require('../../plots/attributes');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+var ScatterGeoMarkerLineAttrs = ScatterGeoAttrs.marker.line;
+
+module.exports = {
+    locations: {
+        valType: 'data_array',
+        
+    },
+    locationmode: ScatterGeoAttrs.locationmode,
+    z: {
+        valType: 'data_array',
+        
+    },
+    text: {
+        valType: 'data_array',
+        
+    },
+    marker: {
+        line: {
+            color: ScatterGeoMarkerLineAttrs.color,
+            width: ScatterGeoMarkerLineAttrs.width
+        }
+    },
+    zauto: colorscaleAttrs.zauto,
+    zmin: colorscaleAttrs.zmin,
+    zmax: colorscaleAttrs.zmax,
+    colorscale: colorscaleAttrs.colorscale,
+    autocolorscale: colorscaleAttrs.autocolorscale,
+    reversescale: colorscaleAttrs.reversescale,
+    showscale: colorscaleAttrs.showscale,
+    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
+        flags: ['location', 'z', 'text', 'name']
+    }),
+    _nestedModules: {
+        'colorbar': 'Colorbar'
+    }
+};
+
+},{"../../components/colorscale/attributes":305,"../../lib/extend":345,"../../plots/attributes":367,"../scattergeo/attributes":529}],447:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var colorscaleDefaults = require('../../components/colorscale/defaults');
+var attributes = require('./attributes');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    var locations = coerce('locations');
+
+    var len;
+    if(locations) len = locations.length;
+
+    if(!locations || !len) {
+        traceOut.visible = false;
+        return;
+    }
+
+    var z = coerce('z');
+    if(!Array.isArray(z)) {
+        traceOut.visible = false;
+        return;
+    }
+
+    if(z.length > len) traceOut.z = z.slice(0, len);
+
+    coerce('locationmode');
+
+    coerce('text');
+
+    coerce('marker.line.color');
+    coerce('marker.line.width');
+
+    colorscaleDefaults(
+        traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
+    );
+
+    coerce('hoverinfo', (layout._dataLength === 1) ? 'location+z+text' : undefined);
+};
+
+},{"../../components/colorscale/defaults":308,"../../lib":349,"./attributes":446}],448:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Choropleth = {};
+
+Choropleth.attributes = require('./attributes');
+Choropleth.supplyDefaults = require('./defaults');
+Choropleth.colorbar = require('../heatmap/colorbar');
+Choropleth.calc = require('../surface/calc');
+Choropleth.plot = require('./plot').plot;
+
+Choropleth.moduleType = 'trace';
+Choropleth.name = 'choropleth';
+Choropleth.basePlotModule = require('../../plots/geo');
+Choropleth.categories = ['geo', 'noOpacity'];
+Choropleth.meta = {
+    
+};
+
+module.exports = Choropleth;
+
+},{"../../plots/geo":385,"../heatmap/colorbar":461,"../surface/calc":539,"./attributes":446,"./defaults":447,"./plot":449}],449:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var Axes = require('../../plots/cartesian/axes');
+var Fx = require('../../plots/cartesian/graph_interact');
+var Color = require('../../components/color');
+var Drawing = require('../../components/drawing');
+
+var getColorscale = require('../../components/colorscale/get_scale');
+var makeScaleFunction = require('../../components/colorscale/make_scale_function');
+var getTopojsonFeatures = require('../../lib/topojson_utils').getTopojsonFeatures;
+var locationToFeature = require('../../lib/geo_location_utils').locationToFeature;
+var arrayToCalcItem = require('../../lib/array_to_calc_item');
+
+var constants = require('../../constants/geo_constants');
+var attributes = require('./attributes');
+
+var plotChoropleth = module.exports = {};
+
+
+plotChoropleth.calcGeoJSON = function(trace, topojson) {
+    var cdi = [],
+        locations = trace.locations,
+        len = locations.length,
+        features = getTopojsonFeatures(trace, topojson),
+        markerLine = (trace.marker || {}).line || {};
+
+    var feature;
+
+    for(var i = 0; i < len; i++) {
+        feature = locationToFeature(trace.locationmode, locations[i], features);
+
+        if(feature === undefined) continue;  // filter the blank features here
+
+        // 'data_array' attributes
+        feature.z = trace.z[i];
+        if(trace.text !== undefined) feature.tx = trace.text[i];
+
+        // 'arrayOk' attributes
+        arrayToCalcItem(markerLine.color, feature, 'mlc', i);
+        arrayToCalcItem(markerLine.width, feature, 'mlw', i);
+
+        cdi.push(feature);
+    }
+
+    if(cdi.length > 0) cdi[0].trace = trace;
+
+    return cdi;
+};
+
+plotChoropleth.plot = function(geo, choroplethData, geoLayout) {
+    var framework = geo.framework,
+        gChoropleth = framework.select('g.choroplethlayer'),
+        gBaseLayer = framework.select('g.baselayer'),
+        gBaseLayerOverChoropleth = framework.select('g.baselayeroverchoropleth'),
+        baseLayersOverChoropleth = constants.baseLayersOverChoropleth,
+        layerName;
+
+    var gChoroplethTraces = gChoropleth
+        .selectAll('g.trace.choropleth')
+        .data(choroplethData, function(trace) { return trace.uid; });
+
+    gChoroplethTraces.enter().append('g')
+        .attr('class', 'trace choropleth');
+
+    gChoroplethTraces.exit().remove();
+
+    gChoroplethTraces
+        .each(function(trace) {
+            var cdi = plotChoropleth.calcGeoJSON(trace, geo.topojson),
+                cleanHoverLabelsFunc = makeCleanHoverLabelsFunc(geo, trace),
+                eventDataFunc = makeEventDataFunc(trace);
+
+            function handleMouseOver(pt, ptIndex) {
+                if(!geo.showHover) return;
+
+                var xy = geo.projection(pt.properties.ct);
+                cleanHoverLabelsFunc(pt);
+
+                Fx.loneHover({
+                    x: xy[0],
+                    y: xy[1],
+                    name: pt.nameLabel,
+                    text: pt.textLabel
+                }, {
+                    container: geo.hoverContainer.node()
+                });
+
+                geo.graphDiv.emit('plotly_hover', eventDataFunc(pt, ptIndex));
+            }
+
+            function handleClick(pt, ptIndex) {
+                geo.graphDiv.emit('plotly_click', eventDataFunc(pt, ptIndex));
+            }
+
+            d3.select(this)
+                .selectAll('path.choroplethlocation')
+                    .data(cdi)
+                .enter().append('path')
+                    .attr('class', 'choroplethlocation')
+                    .on('mouseover', handleMouseOver)
+                    .on('click', handleClick)
+                    .on('mouseout', function() {
+                        Fx.loneUnhover(geo.hoverContainer);
+                    })
+                    .on('mousedown', function() {
+                        // to simulate the 'zoomon' event
+                        Fx.loneUnhover(geo.hoverContainer);
+                    })
+                    .on('mouseup', handleMouseOver);  // ~ 'zoomend'
+        });
+
+    // some baselayers are drawn over choropleth
+    gBaseLayerOverChoropleth.selectAll('*').remove();
+
+    for(var i = 0; i < baseLayersOverChoropleth.length; i++) {
+        layerName = baseLayersOverChoropleth[i];
+        gBaseLayer.select('g.' + layerName).remove();
+        geo.drawTopo(gBaseLayerOverChoropleth, layerName, geoLayout);
+        geo.styleLayer(gBaseLayerOverChoropleth, layerName, geoLayout);
+    }
+
+    plotChoropleth.style(geo);
+};
+
+plotChoropleth.style = function(geo) {
+    geo.framework.selectAll('g.trace.choropleth')
+        .each(function(trace) {
+            var s = d3.select(this),
+                marker = trace.marker || {},
+                markerLine = marker.line || {},
+                zmin = trace.zmin,
+                zmax = trace.zmax,
+                scl = getColorscale(trace.colorscale),
+                sclFunc = makeScaleFunction(scl, zmin, zmax);
+
+            s.selectAll('path.choroplethlocation')
+                .each(function(pt) {
+                    d3.select(this)
+                        .attr('fill', function(pt) { return sclFunc(pt.z); })
+                        .call(Color.stroke, pt.mlc || markerLine.color)
+                        .call(Drawing.dashLine, '', pt.mlw || markerLine.width);
+                });
+        });
+};
+
+function makeCleanHoverLabelsFunc(geo, trace) {
+    var hoverinfo = trace.hoverinfo;
+
+    if(hoverinfo === 'none') {
+        return function cleanHoverLabelsFunc(pt) {
+            delete pt.nameLabel;
+            delete pt.textLabel;
+        };
+    }
+
+    var hoverinfoParts = (hoverinfo === 'all') ?
+            attributes.hoverinfo.flags :
+            hoverinfo.split('+');
+
+    var hasName = (hoverinfoParts.indexOf('name') !== -1),
+        hasLocation = (hoverinfoParts.indexOf('location') !== -1),
+        hasZ = (hoverinfoParts.indexOf('z') !== -1),
+        hasText = (hoverinfoParts.indexOf('text') !== -1),
+        hasIdAsNameLabel = !hasName && hasLocation;
+
+    function formatter(val) {
+        var axis = geo.mockAxis;
+        return Axes.tickText(axis, axis.c2l(val), 'hover').text;
+    }
+
+    return function cleanHoverLabelsFunc(pt) {
+        // put location id in name label container
+        // if name isn't part of hoverinfo
+        var thisText = [];
+
+        if(hasIdAsNameLabel) pt.nameLabel = pt.id;
+        else {
+            if(hasName) pt.nameLabel = trace.name;
+            if(hasLocation) thisText.push(pt.id);
+        }
+
+        if(hasZ) thisText.push(formatter(pt.z));
+        if(hasText) thisText.push(pt.tx);
+
+        pt.textLabel = thisText.join('<br>');
+    };
+}
+
+function makeEventDataFunc(trace) {
+    return function(pt, ptIndex) {
+        return {points: [{
+            data: trace._input,
+            fullData: trace,
+            curveNumber: trace.index,
+            pointNumber: ptIndex,
+            location: pt.id,
+            z: pt.z
+        }]};
+    };
+}
+
+},{"../../components/color":299,"../../components/colorscale/get_scale":310,"../../components/colorscale/make_scale_function":315,"../../components/drawing":317,"../../constants/geo_constants":334,"../../lib/array_to_calc_item":341,"../../lib/geo_location_utils":346,"../../lib/topojson_utils":361,"../../plots/cartesian/axes":369,"../../plots/cartesian/graph_interact":374,"./attributes":446,"d3":70}],450:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var heatmapAttrs = require('../heatmap/attributes');
+var scatterAttrs = require('../scatter/attributes');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+var scatterLineAttrs = scatterAttrs.line;
+
+module.exports = {
+    z: heatmapAttrs.z,
+    x: heatmapAttrs.x,
+    x0: heatmapAttrs.x0,
+    dx: heatmapAttrs.dx,
+    y: heatmapAttrs.y,
+    y0: heatmapAttrs.y0,
+    dy: heatmapAttrs.dy,
+    text: heatmapAttrs.text,
+    transpose: heatmapAttrs.transpose,
+    xtype: heatmapAttrs.xtype,
+    ytype: heatmapAttrs.ytype,
+
+    zauto: heatmapAttrs.zauto,
+    zmin: heatmapAttrs.zmin,
+    zmax: heatmapAttrs.zmax,
+    colorscale: heatmapAttrs.colorscale,
+    autocolorscale: heatmapAttrs.autocolorscale,
+    reversescale: heatmapAttrs.reversescale,
+    showscale: heatmapAttrs.showscale,
+
+    connectgaps: heatmapAttrs.connectgaps,
+
+    autocontour: {
+        valType: 'boolean',
+        dflt: true,
+        
+        
+    },
+    ncontours: {
+        valType: 'integer',
+        dflt: 0,
+        
+        
+    },
+
+    contours: {
+        start: {
+            valType: 'number',
+            dflt: null,
+            
+            
+        },
+        end: {
+            valType: 'number',
+            dflt: null,
+            
+            
+        },
+        size: {
+            valType: 'number',
+            dflt: null,
+            
+            
+        },
+        coloring: {
+            valType: 'enumerated',
+            values: ['fill', 'heatmap', 'lines', 'none'],
+            dflt: 'fill',
+            
+            
+        },
+        showlines: {
+            valType: 'boolean',
+            dflt: true,
+            
+            
+        }
+    },
+
+    line: {
+        color: extendFlat({}, scatterLineAttrs.color, {
+            
+        }),
+        width: scatterLineAttrs.width,
+        dash: scatterLineAttrs.dash,
+        smoothing: extendFlat({}, scatterLineAttrs.smoothing, {
+            
+        })
+    },
+
+    _nestedModules: {
+        'colorbar': 'Colorbar'
+    }
+};
+
+},{"../../lib/extend":345,"../heatmap/attributes":459,"../scatter/attributes":502}],451:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Axes = require('../../plots/cartesian/axes');
+var heatmapCalc = require('../heatmap/calc');
+
+
+module.exports = function calc(gd, trace) {
+    // most is the same as heatmap calc, then adjust it
+    // though a few things inside heatmap calc still look for
+    // contour maps, because the makeBoundArray calls are too entangled
+    var cd = heatmapCalc(gd, trace),
+        contours = trace.contours;
+
+    // check if we need to auto-choose contour levels
+    if(trace.autocontour!==false) {
+        var dummyAx = {
+            type: 'linear',
+            range: [trace.zmin, trace.zmax]
+        };
+        Axes.autoTicks(dummyAx,
+            (trace.zmax - trace.zmin) / (trace.ncontours||15));
+        contours.start = Axes.tickFirst(dummyAx);
+        contours.size = dummyAx.dtick;
+        dummyAx.range.reverse();
+        contours.end = Axes.tickFirst(dummyAx);
+
+        if(contours.start === trace.zmin) contours.start += contours.size;
+        if(contours.end === trace.zmax) contours.end -= contours.size;
+
+        // so rounding errors don't cause us to miss the last contour
+        contours.end += contours.size/100;
+
+        // copy auto-contour info back to the source data.
+        trace._input.contours = contours;
+    }
+
+    return cd;
+};
+
+},{"../../plots/cartesian/axes":369,"../heatmap/calc":460}],452:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var Plots = require('../../plots/plots');
+var getColorscale = require('../../components/colorscale/get_scale');
+var drawColorbar = require('../../components/colorbar/draw');
+
+
+module.exports = function colorbar(gd, cd) {
+    var trace = cd[0].trace,
+        cbId = 'cb' + trace.uid;
+
+    gd._fullLayout._infolayer.selectAll('.' + cbId).remove();
+
+    if(trace.showscale === false) {
+        Plots.autoMargin(gd, cbId);
+        return;
+    }
+
+    var cb = drawColorbar(gd, cbId);
+    cd[0].t.cb = cb;
+
+    var contours = trace.contours,
+        line = trace.line,
+        cs = contours.size||1,
+        nc = Math.floor((contours.end + cs/10 - contours.start)/cs)+1,
+        scl = getColorscale(trace.colorscale),
+        extraLevel = contours.coloring==='lines' ? 0 : 1,
+        colormap = d3.scale.linear().interpolate(d3.interpolateRgb),
+        colorDomain = scl.map(function(si) {
+            return (si[0]*(nc+extraLevel-1)-(extraLevel/2)) * cs +
+                contours.start;
+        }),
+        colorRange = scl.map(function(si) { return si[1]; });
+
+    // colorbar fill and lines
+    if(contours.coloring==='heatmap') {
+        if(trace.zauto && trace.autocontour===false) {
+            trace.zmin = contours.start-cs/2;
+            trace.zmax = trace.zmin+nc*cs;
+        }
+        cb.filllevels({
+            start: trace.zmin,
+            end: trace.zmax,
+            size: (trace.zmax-trace.zmin)/254
+        });
+        colorDomain = scl.map(function(si) {
+            return si[0]*(trace.zmax-trace.zmin) + trace.zmin;
+        });
+
+        // do the contours extend beyond the colorscale?
+        // if so, extend the colorscale with constants
+        var zRange = d3.extent([trace.zmin, trace.zmax, contours.start,
+                contours.start + cs*(nc-1)]),
+            zmin = zRange[trace.zmin<trace.zmax ? 0 : 1],
+            zmax = zRange[trace.zmin<trace.zmax ? 1 : 0];
+        if(zmin!==trace.zmin) {
+            colorDomain.splice(0, 0, zmin);
+            colorRange.splice(0, 0, colorRange[0]);
+        }
+        if(zmax!==trace.zmax) {
+            colorDomain.push(zmax);
+            colorRange.push(colorRange[colorRange.length-1]);
+        }
+    }
+
+    colormap.domain(colorDomain).range(colorRange);
+
+    cb.fillcolor(contours.coloring==='fill' || contours.coloring==='heatmap' ?
+            colormap : '')
+        .line({
+            color: contours.coloring==='lines' ? colormap : line.color,
+            width: contours.showlines!==false ? line.width : 0,
+            dash: line.dash
+        })
+        .levels({
+            start: contours.start,
+            end: contours.end,
+            size: cs
+        })
+        .options(trace.colorbar)();
+};
+
+},{"../../components/colorbar/draw":302,"../../components/colorscale/get_scale":310,"../../plots/plots":413,"d3":70}],453:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var hasColumns = require('../heatmap/has_columns');
+var handleXYZDefaults = require('../heatmap/xyz_defaults');
+var handleStyleDefaults = require('../contour/style_defaults');
+var attributes = require('./attributes');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    var len = handleXYZDefaults(traceIn, traceOut, coerce);
+    if(!len) {
+        traceOut.visible = false;
+        return;
+    }
+
+    coerce('text');
+    coerce('connectgaps', hasColumns(traceOut));
+
+    var contourStart = Lib.coerce2(traceIn, traceOut, attributes, 'contours.start'),
+        contourEnd = Lib.coerce2(traceIn, traceOut, attributes, 'contours.end'),
+        autocontour = coerce('autocontour', !(contourStart && contourEnd));
+
+    if(autocontour) coerce('ncontours');
+    else coerce('contours.size');
+
+    handleStyleDefaults(traceIn, traceOut, coerce, layout);
+};
+
+},{"../../lib":349,"../contour/style_defaults":458,"../heatmap/has_columns":464,"../heatmap/xyz_defaults":470,"./attributes":450}],454:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var heatmapHoverPoints = require('../heatmap/hover');
+
+
+module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
+    return heatmapHoverPoints(pointData, xval, yval, hovermode, true);
+};
+
+},{"../heatmap/hover":465}],455:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Contour = {};
+
+Contour.attributes = require('./attributes');
+Contour.supplyDefaults = require('./defaults');
+Contour.calc = require('./calc');
+Contour.plot = require('./plot');
+Contour.style = require('./style');
+Contour.colorbar = require('./colorbar');
+Contour.hoverPoints = require('./hover');
+
+Contour.moduleType = 'trace';
+Contour.name = 'contour';
+Contour.basePlotModule = require('../../plots/cartesian');
+Contour.categories = ['cartesian', '2dMap', 'contour'];
+Contour.meta = {
+    
+};
+
+module.exports = Contour;
+
+},{"../../plots/cartesian":375,"./attributes":450,"./calc":451,"./colorbar":452,"./defaults":453,"./hover":454,"./plot":456,"./style":457}],456:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var Lib = require('../../lib');
+var Drawing = require('../../components/drawing');
+
+var heatmapPlot = require('../heatmap/plot');
+
+
+module.exports = function plot(gd, plotinfo, cdcontours) {
+    for(var i = 0; i < cdcontours.length; i++) {
+        plotOne(gd, plotinfo, cdcontours[i]);
+    }
+};
+
+// some constants to help with marching squares algorithm
+    // where does the path start for each index?
+var BOTTOMSTART = [1,9,13,104,713],
+    TOPSTART = [4,6,7,104,713],
+    LEFTSTART = [8,12,14,208,1114],
+    RIGHTSTART = [2,3,11,208,1114],
+
+    // which way [dx,dy] do we leave a given index?
+    // saddles are already disambiguated
+    NEWDELTA = [
+        null, [-1, 0], [0, -1], [-1, 0],
+        [1, 0], null, [0, -1], [-1, 0],
+        [0, 1], [0, 1], null, [0, 1],
+        [1, 0], [1, 0], [0, -1]
+    ],
+    // for each saddle, the first index here is used
+    // for dx||dy<0, the second for dx||dy>0
+    CHOOSESADDLE = {
+        104: [4, 1],
+        208: [2, 8],
+        713: [7, 13],
+        1114: [11, 14]
+    },
+    // after one index has been used for a saddle, which do we
+    // substitute to be used up later?
+    SADDLEREMAINDER = {1: 4, 2: 8, 4: 1, 7: 13, 8: 2, 11: 14, 13: 7, 14: 11};
+
+function plotOne(gd, plotinfo, cd) {
+    Lib.markTime('in Contour.plot');
+    var trace = cd[0].trace,
+        x = cd[0].x,
+        y = cd[0].y,
+        contours = trace.contours,
+        uid = trace.uid,
+        xa = plotinfo.x(),
+        ya = plotinfo.y(),
+        fullLayout = gd._fullLayout,
+        id = 'contour' + uid,
+        pathinfo = emptyPathinfo(contours, plotinfo, cd[0]);
+
+    if(trace.visible !== true) {
+        fullLayout._paper.selectAll('.' + id + ',.hm' + uid).remove();
+        fullLayout._infolayer.selectAll('.cb' + uid).remove();
+        return;
+    }
+
+    // use a heatmap to fill - draw it behind the lines
+    if(contours.coloring === 'heatmap') {
+        if(trace.zauto && (trace.autocontour === false)) {
+            trace._input.zmin = trace.zmin =
+                contours.start - contours.size / 2;
+            trace._input.zmax = trace.zmax =
+                trace.zmin + pathinfo.length * contours.size;
+        }
+
+        heatmapPlot(gd, plotinfo, [cd]);
+    }
+    // in case this used to be a heatmap (or have heatmap fill)
+    else fullLayout._paper.selectAll('.hm' + uid).remove();
+
+    makeCrossings(pathinfo);
+    findAllPaths(pathinfo);
+
+    var leftedge = xa.c2p(x[0], true),
+        rightedge = xa.c2p(x[x.length-1], true),
+        bottomedge = ya.c2p(y[0], true),
+        topedge = ya.c2p(y[y.length-1], true),
+        perimeter = [
+            [leftedge, topedge],
+            [rightedge, topedge],
+            [rightedge, bottomedge],
+            [leftedge, bottomedge]
+        ];
+
+    // draw everything
+    var plotGroup = makeContourGroup(plotinfo, cd, id);
+    makeBackground(plotGroup, perimeter, contours);
+    makeFills(plotGroup, pathinfo, perimeter, contours);
+    makeLines(plotGroup, pathinfo, contours);
+    clipGaps(plotGroup, plotinfo, cd[0], perimeter);
+
+    Lib.markTime('done Contour.plot');
+}
+
+function emptyPathinfo(contours, plotinfo, cd0) {
+    var cs = contours.size || 1,
+        pathinfo = [];
+    for(var ci = contours.start; ci < contours.end + cs/10; ci += cs) {
+        pathinfo.push({
+            level: ci,
+            // all the cells with nontrivial marching index
+            crossings: {},
+            // starting points on the edges of the lattice for each contour
+            starts: [],
+            // all unclosed paths (may have less items than starts,
+            // if a path is closed by rounding)
+            edgepaths: [],
+            // all closed paths
+            paths: [],
+            // store axes so we can convert to px
+            xaxis: plotinfo.x(),
+            yaxis: plotinfo.y(),
+            // full data arrays to use for interpolation
+            x: cd0.x,
+            y: cd0.y,
+            z: cd0.z,
+            smoothing: cd0.trace.line.smoothing
+        });
+    }
+    return pathinfo;
+}
+
+// modified marching squares algorithm,
+// so we disambiguate the saddle points from the start
+// and we ignore the cases with no crossings
+// the index I'm using is based on:
+// http://en.wikipedia.org/wiki/Marching_squares
+// except that the saddles bifurcate and I represent them
+// as the decimal combination of the two appropriate
+// non-saddle indices
+function getMarchingIndex(val,corners) {
+    var mi = (corners[0][0] > val ? 0 : 1) +
+             (corners[0][1] > val ? 0 : 2) +
+             (corners[1][1] > val ? 0 : 4) +
+             (corners[1][0] > val ? 0 : 8);
+    if(mi === 5 || mi === 10) {
+        var avg = (corners[0][0] + corners[0][1] +
+                   corners[1][0] + corners[1][1]) / 4;
+        // two peaks with a big valley
+        if(val > avg) return (mi === 5) ? 713 : 1114;
+        // two valleys with a big ridge
+        return (mi === 5) ? 104 : 208;
+    }
+    return (mi === 15) ? 0 : mi;
+}
+
+// Calculate all the marching indices, for ALL levels at once.
+// since we want to be exhaustive we'll check for contour crossings
+// at every intersection, rather than just following a path
+// TODO: shorten the inner loop to only the relevant levels
+function makeCrossings(pathinfo) {
+    var z = pathinfo[0].z,
+        m = z.length,
+        n = z[0].length, // we already made sure z isn't ragged in interp2d
+        twoWide = m===2 || n===2,
+        xi,
+        yi,
+        startIndices,
+        ystartIndices,
+        label,
+        corners,
+        mi,
+        pi,
+        i;
+
+    for(yi = 0; yi<m-1; yi++) {
+        ystartIndices = [];
+        if(yi===0) ystartIndices = ystartIndices.concat(BOTTOMSTART);
+        if(yi===m-2) ystartIndices = ystartIndices.concat(TOPSTART);
+
+        for(xi = 0; xi<n-1; xi++) {
+            startIndices = ystartIndices.slice();
+            if(xi===0) startIndices = startIndices.concat(LEFTSTART);
+            if(xi===n-2) startIndices = startIndices.concat(RIGHTSTART);
+
+            label = xi+','+yi;
+            corners = [[z[yi][xi], z[yi][xi+1]],
+                       [z[yi+1][xi], z[yi+1][xi+1]]];
+            for(i = 0; i < pathinfo.length; i++) {
+                pi = pathinfo[i];
+                mi = getMarchingIndex(pi.level,corners);
+                if(!mi) continue;
+
+                pi.crossings[label] = mi;
+                if(startIndices.indexOf(mi)!==-1) {
+                    pi.starts.push([xi, yi]);
+                    if(twoWide && startIndices.indexOf(mi,
+                            startIndices.indexOf(mi) + 1) !== -1) {
+                        // the same square has starts from opposite sides
+                        // it's not possible to have starts on opposite edges
+                        // of a corner, only a start and an end...
+                        // but if the array is only two points wide (either way)
+                        // you can have starts on opposite sides.
+                        pi.starts.push([xi, yi]);
+                    }
+                }
+            }
+        }
+    }
+}
+
+function makePath(pi, loc, edgeflag) {
+    var startLocStr = loc.join(','),
+        locStr = startLocStr,
+        mi = pi.crossings[locStr],
+        marchStep = startStep(mi, edgeflag, loc),
+        // start by going backward a half step and finding the crossing point
+        pts = [getInterpPx(pi, loc, [-marchStep[0], -marchStep[1]])],
+        startStepStr = marchStep.join(','),
+        m = pi.z.length,
+        n = pi.z[0].length,
+        cnt;
+
+    // now follow the path
+    for(cnt=0; cnt<10000; cnt++) { // just to avoid infinite loops
+        if(mi>20) {
+            mi = CHOOSESADDLE[mi][(marchStep[0]||marchStep[1])<0 ? 0 : 1];
+            pi.crossings[locStr] = SADDLEREMAINDER[mi];
+        }
+        else {
+            delete pi.crossings[locStr];
+        }
+
+        marchStep = NEWDELTA[mi];
+        if(!marchStep) {
+            console.log('found bad marching index', mi, loc, pi.level);
+            break;
+        }
+
+        // find the crossing a half step forward, and then take the full step
+        pts.push(getInterpPx(pi, loc, marchStep));
+        loc[0] += marchStep[0];
+        loc[1] += marchStep[1];
+
+        // don't include the same point multiple times
+        if(equalPts(pts[pts.length-1], pts[pts.length-2])) pts.pop();
+        locStr = loc.join(',');
+
+        // have we completed a loop, or reached an edge?
+        if((locStr===startLocStr && marchStep.join(',')===startStepStr) ||
+            (edgeflag && (
+                (marchStep[0] && (loc[0]<0 || loc[0]>n-2)) ||
+                (marchStep[1] && (loc[1]<0 || loc[1]>m-2))))) {
+            break;
+        }
+        mi = pi.crossings[locStr];
+    }
+
+    if(cnt===10000) {
+        console.log('Infinite loop in contour?');
+    }
+    var closedpath = equalPts(pts[0], pts[pts.length-1]),
+        totaldist = 0,
+        distThresholdFactor = 0.2 * pi.smoothing,
+        alldists = [],
+        cropstart = 0,
+        distgroup,
+        cnt2,
+        cnt3,
+        newpt,
+        ptcnt,
+        ptavg,
+        thisdist;
+
+    // check for points that are too close together (<1/5 the average dist,
+    // less if less smoothed) and just take the center (or avg of center 2)
+    // this cuts down on funny behavior when a point is very close to a contour level
+    for(cnt=1; cnt<pts.length; cnt++) {
+        thisdist = ptDist(pts[cnt], pts[cnt-1]);
+        totaldist += thisdist;
+        alldists.push(thisdist);
+    }
+
+    var distThreshold = totaldist/alldists.length*distThresholdFactor;
+
+    function getpt(i) { return pts[i%pts.length]; }
+
+    for(cnt=pts.length-2; cnt>=cropstart; cnt--) {
+        distgroup = alldists[cnt];
+        if(distgroup<distThreshold) {
+            cnt3 = 0;
+            for(cnt2=cnt-1; cnt2>=cropstart; cnt2--) {
+                if(distgroup+alldists[cnt2]<distThreshold) {
+                    distgroup += alldists[cnt2];
+                }
+                else break;
+            }
+
+            // closed path with close points wrapping around the boundary?
+            if(closedpath && cnt===pts.length-2) {
+                for(cnt3=0; cnt3<cnt2; cnt3++) {
+                    if(distgroup+alldists[cnt3]<distThreshold) {
+                        distgroup += alldists[cnt3];
+                    }
+                    else break;
+                }
+            }
+            ptcnt = cnt-cnt2+cnt3+1;
+            ptavg = Math.floor((cnt+cnt2+cnt3+2)/2);
+
+            // either endpoint included: keep the endpoint
+            if(!closedpath && cnt===pts.length-2) newpt = pts[pts.length-1];
+            else if(!closedpath && cnt2===-1) newpt = pts[0];
+
+            // odd # of points - just take the central one
+            else if(ptcnt%2) newpt = getpt(ptavg);
+
+            // even # of pts - average central two
+            else {
+                newpt = [(getpt(ptavg)[0] + getpt(ptavg+1)[0]) / 2,
+                         (getpt(ptavg)[1] + getpt(ptavg+1)[1]) / 2];
+            }
+
+            pts.splice(cnt2+1, cnt-cnt2+1, newpt);
+            cnt = cnt2+1;
+            if(cnt3) cropstart = cnt3;
+            if(closedpath) {
+                if(cnt===pts.length-2) pts[cnt3] = pts[pts.length-1];
+                else if(cnt===0) pts[pts.length-1] = pts[0];
+            }
+        }
+    }
+    pts.splice(0, cropstart);
+
+    // don't return single-point paths (ie all points were the same
+    // so they got deleted?)
+    if(pts.length<2) return;
+    else if(closedpath) {
+        pts.pop();
+        pi.paths.push(pts);
+    }
+    else {
+        if(!edgeflag) {
+            console.log('unclosed interior contour?',
+                pi.level,startLocStr,pts.join('L'));
+        }
+
+        // edge path - does it start where an existing edge path ends, or vice versa?
+        var merged = false;
+        pi.edgepaths.forEach(function(edgepath, edgei) {
+            if(!merged && equalPts(edgepath[0], pts[pts.length-1])) {
+                pts.pop();
+                merged = true;
+
+                // now does it ALSO meet the end of another (or the same) path?
+                var doublemerged = false;
+                pi.edgepaths.forEach(function(edgepath2, edgei2) {
+                    if(!doublemerged && equalPts(
+                            edgepath2[edgepath2.length-1], pts[0])) {
+                        doublemerged = true;
+                        pts.splice(0, 1);
+                        pi.edgepaths.splice(edgei, 1);
+                        if(edgei2===edgei) {
+                            // the path is now closed
+                            pi.paths.push(pts.concat(edgepath2));
+                        }
+                        else {
+                            pi.edgepaths[edgei2] =
+                                pi.edgepaths[edgei2].concat(pts, edgepath2);
+                        }
+                    }
+                });
+                if(!doublemerged) {
+                    pi.edgepaths[edgei] = pts.concat(edgepath);
+                }
+            }
+        });
+        pi.edgepaths.forEach(function(edgepath, edgei) {
+            if(!merged && equalPts(edgepath[edgepath.length-1], pts[0])) {
+                pts.splice(0, 1);
+                pi.edgepaths[edgei] = edgepath.concat(pts);
+                merged = true;
+            }
+        });
+
+        if(!merged) pi.edgepaths.push(pts);
+    }
+}
+
+function findAllPaths(pathinfo) {
+    var cnt,
+        startLoc,
+        i,
+        pi,
+        j;
+
+    for(i = 0; i < pathinfo.length; i++) {
+        pi = pathinfo[i];
+
+        for(j = 0; j < pi.starts.length; j++) {
+            startLoc = pi.starts[j];
+            makePath(pi, startLoc, 'edge');
+        }
+
+        cnt = 0;
+        while(Object.keys(pi.crossings).length && cnt<10000) {
+            cnt++;
+            startLoc = Object.keys(pi.crossings)[0].split(',').map(Number);
+            makePath(pi, startLoc);
+        }
+        if(cnt===10000) console.log('Infinite loop in contour?');
+    }
+}
+
+// special function to get the marching step of the
+// first point in the path (leading to loc)
+function startStep(mi, edgeflag, loc) {
+    var dx = 0,
+        dy = 0;
+    if(mi>20 && edgeflag) {
+        // these saddles start at +/- x
+        if(mi===208 || mi===1114) {
+            // if we're starting at the left side, we must be going right
+            dx = loc[0]===0 ? 1 : -1;
+        }
+        else {
+            // if we're starting at the bottom, we must be going up
+            dy = loc[1]===0 ? 1 : -1;
+        }
+    }
+    else if(BOTTOMSTART.indexOf(mi)!==-1) dy = 1;
+    else if(LEFTSTART.indexOf(mi)!==-1) dx = 1;
+    else if(TOPSTART.indexOf(mi)!==-1) dy = -1;
+    else dx = -1;
+    return [dx, dy];
+}
+
+function equalPts(pt1, pt2) {
+    return Math.abs(pt1[0] - pt2[0]) < 0.01 &&
+           Math.abs(pt1[1] - pt2[1]) < 0.01;
+}
+
+function ptDist(pt1, pt2) {
+    var dx = pt1[0] - pt2[0],
+        dy = pt1[1] - pt2[1];
+    return Math.sqrt(dx*dx + dy*dy);
+}
+
+function getInterpPx(pi, loc, step) {
+    var locx = loc[0] + Math.max(step[0], 0),
+        locy = loc[1] + Math.max(step[1], 0),
+        zxy = pi.z[locy][locx],
+        xa = pi.xaxis,
+        ya = pi.yaxis;
+
+    if(step[1]) {
+        var dx = (pi.level - zxy) / (pi.z[locy][locx+1] - zxy);
+        return [xa.c2p((1-dx) * pi.x[locx] + dx * pi.x[locx+1], true),
+                ya.c2p(pi.y[locy], true)];
+    }
+    else {
+        var dy = (pi.level - zxy) / (pi.z[locy+1][locx] - zxy);
+        return [xa.c2p(pi.x[locx], true),
+                ya.c2p((1-dy) * pi.y[locy] + dy * pi.y[locy+1], true)];
+    }
+}
+
+function makeContourGroup(plotinfo, cd, id) {
+    var plotgroup = plotinfo.plot.select('.maplayer')
+        .selectAll('g.contour.' + id)
+        .data(cd);
+
+    plotgroup.enter().append('g')
+        .classed('contour', true)
+        .classed(id, true);
+
+    plotgroup.exit().remove();
+
+    return plotgroup;
+}
+
+function makeBackground(plotgroup, perimeter, contours) {
+    var bggroup = plotgroup.selectAll('g.contourbg').data([0]);
+    bggroup.enter().append('g').classed('contourbg',true);
+
+    var bgfill = bggroup.selectAll('path')
+        .data(contours.coloring==='fill' ? [0] : []);
+    bgfill.enter().append('path');
+    bgfill.exit().remove();
+    bgfill
+        .attr('d','M'+perimeter.join('L')+'Z')
+        .style('stroke','none');
+}
+
+function makeFills(plotgroup, pathinfo, perimeter, contours) {
+    var fillgroup = plotgroup.selectAll('g.contourfill')
+        .data([0]);
+    fillgroup.enter().append('g')
+        .classed('contourfill',true);
+
+    var fillitems = fillgroup.selectAll('path')
+        .data(contours.coloring==='fill' ? pathinfo : []);
+    fillitems.enter().append('path');
+    fillitems.exit().remove();
+    fillitems.each(function(pi) {
+        // join all paths for this level together into a single path
+        // first follow clockwise around the perimeter to close any open paths
+        // if the whole perimeter is above this level, start with a path
+        // enclosing the whole thing. With all that, the parity should mean
+        // that we always fill everything above the contour, nothing below
+        var fullpath = joinAllPaths(pi, perimeter);
+
+        if(!fullpath) d3.select(this).remove();
+        else d3.select(this).attr('d',fullpath).style('stroke', 'none');
+    });
+}
+
+function joinAllPaths(pi, perimeter) {
+    var fullpath = (pi.edgepaths.length || pi.z[0][0] < pi.level) ?
+            '' : ('M'+perimeter.join('L')+'Z'),
+        i = 0,
+        startsleft = pi.edgepaths.map(function(v,i) { return i; }),
+        newloop = true,
+        endpt,
+        newendpt,
+        cnt,
+        nexti,
+        possiblei,
+        addpath;
+
+    function istop(pt) { return Math.abs(pt[1] - perimeter[0][1]) < 0.01; }
+    function isbottom(pt) { return Math.abs(pt[1] - perimeter[2][1]) < 0.01; }
+    function isleft(pt) { return Math.abs(pt[0] - perimeter[0][0]) < 0.01; }
+    function isright(pt) { return Math.abs(pt[0] - perimeter[2][0]) < 0.01; }
+
+    while(startsleft.length) {
+        addpath = Drawing.smoothopen(pi.edgepaths[i], pi.smoothing);
+        fullpath += newloop ? addpath : addpath.replace(/^M/, 'L');
+        startsleft.splice(startsleft.indexOf(i), 1);
+        endpt = pi.edgepaths[i][pi.edgepaths[i].length-1];
+        nexti = -1;
+
+        //now loop through sides, moving our endpoint until we find a new start
+        for(cnt=0; cnt<4; cnt++) { // just to prevent infinite loops
+            if(!endpt) {
+                console.log('missing end?',i,pi);
+                break;
+            }
+
+            if(istop(endpt) && !isright(endpt)) newendpt = perimeter[1]; // right top
+            else if(isleft(endpt)) newendpt = perimeter[0]; // left top
+            else if(isbottom(endpt)) newendpt = perimeter[3]; // right bottom
+            else if(isright(endpt)) newendpt = perimeter[2]; // left bottom
+
+            for(possiblei=0; possiblei < pi.edgepaths.length; possiblei++) {
+                var ptNew = pi.edgepaths[possiblei][0];
+                // is ptNew on the (horz. or vert.) segment from endpt to newendpt?
+                if(Math.abs(endpt[0]-newendpt[0]) < 0.01) {
+                    if(Math.abs(endpt[0]-ptNew[0]) < 0.01 &&
+                            (ptNew[1]-endpt[1]) * (newendpt[1]-ptNew[1]) >= 0) {
+                        newendpt = ptNew;
+                        nexti = possiblei;
+                    }
+                }
+                else if(Math.abs(endpt[1]-newendpt[1]) < 0.01) {
+                    if(Math.abs(endpt[1]-ptNew[1]) < 0.01 &&
+                            (ptNew[0]-endpt[0]) * (newendpt[0]-ptNew[0]) >= 0) {
+                        newendpt = ptNew;
+                        nexti = possiblei;
+                    }
+                }
+                else {
+                    console.log('endpt to newendpt is not vert. or horz.',
+                        endpt, newendpt, ptNew);
+                }
+            }
+
+            endpt = newendpt;
+
+            if(nexti>=0) break;
+            fullpath += 'L'+newendpt;
+        }
+
+        if(nexti === pi.edgepaths.length) {
+            console.log('unclosed perimeter path');
+            break;
+        }
+
+        i = nexti;
+
+        // if we closed back on a loop we already included,
+        // close it and start a new loop
+        newloop = (startsleft.indexOf(i)===-1);
+        if(newloop) {
+            i = startsleft[0];
+            fullpath += 'Z';
+        }
+    }
+
+    // finally add the interior paths
+    for(i = 0; i < pi.paths.length; i++) {
+        fullpath += Drawing.smoothclosed(pi.paths[i], pi.smoothing);
+    }
+
+    return fullpath;
+}
+
+function makeLines(plotgroup, pathinfo, contours) {
+    var smoothing = pathinfo[0].smoothing;
+
+    var linegroup = plotgroup.selectAll('g.contourlevel')
+        .data(contours.showlines===false ? [] : pathinfo);
+    linegroup.enter().append('g')
+        .classed('contourlevel',true);
+    linegroup.exit().remove();
+
+    var opencontourlines = linegroup.selectAll('path.openline')
+        .data(function(d) { return d.edgepaths; });
+    opencontourlines.enter().append('path')
+        .classed('openline',true);
+    opencontourlines.exit().remove();
+    opencontourlines
+        .attr('d', function(d) {
+            return Drawing.smoothopen(d, smoothing);
+        })
+        .style('stroke-miterlimit',1);
+
+    var closedcontourlines = linegroup.selectAll('path.closedline')
+        .data(function(d) { return d.paths; });
+    closedcontourlines.enter().append('path')
+        .classed('closedline',true);
+    closedcontourlines.exit().remove();
+    closedcontourlines
+        .attr('d', function(d) {
+            return Drawing.smoothclosed(d, smoothing);
+        })
+        .style('stroke-miterlimit',1);
+}
+
+function clipGaps(plotGroup, plotinfo, cd0, perimeter) {
+    var clipId = 'clip' + cd0.trace.uid;
+
+    var defs = plotinfo.plot.selectAll('defs')
+        .data([0]);
+    defs.enter().append('defs');
+
+    var clipPath = defs.selectAll('#' + clipId)
+        .data(cd0.trace.connectgaps ? [] : [0]);
+    clipPath.enter().append('clipPath').attr('id', clipId);
+    clipPath.exit().remove();
+
+    if(cd0.trace.connectgaps === false) {
+        var clipPathInfo = {
+            // fraction of the way from missing to present point
+            // to draw the boundary.
+            // if you make this 1 (or 1-epsilon) then a point in
+            // a sea of missing data will disappear entirely.
+            level: 0.9,
+            crossings: {},
+            starts: [],
+            edgepaths: [],
+            paths: [],
+            xaxis: plotinfo.x(),
+            yaxis: plotinfo.y(),
+            x: cd0.x,
+            y: cd0.y,
+            // 0 = no data, 1 = data
+            z: makeClipMask(cd0),
+            smoothing: 0
+        };
+
+        makeCrossings([clipPathInfo]);
+        findAllPaths([clipPathInfo]);
+        var fullpath = joinAllPaths(clipPathInfo, perimeter);
+
+        var path = clipPath.selectAll('path')
+            .data([0]);
+        path.enter().append('path');
+        path.attr('d', fullpath);
+    }
+    else clipId = null;
+
+    plotGroup.call(Drawing.setClipUrl, clipId);
+    plotinfo.plot.selectAll('.hm' + cd0.trace.uid)
+        .call(Drawing.setClipUrl, clipId);
+}
+
+function makeClipMask(cd0) {
+    var empties = cd0.trace._emptypoints,
+        z = [],
+        m = cd0.z.length,
+        n = cd0.z[0].length,
+        i,
+        row = [],
+        emptyPoint;
+
+    for(i = 0; i < n; i++) row.push(1);
+    for(i = 0; i < m; i++) z.push(row.slice());
+    for(i = 0; i < empties.length; i++) {
+        emptyPoint = empties[i];
+        z[emptyPoint[0]][emptyPoint[1]] = 0;
+    }
+    // save this mask to determine whether to show this data in hover
+    cd0.zmask = z;
+    return z;
+}
+
+},{"../../components/drawing":317,"../../lib":349,"../heatmap/plot":468,"d3":70}],457:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var Drawing = require('../../components/drawing');
+var getColorscale = require('../../components/colorscale/get_scale');
+var heatmapStyle = require('../heatmap/style');
+
+
+module.exports = function style(gd) {
+    d3.select(gd).selectAll('g.contour')
+        .style('opacity', function(d) { return d.trace.opacity; })
+        .each(function(d) {
+            var c = d3.select(this),
+                trace = d.trace,
+                contours = trace.contours,
+                line = trace.line,
+                colorLines = contours.coloring==='lines',
+                cs = contours.size||1,
+                nc = Math.floor((contours.end + cs/10 - contours.start)/cs) + 1,
+                scl = getColorscale(trace.colorscale),
+                extraLevel = colorLines ? 0 : 1,
+                colormap = d3.scale.linear()
+                    .domain(scl.map(function(si) {
+                        return (si[0]*(nc+extraLevel-1)-(extraLevel/2)) * cs +
+                            contours.start;
+                    }))
+                    .interpolate(d3.interpolateRgb)
+                    .range(scl.map(function(si) { return si[1]; }));
+
+            c.selectAll('g.contourlevel').each(function(d, i) {
+                d3.select(this).selectAll('path')
+                    .call(Drawing.lineGroupStyle,
+                        line.width,
+                        colorLines ? colormap(contours.start+i*cs) : line.color,
+                        line.dash);
+            });
+            c.selectAll('g.contourbg path')
+                .style('fill', colormap(contours.start - cs/2));
+            c.selectAll('g.contourfill path')
+                .style('fill',function(d, i) {
+                    return colormap(contours.start + (i+0.5)*cs);
+                });
+        });
+
+    heatmapStyle(gd);
+};
+
+},{"../../components/colorscale/get_scale":310,"../../components/drawing":317,"../heatmap/style":469,"d3":70}],458:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var colorscaleDefaults = require('../../components/colorscale/defaults');
+
+
+module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, layout) {
+    var coloring = coerce('contours.coloring');
+
+    var showLines;
+    if(coloring === 'fill') showLines = coerce('contours.showlines');
+
+    if(showLines !== false) {
+        if(coloring !== 'lines') coerce('line.color', '#000');
+        coerce('line.width', 0.5);
+        coerce('line.dash');
+    }
+
+    coerce('line.smoothing');
+
+    if((traceOut.contours || {}).coloring !== 'none') {
+        colorscaleDefaults(
+            traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
+        );
+    }
+};
+
+},{"../../components/colorscale/defaults":308}],459:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var scatterAttrs = require('../scatter/attributes');
+var colorscaleAttrs = require('../../components/colorscale/attributes');
+
+var extendFlat = require('../../lib/extend').extendFlat;
+
+
+module.exports = {
+    z: {
+        valType: 'data_array',
+        
+    },
+    x: scatterAttrs.x,
+    x0: scatterAttrs.x0,
+    dx: scatterAttrs.dx,
+    y: scatterAttrs.y,
+    y0: scatterAttrs.y0,
+    dy: scatterAttrs.dy,
+    text: {
+        valType: 'data_array',
+        
+    },
+    transpose: {
+        valType: 'boolean',
+        dflt: false,
+        
+        
+    },
+    xtype: {
+        valType: 'enumerated',
+        values: ['array', 'scaled'],
+        
+        
+    },
+    ytype: {
+        valType: 'enumerated',
+        values: ['array', 'scaled'],
+        
+        
+    },
+    zauto: colorscaleAttrs.zauto,
+    zmin: colorscaleAttrs.zmin,
+    zmax: colorscaleAttrs.zmax,
+    colorscale: colorscaleAttrs.colorscale,
+    autocolorscale: extendFlat({}, colorscaleAttrs.autocolorscale,
+        {dflt: false}),
+    reversescale: colorscaleAttrs.reversescale,
+    showscale: colorscaleAttrs.showscale,
+    zsmooth: {
+        valType: 'enumerated',
+        values: ['fast', 'best', false],
+        dflt: false,
+        
+        
+    },
+    connectgaps: {
+        valType: 'boolean',
+        dflt: false,
+        
+        
+    },
+
+    _nestedModules: {
+        'colorbar': 'Colorbar'
+    }
+};
+
+},{"../../components/colorscale/attributes":305,"../../lib/extend":345,"../scatter/attributes":502}],460:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+var Axes = require('../../plots/cartesian/axes');
+var Plots = require('../../plots/plots');
+
+var histogram2dCalc = require('../histogram2d/calc');
+var colorscaleCalc = require('../../components/colorscale/calc');
+var hasColumns = require('./has_columns');
+var convertColumnXYZ = require('./convert_column_xyz');
+var maxRowLength = require('./max_row_length');
+
+
+module.exports = function calc(gd, trace) {
+    Lib.markTime('start convert x&y');
+
+    // prepare the raw data
+    // run makeCalcdata on x and y even for heatmaps, in case of category mappings
+    var xa = Axes.getFromId(gd, trace.xaxis||'x'),
+        ya = Axes.getFromId(gd, trace.yaxis||'y'),
+        isContour = Plots.traceIs(trace, 'contour'),
+        isHist = Plots.traceIs(trace, 'histogram'),
+        zsmooth = isContour ? 'best' : trace.zsmooth,
+        x,
+        x0,
+        dx,
+        y,
+        y0,
+        dy,
+        z,
+        i;
+
+    // cancel minimum tick spacings (only applies to bars and boxes)
+    xa._minDtick = 0;
+    ya._minDtick = 0;
+
+    Lib.markTime('done convert x&y');
+
+    if(isHist) {
+        var binned = histogram2dCalc(gd, trace);
+        x = binned.x;
+        x0 = binned.x0;
+        dx = binned.dx;
+        y = binned.y;
+        y0 = binned.y0;
+        dy = binned.dy;
+        z = binned.z;
+    }
+    else {
+        if(hasColumns(trace)) convertColumnXYZ(trace, xa, ya);
+
+        x = trace.x ? xa.makeCalcdata(trace, 'x') : [];
+        y = trace.y ? ya.makeCalcdata(trace, 'y') : [];
+        x0 = trace.x0 || 0;
+        dx = trace.dx || 1;
+        y0 = trace.y0 || 0;
+        dy = trace.dy || 1;
+
+        z = cleanZ(trace);
+
+        if(isContour || trace.connectgaps) {
+            trace._emptypoints = findEmpties(z);
+            trace._interpz = interp2d(z, trace._emptypoints, trace._interpz);
+        }
+    }
+
+    function noZsmooth(msg) {
+        zsmooth = trace._input.zsmooth = trace.zsmooth = false;
+        Lib.notifier('cannot fast-zsmooth: ' + msg);
+    }
+
+    // check whether we really can smooth (ie all boxes are about the same size)
+    if(zsmooth === 'fast') {
+        if(xa.type==='log' || ya.type==='log') {
+            noZsmooth('log axis found');
+        }
+        else if(!isHist) {
+            if(x.length) {
+                var avgdx = (x[x.length-1]-x[0]) / (x.length-1),
+                    maxErrX = Math.abs(avgdx/100);
+                for(i=0; i<x.length-1; i++) {
+                    if(Math.abs(x[i+1]-x[i]-avgdx)>maxErrX) {
+                        noZsmooth('x scale is not linear');
+                        break;
+                    }
+                }
+            }
+            if(y.length && zsmooth === 'fast') {
+                var avgdy = (y[y.length-1]-y[0])/(y.length-1),
+                    maxErrY = Math.abs(avgdy/100);
+                for(i=0; i<y.length-1; i++) {
+                    if(Math.abs(y[i+1]-y[i]-avgdy)>maxErrY) {
+                        noZsmooth('y scale is not linear');
+                        break;
+                    }
+                }
+            }
+        }
+    }
+
+    // create arrays of brick boundaries, to be used by autorange and heatmap.plot
+    var xlen = maxRowLength(z),
+        xIn = trace.xtype==='scaled' ? '' : trace.x,
+        xArray = makeBoundArray(trace, xIn, x0, dx, xlen, xa),
+        yIn = trace.ytype==='scaled' ? '' : trace.y,
+        yArray = makeBoundArray(trace, yIn, y0, dy, z.length, ya);
+
+    Axes.expand(xa, xArray);
+    Axes.expand(ya, yArray);
+
+    var cd0 = {x: xArray, y: yArray, z: z};
+
+    // auto-z and autocolorscale if applicable
+    colorscaleCalc(trace, z, '', 'z');
+
+    if(isContour && trace.contours && trace.contours.coloring==='heatmap') {
+        var hmType = trace.type === 'contour' ? 'heatmap' : 'histogram2d';
+        cd0.xfill = makeBoundArray(hmType, xIn, x0, dx, xlen, xa);
+        cd0.yfill = makeBoundArray(hmType, yIn, y0, dy, z.length, ya);
+    }
+
+    return [cd0];
+};
+
+
+function cleanZ(trace) {
+    var zOld = trace.z;
+
+    var rowlen, collen, getCollen, old2new, i, j;
+
+    function cleanZvalue(v) {
+        if(!isNumeric(v)) return undefined;
+        return +v;
+    }
+
+    if(trace.transpose) {
+        rowlen = 0;
+        for(i = 0; i < zOld.length; i++) rowlen = Math.max(rowlen, zOld[i].length);
+        if(rowlen === 0) return false;
+        getCollen = function(zOld) { return zOld.length; };
+        old2new = function(zOld, i, j) { return zOld[j][i]; };
+    }
+    else {
+        rowlen = zOld.length;
+        getCollen = function(zOld, i) { return zOld[i].length; };
+        old2new = function(zOld, i, j) { return zOld[i][j]; };
+    }
+
+    var zNew = new Array(rowlen);
+
+    for(i = 0; i < rowlen; i++) {
+        collen = getCollen(zOld, i);
+        zNew[i] = new Array(collen);
+        for(j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(old2new(zOld, i, j));
+    }
+
+    return zNew;
+}
+
+function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) {
+    var arrayOut = [],
+        isContour = Plots.traceIs(trace, 'contour'),
+        isHist = Plots.traceIs(trace, 'histogram'),
+        v0,
+        dv,
+        i;
+    if(Array.isArray(arrayIn) && !isHist && (ax.type!=='category')) {
+        arrayIn = arrayIn.map(ax.d2c);
+        var len = arrayIn.length;
+
+        // given vals are brick centers
+        // hopefully length==numbricks, but use this method even if too few are supplied
+        // and extend it linearly based on the last two points
+        if(len <= numbricks) {
+            // contour plots only want the centers
+            if(isContour) arrayOut = arrayIn.slice(0, numbricks);
+            else if(numbricks === 1) arrayOut = [arrayIn[0]-0.5,arrayIn[0]+0.5];
+            else {
+                arrayOut = [1.5*arrayIn[0]-0.5*arrayIn[1]];
+                for(i=1; i<len; i++) {
+                    arrayOut.push((arrayIn[i-1] + arrayIn[i])*0.5);
+                }
+                arrayOut.push(1.5*arrayIn[len-1] - 0.5*arrayIn[len-2]);
+            }
+
+            if(len < numbricks) {
+                var lastPt = arrayOut[arrayOut.length - 1],
+                    delta = lastPt - arrayOut[arrayOut.length - 2];
+                for(i = len; i < numbricks; i++) {
+                    lastPt += delta;
+                    arrayOut.push(lastPt);
+                }
+            }
+        }
+        else {
+            // hopefully length==numbricks+1, but do something regardless:
+            // given vals are brick boundaries
+            return isContour ?
+                arrayIn.slice(0, numbricks) :  // we must be strict for contours
+                arrayIn.slice(0, numbricks + 1);
+        }
+    }
+    else {
+        dv = dvIn || 1;
+        if(v0In===undefined) v0 = 0;
+        else if(isHist || ax.type==='category') v0 = v0In;
+        else v0 = ax.d2c(v0In);
+
+        for(i = isContour ? 0 : -0.5; i < numbricks; i++) arrayOut.push(v0 + dv * i);
+    }
+    return arrayOut;
+}
+
+var INTERPTHRESHOLD = 1e-2,
+    NEIGHBORSHIFTS = [[-1, 0], [1, 0], [0, -1], [0, 1]];
+
+function correctionOvershoot(maxFractionalChange) {
+    // start with less overshoot, until we know it's converging,
+    // then ramp up the overshoot for faster convergence
+    return 0.5 - 0.25 * Math.min(1, maxFractionalChange * 0.5);
+}
+
+function interp2d(z, emptyPoints, savedInterpZ) {
+    // fill in any missing data in 2D array z using an iterative
+    // poisson equation solver with zero-derivative BC at edges
+    // amazingly, this just amounts to repeatedly averaging all the existing
+    // nearest neighbors (at least if we don't take x/y scaling into account)
+    var maxFractionalChange = 1,
+        i,
+        thisPt;
+
+    if(Array.isArray(savedInterpZ)) {
+        for(i = 0; i < emptyPoints.length; i++) {
+            thisPt = emptyPoints[i];
+            z[thisPt[0]][thisPt[1]] = savedInterpZ[thisPt[0]][thisPt[1]];
+        }
+    }
+    else {
+        // one pass to fill in a starting value for all the empties
+        iterateInterp2d(z, emptyPoints);
+    }
+
+    // we're don't need to iterate lone empties - remove them
+    for(i = 0; i < emptyPoints.length; i++) {
+        if(emptyPoints[i][2] < 4) break;
+    }
+    // but don't remove these points from the original array,
+    // we'll use them for masking, so make a copy.
+    emptyPoints = emptyPoints.slice(i);
+
+    for(i = 0; i < 100 && maxFractionalChange > INTERPTHRESHOLD; i++) {
+        maxFractionalChange = iterateInterp2d(z, emptyPoints,
+            correctionOvershoot(maxFractionalChange));
+    }
+    if(maxFractionalChange > INTERPTHRESHOLD) {
+        console.log('interp2d didn\'t converge quickly', maxFractionalChange);
+    }
+
+    return z;
+}
+
+function findEmpties(z) {
+    // return a list of empty points in 2D array z
+    // each empty point z[i][j] gives an array [i, j, neighborCount]
+    // neighborCount is the count of 4 nearest neighbors that DO exist
+    // this is to give us an order of points to evaluate for interpolation.
+    // if no neighbors exist, we iteratively look for neighbors that HAVE
+    // neighbors, and add a fractional neighborCount
+    var empties = [],
+        neighborHash = {},
+        noNeighborList = [],
+        nextRow = z[0],
+        row = [],
+        blank = [0, 0, 0],
+        rowLength = maxRowLength(z),
+        prevRow,
+        i,
+        j,
+        thisPt,
+        p,
+        neighborCount,
+        newNeighborHash,
+        foundNewNeighbors;
+
+    for(i = 0; i < z.length; i++) {
+        prevRow = row;
+        row = nextRow;
+        nextRow = z[i + 1] || [];
+        for(j = 0; j < rowLength; j++) {
+            if(row[j]===undefined) {
+                neighborCount = (row[j - 1] !== undefined ? 1 : 0) +
+                    (row[j + 1] !== undefined ? 1 : 0) +
+                    (prevRow[j] !== undefined ? 1 : 0) +
+                    (nextRow[j] !== undefined ? 1 : 0);
+
+                if(neighborCount) {
+                    // for this purpose, don't count off-the-edge points
+                    // as undefined neighbors
+                    if(i === 0) neighborCount++;
+                    if(j === 0) neighborCount++;
+                    if(i === z.length - 1) neighborCount++;
+                    if(j === row.length - 1) neighborCount++;
+
+                    // if all neighbors that could exist do, we don't
+                    // need this for finding farther neighbors
+                    if(neighborCount < 4) {
+                        neighborHash[[i,j]] = [i, j, neighborCount];
+                    }
+
+                    empties.push([i, j, neighborCount]);
+                }
+                else noNeighborList.push([i, j]);
+            }
+        }
+    }
+
+    while(noNeighborList.length) {
+        newNeighborHash = {};
+        foundNewNeighbors = false;
+
+        // look for cells that now have neighbors but didn't before
+        for(p = noNeighborList.length - 1; p >= 0; p--) {
+            thisPt = noNeighborList[p];
+            i = thisPt[0];
+            j = thisPt[1];
+
+            neighborCount = ((neighborHash[[i - 1, j]] || blank)[2] +
+                (neighborHash[[i + 1, j]] || blank)[2] +
+                (neighborHash[[i, j - 1]] || blank)[2] +
+                (neighborHash[[i, j + 1]] || blank)[2])/20;
+
+            if(neighborCount) {
+                newNeighborHash[thisPt] = [i, j, neighborCount];
+                noNeighborList.splice(p, 1);
+                foundNewNeighbors = true;
+            }
+        }
+
+        if(!foundNewNeighbors) {
+            throw 'findEmpties iterated with no new neighbors';
+        }
+
+        // put these new cells into the main neighbor list
+        for(thisPt in newNeighborHash) {
+            neighborHash[thisPt] = newNeighborHash[thisPt];
+            empties.push(newNeighborHash[thisPt]);
+        }
+    }
+
+    // sort the full list in descending order of neighbor count
+    return empties.sort(function(a, b) { return b[2] - a[2]; });
+}
+
+function iterateInterp2d(z, emptyPoints, overshoot) {
+    var maxFractionalChange = 0,
+        thisPt,
+        i,
+        j,
+        p,
+        q,
+        neighborShift,
+        neighborRow,
+        neighborVal,
+        neighborCount,
+        neighborSum,
+        initialVal,
+        minNeighbor,
+        maxNeighbor;
+
+    for(p = 0; p < emptyPoints.length; p++) {
+        thisPt = emptyPoints[p];
+        i = thisPt[0];
+        j = thisPt[1];
+        initialVal = z[i][j];
+        neighborSum = 0;
+        neighborCount = 0;
+
+        for(q = 0; q < 4; q++) {
+            neighborShift = NEIGHBORSHIFTS[q];
+            neighborRow = z[i + neighborShift[0]];
+            if(!neighborRow) continue;
+            neighborVal = neighborRow[j + neighborShift[1]];
+            if(neighborVal !== undefined) {
+                if(neighborSum === 0) {
+                    minNeighbor = maxNeighbor = neighborVal;
+                }
+                else {
+                    minNeighbor = Math.min(minNeighbor, neighborVal);
+                    maxNeighbor = Math.max(maxNeighbor, neighborVal);
+                }
+                neighborCount++;
+                neighborSum += neighborVal;
+            }
+        }
+
+        if(neighborCount === 0) {
+            throw 'iterateInterp2d order is wrong: no defined neighbors';
+        }
+
+        // this is the laplace equation interpolation:
+        // each point is just the average of its neighbors
+        // note that this ignores differential x/y scaling
+        // which I think is the right approach, since we
+        // don't know what that scaling means
+        z[i][j] = neighborSum / neighborCount;
+
+        if(initialVal === undefined) {
+            if(neighborCount < 4) maxFractionalChange = 1;
+        }
+        else {
+            // we can make large empty regions converge faster
+            // if we overshoot the change vs the previous value
+            z[i][j] = (1 + overshoot) * z[i][j] - overshoot * initialVal;
+
+            if(maxNeighbor > minNeighbor) {
+                maxFractionalChange = Math.max(maxFractionalChange,
+                    Math.abs(z[i][j] - initialVal) / (maxNeighbor - minNeighbor));
+            }
+        }
+    }
+
+    return maxFractionalChange;
+}
+
+},{"../../components/colorscale/calc":306,"../../lib":349,"../../plots/cartesian/axes":369,"../../plots/plots":413,"../histogram2d/calc":480,"./convert_column_xyz":462,"./has_columns":464,"./max_row_length":467,"fast-isnumeric":74}],461:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+var Plots = require('../../plots/plots');
+var getColorscale = require('../../components/colorscale/get_scale');
+var drawColorbar = require('../../components/colorbar/draw');
+
+
+module.exports = function colorbar(gd, cd) {
+    var trace = cd[0].trace,
+        cbId = 'cb' + trace.uid,
+        scl = getColorscale(trace.colorscale),
+        zmin = trace.zmin,
+        zmax = trace.zmax;
+
+    if(!isNumeric(zmin)) zmin = Lib.aggNums(Math.min, null, trace.z);
+    if(!isNumeric(zmax)) zmax = Lib.aggNums(Math.max, null, trace.z);
+
+    gd._fullLayout._infolayer.selectAll('.' + cbId).remove();
+
+    if(!trace.showscale) {
+        Plots.autoMargin(gd, cbId);
+        return;
+    }
+
+    var cb = cd[0].t.cb = drawColorbar(gd, cbId);
+    cb.fillcolor(d3.scale.linear()
+            .domain(scl.map(function(v) { return zmin + v[0]*(zmax-zmin); }))
+            .range(scl.map(function(v) { return v[1]; })))
+        .filllevels({start: zmin, end: zmax, size: (zmax-zmin)/254})
+        .options(trace.colorbar)();
+
+    Lib.markTime('done colorbar');
+};
+
+},{"../../components/colorbar/draw":302,"../../components/colorscale/get_scale":310,"../../lib":349,"../../plots/plots":413,"d3":70,"fast-isnumeric":74}],462:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+
+module.exports = function convertColumnXYZ(trace, xa, ya) {
+    var xCol = trace.x.slice(),
+        yCol = trace.y.slice(),
+        zCol = trace.z,
+        textCol = trace.text,
+        colLen = Math.min(xCol.length, yCol.length, zCol.length),
+        hasColumnText = (textCol!==undefined && !Array.isArray(textCol[0]));
+
+    var i;
+
+    if(colLen < xCol.length) xCol = xCol.slice(0, colLen);
+    if(colLen < yCol.length) yCol = yCol.slice(0, colLen);
+
+    for(i = 0; i < colLen; i++) {
+        xCol[i] = xa.d2c(xCol[i]);
+        yCol[i] = ya.d2c(yCol[i]);
+    }
+
+    var xColdv = Lib.distinctVals(xCol),
+        x = xColdv.vals,
+        yColdv = Lib.distinctVals(yCol),
+        y = yColdv.vals,
+        z = Lib.init2dArray(y.length, x.length);
+
+    var ix, iy, text;
+
+    if(hasColumnText) text = Lib.init2dArray(y.length, x.length);
+
+    for(i = 0; i < colLen; i++) {
+        ix = Lib.findBin(xCol[i] + xColdv.minDiff / 2, x);
+        iy = Lib.findBin(yCol[i] + yColdv.minDiff / 2, y);
+
+        z[iy][ix] = zCol[i];
+        if(hasColumnText) text[iy][ix] = textCol[i];
+    }
+
+    trace.x = x;
+    trace.y = y;
+    trace.z = z;
+    if(hasColumnText) trace.text = text;
+};
+
+},{"../../lib":349}],463:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var hasColumns = require('./has_columns');
+var handleXYZDefaults = require('./xyz_defaults');
+var colorscaleDefaults = require('../../components/colorscale/defaults');
+var attributes = require('./attributes');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    var len = handleXYZDefaults(traceIn, traceOut, coerce);
+    if(!len) {
+        traceOut.visible = false;
+        return;
+    }
+
+    coerce('text');
+    coerce('zsmooth');
+    coerce('connectgaps', hasColumns(traceOut) && (traceOut.zsmooth !== false));
+
+    colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'});
+};
+
+},{"../../components/colorscale/defaults":308,"../../lib":349,"./attributes":459,"./has_columns":464,"./xyz_defaults":470}],464:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+module.exports = function(trace) {
+    return !Array.isArray(trace.z[0]);
+};
+
+},{}],465:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Fx = require('../../plots/cartesian/graph_interact');
+var Lib = require('../../lib');
+
+
+module.exports = function hoverPoints(pointData, xval, yval, hovermode, contour) {
+    // never let a heatmap override another type as closest point
+    if(pointData.distance < Fx.MAXDIST) return;
+
+    var cd0 = pointData.cd[0],
+        trace = cd0.trace,
+        xa = pointData.xa,
+        ya = pointData.ya,
+        x = cd0.x,
+        y = cd0.y,
+        z = cd0.z,
+        zmask = cd0.zmask,
+        x2 = x,
+        y2 = y,
+        xl,
+        yl,
+        nx,
+        ny;
+
+    if(pointData.index!==false) {
+        try {
+            nx = Math.round(pointData.index[1]);
+            ny = Math.round(pointData.index[0]);
+        }
+        catch(e) {
+            console.log('Error hovering on heatmap, ' +
+                'pointNumber must be [row,col], found:', pointData.index);
+            return;
+        }
+        if(nx<0 || nx>=z[0].length || ny<0 || ny>z.length) {
+            return;
+        }
+    }
+    else if(Fx.inbox(xval-x[0], xval-x[x.length-1]) > Fx.MAXDIST ||
+            Fx.inbox(yval-y[0], yval-y[y.length-1]) > Fx.MAXDIST) {
+        return;
+    }
+    else {
+        if(contour) {
+            var i2;
+            x2 = [2*x[0]-x[1]];
+
+            for(i2=1; i2<x.length; i2++) {
+                x2.push((x[i2]+x[i2-1])/2);
+            }
+            x2.push([2*x[x.length-1]-x[x.length-2]]);
+
+            y2 = [2*y[0]-y[1]];
+            for(i2=1; i2<y.length; i2++) {
+                y2.push((y[i2]+y[i2-1])/2);
+            }
+            y2.push([2*y[y.length-1]-y[y.length-2]]);
+        }
+        nx = Math.max(0,Math.min(x2.length-2, Lib.findBin(xval,x2)));
+        ny = Math.max(0,Math.min(y2.length-2, Lib.findBin(yval,y2)));
+    }
+    var x0 = xa.c2p(x[nx]),
+        x1 = xa.c2p(x[nx+1]),
+        y0 = ya.c2p(y[ny]),
+        y1 = ya.c2p(y[ny+1]);
+    if(contour) {
+        x1=x0;
+        xl=x[nx];
+        y1=y0;
+        yl=y[ny];
+    }
+    else {
+        xl = (x[nx]+x[nx+1])/2;
+        yl = (y[ny]+y[ny+1])/2;
+        if(trace.zsmooth) {
+            x0=x1=(x0+x1)/2;
+            y0=y1=(y0+y1)/2;
+        }
+    }
+
+    var zVal = z[ny][nx];
+    if(zmask && !zmask[ny][nx]) zVal = undefined;
+
+    var text;
+    if(Array.isArray(trace.text) && Array.isArray(trace.text[ny])) {
+        text = trace.text[ny][nx];
+    }
+
+    return [Lib.extendFlat(pointData, {
+        index: [ny, nx],
+        // never let a 2D override 1D type as closest point
+        distance: Fx.MAXDIST + 10,
+        x0: x0,
+        x1: x1,
+        y0: y0,
+        y1: y1,
+        xLabelVal: xl,
+        yLabelVal: yl,
+        zLabelVal: zVal,
+        text: text
+    })];
+};
+
+},{"../../lib":349,"../../plots/cartesian/graph_interact":374}],466:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Heatmap = {};
+
+Heatmap.attributes = require('./attributes');
+Heatmap.supplyDefaults = require('./defaults');
+Heatmap.calc = require('./calc');
+Heatmap.plot = require('./plot');
+Heatmap.colorbar = require('./colorbar');
+Heatmap.style = require('./style');
+Heatmap.hoverPoints = require('./hover');
+
+Heatmap.moduleType = 'trace';
+Heatmap.name = 'heatmap';
+Heatmap.basePlotModule = require('../../plots/cartesian');
+Heatmap.categories = ['cartesian', '2dMap'];
+Heatmap.meta = {
+    
+};
+
+module.exports = Heatmap;
+
+},{"../../plots/cartesian":375,"./attributes":459,"./calc":460,"./colorbar":461,"./defaults":463,"./hover":465,"./plot":468,"./style":469}],467:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+module.exports = function maxRowLength(z) {
+    var len = 0;
+
+    for(var i = 0; i < z.length; i++) {
+        len = Math.max(len, z[i].length);
+    }
+
+    return len;
+};
+
+},{}],468:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var tinycolor = require('tinycolor2');
+
+var Lib = require('../../lib');
+var Plots = require('../../plots/plots');
+var getColorscale = require('../../components/colorscale/get_scale');
+var xmlnsNamespaces = require('../../constants/xmlns_namespaces');
+
+var maxRowLength = require('./max_row_length');
+
+
+module.exports = function(gd, plotinfo, cdheatmaps) {
+    for(var i = 0; i < cdheatmaps.length; i++) {
+        plotOne(gd, plotinfo, cdheatmaps[i]);
+    }
+};
+
+// From http://www.xarg.org/2010/03/generate-client-side-png-files-using-javascript/
+function plotOne(gd, plotinfo, cd) {
+    Lib.markTime('in Heatmap.plot');
+
+    var trace = cd[0].trace,
+        uid = trace.uid,
+        xa = plotinfo.x(),
+        ya = plotinfo.y(),
+        fullLayout = gd._fullLayout,
+        id = 'hm' + uid;
+
+    // in case this used to be a contour map
+    fullLayout._paper.selectAll('.contour' + uid).remove();
+
+    if(trace.visible !== true) {
+        fullLayout._paper.selectAll('.' + id).remove();
+        fullLayout._infolayer.selectAll('.cb' + uid).remove();
+        return;
+    }
+
+    var z = cd[0].z,
+        min = trace.zmin,
+        max = trace.zmax,
+        scl = getColorscale(trace.colorscale),
+        x = cd[0].x,
+        y = cd[0].y,
+        isContour = Plots.traceIs(trace, 'contour'),
+        zsmooth = isContour ? 'best' : trace.zsmooth,
+
+        // get z dims
+        m = z.length,
+        n = maxRowLength(z),
+        xrev = false,
+        left,
+        right,
+        temp,
+        yrev = false,
+        top,
+        bottom,
+        i;
+
+    // TODO: if there are multiple overlapping categorical heatmaps,
+    // or if we allow category sorting, then the categories may not be
+    // sequential... may need to reorder and/or expand z
+
+    // Get edges of png in pixels (xa.c2p() maps axes coordinates to pixel coordinates)
+    // figure out if either axis is reversed (y is usually reversed, in pixel coords)
+    // also clip the image to maximum 50% outside the visible plot area
+    // bigger image lets you pan more naturally, but slows performance.
+    // TODO: use low-resolution images outside the visible plot for panning
+    // these while loops find the first and last brick bounds that are defined
+    // (in case of log of a negative)
+    i = 0;
+    while(left === undefined && i < x.length - 1) {
+        left = xa.c2p(x[i]);
+        i++;
+    }
+    i = x.length - 1;
+    while(right === undefined && i > 0) {
+        right = xa.c2p(x[i]);
+        i--;
+    }
+
+    if(right < left) {
+        temp = right;
+        right = left;
+        left = temp;
+        xrev = true;
+    }
+
+    i = 0;
+    while(top === undefined && i < y.length - 1) {
+        top = ya.c2p(y[i]);
+        i++;
+    }
+    i = y.length - 1;
+    while(bottom === undefined && i > 0) {
+        bottom = ya.c2p(y[i]);
+        i--;
+    }
+
+    if(bottom < top) {
+        temp = top;
+        top = bottom;
+        bottom = temp;
+        yrev = true;
+    }
+
+    // for contours with heatmap fill, we generate the boundaries based on
+    // brick centers but then use the brick edges for drawing the bricks
+    if(isContour) {
+        // TODO: for 'best' smoothing, we really should use the given brick
+        // centers as well as brick bounds in calculating values, in case of
+        // nonuniform brick sizes
+        x = cd[0].xfill;
+        y = cd[0].yfill;
+    }
+
+    // make an image that goes at most half a screen off either side, to keep
+    // time reasonable when you zoom in. if zsmooth is true/fast, don't worry
+    // about this, because zooming doesn't increase number of pixels
+    // if zsmooth is best, don't include anything off screen because it takes too long
+    if(zsmooth !== 'fast') {
+        var extra = zsmooth === 'best' ? 0 : 0.5;
+        left = Math.max(-extra * xa._length, left);
+        right = Math.min((1 + extra) * xa._length, right);
+        top = Math.max(-extra * ya._length, top);
+        bottom = Math.min((1 + extra) * ya._length, bottom);
+    }
+
+    var imageWidth = Math.round(right - left),
+        imageHeight = Math.round(bottom - top);
+
+    // now redraw
+
+    // if image is entirely off-screen, don't even draw it
+    if(imageWidth <= 0 || imageHeight <= 0) return;
+
+    var canvasW, canvasH;
+    if(zsmooth === 'fast') {
+        canvasW = n;
+        canvasH = m;
+    } else {
+        canvasW = imageWidth;
+        canvasH = imageHeight;
+    }
+
+    var canvas = document.createElement('canvas');
+    canvas.width = canvasW;
+    canvas.height = canvasH;
+    var context = canvas.getContext('2d');
+
+    // interpolate for color scale
+    // use an array instead of color strings, so we preserve alpha
+    var s = d3.scale.linear()
+        .domain(scl.map(function(si) { return si[0]; }))
+        .range(scl.map(function(si) {
+            var c = tinycolor(si[1]).toRgb();
+            return [c.r, c.g, c.b, c.a];
+        }))
+        .clamp(true);
+
+    // map brick boundaries to image pixels
+    var xpx,
+        ypx;
+    if(zsmooth === 'fast') {
+        xpx = xrev ?
+            function(index) { return n - 1 - index; } :
+            Lib.identity;
+        ypx = yrev ?
+            function(index) { return m - 1 - index; } :
+            Lib.identity;
+    }
+    else {
+        xpx = function(index) {
+            return Lib.constrain(Math.round(xa.c2p(x[index]) - left),
+                0, imageWidth);
+        };
+        ypx = function(index) {
+            return Lib.constrain(Math.round(ya.c2p(y[index]) - top),
+                0, imageHeight);
+        };
+    }
+
+    // get interpolated bin value. Returns {bin0:closest bin, frac:fractional dist to next, bin1:next bin}
+    function findInterp(pixel, pixArray) {
+        var maxbin = pixArray.length - 2,
+            bin = Lib.constrain(Lib.findBin(pixel, pixArray), 0, maxbin),
+            pix0 = pixArray[bin],
+            pix1 = pixArray[bin + 1],
+            interp = Lib.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxbin),
+            bin0 = Math.round(interp),
+            frac = Math.abs(interp - bin0);
+
+        if(!interp || interp === maxbin || !frac) {
+            return {
+                bin0: bin0,
+                bin1: bin0,
+                frac: 0
+            };
+        }
+        return {
+            bin0: bin0,
+            frac: frac,
+            bin1: Math.round(bin0 + frac / (interp - bin0))
+        };
+    }
+
+    // build the pixel map brick-by-brick
+    // cruise through z-matrix row-by-row
+    // build a brick at each z-matrix value
+    var yi = ypx(0),
+        yb = [yi, yi],
+        xbi = xrev ? 0 : 1,
+        ybi = yrev ? 0 : 1,
+        // for collecting an average luminosity of the heatmap
+        pixcount = 0,
+        rcount = 0,
+        gcount = 0,
+        bcount = 0,
+        xb,
+        j,
+        xi,
+        v,
+        row,
+        c;
+
+    function setColor(v, pixsize) {
+        if(v !== undefined) {
+            var c = s((v - min) / (max - min));
+            c[0] = Math.round(c[0]);
+            c[1] = Math.round(c[1]);
+            c[2] = Math.round(c[2]);
+
+            pixcount += pixsize;
+            rcount += c[0] * pixsize;
+            gcount += c[1] * pixsize;
+            bcount += c[2] * pixsize;
+            return c;
+        }
+        return [0, 0, 0, 0];
+    }
+
+    function putColor(pixels, pxIndex, c) {
+        pixels[pxIndex] = c[0];
+        pixels[pxIndex + 1] = c[1];
+        pixels[pxIndex + 2] = c[2];
+        pixels[pxIndex + 3] = Math.round(c[3] * 255);
+    }
+
+    function interpColor(r0, r1, xinterp, yinterp) {
+        var z00 = r0[xinterp.bin0];
+        if(z00 === undefined) return setColor(undefined, 1);
+
+        var z01 = r0[xinterp.bin1],
+            z10 = r1[xinterp.bin0],
+            z11 = r1[xinterp.bin1],
+            dx = (z01 - z00) || 0,
+            dy = (z10 - z00) || 0,
+            dxy;
+
+        // the bilinear interpolation term needs different calculations
+        // for all the different permutations of missing data
+        // among the neighbors of the main point, to ensure
+        // continuity across brick boundaries.
+        if(z01 === undefined) {
+            if(z11 === undefined) dxy = 0;
+            else if(z10 === undefined) dxy = 2 * (z11 - z00);
+            else dxy = (2 * z11 - z10 - z00) * 2/3;
+        }
+        else if(z11 === undefined) {
+            if(z10 === undefined) dxy = 0;
+            else dxy = (2 * z00 - z01 - z10) * 2/3;
+        }
+        else if(z10 === undefined) dxy = (2 * z11 - z01 - z00) * 2/3;
+        else dxy = (z11 + z00 - z01 - z10);
+
+        return setColor(z00 + xinterp.frac * dx + yinterp.frac * (dy + xinterp.frac * dxy));
+    }
+
+    Lib.markTime('done init png');
+
+    if(zsmooth) { // best or fast, works fastest with imageData
+        var pxIndex = 0,
+            pixels = new Uint8Array(imageWidth * imageHeight * 4);
+
+        if(zsmooth === 'best') {
+            var xPixArray = new Array(x.length),
+                yPixArray = new Array(y.length),
+                xinterpArray = new Array(imageWidth),
+                yinterp,
+                r0,
+                r1;
+
+            // first make arrays of x and y pixel locations of brick boundaries
+            for(i = 0; i < x.length; i++) xPixArray[i] = Math.round(xa.c2p(x[i]) - left);
+            for(i = 0; i < y.length; i++) yPixArray[i] = Math.round(ya.c2p(y[i]) - top);
+
+            // then make arrays of interpolations
+            // (bin0=closest, bin1=next, frac=fractional dist.)
+            for(i = 0; i < imageWidth; i++) xinterpArray[i] = findInterp(i, xPixArray);
+
+            // now do the interpolations and fill the png
+            for(j = 0; j < imageHeight; j++) {
+                yinterp = findInterp(j, yPixArray);
+                r0 = z[yinterp.bin0];
+                r1 = z[yinterp.bin1];
+                for(i = 0; i < imageWidth; i++, pxIndex += 4) {
+                    c = interpColor(r0, r1, xinterpArray[i], yinterp);
+                    putColor(pixels, pxIndex, c);
+                }
+            }
+        }
+        else { // zsmooth = fast
+            for(j = 0; j < m; j++) {
+                row = z[j];
+                yb = ypx(j);
+                for(i = 0; i < n; i++) {
+                    c = setColor(row[i],1);
+                    pxIndex = (yb * imageWidth + xpx(i)) * 4;
+                    putColor(pixels, pxIndex, c);
+                }
+            }
+        }
+
+        var imageData = context.createImageData(imageWidth, imageHeight);
+        imageData.data.set(pixels);
+        context.putImageData(imageData, 0, 0);
+    } else { // zsmooth = false -> filling potentially large bricks works fastest with fillRect
+        for(j = 0; j < m; j++) {
+            row = z[j];
+            yb.reverse();
+            yb[ybi] = ypx(j + 1);
+            if(yb[0] === yb[1] || yb[0] === undefined || yb[1] === undefined) {
+                continue;
+            }
+            xi = xpx(0);
+            xb = [xi, xi];
+            for(i = 0; i < n; i++) {
+                // build one color brick!
+                xb.reverse();
+                xb[xbi] = xpx(i + 1);
+                if(xb[0] === xb[1] || xb[0] === undefined || xb[1] === undefined) {
+                    continue;
+                }
+                v = row[i];
+                c = setColor(v, (xb[1] - xb[0]) * (yb[1] - yb[0]));
+                context.fillStyle = 'rgba(' + c.join(',') + ')';
+                context.fillRect(xb[0], yb[0], (xb[1] - xb[0]), (yb[1] - yb[0]));
+            }
+        }
+    }
+
+    Lib.markTime('done filling png');
+
+    rcount = Math.round(rcount / pixcount);
+    gcount = Math.round(gcount/ pixcount);
+    bcount = Math.round(bcount / pixcount);
+    var avgColor = tinycolor('rgb(' + rcount + ',' + gcount + ',' + bcount + ')');
+
+    gd._hmpixcount = (gd._hmpixcount||0) + pixcount;
+    gd._hmlumcount = (gd._hmlumcount||0) + pixcount * avgColor.getLuminance();
+
+    var plotgroup = plotinfo.plot.select('.imagelayer')
+        .selectAll('g.hm.' + id)
+        .data([0]);
+    plotgroup.enter().append('g')
+        .classed('hm', true)
+        .classed(id, true);
+    plotgroup.exit().remove();
+
+    var image3 = plotgroup.selectAll('image')
+        .data(cd);
+    image3.enter().append('svg:image');
+    image3.exit().remove();
+
+    image3.attr({
+        xmlns: xmlnsNamespaces.svg,
+        'xlink:href': canvas.toDataURL('image/png'),
+        height: imageHeight,
+        width: imageWidth,
+        x: left,
+        y: top,
+        preserveAspectRatio: 'none'
+    });
+
+    Lib.markTime('done showing png');
+}
+
+},{"../../components/colorscale/get_scale":310,"../../constants/xmlns_namespaces":338,"../../lib":349,"../../plots/plots":413,"./max_row_length":467,"d3":70,"tinycolor2":229}],469:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+module.exports = function style(gd) {
+    d3.select(gd).selectAll('image')
+        .style('opacity', function(d) {
+            return d.trace.opacity;
+        });
+};
+
+},{"d3":70}],470:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var hasColumns = require('./has_columns');
+
+
+module.exports = function handleXYZDefaults(traceIn, traceOut, coerce) {
+    var z = coerce('z');
+    var x, y;
+
+    if(z===undefined || !z.length) return 0;
+
+    if(hasColumns(traceIn)) {
+        x = coerce('x');
+        y = coerce('y');
+
+        // column z must be accompanied by 'x' and 'y' arrays
+        if(!x || !y) return 0;
+    }
+    else {
+        x = coordDefaults('x', coerce);
+        y = coordDefaults('y', coerce);
+
+        // TODO put z validation elsewhere
+        if(!isValidZ(z)) return 0;
+
+        coerce('transpose');
+    }
+
+    return traceOut.z.length;
+};
+
+function coordDefaults(coordStr, coerce) {
+    var coord = coerce(coordStr),
+        coordType = coord ?
+            coerce(coordStr + 'type', 'array') :
+            'scaled';
+
+    if(coordType === 'scaled') {
+        coerce(coordStr + '0');
+        coerce('d' + coordStr);
+    }
+
+    return coord;
+}
+
+function isValidZ(z) {
+    var allRowsAreArrays = true,
+        oneRowIsFilled = false,
+        hasOneNumber = false,
+        zi;
+
+    /*
+     * Without this step:
+     *
+     * hasOneNumber = false breaks contour but not heatmap
+     * allRowsAreArrays = false breaks contour but not heatmap
+     * oneRowIsFilled = false breaks both
+     */
+
+    for(var i = 0; i < z.length; i++) {
+        zi = z[i];
+        if(!Array.isArray(zi)) {
+            allRowsAreArrays = false;
+            break;
+        }
+        if(zi.length > 0) oneRowIsFilled = true;
+        for(var j = 0; j < zi.length; j++) {
+            if(isNumeric(zi[j])) {
+                hasOneNumber = true;
+                break;
+            }
+        }
+    }
+
+    return (allRowsAreArrays && oneRowIsFilled && hasOneNumber);
+}
+
+},{"./has_columns":464,"fast-isnumeric":74}],471:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var barAttrs = require('../bar/attributes');
+var extendFlat = require('../../lib').extendFlat;
+
+var barMarkerAttrs = barAttrs.marker;
+var barMarkerLineAttrs = barMarkerAttrs.line;
+
+
+module.exports = {
+    x: {
+        valType: 'data_array',
+        
+    },
+    y: {
+        valType: 'data_array',
+        
+    },
+
+    text: barAttrs.text,
+    orientation: barAttrs.orientation,
+
+    histfunc: {
+        valType: 'enumerated',
+        values: ['count', 'sum', 'avg', 'min', 'max'],
+        
+        dflt: 'count',
+        
+    },
+    histnorm: {
+        valType: 'enumerated',
+        values: ['', 'percent', 'probability', 'density', 'probability density'],
+        dflt: '',
+        
+        
+    },
+
+    autobinx: {
+        valType: 'boolean',
+        dflt: true,
+        
+        
+    },
+    nbinsx: {
+        valType: 'integer',
+        min: 0,
+        dflt: 0,
+        
+        
+    },
+    xbins: makeBinsAttr('x'),
+
+    autobiny: {
+        valType: 'boolean',
+        dflt: true,
+        
+        
+    },
+    nbinsy: {
+        valType: 'integer',
+        min: 0,
+        dflt: 0,
+        
+        
+    },
+    ybins: makeBinsAttr('y'),
+
+    marker: {
+        color: barMarkerAttrs.color,
+        colorscale: barMarkerAttrs.colorscale,
+        cauto: barMarkerAttrs.cauto,
+        cmax: barMarkerAttrs.cmax,
+        cmin: barMarkerAttrs.cmin,
+        autocolorscale: barMarkerAttrs.autocolorscale,
+        reversescale: barMarkerAttrs.reversescale,
+        showscale: barMarkerAttrs.showscale,
+        line: {
+            color: barMarkerLineAttrs.color,
+            colorscale: barMarkerLineAttrs.colorscale,
+            cauto: barMarkerLineAttrs.cauto,
+            cmax: barMarkerLineAttrs.cmax,
+            cmin: barMarkerLineAttrs.cmin,
+            autocolorscale: barMarkerLineAttrs.autocolorscale,
+            reversescale: barMarkerLineAttrs.reversescale,
+            width: extendFlat({}, barMarkerLineAttrs.width, {dflt: 0})
+        }
+    },
+
+    _nestedModules: {
+        'error_y': 'ErrorBars',
+        'error_x': 'ErrorBars',
+        'marker.colorbar': 'Colorbar'
+    },
+
+    _deprecated: {
+        bardir: barAttrs._deprecated.bardir
+    }
+};
+
+function makeBinsAttr(axLetter) {
+    return {
+        start: {
+            valType: 'number',
+            dflt: null,
+            
+            
+        },
+        end: {
+            valType: 'number',
+            dflt: null,
+            
+            
+        },
+        size: {
+            valType: 'any', // for date axes
+            dflt: 1,
+            
+            
+        }
+    };
+}
+
+},{"../../lib":349,"../bar/attributes":425}],472:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+
+module.exports = function doAvg(size, counts) {
+    var nMax = size.length,
+        total = 0;
+    for(var i=0; i<nMax; i++) {
+        if(counts[i]) {
+            size[i] /= counts[i];
+            total += size[i];
+        }
+        else size[i] = null;
+    }
+    return total;
+};
+
+},{}],473:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+
+module.exports = function handleBinDefaults(traceIn, traceOut, coerce, binDirections) {
+    coerce('histnorm');
+
+    binDirections.forEach(function(binDirection) {
+        // data being binned - note that even though it's a little weird,
+        // it's possible to have bins without data, if there's inferred data
+        var binstrt = coerce(binDirection + 'bins.start'),
+            binend = coerce(binDirection + 'bins.end'),
+            autobin = coerce('autobin' + binDirection, !(binstrt && binend));
+
+        if(autobin) coerce('nbins' + binDirection);
+        else coerce(binDirection + 'bins.size');
+    });
+
+    return traceOut;
+};
+
+},{}],474:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+
+module.exports = {
+    count: function(n, i, size) {
+        size[n]++;
+        return 1;
+    },
+
+    sum: function(n, i, size, counterData) {
+        var v = counterData[i];
+        if(isNumeric(v)) {
+            v = Number(v);
+            size[n] += v;
+            return v;
+        }
+        return 0;
+    },
+
+    avg: function(n, i, size, counterData, counts) {
+        var v = counterData[i];
+        if(isNumeric(v)) {
+            v = Number(v);
+            size[n] += v;
+            counts[n]++;
+        }
+        return 0;
+    },
+
+    min: function(n, i, size, counterData) {
+        var v = counterData[i];
+        if(isNumeric(v)) {
+            v = Number(v);
+            if(!isNumeric(size[n])) {
+                size[n] = v;
+                return v;
+            }
+            else if(size[n]>v) {
+                size[n] = v;
+                return v-size[n];
+            }
+        }
+        return 0;
+    },
+
+    max: function(n, i, size, counterData) {
+        var v = counterData[i];
+        if(isNumeric(v)) {
+            v = Number(v);
+            if(!isNumeric(size[n])) {
+                size[n] = v;
+                return v;
+            }
+            else if(size[n]<v) {
+                size[n] = v;
+                return v-size[n];
+            }
+        }
+        return 0;
+    }
+};
+
+},{"fast-isnumeric":74}],475:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+var Axes = require('../../plots/cartesian/axes');
+
+var binFunctions = require('./bin_functions');
+var normFunctions = require('./norm_functions');
+var doAvg = require('./average');
+
+
+module.exports = function calc(gd, trace) {
+    // ignore as much processing as possible (and including in autorange) if bar is not visible
+    if(trace.visible !== true) return;
+
+    // depending on orientation, set position and size axes and data ranges
+    // note: this logic for choosing orientation is duplicated in graph_obj->setstyles
+    var pos = [],
+        size = [],
+        i,
+        pa = Axes.getFromId(gd,
+            trace.orientation==='h' ? (trace.yaxis || 'y') : (trace.xaxis || 'x')),
+        maindata = trace.orientation==='h' ? 'y' : 'x',
+        counterdata = {x: 'y', y: 'x'}[maindata];
+
+    // prepare the raw data
+    var pos0 = pa.makeCalcdata(trace, maindata);
+    // calculate the bins
+    if((trace['autobin' + maindata]!==false) || !(maindata + 'bins' in trace)) {
+        trace[maindata + 'bins'] = Axes.autoBin(pos0, pa, trace['nbins' + maindata]);
+
+        // copy bin info back to the source data.
+        trace._input[maindata + 'bins'] = trace[maindata + 'bins'];
+    }
+
+    var binspec = trace[maindata + 'bins'],
+        allbins = typeof binspec.size === 'string',
+        bins = allbins ? [] : binspec,
+        // make the empty bin array
+        i2,
+        binend,
+        n,
+        inc = [],
+        counts = [],
+        total = 0,
+        norm = trace.histnorm,
+        func = trace.histfunc,
+        densitynorm = norm.indexOf('density')!==-1,
+        extremefunc = func==='max' || func==='min',
+        sizeinit = extremefunc ? null : 0,
+        binfunc = binFunctions.count,
+        normfunc = normFunctions[norm],
+        doavg = false,
+        rawCounterData;
+
+    if(Array.isArray(trace[counterdata]) && func!=='count') {
+        rawCounterData = trace[counterdata];
+        doavg = func==='avg';
+        binfunc = binFunctions[func];
+    }
+
+    // create the bins (and any extra arrays needed)
+    // assume more than 5000 bins is an error, so we don't crash the browser
+    i = binspec.start;
+    // decrease end a little in case of rounding errors
+    binend = binspec.end +
+        (binspec.start - Axes.tickIncrement(binspec.start, binspec.size)) / 1e6;
+    while(i<binend && pos.length<5000) {
+        i2 = Axes.tickIncrement(i, binspec.size);
+        pos.push((i + i2) / 2);
+        size.push(sizeinit);
+        // nonuniform bins (like months) we need to search,
+        // rather than straight calculate the bin we're in
+        if(allbins) bins.push(i);
+        // nonuniform bins also need nonuniform normalization factors
+        if(densitynorm) inc.push(1 / (i2 - i));
+        if(doavg) counts.push(0);
+        i = i2;
+    }
+
+    var nMax = size.length;
+    // bin the data
+    for(i=0; i<pos0.length; i++) {
+        n = Lib.findBin(pos0[i], bins);
+        if(n>=0 && n<nMax) total += binfunc(n, i, size, rawCounterData, counts);
+    }
+
+    // average and/or normalize the data, if needed
+    if(doavg) total = doAvg(size, counts);
+    if(normfunc) normfunc(size, total, inc);
+
+    var serieslen = Math.min(pos.length, size.length),
+        cd = [],
+        firstNonzero = 0,
+        lastNonzero = serieslen-1;
+    // look for empty bins at the ends to remove, so autoscale omits them
+    for(i=0; i<serieslen; i++) {
+        if(size[i]) {
+            firstNonzero = i;
+            break;
+        }
+    }
+    for(i=serieslen-1; i>firstNonzero; i--) {
+        if(size[i]) {
+            lastNonzero = i;
+            break;
+        }
+    }
+
+    // create the "calculated data" to plot
+    for(i=firstNonzero; i<=lastNonzero; i++) {
+        if((isNumeric(pos[i]) && isNumeric(size[i]))) {
+            cd.push({p: pos[i], s: size[i], b: 0});
+        }
+    }
+
+    return cd;
+};
+
+},{"../../lib":349,"../../plots/cartesian/axes":369,"./average":472,"./bin_functions":474,"./norm_functions":478,"fast-isnumeric":74}],476:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+var Color = require('../../components/color');
+
+var handleBinDefaults = require('./bin_defaults');
+var handleStyleDefaults = require('../bar/style_defaults');
+var errorBarsSupplyDefaults = require('../../components/errorbars/defaults');
+var attributes = require('./attributes');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    var x = coerce('x'),
+        y = coerce('y');
+
+    coerce('text');
+
+    var orientation = coerce('orientation', (y && !x) ? 'h' : 'v'),
+        sample = traceOut[orientation==='v' ? 'x' : 'y'];
+
+    if(!(sample && sample.length)) {
+        traceOut.visible = false;
+        return;
+    }
+
+    var hasAggregationData = traceOut[orientation==='h' ? 'x' : 'y'];
+    if(hasAggregationData) coerce('histfunc');
+
+    var binDirections = (orientation==='h') ? ['y'] : ['x'];
+    handleBinDefaults(traceIn, traceOut, coerce, binDirections);
+
+    handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);
+
+    // override defaultColor for error bars with defaultLine
+    errorBarsSupplyDefaults(traceIn, traceOut, Color.defaultLine, {axis: 'y'});
+    errorBarsSupplyDefaults(traceIn, traceOut, Color.defaultLine, {axis: 'x', inherit: 'y'});
+};
+
+},{"../../components/color":299,"../../components/errorbars/defaults":322,"../../lib":349,"../bar/style_defaults":435,"./attributes":471,"./bin_defaults":473}],477:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+/**
+ * Histogram has its own attribute, defaults and calc steps,
+ * but uses bar's plot to display
+ * and bar's setPositions for stacking and grouping
+ */
+
+/**
+ * histogram errorBarsOK is debatable, but it's put in for backward compat.
+ * there are use cases for it - sqrt for a simple histogram works right now,
+ * constant and % work but they're not so meaningful. I guess it could be cool
+ * to allow quadrature combination of errors in summed histograms...
+ */
+
+
+var Histogram = {};
+
+Histogram.attributes = require('./attributes');
+Histogram.layoutAttributes = require('../bar/layout_attributes');
+Histogram.supplyDefaults = require('./defaults');
+Histogram.supplyLayoutDefaults = require('../bar/layout_defaults');
+Histogram.calc = require('./calc');
+Histogram.setPositions = require('../bar/set_positions');
+Histogram.plot = require('../bar/plot');
+Histogram.style = require('../bar/style');
+Histogram.colorbar = require('../scatter/colorbar');
+Histogram.hoverPoints = require('../bar/hover');
+
+Histogram.moduleType = 'trace';
+Histogram.name = 'histogram';
+Histogram.basePlotModule = require('../../plots/cartesian');
+Histogram.categories = ['cartesian', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend'];
+Histogram.meta = {
+    
+};
+
+module.exports = Histogram;
+
+},{"../../plots/cartesian":375,"../bar/hover":428,"../bar/layout_attributes":430,"../bar/layout_defaults":431,"../bar/plot":432,"../bar/set_positions":433,"../bar/style":434,"../scatter/colorbar":505,"./attributes":471,"./calc":475,"./defaults":476}],478:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+
+module.exports = {
+    percent: function(size, total) {
+        var nMax = size.length,
+            norm = 100/total;
+        for(var n=0; n<nMax; n++) size[n] *= norm;
+    },
+    probability: function(size, total) {
+        var nMax = size.length;
+        for(var n=0; n<nMax; n++) size[n] /= total;
+    },
+    density: function(size, total, inc, yinc) {
+        var nMax = size.length;
+        yinc = yinc||1;
+        for(var n=0; n<nMax; n++) size[n] *= inc[n]*yinc;
+    },
+    'probability density': function(size, total, inc, yinc) {
+        var nMax = size.length;
+        if(yinc) total/=yinc;
+        for(var n=0; n<nMax; n++) size[n] *= inc[n]/total;
+    }
+};
+
+},{}],479:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var histogramAttrs = require('../histogram/attributes');
+var heatmapAttrs = require('../heatmap/attributes');
+
+module.exports = {
+    x: histogramAttrs.x,
+    y: histogramAttrs.y,
+
+    z: {
+        valType: 'data_array',
+        
+    },
+    marker: {
+        color: {
+            valType: 'data_array',
+            
+        }
+    },
+
+    histnorm: histogramAttrs.histnorm,
+    histfunc: histogramAttrs.histfunc,
+    autobinx: histogramAttrs.autobinx,
+    nbinsx: histogramAttrs.nbinsx,
+    xbins: histogramAttrs.xbins,
+    autobiny: histogramAttrs.autobiny,
+    nbinsy: histogramAttrs.nbinsy,
+    ybins: histogramAttrs.ybins,
+
+    zauto: heatmapAttrs.zauto,
+    zmin: heatmapAttrs.zmin,
+    zmax: heatmapAttrs.zmax,
+    colorscale: heatmapAttrs.colorscale,
+    autocolorscale: heatmapAttrs.autocolorscale,
+    reversescale: heatmapAttrs.reversescale,
+    showscale: heatmapAttrs.showscale,
+
+    zsmooth: heatmapAttrs.zsmooth,
+
+    _nestedModules: {
+        'colorbar': 'Colorbar'
+    }
+};
+
+},{"../heatmap/attributes":459,"../histogram/attributes":471}],480:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+var Axes = require('../../plots/cartesian/axes');
+
+var binFunctions = require('../histogram/bin_functions');
+var normFunctions = require('../histogram/norm_functions');
+var doAvg = require('../histogram/average');
+
+
+module.exports = function calc(gd, trace) {
+    var xa = Axes.getFromId(gd, trace.xaxis||'x'),
+        x = trace.x ? xa.makeCalcdata(trace, 'x') : [],
+        ya = Axes.getFromId(gd, trace.yaxis||'y'),
+        y = trace.y ? ya.makeCalcdata(trace, 'y') : [],
+        x0,
+        dx,
+        y0,
+        dy,
+        z,
+        i;
+
+    var serieslen = Math.min(x.length, y.length);
+    if(x.length>serieslen) x.splice(serieslen, x.length-serieslen);
+    if(y.length>serieslen) y.splice(serieslen, y.length-serieslen);
+
+    Lib.markTime('done convert data');
+
+    // calculate the bins
+    if(trace.autobinx || !('xbins' in trace)) {
+        trace.xbins = Axes.autoBin(x, xa, trace.nbinsx, '2d');
+        if(trace.type==='histogram2dcontour') {
+            trace.xbins.start -= trace.xbins.size;
+            trace.xbins.end += trace.xbins.size;
+        }
+
+        // copy bin info back to the source data.
+        trace._input.xbins = trace.xbins;
+    }
+    if(trace.autobiny || !('ybins' in trace)) {
+        trace.ybins = Axes.autoBin(y,ya,trace.nbinsy,'2d');
+        if(trace.type==='histogram2dcontour') {
+            trace.ybins.start -= trace.ybins.size;
+            trace.ybins.end += trace.ybins.size;
+        }
+        trace._input.ybins = trace.ybins;
+    }
+    Lib.markTime('done autoBin');
+
+    // make the empty bin array & scale the map
+    z = [];
+    var onecol = [],
+        zerocol = [],
+        xbins = (typeof(trace.xbins.size)==='string') ? [] : trace.xbins,
+        ybins = (typeof(trace.xbins.size)==='string') ? [] : trace.ybins,
+        total = 0,
+        n,
+        m,
+        counts=[],
+        norm = trace.histnorm,
+        func = trace.histfunc,
+        densitynorm = (norm.indexOf('density')!==-1),
+        extremefunc = (func==='max' || func==='min'),
+        sizeinit = (extremefunc ? null : 0),
+        binfunc = binFunctions.count,
+        normfunc = normFunctions[norm],
+        doavg = false,
+        xinc = [],
+        yinc = [];
+
+    // set a binning function other than count?
+    // for binning functions: check first for 'z',
+    // then 'mc' in case we had a colored scatter plot
+    // and want to transfer these colors to the 2D histo
+    // TODO: this is why we need a data picker in the popover...
+    var rawCounterData = ('z' in trace) ?
+        trace.z :
+        (('marker' in trace && Array.isArray(trace.marker.color)) ?
+            trace.marker.color : '');
+    if(rawCounterData && func!=='count') {
+        doavg = func==='avg';
+        binfunc = binFunctions[func];
+    }
+
+    // decrease end a little in case of rounding errors
+    var binspec = trace.xbins,
+        binend = binspec.end +
+            (binspec.start - Axes.tickIncrement(binspec.start, binspec.size)) / 1e6;
+
+    for(i=binspec.start; i<binend;
+            i=Axes.tickIncrement(i,binspec.size)) {
+        onecol.push(sizeinit);
+        if(Array.isArray(xbins)) xbins.push(i);
+        if(doavg) zerocol.push(0);
+    }
+    if(Array.isArray(xbins)) xbins.push(i);
+
+    var nx = onecol.length;
+    x0 = trace.xbins.start;
+    dx = (i-x0)/nx;
+    x0 += dx/2;
+
+    binspec = trace.ybins;
+    binend = binspec.end +
+        (binspec.start - Axes.tickIncrement(binspec.start, binspec.size)) / 1e6;
+
+    for(i=binspec.start; i<binend;
+            i=Axes.tickIncrement(i,binspec.size)) {
+        z.push(onecol.concat());
+        if(Array.isArray(ybins)) ybins.push(i);
+        if(doavg) counts.push(zerocol.concat());
+    }
+    if(Array.isArray(ybins)) ybins.push(i);
+
+    var ny = z.length;
+    y0 = trace.ybins.start;
+    dy = (i-y0)/ny;
+    y0 += dy/2;
+
+    if(densitynorm) {
+        xinc = onecol.map(function(v,i) {
+            if(Array.isArray(xbins)) return 1/(xbins[i+1]-xbins[i]);
+            return 1/dx;
+        });
+        yinc = z.map(function(v,i) {
+            if(Array.isArray(ybins)) return 1/(ybins[i+1]-ybins[i]);
+            return 1/dy;
+        });
+    }
+
+
+    Lib.markTime('done making bins');
+    // put data into bins
+    for(i=0; i<serieslen; i++) {
+        n = Lib.findBin(x[i],xbins);
+        m = Lib.findBin(y[i],ybins);
+        if(n>=0 && n<nx && m>=0 && m<ny) {
+            total += binfunc(n, i, z[m], rawCounterData, counts[m]);
+        }
+    }
+    // normalize, if needed
+    if(doavg) {
+        for(m=0; m<ny; m++) total += doAvg(z[m], counts[m]);
+    }
+    if(normfunc) {
+        for(m=0; m<ny; m++) normfunc(z[m], total, xinc, yinc[m]);
+    }
+    Lib.markTime('done binning');
+
+    return {
+        x: x,
+        x0: x0,
+        dx: dx,
+        y: y,
+        y0: y0,
+        dy: dy,
+        z: z
+    };
+};
+
+},{"../../lib":349,"../../plots/cartesian/axes":369,"../histogram/average":472,"../histogram/bin_functions":474,"../histogram/norm_functions":478}],481:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var handleSampleDefaults = require('./sample_defaults');
+var colorscaleDefaults = require('../../components/colorscale/defaults');
+var attributes = require('./attributes');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, layout) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    handleSampleDefaults(traceIn, traceOut, coerce);
+
+    coerce('zsmooth');
+
+    colorscaleDefaults(
+        traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
+    );
+};
+
+},{"../../components/colorscale/defaults":308,"../../lib":349,"./attributes":479,"./sample_defaults":483}],482:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Histogram2D = {};
+
+Histogram2D.attributes = require('./attributes');
+Histogram2D.supplyDefaults = require('./defaults');
+Histogram2D.calc = require('../heatmap/calc');
+Histogram2D.plot = require('../heatmap/plot');
+Histogram2D.colorbar = require('../heatmap/colorbar');
+Histogram2D.style = require('../heatmap/style');
+Histogram2D.hoverPoints = require('../heatmap/hover');
+
+Histogram2D.moduleType = 'trace';
+Histogram2D.name = 'histogram2d';
+Histogram2D.basePlotModule = require('../../plots/cartesian');
+Histogram2D.categories = ['cartesian', '2dMap', 'histogram'];
+Histogram2D.meta = {
+    
+    
+};
+
+module.exports = Histogram2D;
+
+},{"../../plots/cartesian":375,"../heatmap/calc":460,"../heatmap/colorbar":461,"../heatmap/hover":465,"../heatmap/plot":468,"../heatmap/style":469,"./attributes":479,"./defaults":481}],483:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var handleBinDefaults = require('../histogram/bin_defaults');
+
+
+module.exports = function handleSampleDefaults(traceIn, traceOut, coerce) {
+    var x = coerce('x'),
+        y = coerce('y');
+
+    // we could try to accept x0 and dx, etc...
+    // but that's a pretty weird use case.
+    // for now require both x and y explicitly specified.
+    if(!(x && x.length && y && y.length)) {
+        traceOut.visible = false;
+        return;
+    }
+
+    // if marker.color is an array, we can use it in aggregation instead of z
+    var hasAggregationData = coerce('z') || coerce('marker.color');
+
+    if(hasAggregationData) coerce('histfunc');
+
+    var binDirections = ['x', 'y'];
+    handleBinDefaults(traceIn, traceOut, coerce, binDirections);
+};
+
+},{"../histogram/bin_defaults":473}],484:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var histogram2dAttrs = require('../histogram2d/attributes');
+var contourAttrs = require('../contour/attributes');
+
+module.exports = {
+    x: histogram2dAttrs.x,
+    y: histogram2dAttrs.y,
+    z: histogram2dAttrs.z,
+    marker: histogram2dAttrs.marker,
+
+    histnorm: histogram2dAttrs.histnorm,
+    histfunc: histogram2dAttrs.histfunc,
+    autobinx: histogram2dAttrs.autobinx,
+    nbinsx: histogram2dAttrs.nbinsx,
+    xbins: histogram2dAttrs.xbins,
+    autobiny: histogram2dAttrs.autobiny,
+    nbinsy: histogram2dAttrs.nbinsy,
+    ybins: histogram2dAttrs.ybins,
+
+    zauto: contourAttrs.zauto,
+    zmin: contourAttrs.zmin,
+    zmax: contourAttrs.zmax,
+    colorscale: contourAttrs.colorscale,
+    autocolorscale: contourAttrs.autocolorscale,
+    reversescale: contourAttrs.reversescale,
+    showscale: contourAttrs.showscale,
+
+    autocontour: contourAttrs.autocontour,
+    ncontours: contourAttrs.ncontours,
+    contours: contourAttrs.contours,
+    line: contourAttrs.line,
+
+    _nestedModules: {
+        'colorbar': 'Colorbar'
+    }
+};
+
+},{"../contour/attributes":450,"../histogram2d/attributes":479}],485:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var handleSampleDefaults = require('../histogram2d/sample_defaults');
+var handleStyleDefaults = require('../contour/style_defaults');
+var attributes = require('./attributes');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    handleSampleDefaults(traceIn, traceOut, coerce);
+
+    var contourStart = Lib.coerce2(traceIn, traceOut, attributes, 'contours.start'),
+        contourEnd = Lib.coerce2(traceIn, traceOut, attributes, 'contours.end'),
+        autocontour = coerce('autocontour', !(contourStart && contourEnd));
+
+    if(autocontour) coerce('ncontours');
+    else coerce('contours.size');
+
+    handleStyleDefaults(traceIn, traceOut, coerce, layout);
+};
+
+},{"../../lib":349,"../contour/style_defaults":458,"../histogram2d/sample_defaults":483,"./attributes":484}],486:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Histogram2dContour = {};
+
+Histogram2dContour.attributes = require('./attributes');
+Histogram2dContour.supplyDefaults = require('./defaults');
+Histogram2dContour.calc = require('../contour/calc');
+Histogram2dContour.plot = require('../contour/plot');
+Histogram2dContour.style = require('../contour/style');
+Histogram2dContour.colorbar = require('../contour/colorbar');
+Histogram2dContour.hoverPoints = require('../contour/hover');
+
+Histogram2dContour.moduleType = 'trace';
+Histogram2dContour.name = 'histogram2dcontour';
+Histogram2dContour.basePlotModule = require('../../plots/cartesian');
+Histogram2dContour.categories = ['cartesian', '2dMap', 'contour', 'histogram'];
+Histogram2dContour.meta = {
+    
+    
+};
+
+module.exports = Histogram2dContour;
+
+},{"../../plots/cartesian":375,"../contour/calc":451,"../contour/colorbar":452,"../contour/hover":454,"../contour/plot":456,"../contour/style":457,"./attributes":484,"./defaults":485}],487:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var colorscaleAttrs = require('../../components/colorscale/attributes');
+var surfaceAtts = require('../surface/attributes');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+
+module.exports = {
+    x: {
+        valType: 'data_array',
+        
+    },
+    y: {
+        valType: 'data_array',
+        
+    },
+    z: {
+        valType: 'data_array',
+        
+    },
+
+    i: {
+        valType: 'data_array',
+        
+    },
+    j: {
+        valType: 'data_array',
+        
+    },
+    k: {
+        valType: 'data_array',
+        
+    },
+
+    delaunayaxis: {
+        valType: 'enumerated',
+        
+        values: [ 'x', 'y', 'z' ],
+        dflt: 'z',
+        
+    },
+
+    alphahull: {
+        valType: 'number',
+        
+        dflt: -1,
+        
+    },
+
+    intensity: {
+        valType: 'data_array',
+        
+    },
+
+    //Color field
+    color: {
+        valType: 'color',
+        
+        
+    },
+    vertexcolor: {
+        valType: 'data_array',  // FIXME: this should be a color array
+        
+        
+    },
+    facecolor: {
+        valType: 'data_array',
+        
+        
+    },
+
+    //Opacity
+    opacity: extendFlat({}, surfaceAtts.opacity),
+
+    //Flat shaded mode
+    flatshading: {
+        valType: 'boolean',
+        
+        dflt: false,
+        
+    },
+
+    contour: {
+        show: extendFlat({}, surfaceAtts.contours.x.show, {
+            
+        }),
+        color: extendFlat({}, surfaceAtts.contours.x.color),
+        width: extendFlat({}, surfaceAtts.contours.x.width)
+    },
+
+    colorscale: colorscaleAttrs.colorscale,
+    reversescale: colorscaleAttrs.reversescale,
+    showscale: colorscaleAttrs.showscale,
+
+    lighting: extendFlat({}, surfaceAtts.lighting),
+
+    _nestedModules: {  // nested module coupling
+        'colorbar': 'Colorbar'
+    }
+};
+
+},{"../../components/colorscale/attributes":305,"../../lib/extend":345,"../surface/attributes":538}],488:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var createMesh = require('gl-mesh3d');
+var tinycolor = require('tinycolor2');
+var triangulate = require('delaunay-triangulate');
+var alphaShape = require('alpha-shape');
+var convexHull = require('convex-hull');
+
+var str2RgbaArray = require('../../lib/str2rgbarray');
+
+
+function Mesh3DTrace(scene, mesh, uid) {
+    this.scene = scene;
+    this.uid = uid;
+    this.mesh = mesh;
+    this.name = '';
+    this.color = '#fff';
+    this.data = null;
+    this.showContour = false;
+}
+
+var proto = Mesh3DTrace.prototype;
+
+proto.handlePick = function(selection) {
+    if(selection.object === this.mesh) {
+        var selectIndex = selection.data.index;
+
+        selection.traceCoordinate = [
+            this.data.x[selectIndex],
+            this.data.y[selectIndex],
+            this.data.z[selectIndex]
+        ];
+
+        return true;
+    }
+};
+
+function parseColorScale(colorscale) {
+    return colorscale.map(function(elem) {
+        var index = elem[0];
+        var color = tinycolor(elem[1]);
+        var rgb = color.toRgb();
+        return {
+            index: index,
+            rgb: [rgb.r, rgb.g, rgb.b, 1]
+        };
+    });
+}
+
+function parseColorArray(colors) {
+    return colors.map(str2RgbaArray);
+}
+
+function zip3(x, y, z) {
+    var result = new Array(x.length);
+    for(var i=0; i<x.length; ++i) {
+        result[i] = [x[i], y[i], z[i]];
+    }
+    return result;
+}
+
+proto.update = function(data) {
+    var scene = this.scene,
+        layout = scene.fullSceneLayout;
+
+    this.data = data;
+
+    //Unpack position data
+    function toDataCoords(axis, coord, scale) {
+        return coord.map(function(x) {
+            return axis.d2l(x) * scale;
+        });
+    }
+
+    var positions = zip3(
+      toDataCoords(layout.xaxis, data.x, scene.dataScale[0]),
+      toDataCoords(layout.yaxis, data.y, scene.dataScale[1]),
+      toDataCoords(layout.zaxis, data.z, scene.dataScale[2]));
+
+    var cells;
+    if(data.i && data.j && data.k) {
+        cells = zip3(data.i, data.j, data.k);
+    }
+    else if(data.alphahull === 0) {
+        cells = convexHull(positions);
+    }
+    else if(data.alphahull > 0) {
+        cells = alphaShape(data.alphahull, positions);
+    }
+    else {
+        var d = ['x', 'y', 'z'].indexOf(data.delaunayaxis);
+        cells = triangulate(positions.map(function(c) {
+            return [c[(d+1)%3], c[(d+2)%3]];
+        }));
+    }
+
+    var config = {
+        positions: positions,
+        cells: cells,
+        ambient: data.lighting.ambient,
+        diffuse: data.lighting.diffuse,
+        specular: data.lighting.specular,
+        roughness: data.lighting.roughness,
+        fresnel: data.lighting.fresnel,
+        opacity: data.opacity,
+        contourEnable: data.contour.show,
+        contourColor: str2RgbaArray(data.contour.color).slice(0,3),
+        contourWidth: data.contour.width,
+        useFacetNormals: data.flatshading
+    };
+
+    if(data.intensity) {
+        this.color = '#fff';
+        config.vertexIntensity = data.intensity;
+        config.colormap = parseColorScale(data.colorscale);
+    }
+    else if(data.vertexcolor) {
+        this.color = data.vertexcolors[0];
+        config.vertexColors = parseColorArray(data.vertexcolor);
+    }
+    else if(data.facecolor) {
+        this.color = data.facecolor[0];
+        config.cellColors = parseColorArray(data.facecolor);
+    }
+    else {
+        this.color = data.color;
+        config.meshColor = str2RgbaArray(data.color);
+    }
+
+    //Update mesh
+    this.mesh.update(config);
+};
+
+proto.dispose = function() {
+    this.scene.glplot.remove(this.mesh);
+    this.mesh.dispose();
+};
+
+function createMesh3DTrace(scene, data) {
+    var gl = scene.glplot.gl;
+    var mesh = createMesh({gl: gl});
+    var result = new Mesh3DTrace(scene, mesh, data.uid);
+    result.update(data);
+    scene.glplot.add(mesh);
+    return result;
+}
+
+module.exports = createMesh3DTrace;
+
+},{"../../lib/str2rgbarray":359,"alpha-shape":39,"convex-hull":60,"delaunay-triangulate":71,"gl-mesh3d":107,"tinycolor2":229}],489:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+var colorbarDefaults = require('../../components/colorbar/defaults');
+var attributes = require('./attributes');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    // read in face/vertex properties
+    function readComponents(array) {
+        var ret = array.map(function(attr) {
+            var result = coerce(attr);
+
+            if(result && Array.isArray(result)) return result;
+            return null;
+        });
+
+        return ret.every(function(x) {
+            return x && x.length === ret[0].length;
+        }) && ret;
+    }
+
+    var coords = readComponents(['x', 'y', 'z']);
+    var indices = readComponents(['i', 'j', 'k']);
+
+    if(!coords) {
+        traceOut.visible = false;
+        return;
+    }
+
+    if(indices) {
+        // otherwise, convert all face indices to ints
+        indices.forEach(function(index) {
+            for(var i = 0; i < index.length; ++i) index[i] |= 0;
+        });
+    }
+
+    //Coerce remaining properties
+    ['lighting.ambient',
+        'lighting.diffuse',
+        'lighting.specular',
+        'lighting.roughness',
+        'lighting.fresnel',
+        'contour.show',
+        'contour.color',
+        'contour.width',
+        'colorscale',
+        'reversescale',
+        'flatshading',
+        'alphahull',
+        'delaunayaxis',
+        'opacity'
+    ].forEach(function(x) { coerce(x); });
+
+    if('intensity' in traceIn) {
+        coerce('intensity');
+        coerce('showscale', true);
+    }
+    else {
+        traceOut.showscale = false;
+
+        if('vertexcolor' in traceIn) coerce('vertexcolor');
+        else if('facecolor' in traceIn) coerce('facecolor');
+        else coerce('color', defaultColor);
+    }
+
+    if(traceOut.reversescale) {
+        traceOut.colorscale = traceOut.colorscale.map(function(si) {
+            return [1 - si[0], si[1]];
+        }).reverse();
+    }
+
+    if(traceOut.showscale) {
+        colorbarDefaults(traceIn, traceOut, layout);
+    }
+};
+
+},{"../../components/colorbar/defaults":301,"../../lib":349,"./attributes":487}],490:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Mesh3D = {};
+
+Mesh3D.attributes = require('./attributes');
+Mesh3D.supplyDefaults = require('./defaults');
+Mesh3D.colorbar = require('../heatmap/colorbar');
+Mesh3D.plot = require('./convert');
+
+Mesh3D.moduleType = 'trace';
+Mesh3D.name = 'mesh3d',
+Mesh3D.basePlotModule = require('../../plots/gl3d');
+Mesh3D.categories = ['gl3d'];
+Mesh3D.meta = {
+    
+};
+
+module.exports = Mesh3D;
+
+},{"../../plots/gl3d":400,"../heatmap/colorbar":461,"./attributes":487,"./convert":488,"./defaults":489}],491:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var colorAttrs = require('../../components/color/attributes');
+var fontAttrs = require('../../plots/font_attributes');
+var plotAttrs = require('../../plots/attributes');
+
+var extendFlat = require('../../lib/extend').extendFlat;
+
+
+module.exports = {
+    labels: {
+        valType: 'data_array',
+        
+    },
+    // equivalent of x0 and dx, if label is missing
+    label0: {
+        valType: 'number',
+        
+        dflt: 0,
+        
+    },
+    dlabel: {
+        valType: 'number',
+        
+        dflt: 1,
+        
+    },
+
+    values: {
+        valType: 'data_array',
+        
+    },
+
+    marker: {
+        colors: {
+            valType: 'data_array',  // TODO 'color_array' ?
+            
+        },
+
+        line: {
+            color: {
+                valType: 'color',
+                
+                dflt: colorAttrs.defaultLine,
+                arrayOk: true,
+                
+            },
+            width: {
+                valType: 'number',
+                
+                min: 0,
+                dflt: 0,
+                arrayOk: true,
+                
+            }
+        }
+    },
+
+    text: {
+        valType: 'data_array',
+        
+    },
+
+// 'see eg:'
+// 'https://www.e-education.psu.edu/natureofgeoinfo/sites/www.e-education.psu.edu.natureofgeoinfo/files/image/hisp_pies.gif',
+// '(this example involves a map too - may someday be a whole trace type',
+// 'of its own. but the point is the size of the whole pie is important.)'
+    scalegroup: {
+        valType: 'string',
+        
+        dflt: '',
+        
+    },
+
+    // labels (legend is handled by plots.attributes.showlegend and layout.hiddenlabels)
+    textinfo: {
+        valType: 'flaglist',
+        
+        flags: ['label', 'text', 'value', 'percent'],
+        extras: ['none'],
+        
+    },
+    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
+        flags: ['label', 'text', 'value', 'percent', 'name']
+    }),
+    textposition: {
+        valType: 'enumerated',
+        
+        values: ['inside', 'outside', 'auto', 'none'],
+        dflt: 'auto',
+        arrayOk: true,
+        
+    },
+    // TODO make those arrayOk?
+    textfont: extendFlat({}, fontAttrs, {
+        
+    }),
+    insidetextfont: extendFlat({}, fontAttrs, {
+        
+    }),
+    outsidetextfont: extendFlat({}, fontAttrs, {
+        
+    }),
+
+    // position and shape
+    domain: {
+        x: {
+            valType: 'info_array',
+            
+            items: [
+                {valType: 'number', min: 0, max: 1},
+                {valType: 'number', min: 0, max: 1}
+            ],
+            dflt: [0, 1],
+            
+        },
+        y: {
+            valType: 'info_array',
+            
+            items: [
+                {valType: 'number', min: 0, max: 1},
+                {valType: 'number', min: 0, max: 1}
+            ],
+            dflt: [0, 1],
+            
+        }
+    },
+    // 3D attributes commented out until I finish them in a later PR
+    // tilt: {
+    //     // degrees to tilt the pie back from straight on
+    //     valType: 'number',
+    //     min: 0,
+    //     max: 90,
+    //     dflt: 0
+    // },
+    // tiltaxis: {
+    //     // degrees away from straight up to tilt the pie
+    //     // only has an effect if tilt is nonzero
+    //     valType: 'number',
+    //     min: -360,
+    //     max: 360,
+    //     dflt: 0
+    // },
+    // depth: {
+    //     // "3D" size, as a fraction of radius
+    //     // only has an effect if tilt is nonzero
+    //     valType: 'number',
+    //     min: 0,
+    //     max: 10,
+    //     dflt: 0.5
+    // },
+    // shading: {
+    //     // how much darker to make the sides than the top,
+    //     // with a 3D effect. We could of course get all
+    //     // fancy with lighting effects, but maybe this is
+    //     // sufficient.
+    //     valType: 'number',
+    //     min: 0,
+    //     max: 1,
+    //     dflt: 0.2
+    // },
+    hole: {
+        valType: 'number',
+        
+        min: 0,
+        max: 1,
+        dflt: 0,
+        
+    },
+
+    // ordering and direction
+    sort: {
+        valType: 'boolean',
+        
+        dflt: true,
+        
+    },
+    direction: {
+        /**
+         * there are two common conventions, both of which place the first
+         * (largest, if sorted) slice with its left edge at 12 o'clock but
+         * succeeding slices follow either cw or ccw from there.
+         *
+         * see http://visage.co/data-visualization-101-pie-charts/
+         */
+        valType: 'enumerated',
+        values: ['clockwise', 'counterclockwise'],
+        
+        dflt: 'counterclockwise',
+        
+    },
+    rotation: {
+        valType: 'number',
+        
+        min: -360,
+        max: 360,
+        dflt: 0,
+        
+    },
+
+    pull: {
+        valType: 'number',
+        
+        min: 0,
+        max: 1,
+        dflt: 0,
+        arrayOk: true,
+        
+    }
+};
+
+},{"../../components/color/attributes":298,"../../lib/extend":345,"../../plots/attributes":367,"../../plots/font_attributes":383}],492:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+var tinycolor = require('tinycolor2');
+
+var Color = require('../../components/color');
+var helpers = require('./helpers');
+
+module.exports = function calc(gd, trace) {
+    var vals = trace.values,
+        labels = trace.labels,
+        cd = [],
+        fullLayout = gd._fullLayout,
+        colorMap = fullLayout._piecolormap,
+        allThisTraceLabels = {},
+        needDefaults = false,
+        vTotal = 0,
+        hiddenLabels = fullLayout.hiddenlabels || [],
+        i,
+        v,
+        label,
+        color,
+        hidden,
+        pt;
+
+    if(trace.dlabel) {
+        labels = new Array(vals.length);
+        for(i = 0; i < vals.length; i++) {
+            labels[i] = String(trace.label0 + i * trace.dlabel);
+        }
+    }
+
+    for(i = 0; i < vals.length; i++) {
+        v = vals[i];
+        if(!isNumeric(v)) continue;
+        v = +v;
+        if(v < 0) continue;
+
+        label = labels[i];
+        if(label === undefined || label === '') label = i;
+        label = String(label);
+        // only take the first occurrence of any given label.
+        // TODO: perhaps (optionally?) sum values for a repeated label?
+        if(allThisTraceLabels[label] === undefined) allThisTraceLabels[label] = true;
+        else continue;
+
+        color = tinycolor(trace.marker.colors[i]);
+        if(color.isValid()) {
+            color = Color.addOpacity(color, color.getAlpha());
+            if(!colorMap[label]) {
+                colorMap[label] = color;
+            }
+        }
+        // have we seen this label and assigned a color to it in a previous trace?
+        else if(colorMap[label]) color = colorMap[label];
+        // color needs a default - mark it false, come back after sorting
+        else {
+            color = false;
+            needDefaults = true;
+        }
+
+        hidden = hiddenLabels.indexOf(label) !== -1;
+
+        if(!hidden) vTotal += v;
+
+        cd.push({
+            v: v,
+            label: label,
+            color: color,
+            i: i,
+            hidden: hidden
+        });
+    }
+
+    if(trace.sort) cd.sort(function(a, b) { return b.v - a.v; });
+
+    /**
+     * now go back and fill in colors we're still missing
+     * this is done after sorting, so we pick defaults
+     * in the order slices will be displayed
+     */
+
+    if(needDefaults) {
+        for(i = 0; i < cd.length; i++) {
+            pt = cd[i];
+            if(pt.color === false) {
+                colorMap[pt.label] = pt.color = nextDefaultColor(fullLayout._piedefaultcolorcount);
+                fullLayout._piedefaultcolorcount++;
+            }
+        }
+    }
+
+    // include the sum of all values in the first point
+    if(cd[0]) cd[0].vTotal = vTotal;
+
+    // now insert text
+    if(trace.textinfo && trace.textinfo !== 'none') {
+        var hasLabel = trace.textinfo.indexOf('label') !== -1,
+            hasText = trace.textinfo.indexOf('text') !== -1,
+            hasValue = trace.textinfo.indexOf('value') !== -1,
+            hasPercent = trace.textinfo.indexOf('percent') !== -1,
+            thisText;
+
+        for(i = 0; i < cd.length; i++) {
+            pt = cd[i];
+            thisText = hasLabel ? [pt.label] : [];
+            if(hasText && trace.text[pt.i]) thisText.push(trace.text[pt.i]);
+            if(hasValue) thisText.push(helpers.formatPieValue(pt.v));
+            if(hasPercent) thisText.push(helpers.formatPiePercent(pt.v / vTotal));
+            pt.text = thisText.join('<br>');
+        }
+    }
+
+    return cd;
+};
+
+/**
+ * pick a default color from the main default set, augmented by
+ * itself lighter then darker before repeating
+ */
+var pieDefaultColors;
+
+function nextDefaultColor(index) {
+    if(!pieDefaultColors) {
+        // generate this default set on demand (but then it gets saved in the module)
+        var mainDefaults = Color.defaults;
+        pieDefaultColors = mainDefaults.slice();
+
+        var i;
+
+        for(i = 0; i < mainDefaults.length; i++) {
+            pieDefaultColors.push(tinycolor(mainDefaults[i]).lighten(20).toHexString());
+        }
+
+        for(i = 0; i < Color.defaults.length; i++) {
+            pieDefaultColors.push(tinycolor(mainDefaults[i]).darken(20).toHexString());
+        }
+    }
+
+    return pieDefaultColors[index % pieDefaultColors.length];
+}
+
+},{"../../components/color":299,"./helpers":494,"fast-isnumeric":74,"tinycolor2":229}],493:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Lib = require('../../lib');
+var attributes = require('./attributes');
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    var coerceFont = Lib.coerceFont;
+
+    var vals = coerce('values');
+    if(!Array.isArray(vals) || !vals.length) {
+        traceOut.visible = false;
+        return;
+    }
+
+    var labels = coerce('labels');
+    if(!Array.isArray(labels)) {
+        coerce('label0');
+        coerce('dlabel');
+    }
+
+    var lineWidth = coerce('marker.line.width');
+    if(lineWidth) coerce('marker.line.color');
+
+    var colors = coerce('marker.colors');
+    if(!Array.isArray(colors)) traceOut.marker.colors = []; // later this will get padded with default colors
+
+    coerce('scalegroup');
+    // TODO: tilt, depth, and hole all need to be coerced to the same values within a scaleegroup
+    // (ideally actually, depth would get set the same *after* scaling, ie the same absolute depth)
+    // and if colors aren't specified we should match these up - potentially even if separate pies
+    // are NOT in the same sharegroup
+
+
+    var textData = coerce('text');
+    var textInfo = coerce('textinfo', Array.isArray(textData) ? 'text+percent' : 'percent');
+
+    coerce('hoverinfo', (layout._dataLength === 1) ? 'label+text+value+percent' : undefined);
+
+    if(textInfo && textInfo !== 'none') {
+        var textPosition = coerce('textposition'),
+            hasBoth = Array.isArray(textPosition) || textPosition === 'auto',
+            hasInside = hasBoth || textPosition === 'inside',
+            hasOutside = hasBoth || textPosition === 'outside';
+
+        if(hasInside || hasOutside) {
+            var dfltFont = coerceFont(coerce, 'textfont', layout.font);
+            if(hasInside) coerceFont(coerce, 'insidetextfont', dfltFont);
+            if(hasOutside) coerceFont(coerce, 'outsidetextfont', dfltFont);
+        }
+    }
+
+    coerce('domain.x');
+    coerce('domain.y');
+
+    // 3D attributes commented out until I finish them in a later PR
+    // var tilt = coerce('tilt');
+    // if(tilt) {
+    //     coerce('tiltaxis');
+    //     coerce('depth');
+    //     coerce('shading');
+    // }
+
+    coerce('hole');
+
+    coerce('sort');
+    coerce('direction');
+    coerce('rotation');
+
+    coerce('pull');
+};
+
+},{"../../lib":349,"./attributes":491}],494:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+exports.formatPiePercent = function formatPiePercent(v) {
+    var vRounded = (v * 100).toPrecision(3);
+    if(vRounded.indexOf('.') !== -1) return vRounded.replace(/[.]?0+$/,'') + '%';
+    return vRounded + '%';
+};
+
+exports.formatPieValue = function formatPieValue(v) {
+    var vRounded = v.toPrecision(10);
+    if(vRounded.indexOf('.') !== -1) return vRounded.replace(/[.]?0+$/,'');
+    return vRounded;
+};
+
+},{}],495:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Pie = {};
+
+Pie.attributes = require('./attributes');
+Pie.supplyDefaults = require('./defaults');
+Pie.supplyLayoutDefaults = require('./layout_defaults');
+Pie.layoutAttributes = require('./layout_attributes');
+Pie.calc = require('./calc');
+Pie.plot = require('./plot');
+Pie.style = require('./style');
+Pie.styleOne = require('./style_one');
+
+Pie.moduleType = 'trace';
+Pie.name = 'pie';
+Pie.basePlotModule = require('../../plots/cartesian');
+Pie.categories = ['pie', 'showLegend'];
+Pie.meta = {
+    
+};
+
+module.exports = Pie;
+
+},{"../../plots/cartesian":375,"./attributes":491,"./calc":492,"./defaults":493,"./layout_attributes":496,"./layout_defaults":497,"./plot":498,"./style":499,"./style_one":500}],496:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+module.exports = {
+    /**
+     * hiddenlabels is the pie chart analog of visible:'legendonly'
+     * but it can contain many labels, and can hide slices
+     * from several pies simultaneously
+     */
+    hiddenlabels: {valType: 'data_array'}
+};
+
+},{}],497:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var layoutAttributes = require('./layout_attributes');
+
+module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
+    }
+    coerce('hiddenlabels');
+};
+
+},{"../../lib":349,"./layout_attributes":496}],498:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var d3 = require('d3');
+
+var Fx = require('../../plots/cartesian/graph_interact');
+var Color = require('../../components/color');
+var Drawing = require('../../components/drawing');
+var svgTextUtils = require('../../lib/svg_text_utils');
+
+var helpers = require('./helpers');
+
+module.exports = function plot(gd, cdpie) {
+    var fullLayout = gd._fullLayout;
+
+    scalePies(cdpie, fullLayout._size);
+
+    var pieGroups = fullLayout._pielayer.selectAll('g.trace').data(cdpie);
+
+    pieGroups.enter().append('g')
+        .attr({
+            'stroke-linejoin': 'round', // TODO: miter might look better but can sometimes cause problems
+                                        // maybe miter with a small-ish stroke-miterlimit?
+            'class': 'trace'
+        });
+    pieGroups.exit().remove();
+    pieGroups.order();
+
+    pieGroups.each(function(cd) {
+        var pieGroup = d3.select(this),
+            cd0 = cd[0],
+            trace = cd0.trace,
+            tiltRads = 0, //trace.tilt * Math.PI / 180,
+            depthLength = (trace.depth||0) * cd0.r * Math.sin(tiltRads) / 2,
+            tiltAxis = trace.tiltaxis || 0,
+            tiltAxisRads = tiltAxis * Math.PI / 180,
+            depthVector = [
+                depthLength * Math.sin(tiltAxisRads),
+                depthLength * Math.cos(tiltAxisRads)
+            ],
+            rSmall = cd0.r * Math.cos(tiltRads);
+
+        var pieParts = pieGroup.selectAll('g.part')
+            .data(trace.tilt ? ['top', 'sides'] : ['top']);
+
+        pieParts.enter().append('g').attr('class', function(d) {
+            return d + ' part';
+        });
+        pieParts.exit().remove();
+        pieParts.order();
+
+        setCoords(cd);
+
+        pieGroup.selectAll('.top').each(function() {
+            var slices = d3.select(this).selectAll('g.slice').data(cd);
+
+            slices.enter().append('g')
+                .classed('slice', true);
+            slices.exit().remove();
+
+            var quadrants = [
+                    [[],[]], // y<0: x<0, x>=0
+                    [[],[]] // y>=0: x<0, x>=0
+                ],
+                hasOutsideText = false;
+
+            slices.each(function(pt) {
+                if(pt.hidden) {
+                    d3.select(this).selectAll('path,g').remove();
+                    return;
+                }
+
+                quadrants[pt.pxmid[1] < 0 ? 0 : 1][pt.pxmid[0] < 0 ? 0 : 1].push(pt);
+
+                var cx = cd0.cx + depthVector[0],
+                    cy = cd0.cy + depthVector[1],
+                    sliceTop = d3.select(this),
+                    slicePath = sliceTop.selectAll('path.surface').data([pt]),
+                    hasHoverData = false;
+
+                function handleMouseOver(evt) {
+                    // in case fullLayout or fullData has changed without a replot
+                    var fullLayout2 = gd._fullLayout,
+                        trace2 = gd._fullData[trace.index],
+                        hoverinfo = trace2.hoverinfo;
+
+                    if(hoverinfo === 'all') hoverinfo = 'label+text+value+percent+name';
+
+                    // in case we dragged over the pie from another subplot,
+                    // or if hover is turned off
+                    if(gd._dragging || fullLayout2.hovermode === false ||
+                            hoverinfo === 'none' || !hoverinfo) {
+                        return;
+                    }
+
+                    var rInscribed = getInscribedRadiusFraction(pt, cd0),
+                        hoverCenterX = cx + pt.pxmid[0] * (1 - rInscribed),
+                        hoverCenterY = cy + pt.pxmid[1] * (1 - rInscribed),
+                        thisText = [];
+                    if(hoverinfo.indexOf('label') !== -1) thisText.push(pt.label);
+                    if(trace2.text && trace2.text[pt.i] && hoverinfo.indexOf('text') !== -1) {
+                        thisText.push(trace2.text[pt.i]);
+                    }
+                    if(hoverinfo.indexOf('value') !== -1) thisText.push(helpers.formatPieValue(pt.v));
+                    if(hoverinfo.indexOf('percent') !== -1) thisText.push(helpers.formatPiePercent(pt.v / cd0.vTotal));
+
+                    Fx.loneHover({
+                        x0: hoverCenterX - rInscribed * cd0.r,
+                        x1: hoverCenterX + rInscribed * cd0.r,
+                        y: hoverCenterY,
+                        text: thisText.join('<br>'),
+                        name: hoverinfo.indexOf('name') !== -1 ? trace2.name : undefined,
+                        color: pt.color,
+                        idealAlign: pt.pxmid[0] < 0 ? 'left' : 'right'
+                    }, {
+                        container: fullLayout2._hoverlayer.node(),
+                        outerContainer: fullLayout2._paper.node()
+                    });
+
+                    Fx.hover(gd, evt, 'pie');
+
+                    hasHoverData = true;
+                }
+
+                function handleMouseOut() {
+                    if(hasHoverData) {
+                        Fx.loneUnhover(fullLayout._hoverlayer.node());
+                        hasHoverData = false;
+                    }
+                }
+
+                function handleClick() {
+                    gd._hoverdata = [pt];
+                    gd._hoverdata.trace = cd.trace;
+                    Fx.click(gd, { target: true });
+                }
+
+                slicePath.enter().append('path')
+                    .classed('surface', true)
+                    .style({'pointer-events': 'all'});
+
+                sliceTop.select('path.textline').remove();
+
+                sliceTop
+                    .on('mouseover', handleMouseOver)
+                    .on('mouseout', handleMouseOut)
+                    .on('click', handleClick);
+
+                if(trace.pull) {
+                    var pull = +(Array.isArray(trace.pull) ? trace.pull[pt.i] : trace.pull) || 0;
+                    if(pull > 0) {
+                        cx += pull * pt.pxmid[0];
+                        cy += pull * pt.pxmid[1];
+                    }
+                }
+
+                pt.cxFinal = cx;
+                pt.cyFinal = cy;
+
+                function arc(start, finish, cw, scale) {
+                    return 'a' + (scale * cd0.r) + ',' + (scale * rSmall) + ' ' + tiltAxis + ' ' +
+                        pt.largeArc + (cw ? ' 1 ' : ' 0 ') +
+                        (scale * (finish[0] - start[0])) + ',' + (scale * (finish[1] - start[1]));
+                }
+
+                var hole = trace.hole;
+                if(pt.v === cd0.vTotal) { // 100% fails bcs arc start and end are identical
+                    var outerCircle = 'M' + (cx + pt.px0[0]) + ',' + (cy + pt.px0[1]) +
+                        arc(pt.px0, pt.pxmid, true, 1) +
+                        arc(pt.pxmid, pt.px0, true, 1) + 'Z';
+                    if(hole) {
+                        slicePath.attr('d',
+                            'M' + (cx + hole * pt.px0[0]) + ',' + (cy + hole * pt.px0[1]) +
+                            arc(pt.px0, pt.pxmid, false, hole) +
+                            arc(pt.pxmid, pt.px0, false, hole) +
+                            'Z' + outerCircle);
+                    }
+                    else slicePath.attr('d', outerCircle);
+                } else {
+
+                    var outerArc = arc(pt.px0, pt.px1, true, 1);
+
+                    if(hole) {
+                        var rim = 1 - hole;
+                        slicePath.attr('d',
+                            'M' + (cx + hole * pt.px1[0]) + ',' + (cy + hole * pt.px1[1]) +
+                            arc(pt.px1, pt.px0, false, hole) +
+                            'l' + (rim * pt.px0[0]) + ',' + (rim * pt.px0[1]) +
+                            outerArc +
+                            'Z');
+                    } else {
+                        slicePath.attr('d',
+                            'M' + cx + ',' + cy +
+                            'l' + pt.px0[0] + ',' + pt.px0[1] +
+                            outerArc +
+                            'Z');
+                    }
+                }
+
+                // add text
+                var textPosition = Array.isArray(trace.textposition) ?
+                        trace.textposition[pt.i] : trace.textposition,
+                    sliceTextGroup = sliceTop.selectAll('g.slicetext')
+                    .data(pt.text && (textPosition !== 'none') ? [0] : []);
+
+                sliceTextGroup.enter().append('g')
+                    .classed('slicetext', true);
+                sliceTextGroup.exit().remove();
+
+                sliceTextGroup.each(function() {
+                    var sliceText = d3.select(this).selectAll('text').data([0]);
+
+                    sliceText.enter().append('text')
+                        // prohibit tex interpretation until we can handle
+                        // tex and regular text together
+                        .attr('data-notex', 1);
+                    sliceText.exit().remove();
+
+                    sliceText.text(pt.text)
+                        .attr({
+                            'class': 'slicetext',
+                            transform: '',
+                            'data-bb': '',
+                            'text-anchor': 'middle',
+                            x: 0,
+                            y: 0
+                        })
+                        .call(Drawing.font, textPosition === 'outside' ?
+                            trace.outsidetextfont : trace.insidetextfont)
+                        .call(svgTextUtils.convertToTspans);
+                    sliceText.selectAll('tspan.line').attr({x: 0, y: 0});
+
+                    // position the text relative to the slice
+                    // TODO: so far this only accounts for flat
+                    var textBB = Drawing.bBox(sliceText.node()),
+                        transform;
+
+                    if(textPosition === 'outside') {
+                        transform = transformOutsideText(textBB, pt);
+                    } else {
+                        transform = transformInsideText(textBB, pt, cd0);
+                        if(textPosition === 'auto' && transform.scale < 1) {
+                            sliceText.call(Drawing.font, trace.outsidetextfont);
+                            if(trace.outsidetextfont.family !== trace.insidetextfont.family ||
+                                    trace.outsidetextfont.size !== trace.insidetextfont.size) {
+                                sliceText.attr({'data-bb': ''});
+                                textBB = Drawing.bBox(sliceText.node());
+                            }
+                            transform = transformOutsideText(textBB, pt);
+                        }
+                    }
+
+                    var translateX = cx + pt.pxmid[0] * transform.rCenter + (transform.x || 0),
+                        translateY = cy + pt.pxmid[1] * transform.rCenter + (transform.y || 0);
+
+                    // save some stuff to use later ensure no labels overlap
+                    if(transform.outside) {
+                        pt.yLabelMin = translateY - textBB.height / 2;
+                        pt.yLabelMid = translateY;
+                        pt.yLabelMax = translateY + textBB.height / 2;
+                        pt.labelExtraX = 0;
+                        pt.labelExtraY = 0;
+                        hasOutsideText = true;
+                    }
+
+                    sliceText.attr('transform',
+                        'translate(' + translateX + ',' + translateY + ')' +
+                        (transform.scale < 1 ? ('scale(' + transform.scale + ')') : '') +
+                        (transform.rotate ? ('rotate(' + transform.rotate + ')') : '') +
+                        'translate(' +
+                            (-(textBB.left + textBB.right) / 2) + ',' +
+                            (-(textBB.top + textBB.bottom) / 2) +
+                        ')');
+                });
+            });
+
+            // now make sure no labels overlap (at least within one pie)
+            if(hasOutsideText) scootLabels(quadrants, trace);
+            slices.each(function(pt) {
+                if(pt.labelExtraX || pt.labelExtraY) {
+                    // first move the text to its new location
+                    var sliceTop = d3.select(this),
+                        sliceText = sliceTop.select('g.slicetext text');
+
+                    sliceText.attr('transform', 'translate(' + pt.labelExtraX + ',' + pt.labelExtraY + ')' +
+                        sliceText.attr('transform'));
+
+                    // then add a line to the new location
+                    var lineStartX = pt.cxFinal + pt.pxmid[0],
+                        lineStartY = pt.cyFinal + pt.pxmid[1],
+                        textLinePath = 'M' + lineStartX + ',' + lineStartY,
+                        finalX = (pt.yLabelMax - pt.yLabelMin) * (pt.pxmid[0] < 0 ? -1 : 1) / 4;
+                    if(pt.labelExtraX) {
+                        var yFromX = pt.labelExtraX * pt.pxmid[1] / pt.pxmid[0],
+                            yNet = pt.yLabelMid + pt.labelExtraY - (pt.cyFinal + pt.pxmid[1]);
+
+                        if(Math.abs(yFromX) > Math.abs(yNet)) {
+                            textLinePath +=
+                                'l' + (yNet * pt.pxmid[0] / pt.pxmid[1]) + ',' + yNet +
+                                'H' + (lineStartX + pt.labelExtraX + finalX);
+                        } else {
+                            textLinePath += 'l' + pt.labelExtraX + ',' + yFromX +
+                                'v' + (yNet - yFromX) +
+                                'h' + finalX;
+                        }
+                    } else {
+                        textLinePath +=
+                            'V' + (pt.yLabelMid + pt.labelExtraY) +
+                            'h' + finalX;
+                    }
+
+                    sliceTop.append('path')
+                        .classed('textline', true)
+                        .call(Color.stroke, trace.outsidetextfont.color)
+                        .attr({
+                            'stroke-width': Math.min(2, trace.outsidetextfont.size / 8),
+                            d: textLinePath,
+                            fill: 'none'
+                        });
+                }
+            });
+        });
+    });
+
+    // This is for a bug in Chrome (as of 2015-07-22, and does not affect FF)
+    // if insidetextfont and outsidetextfont are different sizes, sometimes the size
+    // of an "em" gets taken from the wrong element at first so lines are
+    // spaced wrong. You just have to tell it to try again later and it gets fixed.
+    // I have no idea why we haven't seen this in other contexts. Also, sometimes
+    // it gets the initial draw correct but on redraw it gets confused.
+    setTimeout(function() {
+        pieGroups.selectAll('tspan').each(function() {
+            var s = d3.select(this);
+            if(s.attr('dy')) s.attr('dy', s.attr('dy'));
+        });
+    }, 0);
+};
+
+
+function transformInsideText(textBB, pt, cd0) {
+    var textDiameter = Math.sqrt(textBB.width * textBB.width + textBB.height * textBB.height),
+        textAspect = textBB.width / textBB.height,
+        halfAngle = Math.PI * Math.min(pt.v / cd0.vTotal, 0.5),
+        ring = 1 - cd0.trace.hole,
+        rInscribed = getInscribedRadiusFraction(pt, cd0),
+
+        // max size text can be inserted inside without rotating it
+        // this inscribes the text rectangle in a circle, which is then inscribed
+        // in the slice, so it will be an underestimate, which some day we may want
+        // to improve so this case can get more use
+        transform = {
+            scale: rInscribed * cd0.r * 2 / textDiameter,
+
+            // and the center position and rotation in this case
+            rCenter: 1 - rInscribed,
+            rotate: 0
+        };
+
+    if(transform.scale >= 1) return transform;
+
+        // max size if text is rotated radially
+    var Qr = textAspect + 1 / (2 * Math.tan(halfAngle)),
+        maxHalfHeightRotRadial = cd0.r * Math.min(
+            1 / (Math.sqrt(Qr * Qr + 0.5) + Qr),
+            ring / (Math.sqrt(textAspect * textAspect + ring / 2) + textAspect)
+        ),
+        radialTransform = {
+            scale: maxHalfHeightRotRadial * 2 / textBB.height,
+            rCenter: Math.cos(maxHalfHeightRotRadial / cd0.r) -
+                maxHalfHeightRotRadial * textAspect / cd0.r,
+            rotate: (180 / Math.PI * pt.midangle + 720) % 180 - 90
+        },
+
+        // max size if text is rotated tangentially
+        aspectInv = 1 / textAspect,
+        Qt = aspectInv + 1 / (2 * Math.tan(halfAngle)),
+        maxHalfWidthTangential = cd0.r * Math.min(
+            1 / (Math.sqrt(Qt * Qt + 0.5) + Qt),
+            ring / (Math.sqrt(aspectInv * aspectInv + ring / 2) + aspectInv)
+        ),
+        tangentialTransform = {
+            scale: maxHalfWidthTangential * 2 / textBB.width,
+            rCenter: Math.cos(maxHalfWidthTangential / cd0.r) -
+                maxHalfWidthTangential / textAspect / cd0.r,
+            rotate: (180 / Math.PI * pt.midangle + 810) % 180 - 90
+        },
+        // if we need a rotated transform, pick the biggest one
+        // even if both are bigger than 1
+        rotatedTransform = tangentialTransform.scale > radialTransform.scale ?
+            tangentialTransform : radialTransform;
+
+    if(transform.scale < 1 && rotatedTransform.scale > transform.scale) return rotatedTransform;
+    return transform;
+}
+
+function getInscribedRadiusFraction(pt, cd0) {
+    if(pt.v === cd0.vTotal && !cd0.trace.hole) return 1;// special case of 100% with no hole
+
+    var halfAngle = Math.PI * Math.min(pt.v / cd0.vTotal, 0.5);
+    return Math.min(1 / (1 + 1 / Math.sin(halfAngle)), (1 - cd0.trace.hole) / 2);
+}
+
+function transformOutsideText(textBB, pt) {
+    var x = pt.pxmid[0],
+        y = pt.pxmid[1],
+        dx = textBB.width / 2,
+        dy = textBB.height / 2;
+
+    if(x < 0) dx *= -1;
+    if(y < 0) dy *= -1;
+
+    return {
+        scale: 1,
+        rCenter: 1,
+        rotate: 0,
+        x: dx + Math.abs(dy) * (dx > 0 ? 1 : -1) / 2,
+        y: dy / (1 + x * x / (y * y)),
+        outside: true
+    };
+}
+
+function scootLabels(quadrants, trace) {
+    var xHalf,
+        yHalf,
+        equatorFirst,
+        farthestX,
+        farthestY,
+        xDiffSign,
+        yDiffSign,
+        thisQuad,
+        oppositeQuad,
+        wholeSide,
+        i,
+        thisQuadOutside,
+        firstOppositeOutsidePt;
+
+    function topFirst(a, b) { return a.pxmid[1] - b.pxmid[1]; }
+    function bottomFirst(a, b) { return b.pxmid[1] - a.pxmid[1]; }
+
+    function scootOneLabel(thisPt, prevPt) {
+        if(!prevPt) prevPt = {};
+
+        var prevOuterY = prevPt.labelExtraY + (yHalf ? prevPt.yLabelMax : prevPt.yLabelMin),
+            thisInnerY = yHalf ? thisPt.yLabelMin : thisPt.yLabelMax,
+            thisOuterY = yHalf ? thisPt.yLabelMax : thisPt.yLabelMin,
+            thisSliceOuterY = thisPt.cyFinal + farthestY(thisPt.px0[1], thisPt.px1[1]),
+            newExtraY = prevOuterY - thisInnerY,
+            xBuffer,
+            i,
+            otherPt,
+            otherOuterY,
+            otherOuterX,
+            newExtraX;
+        // make sure this label doesn't overlap other labels
+        // this *only* has us move these labels vertically
+        if(newExtraY * yDiffSign > 0) thisPt.labelExtraY = newExtraY;
+
+        // make sure this label doesn't overlap any slices
+        if(!Array.isArray(trace.pull)) return; // this can only happen with array pulls
+
+        for(i = 0; i < wholeSide.length; i++) {
+            otherPt = wholeSide[i];
+
+            // overlap can only happen if the other point is pulled more than this one
+            if(otherPt === thisPt || ((trace.pull[thisPt.i] || 0) >= trace.pull[otherPt.i] || 0)) continue;
+
+            if((thisPt.pxmid[1] - otherPt.pxmid[1]) * yDiffSign > 0) {
+                // closer to the equator - by construction all of these happen first
+                // move the text vertically to get away from these slices
+                otherOuterY = otherPt.cyFinal + farthestY(otherPt.px0[1], otherPt.px1[1]);
+                newExtraY = otherOuterY - thisInnerY - thisPt.labelExtraY;
+
+                if(newExtraY * yDiffSign > 0) thisPt.labelExtraY += newExtraY;
+
+            } else if((thisOuterY + thisPt.labelExtraY - thisSliceOuterY) * yDiffSign > 0) {
+                // farther from the equator - happens after we've done all the
+                // vertical moving we're going to do
+                // move horizontally to get away from these more polar slices
+
+                // if we're moving horz. based on a slice that's several slices away from this one
+                // then we need some extra space for the lines to labels between them
+                xBuffer = 3 * xDiffSign * Math.abs(i - wholeSide.indexOf(thisPt));
+
+                otherOuterX = otherPt.cxFinal + farthestX(otherPt.px0[0], otherPt.px1[0]);
+                newExtraX = otherOuterX + xBuffer - (thisPt.cxFinal + thisPt.pxmid[0]) - thisPt.labelExtraX;
+
+                if(newExtraX * xDiffSign > 0) thisPt.labelExtraX += newExtraX;
+            }
+        }
+    }
+
+    for(yHalf = 0; yHalf < 2; yHalf++) {
+        equatorFirst = yHalf ? topFirst : bottomFirst;
+        farthestY = yHalf ? Math.max : Math.min;
+        yDiffSign = yHalf ? 1 : -1;
+
+        for(xHalf = 0; xHalf < 2; xHalf++) {
+            farthestX = xHalf ? Math.max : Math.min;
+            xDiffSign = xHalf ? 1 : -1;
+
+            // first sort the array
+            // note this is a copy of cd, so cd itself doesn't get sorted
+            // but we can still modify points in place.
+            thisQuad = quadrants[yHalf][xHalf];
+            thisQuad.sort(equatorFirst);
+
+            oppositeQuad = quadrants[1 - yHalf][xHalf];
+            wholeSide = oppositeQuad.concat(thisQuad);
+
+            thisQuadOutside = [];
+            for(i = 0; i < thisQuad.length; i++) {
+                if(thisQuad[i].yLabelMid !== undefined) thisQuadOutside.push(thisQuad[i]);
+            }
+
+            firstOppositeOutsidePt = false;
+            for(i = 0; yHalf && i < oppositeQuad.length; i++) {
+                if(oppositeQuad[i].yLabelMid !== undefined) {
+                    firstOppositeOutsidePt = oppositeQuad[i];
+                    break;
+                }
+            }
+
+            // each needs to avoid the previous
+            for(i = 0; i < thisQuadOutside.length; i++) {
+                var prevPt = i && thisQuadOutside[i - 1];
+                // bottom half needs to avoid the first label of the top half
+                // top half we still need to call scootOneLabel on the first slice
+                // so we can avoid other slices, but we don't pass a prevPt
+                if(firstOppositeOutsidePt && !i) prevPt = firstOppositeOutsidePt;
+                scootOneLabel(thisQuadOutside[i], prevPt);
+            }
+        }
+    }
+}
+
+function scalePies(cdpie, plotSize) {
+    var pieBoxWidth,
+        pieBoxHeight,
+        i,
+        j,
+        cd0,
+        trace,
+        tiltAxisRads,
+        maxPull,
+        scaleGroups = [],
+        scaleGroup,
+        minPxPerValUnit;
+
+    // first figure out the center and maximum radius for each pie
+    for(i = 0; i < cdpie.length; i++) {
+        cd0 = cdpie[i][0];
+        trace = cd0.trace;
+        pieBoxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]);
+        pieBoxHeight = plotSize.h * (trace.domain.y[1] - trace.domain.y[0]);
+        tiltAxisRads = trace.tiltaxis * Math.PI / 180;
+
+        maxPull = trace.pull;
+        if(Array.isArray(maxPull)) {
+            maxPull = 0;
+            for(j = 0; j < trace.pull.length; j++) {
+                if(trace.pull[j] > maxPull) maxPull = trace.pull[j];
+            }
+        }
+
+        cd0.r = Math.min(
+                pieBoxWidth / maxExtent(trace.tilt, Math.sin(tiltAxisRads), trace.depth),
+                pieBoxHeight / maxExtent(trace.tilt, Math.cos(tiltAxisRads), trace.depth)
+            ) / (2 + 2 * maxPull);
+
+        cd0.cx = plotSize.l + plotSize.w * (trace.domain.x[1] + trace.domain.x[0])/2;
+        cd0.cy = plotSize.t + plotSize.h * (2 - trace.domain.y[1] - trace.domain.y[0])/2;
+
+        if(trace.scalegroup && scaleGroups.indexOf(trace.scalegroup) === -1) {
+            scaleGroups.push(trace.scalegroup);
+        }
+    }
+
+    // Then scale any pies that are grouped
+    for(j = 0; j < scaleGroups.length; j++) {
+        minPxPerValUnit = Infinity;
+        scaleGroup = scaleGroups[j];
+
+        for(i = 0; i < cdpie.length; i++) {
+            cd0 = cdpie[i][0];
+            if(cd0.trace.scalegroup === scaleGroup) {
+                minPxPerValUnit = Math.min(minPxPerValUnit,
+                    cd0.r * cd0.r / cd0.vTotal);
+            }
+        }
+
+        for(i = 0; i < cdpie.length; i++) {
+            cd0 = cdpie[i][0];
+            if(cd0.trace.scalegroup === scaleGroup) {
+                cd0.r = Math.sqrt(minPxPerValUnit * cd0.vTotal);
+            }
+        }
+    }
+
+}
+
+function setCoords(cd) {
+    var cd0 = cd[0],
+        trace = cd0.trace,
+        tilt = trace.tilt,
+        tiltAxisRads,
+        tiltAxisSin,
+        tiltAxisCos,
+        tiltRads,
+        crossTilt,
+        inPlane,
+        currentAngle = trace.rotation * Math.PI / 180,
+        angleFactor = 2 * Math.PI / cd0.vTotal,
+        firstPt = 'px0',
+        lastPt = 'px1',
+        i,
+        cdi,
+        currentCoords;
+
+    if(trace.direction === 'counterclockwise') {
+        for(i = 0; i < cd.length; i++) {
+            if(!cd[i].hidden) break; // find the first non-hidden slice
+        }
+        if(i === cd.length) return; // all slices hidden
+
+        currentAngle += angleFactor * cd[i].v;
+        angleFactor *= -1;
+        firstPt = 'px1';
+        lastPt = 'px0';
+    }
+
+    if(tilt) {
+        tiltRads = tilt * Math.PI / 180;
+        tiltAxisRads = trace.tiltaxis * Math.PI / 180;
+        crossTilt = Math.sin(tiltAxisRads) * Math.cos(tiltAxisRads);
+        inPlane = 1 - Math.cos(tiltRads);
+        tiltAxisSin = Math.sin(tiltAxisRads);
+        tiltAxisCos = Math.cos(tiltAxisRads);
+    }
+
+    function getCoords(angle) {
+        var xFlat = cd0.r * Math.sin(angle),
+            yFlat = -cd0.r * Math.cos(angle);
+
+        if(!tilt) return [xFlat, yFlat];
+
+        return [
+            xFlat * (1 - inPlane * tiltAxisSin * tiltAxisSin) + yFlat * crossTilt * inPlane,
+            xFlat * crossTilt * inPlane + yFlat * (1 - inPlane * tiltAxisCos * tiltAxisCos),
+            Math.sin(tiltRads) * (yFlat * tiltAxisCos - xFlat * tiltAxisSin)
+        ];
+    }
+
+    currentCoords = getCoords(currentAngle);
+
+    for(i = 0; i < cd.length; i++) {
+        cdi = cd[i];
+        if(cdi.hidden) continue;
+
+        cdi[firstPt] = currentCoords;
+
+        currentAngle += angleFactor * cdi.v / 2;
+        cdi.pxmid = getCoords(currentAngle);
+        cdi.midangle = currentAngle;
+
+        currentAngle += angleFactor * cdi.v / 2;
+        currentCoords = getCoords(currentAngle);
+
+        cdi[lastPt] = currentCoords;
+
+        cdi.largeArc = (cdi.v > cd0.vTotal / 2) ? 1 : 0;
+    }
+}
+
+function maxExtent(tilt, tiltAxisFraction, depth) {
+    if(!tilt) return 1;
+    var sinTilt = Math.sin(tilt * Math.PI / 180);
+    return Math.max(0.01, // don't let it go crazy if you tilt the pie totally on its side
+        depth * sinTilt * Math.abs(tiltAxisFraction) +
+        2 * Math.sqrt(1 - sinTilt * sinTilt * tiltAxisFraction * tiltAxisFraction));
+}
+
+},{"../../components/color":299,"../../components/drawing":317,"../../lib/svg_text_utils":360,"../../plots/cartesian/graph_interact":374,"./helpers":494,"d3":70}],499:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var d3 = require('d3');
+
+var styleOne = require('./style_one');
+
+module.exports = function style(gd) {
+    gd._fullLayout._pielayer.selectAll('.trace').each(function(cd) {
+        var cd0 = cd[0],
+            trace = cd0.trace,
+            traceSelection = d3.select(this);
+
+        traceSelection.style({opacity: trace.opacity});
+
+        traceSelection.selectAll('.top path.surface').each(function(pt) {
+            d3.select(this).call(styleOne, pt, trace);
+        });
+    });
+};
+
+},{"./style_one":500,"d3":70}],500:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Color = require('../../components/color');
+
+module.exports = function styleOne(s, pt, trace) {
+    var lineColor = trace.marker.line.color;
+    if(Array.isArray(lineColor)) lineColor = lineColor[pt.i] || Color.defaultLine;
+
+    var lineWidth = trace.marker.line.width || 0;
+    if(Array.isArray(lineWidth)) lineWidth = lineWidth[pt.i] || 0;
+
+    s.style({
+        'stroke-width': lineWidth,
+        fill: pt.color
+    })
+    .call(Color.stroke, lineColor);
+};
+
+},{"../../components/color":299}],501:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+
+// arrayOk attributes, merge them into calcdata array
+module.exports = function arraysToCalcdata(cd) {
+    var trace = cd[0].trace,
+        marker = trace.marker;
+
+    Lib.mergeArray(trace.text, cd, 'tx');
+    Lib.mergeArray(trace.textposition, cd, 'tp');
+    if(trace.textfont) {
+        Lib.mergeArray(trace.textfont.size, cd, 'ts');
+        Lib.mergeArray(trace.textfont.color, cd, 'tc');
+        Lib.mergeArray(trace.textfont.family, cd, 'tf');
+    }
+
+    if(marker && marker.line) {
+        var markerLine = marker.line;
+        Lib.mergeArray(marker.opacity, cd, 'mo');
+        Lib.mergeArray(marker.symbol, cd, 'mx');
+        Lib.mergeArray(marker.color, cd, 'mc');
+        Lib.mergeArray(markerLine.color, cd, 'mlc');
+        Lib.mergeArray(markerLine.width, cd, 'mlw');
+    }
+};
+
+},{"../../lib":349}],502:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Drawing = require('../../components/drawing');
+
+var constants = require('./constants');
+
+
+module.exports = {
+    x: {
+        valType: 'data_array',
+        
+    },
+    x0: {
+        valType: 'any',
+        dflt: 0,
+        
+        
+    },
+    dx: {
+        valType: 'number',
+        dflt: 1,
+        
+        
+    },
+    y: {
+        valType: 'data_array',
+        
+    },
+    y0: {
+        valType: 'any',
+        dflt: 0,
+        
+        
+    },
+    dy: {
+        valType: 'number',
+        dflt: 1,
+        
+        
+    },
+    text: {
+        valType: 'string',
+        
+        dflt: '',
+        arrayOk: true,
+        
+    },
+    mode: {
+        valType: 'flaglist',
+        flags: ['lines', 'markers', 'text'],
+        extras: ['none'],
+        
+        
+    },
+    line: {
+        color: {
+            valType: 'color',
+            
+            
+        },
+        width: {
+            valType: 'number',
+            min: 0,
+            dflt: 2,
+            
+            
+        },
+        shape: {
+            valType: 'enumerated',
+            values: ['linear', 'spline', 'hv', 'vh', 'hvh', 'vhv'],
+            dflt: 'linear',
+            
+            
+        },
+        smoothing: {
+            valType: 'number',
+            min: 0,
+            max: 1.3,
+            dflt: 1,
+            
+            
+        },
+        dash: {
+            valType: 'string',
+            // string type usually doesn't take values... this one should really be
+            // a special type or at least a special coercion function, from the GUI
+            // you only get these values but elsewhere the user can supply a list of
+            // dash lengths in px, and it will be honored
+            values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'],
+            dflt: 'solid',
+            
+            
+        }
+    },
+    connectgaps: {
+        valType: 'boolean',
+        dflt: false,
+        
+        
+    },
+    fill: {
+        valType: 'enumerated',
+        values: ['none', 'tozeroy', 'tozerox', 'tonexty', 'tonextx'],
+        dflt: 'none',
+        
+        
+    },
+    fillcolor: {
+        valType: 'color',
+        
+        
+    },
+    marker: {
+        symbol: {
+            valType: 'enumerated',
+            values: Drawing.symbolList,
+            dflt: 'circle',
+            arrayOk: true,
+            
+            
+        },
+        opacity: {
+            valType: 'number',
+            min: 0,
+            max: 1,
+            arrayOk: true,
+            
+            
+        },
+        size: {
+            valType: 'number',
+            min: 0,
+            dflt: 6,
+            arrayOk: true,
+            
+            
+        },
+        color: {
+            valType: 'color',
+            arrayOk: true,
+            
+            
+        },
+        maxdisplayed: {
+            valType: 'number',
+            min: 0,
+            dflt: 0,
+            
+            
+        },
+        sizeref: {
+            valType: 'number',
+            dflt: 1,
+            
+            
+        },
+        sizemin: {
+            valType: 'number',
+            min: 0,
+            dflt: 0,
+            
+            
+        },
+        sizemode: {
+            valType: 'enumerated',
+            values: ['diameter', 'area'],
+            dflt: 'diameter',
+            
+            
+        },
+        colorscale: {
+            valType: 'colorscale',
+            
+            
+        },
+        cauto: {
+            valType: 'boolean',
+            dflt: true,
+            
+            
+        },
+        cmax: {
+            valType: 'number',
+            dflt: null,
+            
+            
+        },
+        cmin: {
+            valType: 'number',
+            dflt: null,
+            
+            
+        },
+        autocolorscale: {
+            valType: 'boolean',
+            dflt: true,
+            
+            
+        },
+        reversescale: {
+            valType: 'boolean',
+            
+            dflt: false,
+            
+        },
+        showscale: {
+            valType: 'boolean',
+            
+            dflt: false,
+            
+        },
+        line: {
+            color: {
+                valType: 'color',
+                arrayOk: true,
+                
+                
+            },
+            width: {
+                valType: 'number',
+                min: 0,
+                arrayOk: true,
+                
+                
+            },
+            colorscale: {
+                valType: 'colorscale',
+                
+                
+            },
+            cauto: {
+                valType: 'boolean',
+                dflt: true,
+                
+                
+            },
+            cmax: {
+                valType: 'number',
+                dflt: null,
+                
+                
+            },
+            cmin: {
+                valType: 'number',
+                dflt: null,
+                
+                
+            },
+            autocolorscale: {
+                valType: 'boolean',
+                dflt: true,
+                
+                
+            },
+            reversescale: {
+                valType: 'boolean',
+                dflt: false,
+                
+                
+            }
+        }
+    },
+    textposition: {
+        valType: 'enumerated',
+        values: [
+            'top left', 'top center', 'top right',
+            'middle left', 'middle center', 'middle right',
+            'bottom left', 'bottom center', 'bottom right'
+        ],
+        dflt: 'middle center',
+        arrayOk: true,
+        
+        
+    },
+    textfont: {
+        family: {
+            valType: 'string',
+            
+            noBlank: true,
+            strict: true,
+            arrayOk: true
+        },
+        size: {
+            valType: 'number',
+            
+            min: 1,
+            arrayOk: true
+        },
+        color: {
+            valType: 'color',
+            
+            arrayOk: true
+        },
+        
+    },
+    r: {
+        valType: 'data_array',
+        
+    },
+    t: {
+        valType: 'data_array',
+        
+    },
+    _nestedModules: {  // nested module coupling
+        'error_y': 'ErrorBars',
+        'error_x': 'ErrorBars',
+        'marker.colorbar': 'Colorbar'
+    }
+};
+
+},{"../../components/drawing":317,"./constants":506}],503:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+var Axes = require('../../plots/cartesian/axes');
+var Lib = require('../../lib');
+
+var subTypes = require('./subtypes');
+var calcMarkerColorscale = require('./marker_colorscale_calc');
+
+
+module.exports = function calc(gd, trace) {
+    var xa = Axes.getFromId(gd, trace.xaxis || 'x'),
+        ya = Axes.getFromId(gd, trace.yaxis || 'y');
+    Lib.markTime('in Scatter.calc');
+
+    var x = xa.makeCalcdata(trace, 'x');
+    Lib.markTime('finished convert x');
+
+    var y = ya.makeCalcdata(trace, 'y');
+    Lib.markTime('finished convert y');
+
+    var serieslen = Math.min(x.length, y.length),
+        marker,
+        s,
+        i;
+
+    // cancel minimum tick spacings (only applies to bars and boxes)
+    xa._minDtick = 0;
+    ya._minDtick = 0;
+
+    if(x.length > serieslen) x.splice(serieslen, x.length - serieslen);
+    if(y.length > serieslen) y.splice(serieslen, y.length - serieslen);
+
+    // check whether bounds should be tight, padded, extended to zero...
+    // most cases both should be padded on both ends, so start with that.
+    var xOptions = {padded: true},
+        yOptions = {padded: true};
+
+    if(subTypes.hasMarkers(trace)) {
+
+        // Treat size like x or y arrays --- Run d2c
+        // this needs to go before ppad computation
+        marker = trace.marker;
+        s = marker.size;
+
+        if(Array.isArray(s)) {
+            // I tried auto-type but category and dates dont make much sense.
+            var ax = {type: 'linear'};
+            Axes.setConvert(ax);
+            s = ax.makeCalcdata(trace.marker, 'size');
+            if(s.length > serieslen) s.splice(serieslen, s.length - serieslen);
+        }
+
+        var sizeref = 1.6 * (trace.marker.sizeref || 1),
+            markerTrans;
+        if(trace.marker.sizemode === 'area') {
+            markerTrans = function(v) {
+                return Math.max(Math.sqrt((v || 0) / sizeref), 3);
+            };
+        }
+        else {
+            markerTrans = function(v) {
+                return Math.max((v || 0) / sizeref, 3);
+            };
+        }
+        xOptions.ppad = yOptions.ppad = Array.isArray(s) ?
+            s.map(markerTrans) : markerTrans(s);
+    }
+
+    calcMarkerColorscale(trace);
+
+    // TODO: text size
+
+    // include zero (tight) and extremes (padded) if fill to zero
+    // (unless the shape is closed, then it's just filling the shape regardless)
+    if(((trace.fill === 'tozerox') ||
+            ((trace.fill === 'tonextx') && gd.firstscatter)) &&
+            ((x[0] !== x[serieslen - 1]) || (y[0] !== y[serieslen - 1]))) {
+        xOptions.tozero = true;
+    }
+
+    // if no error bars, markers or text, or fill to y=0 remove x padding
+    else if(!trace.error_y.visible && (
+            ['tonexty', 'tozeroy'].indexOf(trace.fill) !== -1 ||
+            (!subTypes.hasMarkers(trace) && !subTypes.hasText(trace))
+        )) {
+        xOptions.padded = false;
+        xOptions.ppad = 0;
+    }
+
+    // now check for y - rather different logic, though still mostly padded both ends
+    // include zero (tight) and extremes (padded) if fill to zero
+    // (unless the shape is closed, then it's just filling the shape regardless)
+    if(((trace.fill === 'tozeroy') || ((trace.fill === 'tonexty') && gd.firstscatter)) &&
+            ((x[0] !== x[serieslen - 1]) || (y[0] !== y[serieslen - 1]))) {
+        yOptions.tozero = true;
+    }
+
+    // tight y: any x fill
+    else if(['tonextx', 'tozerox'].indexOf(trace.fill) !== -1) {
+        yOptions.padded = false;
+    }
+
+    Lib.markTime('ready for Axes.expand');
+    Axes.expand(xa, x, xOptions);
+    Lib.markTime('done expand x');
+    Axes.expand(ya, y, yOptions);
+    Lib.markTime('done expand y');
+
+    // create the "calculated data" to plot
+    var cd = new Array(serieslen);
+    for(i = 0; i < serieslen; i++) {
+        cd[i] = (isNumeric(x[i]) && isNumeric(y[i])) ?
+            {x: x[i], y: y[i]} : {x: false, y: false};
+    }
+
+    // this has migrated up from arraysToCalcdata as we have a reference to 's' here
+    if(typeof s !== undefined) Lib.mergeArray(s, cd, 'ms');
+
+    gd.firstscatter = false;
+    return cd;
+};
+
+},{"../../lib":349,"../../plots/cartesian/axes":369,"./marker_colorscale_calc":515,"./subtypes":520,"fast-isnumeric":74}],504:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+
+module.exports = function cleanData(fullData) {
+    var i,
+        tracei,
+        filli,
+        j,
+        tracej;
+
+    // remove opacity for any trace that has a fill or is filled to
+    for(i = 0; i < fullData.length; i++) {
+        tracei = fullData[i];
+        filli = tracei.fill;
+        if((filli === 'none') || (tracei.type !== 'scatter')) continue;
+        tracei.opacity = undefined;
+
+        if(filli === 'tonexty' || filli === 'tonextx') {
+            for(j = i - 1; j >= 0; j--) {
+                tracej = fullData[j];
+                if((tracej.type === 'scatter') &&
+                        (tracej.xaxis === tracei.xaxis) &&
+                        (tracej.yaxis === tracei.yaxis)) {
+                    tracej.opacity = undefined;
+                    break;
+                }
+            }
+        }
+    }
+};
+
+},{}],505:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+var Plots = require('../../plots/plots');
+var getColorscale = require('../../components/colorscale/get_scale');
+var drawColorbar = require('../../components/colorbar/draw');
+
+
+module.exports = function colorbar(gd, cd) {
+    var trace = cd[0].trace,
+        marker = trace.marker,
+        cbId = 'cb' + trace.uid;
+
+    gd._fullLayout._infolayer.selectAll('.' + cbId).remove();
+
+    // TODO unify Scatter.colorbar and Heatmap.colorbar
+    // TODO make Plotly[module].colorbar support multiple colorbar per trace
+
+    if((marker === undefined) || !marker.showscale) {
+        Plots.autoMargin(gd, cbId);
+        return;
+    }
+
+    var scl = getColorscale(marker.colorscale),
+        vals = marker.color,
+        cmin = marker.cmin,
+        cmax = marker.cmax;
+
+    if(!isNumeric(cmin)) cmin = Lib.aggNums(Math.min, null, vals);
+    if(!isNumeric(cmax)) cmax = Lib.aggNums(Math.max, null, vals);
+
+    var cb = cd[0].t.cb = drawColorbar(gd, cbId);
+
+    cb.fillcolor(d3.scale.linear()
+            .domain(scl.map(function(v) { return cmin + v[0] * (cmax - cmin); }))
+            .range(scl.map(function(v) { return v[1]; })))
+        .filllevels({start: cmin, end: cmax, size: (cmax - cmin) / 254})
+        .options(marker.colorbar)();
+
+    Lib.markTime('done colorbar');
+};
+
+},{"../../components/colorbar/draw":302,"../../components/colorscale/get_scale":310,"../../lib":349,"../../plots/plots":413,"d3":70,"fast-isnumeric":74}],506:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+module.exports = {
+    PTS_LINESONLY: 20
+};
+
+},{}],507:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var attributes = require('./attributes');
+var constants = require('./constants');
+var subTypes = require('./subtypes');
+var handleXYDefaults = require('./xy_defaults');
+var handleMarkerDefaults = require('./marker_defaults');
+var handleLineDefaults = require('./line_defaults');
+var handleTextDefaults = require('./text_defaults');
+var handleFillColorDefaults = require('./fillcolor_defaults');
+var errorBarsSupplyDefaults = require('../../components/errorbars/defaults');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    var len = handleXYDefaults(traceIn, traceOut, coerce),
+        // TODO: default mode by orphan points...
+        defaultMode = len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines';
+    if(!len) {
+        traceOut.visible = false;
+        return;
+    }
+
+    coerce('text');
+    coerce('mode', defaultMode);
+
+    if(subTypes.hasLines(traceOut)) {
+        handleLineDefaults(traceIn, traceOut, defaultColor, coerce);
+        lineShapeDefaults(traceIn, traceOut, coerce);
+        coerce('connectgaps');
+    }
+
+    if(subTypes.hasMarkers(traceOut)) {
+        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce);
+    }
+
+    if(subTypes.hasText(traceOut)) {
+        handleTextDefaults(traceIn, traceOut, layout, coerce);
+    }
+
+    if(subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
+        coerce('marker.maxdisplayed');
+    }
+
+    coerce('fill');
+    if(traceOut.fill !== 'none') {
+        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
+        if(!subTypes.hasLines(traceOut)) lineShapeDefaults(traceIn, traceOut, coerce);
+    }
+
+    errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'});
+    errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'});
+};
+
+function lineShapeDefaults(traceIn, traceOut, coerce) {
+    var shape = coerce('line.shape');
+    if(shape === 'spline') coerce('line.smoothing');
+}
+
+},{"../../components/errorbars/defaults":322,"../../lib":349,"./attributes":502,"./constants":506,"./fillcolor_defaults":508,"./line_defaults":512,"./marker_defaults":516,"./subtypes":520,"./text_defaults":521,"./xy_defaults":522}],508:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Color = require('../../components/color');
+
+
+// common to 'scatter' and 'scattergl'
+module.exports = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) {
+    var inheritColorFromMarker = false;
+
+    if(traceOut.marker) {
+        // don't try to inherit a color array
+        var markerColor = traceOut.marker.color,
+            markerLineColor = (traceOut.marker.line || {}).color;
+
+        if(markerColor && !Array.isArray(markerColor)) {
+            inheritColorFromMarker = markerColor;
+        }
+        else if(markerLineColor && !Array.isArray(markerLineColor)) {
+            inheritColorFromMarker = markerLineColor;
+        }
+    }
+
+    coerce('fillcolor', Color.addOpacity(
+        (traceOut.line || {}).color ||
+        inheritColorFromMarker ||
+        defaultColor, 0.5
+    ));
+};
+
+},{"../../components/color":299}],509:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Color = require('../../components/color');
+var subtypes = require('./subtypes');
+
+
+module.exports = function getTraceColor(trace, di) {
+    var lc, tc;
+
+    // TODO: text modes
+
+    if(trace.mode === 'lines') {
+        lc = trace.line.color;
+        return (lc && Color.opacity(lc)) ?
+            lc : trace.fillcolor;
+    }
+    else if(trace.mode === 'none') {
+        return trace.fill ? trace.fillcolor : '';
+    }
+    else {
+        var mc = di.mcc || (trace.marker || {}).color,
+            mlc = di.mlcc || ((trace.marker || {}).line || {}).color;
+
+        tc = (mc && Color.opacity(mc)) ? mc :
+            (mlc && Color.opacity(mlc) &&
+                (di.mlw || ((trace.marker || {}).line || {}).width)) ? mlc : '';
+
+        if(tc) {
+            // make sure the points aren't TOO transparent
+            if(Color.opacity(tc) < 0.3) {
+                return Color.addOpacity(tc, 0.3);
+            }
+            else return tc;
+        }
+        else {
+            lc = (trace.line || {}).color;
+            return (lc && Color.opacity(lc) &&
+                subtypes.hasLines(trace) && trace.line.width) ?
+                    lc : trace.fillcolor;
+        }
+    }
+};
+
+},{"../../components/color":299,"./subtypes":520}],510:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Fx = require('../../plots/cartesian/graph_interact');
+var ErrorBars = require('../../components/errorbars');
+var getTraceColor = require('./get_trace_color');
+
+
+module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
+    var cd = pointData.cd,
+        trace = cd[0].trace,
+        xa = pointData.xa,
+        ya = pointData.ya,
+        dx = function(di) {
+            // scatter points: d.mrc is the calculated marker radius
+            // adjust the distance so if you're inside the marker it
+            // always will show up regardless of point size, but
+            // prioritize smaller points
+            var rad = Math.max(3, di.mrc || 0);
+            return Math.max(Math.abs(xa.c2p(di.x)-xa.c2p(xval))-rad, 1-3/rad);
+        },
+        dy = function(di) {
+            var rad = Math.max(3, di.mrc || 0);
+            return Math.max(Math.abs(ya.c2p(di.y)-ya.c2p(yval))-rad, 1-3/rad);
+        },
+        dxy = function(di) {
+            var rad = Math.max(3, di.mrc || 0),
+                dx = Math.abs(xa.c2p(di.x)-xa.c2p(xval)),
+                dy = Math.abs(ya.c2p(di.y)-ya.c2p(yval));
+            return Math.max(Math.sqrt(dx*dx + dy*dy)-rad, 1-3/rad);
+        },
+        distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
+
+    Fx.getClosest(cd, distfn, pointData);
+
+    // skip the rest (for this trace) if we didn't find a close point
+    if(pointData.index === false) return;
+
+    // the closest data point
+    var di = cd[pointData.index],
+        xc = xa.c2p(di.x, true),
+        yc = ya.c2p(di.y, true),
+        rad = di.mrc || 1;
+
+    pointData.color = getTraceColor(trace, di);
+
+    pointData.x0 = xc - rad;
+    pointData.x1 = xc + rad;
+    pointData.xLabelVal = di.x;
+
+    pointData.y0 = yc - rad;
+    pointData.y1 = yc + rad;
+    pointData.yLabelVal = di.y;
+
+    if(di.tx) pointData.text = di.tx;
+    else if(trace.text) pointData.text = trace.text;
+
+    ErrorBars.hoverInfo(di, trace, pointData);
+
+    return [pointData];
+};
+
+},{"../../components/errorbars":323,"../../plots/cartesian/graph_interact":374,"./get_trace_color":509}],511:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Scatter = {};
+
+var subtypes = require('./subtypes');
+Scatter.hasLines = subtypes.hasLines;
+Scatter.hasMarkers = subtypes.hasMarkers;
+Scatter.hasText = subtypes.hasText;
+Scatter.isBubble = subtypes.isBubble;
+
+// traces with < this many points are by default shown
+// with points and lines, > just get lines
+Scatter.attributes = require('./attributes');
+Scatter.supplyDefaults = require('./defaults');
+Scatter.cleanData = require('./clean_data');
+Scatter.calc = require('./calc');
+Scatter.arraysToCalcdata = require('./arrays_to_calcdata');
+Scatter.plot = require('./plot');
+Scatter.colorbar = require('./colorbar');
+Scatter.style = require('./style');
+Scatter.hoverPoints = require('./hover');
+Scatter.selectPoints = require('./select');
+
+Scatter.moduleType = 'trace';
+Scatter.name = 'scatter';
+Scatter.basePlotModule = require('../../plots/cartesian');
+Scatter.categories = ['cartesian', 'symbols', 'markerColorscale', 'errorBarsOK', 'showLegend'];
+Scatter.meta = {
+    
+};
+
+module.exports = Scatter;
+
+},{"../../plots/cartesian":375,"./arrays_to_calcdata":501,"./attributes":502,"./calc":503,"./clean_data":504,"./colorbar":505,"./defaults":507,"./hover":510,"./plot":517,"./select":518,"./style":519,"./subtypes":520}],512:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+
+// common to 'scatter', 'scatter3d', 'scattergeo' and 'scattergl'
+module.exports = function lineDefaults(traceIn, traceOut, defaultColor, coerce) {
+    var markerColor = (traceIn.marker || {}).color;
+
+    // don't try to inherit a color array
+    coerce('line.color', (Array.isArray(markerColor) ? false : markerColor) ||
+                         defaultColor);
+    coerce('line.width');
+    coerce('line.dash');
+};
+
+},{}],513:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Axes = require('../../plots/cartesian/axes');
+
+
+module.exports = function linePoints(d, opts) {
+    var xa = opts.xaxis,
+        ya = opts.yaxis,
+        connectGaps = opts.connectGaps,
+        baseTolerance = opts.baseTolerance,
+        linear = opts.linear,
+        segments = [],
+        badnum = Axes.BADNUM,
+        minTolerance = 0.2, // fraction of tolerance "so close we don't even consider it a new point"
+        pts = new Array(d.length),
+        pti = 0,
+        i,
+
+        // pt variables are pixel coordinates [x,y] of one point
+        clusterStartPt, // these four are the outputs of clustering on a line
+        clusterEndPt,
+        clusterHighPt,
+        clusterLowPt,
+        thisPt, // "this" is the next point we're considering adding to the cluster
+
+        clusterRefDist,
+        clusterHighFirst, // did we encounter the high point first, then a low point, or vice versa?
+        clusterUnitVector, // the first two points in the cluster determine its unit vector
+                           // so the second is always in the "High" direction
+        thisVector, // the pixel delta from clusterStartPt
+
+        // val variables are (signed) pixel distances along the cluster vector
+        clusterHighVal,
+        clusterLowVal,
+        thisVal,
+
+        // deviation variables are (signed) pixel distances normal to the cluster vector
+        clusterMinDeviation,
+        clusterMaxDeviation,
+        thisDeviation;
+
+    // turn one calcdata point into pixel coordinates
+    function getPt(index) {
+        var x = xa.c2p(d[index].x),
+            y = ya.c2p(d[index].y);
+        if(x === badnum || y === badnum) return false;
+        return [x, y];
+    }
+
+    // if we're off-screen, increase tolerance over baseTolerance
+    function getTolerance(pt) {
+        var xFrac = pt[0] / xa._length,
+            yFrac = pt[1] / ya._length;
+        return (1 + 10 * Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1)) * baseTolerance;
+    }
+
+    function ptDist(pt1, pt2) {
+        var dx = pt1[0] - pt2[0],
+            dy = pt1[1] - pt2[1];
+        return Math.sqrt(dx * dx + dy * dy);
+    }
+
+    // loop over ALL points in this trace
+    for(i = 0; i < d.length; i++) {
+        clusterStartPt = getPt(i);
+        if(!clusterStartPt) continue;
+
+        pti = 0;
+        pts[pti++] = clusterStartPt;
+
+        // loop over one segment of the trace
+        for(i++; i < d.length; i++) {
+            clusterHighPt = getPt(i);
+            if(!clusterHighPt) {
+                if(connectGaps) continue;
+                else break;
+            }
+
+            // can't decimate if nonlinear line shape
+            // TODO: we *could* decimate [hv]{2,3} shapes if we restricted clusters to horz or vert again
+            // but spline would be verrry awkward to decimate
+            if(!linear) {
+                pts[pti++] = clusterHighPt;
+                continue;
+            }
+
+            clusterRefDist = ptDist(clusterHighPt, clusterStartPt);
+
+            if(clusterRefDist < getTolerance(clusterHighPt) * minTolerance) continue;
+
+            clusterUnitVector = [
+                (clusterHighPt[0] - clusterStartPt[0]) / clusterRefDist,
+                (clusterHighPt[1] - clusterStartPt[1]) / clusterRefDist
+            ];
+
+            clusterLowPt = clusterStartPt;
+            clusterHighVal = clusterRefDist;
+            clusterLowVal = clusterMinDeviation = clusterMaxDeviation = 0;
+            clusterHighFirst = false;
+            clusterEndPt = clusterHighPt;
+
+            // loop over one cluster of points that collapse onto one line
+            for(i++; i < d.length; i++) {
+                thisPt = getPt(i);
+                if(!thisPt) {
+                    if(connectGaps) continue;
+                    else break;
+                }
+                thisVector = [
+                    thisPt[0] - clusterStartPt[0],
+                    thisPt[1] - clusterStartPt[1]
+                ];
+                // cross product (or dot with normal to the cluster vector)
+                thisDeviation = thisVector[0] * clusterUnitVector[1] - thisVector[1] * clusterUnitVector[0];
+                clusterMinDeviation = Math.min(clusterMinDeviation, thisDeviation);
+                clusterMaxDeviation = Math.max(clusterMaxDeviation, thisDeviation);
+
+                if(clusterMaxDeviation - clusterMinDeviation > getTolerance(thisPt)) break;
+
+                clusterEndPt = thisPt;
+                thisVal = thisVector[0] * clusterUnitVector[0] + thisVector[1] * clusterUnitVector[1];
+
+                if(thisVal > clusterHighVal) {
+                    clusterHighVal = thisVal;
+                    clusterHighPt = thisPt;
+                    clusterHighFirst = false;
+                } else if(thisVal < clusterLowVal) {
+                    clusterLowVal = thisVal;
+                    clusterLowPt = thisPt;
+                    clusterHighFirst = true;
+                }
+            }
+
+            // insert this cluster into pts
+            // we've already inserted the start pt, now check if we have high and low pts
+            if(clusterHighFirst) {
+                pts[pti++] = clusterHighPt;
+                if(clusterEndPt !== clusterLowPt) pts[pti++] = clusterLowPt;
+            } else {
+                if(clusterLowPt !== clusterStartPt) pts[pti++] = clusterLowPt;
+                if(clusterEndPt !== clusterHighPt) pts[pti++] = clusterHighPt;
+            }
+            // and finally insert the end pt
+            pts[pti++] = clusterEndPt;
+
+            // have we reached the end of this segment?
+            if(i >= d.length || !thisPt) break;
+
+            // otherwise we have an out-of-cluster point to insert as next clusterStartPt
+            pts[pti++] = thisPt;
+            clusterStartPt = thisPt;
+        }
+
+        segments.push(pts.slice(0, pti));
+    }
+
+    return segments;
+};
+
+},{"../../plots/cartesian/axes":369}],514:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var isNumeric = require('fast-isnumeric');
+
+
+// used in the drawing step for 'scatter' and 'scattegeo' and
+// in the convert step for 'scatter3d'
+module.exports = function makeBubbleSizeFn(trace) {
+    var marker = trace.marker,
+        sizeRef = marker.sizeref || 1,
+        sizeMin = marker.sizemin || 0;
+
+    // for bubble charts, allow scaling the provided value linearly
+    // and by area or diameter.
+    // Note this only applies to the array-value sizes
+
+    var baseFn = (marker.sizemode === 'area') ?
+            function(v) { return Math.sqrt(v / sizeRef); } :
+            function(v) { return v / sizeRef; };
+
+    // TODO add support for position/negative bubbles?
+    // TODO add 'sizeoffset' attribute?
+    return function(v) {
+        var baseSize = baseFn(v / 2);
+
+        // don't show non-numeric and negative sizes
+        return (isNumeric(baseSize) && (baseSize > 0)) ?
+            Math.max(baseSize, sizeMin) :
+            0;
+    };
+};
+
+},{"fast-isnumeric":74}],515:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var hasColorscale = require('../../components/colorscale/has_colorscale');
+var calcColorscale = require('../../components/colorscale/calc');
+
+var subTypes = require('./subtypes');
+
+
+// common to 'scatter', 'scatter3d' and 'scattergeo'
+module.exports = function calcMarkerColorscale(trace) {
+    if(!subTypes.hasMarkers(trace)) return;
+
+    var marker = trace.marker;
+
+    // auto-z and autocolorscale if applicable
+    if(hasColorscale(trace, 'marker')) {
+        calcColorscale(trace, marker.color, 'marker', 'c');
+    }
+
+    if(hasColorscale(trace, 'marker.line')) {
+        calcColorscale(trace, marker.line.color, 'marker.line', 'c');
+    }
+};
+
+},{"../../components/colorscale/calc":306,"../../components/colorscale/has_colorscale":311,"./subtypes":520}],516:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Color = require('../../components/color');
+var hasColorscale = require('../../components/colorscale/has_colorscale');
+var colorscaleDefaults = require('../../components/colorscale/defaults');
+
+var subTypes = require('./subtypes');
+
+
+// common to 'scatter', 'scatter3d', 'scattergeo' and 'scattergl'
+module.exports = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce) {
+    var isBubble = subTypes.isBubble(traceIn),
+        lineColor = (traceIn.line || {}).color,
+        defaultMLC;
+
+    if(lineColor) defaultColor = lineColor;
+
+    coerce('marker.symbol');
+    coerce('marker.opacity', isBubble ? 0.7 : 1);
+    coerce('marker.size');
+
+    coerce('marker.color', defaultColor);
+    if(hasColorscale(traceIn, 'marker')) {
+        colorscaleDefaults(
+            traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'}
+        );
+    }
+
+    // if there's a line with a different color than the marker, use
+    // that line color as the default marker line color
+    // mostly this is for transparent markers to behave nicely
+    if(lineColor && (traceOut.marker.color !== lineColor)) {
+        defaultMLC = lineColor;
+    }
+    else if(isBubble) defaultMLC = Color.background;
+    else defaultMLC = Color.defaultLine;
+
+    coerce('marker.line.color', defaultMLC);
+    if(hasColorscale(traceIn, 'marker.line')) {
+        colorscaleDefaults(
+            traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'}
+        );
+    }
+
+    coerce('marker.line.width', isBubble ? 1 : 0);
+
+    if(isBubble) {
+        coerce('marker.sizeref');
+        coerce('marker.sizemin');
+        coerce('marker.sizemode');
+    }
+};
+
+},{"../../components/color":299,"../../components/colorscale/defaults":308,"../../components/colorscale/has_colorscale":311,"./subtypes":520}],517:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var Lib = require('../../lib');
+var Drawing = require('../../components/drawing');
+
+var subTypes = require('./subtypes');
+var arraysToCalcdata = require('./arrays_to_calcdata');
+var linePoints = require('./line_points');
+
+
+module.exports = function plot(gd, plotinfo, cdscatter) {
+    selectMarkers(gd, plotinfo, cdscatter);
+
+    var xa = plotinfo.x(),
+        ya = plotinfo.y();
+
+    // make the container for scatter plots
+    // (so error bars can find them along with bars)
+    var scattertraces = plotinfo.plot.select('.scatterlayer')
+        .selectAll('g.trace.scatter')
+        .data(cdscatter);
+    scattertraces.enter().append('g')
+        .attr('class', 'trace scatter')
+        .style('stroke-miterlimit', 2);
+
+    // BUILD LINES AND FILLS
+    var prevpath = '',
+        tozero, tonext, nexttonext;
+
+    scattertraces.each(function(d) {
+        var trace = d[0].trace,
+            line = trace.line,
+            tr = d3.select(this);
+        if(trace.visible !== true) return;
+
+        d[0].node3 = tr; // store node for tweaking by selectPoints
+
+        arraysToCalcdata(d);
+
+        if(!subTypes.hasLines(trace) && trace.fill === 'none') return;
+
+        var thispath,
+            // fullpath is all paths for this curve, joined together straight
+            // across gaps, for filling
+            fullpath = '',
+            // revpath is fullpath reversed, for fill-to-next
+            revpath = '',
+            // functions for converting a point array to a path
+            pathfn, revpathbase, revpathfn;
+
+        // make the fill-to-zero path now, so it shows behind the line
+        // fill to next puts the fill associated with one trace
+        // grouped with the previous
+        if(trace.fill.substr(0, 6) === 'tozero' ||
+                (trace.fill.substr(0, 2) === 'to' && !prevpath)) {
+            tozero = tr.append('path')
+                .classed('js-fill', true);
+        }
+        else tozero = null;
+
+        // make the fill-to-next path now for the NEXT trace, so it shows
+        // behind both lines.
+        // nexttonext was created last time, but give it
+        // this curve's data for fill color
+        if(nexttonext) tonext = nexttonext.datum(d);
+
+        // now make a new nexttonext for next time
+        nexttonext = tr.append('path').classed('js-fill', true);
+
+        if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) {
+            pathfn = Drawing.steps(line.shape);
+            revpathbase = Drawing.steps(
+                line.shape.split('').reverse().join('')
+            );
+        }
+        else if(line.shape === 'spline') {
+            pathfn = revpathbase = function(pts) {
+                return Drawing.smoothopen(pts, line.smoothing);
+            };
+        }
+        else {
+            pathfn = revpathbase = function(pts) {
+                return 'M' + pts.join('L');
+            };
+        }
+
+        revpathfn = function(pts) {
+            // note: this is destructive (reverses pts in place) so can't use pts after this
+            return 'L' + revpathbase(pts.reverse()).substr(1);
+        };
+
+        var segments = linePoints(d, {
+            xaxis: xa,
+            yaxis: ya,
+            connectGaps: trace.connectgaps,
+            baseTolerance: Math.max(line.width || 1, 3) / 4,
+            linear: line.shape === 'linear'
+        });
+
+        if(segments.length) {
+            var pt0 = segments[0][0],
+                lastSegment = segments[segments.length - 1],
+                pt1 = lastSegment[lastSegment.length - 1];
+
+            for(var i = 0; i < segments.length; i++) {
+                var pts = segments[i];
+                thispath = pathfn(pts);
+                fullpath += fullpath ? ('L' + thispath.substr(1)) : thispath;
+                revpath = revpathfn(pts) + revpath;
+                if(subTypes.hasLines(trace) && pts.length > 1) {
+                    tr.append('path').classed('js-line', true).attr('d', thispath);
+                }
+            }
+            if(tozero) {
+                if(pt0 && pt1) {
+                    if(trace.fill.charAt(trace.fill.length - 1) === 'y') {
+                        pt0[1] = pt1[1] = ya.c2p(0, true);
+                    }
+                    else pt0[0] = pt1[0] = xa.c2p(0, true);
+
+                    // fill to zero: full trace path, plus extension of
+                    // the endpoints to the appropriate axis
+                    tozero.attr('d', fullpath + 'L' + pt1 + 'L' + pt0 + 'Z');
+                }
+            }
+            else if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevpath) {
+                // fill to next: full trace path, plus the previous path reversed
+                tonext.attr('d', fullpath + prevpath + 'Z');
+            }
+            prevpath = revpath;
+        }
+    });
+
+    // remove paths that didn't get used
+    scattertraces.selectAll('path:not([d])').remove();
+
+    function visFilter(d) {
+        return d.filter(function(v) { return v.vis; });
+    }
+
+    scattertraces.append('g')
+        .attr('class', 'points')
+        .each(function(d) {
+            var trace = d[0].trace,
+                s = d3.select(this),
+                showMarkers = subTypes.hasMarkers(trace),
+                showText = subTypes.hasText(trace);
+
+            if((!showMarkers && !showText) || trace.visible !== true) s.remove();
+            else {
+                if(showMarkers) {
+                    s.selectAll('path.point')
+                        .data(trace.marker.maxdisplayed ? visFilter : Lib.identity)
+                        .enter().append('path')
+                            .classed('point', true)
+                            .call(Drawing.translatePoints, xa, ya);
+                }
+                if(showText) {
+                    s.selectAll('g')
+                        .data(trace.marker.maxdisplayed ? visFilter : Lib.identity)
+                        // each text needs to go in its own 'g' in case
+                        // it gets converted to mathjax
+                        .enter().append('g')
+                            .append('text')
+                            .call(Drawing.translatePoints, xa, ya);
+                }
+            }
+        });
+};
+
+function selectMarkers(gd, plotinfo, cdscatter) {
+    var xa = plotinfo.x(),
+        ya = plotinfo.y(),
+        xr = d3.extent(xa.range.map(xa.l2c)),
+        yr = d3.extent(ya.range.map(ya.l2c));
+
+    cdscatter.forEach(function(d, i) {
+        var trace = d[0].trace;
+        if(!subTypes.hasMarkers(trace)) return;
+        // if marker.maxdisplayed is used, select a maximum of
+        // mnum markers to show, from the set that are in the viewport
+        var mnum = trace.marker.maxdisplayed;
+
+        // TODO: remove some as we get away from the viewport?
+        if(mnum === 0) return;
+
+        var cd = d.filter(function(v) {
+                return v.x>=xr[0] && v.x<=xr[1] && v.y>=yr[0] && v.y<=yr[1];
+            }),
+            inc = Math.ceil(cd.length / mnum),
+            tnum = 0;
+        cdscatter.forEach(function(cdj, j) {
+            var tracei = cdj[0].trace;
+            if(subTypes.hasMarkers(tracei) &&
+                    tracei.marker.maxdisplayed>0 && j<i) {
+                tnum++;
+            }
+        });
+
+        // if multiple traces use maxdisplayed, stagger which markers we
+        // display this formula offsets successive traces by 1/3 of the
+        // increment, adding an extra small amount after each triplet so
+        // it's not quite periodic
+        var i0 = Math.round(tnum*inc/3 + Math.floor(tnum/3) * inc/7.1);
+
+        // for error bars: save in cd which markers to show
+        // so we don't have to repeat this
+        d.forEach(function(v) { delete v.vis; });
+        cd.forEach(function(v, i) {
+            if(Math.round((i + i0) % inc) === 0) v.vis = true;
+        });
+    });
+}
+
+},{"../../components/drawing":317,"../../lib":349,"./arrays_to_calcdata":501,"./line_points":513,"./subtypes":520,"d3":70}],518:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var subtypes = require('./subtypes');
+
+var DESELECTDIM = 0.2;
+
+module.exports = function selectPoints(searchInfo, polygon) {
+    var cd = searchInfo.cd,
+        xa = searchInfo.xaxis,
+        ya = searchInfo.yaxis,
+        selection = [],
+        trace = cd[0].trace,
+        curveNumber = trace.index,
+        marker = trace.marker,
+        i,
+        di,
+        x,
+        y;
+
+    // TODO: include lines? that would require per-segment line properties
+    if(!subtypes.hasMarkers(trace) && ! subtypes.hasText(trace)) return;
+
+    var opacity = Array.isArray(marker.opacity) ? 1 : marker.opacity;
+
+    if(polygon === false) { // clear selection
+        for(i = 0; i < cd.length; i++) cd[i].dim = 0;
+    }
+    else {
+        for(i = 0; i < cd.length; i++) {
+            di = cd[i];
+            x = xa.c2p(di.x);
+            y = ya.c2p(di.y);
+            if(polygon.contains([x, y])) {
+                selection.push({
+                    curveNumber: curveNumber,
+                    pointNumber: i,
+                    x: di.x,
+                    y: di.y
+                });
+                di.dim = 0;
+            }
+            else di.dim = 1;
+        }
+    }
+
+    // do the dimming here, as well as returning the selection
+    // The logic here duplicates Drawing.pointStyle, but I don't want
+    // d.dim in pointStyle in case something goes wrong with selection.
+    cd[0].node3.selectAll('path.point')
+        .style('opacity', function(d) {
+            return ((d.mo+1 || opacity+1) - 1) * (d.dim ? DESELECTDIM : 1);
+        });
+    cd[0].node3.selectAll('text')
+        .style('opacity', function(d) {
+            return d.dim ? DESELECTDIM : 1;
+        });
+
+    return selection;
+};
+
+},{"./subtypes":520}],519:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var Drawing = require('../../components/drawing');
+
+
+module.exports = function style(gd) {
+    var s = d3.select(gd).selectAll('g.trace.scatter');
+
+    s.style('opacity', function(d) {
+        return d[0].trace.opacity;
+    });
+
+    s.selectAll('g.points')
+        .each(function(d) {
+            d3.select(this).selectAll('path.point')
+                .call(Drawing.pointStyle, d.trace || d[0].trace);
+            d3.select(this).selectAll('text')
+                .call(Drawing.textPointStyle, d.trace || d[0].trace);
+        });
+
+    s.selectAll('g.trace path.js-line')
+        .call(Drawing.lineGroupStyle);
+
+    s.selectAll('g.trace path.js-fill')
+        .call(Drawing.fillGroupStyle);
+};
+
+},{"../../components/drawing":317,"d3":70}],520:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+module.exports = {
+    hasLines: function(trace) {
+        return trace.visible && trace.mode &&
+            trace.mode.indexOf('lines') !== -1;
+    },
+
+    hasMarkers: function(trace) {
+        return trace.visible && trace.mode &&
+            trace.mode.indexOf('markers') !== -1;
+    },
+
+    hasText: function(trace) {
+        return trace.visible && trace.mode &&
+            trace.mode.indexOf('text') !== -1;
+    },
+
+    isBubble: function(trace) {
+        return (typeof trace.marker === 'object' &&
+                    Array.isArray(trace.marker.size));
+    }
+};
+
+},{}],521:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+
+// common to 'scatter', 'scatter3d' and 'scattergeo'
+module.exports = function(traceIn, traceOut, layout, coerce) {
+    coerce('textposition');
+    Lib.coerceFont(coerce, 'textfont', layout.font);
+};
+
+},{"../../lib":349}],522:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+
+module.exports = function handleXYDefaults(traceIn, traceOut, coerce) {
+    var len,
+        x = coerce('x'),
+        y = coerce('y');
+
+    if(x) {
+        if(y) {
+            len = Math.min(x.length, y.length);
+            // TODO: not sure we should do this here... but I think
+            // the way it works in calc is wrong, because it'll delete data
+            // which could be a problem eg in streaming / editing if x and y
+            // come in at different times
+            // so we need to revisit calc before taking this out
+            if(len < x.length) traceOut.x = x.slice(0, len);
+            if(len < y.length) traceOut.y = y.slice(0, len);
+        }
+        else {
+            len = x.length;
+            coerce('y0');
+            coerce('dy');
+        }
+    }
+    else {
+        if(!y) return 0;
+
+        len = traceOut.y.length;
+        coerce('x0');
+        coerce('dx');
+    }
+    return len;
+};
+
+},{}],523:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var scatterAttrs = require('../scatter/attributes');
+var MARKER_SYMBOLS = require('../../constants/gl_markers');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+var scatterLineAttrs = scatterAttrs.line,
+    scatterMarkerAttrs = scatterAttrs.marker,
+    scatterMarkerLineAttrs = scatterMarkerAttrs.line;
+
+function makeProjectionAttr(axLetter) {
+    return {
+        show: {
+            valType: 'boolean',
+            
+            dflt: false,
+            
+        },
+        opacity: {
+            valType: 'number',
+            
+            min: 0,
+            max: 1,
+            dflt: 1,
+            
+        },
+        scale: {
+            valType: 'number',
+            
+            min: 0,
+            max: 10,
+            dflt: 2/3,
+            
+        }
+    };
+}
+
+module.exports = {
+    x: {
+        valType: 'data_array',
+        
+    },
+    y: {
+        valType: 'data_array',
+        
+    },
+    z: {
+        valType: 'data_array',
+        
+    },
+    text: extendFlat({}, scatterAttrs.text, {
+        
+    }),
+    mode: extendFlat({}, scatterAttrs.mode,  // shouldn't this be on-par with 2D?
+        {dflt: 'lines+markers'}),
+    surfaceaxis: {
+        valType: 'enumerated',
+        
+        values: [-1, 0, 1, 2],
+        dflt: -1,
+        
+    },
+    surfacecolor: {
+        valType: 'color',
+        
+        
+    },
+    projection: {
+        x: makeProjectionAttr('x'),
+        y: makeProjectionAttr('y'),
+        z: makeProjectionAttr('z')
+    },
+    line: {
+        color: scatterLineAttrs.color,
+        width: scatterLineAttrs.width,
+        dash: scatterLineAttrs.dash
+    },
+    marker: {  // Parity with scatter.js?
+        color: scatterMarkerAttrs.color,
+        symbol: {
+            valType: 'enumerated',
+            values: Object.keys(MARKER_SYMBOLS),
+            
+            dflt: 'circle',
+            arrayOk: true,
+            
+        },
+        size: extendFlat({}, scatterMarkerAttrs.size, {dflt: 8}),
+        sizeref: scatterMarkerAttrs.sizeref,
+        sizemin: scatterMarkerAttrs.sizemin,
+        sizemode: scatterMarkerAttrs.sizemode,
+        opacity: extendFlat({}, scatterMarkerAttrs.opacity, {
+            arrayOk: false,
+            
+        }),
+        colorscale: scatterMarkerAttrs.colorscale,
+        cauto: scatterMarkerAttrs.cauto,
+        cmax: scatterMarkerAttrs.cmax,
+        cmin: scatterMarkerAttrs.cmin,
+        autocolorscale: scatterMarkerAttrs.autocolorscale,
+        reversescale: scatterMarkerAttrs.reversescale,
+        showscale: scatterMarkerAttrs.showscale,
+        line: {
+            color: scatterMarkerLineAttrs.color,
+            width: extendFlat({}, scatterMarkerLineAttrs.width, {arrayOk: false}),
+            colorscale: scatterMarkerLineAttrs.colorscale,
+            cauto: scatterMarkerLineAttrs.cauto,
+            cmax: scatterMarkerLineAttrs.cmax,
+            cmin: scatterMarkerLineAttrs.cmin,
+            autocolorscale: scatterMarkerLineAttrs.autocolorscale,
+            reversescale: scatterMarkerLineAttrs.reversescale
+        }
+    },
+    textposition: extendFlat({}, scatterAttrs.textposition, {dflt: 'top center'}),
+    textfont: scatterAttrs.textfont,
+    _nestedModules: {
+        'error_x': 'ErrorBars',
+        'error_y': 'ErrorBars',
+        'error_z': 'ErrorBars',
+        'marker.colorbar': 'Colorbar'
+    }
+};
+
+},{"../../constants/gl_markers":337,"../../lib/extend":345,"../scatter/attributes":502}],524:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var arraysToCalcdata = require('../scatter/arrays_to_calcdata');
+var calcMarkerColorscale = require('../scatter/marker_colorscale_calc');
+
+
+/**
+ * This is a kludge to put the array attributes into
+ * calcdata the way Scatter.plot does, so that legends and
+ * popovers know what to do with them.
+ */
+module.exports = function calc(gd, trace) {
+    var cd = [{x: false, y: false, trace: trace, t: {}}];
+
+    arraysToCalcdata(cd);
+    calcMarkerColorscale(trace);
+
+    return cd;
+};
+
+},{"../scatter/arrays_to_calcdata":501,"../scatter/marker_colorscale_calc":515}],525:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var makeComputeError = require('../../components/errorbars/compute_error');
+
+
+function calculateAxisErrors(data, params, scaleFactor) {
+    if(!params || !params.visible) return null;
+
+    var computeError = makeComputeError(params);
+    var result = new Array(data.length);
+
+    for(var i = 0; i < data.length; i++) {
+        var errors = computeError(+data[i], i);
+
+        result[i] = [
+            -errors[0] * scaleFactor,
+            errors[1] * scaleFactor
+        ];
+    }
+
+    return result;
+}
+
+function dataLength(array) {
+    for(var i = 0; i < array.length; i++) {
+        if(array[i]) return array[i].length;
+    }
+    return 0;
+}
+
+function calculateErrors(data, scaleFactor) {
+    var errors = [
+        calculateAxisErrors(data.x, data.error_x, scaleFactor[0]),
+        calculateAxisErrors(data.y, data.error_y, scaleFactor[1]),
+        calculateAxisErrors(data.z, data.error_z, scaleFactor[2])
+    ];
+
+    var n = dataLength(errors);
+    if(n === 0) return null;
+
+    var errorBounds = new Array(n);
+
+    for(var i = 0; i < n; i++) {
+        var bound = [[0,0,0], [0,0,0]];
+
+        for(var j = 0; j < 3; j++) {
+            if(errors[j]) {
+                for(var k = 0; k < 2; k++) {
+                    bound[k][j] = errors[j][i][k];
+                }
+            }
+        }
+
+        errorBounds[i] = bound;
+    }
+
+    return errorBounds;
+}
+
+module.exports = calculateErrors;
+
+},{"../../components/errorbars/compute_error":321}],526:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var createLinePlot = require('gl-line3d');
+var createScatterPlot = require('gl-scatter3d');
+var createErrorBars = require('gl-error3d');
+var createMesh = require('gl-mesh3d');
+var triangulate = require('delaunay-triangulate');
+
+var Lib = require('../../lib');
+var str2RgbaArray = require('../../lib/str2rgbarray');
+var formatColor = require('../../lib/gl_format_color');
+var makeBubbleSizeFn = require('../scatter/make_bubble_size_func');
+var DASH_PATTERNS = require('../../constants/gl3d_dashes');
+var MARKER_SYMBOLS = require('../../constants/gl_markers');
+
+var calculateError = require('./calc_errors');
+
+function LineWithMarkers(scene, uid) {
+    this.scene = scene;
+    this.uid = uid;
+    this.linePlot = null;
+    this.scatterPlot = null;
+    this.errorBars = null;
+    this.textMarkers = null;
+    this.delaunayMesh = null;
+    this.color = null;
+    this.mode = '';
+    this.dataPoints = [];
+    this.axesBounds = [
+        [-Infinity,-Infinity,-Infinity],
+        [Infinity,Infinity,Infinity]
+    ];
+    this.textLabels = null;
+    this.data = null;
+}
+
+var proto = LineWithMarkers.prototype;
+
+proto.handlePick = function(selection) {
+    if(selection.object &&
+        (selection.object === this.linePlot ||
+         selection.object === this.delaunayMesh ||
+         selection.object === this.textMarkers ||
+         selection.object === this.scatterPlot)) {
+        if(selection.object.highlight) {
+            selection.object.highlight(null);
+        }
+        if(this.scatterPlot) {
+            selection.object = this.scatterPlot;
+            this.scatterPlot.highlight(selection.data);
+        }
+        if(this.textLabels && this.textLabels[selection.data.index]!==undefined) {
+            selection.textLabel = this.textLabels[selection.data.index];
+        }
+        else selection.textLabel = '';
+
+        var selectIndex = selection.data.index;
+        selection.traceCoordinate = [
+            this.data.x[selectIndex],
+            this.data.y[selectIndex],
+            this.data.z[selectIndex]
+        ];
+
+        return true;
+    }
+};
+
+function constructDelaunay(points, color, axis) {
+    var u = (axis+1)%3;
+    var v = (axis+2)%3;
+    var filteredPoints = [];
+    var filteredIds = [];
+    var i;
+
+    for(i=0; i<points.length; ++i) {
+        var p = points[i];
+        if(isNaN(p[u]) || !isFinite(p[u]) ||
+           isNaN(p[v]) || !isFinite(p[v])) {
+            continue;
+        }
+        filteredPoints.push([p[u], p[v]]);
+        filteredIds.push(i);
+    }
+    var cells = triangulate(filteredPoints);
+    for(i=0; i<cells.length; ++i) {
+        var c = cells[i];
+        for(var j=0; j<c.length; ++j) {
+            c[j] = filteredIds[c[j]];
+        }
+    }
+    return {
+        positions: points,
+        cells: cells,
+        meshColor: color
+    };
+}
+
+function calculateErrorParams(errors) {
+    var capSize = [0.0, 0.0, 0.0],
+        color = [[0,0,0], [0,0,0], [0,0,0]],
+        lineWidth = [0.0, 0.0, 0.0];
+
+    for(var i = 0; i < 3; i++) {
+        var e = errors[i];
+
+        if(e && e.copy_zstyle !== false) e = errors[2];
+        if(!e) continue;
+
+        capSize[i] = e.width / 2;  // ballpark rescaling
+        color[i] = str2RgbaArray(e.color);
+        lineWidth = e.thickness;
+
+    }
+
+    return {capSize: capSize, color: color, lineWidth: lineWidth};
+}
+
+function calculateTextOffset(tp) {
+    //Read out text properties
+    var textOffset = [0, 0];
+    if(Array.isArray(tp)) return [0, -1];
+    if(tp.indexOf('bottom') >= 0) textOffset[1] += 1;
+    if(tp.indexOf('top') >= 0) textOffset[1] -= 1;
+    if(tp.indexOf('left') >= 0) textOffset[0] -= 1;
+    if(tp.indexOf('right') >= 0) textOffset[0] += 1;
+    return textOffset;
+}
+
+
+function calculateSize(sizeIn, sizeFn) {
+    // rough parity with Plotly 2D markers
+    return sizeFn(sizeIn * 4);
+}
+
+function calculateSymbol(symbolIn) {
+    return MARKER_SYMBOLS[symbolIn];
+}
+
+function formatParam(paramIn, len, calculate, dflt, extraFn) {
+    var paramOut = null;
+
+    if(Array.isArray(paramIn)) {
+        paramOut = [];
+
+        for(var i = 0; i < len; i++) {
+            if(paramIn[i]===undefined) paramOut[i] = dflt;
+            else paramOut[i] = calculate(paramIn[i], extraFn);
+        }
+
+    }
+    else paramOut = calculate(paramIn, Lib.identity);
+
+    return paramOut;
+}
+
+
+function convertPlotlyOptions(scene, data) {
+    var params, i,
+        points = [],
+        sceneLayout = scene.fullSceneLayout,
+        scaleFactor = scene.dataScale,
+        xaxis = sceneLayout.xaxis,
+        yaxis = sceneLayout.yaxis,
+        zaxis = sceneLayout.zaxis,
+        marker = data.marker,
+        line = data.line,
+        xc, x = data.x || [],
+        yc, y = data.y || [],
+        zc, z = data.z || [],
+        len = x.length,
+        text;
+
+    //Convert points
+    for(i = 0; i < len; i++) {
+        // sanitize numbers and apply transforms based on axes.type
+        xc = xaxis.d2l(x[i]) * scaleFactor[0];
+        yc = yaxis.d2l(y[i]) * scaleFactor[1];
+        zc = zaxis.d2l(z[i]) * scaleFactor[2];
+
+        points[i] = [xc, yc, zc];
+    }
+
+    // convert text
+    if(Array.isArray(data.text)) text = data.text;
+    else if(data.text !== undefined) {
+        text = new Array(len);
+        for(i = 0; i < len; i++) text[i] = data.text;
+    }
+
+    //Build object parameters
+    params = {
+        position: points,
+        mode: data.mode,
+        text: text
+    };
+
+    if('line' in data) {
+        params.lineColor = str2RgbaArray(line.color);
+        params.lineWidth = line.width;
+        params.lineDashes = line.dash;
+    }
+
+    if('marker' in data) {
+        var sizeFn = makeBubbleSizeFn(data);
+
+        params.scatterColor = formatColor(marker, 1, len);
+        params.scatterSize = formatParam(marker.size, len, calculateSize, 20, sizeFn);
+        params.scatterMarker = formatParam(marker.symbol, len, calculateSymbol, 'â');
+        params.scatterLineWidth = marker.line.width;  // arrayOk === false
+        params.scatterLineColor = formatColor(marker.line, 1, len);
+        params.scatterAngle = 0;
+    }
+
+    if('textposition' in data) {
+        params.textOffset = calculateTextOffset(data.textposition);  // arrayOk === false
+        params.textColor = formatColor(data.textfont, 1, len);
+        params.textSize = formatParam(data.textfont.size, len, Lib.identity, 12);
+        params.textFont = data.textfont.family;  // arrayOk === false
+        params.textAngle = 0;
+    }
+
+    var dims = ['x', 'y', 'z'];
+    params.project = [false, false, false];
+    params.projectScale = [1,1,1];
+    params.projectOpacity = [1,1,1];
+    for(i = 0; i < 3; ++i) {
+        var projection = data.projection[dims[i]];
+        if((params.project[i] = projection.show)) {
+            params.projectOpacity[i] = projection.opacity;
+            params.projectScale[i] = projection.scale;
+        }
+    }
+
+    params.errorBounds = calculateError(data, scaleFactor);
+
+    var errorParams = calculateErrorParams([data.error_x, data.error_y, data.error_z]);
+    params.errorColor = errorParams.color;
+    params.errorLineWidth = errorParams.lineWidth;
+    params.errorCapSize = errorParams.capSize;
+
+    params.delaunayAxis = data.surfaceaxis;
+    params.delaunayColor = str2RgbaArray(data.surfacecolor);
+
+    return params;
+}
+
+function arrayToColor(color) {
+    if(Array.isArray(color)) {
+        var c = color[0];
+
+        if(Array.isArray(c)) color = c;
+
+        return 'rgb(' + color.slice(0,3).map(function(x) {
+            return Math.round(x*255);
+        }) + ')';
+    }
+
+    return null;
+}
+
+proto.update = function(data) {
+    var gl = this.scene.glplot.gl,
+        lineOptions,
+        scatterOptions,
+        errorOptions,
+        textOptions,
+        dashPattern = DASH_PATTERNS.solid;
+
+    //Save data
+    this.data = data;
+
+    //Run data conversion
+    var options = convertPlotlyOptions(this.scene, data);
+
+    if('mode' in options) {
+        this.mode = options.mode;
+    }
+    if('lineDashes' in options) {
+        if(options.lineDashes in DASH_PATTERNS) {
+            dashPattern = DASH_PATTERNS[options.lineDashes];
+        }
+    }
+
+    this.color = arrayToColor(options.scatterColor) ||
+                 arrayToColor(options.lineColor);
+
+    //Save data points
+    this.dataPoints = options.position;
+
+    lineOptions = {
+        gl: gl,
+        position: options.position,
+        color: options.lineColor,
+        lineWidth: options.lineWidth || 1,
+        dashes: dashPattern[0],
+        dashScale: dashPattern[1],
+        opacity: data.opacity
+    };
+
+    if(this.mode.indexOf('lines') !== -1) {
+        if(this.linePlot) this.linePlot.update(lineOptions);
+        else {
+            this.linePlot = createLinePlot(lineOptions);
+            this.scene.glplot.add(this.linePlot);
+        }
+    } else if(this.linePlot) {
+        this.scene.glplot.remove(this.linePlot);
+        this.linePlot.dispose();
+        this.linePlot = null;
+    }
+
+    // N.B. marker.opacity must be a scalar for performance
+    var scatterOpacity = data.opacity;
+    if(data.marker && data.marker.opacity) scatterOpacity *= data.marker.opacity;
+
+    scatterOptions = {
+        gl: gl,
+        position: options.position,
+        color: options.scatterColor,
+        size: options.scatterSize,
+        glyph: options.scatterMarker,
+        opacity: scatterOpacity,
+        orthographic: true,
+        lineWidth: options.scatterLineWidth,
+        lineColor: options.scatterLineColor,
+        project: options.project,
+        projectScale: options.projectScale,
+        projectOpacity: options.projectOpacity
+    };
+
+    if(this.mode.indexOf('markers') !== -1) {
+        if(this.scatterPlot) this.scatterPlot.update(scatterOptions);
+        else {
+            this.scatterPlot = createScatterPlot(scatterOptions);
+            this.scatterPlot.highlightScale = 1;
+            this.scene.glplot.add(this.scatterPlot);
+        }
+    } else if(this.scatterPlot) {
+        this.scene.glplot.remove(this.scatterPlot);
+        this.scatterPlot.dispose();
+        this.scatterPlot = null;
+    }
+
+    textOptions = {
+        gl: gl,
+        position: options.position,
+        glyph: options.text,
+        color: options.textColor,
+        size: options.textSize,
+        angle: options.textAngle,
+        alignment: options.textOffset,
+        font: options.textFont,
+        orthographic: true,
+        lineWidth: 0,
+        project: false,
+        opacity: data.opacity
+    };
+
+    this.textLabels = options.text;
+
+    if(this.mode.indexOf('text') !== -1) {
+        if(this.textMarkers) this.textMarkers.update(textOptions);
+        else {
+            this.textMarkers = createScatterPlot(textOptions);
+            this.textMarkers.highlightScale = 1;
+            this.scene.glplot.add(this.textMarkers);
+        }
+    } else if(this.textMarkers) {
+        this.scene.glplot.remove(this.textMarkers);
+        this.textMarkers.dispose();
+        this.textMarkers = null;
+    }
+
+    errorOptions = {
+        gl: gl,
+        position: options.position,
+        color: options.errorColor,
+        error: options.errorBounds,
+        lineWidth: options.errorLineWidth,
+        capSize: options.errorCapSize,
+        opacity: data.opacity
+    };
+    if(this.errorBars) {
+        if(options.errorBounds) {
+            this.errorBars.update(errorOptions);
+        } else {
+            this.scene.glplot.remove(this.errorBars);
+            this.errorBars.dispose();
+            this.errorBars = null;
+        }
+    } else if(options.errorBounds) {
+        this.errorBars = createErrorBars(errorOptions);
+        this.scene.glplot.add(this.errorBars);
+    }
+
+    if(options.delaunayAxis >= 0) {
+        var delaunayOptions = constructDelaunay(
+            options.position,
+            options.delaunayColor,
+            options.delaunayAxis);
+        if(this.delaunayMesh) {
+            this.delaunayMesh.update(delaunayOptions);
+        } else {
+            delaunayOptions.gl = gl;
+            this.delaunayMesh = createMesh(delaunayOptions);
+            this.scene.glplot.add(this.delaunayMesh);
+        }
+    } else if(this.delaunayMesh) {
+        this.scene.glplot.remove(this.delaunayMesh);
+        this.delaunayMesh.dispose();
+        this.delaunayMesh = null;
+    }
+};
+
+proto.dispose = function() {
+    if(this.linePlot) {
+        this.scene.glplot.remove(this.linePlot);
+        this.linePlot.dispose();
+    }
+    if(this.scatterPlot) {
+        this.scene.glplot.remove(this.scatterPlot);
+        this.scatterPlot.dispose();
+    }
+    if(this.errorBars) {
+        this.scene.remove(this.errorBars);
+        this.errorBars.dispose();
+    }
+    if(this.textMarkers) {
+        this.scene.glplot.remove(this.textMarkers);
+        this.textMarkers.dispose();
+    }
+    if(this.delaunayMesh) {
+        this.scene.glplot.remove(this.textMarkers);
+        this.delaunayMesh.dispose();
+    }
+};
+
+function createLineWithMarkers(scene, data) {
+    var plot = new LineWithMarkers(scene, data.uid);
+    plot.update(data);
+    return plot;
+}
+
+module.exports = createLineWithMarkers;
+
+},{"../../constants/gl3d_dashes":336,"../../constants/gl_markers":337,"../../lib":349,"../../lib/gl_format_color":347,"../../lib/str2rgbarray":359,"../scatter/make_bubble_size_func":514,"./calc_errors":525,"delaunay-triangulate":71,"gl-error3d":78,"gl-line3d":84,"gl-mesh3d":107,"gl-scatter3d":150}],527:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var subTypes = require('../scatter/subtypes');
+var handleMarkerDefaults = require('../scatter/marker_defaults');
+var handleLineDefaults = require('../scatter/line_defaults');
+var handleTextDefaults = require('../scatter/text_defaults');
+var errorBarsSupplyDefaults = require('../../components/errorbars/defaults');
+
+var attributes = require('./attributes');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    var len = handleXYZDefaults(traceIn, traceOut, coerce);
+    if(!len) {
+        traceOut.visible = false;
+        return;
+    }
+
+    coerce('text');
+    coerce('mode');
+
+    if(subTypes.hasLines(traceOut)) {
+        handleLineDefaults(traceIn, traceOut, defaultColor, coerce);
+    }
+
+    if(subTypes.hasMarkers(traceOut)) {
+        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce);
+    }
+
+    if(subTypes.hasText(traceOut)) {
+        handleTextDefaults(traceIn, traceOut, layout, coerce);
+    }
+
+    var lineColor = (traceOut.line || {}).color ,
+        markerColor = (traceOut.marker || {}).color;
+    if(coerce('surfaceaxis') >= 0) coerce('surfacecolor', lineColor || markerColor);
+
+    var dims = ['x', 'y', 'z'];
+    for(var i = 0; i < 3; ++i) {
+        var projection = 'projection.' + dims[i];
+        if(coerce(projection + '.show')) {
+            coerce(projection + '.opacity');
+            coerce(projection + '.scale');
+        }
+    }
+
+    errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'z'});
+    errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y', inherit: 'z'});
+    errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'z'});
+};
+
+function handleXYZDefaults(traceIn, traceOut, coerce) {
+    var len = 0,
+        x = coerce('x'),
+        y = coerce('y'),
+        z = coerce('z');
+
+    if(x && y && z) {
+        len = Math.min(x.length, y.length, z.length);
+        if(len < x.length) traceOut.x = x.slice(0, len);
+        if(len < y.length) traceOut.y = y.slice(0, len);
+        if(len < z.length) traceOut.z = z.slice(0, len);
+    }
+
+    return len;
+}
+
+},{"../../components/errorbars/defaults":322,"../../lib":349,"../scatter/line_defaults":512,"../scatter/marker_defaults":516,"../scatter/subtypes":520,"../scatter/text_defaults":521,"./attributes":523}],528:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var Scatter3D = {};
+
+Scatter3D.plot = require('./convert');
+Scatter3D.attributes = require('./attributes');
+Scatter3D.markerSymbols = require('../../constants/gl_markers');
+Scatter3D.supplyDefaults = require('./defaults');
+Scatter3D.colorbar = require('../scatter/colorbar');
+Scatter3D.calc = require('./calc');
+
+Scatter3D.moduleType = 'trace';
+Scatter3D.name = 'scatter3d';
+Scatter3D.basePlotModule = require('../../plots/gl3d');
+Scatter3D.categories = ['gl3d', 'symbols', 'markerColorscale', 'showLegend'];
+Scatter3D.meta = {
+    
+    
+};
+
+module.exports = Scatter3D;
+
+},{"../../constants/gl_markers":337,"../../plots/gl3d":400,"../scatter/colorbar":505,"./attributes":523,"./calc":524,"./convert":526,"./defaults":527}],529:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var scatterAttrs = require('../scatter/attributes');
+var plotAttrs = require('../../plots/attributes');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+var scatterMarkerAttrs = scatterAttrs.marker,
+    scatterLineAttrs = scatterAttrs.line,
+    scatterMarkerLineAttrs = scatterMarkerAttrs.line;
+
+
+module.exports = {
+    lon: {
+        valType: 'data_array',
+        
+    },
+    lat: {
+        valType: 'data_array',
+        
+    },
+    locations: {
+        valType: 'data_array',
+        
+    },
+    locationmode: {
+        valType: 'enumerated',
+        values: ['ISO-3', 'USA-states', 'country names'],
+        
+        dflt: 'ISO-3',
+        
+    },
+    mode: extendFlat({}, scatterAttrs.mode, {dflt: 'markers'}),
+    text: extendFlat({}, scatterAttrs.text, {
+        
+    }),
+    line: {
+        color: scatterLineAttrs.color,
+        width: scatterLineAttrs.width,
+        dash: scatterLineAttrs.dash
+    },
+    marker: {
+        symbol: scatterMarkerAttrs.symbol,
+        opacity: scatterMarkerAttrs.opacity,
+        size: scatterMarkerAttrs.size,
+        sizeref: scatterMarkerAttrs.sizeref,
+        sizemin: scatterMarkerAttrs.sizemin,
+        sizemode: scatterMarkerAttrs.sizemode,
+        color: scatterMarkerAttrs.color,
+        colorscale: scatterMarkerAttrs.colorscale,
+        cauto: scatterMarkerAttrs.cauto,
+        cmax: scatterMarkerAttrs.cmax,
+        cmin: scatterMarkerAttrs.cmin,
+        autocolorscale: scatterMarkerAttrs.autocolorscale,
+        reversescale: scatterMarkerAttrs.reversescale,
+        showscale: scatterMarkerAttrs.showscale,
+        line: {
+            color: scatterMarkerLineAttrs.color,
+            width: scatterMarkerLineAttrs.width,
+            colorscale: scatterMarkerLineAttrs.colorscale,
+            cauto: scatterMarkerLineAttrs.cauto,
+            cmax: scatterMarkerLineAttrs.cmax,
+            cmin: scatterMarkerLineAttrs.cmin,
+            autocolorscale: scatterMarkerLineAttrs.autocolorscale,
+            reversescale: scatterMarkerLineAttrs.reversescale
+        }
+    },
+    textfont: scatterAttrs.textfont,
+    textposition: scatterAttrs.textposition,
+    hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
+        flags: ['lon', 'lat', 'location', 'text', 'name']
+    }),
+    _nestedModules: {
+        'marker.colorbar': 'Colorbar'
+    }
+};
+
+},{"../../lib/extend":345,"../../plots/attributes":367,"../scatter/attributes":502}],530:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var calcMarkerColorscale = require('../scatter/marker_colorscale_calc');
+
+
+module.exports = function calc(gd, trace) {
+    var cd = [{x: false, y: false, trace: trace, t: {}}];
+
+    calcMarkerColorscale(trace);
+
+    return cd;
+};
+
+},{"../scatter/marker_colorscale_calc":515}],531:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var subTypes = require('../scatter/subtypes');
+var handleMarkerDefaults = require('../scatter/marker_defaults');
+var handleLineDefaults = require('../scatter/line_defaults');
+var handleTextDefaults = require('../scatter/text_defaults');
+
+var attributes = require('./attributes');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    var len = handleLonLatLocDefaults(traceIn, traceOut, coerce);
+    if(!len) {
+        traceOut.visible = false;
+        return;
+    }
+
+    coerce('text');
+    coerce('mode');
+
+    if(subTypes.hasLines(traceOut)) {
+        handleLineDefaults(traceIn, traceOut, defaultColor, coerce);
+    }
+
+    if(subTypes.hasMarkers(traceOut)) {
+        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce);
+    }
+
+    if(subTypes.hasText(traceOut)) {
+        handleTextDefaults(traceIn, traceOut, layout, coerce);
+    }
+
+    coerce('hoverinfo', (layout._dataLength === 1) ? 'lon+lat+location+text' : undefined);
+};
+
+function handleLonLatLocDefaults(traceIn, traceOut, coerce) {
+    var len = 0,
+        locations = coerce('locations');
+
+    var lon, lat;
+
+    if(locations) {
+        coerce('locationmode');
+        len = locations.length;
+        return len;
+    }
+
+    lon = coerce('lon') || [];
+    lat = coerce('lat') || [];
+    len = Math.min(lon.length, lat.length);
+
+    if(len < lon.length) traceOut.lon = lon.slice(0, len);
+    if(len < lat.length) traceOut.lat = lat.slice(0, len);
+
+    return len;
+}
+
+},{"../../lib":349,"../scatter/line_defaults":512,"../scatter/marker_defaults":516,"../scatter/subtypes":520,"../scatter/text_defaults":521,"./attributes":529}],532:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var ScatterGeo = {};
+
+ScatterGeo.attributes = require('./attributes');
+ScatterGeo.supplyDefaults = require('./defaults');
+ScatterGeo.colorbar = require('../scatter/colorbar');
+ScatterGeo.calc = require('./calc');
+ScatterGeo.plot = require('./plot').plot;
+
+ScatterGeo.moduleType = 'trace';
+ScatterGeo.name = 'scattergeo';
+ScatterGeo.basePlotModule = require('../../plots/geo');
+ScatterGeo.categories = ['geo', 'symbols', 'markerColorscale', 'showLegend'];
+ScatterGeo.meta = {
+    
+    
+};
+
+module.exports = ScatterGeo;
+
+},{"../../plots/geo":385,"../scatter/colorbar":505,"./attributes":529,"./calc":530,"./defaults":531,"./plot":533}],533:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var d3 = require('d3');
+
+var Fx = require('../../plots/cartesian/graph_interact');
+var Axes = require('../../plots/cartesian/axes');
+
+var getTopojsonFeatures = require('../../lib/topojson_utils').getTopojsonFeatures;
+var locationToFeature = require('../../lib/geo_location_utils').locationToFeature;
+var arrayToCalcItem = require('../../lib/array_to_calc_item');
+
+var Color = require('../../components/color');
+var Drawing = require('../../components/drawing');
+var subTypes = require('../scatter/subtypes');
+
+var attributes = require('./attributes');
+
+var plotScatterGeo = module.exports = {};
+
+
+plotScatterGeo.calcGeoJSON = function(trace, topojson) {
+    var cdi = [],
+        hasLocationData = Array.isArray(trace.locations);
+
+    var len, features, getLonLat, locations;
+
+    if(hasLocationData) {
+        locations = trace.locations;
+        len = locations.length;
+        features = getTopojsonFeatures(trace, topojson);
+        getLonLat = function(trace, i) {
+            var feature = locationToFeature(trace.locationmode, locations[i], features);
+
+            return (feature !== undefined) ?
+                feature.properties.ct :
+                undefined;
+        };
+    }
+    else {
+        len = trace.lon.length;
+        getLonLat = function(trace, i) {
+            return [trace.lon[i], trace.lat[i]];
+        };
+    }
+
+    for(var i = 0; i < len; i++) {
+        var lonlat = getLonLat(trace, i);
+
+        if(!lonlat) continue;  // filter the blank points here
+
+        var calcItem = {
+            lon: lonlat[0],
+            lat: lonlat[1],
+            location: hasLocationData ? trace.locations[i] : null
+        };
+
+        arrayItemToCalcdata(trace, calcItem, i);
+
+        cdi.push(calcItem);
+    }
+
+    if(cdi.length > 0) cdi[0].trace = trace;
+
+    return cdi;
+};
+
+// similar Scatter.arraysToCalcdata but inside a filter loop
+function arrayItemToCalcdata(trace, calcItem, i) {
+    var marker = trace.marker;
+
+    function merge(traceAttr, calcAttr) {
+        arrayToCalcItem(traceAttr, calcItem, calcAttr, i);
+    }
+
+    merge(trace.text, 'tx');
+    merge(trace.textposition, 'tp');
+    if(trace.textfont) {
+        merge(trace.textfont.size, 'ts');
+        merge(trace.textfont.color, 'tc');
+        merge(trace.textfont.family, 'tf');
+    }
+
+    if(marker && marker.line) {
+        var markerLine = marker.line;
+        merge(marker.opacity, 'mo');
+        merge(marker.symbol, 'mx');
+        merge(marker.color, 'mc');
+        merge(marker.size, 'ms');
+        merge(markerLine.color, 'mlc');
+        merge(markerLine.width, 'mlw');
+    }
+}
+
+function makeLineGeoJSON(trace) {
+    var N = trace.lon.length,
+        coordinates = new Array(N);
+
+    for(var i = 0; i < N; i++) {
+        coordinates[i] = [trace.lon[i], trace.lat[i]];
+    }
+
+    return {
+        type: 'LineString',
+        coordinates: coordinates,
+        trace: trace
+    };
+}
+
+plotScatterGeo.plot = function(geo, scattergeoData) {
+    var gScatterGeoTraces = geo.framework.select('.scattergeolayer')
+        .selectAll('g.trace.scattergeo')
+        .data(scattergeoData, function(trace) { return trace.uid; });
+
+    gScatterGeoTraces.enter().append('g')
+        .attr('class', 'trace scattergeo');
+
+    gScatterGeoTraces.exit().remove();
+
+    // TODO add hover - how?
+    gScatterGeoTraces
+        .each(function(trace) {
+            if(!subTypes.hasLines(trace)) return;
+
+            d3.select(this)
+                .append('path')
+                .datum(makeLineGeoJSON(trace))
+                .attr('class', 'js-line');
+        });
+
+    gScatterGeoTraces.append('g')
+        .attr('class', 'points')
+        .each(function(trace) {
+            var s = d3.select(this),
+                showMarkers = subTypes.hasMarkers(trace),
+                showText = subTypes.hasText(trace);
+
+            if((!showMarkers && !showText)) return;
+
+            var cdi = plotScatterGeo.calcGeoJSON(trace, geo.topojson),
+                cleanHoverLabelsFunc = makeCleanHoverLabelsFunc(geo, trace),
+                eventDataFunc = makeEventDataFunc(trace);
+
+            var hoverinfo = trace.hoverinfo,
+                hasNameLabel = (
+                    hoverinfo === 'all' ||
+                    hoverinfo.indexOf('name') !== -1
+                );
+
+            function handleMouseOver(pt, ptIndex) {
+                if(!geo.showHover) return;
+
+                var xy = geo.projection([pt.lon, pt.lat]);
+                cleanHoverLabelsFunc(pt);
+
+                Fx.loneHover({
+                    x: xy[0],
+                    y: xy[1],
+                    name: hasNameLabel ? trace.name : undefined,
+                    text: pt.textLabel,
+                    color: pt.mc || (trace.marker || {}).color
+                }, {
+                    container: geo.hoverContainer.node()
+                });
+
+                geo.graphDiv.emit('plotly_hover', eventDataFunc(pt, ptIndex));
+            }
+
+            function handleClick(pt, ptIndex) {
+                geo.graphDiv.emit('plotly_click', eventDataFunc(pt, ptIndex));
+            }
+
+            if(showMarkers) {
+                s.selectAll('path.point')
+                    .data(cdi)
+                    .enter().append('path')
+                        .attr('class', 'point')
+                        .on('mouseover', handleMouseOver)
+                        .on('click', handleClick)
+                        .on('mouseout', function() {
+                            Fx.loneUnhover(geo.hoverContainer);
+                        })
+                        .on('mousedown', function() {
+                            // to simulate the 'zoomon' event
+                            Fx.loneUnhover(geo.hoverContainer);
+                        })
+                        .on('mouseup', handleMouseOver);  // ~ 'zoomend'
+            }
+
+            if(showText) {
+                s.selectAll('g')
+                    .data(cdi)
+                    .enter().append('g')
+                        .append('text');
+            }
+        });
+
+    plotScatterGeo.style(geo);
+};
+
+plotScatterGeo.style = function(geo) {
+    var selection = geo.framework.selectAll('g.trace.scattergeo');
+
+    selection.style('opacity', function(trace) { return trace.opacity; });
+
+    selection.selectAll('g.points')
+        .each(function(trace) {
+            d3.select(this).selectAll('path.point')
+                .call(Drawing.pointStyle, trace);
+            d3.select(this).selectAll('text')
+                .call(Drawing.textPointStyle, trace);
+        });
+
+    // GeoJSON calc data is incompatible with Drawing.lineGroupStyle
+    selection.selectAll('path.js-line')
+        .style('fill', 'none')
+        .each(function(d) {
+            var trace = d.trace,
+                line = trace.line || {};
+
+            d3.select(this)
+                .call(Color.stroke, line.color)
+                .call(Drawing.dashLine, line.dash || '', line.width || 0);
+        });
+};
+
+function makeCleanHoverLabelsFunc(geo, trace) {
+    var hoverinfo = trace.hoverinfo;
+
+    if(hoverinfo === 'none') {
+        return function cleanHoverLabelsFunc(d) { delete d.textLabel; };
+    }
+
+    var hoverinfoParts = (hoverinfo === 'all') ?
+            attributes.hoverinfo.flags :
+            hoverinfo.split('+');
+
+    var hasLocation = (
+            hoverinfoParts.indexOf('location') !== -1 &&
+            Array.isArray(trace.locations)
+        ),
+        hasLon = (hoverinfoParts.indexOf('lon') !== -1),
+        hasLat = (hoverinfoParts.indexOf('lat') !== -1),
+        hasText = (hoverinfoParts.indexOf('text') !== -1);
+
+    function formatter(val) {
+        var axis = geo.mockAxis;
+        return Axes.tickText(axis, axis.c2l(val), 'hover').text + '\u00B0';
+    }
+
+    return function cleanHoverLabelsFunc(pt) {
+        var thisText = [];
+
+        if(hasLocation) thisText.push(pt.location);
+        else if(hasLon && hasLat) {
+            thisText.push('(' + formatter(pt.lon) + ', ' + formatter(pt.lat) + ')');
+        }
+        else if(hasLon) thisText.push('lon: ' + formatter(pt.lon));
+        else if(hasLat) thisText.push('lat: ' + formatter(pt.lat));
+
+        if(hasText) thisText.push(pt.tx || trace.text);
+
+        pt.textLabel = thisText.join('<br>');
+    };
+}
+
+function makeEventDataFunc(trace) {
+    var hasLocation = Array.isArray(trace.locations);
+
+    return function(pt, ptIndex) {
+        return {points: [{
+            data: trace._input,
+            fullData: trace,
+            curveNumber: trace.index,
+            pointNumber: ptIndex,
+            lon: pt.lon,
+            lat: pt.lat,
+            location: hasLocation ? pt.location : null
+        }]};
+    };
+}
+
+},{"../../components/color":299,"../../components/drawing":317,"../../lib/array_to_calc_item":341,"../../lib/geo_location_utils":346,"../../lib/topojson_utils":361,"../../plots/cartesian/axes":369,"../../plots/cartesian/graph_interact":374,"../scatter/subtypes":520,"./attributes":529,"d3":70}],534:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var scatterAttrs = require('../scatter/attributes');
+var DASHES = require('../../constants/gl2d_dashes');
+var MARKERS = require('../../constants/gl_markers');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+var scatterLineAttrs = scatterAttrs.line,
+    scatterMarkerAttrs = scatterAttrs.marker,
+    scatterMarkerLineAttrs = scatterMarkerAttrs.line;
+
+module.exports = {
+    x: scatterAttrs.x,
+    x0: scatterAttrs.x0,
+    dx: scatterAttrs.dx,
+    y: scatterAttrs.y,
+    y0: scatterAttrs.y0,
+    dy: scatterAttrs.dy,
+    text: extendFlat({}, scatterAttrs.text, {
+        
+    }),
+    mode: {
+        valType: 'flaglist',
+        flags: ['lines', 'markers'],
+        extras: ['none'],
+        
+        
+    },
+    line: {
+        color: scatterLineAttrs.color,
+        width: scatterLineAttrs.width,
+        dash: {
+            valType: 'enumerated',
+            values: Object.keys(DASHES),
+            dflt: 'solid',
+            
+            
+        }
+    },
+    marker: {
+        color: scatterMarkerAttrs.color,
+        symbol: {
+            valType: 'enumerated',
+            values: Object.keys(MARKERS),
+            dflt: 'circle',
+            arrayOk: true,
+            
+            
+        },
+        size: scatterMarkerAttrs.size,
+        sizeref: scatterMarkerAttrs.sizeref,
+        sizemin: scatterMarkerAttrs.sizemin,
+        sizemode: scatterMarkerAttrs.sizemode,
+        opacity: scatterMarkerAttrs.opacity,
+        colorscale: scatterMarkerAttrs.colorscale,
+        cauto: scatterMarkerAttrs.cauto,
+        cmax: scatterMarkerAttrs.cmax,
+        cmin: scatterMarkerAttrs.cmin,
+        autocolorscale: scatterMarkerAttrs.autocolorscale,
+        reversescale: scatterMarkerAttrs.reversescale,
+        showscale: scatterMarkerAttrs.showscale,
+        line: {
+            color: scatterMarkerLineAttrs.color,
+            width: scatterMarkerLineAttrs.width,
+            colorscale: scatterMarkerLineAttrs.colorscale,
+            cauto: scatterMarkerLineAttrs.cauto,
+            cmax: scatterMarkerLineAttrs.cmax,
+            cmin: scatterMarkerLineAttrs.cmin,
+            autocolorscale: scatterMarkerLineAttrs.autocolorscale,
+            reversescale: scatterMarkerLineAttrs.reversescale
+        }
+    },
+    fill: extendFlat({}, scatterAttrs.fill, {
+        values: ['none', 'tozeroy', 'tozerox']
+    }),
+    fillcolor: scatterAttrs.fillcolor,
+    _nestedModules: {
+        'error_x': 'ErrorBars',
+        'error_y': 'ErrorBars',
+        'marker.colorbar': 'Colorbar'
+    }
+};
+
+},{"../../constants/gl2d_dashes":335,"../../constants/gl_markers":337,"../../lib/extend":345,"../scatter/attributes":502}],535:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var createScatter = require('gl-scatter2d');
+var createFancyScatter = require('gl-scatter2d-fancy');
+var createLine = require('gl-line2d');
+var createError = require('gl-error2d');
+var isNumeric = require('fast-isnumeric');
+
+var Lib = require('../../lib');
+var Axes = require('../../plots/cartesian/axes');
+var ErrorBars = require('../../components/errorbars');
+var str2RGBArray = require('../../lib/str2rgbarray');
+var formatColor = require('../../lib/gl_format_color');
+var subTypes = require('../scatter/subtypes');
+var makeBubbleSizeFn = require('../scatter/make_bubble_size_func');
+var getTraceColor = require('../scatter/get_trace_color');
+var MARKER_SYMBOLS = require('../../constants/gl_markers');
+var DASHES = require('../../constants/gl2d_dashes');
+
+var AXES = ['xaxis', 'yaxis'];
+
+
+function LineWithMarkers(scene, uid) {
+    this.scene = scene;
+    this.uid = uid;
+
+    this.xData = [];
+    this.yData = [];
+    this.textLabels = [];
+    this.color = 'rgb(0, 0, 0)';
+    this.name = '';
+    this.hoverinfo = 'all';
+
+    this.idToIndex = [];
+    this.bounds = [0, 0, 0, 0];
+
+    this.hasLines = false;
+    this.lineOptions = {
+        positions: new Float32Array(),
+        color: [0, 0, 0, 1],
+        width: 1,
+        fill: [false, false, false, false],
+        fillColor: [
+            [0, 0, 0, 1],
+            [0, 0, 0, 1],
+            [0, 0, 0, 1],
+            [0, 0, 0, 1]],
+        dashes: [1]
+    };
+    this.line = createLine(scene.glplot, this.lineOptions);
+    this.line._trace = this;
+
+    this.hasErrorX = false;
+    this.errorXOptions = {
+        positions: new Float32Array(),
+        errors: new Float32Array(),
+        lineWidth: 1,
+        capSize: 0,
+        color: [0, 0, 0, 1]
+    };
+    this.errorX = createError(scene.glplot, this.errorXOptions);
+    this.errorX._trace = this;
+
+    this.hasErrorY = false;
+    this.errorYOptions = {
+        positions: new Float32Array(),
+        errors: new Float32Array(),
+        lineWidth: 1,
+        capSize: 0,
+        color: [0, 0, 0, 1]
+    };
+    this.errorY = createError(scene.glplot, this.errorYOptions);
+    this.errorY._trace = this;
+
+    this.hasMarkers = false;
+    this.scatterOptions = {
+        positions: new Float32Array(),
+        sizes: [],
+        colors: [],
+        glyphs: [],
+        borderWidths: [],
+        borderColors: [],
+        size: 12,
+        color: [0, 0, 0, 1],
+        borderSize: 1,
+        borderColor: [0, 0, 0, 1]
+    };
+    this.scatter = createScatter(scene.glplot, this.scatterOptions);
+    this.scatter._trace = this;
+    this.fancyScatter = createFancyScatter(scene.glplot, this.scatterOptions);
+    this.fancyScatter._trace = this;
+}
+
+var proto = LineWithMarkers.prototype;
+
+proto.handlePick = function(pickResult) {
+    var index = this.idToIndex[pickResult.pointId];
+
+    return {
+        trace: this,
+        dataCoord: pickResult.dataCoord,
+        traceCoord: [
+            this.xData[index],
+            this.yData[index]
+        ],
+        textLabel: Array.isArray(this.textLabels) ?
+            this.textLabels[index] :
+            this.textLabels,
+        color: Array.isArray(this.color) ?
+            this.color[index] :
+            this.color,
+        name: this.name,
+        hoverinfo: this.hoverinfo
+    };
+};
+
+// check if trace is fancy
+proto.isFancy = function(options) {
+    if(this.scene.xaxis.type !== 'linear') return true;
+    if(this.scene.yaxis.type !== 'linear') return true;
+
+    if(!options.x || !options.y) return true;
+
+    var marker = options.marker || {};
+    if(Array.isArray(marker.symbol) ||
+         marker.symbol !== 'circle' ||
+         Array.isArray(marker.size) ||
+         Array.isArray(marker.line.width) ||
+         Array.isArray(marker.opacity)
+    ) return true;
+
+    var markerColor = marker.color;
+    if(Array.isArray(markerColor)) return true;
+
+    var lineColor = Array.isArray(marker.line.color);
+    if(Array.isArray(lineColor)) return true;
+
+    if(this.hasErrorX) return true;
+    if(this.hasErrorY) return true;
+
+    return false;
+};
+
+// handle the situation where values can be array-like or not array like
+function convertArray(convert, data, count) {
+    if(!Array.isArray(data)) data = [data];
+
+    return _convertArray(convert, data, count);
+}
+
+function _convertArray(convert, data, count) {
+    var result = new Array(count),
+        data0 = data[0];
+
+    for(var i = 0; i < count; ++i) {
+        result[i] = (i >= data.length) ?
+            convert(data0) :
+            convert(data[i]);
+    }
+
+    return result;
+}
+
+var convertNumber = convertArray.bind(null, function(x) { return +x; });
+var convertColorBase = convertArray.bind(null, str2RGBArray);
+var convertSymbol = convertArray.bind(null, function(x) {
+    return MARKER_SYMBOLS[x] || 'â';
+});
+
+function convertColor(color, opacity, count) {
+    return _convertColor(
+        convertColorBase(color, count),
+        convertNumber(opacity, count),
+        count
+    );
+}
+
+function convertColorScale(containerIn, markerOpacity, traceOpacity, count) {
+    var colors = formatColor(containerIn, markerOpacity, count);
+
+    colors = Array.isArray(colors[0]) ?
+        colors :
+        _convertArray(Lib.identity, [colors], count);
+
+    return _convertColor(
+        colors,
+        convertNumber(traceOpacity, count),
+        count
+    );
+}
+
+function _convertColor(colors, opacities, count) {
+    var result = new Array(4 * count);
+
+    for(var i = 0; i < count; ++i) {
+        for(var j = 0; j < 3; ++j) result[4*i+j] = colors[i][j];
+
+        result[4*i+3] = colors[i][3] * opacities[i];
+    }
+
+    return result;
+}
+
+/**
+ * Truncate a Float32Array to some length. A wrapper to support environments
+ * (e.g. node-webkit) that do not implement Float32Array.prototype.slice
+ */
+function truncate(float32ArrayIn, len) {
+    if(Float32Array.slice === undefined) {
+        var float32ArrayOut = new Float32Array(len);
+        for(var i = 0; i < len; i++) float32ArrayOut[i] = float32ArrayIn[i];
+        return float32ArrayOut;
+    }
+
+    return float32ArrayIn.slice(0, len);
+}
+
+/* Order is important here to get the correct laying:
+ * - lines
+ * - errorX
+ * - errorY
+ * - markers
+ */
+proto.update = function(options) {
+    if(options.visible !== true) {
+        this.hasLines = false;
+        this.hasErrorX = false;
+        this.hasErrorY = false;
+        this.hasMarkers = false;
+    }
+    else {
+        this.hasLines = subTypes.hasLines(options);
+        this.hasErrorX = options.error_x.visible === true;
+        this.hasErrorY = options.error_y.visible === true;
+        this.hasMarkers = subTypes.hasMarkers(options);
+    }
+
+    this.textLabels = options.text;
+    this.name = options.name;
+    this.hoverinfo = options.hoverinfo;
+    this.bounds = [Infinity, Infinity, -Infinity, -Infinity];
+
+    if(this.isFancy(options)) {
+        this.updateFancy(options);
+    }
+    else {
+        this.updateFast(options);
+    }
+
+    // not quite on-par with 'scatter', but close enough for now
+    // does not handle the colorscale case
+    this.color = getTraceColor(options, {});
+};
+
+proto.updateFast = function(options) {
+    var x = this.xData = options.x;
+    var y = this.yData = options.y;
+
+    var len = x.length,
+        idToIndex = new Array(len),
+        positions = new Float32Array(2 * len),
+        bounds = this.bounds,
+        pId = 0,
+        ptr = 0;
+
+    var xx, yy;
+
+    // TODO add 'very fast' mode that bypasses this loop
+    // TODO bypass this on modebar +/- zoom
+    for(var i = 0; i < len; ++i) {
+        xx = x[i];
+        yy = y[i];
+
+        // check for isNaN is faster but doesn't skip over nulls
+        if(!isNumeric(xx) || !isNumeric(yy)) continue;
+
+        idToIndex[pId++] = i;
+
+        positions[ptr++] = xx;
+        positions[ptr++] = yy;
+
+        bounds[0] = Math.min(bounds[0], xx);
+        bounds[1] = Math.min(bounds[1], yy);
+        bounds[2] = Math.max(bounds[2], xx);
+        bounds[3] = Math.max(bounds[3], yy);
+    }
+
+    positions = truncate(positions, ptr);
+    this.idToIndex = idToIndex;
+
+    this.updateLines(options, positions);
+    this.updateError('X', options);
+    this.updateError('Y', options);
+
+    var markerSize;
+
+    if(this.hasMarkers) {
+        this.scatterOptions.positions = positions;
+
+        var markerColor = str2RGBArray(options.marker.color),
+            borderColor = str2RGBArray(options.marker.line.color),
+            opacity = (options.opacity) * (options.marker.opacity);
+
+        markerColor[3] *= opacity;
+        this.scatterOptions.color = markerColor;
+
+        borderColor[3] *= opacity;
+        this.scatterOptions.borderColor = borderColor;
+
+        markerSize = options.marker.size;
+        this.scatterOptions.size = markerSize;
+        this.scatterOptions.borderSize = options.marker.line.width;
+
+        this.scatter.update(this.scatterOptions);
+    }
+    else {
+        this.scatterOptions.positions = new Float32Array();
+        this.scatterOptions.glyphs = [];
+        this.scatter.update(this.scatterOptions);
+    }
+
+    // turn off fancy scatter plot
+    this.scatterOptions.positions = new Float32Array();
+    this.scatterOptions.glyphs = [];
+    this.fancyScatter.update(this.scatterOptions);
+
+    // add item for autorange routine
+    this.expandAxesFast(bounds, markerSize);
+};
+
+proto.updateFancy = function(options) {
+    var scene = this.scene,
+        xaxis = scene.xaxis,
+        yaxis = scene.yaxis,
+        bounds = this.bounds;
+
+    // makeCalcdata runs d2c (data-to-coordinate) on every point
+    var x = this.xData = xaxis.makeCalcdata(options, 'x');
+    var y = this.yData = yaxis.makeCalcdata(options, 'y');
+
+    // get error values
+    var errorVals = ErrorBars.calcFromTrace(options, scene.fullLayout);
+
+    var len = x.length,
+        idToIndex = new Array(len),
+        positions = new Float32Array(2 * len),
+        errorsX = new Float32Array(4 * len),
+        errorsY = new Float32Array(4 * len),
+        pId = 0,
+        ptr = 0,
+        ptrX = 0,
+        ptrY = 0;
+
+    var getX = (xaxis.type === 'log') ?
+            function(x) { return xaxis.d2l(x); } :
+            function(x) { return x; };
+    var getY = (yaxis.type === 'log') ?
+            function(y) { return yaxis.d2l(y); } :
+            function(y) { return y; };
+
+    var i, j, xx, yy, ex0, ex1, ey0, ey1;
+
+    for(i = 0; i < len; ++i) {
+        xx = getX(x[i]);
+        yy = getY(y[i]);
+
+        if(isNaN(xx) || isNaN(yy)) continue;
+
+        idToIndex[pId++] = i;
+
+        positions[ptr++] = xx;
+        positions[ptr++] = yy;
+
+        ex0 = errorsX[ptrX++] = xx - errorVals[i].xs || 0;
+        ex1 = errorsX[ptrX++] = errorVals[i].xh - xx || 0;
+        errorsX[ptrX++] = 0;
+        errorsX[ptrX++] = 0;
+
+        errorsY[ptrY++] = 0;
+        errorsY[ptrY++] = 0;
+        ey0 = errorsY[ptrY++] = yy - errorVals[i].ys || 0;
+        ey1 = errorsY[ptrY++] = errorVals[i].yh - yy || 0;
+
+        bounds[0] = Math.min(bounds[0], xx - ex0);
+        bounds[1] = Math.min(bounds[1], yy - ey0);
+        bounds[2] = Math.max(bounds[2], xx + ex1);
+        bounds[3] = Math.max(bounds[3], yy + ey1);
+    }
+
+    positions = truncate(positions, ptr);
+    this.idToIndex = idToIndex;
+
+    this.updateLines(options, positions);
+    this.updateError('X', options, positions, errorsX);
+    this.updateError('Y', options, positions, errorsY);
+
+    var sizes;
+
+    if(this.hasMarkers) {
+        this.scatterOptions.positions = positions;
+
+        // TODO rewrite convert function so that
+        // we don't have to loop through the data another time
+
+        this.scatterOptions.sizes = new Array(pId);
+        this.scatterOptions.glyphs = new Array(pId);
+        this.scatterOptions.borderWidths = new Array(pId);
+        this.scatterOptions.colors = new Array(pId * 4);
+        this.scatterOptions.borderColors = new Array(pId * 4);
+
+        var markerSizeFunc = makeBubbleSizeFn(options),
+            markerOpts = options.marker,
+            markerOpacity = markerOpts.opacity,
+            traceOpacity = options.opacity,
+            colors = convertColorScale(markerOpts, markerOpacity, traceOpacity, len),
+            glyphs = convertSymbol(markerOpts.symbol, len),
+            borderWidths = convertNumber(markerOpts.line.width, len),
+            borderColors = convertColorScale(markerOpts.line, markerOpacity, traceOpacity, len),
+            index;
+
+        sizes = convertArray(markerSizeFunc, markerOpts.size, len);
+
+        for(i = 0; i < pId; ++i) {
+            index = idToIndex[i];
+
+            this.scatterOptions.sizes[i] = 4.0 * sizes[index];
+            this.scatterOptions.glyphs[i] = glyphs[index];
+            this.scatterOptions.borderWidths[i] = 0.5 * borderWidths[index];
+
+            for(j = 0; j < 4; ++j) {
+                this.scatterOptions.colors[4*i+j] = colors[4*index+j];
+                this.scatterOptions.borderColors[4*i+j] = borderColors[4*index+j];
+            }
+        }
+
+        this.fancyScatter.update(this.scatterOptions);
+    }
+    else {
+        this.scatterOptions.positions = new Float32Array();
+        this.scatterOptions.glyphs = [];
+        this.fancyScatter.update(this.scatterOptions);
+    }
+
+    // turn off fast scatter plot
+    this.scatterOptions.positions = new Float32Array();
+    this.scatterOptions.glyphs = [];
+    this.scatter.update(this.scatterOptions);
+
+    // add item for autorange routine
+    this.expandAxesFancy(x, y, sizes);
+};
+
+proto.updateLines = function(options, positions) {
+    if(this.hasLines) {
+        this.lineOptions.positions = positions;
+
+        var lineColor = str2RGBArray(options.line.color);
+        if(this.hasMarkers) lineColor[3] *= options.marker.opacity;
+
+        var lineWidth = Math.round(0.5 * this.lineOptions.width),
+            dashes = (DASHES[options.line.dash] || [1]).slice();
+
+        for(var i = 0; i < dashes.length; ++i) dashes[i] *= lineWidth;
+
+        switch(options.fill) {
+            case 'tozeroy':
+                this.lineOptions.fill = [false, true, false, false];
+                break;
+            case 'tozerox':
+                this.lineOptions.fill = [true, false, false, false];
+                break;
+            default:
+                this.lineOptions.fill = [false, false, false, false];
+                break;
+        }
+
+        var fillColor = str2RGBArray(options.fillcolor);
+
+        this.lineOptions.color = lineColor;
+        this.lineOptions.width = 2.0 * options.line.width;
+        this.lineOptions.dashes = dashes;
+        this.lineOptions.fillColor = [fillColor, fillColor, fillColor, fillColor];
+    }
+    else {
+        this.lineOptions.positions = new Float32Array();
+    }
+
+    this.line.update(this.lineOptions);
+};
+
+proto.updateError = function(axLetter, options, positions, errors) {
+    var errorObj = this['error' + axLetter],
+        errorOptions = options['error_' + axLetter.toLowerCase()],
+        errorObjOptions = this['error' + axLetter + 'Options'];
+
+    if(axLetter.toLowerCase() === 'x' && errorOptions.copy_ystyle) {
+        errorOptions = options.error_y;
+    }
+
+    if(this['hasError' + axLetter]) {
+        errorObjOptions.positions = positions;
+        errorObjOptions.errors = errors;
+        errorObjOptions.capSize = errorOptions.width;
+        errorObjOptions.lineWidth = errorOptions.thickness / 2;  // ballpark rescaling
+        errorObjOptions.color = convertColor(errorOptions.color, 1, 1);
+    }
+    else {
+        errorObjOptions.positions = new Float32Array();
+    }
+
+    errorObj.update(errorObjOptions);
+};
+
+proto.expandAxesFast = function(bounds, markerSize) {
+    var pad = markerSize || 10;
+    var ax, min, max;
+
+    for(var i = 0; i < 2; i++) {
+        ax = this.scene[AXES[i]];
+
+        min = ax._min;
+        if(!min) min = [];
+        min.push({ val: bounds[i], pad: pad });
+
+        max = ax._max;
+        if(!max) max = [];
+        max.push({ val: bounds[i+2], pad: pad });
+    }
+};
+
+// not quite on-par with 'scatter' (scatter fill in several other expand options),
+// but close enough for now
+proto.expandAxesFancy = function(x, y, ppad) {
+    var scene = this.scene,
+        expandOpts = { padded: true, ppad: ppad };
+
+    Axes.expand(scene.xaxis, x, expandOpts);
+    Axes.expand(scene.yaxis, y, expandOpts);
+};
+
+proto.dispose = function() {
+    this.line.dispose();
+    this.errorX.dispose();
+    this.errorY.dispose();
+    this.scatter.dispose();
+    this.fancyScatter.dispose();
+};
+
+function createLineWithMarkers(scene, data) {
+    var plot = new LineWithMarkers(scene, data.uid);
+    plot.update(data);
+    return plot;
+}
+
+module.exports = createLineWithMarkers;
+
+},{"../../components/errorbars":323,"../../constants/gl2d_dashes":335,"../../constants/gl_markers":337,"../../lib":349,"../../lib/gl_format_color":347,"../../lib/str2rgbarray":359,"../../plots/cartesian/axes":369,"../scatter/get_trace_color":509,"../scatter/make_bubble_size_func":514,"../scatter/subtypes":520,"fast-isnumeric":74,"gl-error2d":76,"gl-line2d":82,"gl-scatter2d":147,"gl-scatter2d-fancy":142}],536:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var constants = require('../scatter/constants');
+var subTypes = require('../scatter/subtypes');
+var handleXYDefaults = require('../scatter/xy_defaults');
+var handleMarkerDefaults = require('../scatter/marker_defaults');
+var handleLineDefaults = require('../scatter/line_defaults');
+var handleFillColorDefaults = require('../scatter/fillcolor_defaults');
+var errorBarsSupplyDefaults = require('../../components/errorbars/defaults');
+
+var attributes = require('./attributes');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    var len = handleXYDefaults(traceIn, traceOut, coerce);
+    if(!len) {
+        traceOut.visible = false;
+        return;
+    }
+
+    coerce('text');
+    coerce('mode', len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines');
+
+    if(subTypes.hasLines(traceOut)) {
+        handleLineDefaults(traceIn, traceOut, defaultColor, coerce);
+    }
+
+    if(subTypes.hasMarkers(traceOut)) {
+        handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce);
+    }
+
+    coerce('fill');
+    if(traceOut.fill !== 'none') {
+        handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
+    }
+
+    errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'y'});
+    errorBarsSupplyDefaults(traceIn, traceOut, defaultColor, {axis: 'x', inherit: 'y'});
+};
+
+},{"../../components/errorbars/defaults":322,"../../lib":349,"../scatter/constants":506,"../scatter/fillcolor_defaults":508,"../scatter/line_defaults":512,"../scatter/marker_defaults":516,"../scatter/subtypes":520,"../scatter/xy_defaults":522,"./attributes":534}],537:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+'use strict';
+
+var ScatterGl = {};
+
+ScatterGl.attributes = require('./attributes');
+ScatterGl.supplyDefaults = require('./defaults');
+ScatterGl.colorbar = require('../scatter/colorbar');
+
+// reuse the Scatter3D 'dummy' calc step so that legends know what to do
+ScatterGl.calc = require('../scatter3d/calc');
+ScatterGl.plot = require('./convert');
+
+ScatterGl.moduleType = 'trace';
+ScatterGl.name = 'scattergl';
+ScatterGl.basePlotModule = require('../../plots/gl2d');
+ScatterGl.categories = ['gl2d', 'symbols', 'errorBarsOK', 'markerColorscale', 'showLegend'];
+ScatterGl.meta = {
+    
+};
+
+module.exports = ScatterGl;
+
+},{"../../plots/gl2d":397,"../scatter/colorbar":505,"../scatter3d/calc":524,"./attributes":534,"./convert":535,"./defaults":536}],538:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var colorscaleAttrs = require('../../components/colorscale/attributes');
+var extendFlat = require('../../lib/extend').extendFlat;
+
+
+function makeContourProjAttr(axLetter) {
+    return {
+        valType: 'boolean',
+        
+        dflt: false,
+        
+    };
+}
+
+function makeContourAttr(axLetter) {
+    return {
+        show: {
+            valType: 'boolean',
+            
+            dflt: false,
+            
+        },
+        project: {
+            x: makeContourProjAttr('x'),
+            y: makeContourProjAttr('y'),
+            z: makeContourProjAttr('z')
+        },
+        color: {
+            valType: 'color',
+            
+            dflt: '#000'
+        },
+        usecolormap: {
+            valType: 'boolean',
+            
+            dflt: false
+        },
+        width: {
+            valType: 'number',
+            
+            min: 1,
+            max: 16,
+            dflt: 2
+        },
+        highlight: {
+            valType: 'boolean',
+            
+            dflt: false
+        },
+        highlightColor: {
+            valType: 'color',
+            
+            dflt: '#000'
+        },
+        highlightWidth: {
+            valType: 'number',
+            
+            min: 1,
+            max: 16,
+            dflt: 2
+        }
+    };
+}
+
+module.exports = {
+    z: {
+        valType: 'data_array',
+        
+    },
+    x: {
+        valType: 'data_array',
+        
+    },
+    y: {
+        valType: 'data_array',
+        
+    },
+    text: {
+        valType: 'data_array',
+        
+    },
+    zauto: colorscaleAttrs.zauto,
+    zmin: colorscaleAttrs.zmin,
+    zmax: colorscaleAttrs.zmax,
+    colorscale: colorscaleAttrs.colorscale,
+    autocolorscale: extendFlat({}, colorscaleAttrs.autocolorscale,
+        {dflt: false}),
+    reversescale: colorscaleAttrs.reversescale,
+    showscale: colorscaleAttrs.showscale,
+    contours: {
+        x: makeContourAttr('x'),
+        y: makeContourAttr('y'),
+        z: makeContourAttr('z')
+    },
+    hidesurface: {
+        valType: 'boolean',
+        
+        dflt: false
+    },
+    lighting: {
+        ambient: {
+            valType: 'number',
+            
+            min: 0.00,
+            max: 1.0,
+            dflt: 0.8
+        },
+        diffuse: {
+            valType: 'number',
+            
+            min: 0.00,
+            max: 1.00,
+            dflt: 0.8
+        },
+        specular: {
+            valType: 'number',
+            
+            min: 0.00,
+            max: 2.00,
+            dflt: 0.05
+        },
+        roughness: {
+            valType: 'number',
+            
+            min: 0.00,
+            max: 1.00,
+            dflt: 0.5
+        },
+        fresnel: {
+            valType: 'number',
+            
+            min: 0.00,
+            max: 5.00,
+            dflt: 0.2
+        }
+    },
+
+    opacity: {
+        valType: 'number',
+        
+        min: 0,
+        max: 1,
+        dflt: 1
+    },
+
+    _nestedModules: {  // nested module coupling
+        'colorbar': 'Colorbar'
+    }
+};
+
+},{"../../components/colorscale/attributes":305,"../../lib/extend":345}],539:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var colorscaleCalc = require('../../components/colorscale/calc');
+
+
+// Compute auto-z and autocolorscale if applicable
+module.exports = function calc(gd, trace) {
+    colorscaleCalc(trace, trace.z, '', 'z');
+};
+
+},{"../../components/colorscale/calc":306}],540:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var createSurface = require('gl-surface3d');
+var ndarray = require('ndarray');
+var homography = require('ndarray-homography');
+var fill = require('ndarray-fill');
+var ops = require('ndarray-ops');
+var tinycolor = require('tinycolor2');
+
+var str2RgbaArray = require('../../lib/str2rgbarray');
+
+var MIN_RESOLUTION = 128;
+
+
+function SurfaceTrace(scene, surface, uid) {
+    this.scene = scene;
+    this.uid = uid;
+    this.surface = surface;
+    this.data = null;
+    this.showContour = [false, false, false];
+    this.dataScale = 1.0;
+}
+
+var proto = SurfaceTrace.prototype;
+
+proto.handlePick = function(selection) {
+    if(selection.object === this.surface) {
+        var selectIndex = [
+            Math.min(
+                Math.round(selection.data.index[0]/this.dataScale-1)|0,
+                this.data.z[0].length-1
+            ),
+            Math.min(
+                Math.round(selection.data.index[1]/this.dataScale-1)|0,
+                this.data.z.length-1
+            )
+        ];
+        var traceCoordinate = [0,0,0];
+
+        if(Array.isArray(this.data.x[0])) {
+            traceCoordinate[0] = this.data.x[selectIndex[1]][selectIndex[0]];
+        } else {
+            traceCoordinate[0] = this.data.x[selectIndex[0]];
+        }
+        if(Array.isArray(this.data.y[0])) {
+            traceCoordinate[1] = this.data.y[selectIndex[1]][selectIndex[0]];
+        } else {
+            traceCoordinate[1] = this.data.y[selectIndex[1]];
+        }
+
+        traceCoordinate[2] = this.data.z[selectIndex[1]][selectIndex[0]];
+        selection.traceCoordinate = traceCoordinate;
+
+        var sceneLayout = this.scene.fullSceneLayout;
+        selection.dataCoordinate = [
+            sceneLayout.xaxis.d2l(traceCoordinate[0]) * this.scene.dataScale[0],
+            sceneLayout.yaxis.d2l(traceCoordinate[1]) * this.scene.dataScale[1],
+            sceneLayout.zaxis.d2l(traceCoordinate[2]) * this.scene.dataScale[2]
+        ];
+
+        var text = this.data.text;
+        if(text && text[selectIndex[1]] && text[selectIndex[1]][selectIndex[0]]!==undefined) {
+            selection.textLabel = text[selectIndex[1]][selectIndex[0]];
+        }
+        else selection.textLabel = '';
+
+        selection.data.dataCoordinate = selection.dataCoordinate.slice();
+
+        this.surface.highlight(selection.data);
+
+        // Snap spikes to data coordinate
+        this.scene.glplot.spikes.position = selection.dataCoordinate;
+
+        return true;
+    }
+};
+
+function parseColorScale(colorscale, alpha) {
+    if(alpha === undefined) alpha = 1;
+
+    return colorscale.map(function(elem) {
+        var index = elem[0];
+        var color = tinycolor(elem[1]);
+        var rgb = color.toRgb();
+        return {
+            index: index,
+            rgb: [rgb.r, rgb.g, rgb.b, alpha]
+        };
+    });
+}
+
+// Pad coords by +1
+function padField(field) {
+    var shape = field.shape;
+    var nshape = [shape[0]+2, shape[1]+2];
+    var nfield = ndarray(new Float32Array(nshape[0] * nshape[1]), nshape);
+
+    // Center
+    ops.assign(nfield.lo(1, 1).hi(shape[0], shape[1]), field);
+
+    // Edges
+    ops.assign(nfield.lo(1).hi(shape[0], 1),
+                field.hi(shape[0], 1));
+    ops.assign(nfield.lo(1, nshape[1]-1).hi(shape[0], 1),
+                field.lo(0, shape[1]-1).hi(shape[0], 1));
+    ops.assign(nfield.lo(0, 1).hi(1, shape[1]),
+                field.hi(1));
+    ops.assign(nfield.lo(nshape[0]-1, 1).hi(1, shape[1]),
+                field.lo(shape[0]-1));
+
+    // Corners
+    nfield.set(0, 0, field.get(0, 0));
+    nfield.set(0, nshape[1]-1, field.get(0, shape[1]-1));
+    nfield.set(nshape[0]-1, 0, field.get(shape[0]-1, 0));
+    nfield.set(nshape[0]-1, nshape[1]-1, field.get(shape[0]-1, shape[1]-1));
+
+    return nfield;
+}
+
+function refine(coords) {
+    var minScale = Math.max(coords[0].shape[0], coords[0].shape[1]);
+
+    if(minScale < MIN_RESOLUTION) {
+        var scaleF = MIN_RESOLUTION / minScale;
+        var nshape = [
+            Math.floor((coords[0].shape[0]) * scaleF+1)|0,
+            Math.floor((coords[0].shape[1]) * scaleF+1)|0 ];
+        var nsize = nshape[0] * nshape[1];
+
+        for(var i = 0; i < 3; ++i) {
+            var padImg = padField(coords[i]);
+            var scaledImg = ndarray(new Float32Array(nsize), nshape);
+            homography(scaledImg, padImg, [scaleF, 0, 0,
+                                              0, scaleF, 0,
+                                              0, 0, 1]);
+            coords[i] = scaledImg;
+        }
+
+        return scaleF;
+    }
+
+    return 1.0;
+}
+
+proto.setContourLevels = function() {
+    var nlevels = [[], [], []];
+    var needsUpdate = false;
+
+    for(var i = 0; i < 3; ++i) {
+        if(this.showContour[i]) {
+            needsUpdate = true;
+            nlevels[i] = this.scene.contourLevels[i];
+        }
+    }
+
+    if(needsUpdate) {
+        this.surface.update({ levels: nlevels });
+    }
+};
+
+proto.update = function(data) {
+    var i,
+        scene = this.scene,
+        sceneLayout = scene.fullSceneLayout,
+        surface = this.surface,
+        alpha = data.opacity,
+        colormap = parseColorScale(data.colorscale, alpha),
+        z = data.z,
+        x = data.x,
+        y = data.y,
+        xaxis = sceneLayout.xaxis,
+        yaxis = sceneLayout.yaxis,
+        zaxis = sceneLayout.zaxis,
+        scaleFactor = scene.dataScale,
+        xlen = z[0].length,
+        ylen = z.length,
+        coords = [
+            ndarray(new Float32Array(xlen * ylen), [xlen, ylen]),
+            ndarray(new Float32Array(xlen * ylen), [xlen, ylen]),
+            ndarray(new Float32Array(xlen * ylen), [xlen, ylen])
+        ],
+        xc = coords[0],
+        yc = coords[1],
+        contourLevels = scene.contourLevels;
+
+    //Save data
+    this.data = data;
+
+    /*
+     * Fill and transpose zdata.
+     * Consistent with 'heatmap' and 'contour', plotly 'surface'
+     * 'z' are such that sub-arrays correspond to y-coords
+     * and that the sub-array entries correspond to a x-coords,
+     * which is the transpose of 'gl-surface-plot'.
+     */
+    fill(coords[2], function(row, col) {
+        return zaxis.d2l(z[col][row]) * scaleFactor[2];
+    });
+
+    // coords x
+    if(Array.isArray(x[0])) {
+        fill(xc, function(row, col) {
+            return xaxis.d2l(x[col][row]) * scaleFactor[0];
+        });
+    } else {
+        // ticks x
+        fill(xc, function(row) {
+            return xaxis.d2l(x[row]) * scaleFactor[0];
+        });
+    }
+
+    // coords y
+    if(Array.isArray(y[0])) {
+        fill(yc, function(row, col) {
+            return yaxis.d2l(y[col][row]) * scaleFactor[1];
+        });
+    } else {
+        // ticks y
+        fill(yc, function(row, col) {
+            return yaxis.d2l(y[col]) * scaleFactor[1];
+        });
+    }
+
+    //Refine if necessary
+    this.dataScale = refine(coords);
+
+    var params = {
+        colormap: colormap,
+        levels: [[], [], []],
+        showContour: [true, true, true],
+        showSurface: !data.hidesurface,
+        contourProject: [
+            [false, false, false],
+            [false, false, false],
+            [false, false, false]
+        ],
+        contourWidth: [1, 1, 1],
+        contourColor: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
+        contourTint: [1, 1, 1],
+        dynamicColor: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]],
+        dynamicWidth: [1, 1, 1],
+        dynamicTint: [1, 1, 1],
+        opacity: 1,
+        colorBounds: [data.zmin * scaleFactor[2], data.zmax * scaleFactor[2]]
+    };
+
+
+    if('opacity' in data) {
+        if(data.opacity < 1) {
+            params.opacity = 0.25 * data.opacity;
+        }
+    }
+
+    var highlightEnable = [true, true, true];
+    var contourEnable = [true, true, true];
+    var axis = ['x', 'y', 'z'];
+
+    for(i = 0; i < 3; ++i) {
+        var contourParams = data.contours[axis[i]];
+        highlightEnable[i] = contourParams.highlight;
+        contourEnable[i] = contourParams.show;
+
+        params.showContour[i] = contourParams.show || contourParams.highlight;
+        if(!params.showContour[i]) continue;
+
+        params.contourProject[i] = [
+            contourParams.project.x,
+            contourParams.project.y,
+            contourParams.project.z
+        ];
+
+        if(contourParams.show) {
+            this.showContour[i] = true;
+            params.levels[i] = contourLevels[i];
+            surface.highlightColor[i] = params.contourColor[i] = str2RgbaArray(contourParams.color);
+            if(contourParams.usecolormap) {
+                surface.highlightTint[i] = params.contourTint[i] = 0;
+            }
+            else {
+                surface.highlightTint[i] = params.contourTint[i] = 1;
+            }
+            params.contourWidth[i] = contourParams.width;
+        } else {
+            this.showContour[i] = false;
+        }
+
+        if(contourParams.highlight) {
+            params.dynamicColor[i] = str2RgbaArray(contourParams.highlightColor);
+            params.dynamicWidth[i] = contourParams.highlightWidth;
+        }
+    }
+
+    params.coords = coords;
+    surface.update(params);
+
+    surface.highlightEnable = highlightEnable;
+    surface.contourEnable = contourEnable;
+    surface.visible = data.visible;
+
+    surface.snapToData = true;
+
+    if('lighting' in data) {
+        surface.ambientLight = data.lighting.ambient;
+        surface.diffuseLight = data.lighting.diffuse;
+        surface.specularLight = data.lighting.specular;
+        surface.roughness = data.lighting.roughness;
+        surface.fresnel = data.lighting.fresnel;
+    }
+
+    if(alpha && alpha < 1) {
+        surface.supportsTransparency = true;
+    }
+};
+
+
+proto.dispose = function() {
+    this.scene.glplot.remove(this.surface);
+    this.surface.dispose();
+};
+
+function createSurfaceTrace(scene, data) {
+    var gl = scene.glplot.gl;
+    var surface = createSurface({ gl: gl });
+    var result = new SurfaceTrace(scene, surface, data.uid);
+    result.update(data);
+    scene.glplot.add(surface);
+    return result;
+}
+
+module.exports = createSurfaceTrace;
+
+},{"../../lib/str2rgbarray":359,"gl-surface3d":184,"ndarray":208,"ndarray-fill":201,"ndarray-homography":206,"ndarray-ops":207,"tinycolor2":229}],541:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Lib = require('../../lib');
+
+var colorscaleDefaults = require('../../components/colorscale/defaults');
+var attributes = require('./attributes');
+
+
+module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
+    var i, j;
+
+    function coerce(attr, dflt) {
+        return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
+    }
+
+    var z = coerce('z');
+    if(!z) {
+        traceOut.visible = false;
+        return;
+    }
+
+    var xlen = z[0].length;
+    var ylen = z.length;
+
+    coerce('x');
+    coerce('y');
+
+    if(!Array.isArray(traceOut.x)) {
+        // build a linearly scaled x
+        traceOut.x = [];
+        for(i = 0; i < xlen; ++i) {
+            traceOut.x[i] = i;
+        }
+    }
+
+    coerce('text');
+    if(!Array.isArray(traceOut.y)) {
+        traceOut.y = [];
+        for(i = 0; i < ylen; ++i) {
+            traceOut.y[i] = i;
+        }
+    }
+
+    coerce('lighting.ambient');
+    coerce('lighting.diffuse');
+    coerce('lighting.specular');
+    coerce('lighting.roughness');
+    coerce('lighting.fresnel');
+    coerce('hidesurface');
+    coerce('opacity');
+
+    coerce('colorscale');
+
+    var dims = ['x', 'y', 'z'];
+    for(i = 0; i < 3; ++i) {
+
+        var contourDim = 'contours.' + dims[i];
+        var show = coerce(contourDim + '.show');
+        var highlight = coerce(contourDim + '.highlight');
+
+        if(show || highlight) {
+            for(j = 0; j < 3; ++j) {
+                coerce(contourDim + '.project.' + dims[j]);
+            }
+        }
+
+        if(show) {
+            coerce(contourDim + '.color');
+            coerce(contourDim + '.width');
+            coerce(contourDim + '.usecolormap');
+        }
+
+        if(highlight) {
+            coerce(contourDim + '.highlightColor');
+            coerce(contourDim + '.highlightWidth');
+        }
+    }
+
+    colorscaleDefaults(
+        traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
+    );
+};
+
+},{"../../components/colorscale/defaults":308,"../../lib":349,"./attributes":538}],542:[function(require,module,exports){
+/**
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+*
+* This source code is licensed under the MIT license found in the
+* LICENSE file in the root directory of this source tree.
+*/
+
+
+'use strict';
+
+var Surface = {};
+
+Surface.attributes = require('./attributes');
+Surface.supplyDefaults = require('./defaults');
+Surface.colorbar = require('../heatmap/colorbar');
+Surface.calc = require('./calc');
+Surface.plot = require('./convert');
+
+Surface.moduleType = 'trace';
+Surface.name = 'surface';
+Surface.basePlotModule = require('../../plots/gl3d');
+Surface.categories = ['gl3d', 'noOpacity'];
+Surface.meta = {
+    
+};
+
+module.exports = Surface;
+
+},{"../../plots/gl3d":400,"../heatmap/colorbar":461,"./attributes":538,"./calc":539,"./convert":540,"./defaults":541}]},{},[12])(12)
+});
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/js/plotly.min.js
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/js/plotly.min.js	(revision 13712)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive.WebJobManager/wwwroot/js/plotly.min.js	(revision 13712)
@@ -0,0 +1,42 @@
+/**
+* plotly.js v1.6.3
+* Copyright 2012-2016, Plotly, Inc.
+* All rights reserved.
+* Licensed under the MIT license
+*/
+!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.Plotly=t()}}(function(){var t;return function e(t,r,n){function i(o,s){if(!r[o]){if(!t[o]){var l="function"==typeof require&&require;if(!s&&l)return l(o,!0);if(a)return a(o,!0);var u=new Error("Cannot find module '"+o+"'");throw u.code="MODULE_NOT_FOUND",u}var c=r[o]={exports:{}};t[o][0].call(c.exports,function(e){var r=t[o][1][e];return i(r?r:e)},c,c.exports,e,t,r,n)}return r[o].exports}for(var a="function"==typeof require&&require,o=0;o<n.length;o++)i(n[o]);return i}({1:[function(t,e,r){"use strict";var n=t("../src/plotly"),i={"X,X div":"font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;","X input,X button":"font-family:'Open Sans', verdana, arial, sans-serif;","X input:focus,X button:focus":"outline:none;","X a":"text-decoration:none;","X a:hover":"text-decoration:none;","X .crisp":"shape-rendering:crispEdges;","X svg":"overflow:hidden;","X svg a":"fill:#447adb;","X svg a:hover":"fill:#3c6dc5;","X .main-svg":"position:absolute;top:0;left:0;pointer-events:none;","X .main-svg .draglayer":"pointer-events:all;","X .cursor-pointer":"cursor:pointer;","X .cursor-crosshair":"cursor:crosshair;","X .cursor-move":"cursor:move;","X .cursor-col-resize":"cursor:col-resize;","X .cursor-row-resize":"cursor:row-resize;","X .cursor-ns-resize":"cursor:ns-resize;","X .cursor-ew-resize":"cursor:ew-resize;","X .cursor-sw-resize":"cursor:sw-resize;","X .cursor-s-resize":"cursor:s-resize;","X .cursor-se-resize":"cursor:se-resize;","X .cursor-w-resize":"cursor:w-resize;","X .cursor-e-resize":"cursor:e-resize;","X .cursor-nw-resize":"cursor:nw-resize;","X .cursor-n-resize":"cursor:n-resize;","X .cursor-ne-resize":"cursor:ne-resize;","X .modebar":"position:absolute;top:2px;right:2px;z-index:1001;background:rgba(255,255,255,0.7);","X .modebar--hover":"opacity:0;-webkit-transition:opacity 0.3s ease 0s;-moz-transition:opacity 0.3s ease 0s;-ms-transition:opacity 0.3s ease 0s;-o-transition:opacity 0.3s ease 0s;transition:opacity 0.3s ease 0s;","X:hover .modebar--hover":"opacity:1;","X .modebar-group":"float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;","X .modebar-group:first-child":"margin-left:0px;","X .modebar-btn":"position:relative;font-size:16px;padding:3px 4px;cursor:pointer;line-height:normal;box-sizing:border-box;","X .modebar-btn svg":"position:relative;top:2px;","X .modebar-btn path":"fill:rgba(0,31,95,0.3);","X .modebar-btn.active path,X .modebar-btn:hover path":"fill:rgba(0,22,72,0.5);","X .modebar-btn.modebar-btn--logo":"padding:3px 1px;","X .modebar-btn.modebar-btn--logo path":"fill:#447adb !important;","X [data-title]:before,X [data-title]:after":"position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;","X [data-title]:hover:before,X [data-title]:hover:after":"display:block;opacity:1;","X [data-title]:before":"content:'';position:absolute;background:transparent;border:6px solid transparent;z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;","X [data-title]:after":"content:attr(data-title);background:#69738a;color:white;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;","X .select-outline":"fill:none;stroke-width:1;shape-rendering:crispEdges;","X .select-outline-1":"stroke:white;","X .select-outline-2":"stroke:black;stroke-dasharray:2px 2px;",Y:"font-family:'Open Sans';position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;","Y p":"margin:0;","Y .notifier-note":"min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,0.9);color:#fff;padding:10px;","Y .notifier-close":"color:#fff;opacity:0.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;","Y .notifier-close:hover":"color:#444;text-decoration:none;cursor:pointer;"};for(var a in i){var o=a.replace(/^,/," ,").replace(/X/g,".js-plotly-plot .plotly").replace(/Y/g,".plotly-notifier");n.Lib.addStyleRule(o,i[a])}},{"../src/plotly":366}],2:[function(t,e,r){"use strict";e.exports={undo:{width:857.1,path:"m857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z",ascent:850,descent:-150},home:{width:928.6,path:"m786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z",ascent:850,descent:-150},"camera-retro":{width:1e3,path:"m518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z",ascent:850,descent:-150},zoombox:{width:1e3,path:"m1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z",ascent:850,descent:-150},pan:{width:1e3,path:"m1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z",ascent:850,descent:-150},zoom_plus:{width:1e3,path:"m1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z",ascent:850,descent:-150},zoom_minus:{width:1e3,path:"m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z",ascent:850,descent:-150},autoscale:{width:1e3,path:"m250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z",ascent:850,descent:-150},tooltip_basic:{width:1500,path:"m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z",ascent:850,descent:-150},tooltip_compare:{width:1125,path:"m187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z",ascent:850,descent:-150},plotlylogo:{width:1542,path:"m0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z",ascent:850,descent:-150},"z-axis":{width:1e3,path:"m833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z",ascent:850,descent:-150},"3d_rotate":{width:1e3,path:"m922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z",ascent:850,descent:-150},camera:{width:1e3,path:"m500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z",ascent:850,descent:-150},movie:{width:1e3,path:"m938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z",ascent:850,descent:-150},question:{width:857.1,path:"m500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z",ascent:850,descent:-150},disk:{width:857.1,path:"m214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z",ascent:850,descent:-150},lasso:{width:1031,path:"m1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z",ascent:850,descent:-150},selectbox:{width:1e3,path:"m0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z",ascent:850,descent:-150}}},{}],3:[function(t,e,r){e.exports=t("../src/traces/bar")},{"../src/traces/bar":429}],4:[function(t,e,r){e.exports=t("../src/traces/box")},{"../src/traces/box":440}],5:[function(t,e,r){e.exports=t("../src/traces/choropleth")},{"../src/traces/choropleth":448}],6:[function(t,e,r){e.exports=t("../src/traces/contour")},{"../src/traces/contour":455}],7:[function(t,e,r){e.exports=t("../src/core")},{"../src/core":339}],8:[function(t,e,r){e.exports=t("../src/traces/heatmap")},{"../src/traces/heatmap":466}],9:[function(t,e,r){e.exports=t("../src/traces/histogram")},{"../src/traces/histogram":477}],10:[function(t,e,r){e.exports=t("../src/traces/histogram2d")},{"../src/traces/histogram2d":482}],11:[function(t,e,r){e.exports=t("../src/traces/histogram2dcontour")},{"../src/traces/histogram2dcontour":486}],12:[function(t,e,r){"use strict";var n=t("./core");n.register([t("./bar"),t("./box"),t("./heatmap"),t("./histogram"),t("./histogram2d"),t("./histogram2dcontour"),t("./pie"),t("./contour"),t("./scatter3d"),t("./surface"),t("./mesh3d"),t("./scattergeo"),t("./choropleth"),t("./scattergl")]),e.exports=n},{"./bar":3,"./box":4,"./choropleth":5,"./contour":6,"./core":7,"./heatmap":8,"./histogram":9,"./histogram2d":10,"./histogram2dcontour":11,"./mesh3d":13,"./pie":14,"./scatter3d":15,"./scattergeo":16,"./scattergl":17,"./surface":18}],13:[function(t,e,r){e.exports=t("../src/traces/mesh3d")},{"../src/traces/mesh3d":490}],14:[function(t,e,r){e.exports=t("../src/traces/pie")},{"../src/traces/pie":495}],15:[function(t,e,r){e.exports=t("../src/traces/scatter3d")},{"../src/traces/scatter3d":528}],16:[function(t,e,r){e.exports=t("../src/traces/scattergeo")},{"../src/traces/scattergeo":532}],17:[function(t,e,r){e.exports=t("../src/traces/scattergl")},{"../src/traces/scattergl":537}],18:[function(t,e,r){e.exports=t("../src/traces/surface")},{"../src/traces/surface":542}],19:[function(t,e,r){"use strict";function n(t,e,r){return Math.min(e,Math.max(t,r))}function i(t,e,r){this.dimension=t.length,this.bounds=[new Array(this.dimension),new Array(this.dimension)];for(var n=0;n<this.dimension;++n)this.bounds[0][n]=-(1/0),this.bounds[1][n]=1/0;this._state=t.slice().reverse(),this._velocity=e.slice().reverse(),this._time=[r],this._scratch=[t.slice(),t.slice(),t.slice(),t.slice(),t.slice()]}function a(t){for(var e=new Array(t),r=0;t>r;++r)e[r]=0;return e}function o(t,e,r){switch(arguments.length){case 0:return new i([0],[0],0);case 1:if("number"==typeof t){var n=a(t);return new i(n,n,0)}return new i(t,a(t.length),0);case 2:if("number"==typeof e){var n=a(t.length);return new i(t,n,+e)}r=0;case 3:if(t.length!==e.length)throw new Error("state and velocity lengths must match");return new i(t,e,r)}}e.exports=o;var s=t("cubic-hermite"),l=t("binary-search-bounds"),u=i.prototype;u.flush=function(t){var e=l.gt(this._time,t)-1;0>=e||(this._time.splice(0,e),this._state.splice(0,e*this.dimension),this._velocity.splice(0,e*this.dimension))},u.curve=function(t){var e=this._time,r=e.length,i=l.le(e,t),a=this._scratch[0],o=this._state,u=this._velocity,c=this.dimension,h=this.bounds;if(0>i)for(var f=c-1,d=0;c>d;++d,--f)a[d]=o[f];else if(i>=r-1)for(var f=o.length-1,p=t-e[r-1],d=0;c>d;++d,--f)a[d]=o[f]+p*u[f];else{for(var f=c*(i+1)-1,g=e[i],v=e[i+1],m=v-g||1,y=this._scratch[1],b=this._scratch[2],x=this._scratch[3],_=this._scratch[4],w=!0,d=0;c>d;++d,--f)y[d]=o[f],x[d]=u[f]*m,b[d]=o[f+c],_[d]=u[f+c]*m,w=w&&y[d]===b[d]&&x[d]===_[d]&&0===x[d];if(w)for(var d=0;c>d;++d)a[d]=y[d];else s(y,x,b,_,(t-g)/m,a)}for(var A=h[0],k=h[1],d=0;c>d;++d)a[d]=n(A[d],k[d],a[d]);return a},u.dcurve=function(t){var e=this._time,r=e.length,n=l.le(e,t),i=this._scratch[0],a=this._state,o=this._velocity,u=this.dimension;if(n>=r-1)for(var c=a.length-1,h=(t-e[r-1],0);u>h;++h,--c)i[h]=o[c];else{for(var c=u*(n+1)-1,f=e[n],d=e[n+1],p=d-f||1,g=this._scratch[1],v=this._scratch[2],m=this._scratch[3],y=this._scratch[4],b=!0,h=0;u>h;++h,--c)g[h]=a[c],m[h]=o[c]*p,v[h]=a[c+u],y[h]=o[c+u]*p,b=b&&g[h]===v[h]&&m[h]===y[h]&&0===m[h];if(b)for(var h=0;u>h;++h)i[h]=0;else{s.derivative(g,m,v,y,(t-f)/p,i);for(var h=0;u>h;++h)i[h]/=p}}return i},u.lastT=function(){var t=this._time;return t[t.length-1]},u.stable=function(){for(var t=this._velocity,e=t.length,r=this.dimension-1;r>=0;--r)if(t[--e])return!1;return!0},u.jump=function(t){var e=this.lastT(),r=this.dimension;if(!(e>t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=this.bounds,l=s[0],u=s[1];this._time.push(e,t);for(var c=0;2>c;++c)for(var h=0;r>h;++h)i.push(i[o++]),a.push(0);this._time.push(t);for(var h=r;h>0;--h)i.push(n(l[h-1],u[h-1],arguments[h])),a.push(0)}},u.push=function(t){var e=this.lastT(),r=this.dimension;if(!(e>t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=t-e,l=this.bounds,u=l[0],c=l[1],h=s>1e-6?1/s:0;this._time.push(t);for(var f=r;f>0;--f){var d=n(u[f-1],c[f-1],arguments[f]);i.push(d),a.push((d-i[o++])*h)}}},u.set=function(t){var e=this.dimension;if(!(t<this.lastT()||arguments.length!==e+1)){var r=this._state,i=this._velocity,a=this.bounds,o=a[0],s=a[1];this._time.push(t);for(var l=e;l>0;--l)r.push(n(o[l-1],s[l-1],arguments[l])),i.push(0)}},u.move=function(t){var e=this.lastT(),r=this.dimension;if(!(e>=t||arguments.length!==r+1)){var i=this._state,a=this._velocity,o=i.length-this.dimension,s=this.bounds,l=s[0],u=s[1],c=t-e,h=c>1e-6?1/c:0;this._time.push(t);for(var f=r;f>0;--f){var d=arguments[f];i.push(n(l[f-1],u[f-1],i[o++]+d)),a.push(d*h)}}},u.idle=function(t){var e=this.lastT();if(!(e>t)){var r=this.dimension,i=this._state,a=this._velocity,o=i.length-r,s=this.bounds,l=s[0],u=s[1],c=t-e;this._time.push(t);for(var h=r-1;h>=0;--h)i.push(n(l[h],u[h],i[o]+c*a[o])),a.push(0),o+=1}}},{"binary-search-bounds":20,"cubic-hermite":21}],20:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){var o=["function ",t,"(a,l,h,",n.join(","),"){",a?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a",i?".get(m)":"[m]"];return a?e.indexOf("c")<0?o.push(";if(x===y){return m}else if(x<=y){"):o.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):o.push(";if(",e,"){i=m;"),r?o.push("l=m+1}else{h=m-1}"):o.push("h=m-1}else{l=m+1}"),o.push("}"),a?o.push("return -1};"):o.push("return i};"),o.join("")}function i(t,e,r,i){var a=new Function([n("A","x"+t+"y",e,["y"],!1,i),n("B","x"+t+"y",e,["y"],!0,i),n("P","c(x,y)"+t+"0",e,["y","c"],!1,i),n("Q","c(x,y)"+t+"0",e,["y","c"],!0,i),"function dispatchBsearch",r,"(a,y,c,l,h){if(a.shape){if(typeof(c)==='function'){return Q(a,(l===undefined)?0:l|0,(h===undefined)?a.shape[0]-1:h|0,y,c)}else{return B(a,(c===undefined)?0:c|0,(l===undefined)?a.shape[0]-1:l|0,y)}}else{if(typeof(c)==='function'){return P(a,(l===undefined)?0:l|0,(h===undefined)?a.length-1:h|0,y,c)}else{return A(a,(c===undefined)?0:c|0,(l===undefined)?a.length-1:l|0,y)}}}return dispatchBsearch",r].join(""));return a()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],21:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){var o=6*i*i-6*i,s=3*i*i-4*i+1,l=-6*i*i+6*i,u=3*i*i-2*i;if(t.length){a||(a=new Array(t.length));for(var c=t.length-1;c>=0;--c)a[c]=o*t[c]+s*e[c]+l*r[c]+u*n[c];return a}return o*t+s*e+l*r[c]+u*n}function i(t,e,r,n,i,a){var o=i-1,s=i*i,l=o*o,u=(1+2*i)*l,c=i*l,h=s*(3-2*i),f=s*o;if(t.length){a||(a=new Array(t.length));for(var d=t.length-1;d>=0;--d)a[d]=u*t[d]+c*e[d]+h*r[d]+f*n[d];return a}return u*t+c*e+h*r+f*n}e.exports=i,e.exports.derivative=n},{}],22:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=r[0],s=r[1],l=r[2];return t[0]=i*l-a*s,t[1]=a*o-n*l,t[2]=n*s-i*o,t}e.exports=n},{}],23:[function(t,e,r){function n(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}e.exports=n},{}],24:[function(t,e,r){function n(t){var e=t[0],r=t[1],n=t[2];return Math.sqrt(e*e+r*r+n*n)}e.exports=n},{}],25:[function(t,e,r){function n(t,e,r,n){var i=e[0],a=e[1],o=e[2];return t[0]=i+n*(r[0]-i),t[1]=a+n*(r[1]-a),t[2]=o+n*(r[2]-o),t}e.exports=n},{}],26:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=r*r+n*n+i*i;return a>0&&(a=1/Math.sqrt(a),t[0]=e[0]*a,t[1]=e[1]*a,t[2]=e[2]*a),t}e.exports=n},{}],27:[function(t,e,r){"use strict";function n(t){this._components=t.slice(),this._time=[0],this.prevMatrix=t.slice(),this.nextMatrix=t.slice(),this.computedMatrix=t.slice(),this.computedInverse=t.slice(),this.computedEye=[0,0,0],this.computedUp=[0,0,0],this.computedCenter=[0,0,0],this.computedRadius=[0],this._limits=[-(1/0),1/0]}function i(t){t=t||{};var e=t.matrix||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];return new n(e)}var a=t("binary-search-bounds"),o=t("mat4-interpolate"),s=t("gl-mat4/invert"),l=t("gl-mat4/rotateX"),u=t("gl-mat4/rotateY"),c=t("gl-mat4/rotateZ"),h=t("gl-mat4/lookAt"),f=t("gl-mat4/translate"),d=(t("gl-mat4/scale"),t("gl-vec3/normalize")),p=[0,0,0];e.exports=i;var g=n.prototype;g.recalcMatrix=function(t){var e=this._time,r=a.le(e,t),n=this.computedMatrix;if(!(0>r)){var i=this._components;if(r===e.length-1)for(var l=16*r,u=0;16>u;++u)n[u]=i[l++];else{for(var c=e[r+1]-e[r],l=16*r,h=this.prevMatrix,f=!0,u=0;16>u;++u)h[u]=i[l++];for(var p=this.nextMatrix,u=0;16>u;++u)p[u]=i[l++],f=f&&h[u]===p[u];if(1e-6>c||f)for(var u=0;16>u;++u)n[u]=h[u];else o(n,h,p,(t-e[r])/c)}var g=this.computedUp;g[0]=n[1],g[1]=n[5],g[2]=n[6],d(g,g);var v=this.computedInverse;s(v,n);var m=this.computedEye,y=v[15];m[0]=v[12]/y,m[1]=v[13]/y,m[2]=v[14]/y;for(var b=this.computedCenter,x=Math.exp(this.computedRadius[0]),u=0;3>u;++u)b[u]=m[u]-n[2+4*u]*x}},g.idle=function(t){if(!(t<this.lastT())){for(var e=this._components,r=e.length-16,n=0;16>n;++n)e.push(e[r++]);this._time.push(t)}},g.flush=function(t){var e=a.gt(this._time,t)-2;0>e||(this._time.slice(0,e),this._components.slice(0,16*e))},g.lastT=function(){return this._time[this._time.length-1]},g.lookAt=function(t,e,r,n){this.recalcMatrix(t),e=e||this.computedEye,r=r||p,n=n||this.computedUp,this.setMatrix(t,h(this.computedMatrix,e,r,n));for(var i=0,a=0;3>a;++a)i+=Math.pow(r[a]-e[a],2);i=Math.log(Math.sqrt(i)),this.computedRadius[0]=i},g.rotate=function(t,e,r,n){this.recalcMatrix(t);var i=this.computedInverse;e&&u(i,i,e),r&&l(i,i,r),n&&c(i,i,n),this.setMatrix(t,s(this.computedMatrix,i))};var v=[0,0,0];g.pan=function(t,e,r,n){v[0]=-(e||0),v[1]=-(r||0),v[2]=-(n||0),this.recalcMatrix(t);var i=this.computedInverse;f(i,i,v),this.setMatrix(t,s(i,i))},g.translate=function(t,e,r,n){v[0]=e||0,v[1]=r||0,v[2]=n||0,this.recalcMatrix(t);var i=this.computedMatrix;f(i,i,v),this.setMatrix(t,i)},g.setMatrix=function(t,e){if(!(t<this.lastT())){this._time.push(t);for(var r=0;16>r;++r)this._components.push(e[r])}},g.setDistance=function(t,e){this.computedRadius[0]=e},g.setDistanceLimits=function(t,e){var r=this._limits;r[0]=t,r[1]=e},g.getDistanceLimits=function(t){var e=this._limits;return t?(t[0]=e[0],t[1]=e[1],t):e}},{"binary-search-bounds":28,"gl-mat4/invert":94,"gl-mat4/lookAt":95,"gl-mat4/rotateX":99,"gl-mat4/rotateY":100,"gl-mat4/rotateZ":101,"gl-mat4/scale":102,"gl-mat4/translate":103,"gl-vec3/normalize":26,"mat4-interpolate":29}],28:[function(t,e,r){arguments[4][20][0].apply(r,arguments)},{dup:20}],29:[function(t,e,r){function n(t,e,r,n){if(0===c(e)||0===c(r))return!1;var i=u(e,f.translate,f.scale,f.skew,f.perspective,f.quaternion),a=u(r,d.translate,d.scale,d.skew,d.perspective,d.quaternion);return i&&a?(s(p.translate,f.translate,d.translate,n),s(p.skew,f.skew,d.skew,n),s(p.scale,f.scale,d.scale,n),s(p.perspective,f.perspective,d.perspective,n),h(p.quaternion,f.quaternion,d.quaternion,n),l(t,p.translate,p.scale,p.skew,p.perspective,p.quaternion),!0):!1}function i(){return{translate:a(),scale:a(1),skew:a(),perspective:o(),quaternion:o()}}function a(t){return[t||0,t||0,t||0]}function o(){return[0,0,0,1]}var s=t("gl-vec3/lerp"),l=t("mat4-recompose"),u=t("mat4-decompose"),c=t("gl-mat4/determinant"),h=t("quat-slerp"),f=i(),d=i(),p=i();e.exports=n},{"gl-mat4/determinant":90,"gl-vec3/lerp":25,"mat4-decompose":30,"mat4-recompose":32,"quat-slerp":33}],30:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}function i(t,e){t[0][0]=e[0],t[0][1]=e[1],t[0][2]=e[2],t[1][0]=e[4],t[1][1]=e[5],t[1][2]=e[6],t[2][0]=e[8],t[2][1]=e[9],t[2][2]=e[10]}function a(t,e,r,n,i){t[0]=e[0]*n+r[0]*i,t[1]=e[1]*n+r[1]*i,t[2]=e[2]*n+r[2]*i}var o=t("./normalize"),s=t("gl-mat4/create"),l=t("gl-mat4/clone"),u=t("gl-mat4/determinant"),c=t("gl-mat4/invert"),h=t("gl-mat4/transpose"),f={length:t("gl-vec3/length"),normalize:t("gl-vec3/normalize"),dot:t("gl-vec3/dot"),cross:t("gl-vec3/cross")},d=s(),p=s(),g=[0,0,0,0],v=[[0,0,0],[0,0,0],[0,0,0]],m=[0,0,0];e.exports=function(t,e,r,s,y,b){if(e||(e=[0,0,0]),r||(r=[0,0,0]),s||(s=[0,0,0]),y||(y=[0,0,0,1]),b||(b=[0,0,0,1]),!o(d,t))return!1;if(l(p,d),p[3]=0,p[7]=0,p[11]=0,p[15]=1,Math.abs(u(p)<1e-8))return!1;var x=d[3],_=d[7],w=d[11],A=d[12],k=d[13],M=d[14],T=d[15];if(0!==x||0!==_||0!==w){g[0]=x,g[1]=_,g[2]=w,g[3]=T;var E=c(p,p);if(!E)return!1;h(p,p),n(y,g,p)}else y[0]=y[1]=y[2]=0,y[3]=1;if(e[0]=A,e[1]=k,e[2]=M,i(v,d),r[0]=f.length(v[0]),f.normalize(v[0],v[0]),s[0]=f.dot(v[0],v[1]),a(v[1],v[1],v[0],1,-s[0]),r[1]=f.length(v[1]),f.normalize(v[1],v[1]),s[0]/=r[1],s[1]=f.dot(v[0],v[2]),a(v[2],v[2],v[0],1,-s[1]),s[2]=f.dot(v[1],v[2]),a(v[2],v[2],v[1],1,-s[2]),r[2]=f.length(v[2]),f.normalize(v[2],v[2]),s[1]/=r[2],s[2]/=r[2],f.cross(m,v[1],v[2]),f.dot(v[0],m)<0)for(var L=0;3>L;L++)r[L]*=-1,v[L][0]*=-1,v[L][1]*=-1,v[L][2]*=-1;return b[0]=.5*Math.sqrt(Math.max(1+v[0][0]-v[1][1]-v[2][2],0)),b[1]=.5*Math.sqrt(Math.max(1-v[0][0]+v[1][1]-v[2][2],0)),b[2]=.5*Math.sqrt(Math.max(1-v[0][0]-v[1][1]+v[2][2],0)),b[3]=.5*Math.sqrt(Math.max(1+v[0][0]+v[1][1]+v[2][2],0)),v[2][1]>v[1][2]&&(b[0]=-b[0]),v[0][2]>v[2][0]&&(b[1]=-b[1]),v[1][0]>v[0][1]&&(b[2]=-b[2]),!0}},{"./normalize":31,"gl-mat4/clone":88,"gl-mat4/create":89,"gl-mat4/determinant":90,"gl-mat4/invert":94,"gl-mat4/transpose":104,"gl-vec3/cross":22,"gl-vec3/dot":23,"gl-vec3/length":24,"gl-vec3/normalize":26}],31:[function(t,e,r){e.exports=function(t,e){var r=e[15];if(0===r)return!1;for(var n=1/r,i=0;16>i;i++)t[i]=e[i]*n;return!0}},{}],32:[function(t,e,r){var n={identity:t("gl-mat4/identity"),translate:t("gl-mat4/translate"),multiply:t("gl-mat4/multiply"),create:t("gl-mat4/create"),scale:t("gl-mat4/scale"),fromRotationTranslation:t("gl-mat4/fromRotationTranslation")},i=(n.create(),n.create());e.exports=function(t,e,r,a,o,s){return n.identity(t),n.fromRotationTranslation(t,s,e),t[3]=o[0],t[7]=o[1],t[11]=o[2],t[15]=o[3],n.identity(i),0!==a[2]&&(i[9]=a[2],n.multiply(t,t,i)),0!==a[1]&&(i[9]=0,i[8]=a[1],n.multiply(t,t,i)),0!==a[0]&&(i[8]=0,i[4]=a[0],n.multiply(t,t,i)),n.scale(t,t,r),t}},{"gl-mat4/create":89,"gl-mat4/fromRotationTranslation":92,"gl-mat4/identity":93,"gl-mat4/multiply":96,"gl-mat4/scale":102,"gl-mat4/translate":103}],33:[function(t,e,r){e.exports=t("gl-quat/slerp")},{"gl-quat/slerp":34}],34:[function(t,e,r){function n(t,e,r,n){var i,a,o,s,l,u=e[0],c=e[1],h=e[2],f=e[3],d=r[0],p=r[1],g=r[2],v=r[3];return a=u*d+c*p+h*g+f*v,0>a&&(a=-a,d=-d,p=-p,g=-g,v=-v),1-a>1e-6?(i=Math.acos(a),o=Math.sin(i),s=Math.sin((1-n)*i)/o,l=Math.sin(n*i)/o):(s=1-n,l=n),t[0]=s*u+l*d,t[1]=s*c+l*p,t[2]=s*h+l*g,t[3]=s*f+l*v,t}e.exports=n},{}],35:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s,l,u){var c=e+a+u;if(h>0){var h=Math.sqrt(c+1);t[0]=.5*(o-l)/h,t[1]=.5*(s-n)/h,t[2]=.5*(r-a)/h,t[3]=.5*h}else{var f=Math.max(e,a,u),h=Math.sqrt(2*f-c+1);e>=f?(t[0]=.5*h,t[1]=.5*(i+r)/h,t[2]=.5*(s+n)/h,t[3]=.5*(o-l)/h):a>=f?(t[0]=.5*(r+i)/h,t[1]=.5*h,t[2]=.5*(l+o)/h,t[3]=.5*(s-n)/h):(t[0]=.5*(n+s)/h,t[1]=.5*(o+l)/h,t[2]=.5*h,t[3]=.5*(r-i)/h)}return t}e.exports=n},{}],36:[function(t,e,r){"use strict";function n(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function i(t,e,r,n){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2)+Math.pow(n,2))}function a(t,e){var r=e[0],n=e[1],a=e[2],o=e[3],s=i(r,n,a,o);s>1e-6?(t[0]=r/s,t[1]=n/s,t[2]=a/s,t[3]=o/s):(t[0]=t[1]=t[2]=0,t[3]=1)}function o(t,e,r){this.radius=l([r]),this.center=l(e),this.rotation=l(t),this.computedRadius=this.radius.curve(0),this.computedCenter=this.center.curve(0),this.computedRotation=this.rotation.curve(0),this.computedUp=[.1,0,0],this.computedEye=[.1,0,0],this.computedMatrix=[.1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.recalcMatrix(0)}function s(t){t=t||{};var e=t.center||[0,0,0],r=t.rotation||[0,0,0,1],n=t.radius||1;e=[].slice.call(e,0,3),r=[].slice.call(r,0,4),a(r,r);var i=new o(r,e,Math.log(n));return i.setDistanceLimits(t.zoomMin,t.zoomMax),("eye"in t||"up"in t)&&i.lookAt(0,t.eye,t.center,t.up),i}e.exports=s;var l=t("filtered-vector"),u=t("gl-mat4/lookAt"),c=t("gl-mat4/fromQuat"),h=t("gl-mat4/invert"),f=t("./lib/quatFromFrame"),d=o.prototype;d.lastT=function(){return Math.max(this.radius.lastT(),this.center.lastT(),this.rotation.lastT())},d.recalcMatrix=function(t){this.radius.curve(t),this.center.curve(t),this.rotation.curve(t);var e=this.computedRotation;a(e,e);var r=this.computedMatrix;c(r,e);var n=this.computedCenter,i=this.computedEye,o=this.computedUp,s=Math.exp(this.computedRadius[0]);i[0]=n[0]+s*r[2],i[1]=n[1]+s*r[6],i[2]=n[2]+s*r[10],o[0]=r[1],o[1]=r[5],o[2]=r[9];for(var l=0;3>l;++l){for(var u=0,h=0;3>h;++h)u+=r[l+4*h]*i[h];r[12+l]=-u}},d.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;16>n;++n)e[n]=r[n];return e}return r},d.idle=function(t){this.center.idle(t),this.radius.idle(t),this.rotation.idle(t)},d.flush=function(t){this.center.flush(t),this.radius.flush(t),this.rotation.flush(t)},d.pan=function(t,e,r,i){e=e||0,r=r||0,i=i||0,this.recalcMatrix(t);var a=this.computedMatrix,o=a[1],s=a[5],l=a[9],u=n(o,s,l);o/=u,s/=u,l/=u;var c=a[0],h=a[4],f=a[8],d=c*o+h*s+f*l;c-=o*d,h-=s*d,f-=l*d;var p=n(c,h,f);c/=p,h/=p,f/=p;var g=a[2],v=a[6],m=a[10],y=g*o+v*s+m*l,b=g*c+v*h+m*f;g-=y*o+b*c,v-=y*s+b*h,m-=y*l+b*f;var x=n(g,v,m);g/=x,v/=x,m/=x;var _=c*e+o*r,w=h*e+s*r,A=f*e+l*r;this.center.move(t,_,w,A);var k=Math.exp(this.computedRadius[0]);k=Math.max(1e-4,k+i),this.radius.set(t,Math.log(k))},d.rotate=function(t,e,r,a){this.recalcMatrix(t),e=e||0,r=r||0;var o=this.computedMatrix,s=o[0],l=o[4],u=o[8],c=o[1],h=o[5],f=o[9],d=o[2],p=o[6],g=o[10],v=e*s+r*c,m=e*l+r*h,y=e*u+r*f,b=-(p*y-g*m),x=-(g*v-d*y),_=-(d*m-p*v),w=Math.sqrt(Math.max(0,1-Math.pow(b,2)-Math.pow(x,2)-Math.pow(_,2))),A=i(b,x,_,w);A>1e-6?(b/=A,x/=A,_/=A,w/=A):(b=x=_=0,w=1);var k=this.computedRotation,M=k[0],T=k[1],E=k[2],L=k[3],S=M*w+L*b+T*_-E*x,C=T*w+L*x+E*b-M*_,P=E*w+L*_+M*x-T*b,z=L*w-M*b-T*x-E*_;if(a){b=d,x=p,_=g;var R=Math.sin(a)/n(b,x,_);b*=R,x*=R,_*=R,w=Math.cos(e),S=S*w+z*b+C*_-P*x,C=C*w+z*x+P*b-S*_,P=P*w+z*_+S*x-C*b,z=z*w-S*b-C*x-P*_}var O=i(S,C,P,z);O>1e-6?(S/=O,C/=O,P/=O,z/=O):(S=C=P=0,z=1),this.rotation.set(t,S,C,P,z)},d.lookAt=function(t,e,r,n){this.recalcMatrix(t),r=r||this.computedCenter,e=e||this.computedEye,n=n||this.computedUp;var i=this.computedMatrix;u(i,e,r,n);var o=this.computedRotation;f(o,i[0],i[1],i[2],i[4],i[5],i[6],i[8],i[9],i[10]),a(o,o),this.rotation.set(t,o[0],o[1],o[2],o[3]);for(var s=0,l=0;3>l;++l)s+=Math.pow(r[l]-e[l],2);this.radius.set(t,.5*Math.log(Math.max(s,1e-6))),this.center.set(t,r[0],r[1],r[2])},d.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},d.setMatrix=function(t,e){var r=this.computedRotation;f(r,e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]),a(r,r),this.rotation.set(t,r[0],r[1],r[2],r[3]);var n=this.computedMatrix;h(n,e);var i=n[15];if(Math.abs(i)>1e-6){var o=n[12]/i,s=n[13]/i,l=n[14]/i;this.recalcMatrix(t);var u=Math.exp(this.computedRadius[0]);this.center.set(t,o-n[2]*u,s-n[6]*u,l-n[10]*u),this.radius.idle(t)}else this.center.idle(t),this.radius.idle(t)},d.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},d.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-(1/0),e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},d.getDistanceLimits=function(t){var e=this.radius.bounds;return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},d.toJSON=function(){return this.recalcMatrix(this.lastT()),{center:this.computedCenter.slice(),rotation:this.computedRotation.slice(),distance:Math.log(this.computedRadius[0]),
+zoomMin:this.radius.bounds[0][0],zoomMax:this.radius.bounds[1][0]}},d.fromJSON=function(t){var e=this.lastT(),r=t.center;r&&this.center.set(e,r[0],r[1],r[2]);var n=t.rotation;n&&this.rotation.set(e,n[0],n[1],n[2],n[3]);var i=t.distance;i&&i>0&&this.radius.set(e,Math.log(i)),this.setDistanceLimits(t.zoomMin,t.zoomMax)}},{"./lib/quatFromFrame":35,"filtered-vector":19,"gl-mat4/fromQuat":91,"gl-mat4/invert":94,"gl-mat4/lookAt":95}],37:[function(t,e,r){"use strict";function n(t,e,r){return Math.sqrt(Math.pow(t,2)+Math.pow(e,2)+Math.pow(r,2))}function i(t){return Math.min(1,Math.max(-1,t))}function a(t){var e=Math.abs(t[0]),r=Math.abs(t[1]),n=Math.abs(t[2]),i=[0,0,0];e>Math.max(r,n)?i[2]=1:r>Math.max(e,n)?i[0]=1:i[1]=1;for(var a=0,o=0,s=0;3>s;++s)a+=t[s]*t[s],o+=i[s]*t[s];for(var s=0;3>s;++s)i[s]-=o/a*t[s];return f(i,i),i}function o(t,e,r,n,i,a,o,s){this.center=l(r),this.up=l(n),this.right=l(i),this.radius=l([a]),this.angle=l([o,s]),this.angle.bounds=[[-(1/0),-Math.PI/2],[1/0,Math.PI/2]],this.setDistanceLimits(t,e),this.computedCenter=this.center.curve(0),this.computedUp=this.up.curve(0),this.computedRight=this.right.curve(0),this.computedRadius=this.radius.curve(0),this.computedAngle=this.angle.curve(0),this.computedToward=[0,0,0],this.computedEye=[0,0,0],this.computedMatrix=new Array(16);for(var u=0;16>u;++u)this.computedMatrix[u]=.5;this.recalcMatrix(0)}function s(t){t=t||{};var e=t.center||[0,0,0],r=t.up||[0,1,0],i=t.right||a(r),s=t.radius||1,l=t.theta||0,u=t.phi||0;if(e=[].slice.call(e,0,3),r=[].slice.call(r,0,3),f(r,r),i=[].slice.call(i,0,3),f(i,i),"eye"in t){var c=t.eye,p=[c[0]-e[0],c[1]-e[1],c[2]-e[2]];h(i,p,r),n(i[0],i[1],i[2])<1e-6?i=a(r):f(i,i),s=n(p[0],p[1],p[2]);var g=d(r,p)/s,v=d(i,p)/s;u=Math.acos(g),l=Math.acos(v)}return s=Math.log(s),new o(t.zoomMin,t.zoomMax,e,r,i,s,l,u)}e.exports=s;var l=t("filtered-vector"),u=t("gl-mat4/invert"),c=t("gl-mat4/rotate"),h=t("gl-vec3/cross"),f=t("gl-vec3/normalize"),d=t("gl-vec3/dot"),p=o.prototype;p.setDistanceLimits=function(t,e){t=t>0?Math.log(t):-(1/0),e=e>0?Math.log(e):1/0,e=Math.max(e,t),this.radius.bounds[0][0]=t,this.radius.bounds[1][0]=e},p.getDistanceLimits=function(t){var e=this.radius.bounds[0];return t?(t[0]=Math.exp(e[0][0]),t[1]=Math.exp(e[1][0]),t):[Math.exp(e[0][0]),Math.exp(e[1][0])]},p.recalcMatrix=function(t){this.center.curve(t),this.up.curve(t),this.right.curve(t),this.radius.curve(t),this.angle.curve(t);for(var e=this.computedUp,r=this.computedRight,i=0,a=0,o=0;3>o;++o)a+=e[o]*r[o],i+=e[o]*e[o];for(var s=Math.sqrt(i),l=0,o=0;3>o;++o)r[o]-=e[o]*a/i,l+=r[o]*r[o],e[o]/=s;for(var u=Math.sqrt(l),o=0;3>o;++o)r[o]/=u;var c=this.computedToward;h(c,e,r),f(c,c);for(var d=Math.exp(this.computedRadius[0]),p=this.computedAngle[0],g=this.computedAngle[1],v=Math.cos(p),m=Math.sin(p),y=Math.cos(g),b=Math.sin(g),x=this.computedCenter,_=v*y,w=m*y,A=b,k=-v*b,M=-m*b,T=y,E=this.computedEye,L=this.computedMatrix,o=0;3>o;++o){var S=_*r[o]+w*c[o]+A*e[o];L[4*o+1]=k*r[o]+M*c[o]+T*e[o],L[4*o+2]=S,L[4*o+3]=0}var C=L[1],P=L[5],z=L[9],R=L[2],O=L[6],I=L[10],j=P*I-z*O,N=z*R-C*I,F=C*O-P*R,B=n(j,N,F);j/=B,N/=B,F/=B,L[0]=j,L[4]=N,L[8]=F;for(var o=0;3>o;++o)E[o]=x[o]+L[2+4*o]*d;for(var o=0;3>o;++o){for(var l=0,D=0;3>D;++D)l+=L[o+4*D]*E[D];L[12+o]=-l}L[15]=1},p.getMatrix=function(t,e){this.recalcMatrix(t);var r=this.computedMatrix;if(e){for(var n=0;16>n;++n)e[n]=r[n];return e}return r};var g=[0,0,0];p.rotate=function(t,e,r,n){if(this.angle.move(t,e,r),n){this.recalcMatrix(t);var i=this.computedMatrix;g[0]=i[2],g[1]=i[6],g[2]=i[10];for(var a=this.computedUp,o=this.computedRight,s=this.computedToward,l=0;3>l;++l)i[4*l]=a[l],i[4*l+1]=o[l],i[4*l+2]=s[l];c(i,i,n,g);for(var l=0;3>l;++l)a[l]=i[4*l],o[l]=i[4*l+1];this.up.set(t,a[0],a[1],a[2]),this.right.set(t,o[0],o[1],o[2])}},p.pan=function(t,e,r,i){e=e||0,r=r||0,i=i||0,this.recalcMatrix(t);var a=this.computedMatrix,o=(Math.exp(this.computedRadius[0]),a[1]),s=a[5],l=a[9],u=n(o,s,l);o/=u,s/=u,l/=u;var c=a[0],h=a[4],f=a[8],d=c*o+h*s+f*l;c-=o*d,h-=s*d,f-=l*d;var p=n(c,h,f);c/=p,h/=p,f/=p;var g=c*e+o*r,v=h*e+s*r,m=f*e+l*r;this.center.move(t,g,v,m);var y=Math.exp(this.computedRadius[0]);y=Math.max(1e-4,y+i),this.radius.set(t,Math.log(y))},p.translate=function(t,e,r,n){this.center.move(t,e||0,r||0,n||0)},p.setMatrix=function(t,e,r,a){var o=1;"number"==typeof r&&(o=0|r),(0>o||o>3)&&(o=1);var s=(o+2)%3;e||(this.recalcMatrix(t),e=this.computedMatrix);var l=e[o],c=e[o+4],h=e[o+8];if(a){var f=Math.abs(l),d=Math.abs(c),p=Math.abs(h),g=Math.max(f,d,p);f===g?(l=0>l?-1:1,c=h=0):p===g?(h=0>h?-1:1,l=c=0):(c=0>c?-1:1,l=h=0)}else{var v=n(l,c,h);l/=v,c/=v,h/=v}var m=e[s],y=e[s+4],b=e[s+8],x=m*l+y*c+b*h;m-=l*x,y-=c*x,b-=h*x;var _=n(m,y,b);m/=_,y/=_,b/=_;var w=c*b-h*y,A=h*m-l*b,k=l*y-c*m,M=n(w,A,k);w/=M,A/=M,k/=M,this.center.jump(t,H,G,Y),this.radius.idle(t),this.up.jump(t,l,c,h),this.right.jump(t,m,y,b);var T,E;if(2===o){var L=e[1],S=e[5],C=e[9],P=L*m+S*y+C*b,z=L*w+S*A+C*k;T=0>j?-Math.PI/2:Math.PI/2,E=Math.atan2(z,P)}else{var R=e[2],O=e[6],I=e[10],j=R*l+O*c+I*h,N=R*m+O*y+I*b,F=R*w+O*A+I*k;T=Math.asin(i(j)),E=Math.atan2(F,N)}this.angle.jump(t,E,T),this.recalcMatrix(t);var B=e[2],D=e[6],U=e[10],V=this.computedMatrix;u(V,e);var q=V[15],H=V[12]/q,G=V[13]/q,Y=V[14]/q,X=Math.exp(this.computedRadius[0]);this.center.jump(t,H-B*X,G-D*X,Y-U*X)},p.lastT=function(){return Math.max(this.center.lastT(),this.up.lastT(),this.right.lastT(),this.radius.lastT(),this.angle.lastT())},p.idle=function(t){this.center.idle(t),this.up.idle(t),this.right.idle(t),this.radius.idle(t),this.angle.idle(t)},p.flush=function(t){this.center.flush(t),this.up.flush(t),this.right.flush(t),this.radius.flush(t),this.angle.flush(t)},p.setDistance=function(t,e){e>0&&this.radius.set(t,Math.log(e))},p.lookAt=function(t,e,r,a){this.recalcMatrix(t),e=e||this.computedEye,r=r||this.computedCenter,a=a||this.computedUp;var o=a[0],s=a[1],l=a[2],u=n(o,s,l);if(!(1e-6>u)){o/=u,s/=u,l/=u;var c=e[0]-r[0],h=e[1]-r[1],f=e[2]-r[2],d=n(c,h,f);if(!(1e-6>d)){c/=d,h/=d,f/=d;var p=this.computedRight,g=p[0],v=p[1],m=p[2],y=o*g+s*v+l*m;g-=y*o,v-=y*s,m-=y*l;var b=n(g,v,m);if(!(.01>b&&(g=s*f-l*h,v=l*c-o*f,m=o*h-s*c,b=n(g,v,m),1e-6>b))){g/=b,v/=b,m/=b,this.up.set(t,o,s,l),this.right.set(t,g,v,m),this.center.set(t,r[0],r[1],r[2]),this.radius.set(t,Math.log(d));var x=s*m-l*v,_=l*g-o*m,w=o*v-s*g,A=n(x,_,w);x/=A,_/=A,w/=A;var k=o*c+s*h+l*f,M=g*c+v*h+m*f,T=x*c+_*h+w*f,E=Math.asin(i(k)),L=Math.atan2(T,M),S=this.angle._state,C=S[S.length-1],P=S[S.length-2];C%=2*Math.PI;var z=Math.abs(C+2*Math.PI-L),R=Math.abs(C-L),O=Math.abs(C-2*Math.PI-L);R>z&&(C+=2*Math.PI),R>O&&(C-=2*Math.PI),this.angle.jump(this.angle.lastT(),C,P),this.angle.set(t,L,E)}}}}},{"filtered-vector":19,"gl-mat4/invert":94,"gl-mat4/rotate":98,"gl-vec3/cross":22,"gl-vec3/dot":23,"gl-vec3/normalize":26}],38:[function(t,e,r){"use strict";function n(t,e){this._controllerNames=Object.keys(t),this._controllerList=this._controllerNames.map(function(e){return t[e]}),this._mode=e,this._active=t[e],this._active||(this._mode="turntable",this._active=t.turntable),this.modes=this._controllerNames,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}function i(t){t=t||{};var e=t.eye||[0,0,1],r=t.center||[0,0,0],i=t.up||[0,1,0],l=t.distanceLimits||[0,1/0],u=t.mode||"turntable",c=a(),h=o(),f=s();return c.setDistanceLimits(l[0],l[1]),c.lookAt(0,e,r,i),h.setDistanceLimits(l[0],l[1]),h.lookAt(0,e,r,i),f.setDistanceLimits(l[0],l[1]),f.lookAt(0,e,r,i),new n({turntable:c,orbit:h,matrix:f},u)}e.exports=i;var a=t("turntable-camera-controller"),o=t("orbit-camera-controller"),s=t("matrix-camera-controller"),l=n.prototype,u=[["flush",1],["idle",1],["lookAt",4],["rotate",4],["pan",4],["translate",4],["setMatrix",2],["setDistanceLimits",2],["setDistance",2]];u.forEach(function(t){for(var e=t[0],r=[],n=0;n<t[1];++n)r.push("a"+n);var i="var cc=this._controllerList;for(var i=0;i<cc.length;++i){cc[i]."+t[0]+"("+r.join()+")}";l[e]=Function.apply(null,r.concat(i))}),l.recalcMatrix=function(t){this._active.recalcMatrix(t)},l.getDistance=function(t){return this._active.getDistance(t)},l.getDistanceLimits=function(t){return this._active.getDistanceLimits(t)},l.lastT=function(){return this._active.lastT()},l.setMode=function(t){if(t!==this._mode){var e=this._controllerNames.indexOf(t);if(!(0>e)){var r=this._active,n=this._controllerList[e],i=Math.max(r.lastT(),n.lastT());r.recalcMatrix(i),n.setMatrix(i,r.computedMatrix),this._active=n,this._mode=t,this.computedMatrix=this._active.computedMatrix,this.computedEye=this._active.computedEye,this.computedUp=this._active.computedUp,this.computedCenter=this._active.computedCenter,this.computedRadius=this._active.computedRadius}}},l.getMode=function(){return this._mode}},{"matrix-camera-controller":27,"orbit-camera-controller":36,"turntable-camera-controller":37}],39:[function(t,e,r){function n(t,e){return a(i(t,e))}e.exports=n;var i=t("alpha-complex"),a=t("simplicial-complex-boundary")},{"alpha-complex":40,"simplicial-complex-boundary":43}],40:[function(t,e,r){"use strict";function n(t,e){return i(e).filter(function(r){for(var n=new Array(r.length),i=0;i<r.length;++i)n[i]=e[r[i]];return a(n)*t<1})}e.exports=n;var i=t("delaunay-triangulate"),a=t("circumradius")},{circumradius:41,"delaunay-triangulate":71}],41:[function(t,e,r){function n(t){for(var e=i(t),r=0,n=0;n<t.length;++n)for(var a=t[n],o=0;o<e.length;++o)r+=Math.pow(a[o]-e[o],2);return Math.sqrt(r/t.length)}e.exports=n;var i=t("circumcenter")},{circumcenter:42}],42:[function(t,e,r){"use strict";function n(t,e){for(var r=0,n=t.length,i=0;n>i;++i)r+=t[i]*e[i];return r}function i(t){var e=t.length;if(0===e)return[];var r=(t[0].length,o([t.length+1,t.length+1],1)),i=o([t.length+1],1);r[e][e]=0;for(var a=0;e>a;++a){for(var l=0;a>=l;++l)r[l][a]=r[a][l]=2*n(t[a],t[l]);i[a]=n(t[a],t[a])}for(var u=s(r,i),c=0,h=u[e+1],a=0;a<h.length;++a)c+=h[a];for(var f=new Array(e),a=0;e>a;++a){for(var h=u[a],d=0,l=0;l<h.length;++l)d+=h[l];f[a]=d/c}return f}function a(t){if(0===t.length)return[];for(var e=t[0].length,r=o([e]),n=i(t),a=0;a<t.length;++a)for(var s=0;e>s;++s)r[s]+=t[a][s]*n[a];return r}var o=t("dup"),s=t("robust-linear-solve");a.barycenetric=i,e.exports=a},{dup:72,"robust-linear-solve":211}],43:[function(t,e,r){"use strict";function n(t){return a(i(t))}e.exports=n;var i=t("boundary-cells"),a=t("reduce-simplicial-complex")},{"boundary-cells":44,"reduce-simplicial-complex":47}],44:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=0,n=0;e>n;++n)r+=t[n].length;for(var i=new Array(r),a=0,n=0;e>n;++n)for(var o=t[n],s=o.length,l=0;s>l;++l)for(var u=i[a++]=new Array(s-1),c=1;s>c;++c)u[c-1]=o[(l+c)%s];return i}e.exports=n},{}],45:[function(t,e,r){"use strict";function n(t){for(var e=1,r=1;r<t.length;++r)for(var n=0;r>n;++n)if(t[r]<t[n])e=-e;else if(t[n]===t[r])return 0;return e}e.exports=n},{}],46:[function(t,e,r){"use strict";function n(t,e){return i(t,e)||a(t)-a(e)}var i=t("compare-cell"),a=t("cell-orientation");e.exports=n},{"cell-orientation":45,"compare-cell":59}],47:[function(t,e,r){"use strict";function n(t){t.sort(a);for(var e=t.length,r=0,n=0;e>n;++n){var s=t[n],l=o(s);if(0!==l){if(r>0){var u=t[r-1];if(0===i(s,u)&&o(u)!==l){r-=1;continue}}t[r++]=s}}return t.length=r,t}var i=t("compare-cell"),a=t("compare-oriented-cell"),o=t("cell-orientation");e.exports=n},{"cell-orientation":45,"compare-cell":59,"compare-oriented-cell":46}],48:[function(t,e,r){"use strict";var n=function(){function t(t){return!Array.isArray(t)&&null!==t&&"object"==typeof t}function e(t,e,r){for(var n=(e-t)/Math.max(r-1,1),i=[],a=0;r>a;a++)i.push(t+a*n);return i}function r(){for(var t=[].slice.call(arguments),e=t.map(function(t){return t.length}),r=Math.min.apply(null,e),n=[],i=0;r>i;i++){n[i]=[];for(var a=0;a<t.length;++a)n[i][a]=t[a][i]}return n}function n(t,e,r){for(var n=Math.min.apply(null,[t.length,e.length,r.length]),i=[],a=0;n>a;a++)i.push([t[a],e[a],r[a]]);return i}function i(t){function e(t){for(var n=0;n<t.length;n++)Array.isArray(t[n])?e(t[n],r):r+=t[n]}var r=0;return e(t,r),r}function a(t){for(var e=[],r=0;r<t.length;++r){e[r]=[];for(var n=0;n<t[r].length;++n)e[r][n]=t[r][n]}return e}function o(t){for(var e=[],r=0;r<t.length;++r)e[r]=t[r];return e}function s(t,e){if(t.length!==e.length)return!1;for(var r=t.length;r--;)if(t[r]!==e[r])return!1;return!0}function l(t,e){var r,n;if("string"!=typeof t)return t;if(r=[],"#"===t[0]?(t=t.substr(1),3===t.length&&(t+=t),n=parseInt(t,16),r[0]=n>>16&255,r[1]=n>>8&255,r[2]=255&n):h.test(t)&&(n=t.match(f),r[0]=parseInt(n[1]),r[1]=parseInt(n[2]),r[2]=parseInt(n[3])),!e)for(var i=0;3>i;++i)r[i]=r[i]/255;return r}function u(t,e){var r,n;if("string"!=typeof t)return t;if(r=[],"#"===t[0]?(t=t.substr(1),3===t.length&&(t+=t),n=parseInt(t,16),r[0]=n>>16&255,r[1]=n>>8&255,r[2]=255&n):h.test(t)&&(n=t.match(f),r[0]=parseInt(n[1]),r[1]=parseInt(n[2]),r[2]=parseInt(n[3]),n[4]?r[3]=parseFloat(n[4]):r[3]=1),!e)for(var i=0;3>i;++i)r[i]=r[i]/255;return r}var c={},h=/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,.*)?\)$/,f=/^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,?\s*(.*)?\)$/;return c.isPlainObject=t,c.linspace=e,c.zip3=n,c.sum=i,c.zip=r,c.isEqual=s,c.copy2D=a,c.copy1D=o,c.str2RgbArray=l,c.str2RgbaArray=u,c};e.exports=n()},{}],49:[function(t,e,r){"use strict";"use restrict";function n(t){var e=32;return t&=-t,t&&e--,65535&t&&(e-=16),16711935&t&&(e-=8),252645135&t&&(e-=4),858993459&t&&(e-=2),1431655765&t&&(e-=1),e}var i=32;r.INT_BITS=i,r.INT_MAX=2147483647,r.INT_MIN=-1<<i-1,r.sign=function(t){return(t>0)-(0>t)},r.abs=function(t){var e=t>>i-1;return(t^e)-e},r.min=function(t,e){return e^(t^e)&-(e>t)},r.max=function(t,e){return t^(t^e)&-(e>t)},r.isPow2=function(t){return!(t&t-1||!t)},r.log2=function(t){var e,r;return e=(t>65535)<<4,t>>>=e,r=(t>255)<<3,t>>>=r,e|=r,r=(t>15)<<2,t>>>=r,e|=r,r=(t>3)<<1,t>>>=r,e|=r,e|t>>1},r.log10=function(t){return t>=1e9?9:t>=1e8?8:t>=1e7?7:t>=1e6?6:t>=1e5?5:t>=1e4?4:t>=1e3?3:t>=100?2:t>=10?1:0},r.popCount=function(t){return t-=t>>>1&1431655765,t=(858993459&t)+(t>>>2&858993459),16843009*(t+(t>>>4)&252645135)>>>24},r.countTrailingZeros=n,r.nextPow2=function(t){return t+=0===t,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t+1},r.prevPow2=function(t){return t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t-(t>>>1)},r.parity=function(t){return t^=t>>>16,t^=t>>>8,t^=t>>>4,t&=15,27030>>>t&1};var a=new Array(256);!function(t){for(var e=0;256>e;++e){var r=e,n=e,i=7;for(r>>>=1;r;r>>>=1)n<<=1,n|=1&r,--i;t[e]=n<<i&255}}(a),r.reverse=function(t){return a[255&t]<<24|a[t>>>8&255]<<16|a[t>>>16&255]<<8|a[t>>>24&255]},r.interleave2=function(t,e){return t&=65535,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e&=65535,e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},r.deinterleave2=function(t,e){return t=t>>>e&1431655765,t=858993459&(t|t>>>1),t=252645135&(t|t>>>2),t=16711935&(t|t>>>4),t=65535&(t|t>>>16),t<<16>>16},r.interleave3=function(t,e,r){return t&=1023,t=4278190335&(t|t<<16),t=251719695&(t|t<<8),t=3272356035&(t|t<<4),t=1227133513&(t|t<<2),e&=1023,e=4278190335&(e|e<<16),e=251719695&(e|e<<8),e=3272356035&(e|e<<4),e=1227133513&(e|e<<2),t|=e<<1,r&=1023,r=4278190335&(r|r<<16),r=251719695&(r|r<<8),r=3272356035&(r|r<<4),r=1227133513&(r|r<<2),t|r<<2},r.deinterleave3=function(t,e){return t=t>>>e&1227133513,t=3272356035&(t|t>>>2),t=251719695&(t|t>>>4),t=4278190335&(t|t>>>8),t=1023&(t|t>>>16),t<<22>>22},r.nextCombination=function(t){var e=t|t-1;return e+1|(~e&-~e)-1>>>n(t)+1}},{}],50:[function(t,e,r){(function(e){"use strict";function n(){try{var t=new Uint8Array(1);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(e){return!1}}function i(){return a.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(t){return this instanceof a?(a.TYPED_ARRAY_SUPPORT||(this.length=0,this.parent=void 0),"number"==typeof t?o(this,t):"string"==typeof t?s(this,t,arguments.length>1?arguments[1]:"utf8"):l(this,t)):arguments.length>1?new a(t,arguments[1]):new a(t)}function o(t,e){if(t=g(t,0>e?0:0|v(e)),!a.TYPED_ARRAY_SUPPORT)for(var r=0;e>r;r++)t[r]=0;return t}function s(t,e,r){("string"!=typeof r||""===r)&&(r="utf8");var n=0|y(e,r);return t=g(t,n),t.write(e,r),t}function l(t,e){if(a.isBuffer(e))return u(t,e);if($(e))return c(t,e);if(null==e)throw new TypeError("must start with number, buffer, array or string");if("undefined"!=typeof ArrayBuffer){if(e.buffer instanceof ArrayBuffer)return h(t,e);if(e instanceof ArrayBuffer)return f(t,e)}return e.length?d(t,e):p(t,e)}function u(t,e){var r=0|v(e.length);return t=g(t,r),e.copy(t,0,0,r),t}function c(t,e){var r=0|v(e.length);t=g(t,r);for(var n=0;r>n;n+=1)t[n]=255&e[n];return t}function h(t,e){var r=0|v(e.length);t=g(t,r);for(var n=0;r>n;n+=1)t[n]=255&e[n];return t}function f(t,e){return e.byteLength,a.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=a.prototype):t=h(t,new Uint8Array(e)),t}function d(t,e){var r=0|v(e.length);t=g(t,r);for(var n=0;r>n;n+=1)t[n]=255&e[n];return t}function p(t,e){var r,n=0;"Buffer"===e.type&&$(e.data)&&(r=e.data,n=0|v(r.length)),t=g(t,n);for(var i=0;n>i;i+=1)t[i]=255&r[i];return t}function g(t,e){a.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=a.prototype):t.length=e;var r=0!==e&&e<=a.poolSize>>>1;return r&&(t.parent=K),t}function v(t){if(t>=i())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i().toString(16)+" bytes");return 0|t}function m(t,e){if(!(this instanceof m))return new m(t,e);var r=new a(t,e);return delete r.parent,r}function y(t,e){"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"binary":case"raw":case"raws":return r;case"utf8":case"utf-8":return q(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(t).length;default:if(n)return q(t).length;e=(""+e).toLowerCase(),n=!0}}function b(t,e,r){var n=!1;if(e=0|e,r=void 0===r||r===1/0?this.length:0|r,t||(t="utf8"),0>e&&(e=0),r>this.length&&(r=this.length),e>=r)return"";for(;;)switch(t){case"hex":return P(this,e,r);case"utf8":case"utf-8":return E(this,e,r);case"ascii":return S(this,e,r);case"binary":return C(this,e,r);case"base64":return T(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return z(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function x(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n),n>i&&(n=i)):n=i;var a=e.length;if(a%2!==0)throw new Error("Invalid hex string");n>a/2&&(n=a/2);for(var o=0;n>o;o++){var s=parseInt(e.substr(2*o,2),16);if(isNaN(s))throw new Error("Invalid hex string");t[r+o]=s}return o}function _(t,e,r,n){return X(q(e,t.length-r),t,r,n)}function w(t,e,r,n){return X(H(e),t,r,n)}function A(t,e,r,n){return w(t,e,r,n)}function k(t,e,r,n){return X(Y(e),t,r,n)}function M(t,e,r,n){return X(G(e,t.length-r),t,r,n)}function T(t,e,r){return 0===e&&r===t.length?W.fromByteArray(t):W.fromByteArray(t.slice(e,r))}function E(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;r>i;){var a=t[i],o=null,s=a>239?4:a>223?3:a>191?2:1;if(r>=i+s){var l,u,c,h;switch(s){case 1:128>a&&(o=a);break;case 2:l=t[i+1],128===(192&l)&&(h=(31&a)<<6|63&l,h>127&&(o=h));break;case 3:l=t[i+1],u=t[i+2],128===(192&l)&&128===(192&u)&&(h=(15&a)<<12|(63&l)<<6|63&u,h>2047&&(55296>h||h>57343)&&(o=h));break;case 4:l=t[i+1],u=t[i+2],c=t[i+3],128===(192&l)&&128===(192&u)&&128===(192&c)&&(h=(15&a)<<18|(63&l)<<12|(63&u)<<6|63&c,h>65535&&1114112>h&&(o=h))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return L(n)}function L(t){var e=t.length;if(Q>=e)return String.fromCharCode.apply(String,t);for(var r="",n=0;e>n;)r+=String.fromCharCode.apply(String,t.slice(n,n+=Q));return r}function S(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;r>i;i++)n+=String.fromCharCode(127&t[i]);return n}function C(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;r>i;i++)n+=String.fromCharCode(t[i]);return n}function P(t,e,r){var n=t.length;(!e||0>e)&&(e=0),(!r||0>r||r>n)&&(r=n);for(var i="",a=e;r>a;a++)i+=V(t[a]);return i}function z(t,e,r){for(var n=t.slice(e,r),i="",a=0;a<n.length;a+=2)i+=String.fromCharCode(n[a]+256*n[a+1]);return i}function R(t,e,r){if(t%1!==0||0>t)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,r,n,i,o){if(!a.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");if(e>i||o>e)throw new RangeError("value is out of bounds");if(r+n>t.length)throw new RangeError("index out of range")}function I(t,e,r,n){0>e&&(e=65535+e+1);for(var i=0,a=Math.min(t.length-r,2);a>i;i++)t[r+i]=(e&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function j(t,e,r,n){0>e&&(e=4294967295+e+1);for(var i=0,a=Math.min(t.length-r,4);a>i;i++)t[r+i]=e>>>8*(n?i:3-i)&255}function N(t,e,r,n,i,a){if(e>i||a>e)throw new RangeError("value is out of bounds");if(r+n>t.length)throw new RangeError("index out of range");if(0>r)throw new RangeError("index out of range")}function F(t,e,r,n,i){return i||N(t,e,r,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(t,e,r,n,23,4),r+4}function B(t,e,r,n,i){return i||N(t,e,r,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(t,e,r,n,52,8),r+8}function D(t){if(t=U(t).replace(J,""),t.length<2)return"";for(;t.length%4!==0;)t+="=";return t}function U(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function V(t){return 16>t?"0"+t.toString(16):t.toString(16)}function q(t,e){e=e||1/0;for(var r,n=t.length,i=null,a=[],o=0;n>o;o++){if(r=t.charCodeAt(o),r>55295&&57344>r){if(!i){if(r>56319){(e-=3)>-1&&a.push(239,191,189);continue}if(o+1===n){(e-=3)>-1&&a.push(239,191,189);continue}i=r;continue}if(56320>r){(e-=3)>-1&&a.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&a.push(239,191,189);if(i=null,128>r){if((e-=1)<0)break;a.push(r)}else if(2048>r){if((e-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(65536>r){if((e-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(1114112>r))throw new Error("Invalid code point");if((e-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function H(t){for(var e=[],r=0;r<t.length;r++)e.push(255&t.charCodeAt(r));return e}function G(t,e){for(var r,n,i,a=[],o=0;o<t.length&&!((e-=2)<0);o++)r=t.charCodeAt(o),n=r>>8,i=r%256,a.push(i),a.push(n);return a}function Y(t){return W.toByteArray(D(t))}function X(t,e,r,n){for(var i=0;n>i&&!(i+r>=e.length||i>=t.length);i++)e[i+r]=t[i];return i}var W=t("base64-js"),Z=t("ieee754"),$=t("isarray");r.Buffer=a,r.SlowBuffer=m,r.INSPECT_MAX_BYTES=50,a.poolSize=8192;var K={};a.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:n(),a.TYPED_ARRAY_SUPPORT?(a.prototype.__proto__=Uint8Array.prototype,a.__proto__=Uint8Array):(a.prototype.length=void 0,a.prototype.parent=void 0),a.isBuffer=function(t){return!(null==t||!t._isBuffer)},a.compare=function(t,e){if(!a.isBuffer(t)||!a.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,n=e.length,i=0,o=Math.min(r,n);o>i&&t[i]===e[i];)++i;return i!==o&&(r=t[i],n=e[i]),n>r?-1:r>n?1:0},a.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(t,e){if(!$(t))throw new TypeError("list argument must be an Array of Buffers.");if(0===t.length)return new a(0);var r;if(void 0===e)for(e=0,r=0;r<t.length;r++)e+=t[r].length;var n=new a(e),i=0;for(r=0;r<t.length;r++){var o=t[r];o.copy(n,i),i+=o.length}return n},a.byteLength=y,a.prototype._isBuffer=!0,a.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?E(this,0,t):b.apply(this,arguments)},a.prototype.equals=function(t){if(!a.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?!0:0===a.compare(this,t)},a.prototype.inspect=function(){var t="",e=r.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,e).match(/.{2}/g).join(" "),this.length>e&&(t+=" ... ")),"<Buffer "+t+">"},a.prototype.compare=function(t){if(!a.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t?0:a.compare(this,t)},a.prototype.indexOf=function(t,e){function r(t,e,r){for(var n=-1,i=0;r+i<t.length;i++)if(t[r+i]===e[-1===n?0:i-n]){if(-1===n&&(n=i),i-n+1===e.length)return r+n}else n=-1;return-1}if(e>2147483647?e=2147483647:-2147483648>e&&(e=-2147483648),e>>=0,0===this.length)return-1;if(e>=this.length)return-1;if(0>e&&(e=Math.max(this.length+e,0)),"string"==typeof t)return 0===t.length?-1:String.prototype.indexOf.call(this,t,e);if(a.isBuffer(t))return r(this,t,e);if("number"==typeof t)return a.TYPED_ARRAY_SUPPORT&&"function"===Uint8Array.prototype.indexOf?Uint8Array.prototype.indexOf.call(this,t,e):r(this,[t],e);throw new TypeError("val must be string, number or Buffer")},a.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else if(isFinite(e))e=0|e,isFinite(r)?(r=0|r,void 0===n&&(n="utf8")):(n=r,r=void 0);else{var i=n;n=e,e=0|r,r=i}var a=this.length-e;if((void 0===r||r>a)&&(r=a),t.length>0&&(0>r||0>e)||e>this.length)throw new RangeError("attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return x(this,t,e,r);case"utf8":case"utf-8":return _(this,t,e,r);case"ascii":return w(this,t,e,r);case"binary":return A(this,t,e,r);case"base64":return k(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var Q=4096;a.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,0>t?(t+=r,0>t&&(t=0)):t>r&&(t=r),0>e?(e+=r,0>e&&(e=0)):e>r&&(e=r),t>e&&(e=t);var n;if(a.TYPED_ARRAY_SUPPORT)n=this.subarray(t,e),n.__proto__=a.prototype;else{var i=e-t;n=new a(i,void 0);for(var o=0;i>o;o++)n[o]=this[o+t]}return n.length&&(n.parent=this.parent||this),n},a.prototype.readUIntLE=function(t,e,r){t=0|t,e=0|e,r||R(t,e,this.length);for(var n=this[t],i=1,a=0;++a<e&&(i*=256);)n+=this[t+a]*i;return n},a.prototype.readUIntBE=function(t,e,r){t=0|t,e=0|e,r||R(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},a.prototype.readUInt8=function(t,e){return e||R(t,1,this.length),this[t]},a.prototype.readUInt16LE=function(t,e){return e||R(t,2,this.length),this[t]|this[t+1]<<8},a.prototype.readUInt16BE=function(t,e){return e||R(t,2,this.length),this[t]<<8|this[t+1]},a.prototype.readUInt32LE=function(t,e){return e||R(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},a.prototype.readUInt32BE=function(t,e){return e||R(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},a.prototype.readIntLE=function(t,e,r){t=0|t,e=0|e,r||R(t,e,this.length);for(var n=this[t],i=1,a=0;++a<e&&(i*=256);)n+=this[t+a]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*e)),n},a.prototype.readIntBE=function(t,e,r){t=0|t,e=0|e,r||R(t,e,this.length);for(var n=e,i=1,a=this[t+--n];n>0&&(i*=256);)a+=this[t+--n]*i;return i*=128,a>=i&&(a-=Math.pow(2,8*e)),a},a.prototype.readInt8=function(t,e){return e||R(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},a.prototype.readInt16LE=function(t,e){e||R(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt16BE=function(t,e){e||R(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt32LE=function(t,e){return e||R(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},a.prototype.readInt32BE=function(t,e){return e||R(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},a.prototype.readFloatLE=function(t,e){return e||R(t,4,this.length),Z.read(this,t,!0,23,4)},a.prototype.readFloatBE=function(t,e){return e||R(t,4,this.length),Z.read(this,t,!1,23,4)},a.prototype.readDoubleLE=function(t,e){return e||R(t,8,this.length),Z.read(this,t,!0,52,8)},a.prototype.readDoubleBE=function(t,e){return e||R(t,8,this.length),Z.read(this,t,!1,52,8)},a.prototype.writeUIntLE=function(t,e,r,n){t=+t,e=0|e,r=0|r,n||O(this,t,e,r,Math.pow(2,8*r),0);var i=1,a=0;for(this[e]=255&t;++a<r&&(i*=256);)this[e+a]=t/i&255;return e+r},a.prototype.writeUIntBE=function(t,e,r,n){t=+t,e=0|e,r=0|r,n||O(this,t,e,r,Math.pow(2,8*r),0);var i=r-1,a=1;for(this[e+i]=255&t;--i>=0&&(a*=256);)this[e+i]=t/a&255;return e+r},a.prototype.writeUInt8=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,1,255,0),a.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},a.prototype.writeUInt16LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):I(this,t,e,!0),e+2},a.prototype.writeUInt16BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,65535,0),a.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):I(this,t,e,!1),e+2},a.prototype.writeUInt32LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):j(this,t,e,!0),e+4},a.prototype.writeUInt32BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,4294967295,0),a.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):j(this,t,e,!1),e+4},a.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e=0|e,!n){var i=Math.pow(2,8*r-1);O(this,t,e,r,i-1,-i)}var a=0,o=1,s=0>t?1:0;for(this[e]=255&t;++a<r&&(o*=256);)this[e+a]=(t/o>>0)-s&255;return e+r},a.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e=0|e,!n){var i=Math.pow(2,8*r-1);O(this,t,e,r,i-1,-i)}var a=r-1,o=1,s=0>t?1:0;for(this[e+a]=255&t;--a>=0&&(o*=256);)this[e+a]=(t/o>>0)-s&255;return e+r},a.prototype.writeInt8=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,1,127,-128),a.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),0>t&&(t=255+t+1),this[e]=255&t,e+1},a.prototype.writeInt16LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):I(this,t,e,!0),e+2},a.prototype.writeInt16BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,2,32767,-32768),a.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):I(this,t,e,!1),e+2},a.prototype.writeInt32LE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,2147483647,-2147483648),a.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):j(this,t,e,!0),e+4},a.prototype.writeInt32BE=function(t,e,r){return t=+t,e=0|e,r||O(this,t,e,4,2147483647,-2147483648),0>t&&(t=4294967295+t+1),a.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):j(this,t,e,!1),e+4},a.prototype.writeFloatLE=function(t,e,r){return F(this,t,e,!0,r)},a.prototype.writeFloatBE=function(t,e,r){return F(this,t,e,!1,r)},a.prototype.writeDoubleLE=function(t,e,r){return B(this,t,e,!0,r)},a.prototype.writeDoubleBE=function(t,e,r){return B(this,t,e,!1,r)},a.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&r>n&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(0>e)throw new RangeError("targetStart out of bounds");if(0>r||r>=this.length)throw new RangeError("sourceStart out of bounds");if(0>n)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);var i,o=n-r;if(this===t&&e>r&&n>e)for(i=o-1;i>=0;i--)t[i+e]=this[i+r];else if(1e3>o||!a.TYPED_ARRAY_SUPPORT)for(i=0;o>i;i++)t[i+e]=this[i+r];else Uint8Array.prototype.set.call(t,this.subarray(r,r+o),e);return o},a.prototype.fill=function(t,e,r){if(t||(t=0),e||(e=0),r||(r=this.length),e>r)throw new RangeError("end < start");if(r!==e&&0!==this.length){if(0>e||e>=this.length)throw new RangeError("start out of bounds");
+if(0>r||r>this.length)throw new RangeError("end out of bounds");var n;if("number"==typeof t)for(n=e;r>n;n++)this[n]=t;else{var i=q(t.toString()),a=i.length;for(n=e;r>n;n++)this[n]=i[n%a]}return this}};var J=/[^+\/0-9A-Za-z-_]/g}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"base64-js":51,ieee754:52,isarray:53}],51:[function(t,e,r){!function(t){"use strict";function e(t){var e=t.charCodeAt(0);return e===o||e===h?62:e===s||e===f?63:l>e?-1:l+10>e?e-l+26+26:c+26>e?e-c:u+26>e?e-u+26:void 0}function r(t){function r(t){u[h++]=t}var n,i,o,s,l,u;if(t.length%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var c=t.length;l="="===t.charAt(c-2)?2:"="===t.charAt(c-1)?1:0,u=new a(3*t.length/4-l),o=l>0?t.length-4:t.length;var h=0;for(n=0,i=0;o>n;n+=4,i+=3)s=e(t.charAt(n))<<18|e(t.charAt(n+1))<<12|e(t.charAt(n+2))<<6|e(t.charAt(n+3)),r((16711680&s)>>16),r((65280&s)>>8),r(255&s);return 2===l?(s=e(t.charAt(n))<<2|e(t.charAt(n+1))>>4,r(255&s)):1===l&&(s=e(t.charAt(n))<<10|e(t.charAt(n+1))<<4|e(t.charAt(n+2))>>2,r(s>>8&255),r(255&s)),u}function n(t){function e(t){return i.charAt(t)}function r(t){return e(t>>18&63)+e(t>>12&63)+e(t>>6&63)+e(63&t)}var n,a,o,s=t.length%3,l="";for(n=0,o=t.length-s;o>n;n+=3)a=(t[n]<<16)+(t[n+1]<<8)+t[n+2],l+=r(a);switch(s){case 1:a=t[t.length-1],l+=e(a>>2),l+=e(a<<4&63),l+="==";break;case 2:a=(t[t.length-2]<<8)+t[t.length-1],l+=e(a>>10),l+=e(a>>4&63),l+=e(a<<2&63),l+="="}return l}var i="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a="undefined"!=typeof Uint8Array?Uint8Array:Array,o="+".charCodeAt(0),s="/".charCodeAt(0),l="0".charCodeAt(0),u="a".charCodeAt(0),c="A".charCodeAt(0),h="-".charCodeAt(0),f="_".charCodeAt(0);t.toByteArray=r,t.fromByteArray=n}("undefined"==typeof r?this.base64js={}:r)},{}],52:[function(t,e,r){r.read=function(t,e,r,n,i){var a,o,s=8*i-n-1,l=(1<<s)-1,u=l>>1,c=-7,h=r?i-1:0,f=r?-1:1,d=t[e+h];for(h+=f,a=d&(1<<-c)-1,d>>=-c,c+=s;c>0;a=256*a+t[e+h],h+=f,c-=8);for(o=a&(1<<-c)-1,a>>=-c,c+=n;c>0;o=256*o+t[e+h],h+=f,c-=8);if(0===a)a=1-u;else{if(a===l)return o?NaN:(d?-1:1)*(1/0);o+=Math.pow(2,n),a-=u}return(d?-1:1)*o*Math.pow(2,a-n)},r.write=function(t,e,r,n,i,a){var o,s,l,u=8*a-i-1,c=(1<<u)-1,h=c>>1,f=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:a-1,p=n?1:-1,g=0>e||0===e&&0>1/e?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),e+=o+h>=1?f/l:f*Math.pow(2,1-h),e*l>=2&&(o++,l/=2),o+h>=c?(s=0,o=c):o+h>=1?(s=(e*l-1)*Math.pow(2,i),o+=h):(s=e*Math.pow(2,h-1)*Math.pow(2,i),o=0));i>=8;t[r+d]=255&s,d+=p,s/=256,i-=8);for(o=o<<i|s,u+=i;u>0;t[r+d]=255&o,d+=p,o/=256,u-=8);t[r+d-p]|=128*g}},{}],53:[function(t,e,r){var n={}.toString;e.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},{}],54:[function(t,e,r){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function a(t){return"number"==typeof t}function o(t){return"object"==typeof t&&null!==t}function s(t){return void 0===t}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(t){if(!a(t)||0>t||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},n.prototype.emit=function(t){var e,r,n,a,l,u;if(this._events||(this._events={}),"error"===t&&(!this._events.error||o(this._events.error)&&!this._events.error.length)){if(e=arguments[1],e instanceof Error)throw e;throw TypeError('Uncaught, unspecified "error" event.')}if(r=this._events[t],s(r))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:a=Array.prototype.slice.call(arguments,1),r.apply(this,a)}else if(o(r))for(a=Array.prototype.slice.call(arguments,1),u=r.slice(),n=u.length,l=0;n>l;l++)u[l].apply(this,a);return!0},n.prototype.addListener=function(t,e){var r;if(!i(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?o(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,o(this._events[t])&&!this._events[t].warned&&(r=s(this._maxListeners)?n.defaultMaxListeners:this._maxListeners,r&&r>0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function r(){this.removeListener(t,r),n||(n=!0,e.apply(this,arguments))}if(!i(e))throw TypeError("listener must be a function");var n=!1;return r.listener=e,this.on(t,r),this},n.prototype.removeListener=function(t,e){var r,n,a,s;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(r=this._events[t],a=r.length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(r)){for(s=a;s-- >0;)if(r[s]===e||r[s].listener&&r[s].listener===e){n=s;break}if(0>n)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(r=this._events[t],i(r))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},{}],55:[function(t,e,r){function n(){c=!1,s.length?u=s.concat(u):h=-1,u.length&&i()}function i(){if(!c){var t=setTimeout(n);c=!0;for(var e=u.length;e;){for(s=u,u=[];++h<e;)s&&s[h].run();h=-1,e=u.length}s=null,c=!1,clearTimeout(t)}}function a(t,e){this.fun=t,this.array=e}function o(){}var s,l=e.exports={},u=[],c=!1,h=-1;l.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];u.push(new a(t,e)),1!==u.length||c||setTimeout(i,0)},a.prototype.run=function(){this.fun.apply(null,this.array)},l.title="browser",l.browser=!0,l.env={},l.argv=[],l.version="",l.versions={},l.on=o,l.addListener=o,l.once=o,l.off=o,l.removeListener=o,l.removeAllListeners=o,l.emit=o,l.binding=function(t){throw new Error("process.binding is not supported")},l.cwd=function(){return"/"},l.chdir=function(t){throw new Error("process.chdir is not supported")},l.umask=function(){return 0}},{}],56:[function(t,e,r){e.exports={jet:[{index:0,rgb:[0,0,131]},{index:.125,rgb:[0,60,170]},{index:.375,rgb:[5,255,255]},{index:.625,rgb:[255,255,0]},{index:.875,rgb:[250,0,0]},{index:1,rgb:[128,0,0]}],hsv:[{index:0,rgb:[255,0,0]},{index:.169,rgb:[253,255,2]},{index:.173,rgb:[247,255,2]},{index:.337,rgb:[0,252,4]},{index:.341,rgb:[0,252,10]},{index:.506,rgb:[1,249,255]},{index:.671,rgb:[2,0,253]},{index:.675,rgb:[8,0,253]},{index:.839,rgb:[255,0,251]},{index:.843,rgb:[255,0,245]},{index:1,rgb:[255,0,6]}],hot:[{index:0,rgb:[0,0,0]},{index:.3,rgb:[230,0,0]},{index:.6,rgb:[255,210,0]},{index:1,rgb:[255,255,255]}],cool:[{index:0,rgb:[0,255,255]},{index:1,rgb:[255,0,255]}],spring:[{index:0,rgb:[255,0,255]},{index:1,rgb:[255,255,0]}],summer:[{index:0,rgb:[0,128,102]},{index:1,rgb:[255,255,102]}],autumn:[{index:0,rgb:[255,0,0]},{index:1,rgb:[255,255,0]}],winter:[{index:0,rgb:[0,0,255]},{index:1,rgb:[0,255,128]}],bone:[{index:0,rgb:[0,0,0]},{index:.376,rgb:[84,84,116]},{index:.753,rgb:[169,200,200]},{index:1,rgb:[255,255,255]}],copper:[{index:0,rgb:[0,0,0]},{index:.804,rgb:[255,160,102]},{index:1,rgb:[255,199,127]}],greys:[{index:0,rgb:[0,0,0]},{index:1,rgb:[255,255,255]}],yignbu:[{index:0,rgb:[8,29,88]},{index:.125,rgb:[37,52,148]},{index:.25,rgb:[34,94,168]},{index:.375,rgb:[29,145,192]},{index:.5,rgb:[65,182,196]},{index:.625,rgb:[127,205,187]},{index:.75,rgb:[199,233,180]},{index:.875,rgb:[237,248,217]},{index:1,rgb:[255,255,217]}],greens:[{index:0,rgb:[0,68,27]},{index:.125,rgb:[0,109,44]},{index:.25,rgb:[35,139,69]},{index:.375,rgb:[65,171,93]},{index:.5,rgb:[116,196,118]},{index:.625,rgb:[161,217,155]},{index:.75,rgb:[199,233,192]},{index:.875,rgb:[229,245,224]},{index:1,rgb:[247,252,245]}],yiorrd:[{index:0,rgb:[128,0,38]},{index:.125,rgb:[189,0,38]},{index:.25,rgb:[227,26,28]},{index:.375,rgb:[252,78,42]},{index:.5,rgb:[253,141,60]},{index:.625,rgb:[254,178,76]},{index:.75,rgb:[254,217,118]},{index:.875,rgb:[255,237,160]},{index:1,rgb:[255,255,204]}],bluered:[{index:0,rgb:[0,0,255]},{index:1,rgb:[255,0,0]}],rdbu:[{index:0,rgb:[5,10,172]},{index:.35,rgb:[106,137,247]},{index:.5,rgb:[190,190,190]},{index:.6,rgb:[220,170,132]},{index:.7,rgb:[230,145,90]},{index:1,rgb:[178,10,28]}],picnic:[{index:0,rgb:[0,0,255]},{index:.1,rgb:[51,153,255]},{index:.2,rgb:[102,204,255]},{index:.3,rgb:[153,204,255]},{index:.4,rgb:[204,204,255]},{index:.5,rgb:[255,255,255]},{index:.6,rgb:[255,204,255]},{index:.7,rgb:[255,153,255]},{index:.8,rgb:[255,102,204]},{index:.9,rgb:[255,102,102]},{index:1,rgb:[255,0,0]}],rainbow:[{index:0,rgb:[150,0,90]},{index:.125,rgb:[0,0,200]},{index:.25,rgb:[0,25,255]},{index:.375,rgb:[0,152,255]},{index:.5,rgb:[44,255,150]},{index:.625,rgb:[151,255,0]},{index:.75,rgb:[255,234,0]},{index:.875,rgb:[255,111,0]},{index:1,rgb:[255,0,0]}],portland:[{index:0,rgb:[12,51,131]},{index:.25,rgb:[10,136,186]},{index:.5,rgb:[242,211,56]},{index:.75,rgb:[242,143,56]},{index:1,rgb:[217,30,30]}],blackbody:[{index:0,rgb:[0,0,0]},{index:.2,rgb:[230,0,0]},{index:.4,rgb:[230,210,0]},{index:.7,rgb:[255,255,255]},{index:1,rgb:[160,200,255]}],earth:[{index:0,rgb:[0,0,130]},{index:.1,rgb:[0,180,180]},{index:.2,rgb:[40,210,40]},{index:.4,rgb:[230,230,50]},{index:.6,rgb:[120,70,20]},{index:1,rgb:[255,255,255]}],electric:[{index:0,rgb:[0,0,0]},{index:.15,rgb:[30,0,100]},{index:.4,rgb:[120,0,100]},{index:.6,rgb:[160,90,0]},{index:.8,rgb:[230,200,0]},{index:1,rgb:[255,250,220]}],alpha:[{index:0,rgb:[255,255,255,0]},{index:0,rgb:[255,255,255,1]}]}},{}],57:[function(t,e,r){"use strict";function n(t){for(var e,r="#",n=0;3>n;++n)e=t[n],e=e.toString(16),r+=("00"+e).substr(e.length);return r}function i(t){return"rgba("+t.join(",")+")"}var a=t("arraytools"),o=t("clone"),s=t("./colorScales");e.exports=function(t){var e,r,l,u,c,h,f,d,p,g,v,m,y,b=[],x=[],_=[],w=[];if(a.isPlainObject(t)||(t={}),p=t.nshades||72,d=t.format||"hex",f=t.colormap,f||(f="jet"),"string"==typeof f){if(f=f.toLowerCase(),!s[f])throw Error(f+" not a supported colorscale");h=o(s[f])}else{if(!Array.isArray(f))throw Error("unsupported colormap option",f);h=o(f)}if(h.length>p)throw new Error(f+" map requires nshades to be at least size "+h.length);for(v=Array.isArray(t.alpha)?2!==t.alpha.length?[1,1]:o(t.alpha):"number"==typeof t.alpha?[t.alpha,t.alpha]:[1,1],e=h.map(function(t){return Math.round(t.index*p)}),v[0]<0&&(v[0]=0),v[1]<0&&(v[0]=0),v[0]>1&&(v[0]=1),v[1]>1&&(v[0]=1),y=0;y<e.length;++y)m=h[y].index,r=h[y].rgb,4===r.length&&r[3]>=0&&r[3]<=1||(r[3]=v[0]+(v[1]-v[0])*m);for(y=0;y<e.length-1;++y)c=e[y+1]-e[y],l=h[y].rgb,u=h[y+1].rgb,b=b.concat(a.linspace(l[0],u[0],c)),x=x.concat(a.linspace(l[1],u[1],c)),_=_.concat(a.linspace(l[2],u[2],c)),w=w.concat(a.linspace(l[3],u[3],c));return b=b.map(Math.round),x=x.map(Math.round),_=_.map(Math.round),g=a.zip(b,x,_,w),"hex"===d&&(g=g.map(n)),"rgbaString"===d&&(g=g.map(i)),g}},{"./colorScales":56,arraytools:48,clone:58}],58:[function(t,e,r){(function(t){var r=function(){"use strict";function e(r,n,i,a){function s(r,i){if(null===r)return null;if(0==i)return r;var l,f;if("object"!=typeof r)return r;if(e.__isArray(r))l=[];else if(e.__isRegExp(r))l=new RegExp(r.source,o(r)),r.lastIndex&&(l.lastIndex=r.lastIndex);else if(e.__isDate(r))l=new Date(r.getTime());else{if(h&&t.isBuffer(r))return l=new t(r.length),r.copy(l),l;"undefined"==typeof a?(f=Object.getPrototypeOf(r),l=Object.create(f)):(l=Object.create(a),f=a)}if(n){var d=u.indexOf(r);if(-1!=d)return c[d];u.push(r),c.push(l)}for(var p in r){var g;f&&(g=Object.getOwnPropertyDescriptor(f,p)),g&&null==g.set||(l[p]=s(r[p],i-1))}return l}var l;"object"==typeof n&&(i=n.depth,a=n.prototype,l=n.filter,n=n.circular);var u=[],c=[],h="undefined"!=typeof t;return"undefined"==typeof n&&(n=!0),"undefined"==typeof i&&(i=1/0),s(r,i)}function r(t){return Object.prototype.toString.call(t)}function n(t){return"object"==typeof t&&"[object Date]"===r(t)}function i(t){return"object"==typeof t&&"[object Array]"===r(t)}function a(t){return"object"==typeof t&&"[object RegExp]"===r(t)}function o(t){var e="";return t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),e}return e.clonePrototype=function(t){if(null===t)return null;var e=function(){};return e.prototype=t,new e},e.__objToStr=r,e.__isDate=n,e.__isArray=i,e.__isRegExp=a,e.__getRegExpFlags=o,e}();"object"==typeof e&&e.exports&&(e.exports=r)}).call(this,t("buffer").Buffer)},{buffer:50}],59:[function(t,e,r){function n(t,e){return t-e}function i(t,e){var r=t.length,i=t.length-e.length;if(i)return i;switch(r){case 0:return 0;case 1:return t[0]-e[0];case 2:return t[0]+t[1]-e[0]-e[1]||a(t[0],t[1])-a(e[0],e[1]);case 3:var o=t[0]+t[1],s=e[0]+e[1];if(i=o+t[2]-(s+e[2]))return i;var l=a(t[0],t[1]),u=a(e[0],e[1]);return a(l,t[2])-a(u,e[2])||a(l+t[2],o)-a(u+e[2],s);case 4:var c=t[0],h=t[1],f=t[2],d=t[3],p=e[0],g=e[1],v=e[2],m=e[3];return c+h+f+d-(p+g+v+m)||a(c,h,f,d)-a(p,g,v,m,p)||a(c+h,c+f,c+d,h+f,h+d,f+d)-a(p+g,p+v,p+m,g+v,g+m,v+m)||a(c+h+f,c+h+d,c+f+d,h+f+d)-a(p+g+v,p+g+m,p+v+m,g+v+m);default:for(var y=t.slice().sort(n),b=e.slice().sort(n),x=0;r>x;++x)if(i=y[x]-b[x])return i;return 0}}e.exports=i;var a=Math.min},{}],60:[function(t,e,r){"use strict";function n(t){var e=t.length;if(0===e)return[];if(1===e)return[[0]];var r=t[0].length;return 0===r?[]:1===r?i(t):2===r?a(t):o(t,r)}var i=t("./lib/ch1d"),a=t("./lib/ch2d"),o=t("./lib/chnd");e.exports=n},{"./lib/ch1d":61,"./lib/ch2d":62,"./lib/chnd":63}],61:[function(t,e,r){"use strict";function n(t){for(var e=0,r=0,n=1;n<t.length;++n)t[n][0]<t[e][0]&&(e=n),t[n][0]>t[r][0]&&(r=n);return r>e?[[e],[r]]:e>r?[[r],[e]]:[[e]]}e.exports=n},{}],62:[function(t,e,r){"use strict";function n(t){var e=i(t),r=e.length;if(2>=r)return[];for(var n=new Array(r),a=e[r-1],o=0;r>o;++o){var s=e[o];n[o]=[a,s],a=s}return n}e.exports=n;var i=t("monotone-convex-hull-2d")},{"monotone-convex-hull-2d":65}],63:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),i=0;i<e.length;++i)n[i]=t[e[i]];for(var a=e.length,i=0;r>i;++i)e.indexOf(i)<0&&(n[a++]=t[i]);return n}function i(t,e){for(var r=t.length,n=e.length,i=0;r>i;++i)for(var a=t[i],o=0;o<a.length;++o){var s=a[o];if(n>s)a[o]=e[s];else{s-=n;for(var l=0;n>l;++l)s>=e[l]&&(s+=1);a[o]=s}}return t}function a(t,e){try{return o(t,!0)}catch(r){var a=s(t);if(a.length<=e)return[];var l=n(t,a),u=o(l,!0);return i(u,a)}}e.exports=a;var o=t("incremental-convex-hull"),s=t("affine-hull")},{"affine-hull":64,"incremental-convex-hull":191}],64:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(e+1),n=0;n<t.length;++n)r[n]=t[n];for(var n=0;n<=t.length;++n){for(var i=t.length;e>=i;++i){for(var o=new Array(e),s=0;e>s;++s)o[s]=Math.pow(i+1-n,s);r[i]=o}var l=a.apply(void 0,r);if(l)return!0}return!1}function i(t){var e=t.length;if(0===e)return[];if(1===e)return[0];for(var r=t[0].length,i=[t[0]],a=[0],o=1;e>o;++o)if(i.push(t[o]),n(i,r)){if(a.push(o),a.length===r+1)return a}else i.pop();return a}e.exports=i;var a=t("robust-orientation")},{"robust-orientation":214}],65:[function(t,e,r){"use strict";function n(t){var e=t.length;if(3>e){for(var r=new Array(e),n=0;e>n;++n)r[n]=n;return 2===e&&t[0][0]===t[1][0]&&t[0][1]===t[1][1]?[0]:r}for(var a=new Array(e),n=0;e>n;++n)a[n]=n;a.sort(function(e,r){var n=t[e][0]-t[r][0];return n?n:t[e][1]-t[r][1]});for(var o=[a[0],a[1]],s=[a[0],a[1]],n=2;e>n;++n){for(var l=a[n],u=t[l],c=o.length;c>1&&i(t[o[c-2]],t[o[c-1]],u)<=0;)c-=1,o.pop();for(o.push(l),c=s.length;c>1&&i(t[s[c-2]],t[s[c-1]],u)>=0;)c-=1,s.pop();s.push(l)}for(var r=new Array(s.length+o.length-2),h=0,n=0,f=o.length;f>n;++n)r[h++]=o[n];for(var d=s.length-2;d>0;--d)r[h++]=s[d];return r}e.exports=n;var i=t("robust-orientation")[3]},{"robust-orientation":214}],66:[function(t,e,r){"use strict";function n(){this.argTypes=[],this.shimArgs=[],this.arrayArgs=[],this.arrayBlockIndices=[],this.scalarArgs=[],this.offsetArgs=[],this.offsetArgIndex=[],this.indexArgs=[],this.shapeArgs=[],this.funcName="",this.pre=null,this.body=null,this.post=null,this.debug=!1}function i(t){var e=new n;e.pre=t.pre,e.body=t.body,e.post=t.post;var r=t.args.slice(0);e.argTypes=r;for(var i=0;i<r.length;++i){var o=r[i];if("array"===o||"object"==typeof o&&o.blockIndices){if(e.argTypes[i]="array",e.arrayArgs.push(i),e.arrayBlockIndices.push(o.blockIndices?o.blockIndices:0),e.shimArgs.push("array"+i),i<e.pre.args.length&&e.pre.args[i].count>0)throw new Error("cwise: pre() block may not reference array args");if(i<e.post.args.length&&e.post.args[i].count>0)throw new Error("cwise: post() block may not reference array args")}else if("scalar"===o)e.scalarArgs.push(i),e.shimArgs.push("scalar"+i);else if("index"===o){if(e.indexArgs.push(i),i<e.pre.args.length&&e.pre.args[i].count>0)throw new Error("cwise: pre() block may not reference array index");if(i<e.body.args.length&&e.body.args[i].lvalue)throw new Error("cwise: body() block may not write to array index");if(i<e.post.args.length&&e.post.args[i].count>0)throw new Error("cwise: post() block may not reference array index")}else if("shape"===o){if(e.shapeArgs.push(i),i<e.pre.args.length&&e.pre.args[i].lvalue)throw new Error("cwise: pre() block may not write to array shape");if(i<e.body.args.length&&e.body.args[i].lvalue)throw new Error("cwise: body() block may not write to array shape");if(i<e.post.args.length&&e.post.args[i].lvalue)throw new Error("cwise: post() block may not write to array shape")}else{if("object"!=typeof o||!o.offset)throw new Error("cwise: Unknown argument type "+r[i]);e.argTypes[i]="offset",e.offsetArgs.push({array:o.array,offset:o.offset}),e.offsetArgIndex.push(i)}}if(e.arrayArgs.length<=0)throw new Error("cwise: No array arguments specified");if(e.pre.args.length>r.length)throw new Error("cwise: Too many arguments in pre() block");if(e.body.args.length>r.length)throw new Error("cwise: Too many arguments in body() block");if(e.post.args.length>r.length)throw new Error("cwise: Too many arguments in post() block");return e.debug=!!t.printCode||!!t.debug,e.funcName=t.funcName||"cwise",e.blockSize=t.blockSize||64,a(e)}var a=t("./lib/thunk.js");e.exports=i},{"./lib/thunk.js":68}],67:[function(t,e,r){"use strict";function n(t,e,r){var n,i,a=t.length,o=e.arrayArgs.length,s=e.indexArgs.length>0,l=[],u=[],c=0,h=0;for(n=0;a>n;++n)u.push(["i",n,"=0"].join(""));for(i=0;o>i;++i)for(n=0;a>n;++n)h=c,c=t[n],0===n?u.push(["d",i,"s",n,"=t",i,"p",c].join("")):u.push(["d",i,"s",n,"=(t",i,"p",c,"-s",h,"*t",i,"p",h,")"].join(""));for(l.push("var "+u.join(",")),n=a-1;n>=0;--n)c=t[n],l.push(["for(i",n,"=0;i",n,"<s",c,";++i",n,"){"].join(""));for(l.push(r),n=0;a>n;++n){for(h=c,c=t[n],i=0;o>i;++i)l.push(["p",i,"+=d",i,"s",n].join(""));s&&(n>0&&l.push(["index[",h,"]-=s",h].join("")),l.push(["++index[",c,"]"].join(""))),l.push("}")}return l.join("\n")}function i(t,e,r,i){for(var a=e.length,o=r.arrayArgs.length,s=r.blockSize,l=r.indexArgs.length>0,u=[],c=0;o>c;++c)u.push(["var offset",c,"=p",c].join(""));for(var c=t;a>c;++c)u.push(["for(var j"+c+"=SS[",e[c],"]|0;j",c,">0;){"].join("")),u.push(["if(j",c,"<",s,"){"].join("")),u.push(["s",e[c],"=j",c].join("")),u.push(["j",c,"=0"].join("")),u.push(["}else{s",e[c],"=",s].join("")),u.push(["j",c,"-=",s,"}"].join("")),l&&u.push(["index[",e[c],"]=j",c].join(""));for(var c=0;o>c;++c){for(var h=["offset"+c],f=t;a>f;++f)h.push(["j",f,"*t",c,"p",e[f]].join(""));u.push(["p",c,"=(",h.join("+"),")"].join(""))}u.push(n(e,r,i));for(var c=t;a>c;++c)u.push("}");return u.join("\n")}function a(t){for(var e=0,r=t[0].length;r>e;){for(var n=1;n<t.length;++n)if(t[n][e]!==t[0][e])return e;++e}return e}function o(t,e,r){for(var n=t.body,i=[],a=[],o=0;o<t.args.length;++o){var s=t.args[o];if(!(s.count<=0)){var l=new RegExp(s.name,"g"),u="",c=e.arrayArgs.indexOf(o);switch(e.argTypes[o]){case"offset":var h=e.offsetArgIndex.indexOf(o),f=e.offsetArgs[h];c=f.array,u="+q"+h;case"array":u="p"+c+u;var d="l"+o,p="a"+c;if(0===e.arrayBlockIndices[c])1===s.count?"generic"===r[c]?s.lvalue?(i.push(["var ",d,"=",p,".get(",u,")"].join("")),n=n.replace(l,d),a.push([p,".set(",u,",",d,")"].join(""))):n=n.replace(l,[p,".get(",u,")"].join("")):n=n.replace(l,[p,"[",u,"]"].join("")):"generic"===r[c]?(i.push(["var ",d,"=",p,".get(",u,")"].join("")),n=n.replace(l,d),s.lvalue&&a.push([p,".set(",u,",",d,")"].join(""))):(i.push(["var ",d,"=",p,"[",u,"]"].join("")),n=n.replace(l,d),s.lvalue&&a.push([p,"[",u,"]=",d].join("")));else{for(var g=[s.name],v=[u],m=0;m<Math.abs(e.arrayBlockIndices[c]);m++)g.push("\\s*\\[([^\\]]+)\\]"),v.push("$"+(m+1)+"*t"+c+"b"+m);if(l=new RegExp(g.join(""),"g"),u=v.join("+"),"generic"===r[c])throw new Error("cwise: Generic arrays not supported in combination with blocks!");n=n.replace(l,[p,"[",u,"]"].join(""))}break;case"scalar":n=n.replace(l,"Y"+e.scalarArgs.indexOf(o));break;case"index":n=n.replace(l,"index");break;case"shape":n=n.replace(l,"shape")}}}return[i.join("\n"),n,a.join("\n")].join("\n").trim()}function s(t){for(var e=new Array(t.length),r=!0,n=0;n<t.length;++n){var i=t[n],a=i.match(/\d+/);a=a?a[0]:"",0===i.charAt(0)?e[n]="u"+i.charAt(1)+a:e[n]=i.charAt(0)+a,n>0&&(r=r&&e[n]===e[n-1])}return r?e[0]:e.join("")}function l(t,e){for(var r=e[1].length-Math.abs(t.arrayBlockIndices[0])|0,l=new Array(t.arrayArgs.length),c=new Array(t.arrayArgs.length),h=0;h<t.arrayArgs.length;++h)c[h]=e[2*h],l[h]=e[2*h+1];for(var f=[],d=[],p=[],g=[],v=[],h=0;h<t.arrayArgs.length;++h){t.arrayBlockIndices[h]<0?(p.push(0),g.push(r),f.push(r),d.push(r+t.arrayBlockIndices[h])):(p.push(t.arrayBlockIndices[h]),g.push(t.arrayBlockIndices[h]+r),f.push(0),d.push(t.arrayBlockIndices[h]));for(var m=[],y=0;y<l[h].length;y++)p[h]<=l[h][y]&&l[h][y]<g[h]&&m.push(l[h][y]-p[h]);v.push(m)}for(var b=["SS"],x=["'use strict'"],_=[],y=0;r>y;++y)_.push(["s",y,"=SS[",y,"]"].join(""));for(var h=0;h<t.arrayArgs.length;++h){b.push("a"+h),b.push("t"+h),b.push("p"+h);for(var y=0;r>y;++y)_.push(["t",h,"p",y,"=t",h,"[",p[h]+y,"]"].join(""));for(var y=0;y<Math.abs(t.arrayBlockIndices[h]);++y)_.push(["t",h,"b",y,"=t",h,"[",f[h]+y,"]"].join(""))}for(var h=0;h<t.scalarArgs.length;++h)b.push("Y"+h);if(t.shapeArgs.length>0&&_.push("shape=SS.slice(0)"),t.indexArgs.length>0){for(var w=new Array(r),h=0;r>h;++h)w[h]="0";_.push(["index=[",w.join(","),"]"].join(""))}for(var h=0;h<t.offsetArgs.length;++h){for(var A=t.offsetArgs[h],k=[],y=0;y<A.offset.length;++y)0!==A.offset[y]&&(1===A.offset[y]?k.push(["t",A.array,"p",y].join("")):k.push([A.offset[y],"*t",A.array,"p",y].join("")));0===k.length?_.push("q"+h+"=0"):_.push(["q",h,"=",k.join("+")].join(""))}var M=u([].concat(t.pre.thisVars).concat(t.body.thisVars).concat(t.post.thisVars));_=_.concat(M),x.push("var "+_.join(","));for(var h=0;h<t.arrayArgs.length;++h)x.push("p"+h+"|=0");t.pre.body.length>3&&x.push(o(t.pre,t,c));var T=o(t.body,t,c),E=a(v);r>E?x.push(i(E,v[0],t,T)):x.push(n(v[0],t,T)),t.post.body.length>3&&x.push(o(t.post,t,c)),t.debug&&console.log("-----Generated cwise routine for ",e,":\n"+x.join("\n")+"\n----------");var L=[t.funcName||"unnamed","_cwise_loop_",l[0].join("s"),"m",E,s(c)].join(""),S=new Function(["function ",L,"(",b.join(","),"){",x.join("\n"),"} return ",L].join(""));return S()}var u=t("uniq");e.exports=l},{uniq:234}],68:[function(t,e,r){"use strict";function n(t){var e=["'use strict'","var CACHED={}"],r=[],n=t.funcName+"_cwise_thunk";e.push(["return function ",n,"(",t.shimArgs.join(","),"){"].join(""));for(var a=[],o=[],s=[["array",t.arrayArgs[0],".shape.slice(",Math.max(0,t.arrayBlockIndices[0]),t.arrayBlockIndices[0]<0?","+t.arrayBlockIndices[0]+")":")"].join("")],l=[],u=[],c=0;c<t.arrayArgs.length;++c){var h=t.arrayArgs[c];r.push(["t",h,"=array",h,".dtype,","r",h,"=array",h,".order"].join("")),a.push("t"+h),a.push("r"+h),o.push("t"+h),o.push("r"+h+".join()"),s.push("array"+h+".data"),s.push("array"+h+".stride"),s.push("array"+h+".offset|0"),c>0&&(l.push("array"+t.arrayArgs[0]+".shape.length===array"+h+".shape.length+"+(Math.abs(t.arrayBlockIndices[0])-Math.abs(t.arrayBlockIndices[c]))),u.push("array"+t.arrayArgs[0]+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[0])+"]===array"+h+".shape[shapeIndex+"+Math.max(0,t.arrayBlockIndices[c])+"]"))}t.arrayArgs.length>1&&(e.push("if (!("+l.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same dimensionality!')"),e.push("for(var shapeIndex=array"+t.arrayArgs[0]+".shape.length-"+Math.abs(t.arrayBlockIndices[0])+"; shapeIndex-->0;) {"),e.push("if (!("+u.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')"),e.push("}"));for(var c=0;c<t.scalarArgs.length;++c)s.push("scalar"+t.scalarArgs[c]);r.push(["type=[",o.join(","),"].join()"].join("")),r.push("proc=CACHED[type]"),e.push("var "+r.join(",")),e.push(["if(!proc){","CACHED[type]=proc=compile([",a.join(","),"])}","return proc(",s.join(","),")}"].join("")),t.debug&&console.log("-----Generated thunk:\n"+e.join("\n")+"\n----------");var f=new Function("compile",e.join("\n"));return f(i.bind(void 0,t))}var i=t("./compile.js");e.exports=n},{"./compile.js":67}],69:[function(t,e,r){e.exports=t("cwise-compiler")},{"cwise-compiler":66}],70:[function(e,r,n){!function(){function e(t){return t&&(t.ownerDocument||t.document||t).documentElement}function n(t){return t&&(t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView)}function i(t,e){return e>t?-1:t>e?1:t>=e?0:NaN}function a(t){return null===t?NaN:+t}function o(t){return!isNaN(t)}function s(t){return{left:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);i>n;){var a=n+i>>>1;t(e[a],r)<0?n=a+1:i=a}return n},right:function(e,r,n,i){for(arguments.length<3&&(n=0),arguments.length<4&&(i=e.length);i>n;){var a=n+i>>>1;t(e[a],r)>0?i=a:n=a+1}return n}}}function l(t){return t.length}function u(t){for(var e=1;t*e%1;)e*=10;return e}function c(t,e){for(var r in e)Object.defineProperty(t.prototype,r,{value:e[r],enumerable:!1})}function h(){this._=Object.create(null)}function f(t){return(t+="")===Ao||t[0]===ko?ko+t:t}function d(t){return(t+="")[0]===ko?t.slice(1):t}function p(t){return f(t)in this._}function g(t){return(t=f(t))in this._&&delete this._[t]}function v(){var t=[];for(var e in this._)t.push(d(e));return t}function m(){var t=0;for(var e in this._)++t;return t}function y(){for(var t in this._)return!1;return!0}function b(){this._=Object.create(null)}function x(t){return t}function _(t,e,r){return function(){var n=r.apply(e,arguments);return n===e?t:n}}function w(t,e){if(e in t)return e;e=e.charAt(0).toUpperCase()+e.slice(1);for(var r=0,n=Mo.length;n>r;++r){var i=Mo[r]+e;if(i in t)return i}}function A(){}function k(){}function M(t){function e(){for(var e,n=r,i=-1,a=n.length;++i<a;)(e=n[i].on)&&e.apply(this,arguments);return t}var r=[],n=new h;return e.on=function(e,i){var a,o=n.get(e);return arguments.length<2?o&&o.on:(o&&(o.on=null,r=r.slice(0,a=r.indexOf(o)).concat(r.slice(a+1)),n.remove(e)),i&&r.push(n.set(e,{on:i})),t)},e}function T(){uo.event.preventDefault()}function E(){for(var t,e=uo.event;t=e.sourceEvent;)e=t;return e}function L(t){for(var e=new k,r=0,n=arguments.length;++r<n;)e[arguments[r]]=M(e);return e.of=function(r,n){return function(i){try{var a=i.sourceEvent=uo.event;i.target=t,uo.event=i,e[i.type].apply(r,n)}finally{uo.event=a}}},e}function S(t){return Eo(t,Po),t}function C(t){return"function"==typeof t?t:function(){return Lo(t,this)}}function P(t){return"function"==typeof t?t:function(){return So(t,this)}}function z(t,e){function r(){this.removeAttribute(t)}function n(){this.removeAttributeNS(t.space,t.local)}function i(){this.setAttribute(t,e)}function a(){this.setAttributeNS(t.space,t.local,e)}function o(){var r=e.apply(this,arguments);null==r?this.removeAttribute(t):this.setAttribute(t,r)}function s(){var r=e.apply(this,arguments);null==r?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,r)}return t=uo.ns.qualify(t),null==e?t.local?n:r:"function"==typeof e?t.local?s:o:t.local?a:i}function R(t){return t.trim().replace(/\s+/g," ")}function O(t){return new RegExp("(?:^|\\s+)"+uo.requote(t)+"(?:\\s+|$)","g")}function I(t){return(t+"").trim().split(/^|\s+/)}function j(t,e){function r(){for(var r=-1;++r<i;)t[r](this,e)}function n(){for(var r=-1,n=e.apply(this,arguments);++r<i;)t[r](this,n)}t=I(t).map(N);var i=t.length;return"function"==typeof e?n:r}function N(t){var e=O(t);return function(r,n){if(i=r.classList)return n?i.add(t):i.remove(t);var i=r.getAttribute("class")||"";n?(e.lastIndex=0,e.test(i)||r.setAttribute("class",R(i+" "+t))):r.setAttribute("class",R(i.replace(e," ")))}}function F(t,e,r){function n(){this.style.removeProperty(t)}function i(){this.style.setProperty(t,e,r)}function a(){var n=e.apply(this,arguments);null==n?this.style.removeProperty(t):this.style.setProperty(t,n,r)}return null==e?n:"function"==typeof e?a:i}function B(t,e){function r(){delete this[t]}function n(){this[t]=e}function i(){var r=e.apply(this,arguments);null==r?delete this[t]:this[t]=r}return null==e?r:"function"==typeof e?i:n}function D(t){function e(){var e=this.ownerDocument,r=this.namespaceURI;return r?e.createElementNS(r,t):e.createElement(t)}function r(){return this.ownerDocument.createElementNS(t.space,t.local)}return"function"==typeof t?t:(t=uo.ns.qualify(t)).local?r:e}function U(){var t=this.parentNode;t&&t.removeChild(this)}function V(t){return{__data__:t}}function q(t){return function(){return Co(this,t)}}function H(t){return arguments.length||(t=i),function(e,r){return e&&r?t(e.__data__,r.__data__):!e-!r}}function G(t,e){for(var r=0,n=t.length;n>r;r++)for(var i,a=t[r],o=0,s=a.length;s>o;o++)(i=a[o])&&e(i,o,r);return t}function Y(t){return Eo(t,Ro),t}function X(t){var e,r;return function(n,i,a){var o,s=t[a].update,l=s.length;for(a!=r&&(r=a,e=0),i>=e&&(e=i+1);!(o=s[e])&&++e<l;);return o}}function W(t,e,r){function n(){var e=this[o];e&&(this.removeEventListener(t,e,e.$),delete this[o])}function i(){var i=l(e,ho(arguments));n.call(this),this.addEventListener(t,this[o]=i,i.$=r),i._=e}function a(){var e,r=new RegExp("^__on([^.]+)"+uo.requote(t)+"$");for(var n in this)if(e=n.match(r)){var i=this[n];this.removeEventListener(e[1],i,i.$),delete this[n]}}var o="__on"+t,s=t.indexOf("."),l=Z;s>0&&(t=t.slice(0,s));var u=Oo.get(t);return u&&(t=u,l=$),s?e?i:n:e?A:a}function Z(t,e){return function(r){var n=uo.event;uo.event=r,e[0]=this.__data__;try{t.apply(this,e)}finally{uo.event=n}}}function $(t,e){var r=Z(t,e);return function(t){var e=this,n=t.relatedTarget;n&&(n===e||8&n.compareDocumentPosition(e))||r.call(e,t)}}function K(t){var r=".dragsuppress-"+ ++jo,i="click"+r,a=uo.select(n(t)).on("touchmove"+r,T).on("dragstart"+r,T).on("selectstart"+r,T);if(null==Io&&(Io="onselectstart"in t?!1:w(t.style,"userSelect")),Io){var o=e(t).style,s=o[Io];o[Io]="none"}return function(t){
+if(a.on(r,null),Io&&(o[Io]=s),t){var e=function(){a.on(i,null)};a.on(i,function(){T(),e()},!0),setTimeout(e,0)}}}function Q(t,e){e.changedTouches&&(e=e.changedTouches[0]);var r=t.ownerSVGElement||t;if(r.createSVGPoint){var i=r.createSVGPoint();if(0>No){var a=n(t);if(a.scrollX||a.scrollY){r=uo.select("body").append("svg").style({position:"absolute",top:0,left:0,margin:0,padding:0,border:"none"},"important");var o=r[0][0].getScreenCTM();No=!(o.f||o.e),r.remove()}}return No?(i.x=e.pageX,i.y=e.pageY):(i.x=e.clientX,i.y=e.clientY),i=i.matrixTransform(t.getScreenCTM().inverse()),[i.x,i.y]}var s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}function J(){return uo.event.changedTouches[0].identifier}function tt(t){return t>0?1:0>t?-1:0}function et(t,e,r){return(e[0]-t[0])*(r[1]-t[1])-(e[1]-t[1])*(r[0]-t[0])}function rt(t){return t>1?0:-1>t?Do:Math.acos(t)}function nt(t){return t>1?qo:-1>t?-qo:Math.asin(t)}function it(t){return((t=Math.exp(t))-1/t)/2}function at(t){return((t=Math.exp(t))+1/t)/2}function ot(t){return((t=Math.exp(2*t))-1)/(t+1)}function st(t){return(t=Math.sin(t/2))*t}function lt(){}function ut(t,e,r){return this instanceof ut?(this.h=+t,this.s=+e,void(this.l=+r)):arguments.length<2?t instanceof ut?new ut(t.h,t.s,t.l):At(""+t,kt,ut):new ut(t,e,r)}function ct(t,e,r){function n(t){return t>360?t-=360:0>t&&(t+=360),60>t?a+(o-a)*t/60:180>t?o:240>t?a+(o-a)*(240-t)/60:a}function i(t){return Math.round(255*n(t))}var a,o;return t=isNaN(t)?0:(t%=360)<0?t+360:t,e=isNaN(e)?0:0>e?0:e>1?1:e,r=0>r?0:r>1?1:r,o=.5>=r?r*(1+e):r+e-r*e,a=2*r-o,new bt(i(t+120),i(t),i(t-120))}function ht(t,e,r){return this instanceof ht?(this.h=+t,this.c=+e,void(this.l=+r)):arguments.length<2?t instanceof ht?new ht(t.h,t.c,t.l):t instanceof dt?gt(t.l,t.a,t.b):gt((t=Mt((t=uo.rgb(t)).r,t.g,t.b)).l,t.a,t.b):new ht(t,e,r)}function ft(t,e,r){return isNaN(t)&&(t=0),isNaN(e)&&(e=0),new dt(r,Math.cos(t*=Ho)*e,Math.sin(t)*e)}function dt(t,e,r){return this instanceof dt?(this.l=+t,this.a=+e,void(this.b=+r)):arguments.length<2?t instanceof dt?new dt(t.l,t.a,t.b):t instanceof ht?ft(t.h,t.c,t.l):Mt((t=bt(t)).r,t.g,t.b):new dt(t,e,r)}function pt(t,e,r){var n=(t+16)/116,i=n+e/500,a=n-r/200;return i=vt(i)*es,n=vt(n)*rs,a=vt(a)*ns,new bt(yt(3.2404542*i-1.5371385*n-.4985314*a),yt(-.969266*i+1.8760108*n+.041556*a),yt(.0556434*i-.2040259*n+1.0572252*a))}function gt(t,e,r){return t>0?new ht(Math.atan2(r,e)*Go,Math.sqrt(e*e+r*r),t):new ht(NaN,NaN,t)}function vt(t){return t>.206893034?t*t*t:(t-4/29)/7.787037}function mt(t){return t>.008856?Math.pow(t,1/3):7.787037*t+4/29}function yt(t){return Math.round(255*(.00304>=t?12.92*t:1.055*Math.pow(t,1/2.4)-.055))}function bt(t,e,r){return this instanceof bt?(this.r=~~t,this.g=~~e,void(this.b=~~r)):arguments.length<2?t instanceof bt?new bt(t.r,t.g,t.b):At(""+t,bt,ct):new bt(t,e,r)}function xt(t){return new bt(t>>16,t>>8&255,255&t)}function _t(t){return xt(t)+""}function wt(t){return 16>t?"0"+Math.max(0,t).toString(16):Math.min(255,t).toString(16)}function At(t,e,r){var n,i,a,o=0,s=0,l=0;if(n=/([a-z]+)\((.*)\)/.exec(t=t.toLowerCase()))switch(i=n[2].split(","),n[1]){case"hsl":return r(parseFloat(i[0]),parseFloat(i[1])/100,parseFloat(i[2])/100);case"rgb":return e(Et(i[0]),Et(i[1]),Et(i[2]))}return(a=os.get(t))?e(a.r,a.g,a.b):(null==t||"#"!==t.charAt(0)||isNaN(a=parseInt(t.slice(1),16))||(4===t.length?(o=(3840&a)>>4,o=o>>4|o,s=240&a,s=s>>4|s,l=15&a,l=l<<4|l):7===t.length&&(o=(16711680&a)>>16,s=(65280&a)>>8,l=255&a)),e(o,s,l))}function kt(t,e,r){var n,i,a=Math.min(t/=255,e/=255,r/=255),o=Math.max(t,e,r),s=o-a,l=(o+a)/2;return s?(i=.5>l?s/(o+a):s/(2-o-a),n=t==o?(e-r)/s+(r>e?6:0):e==o?(r-t)/s+2:(t-e)/s+4,n*=60):(n=NaN,i=l>0&&1>l?0:n),new ut(n,i,l)}function Mt(t,e,r){t=Tt(t),e=Tt(e),r=Tt(r);var n=mt((.4124564*t+.3575761*e+.1804375*r)/es),i=mt((.2126729*t+.7151522*e+.072175*r)/rs),a=mt((.0193339*t+.119192*e+.9503041*r)/ns);return dt(116*i-16,500*(n-i),200*(i-a))}function Tt(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Et(t){var e=parseFloat(t);return"%"===t.charAt(t.length-1)?Math.round(2.55*e):e}function Lt(t){return"function"==typeof t?t:function(){return t}}function St(t){return function(e,r,n){return 2===arguments.length&&"function"==typeof r&&(n=r,r=null),Ct(e,r,t,n)}}function Ct(t,e,r,n){function i(){var t,e=l.status;if(!e&&zt(l)||e>=200&&300>e||304===e){try{t=r.call(a,l)}catch(n){return void o.error.call(a,n)}o.load.call(a,t)}else o.error.call(a,l)}var a={},o=uo.dispatch("beforesend","progress","load","error"),s={},l=new XMLHttpRequest,u=null;return!this.XDomainRequest||"withCredentials"in l||!/^(http(s)?:)?\/\//.test(t)||(l=new XDomainRequest),"onload"in l?l.onload=l.onerror=i:l.onreadystatechange=function(){l.readyState>3&&i()},l.onprogress=function(t){var e=uo.event;uo.event=t;try{o.progress.call(a,l)}finally{uo.event=e}},a.header=function(t,e){return t=(t+"").toLowerCase(),arguments.length<2?s[t]:(null==e?delete s[t]:s[t]=e+"",a)},a.mimeType=function(t){return arguments.length?(e=null==t?null:t+"",a):e},a.responseType=function(t){return arguments.length?(u=t,a):u},a.response=function(t){return r=t,a},["get","post"].forEach(function(t){a[t]=function(){return a.send.apply(a,[t].concat(ho(arguments)))}}),a.send=function(r,n,i){if(2===arguments.length&&"function"==typeof n&&(i=n,n=null),l.open(r,t,!0),null==e||"accept"in s||(s.accept=e+",*/*"),l.setRequestHeader)for(var c in s)l.setRequestHeader(c,s[c]);return null!=e&&l.overrideMimeType&&l.overrideMimeType(e),null!=u&&(l.responseType=u),null!=i&&a.on("error",i).on("load",function(t){i(null,t)}),o.beforesend.call(a,l),l.send(null==n?null:n),a},a.abort=function(){return l.abort(),a},uo.rebind(a,o,"on"),null==n?a:a.get(Pt(n))}function Pt(t){return 1===t.length?function(e,r){t(null==e?r:null)}:t}function zt(t){var e=t.responseType;return e&&"text"!==e?t.response:t.responseText}function Rt(t,e,r){var n=arguments.length;2>n&&(e=0),3>n&&(r=Date.now());var i=r+e,a={c:t,t:i,n:null};return ls?ls.n=a:ss=a,ls=a,us||(cs=clearTimeout(cs),us=1,hs(Ot)),a}function Ot(){var t=It(),e=jt()-t;e>24?(isFinite(e)&&(clearTimeout(cs),cs=setTimeout(Ot,e)),us=0):(us=1,hs(Ot))}function It(){for(var t=Date.now(),e=ss;e;)t>=e.t&&e.c(t-e.t)&&(e.c=null),e=e.n;return t}function jt(){for(var t,e=ss,r=1/0;e;)e.c?(e.t<r&&(r=e.t),e=(t=e).n):e=t?t.n=e.n:ss=e.n;return ls=t,r}function Nt(t,e){return e-(t?Math.ceil(Math.log(t)/Math.LN10):1)}function Ft(t,e){var r=Math.pow(10,3*wo(8-e));return{scale:e>8?function(t){return t/r}:function(t){return t*r},symbol:t}}function Bt(t){var e=t.decimal,r=t.thousands,n=t.grouping,i=t.currency,a=n&&r?function(t,e){for(var i=t.length,a=[],o=0,s=n[0],l=0;i>0&&s>0&&(l+s+1>e&&(s=Math.max(1,e-l)),a.push(t.substring(i-=s,i+s)),!((l+=s+1)>e));)s=n[o=(o+1)%n.length];return a.reverse().join(r)}:x;return function(t){var r=ds.exec(t),n=r[1]||" ",o=r[2]||">",s=r[3]||"-",l=r[4]||"",u=r[5],c=+r[6],h=r[7],f=r[8],d=r[9],p=1,g="",v="",m=!1,y=!0;switch(f&&(f=+f.substring(1)),(u||"0"===n&&"="===o)&&(u=n="0",o="="),d){case"n":h=!0,d="g";break;case"%":p=100,v="%",d="f";break;case"p":p=100,v="%",d="r";break;case"b":case"o":case"x":case"X":"#"===l&&(g="0"+d.toLowerCase());case"c":y=!1;case"d":m=!0,f=0;break;case"s":p=-1,d="r"}"$"===l&&(g=i[0],v=i[1]),"r"!=d||f||(d="g"),null!=f&&("g"==d?f=Math.max(1,Math.min(21,f)):("e"==d||"f"==d)&&(f=Math.max(0,Math.min(20,f)))),d=ps.get(d)||Dt;var b=u&&h;return function(t){var r=v;if(m&&t%1)return"";var i=0>t||0===t&&0>1/t?(t=-t,"-"):"-"===s?"":s;if(0>p){var l=uo.formatPrefix(t,f);t=l.scale(t),r=l.symbol+v}else t*=p;t=d(t,f);var x,_,w=t.lastIndexOf(".");if(0>w){var A=y?t.lastIndexOf("e"):-1;0>A?(x=t,_=""):(x=t.substring(0,A),_=t.substring(A))}else x=t.substring(0,w),_=e+t.substring(w+1);!u&&h&&(x=a(x,1/0));var k=g.length+x.length+_.length+(b?0:i.length),M=c>k?new Array(k=c-k+1).join(n):"";return b&&(x=a(M+x,M.length?c-_.length:1/0)),i+=g,t=x+_,("<"===o?i+t+M:">"===o?M+i+t:"^"===o?M.substring(0,k>>=1)+i+t+M.substring(k):i+(b?t:M+t))+r}}}function Dt(t){return t+""}function Ut(){this._=new Date(arguments.length>1?Date.UTC.apply(this,arguments):arguments[0])}function Vt(t,e,r){function n(e){var r=t(e),n=a(r,1);return n-e>e-r?r:n}function i(r){return e(r=t(new vs(r-1)),1),r}function a(t,r){return e(t=new vs(+t),r),t}function o(t,n,a){var o=i(t),s=[];if(a>1)for(;n>o;)r(o)%a||s.push(new Date(+o)),e(o,1);else for(;n>o;)s.push(new Date(+o)),e(o,1);return s}function s(t,e,r){try{vs=Ut;var n=new Ut;return n._=t,o(n,e,r)}finally{vs=Date}}t.floor=t,t.round=n,t.ceil=i,t.offset=a,t.range=o;var l=t.utc=qt(t);return l.floor=l,l.round=qt(n),l.ceil=qt(i),l.offset=qt(a),l.range=s,t}function qt(t){return function(e,r){try{vs=Ut;var n=new Ut;return n._=e,t(n,r)._}finally{vs=Date}}}function Ht(t){function e(t){function e(e){for(var r,i,a,o=[],s=-1,l=0;++s<n;)37===t.charCodeAt(s)&&(o.push(t.slice(l,s)),null!=(i=ys[r=t.charAt(++s)])&&(r=t.charAt(++s)),(a=L[r])&&(r=a(e,null==i?"e"===r?" ":"0":i)),o.push(r),l=s+1);return o.push(t.slice(l,s)),o.join("")}var n=t.length;return e.parse=function(e){var n={y:1900,m:0,d:1,H:0,M:0,S:0,L:0,Z:null},i=r(n,t,e,0);if(i!=e.length)return null;"p"in n&&(n.H=n.H%12+12*n.p);var a=null!=n.Z&&vs!==Ut,o=new(a?Ut:vs);return"j"in n?o.setFullYear(n.y,0,n.j):"W"in n||"U"in n?("w"in n||(n.w="W"in n?1:0),o.setFullYear(n.y,0,1),o.setFullYear(n.y,0,"W"in n?(n.w+6)%7+7*n.W-(o.getDay()+5)%7:n.w+7*n.U-(o.getDay()+6)%7)):o.setFullYear(n.y,n.m,n.d),o.setHours(n.H+(n.Z/100|0),n.M+n.Z%100,n.S,n.L),a?o._:o},e.toString=function(){return t},e}function r(t,e,r,n){for(var i,a,o,s=0,l=e.length,u=r.length;l>s;){if(n>=u)return-1;if(i=e.charCodeAt(s++),37===i){if(o=e.charAt(s++),a=S[o in ys?e.charAt(s++):o],!a||(n=a(t,r,n))<0)return-1}else if(i!=r.charCodeAt(n++))return-1}return n}function n(t,e,r){w.lastIndex=0;var n=w.exec(e.slice(r));return n?(t.w=A.get(n[0].toLowerCase()),r+n[0].length):-1}function i(t,e,r){x.lastIndex=0;var n=x.exec(e.slice(r));return n?(t.w=_.get(n[0].toLowerCase()),r+n[0].length):-1}function a(t,e,r){T.lastIndex=0;var n=T.exec(e.slice(r));return n?(t.m=E.get(n[0].toLowerCase()),r+n[0].length):-1}function o(t,e,r){k.lastIndex=0;var n=k.exec(e.slice(r));return n?(t.m=M.get(n[0].toLowerCase()),r+n[0].length):-1}function s(t,e,n){return r(t,L.c.toString(),e,n)}function l(t,e,n){return r(t,L.x.toString(),e,n)}function u(t,e,n){return r(t,L.X.toString(),e,n)}function c(t,e,r){var n=b.get(e.slice(r,r+=2).toLowerCase());return null==n?-1:(t.p=n,r)}var h=t.dateTime,f=t.date,d=t.time,p=t.periods,g=t.days,v=t.shortDays,m=t.months,y=t.shortMonths;e.utc=function(t){function r(t){try{vs=Ut;var e=new vs;return e._=t,n(e)}finally{vs=Date}}var n=e(t);return r.parse=function(t){try{vs=Ut;var e=n.parse(t);return e&&e._}finally{vs=Date}},r.toString=n.toString,r},e.multi=e.utc.multi=ce;var b=uo.map(),x=Yt(g),_=Xt(g),w=Yt(v),A=Xt(v),k=Yt(m),M=Xt(m),T=Yt(y),E=Xt(y);p.forEach(function(t,e){b.set(t.toLowerCase(),e)});var L={a:function(t){return v[t.getDay()]},A:function(t){return g[t.getDay()]},b:function(t){return y[t.getMonth()]},B:function(t){return m[t.getMonth()]},c:e(h),d:function(t,e){return Gt(t.getDate(),e,2)},e:function(t,e){return Gt(t.getDate(),e,2)},H:function(t,e){return Gt(t.getHours(),e,2)},I:function(t,e){return Gt(t.getHours()%12||12,e,2)},j:function(t,e){return Gt(1+gs.dayOfYear(t),e,3)},L:function(t,e){return Gt(t.getMilliseconds(),e,3)},m:function(t,e){return Gt(t.getMonth()+1,e,2)},M:function(t,e){return Gt(t.getMinutes(),e,2)},p:function(t){return p[+(t.getHours()>=12)]},S:function(t,e){return Gt(t.getSeconds(),e,2)},U:function(t,e){return Gt(gs.sundayOfYear(t),e,2)},w:function(t){return t.getDay()},W:function(t,e){return Gt(gs.mondayOfYear(t),e,2)},x:e(f),X:e(d),y:function(t,e){return Gt(t.getFullYear()%100,e,2)},Y:function(t,e){return Gt(t.getFullYear()%1e4,e,4)},Z:le,"%":function(){return"%"}},S={a:n,A:i,b:a,B:o,c:s,d:re,e:re,H:ie,I:ie,j:ne,L:se,m:ee,M:ae,p:c,S:oe,U:Zt,w:Wt,W:$t,x:l,X:u,y:Qt,Y:Kt,Z:Jt,"%":ue};return e}function Gt(t,e,r){var n=0>t?"-":"",i=(n?-t:t)+"",a=i.length;return n+(r>a?new Array(r-a+1).join(e)+i:i)}function Yt(t){return new RegExp("^(?:"+t.map(uo.requote).join("|")+")","i")}function Xt(t){for(var e=new h,r=-1,n=t.length;++r<n;)e.set(t[r].toLowerCase(),r);return e}function Wt(t,e,r){bs.lastIndex=0;var n=bs.exec(e.slice(r,r+1));return n?(t.w=+n[0],r+n[0].length):-1}function Zt(t,e,r){bs.lastIndex=0;var n=bs.exec(e.slice(r));return n?(t.U=+n[0],r+n[0].length):-1}function $t(t,e,r){bs.lastIndex=0;var n=bs.exec(e.slice(r));return n?(t.W=+n[0],r+n[0].length):-1}function Kt(t,e,r){bs.lastIndex=0;var n=bs.exec(e.slice(r,r+4));return n?(t.y=+n[0],r+n[0].length):-1}function Qt(t,e,r){bs.lastIndex=0;var n=bs.exec(e.slice(r,r+2));return n?(t.y=te(+n[0]),r+n[0].length):-1}function Jt(t,e,r){return/^[+-]\d{4}$/.test(e=e.slice(r,r+5))?(t.Z=-e,r+5):-1}function te(t){return t+(t>68?1900:2e3)}function ee(t,e,r){bs.lastIndex=0;var n=bs.exec(e.slice(r,r+2));return n?(t.m=n[0]-1,r+n[0].length):-1}function re(t,e,r){bs.lastIndex=0;var n=bs.exec(e.slice(r,r+2));return n?(t.d=+n[0],r+n[0].length):-1}function ne(t,e,r){bs.lastIndex=0;var n=bs.exec(e.slice(r,r+3));return n?(t.j=+n[0],r+n[0].length):-1}function ie(t,e,r){bs.lastIndex=0;var n=bs.exec(e.slice(r,r+2));return n?(t.H=+n[0],r+n[0].length):-1}function ae(t,e,r){bs.lastIndex=0;var n=bs.exec(e.slice(r,r+2));return n?(t.M=+n[0],r+n[0].length):-1}function oe(t,e,r){bs.lastIndex=0;var n=bs.exec(e.slice(r,r+2));return n?(t.S=+n[0],r+n[0].length):-1}function se(t,e,r){bs.lastIndex=0;var n=bs.exec(e.slice(r,r+3));return n?(t.L=+n[0],r+n[0].length):-1}function le(t){var e=t.getTimezoneOffset(),r=e>0?"-":"+",n=wo(e)/60|0,i=wo(e)%60;return r+Gt(n,"0",2)+Gt(i,"0",2)}function ue(t,e,r){xs.lastIndex=0;var n=xs.exec(e.slice(r,r+1));return n?r+n[0].length:-1}function ce(t){for(var e=t.length,r=-1;++r<e;)t[r][0]=this(t[r][0]);return function(e){for(var r=0,n=t[r];!n[1](e);)n=t[++r];return n[0](e)}}function he(){}function fe(t,e,r){var n=r.s=t+e,i=n-t,a=n-i;r.t=t-a+(e-i)}function de(t,e){t&&ks.hasOwnProperty(t.type)&&ks[t.type](t,e)}function pe(t,e,r){var n,i=-1,a=t.length-r;for(e.lineStart();++i<a;)n=t[i],e.point(n[0],n[1],n[2]);e.lineEnd()}function ge(t,e){var r=-1,n=t.length;for(e.polygonStart();++r<n;)pe(t[r],e,1);e.polygonEnd()}function ve(){function t(t,e){t*=Ho,e=e*Ho/2+Do/4;var r=t-n,o=r>=0?1:-1,s=o*r,l=Math.cos(e),u=Math.sin(e),c=a*u,h=i*l+c*Math.cos(s),f=c*o*Math.sin(s);Ts.add(Math.atan2(f,h)),n=t,i=l,a=u}var e,r,n,i,a;Es.point=function(o,s){Es.point=t,n=(e=o)*Ho,i=Math.cos(s=(r=s)*Ho/2+Do/4),a=Math.sin(s)},Es.lineEnd=function(){t(e,r)}}function me(t){var e=t[0],r=t[1],n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function ye(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function be(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function xe(t,e){t[0]+=e[0],t[1]+=e[1],t[2]+=e[2]}function _e(t,e){return[t[0]*e,t[1]*e,t[2]*e]}function we(t){var e=Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=e,t[1]/=e,t[2]/=e}function Ae(t){return[Math.atan2(t[1],t[0]),nt(t[2])]}function ke(t,e){return wo(t[0]-e[0])<Fo&&wo(t[1]-e[1])<Fo}function Me(t,e){t*=Ho;var r=Math.cos(e*=Ho);Te(r*Math.cos(t),r*Math.sin(t),Math.sin(e))}function Te(t,e,r){++Ls,Cs+=(t-Cs)/Ls,Ps+=(e-Ps)/Ls,zs+=(r-zs)/Ls}function Ee(){function t(t,i){t*=Ho;var a=Math.cos(i*=Ho),o=a*Math.cos(t),s=a*Math.sin(t),l=Math.sin(i),u=Math.atan2(Math.sqrt((u=r*l-n*s)*u+(u=n*o-e*l)*u+(u=e*s-r*o)*u),e*o+r*s+n*l);Ss+=u,Rs+=u*(e+(e=o)),Os+=u*(r+(r=s)),Is+=u*(n+(n=l)),Te(e,r,n)}var e,r,n;Bs.point=function(i,a){i*=Ho;var o=Math.cos(a*=Ho);e=o*Math.cos(i),r=o*Math.sin(i),n=Math.sin(a),Bs.point=t,Te(e,r,n)}}function Le(){Bs.point=Me}function Se(){function t(t,e){t*=Ho;var r=Math.cos(e*=Ho),o=r*Math.cos(t),s=r*Math.sin(t),l=Math.sin(e),u=i*l-a*s,c=a*o-n*l,h=n*s-i*o,f=Math.sqrt(u*u+c*c+h*h),d=n*o+i*s+a*l,p=f&&-rt(d)/f,g=Math.atan2(f,d);js+=p*u,Ns+=p*c,Fs+=p*h,Ss+=g,Rs+=g*(n+(n=o)),Os+=g*(i+(i=s)),Is+=g*(a+(a=l)),Te(n,i,a)}var e,r,n,i,a;Bs.point=function(o,s){e=o,r=s,Bs.point=t,o*=Ho;var l=Math.cos(s*=Ho);n=l*Math.cos(o),i=l*Math.sin(o),a=Math.sin(s),Te(n,i,a)},Bs.lineEnd=function(){t(e,r),Bs.lineEnd=Le,Bs.point=Me}}function Ce(t,e){function r(r,n){return r=t(r,n),e(r[0],r[1])}return t.invert&&e.invert&&(r.invert=function(r,n){return r=e.invert(r,n),r&&t.invert(r[0],r[1])}),r}function Pe(){return!0}function ze(t,e,r,n,i){var a=[],o=[];if(t.forEach(function(t){if(!((e=t.length-1)<=0)){var e,r=t[0],n=t[e];if(ke(r,n)){i.lineStart();for(var s=0;e>s;++s)i.point((r=t[s])[0],r[1]);return void i.lineEnd()}var l=new Oe(r,t,null,!0),u=new Oe(r,null,l,!1);l.o=u,a.push(l),o.push(u),l=new Oe(n,t,null,!1),u=new Oe(n,null,l,!0),l.o=u,a.push(l),o.push(u)}}),o.sort(e),Re(a),Re(o),a.length){for(var s=0,l=r,u=o.length;u>s;++s)o[s].e=l=!l;for(var c,h,f=a[0];;){for(var d=f,p=!0;d.v;)if((d=d.n)===f)return;c=d.z,i.lineStart();do{if(d.v=d.o.v=!0,d.e){if(p)for(var s=0,u=c.length;u>s;++s)i.point((h=c[s])[0],h[1]);else n(d.x,d.n.x,1,i);d=d.n}else{if(p){c=d.p.z;for(var s=c.length-1;s>=0;--s)i.point((h=c[s])[0],h[1])}else n(d.x,d.p.x,-1,i);d=d.p}d=d.o,c=d.z,p=!p}while(!d.v);i.lineEnd()}}}function Re(t){if(e=t.length){for(var e,r,n=0,i=t[0];++n<e;)i.n=r=t[n],r.p=i,i=r;i.n=r=t[0],r.p=i}}function Oe(t,e,r,n){this.x=t,this.z=e,this.o=r,this.e=n,this.v=!1,this.n=this.p=null}function Ie(t,e,r,n){return function(i,a){function o(e,r){var n=i(e,r);t(e=n[0],r=n[1])&&a.point(e,r)}function s(t,e){var r=i(t,e);v.point(r[0],r[1])}function l(){y.point=s,v.lineStart()}function u(){y.point=o,v.lineEnd()}function c(t,e){g.push([t,e]);var r=i(t,e);x.point(r[0],r[1])}function h(){x.lineStart(),g=[]}function f(){c(g[0][0],g[0][1]),x.lineEnd();var t,e=x.clean(),r=b.buffer(),n=r.length;if(g.pop(),p.push(g),g=null,n)if(1&e){t=r[0];var i,n=t.length-1,o=-1;if(n>0){for(_||(a.polygonStart(),_=!0),a.lineStart();++o<n;)a.point((i=t[o])[0],i[1]);a.lineEnd()}}else n>1&&2&e&&r.push(r.pop().concat(r.shift())),d.push(r.filter(je))}var d,p,g,v=e(a),m=i.invert(n[0],n[1]),y={point:o,lineStart:l,lineEnd:u,polygonStart:function(){y.point=c,y.lineStart=h,y.lineEnd=f,d=[],p=[]},polygonEnd:function(){y.point=o,y.lineStart=l,y.lineEnd=u,d=uo.merge(d);var t=Ve(m,p);d.length?(_||(a.polygonStart(),_=!0),ze(d,Fe,t,r,a)):t&&(_||(a.polygonStart(),_=!0),a.lineStart(),r(null,null,1,a),a.lineEnd()),_&&(a.polygonEnd(),_=!1),d=p=null},sphere:function(){a.polygonStart(),a.lineStart(),r(null,null,1,a),a.lineEnd(),a.polygonEnd()}},b=Ne(),x=e(b),_=!1;return y}}function je(t){return t.length>1}function Ne(){var t,e=[];return{lineStart:function(){e.push(t=[])},point:function(e,r){t.push([e,r])},lineEnd:A,buffer:function(){var r=e;return e=[],t=null,r},rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))}}}function Fe(t,e){return((t=t.x)[0]<0?t[1]-qo-Fo:qo-t[1])-((e=e.x)[0]<0?e[1]-qo-Fo:qo-e[1])}function Be(t){var e,r=NaN,n=NaN,i=NaN;return{lineStart:function(){t.lineStart(),e=1},point:function(a,o){var s=a>0?Do:-Do,l=wo(a-r);wo(l-Do)<Fo?(t.point(r,n=(n+o)/2>0?qo:-qo),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),t.point(a,n),e=0):i!==s&&l>=Do&&(wo(r-i)<Fo&&(r-=i*Fo),wo(a-s)<Fo&&(a-=s*Fo),n=De(r,n,a,o),t.point(i,n),t.lineEnd(),t.lineStart(),t.point(s,n),e=0),t.point(r=a,n=o),i=s},lineEnd:function(){t.lineEnd(),r=n=NaN},clean:function(){return 2-e}}}function De(t,e,r,n){var i,a,o=Math.sin(t-r);return wo(o)>Fo?Math.atan((Math.sin(e)*(a=Math.cos(n))*Math.sin(r)-Math.sin(n)*(i=Math.cos(e))*Math.sin(t))/(i*a*o)):(e+n)/2}function Ue(t,e,r,n){var i;if(null==t)i=r*qo,n.point(-Do,i),n.point(0,i),n.point(Do,i),n.point(Do,0),n.point(Do,-i),n.point(0,-i),n.point(-Do,-i),n.point(-Do,0),n.point(-Do,i);else if(wo(t[0]-e[0])>Fo){var a=t[0]<e[0]?Do:-Do;i=r*a/2,n.point(-a,i),n.point(0,i),n.point(a,i)}else n.point(e[0],e[1])}function Ve(t,e){var r=t[0],n=t[1],i=[Math.sin(r),-Math.cos(r),0],a=0,o=0;Ts.reset();for(var s=0,l=e.length;l>s;++s){var u=e[s],c=u.length;if(c)for(var h=u[0],f=h[0],d=h[1]/2+Do/4,p=Math.sin(d),g=Math.cos(d),v=1;;){v===c&&(v=0),t=u[v];var m=t[0],y=t[1]/2+Do/4,b=Math.sin(y),x=Math.cos(y),_=m-f,w=_>=0?1:-1,A=w*_,k=A>Do,M=p*b;if(Ts.add(Math.atan2(M*w*Math.sin(A),g*x+M*Math.cos(A))),a+=k?_+w*Uo:_,k^f>=r^m>=r){var T=be(me(h),me(t));we(T);var E=be(i,T);we(E);var L=(k^_>=0?-1:1)*nt(E[2]);(n>L||n===L&&(T[0]||T[1]))&&(o+=k^_>=0?1:-1)}if(!v++)break;f=m,p=b,g=x,h=t}}return(-Fo>a||Fo>a&&0>Ts)^1&o}function qe(t){function e(t,e){return Math.cos(t)*Math.cos(e)>a}function r(t){var r,a,l,u,c;return{lineStart:function(){u=l=!1,c=1},point:function(h,f){var d,p=[h,f],g=e(h,f),v=o?g?0:i(h,f):g?i(h+(0>h?Do:-Do),f):0;if(!r&&(u=l=g)&&t.lineStart(),g!==l&&(d=n(r,p),(ke(r,d)||ke(p,d))&&(p[0]+=Fo,p[1]+=Fo,g=e(p[0],p[1]))),g!==l)c=0,g?(t.lineStart(),d=n(p,r),t.point(d[0],d[1])):(d=n(r,p),t.point(d[0],d[1]),t.lineEnd()),r=d;else if(s&&r&&o^g){var m;v&a||!(m=n(p,r,!0))||(c=0,o?(t.lineStart(),t.point(m[0][0],m[0][1]),t.point(m[1][0],m[1][1]),t.lineEnd()):(t.point(m[1][0],m[1][1]),t.lineEnd(),t.lineStart(),t.point(m[0][0],m[0][1])))}!g||r&&ke(r,p)||t.point(p[0],p[1]),r=p,l=g,a=v},lineEnd:function(){l&&t.lineEnd(),r=null},clean:function(){return c|(u&&l)<<1}}}function n(t,e,r){var n=me(t),i=me(e),o=[1,0,0],s=be(n,i),l=ye(s,s),u=s[0],c=l-u*u;if(!c)return!r&&t;var h=a*l/c,f=-a*u/c,d=be(o,s),p=_e(o,h),g=_e(s,f);xe(p,g);var v=d,m=ye(p,v),y=ye(v,v),b=m*m-y*(ye(p,p)-1);if(!(0>b)){var x=Math.sqrt(b),_=_e(v,(-m-x)/y);if(xe(_,p),_=Ae(_),!r)return _;var w,A=t[0],k=e[0],M=t[1],T=e[1];A>k&&(w=A,A=k,k=w);var E=k-A,L=wo(E-Do)<Fo,S=L||Fo>E;if(!L&&M>T&&(w=M,M=T,T=w),S?L?M+T>0^_[1]<(wo(_[0]-A)<Fo?M:T):M<=_[1]&&_[1]<=T:E>Do^(A<=_[0]&&_[0]<=k)){var C=_e(v,(-m+x)/y);return xe(C,p),[_,Ae(C)]}}}function i(e,r){var n=o?t:Do-t,i=0;return-n>e?i|=1:e>n&&(i|=2),-n>r?i|=4:r>n&&(i|=8),i}var a=Math.cos(t),o=a>0,s=wo(a)>Fo,l=vr(t,6*Ho);return Ie(e,r,l,o?[0,-t]:[-Do,t-Do])}function He(t,e,r,n){return function(i){var a,o=i.a,s=i.b,l=o.x,u=o.y,c=s.x,h=s.y,f=0,d=1,p=c-l,g=h-u;if(a=t-l,p||!(a>0)){if(a/=p,0>p){if(f>a)return;d>a&&(d=a)}else if(p>0){if(a>d)return;a>f&&(f=a)}if(a=r-l,p||!(0>a)){if(a/=p,0>p){if(a>d)return;a>f&&(f=a)}else if(p>0){if(f>a)return;d>a&&(d=a)}if(a=e-u,g||!(a>0)){if(a/=g,0>g){if(f>a)return;d>a&&(d=a)}else if(g>0){if(a>d)return;a>f&&(f=a)}if(a=n-u,g||!(0>a)){if(a/=g,0>g){if(a>d)return;a>f&&(f=a)}else if(g>0){if(f>a)return;d>a&&(d=a)}return f>0&&(i.a={x:l+f*p,y:u+f*g}),1>d&&(i.b={x:l+d*p,y:u+d*g}),i}}}}}}function Ge(t,e,r,n){function i(n,i){return wo(n[0]-t)<Fo?i>0?0:3:wo(n[0]-r)<Fo?i>0?2:1:wo(n[1]-e)<Fo?i>0?1:0:i>0?3:2}function a(t,e){return o(t.x,e.x)}function o(t,e){var r=i(t,1),n=i(e,1);return r!==n?r-n:0===r?e[1]-t[1]:1===r?t[0]-e[0]:2===r?t[1]-e[1]:e[0]-t[0]}return function(s){function l(t){for(var e=0,r=v.length,n=t[1],i=0;r>i;++i)for(var a,o=1,s=v[i],l=s.length,u=s[0];l>o;++o)a=s[o],u[1]<=n?a[1]>n&&et(u,a,t)>0&&++e:a[1]<=n&&et(u,a,t)<0&&--e,u=a;return 0!==e}function u(a,s,l,u){var c=0,h=0;if(null==a||(c=i(a,l))!==(h=i(s,l))||o(a,s)<0^l>0){do u.point(0===c||3===c?t:r,c>1?n:e);while((c=(c+l+4)%4)!==h)}else u.point(s[0],s[1])}function c(i,a){return i>=t&&r>=i&&a>=e&&n>=a}function h(t,e){c(t,e)&&s.point(t,e)}function f(){S.point=p,v&&v.push(m=[]),k=!0,A=!1,_=w=NaN}function d(){g&&(p(y,b),x&&A&&E.rejoin(),g.push(E.buffer())),S.point=h,A&&s.lineEnd()}function p(t,e){t=Math.max(-Us,Math.min(Us,t)),e=Math.max(-Us,Math.min(Us,e));var r=c(t,e);if(v&&m.push([t,e]),k)y=t,b=e,x=r,k=!1,r&&(s.lineStart(),s.point(t,e));else if(r&&A)s.point(t,e);else{var n={a:{x:_,y:w},b:{x:t,y:e}};L(n)?(A||(s.lineStart(),s.point(n.a.x,n.a.y)),s.point(n.b.x,n.b.y),r||s.lineEnd(),M=!1):r&&(s.lineStart(),s.point(t,e),M=!1)}_=t,w=e,A=r}var g,v,m,y,b,x,_,w,A,k,M,T=s,E=Ne(),L=He(t,e,r,n),S={point:h,lineStart:f,lineEnd:d,polygonStart:function(){s=E,g=[],v=[],M=!0},polygonEnd:function(){s=T,g=uo.merge(g);var e=l([t,n]),r=M&&e,i=g.length;(r||i)&&(s.polygonStart(),r&&(s.lineStart(),u(null,null,1,s),s.lineEnd()),i&&ze(g,a,e,u,s),s.polygonEnd()),g=v=m=null}};return S}}function Ye(t){var e=0,r=Do/3,n=lr(t),i=n(e,r);return i.parallels=function(t){return arguments.length?n(e=t[0]*Do/180,r=t[1]*Do/180):[e/Do*180,r/Do*180]},i}function Xe(t,e){function r(t,e){var r=Math.sqrt(a-2*i*Math.sin(e))/i;return[r*Math.sin(t*=i),o-r*Math.cos(t)]}var n=Math.sin(t),i=(n+Math.sin(e))/2,a=1+n*(2*i-n),o=Math.sqrt(a)/i;return r.invert=function(t,e){var r=o-e;return[Math.atan2(t,r)/i,nt((a-(t*t+r*r)*i*i)/(2*i))]},r}function We(){function t(t,e){qs+=i*t-n*e,n=t,i=e}var e,r,n,i;Ws.point=function(a,o){Ws.point=t,e=n=a,r=i=o},Ws.lineEnd=function(){t(e,r)}}function Ze(t,e){Hs>t&&(Hs=t),t>Ys&&(Ys=t),Gs>e&&(Gs=e),e>Xs&&(Xs=e)}function $e(){function t(t,e){o.push("M",t,",",e,a)}function e(t,e){o.push("M",t,",",e),s.point=r}function r(t,e){o.push("L",t,",",e)}function n(){s.point=t}function i(){o.push("Z")}var a=Ke(4.5),o=[],s={point:t,lineStart:function(){s.point=e},lineEnd:n,polygonStart:function(){s.lineEnd=i},polygonEnd:function(){s.lineEnd=n,s.point=t},pointRadius:function(t){return a=Ke(t),s},result:function(){if(o.length){var t=o.join("");return o=[],t}}};return s}function Ke(t){return"m0,"+t+"a"+t+","+t+" 0 1,1 0,"+-2*t+"a"+t+","+t+" 0 1,1 0,"+2*t+"z"}function Qe(t,e){Cs+=t,Ps+=e,++zs}function Je(){function t(t,n){var i=t-e,a=n-r,o=Math.sqrt(i*i+a*a);Rs+=o*(e+t)/2,Os+=o*(r+n)/2,Is+=o,Qe(e=t,r=n)}var e,r;$s.point=function(n,i){$s.point=t,Qe(e=n,r=i)}}function tr(){$s.point=Qe}function er(){function t(t,e){var r=t-n,a=e-i,o=Math.sqrt(r*r+a*a);Rs+=o*(n+t)/2,Os+=o*(i+e)/2,Is+=o,o=i*t-n*e,js+=o*(n+t),Ns+=o*(i+e),Fs+=3*o,Qe(n=t,i=e)}var e,r,n,i;$s.point=function(a,o){$s.point=t,Qe(e=n=a,r=i=o)},$s.lineEnd=function(){t(e,r)}}function rr(t){function e(e,r){t.moveTo(e+o,r),t.arc(e,r,o,0,Uo)}function r(e,r){t.moveTo(e,r),s.point=n}function n(e,r){t.lineTo(e,r)}function i(){s.point=e}function a(){t.closePath()}var o=4.5,s={point:e,lineStart:function(){s.point=r},lineEnd:i,polygonStart:function(){s.lineEnd=a},polygonEnd:function(){s.lineEnd=i,s.point=e},pointRadius:function(t){return o=t,s},result:A};return s}function nr(t){function e(t){return(s?n:r)(t)}function r(e){return or(e,function(r,n){r=t(r,n),e.point(r[0],r[1])})}function n(e){function r(r,n){r=t(r,n),e.point(r[0],r[1])}function n(){b=NaN,k.point=a,e.lineStart()}function a(r,n){var a=me([r,n]),o=t(r,n);i(b,x,y,_,w,A,b=o[0],x=o[1],y=r,_=a[0],w=a[1],A=a[2],s,e),e.point(b,x)}function o(){k.point=r,e.lineEnd()}function l(){n(),k.point=u,k.lineEnd=c}function u(t,e){a(h=t,f=e),d=b,p=x,g=_,v=w,m=A,k.point=a}function c(){i(b,x,y,_,w,A,d,p,h,g,v,m,s,e),k.lineEnd=o,o()}var h,f,d,p,g,v,m,y,b,x,_,w,A,k={point:r,lineStart:n,lineEnd:o,polygonStart:function(){e.polygonStart(),k.lineStart=l},polygonEnd:function(){e.polygonEnd(),k.lineStart=n}};return k}function i(e,r,n,s,l,u,c,h,f,d,p,g,v,m){var y=c-e,b=h-r,x=y*y+b*b;if(x>4*a&&v--){var _=s+d,w=l+p,A=u+g,k=Math.sqrt(_*_+w*w+A*A),M=Math.asin(A/=k),T=wo(wo(A)-1)<Fo||wo(n-f)<Fo?(n+f)/2:Math.atan2(w,_),E=t(T,M),L=E[0],S=E[1],C=L-e,P=S-r,z=b*C-y*P;(z*z/x>a||wo((y*C+b*P)/x-.5)>.3||o>s*d+l*p+u*g)&&(i(e,r,n,s,l,u,L,S,T,_/=k,w/=k,A,v,m),m.point(L,S),i(L,S,T,_,w,A,c,h,f,d,p,g,v,m))}}var a=.5,o=Math.cos(30*Ho),s=16;return e.precision=function(t){return arguments.length?(s=(a=t*t)>0&&16,e):Math.sqrt(a)},e}function ir(t){var e=nr(function(e,r){return t([e*Go,r*Go])});return function(t){return ur(e(t))}}function ar(t){this.stream=t}function or(t,e){return{point:e,sphere:function(){t.sphere()},lineStart:function(){t.lineStart()},lineEnd:function(){t.lineEnd()},polygonStart:function(){t.polygonStart()},polygonEnd:function(){t.polygonEnd()}}}function sr(t){return lr(function(){return t})()}function lr(t){function e(t){return t=s(t[0]*Ho,t[1]*Ho),[t[0]*f+l,u-t[1]*f]}function r(t){return t=s.invert((t[0]-l)/f,(u-t[1])/f),t&&[t[0]*Go,t[1]*Go]}function n(){s=Ce(o=fr(m,y,b),a);var t=a(g,v);return l=d-t[0]*f,u=p+t[1]*f,i()}function i(){return c&&(c.valid=!1,c=null),e}var a,o,s,l,u,c,h=nr(function(t,e){return t=a(t,e),[t[0]*f+l,u-t[1]*f]}),f=150,d=480,p=250,g=0,v=0,m=0,y=0,b=0,_=Ds,w=x,A=null,k=null;return e.stream=function(t){return c&&(c.valid=!1),c=ur(_(o,h(w(t)))),c.valid=!0,c},e.clipAngle=function(t){return arguments.length?(_=null==t?(A=t,Ds):qe((A=+t)*Ho),i()):A},e.clipExtent=function(t){return arguments.length?(k=t,w=t?Ge(t[0][0],t[0][1],t[1][0],t[1][1]):x,i()):k},e.scale=function(t){return arguments.length?(f=+t,n()):f},e.translate=function(t){return arguments.length?(d=+t[0],p=+t[1],n()):[d,p]},e.center=function(t){return arguments.length?(g=t[0]%360*Ho,v=t[1]%360*Ho,n()):[g*Go,v*Go]},e.rotate=function(t){return arguments.length?(m=t[0]%360*Ho,y=t[1]%360*Ho,b=t.length>2?t[2]%360*Ho:0,n()):[m*Go,y*Go,b*Go]},uo.rebind(e,h,"precision"),function(){return a=t.apply(this,arguments),e.invert=a.invert&&r,n()}}function ur(t){return or(t,function(e,r){t.point(e*Ho,r*Ho)})}function cr(t,e){return[t,e]}function hr(t,e){return[t>Do?t-Uo:-Do>t?t+Uo:t,e]}function fr(t,e,r){return t?e||r?Ce(pr(t),gr(e,r)):pr(t):e||r?gr(e,r):hr}function dr(t){return function(e,r){return e+=t,[e>Do?e-Uo:-Do>e?e+Uo:e,r]}}function pr(t){var e=dr(t);return e.invert=dr(-t),e}function gr(t,e){function r(t,e){var r=Math.cos(e),s=Math.cos(t)*r,l=Math.sin(t)*r,u=Math.sin(e),c=u*n+s*i;return[Math.atan2(l*a-c*o,s*n-u*i),nt(c*a+l*o)]}var n=Math.cos(t),i=Math.sin(t),a=Math.cos(e),o=Math.sin(e);return r.invert=function(t,e){var r=Math.cos(e),s=Math.cos(t)*r,l=Math.sin(t)*r,u=Math.sin(e),c=u*a-l*o;return[Math.atan2(l*a+u*o,s*n+c*i),nt(c*n-s*i)]},r}function vr(t,e){var r=Math.cos(t),n=Math.sin(t);return function(i,a,o,s){var l=o*e;null!=i?(i=mr(r,i),a=mr(r,a),(o>0?a>i:i>a)&&(i+=o*Uo)):(i=t+o*Uo,a=t-.5*l);for(var u,c=i;o>0?c>a:a>c;c-=l)s.point((u=Ae([r,-n*Math.cos(c),-n*Math.sin(c)]))[0],u[1])}}function mr(t,e){var r=me(e);r[0]-=t,we(r);var n=rt(-r[1]);return((-r[2]<0?-n:n)+2*Math.PI-Fo)%(2*Math.PI)}function yr(t,e,r){var n=uo.range(t,e-Fo,r).concat(e);return function(t){return n.map(function(e){return[t,e]})}}function br(t,e,r){var n=uo.range(t,e-Fo,r).concat(e);return function(t){return n.map(function(e){return[e,t]})}}function xr(t){return t.source}function _r(t){return t.target}function wr(t,e,r,n){var i=Math.cos(e),a=Math.sin(e),o=Math.cos(n),s=Math.sin(n),l=i*Math.cos(t),u=i*Math.sin(t),c=o*Math.cos(r),h=o*Math.sin(r),f=2*Math.asin(Math.sqrt(st(n-e)+i*o*st(r-t))),d=1/Math.sin(f),p=f?function(t){var e=Math.sin(t*=f)*d,r=Math.sin(f-t)*d,n=r*l+e*c,i=r*u+e*h,o=r*a+e*s;return[Math.atan2(i,n)*Go,Math.atan2(o,Math.sqrt(n*n+i*i))*Go]}:function(){return[t*Go,e*Go]};return p.distance=f,p}function Ar(){function t(t,i){var a=Math.sin(i*=Ho),o=Math.cos(i),s=wo((t*=Ho)-e),l=Math.cos(s);Ks+=Math.atan2(Math.sqrt((s=o*Math.sin(s))*s+(s=n*a-r*o*l)*s),r*a+n*o*l),e=t,r=a,n=o}var e,r,n;Qs.point=function(i,a){e=i*Ho,r=Math.sin(a*=Ho),n=Math.cos(a),Qs.point=t},Qs.lineEnd=function(){Qs.point=Qs.lineEnd=A}}function kr(t,e){function r(e,r){var n=Math.cos(e),i=Math.cos(r),a=t(n*i);return[a*i*Math.sin(e),a*Math.sin(r)]}return r.invert=function(t,r){var n=Math.sqrt(t*t+r*r),i=e(n),a=Math.sin(i),o=Math.cos(i);return[Math.atan2(t*a,n*o),Math.asin(n&&r*a/n)]},r}function Mr(t,e){function r(t,e){o>0?-qo+Fo>e&&(e=-qo+Fo):e>qo-Fo&&(e=qo-Fo);var r=o/Math.pow(i(e),a);return[r*Math.sin(a*t),o-r*Math.cos(a*t)]}var n=Math.cos(t),i=function(t){return Math.tan(Do/4+t/2)},a=t===e?Math.sin(t):Math.log(n/Math.cos(e))/Math.log(i(e)/i(t)),o=n*Math.pow(i(t),a)/a;return a?(r.invert=function(t,e){var r=o-e,n=tt(a)*Math.sqrt(t*t+r*r);return[Math.atan2(t,r)/a,2*Math.atan(Math.pow(o/n,1/a))-qo]},r):Er}function Tr(t,e){function r(t,e){var r=a-e;return[r*Math.sin(i*t),a-r*Math.cos(i*t)]}var n=Math.cos(t),i=t===e?Math.sin(t):(n-Math.cos(e))/(e-t),a=n/i+t;return wo(i)<Fo?cr:(r.invert=function(t,e){var r=a-e;return[Math.atan2(t,r)/i,a-tt(i)*Math.sqrt(t*t+r*r)]},r)}function Er(t,e){return[t,Math.log(Math.tan(Do/4+e/2))]}function Lr(t){var e,r=sr(t),n=r.scale,i=r.translate,a=r.clipExtent;return r.scale=function(){var t=n.apply(r,arguments);return t===r?e?r.clipExtent(null):r:t},r.translate=function(){var t=i.apply(r,arguments);return t===r?e?r.clipExtent(null):r:t;
+},r.clipExtent=function(t){var o=a.apply(r,arguments);if(o===r){if(e=null==t){var s=Do*n(),l=i();a([[l[0]-s,l[1]-s],[l[0]+s,l[1]+s]])}}else e&&(o=null);return o},r.clipExtent(null)}function Sr(t,e){return[Math.log(Math.tan(Do/4+e/2)),-t]}function Cr(t){return t[0]}function Pr(t){return t[1]}function zr(t){for(var e=t.length,r=[0,1],n=2,i=2;e>i;i++){for(;n>1&&et(t[r[n-2]],t[r[n-1]],t[i])<=0;)--n;r[n++]=i}return r.slice(0,n)}function Rr(t,e){return t[0]-e[0]||t[1]-e[1]}function Or(t,e,r){return(r[0]-e[0])*(t[1]-e[1])<(r[1]-e[1])*(t[0]-e[0])}function Ir(t,e,r,n){var i=t[0],a=r[0],o=e[0]-i,s=n[0]-a,l=t[1],u=r[1],c=e[1]-l,h=n[1]-u,f=(s*(l-u)-h*(i-a))/(h*o-s*c);return[i+f*o,l+f*c]}function jr(t){var e=t[0],r=t[t.length-1];return!(e[0]-r[0]||e[1]-r[1])}function Nr(){an(this),this.edge=this.site=this.circle=null}function Fr(t){var e=cl.pop()||new Nr;return e.site=t,e}function Br(t){Zr(t),sl.remove(t),cl.push(t),an(t)}function Dr(t){var e=t.circle,r=e.x,n=e.cy,i={x:r,y:n},a=t.P,o=t.N,s=[t];Br(t);for(var l=a;l.circle&&wo(r-l.circle.x)<Fo&&wo(n-l.circle.cy)<Fo;)a=l.P,s.unshift(l),Br(l),l=a;s.unshift(l),Zr(l);for(var u=o;u.circle&&wo(r-u.circle.x)<Fo&&wo(n-u.circle.cy)<Fo;)o=u.N,s.push(u),Br(u),u=o;s.push(u),Zr(u);var c,h=s.length;for(c=1;h>c;++c)u=s[c],l=s[c-1],en(u.edge,l.site,u.site,i);l=s[0],u=s[h-1],u.edge=Jr(l.site,u.site,null,i),Wr(l),Wr(u)}function Ur(t){for(var e,r,n,i,a=t.x,o=t.y,s=sl._;s;)if(n=Vr(s,o)-a,n>Fo)s=s.L;else{if(i=a-qr(s,o),!(i>Fo)){n>-Fo?(e=s.P,r=s):i>-Fo?(e=s,r=s.N):e=r=s;break}if(!s.R){e=s;break}s=s.R}var l=Fr(t);if(sl.insert(e,l),e||r){if(e===r)return Zr(e),r=Fr(e.site),sl.insert(l,r),l.edge=r.edge=Jr(e.site,l.site),Wr(e),void Wr(r);if(!r)return void(l.edge=Jr(e.site,l.site));Zr(e),Zr(r);var u=e.site,c=u.x,h=u.y,f=t.x-c,d=t.y-h,p=r.site,g=p.x-c,v=p.y-h,m=2*(f*v-d*g),y=f*f+d*d,b=g*g+v*v,x={x:(v*y-d*b)/m+c,y:(f*b-g*y)/m+h};en(r.edge,u,p,x),l.edge=Jr(u,t,null,x),r.edge=Jr(t,p,null,x),Wr(e),Wr(r)}}function Vr(t,e){var r=t.site,n=r.x,i=r.y,a=i-e;if(!a)return n;var o=t.P;if(!o)return-(1/0);r=o.site;var s=r.x,l=r.y,u=l-e;if(!u)return s;var c=s-n,h=1/a-1/u,f=c/u;return h?(-f+Math.sqrt(f*f-2*h*(c*c/(-2*u)-l+u/2+i-a/2)))/h+n:(n+s)/2}function qr(t,e){var r=t.N;if(r)return Vr(r,e);var n=t.site;return n.y===e?n.x:1/0}function Hr(t){this.site=t,this.edges=[]}function Gr(t){for(var e,r,n,i,a,o,s,l,u,c,h=t[0][0],f=t[1][0],d=t[0][1],p=t[1][1],g=ol,v=g.length;v--;)if(a=g[v],a&&a.prepare())for(s=a.edges,l=s.length,o=0;l>o;)c=s[o].end(),n=c.x,i=c.y,u=s[++o%l].start(),e=u.x,r=u.y,(wo(n-e)>Fo||wo(i-r)>Fo)&&(s.splice(o,0,new rn(tn(a.site,c,wo(n-h)<Fo&&p-i>Fo?{x:h,y:wo(e-h)<Fo?r:p}:wo(i-p)<Fo&&f-n>Fo?{x:wo(r-p)<Fo?e:f,y:p}:wo(n-f)<Fo&&i-d>Fo?{x:f,y:wo(e-f)<Fo?r:d}:wo(i-d)<Fo&&n-h>Fo?{x:wo(r-d)<Fo?e:h,y:d}:null),a.site,null)),++l)}function Yr(t,e){return e.angle-t.angle}function Xr(){an(this),this.x=this.y=this.arc=this.site=this.cy=null}function Wr(t){var e=t.P,r=t.N;if(e&&r){var n=e.site,i=t.site,a=r.site;if(n!==a){var o=i.x,s=i.y,l=n.x-o,u=n.y-s,c=a.x-o,h=a.y-s,f=2*(l*h-u*c);if(!(f>=-Bo)){var d=l*l+u*u,p=c*c+h*h,g=(h*d-u*p)/f,v=(l*p-c*d)/f,h=v+s,m=hl.pop()||new Xr;m.arc=t,m.site=i,m.x=g+o,m.y=h+Math.sqrt(g*g+v*v),m.cy=h,t.circle=m;for(var y=null,b=ul._;b;)if(m.y<b.y||m.y===b.y&&m.x<=b.x){if(!b.L){y=b.P;break}b=b.L}else{if(!b.R){y=b;break}b=b.R}ul.insert(y,m),y||(ll=m)}}}}function Zr(t){var e=t.circle;e&&(e.P||(ll=e.N),ul.remove(e),hl.push(e),an(e),t.circle=null)}function $r(t){for(var e,r=al,n=He(t[0][0],t[0][1],t[1][0],t[1][1]),i=r.length;i--;)e=r[i],(!Kr(e,t)||!n(e)||wo(e.a.x-e.b.x)<Fo&&wo(e.a.y-e.b.y)<Fo)&&(e.a=e.b=null,r.splice(i,1))}function Kr(t,e){var r=t.b;if(r)return!0;var n,i,a=t.a,o=e[0][0],s=e[1][0],l=e[0][1],u=e[1][1],c=t.l,h=t.r,f=c.x,d=c.y,p=h.x,g=h.y,v=(f+p)/2,m=(d+g)/2;if(g===d){if(o>v||v>=s)return;if(f>p){if(a){if(a.y>=u)return}else a={x:v,y:l};r={x:v,y:u}}else{if(a){if(a.y<l)return}else a={x:v,y:u};r={x:v,y:l}}}else if(n=(f-p)/(g-d),i=m-n*v,-1>n||n>1)if(f>p){if(a){if(a.y>=u)return}else a={x:(l-i)/n,y:l};r={x:(u-i)/n,y:u}}else{if(a){if(a.y<l)return}else a={x:(u-i)/n,y:u};r={x:(l-i)/n,y:l}}else if(g>d){if(a){if(a.x>=s)return}else a={x:o,y:n*o+i};r={x:s,y:n*s+i}}else{if(a){if(a.x<o)return}else a={x:s,y:n*s+i};r={x:o,y:n*o+i}}return t.a=a,t.b=r,!0}function Qr(t,e){this.l=t,this.r=e,this.a=this.b=null}function Jr(t,e,r,n){var i=new Qr(t,e);return al.push(i),r&&en(i,t,e,r),n&&en(i,e,t,n),ol[t.i].edges.push(new rn(i,t,e)),ol[e.i].edges.push(new rn(i,e,t)),i}function tn(t,e,r){var n=new Qr(t,null);return n.a=e,n.b=r,al.push(n),n}function en(t,e,r,n){t.a||t.b?t.l===r?t.b=n:t.a=n:(t.a=n,t.l=e,t.r=r)}function rn(t,e,r){var n=t.a,i=t.b;this.edge=t,this.site=e,this.angle=r?Math.atan2(r.y-e.y,r.x-e.x):t.l===e?Math.atan2(i.x-n.x,n.y-i.y):Math.atan2(n.x-i.x,i.y-n.y)}function nn(){this._=null}function an(t){t.U=t.C=t.L=t.R=t.P=t.N=null}function on(t,e){var r=e,n=e.R,i=r.U;i?i.L===r?i.L=n:i.R=n:t._=n,n.U=i,r.U=n,r.R=n.L,r.R&&(r.R.U=r),n.L=r}function sn(t,e){var r=e,n=e.L,i=r.U;i?i.L===r?i.L=n:i.R=n:t._=n,n.U=i,r.U=n,r.L=n.R,r.L&&(r.L.U=r),n.R=r}function ln(t){for(;t.L;)t=t.L;return t}function un(t,e){var r,n,i,a=t.sort(cn).pop();for(al=[],ol=new Array(t.length),sl=new nn,ul=new nn;;)if(i=ll,a&&(!i||a.y<i.y||a.y===i.y&&a.x<i.x))(a.x!==r||a.y!==n)&&(ol[a.i]=new Hr(a),Ur(a),r=a.x,n=a.y),a=t.pop();else{if(!i)break;Dr(i.arc)}e&&($r(e),Gr(e));var o={cells:ol,edges:al};return sl=ul=al=ol=null,o}function cn(t,e){return e.y-t.y||e.x-t.x}function hn(t,e,r){return(t.x-r.x)*(e.y-t.y)-(t.x-e.x)*(r.y-t.y)}function fn(t){return t.x}function dn(t){return t.y}function pn(){return{leaf:!0,nodes:[],point:null,x:null,y:null}}function gn(t,e,r,n,i,a){if(!t(e,r,n,i,a)){var o=.5*(r+i),s=.5*(n+a),l=e.nodes;l[0]&&gn(t,l[0],r,n,o,s),l[1]&&gn(t,l[1],o,n,i,s),l[2]&&gn(t,l[2],r,s,o,a),l[3]&&gn(t,l[3],o,s,i,a)}}function vn(t,e,r,n,i,a,o){var s,l=1/0;return function u(t,c,h,f,d){if(!(c>a||h>o||n>f||i>d)){if(p=t.point){var p,g=e-t.x,v=r-t.y,m=g*g+v*v;if(l>m){var y=Math.sqrt(l=m);n=e-y,i=r-y,a=e+y,o=r+y,s=p}}for(var b=t.nodes,x=.5*(c+f),_=.5*(h+d),w=e>=x,A=r>=_,k=A<<1|w,M=k+4;M>k;++k)if(t=b[3&k])switch(3&k){case 0:u(t,c,h,x,_);break;case 1:u(t,x,h,f,_);break;case 2:u(t,c,_,x,d);break;case 3:u(t,x,_,f,d)}}}(t,n,i,a,o),s}function mn(t,e){t=uo.rgb(t),e=uo.rgb(e);var r=t.r,n=t.g,i=t.b,a=e.r-r,o=e.g-n,s=e.b-i;return function(t){return"#"+wt(Math.round(r+a*t))+wt(Math.round(n+o*t))+wt(Math.round(i+s*t))}}function yn(t,e){var r,n={},i={};for(r in t)r in e?n[r]=_n(t[r],e[r]):i[r]=t[r];for(r in e)r in t||(i[r]=e[r]);return function(t){for(r in n)i[r]=n[r](t);return i}}function bn(t,e){return t=+t,e=+e,function(r){return t*(1-r)+e*r}}function xn(t,e){var r,n,i,a=dl.lastIndex=pl.lastIndex=0,o=-1,s=[],l=[];for(t+="",e+="";(r=dl.exec(t))&&(n=pl.exec(e));)(i=n.index)>a&&(i=e.slice(a,i),s[o]?s[o]+=i:s[++o]=i),(r=r[0])===(n=n[0])?s[o]?s[o]+=n:s[++o]=n:(s[++o]=null,l.push({i:o,x:bn(r,n)})),a=pl.lastIndex;return a<e.length&&(i=e.slice(a),s[o]?s[o]+=i:s[++o]=i),s.length<2?l[0]?(e=l[0].x,function(t){return e(t)+""}):function(){return e}:(e=l.length,function(t){for(var r,n=0;e>n;++n)s[(r=l[n]).i]=r.x(t);return s.join("")})}function _n(t,e){for(var r,n=uo.interpolators.length;--n>=0&&!(r=uo.interpolators[n](t,e)););return r}function wn(t,e){var r,n=[],i=[],a=t.length,o=e.length,s=Math.min(t.length,e.length);for(r=0;s>r;++r)n.push(_n(t[r],e[r]));for(;a>r;++r)i[r]=t[r];for(;o>r;++r)i[r]=e[r];return function(t){for(r=0;s>r;++r)i[r]=n[r](t);return i}}function An(t){return function(e){return 0>=e?0:e>=1?1:t(e)}}function kn(t){return function(e){return 1-t(1-e)}}function Mn(t){return function(e){return.5*(.5>e?t(2*e):2-t(2-2*e))}}function Tn(t){return t*t}function En(t){return t*t*t}function Ln(t){if(0>=t)return 0;if(t>=1)return 1;var e=t*t,r=e*t;return 4*(.5>t?r:3*(t-e)+r-.75)}function Sn(t){return function(e){return Math.pow(e,t)}}function Cn(t){return 1-Math.cos(t*qo)}function Pn(t){return Math.pow(2,10*(t-1))}function zn(t){return 1-Math.sqrt(1-t*t)}function Rn(t,e){var r;return arguments.length<2&&(e=.45),arguments.length?r=e/Uo*Math.asin(1/t):(t=1,r=e/4),function(n){return 1+t*Math.pow(2,-10*n)*Math.sin((n-r)*Uo/e)}}function On(t){return t||(t=1.70158),function(e){return e*e*((t+1)*e-t)}}function In(t){return 1/2.75>t?7.5625*t*t:2/2.75>t?7.5625*(t-=1.5/2.75)*t+.75:2.5/2.75>t?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}function jn(t,e){t=uo.hcl(t),e=uo.hcl(e);var r=t.h,n=t.c,i=t.l,a=e.h-r,o=e.c-n,s=e.l-i;return isNaN(o)&&(o=0,n=isNaN(n)?e.c:n),isNaN(a)?(a=0,r=isNaN(r)?e.h:r):a>180?a-=360:-180>a&&(a+=360),function(t){return ft(r+a*t,n+o*t,i+s*t)+""}}function Nn(t,e){t=uo.hsl(t),e=uo.hsl(e);var r=t.h,n=t.s,i=t.l,a=e.h-r,o=e.s-n,s=e.l-i;return isNaN(o)&&(o=0,n=isNaN(n)?e.s:n),isNaN(a)?(a=0,r=isNaN(r)?e.h:r):a>180?a-=360:-180>a&&(a+=360),function(t){return ct(r+a*t,n+o*t,i+s*t)+""}}function Fn(t,e){t=uo.lab(t),e=uo.lab(e);var r=t.l,n=t.a,i=t.b,a=e.l-r,o=e.a-n,s=e.b-i;return function(t){return pt(r+a*t,n+o*t,i+s*t)+""}}function Bn(t,e){return e-=t,function(r){return Math.round(t+e*r)}}function Dn(t){var e=[t.a,t.b],r=[t.c,t.d],n=Vn(e),i=Un(e,r),a=Vn(qn(r,e,-i))||0;e[0]*r[1]<r[0]*e[1]&&(e[0]*=-1,e[1]*=-1,n*=-1,i*=-1),this.rotate=(n?Math.atan2(e[1],e[0]):Math.atan2(-r[0],r[1]))*Go,this.translate=[t.e,t.f],this.scale=[n,a],this.skew=a?Math.atan2(i,a)*Go:0}function Un(t,e){return t[0]*e[0]+t[1]*e[1]}function Vn(t){var e=Math.sqrt(Un(t,t));return e&&(t[0]/=e,t[1]/=e),e}function qn(t,e,r){return t[0]+=r*e[0],t[1]+=r*e[1],t}function Hn(t){return t.length?t.pop()+",":""}function Gn(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push("translate(",null,",",null,")");n.push({i:i-4,x:bn(t[0],e[0])},{i:i-2,x:bn(t[1],e[1])})}else(e[0]||e[1])&&r.push("translate("+e+")")}function Yn(t,e,r,n){t!==e?(t-e>180?e+=360:e-t>180&&(t+=360),n.push({i:r.push(Hn(r)+"rotate(",null,")")-2,x:bn(t,e)})):e&&r.push(Hn(r)+"rotate("+e+")")}function Xn(t,e,r,n){t!==e?n.push({i:r.push(Hn(r)+"skewX(",null,")")-2,x:bn(t,e)}):e&&r.push(Hn(r)+"skewX("+e+")")}function Wn(t,e,r,n){if(t[0]!==e[0]||t[1]!==e[1]){var i=r.push(Hn(r)+"scale(",null,",",null,")");n.push({i:i-4,x:bn(t[0],e[0])},{i:i-2,x:bn(t[1],e[1])})}else(1!==e[0]||1!==e[1])&&r.push(Hn(r)+"scale("+e+")")}function Zn(t,e){var r=[],n=[];return t=uo.transform(t),e=uo.transform(e),Gn(t.translate,e.translate,r,n),Yn(t.rotate,e.rotate,r,n),Xn(t.skew,e.skew,r,n),Wn(t.scale,e.scale,r,n),t=e=null,function(t){for(var e,i=-1,a=n.length;++i<a;)r[(e=n[i]).i]=e.x(t);return r.join("")}}function $n(t,e){return e=(e-=t=+t)||1/e,function(r){return(r-t)/e}}function Kn(t,e){return e=(e-=t=+t)||1/e,function(r){return Math.max(0,Math.min(1,(r-t)/e))}}function Qn(t){for(var e=t.source,r=t.target,n=ti(e,r),i=[e];e!==n;)e=e.parent,i.push(e);for(var a=i.length;r!==n;)i.splice(a,0,r),r=r.parent;return i}function Jn(t){for(var e=[],r=t.parent;null!=r;)e.push(t),t=r,r=r.parent;return e.push(t),e}function ti(t,e){if(t===e)return t;for(var r=Jn(t),n=Jn(e),i=r.pop(),a=n.pop(),o=null;i===a;)o=i,i=r.pop(),a=n.pop();return o}function ei(t){t.fixed|=2}function ri(t){t.fixed&=-7}function ni(t){t.fixed|=4,t.px=t.x,t.py=t.y}function ii(t){t.fixed&=-5}function ai(t,e,r){var n=0,i=0;if(t.charge=0,!t.leaf)for(var a,o=t.nodes,s=o.length,l=-1;++l<s;)a=o[l],null!=a&&(ai(a,e,r),t.charge+=a.charge,n+=a.charge*a.cx,i+=a.charge*a.cy);if(t.point){t.leaf||(t.point.x+=Math.random()-.5,t.point.y+=Math.random()-.5);var u=e*r[t.point.index];t.charge+=t.pointCharge=u,n+=u*t.point.x,i+=u*t.point.y}t.cx=n/t.charge,t.cy=i/t.charge}function oi(t,e){return uo.rebind(t,e,"sort","children","value"),t.nodes=t,t.links=fi,t}function si(t,e){for(var r=[t];null!=(t=r.pop());)if(e(t),(i=t.children)&&(n=i.length))for(var n,i;--n>=0;)r.push(i[n])}function li(t,e){for(var r=[t],n=[];null!=(t=r.pop());)if(n.push(t),(a=t.children)&&(i=a.length))for(var i,a,o=-1;++o<i;)r.push(a[o]);for(;null!=(t=n.pop());)e(t)}function ui(t){return t.children}function ci(t){return t.value}function hi(t,e){return e.value-t.value}function fi(t){return uo.merge(t.map(function(t){return(t.children||[]).map(function(e){return{source:t,target:e}})}))}function di(t){return t.x}function pi(t){return t.y}function gi(t,e,r){t.y0=e,t.y=r}function vi(t){return uo.range(t.length)}function mi(t){for(var e=-1,r=t[0].length,n=[];++e<r;)n[e]=0;return n}function yi(t){for(var e,r=1,n=0,i=t[0][1],a=t.length;a>r;++r)(e=t[r][1])>i&&(n=r,i=e);return n}function bi(t){return t.reduce(xi,0)}function xi(t,e){return t+e[1]}function _i(t,e){return wi(t,Math.ceil(Math.log(e.length)/Math.LN2+1))}function wi(t,e){for(var r=-1,n=+t[0],i=(t[1]-n)/e,a=[];++r<=e;)a[r]=i*r+n;return a}function Ai(t){return[uo.min(t),uo.max(t)]}function ki(t,e){return t.value-e.value}function Mi(t,e){var r=t._pack_next;t._pack_next=e,e._pack_prev=t,e._pack_next=r,r._pack_prev=e}function Ti(t,e){t._pack_next=e,e._pack_prev=t}function Ei(t,e){var r=e.x-t.x,n=e.y-t.y,i=t.r+e.r;return.999*i*i>r*r+n*n}function Li(t){function e(t){c=Math.min(t.x-t.r,c),h=Math.max(t.x+t.r,h),f=Math.min(t.y-t.r,f),d=Math.max(t.y+t.r,d)}if((r=t.children)&&(u=r.length)){var r,n,i,a,o,s,l,u,c=1/0,h=-(1/0),f=1/0,d=-(1/0);if(r.forEach(Si),n=r[0],n.x=-n.r,n.y=0,e(n),u>1&&(i=r[1],i.x=i.r,i.y=0,e(i),u>2))for(a=r[2],zi(n,i,a),e(a),Mi(n,a),n._pack_prev=a,Mi(a,i),i=n._pack_next,o=3;u>o;o++){zi(n,i,a=r[o]);var p=0,g=1,v=1;for(s=i._pack_next;s!==i;s=s._pack_next,g++)if(Ei(s,a)){p=1;break}if(1==p)for(l=n._pack_prev;l!==s._pack_prev&&!Ei(l,a);l=l._pack_prev,v++);p?(v>g||g==v&&i.r<n.r?Ti(n,i=s):Ti(n=l,i),o--):(Mi(n,a),i=a,e(a))}var m=(c+h)/2,y=(f+d)/2,b=0;for(o=0;u>o;o++)a=r[o],a.x-=m,a.y-=y,b=Math.max(b,a.r+Math.sqrt(a.x*a.x+a.y*a.y));t.r=b,r.forEach(Ci)}}function Si(t){t._pack_next=t._pack_prev=t}function Ci(t){delete t._pack_next,delete t._pack_prev}function Pi(t,e,r,n){var i=t.children;if(t.x=e+=n*t.x,t.y=r+=n*t.y,t.r*=n,i)for(var a=-1,o=i.length;++a<o;)Pi(i[a],e,r,n)}function zi(t,e,r){var n=t.r+r.r,i=e.x-t.x,a=e.y-t.y;if(n&&(i||a)){var o=e.r+r.r,s=i*i+a*a;o*=o,n*=n;var l=.5+(n-o)/(2*s),u=Math.sqrt(Math.max(0,2*o*(n+s)-(n-=s)*n-o*o))/(2*s);r.x=t.x+l*i+u*a,r.y=t.y+l*a-u*i}else r.x=t.x+n,r.y=t.y}function Ri(t,e){return t.parent==e.parent?1:2}function Oi(t){var e=t.children;return e.length?e[0]:t.t}function Ii(t){var e,r=t.children;return(e=r.length)?r[e-1]:t.t}function ji(t,e,r){var n=r/(e.i-t.i);e.c-=n,e.s+=r,t.c+=n,e.z+=r,e.m+=r}function Ni(t){for(var e,r=0,n=0,i=t.children,a=i.length;--a>=0;)e=i[a],e.z+=r,e.m+=r,r+=e.s+(n+=e.c)}function Fi(t,e,r){return t.a.parent===e.parent?t.a:r}function Bi(t){return 1+uo.max(t,function(t){return t.y})}function Di(t){return t.reduce(function(t,e){return t+e.x},0)/t.length}function Ui(t){var e=t.children;return e&&e.length?Ui(e[0]):t}function Vi(t){var e,r=t.children;return r&&(e=r.length)?Vi(r[e-1]):t}function qi(t){return{x:t.x,y:t.y,dx:t.dx,dy:t.dy}}function Hi(t,e){var r=t.x+e[3],n=t.y+e[0],i=t.dx-e[1]-e[3],a=t.dy-e[0]-e[2];return 0>i&&(r+=i/2,i=0),0>a&&(n+=a/2,a=0),{x:r,y:n,dx:i,dy:a}}function Gi(t){var e=t[0],r=t[t.length-1];return r>e?[e,r]:[r,e]}function Yi(t){return t.rangeExtent?t.rangeExtent():Gi(t.range())}function Xi(t,e,r,n){var i=r(t[0],t[1]),a=n(e[0],e[1]);return function(t){return a(i(t))}}function Wi(t,e){var r,n=0,i=t.length-1,a=t[n],o=t[i];return a>o&&(r=n,n=i,i=r,r=a,a=o,o=r),t[n]=e.floor(a),t[i]=e.ceil(o),t}function Zi(t){return t?{floor:function(e){return Math.floor(e/t)*t},ceil:function(e){return Math.ceil(e/t)*t}}:Ml}function $i(t,e,r,n){var i=[],a=[],o=0,s=Math.min(t.length,e.length)-1;for(t[s]<t[0]&&(t=t.slice().reverse(),e=e.slice().reverse());++o<=s;)i.push(r(t[o-1],t[o])),a.push(n(e[o-1],e[o]));return function(e){var r=uo.bisect(t,e,1,s)-1;return a[r](i[r](e))}}function Ki(t,e,r,n){function i(){var i=Math.min(t.length,e.length)>2?$i:Xi,l=n?Kn:$n;return o=i(t,e,l,r),s=i(e,t,l,_n),a}function a(t){return o(t)}var o,s;return a.invert=function(t){return s(t)},a.domain=function(e){return arguments.length?(t=e.map(Number),i()):t},a.range=function(t){return arguments.length?(e=t,i()):e},a.rangeRound=function(t){return a.range(t).interpolate(Bn)},a.clamp=function(t){return arguments.length?(n=t,i()):n},a.interpolate=function(t){return arguments.length?(r=t,i()):r},a.ticks=function(e){return ea(t,e)},a.tickFormat=function(e,r){return ra(t,e,r)},a.nice=function(e){return Ji(t,e),i()},a.copy=function(){return Ki(t,e,r,n)},i()}function Qi(t,e){return uo.rebind(t,e,"range","rangeRound","interpolate","clamp")}function Ji(t,e){return Wi(t,Zi(ta(t,e)[2])),Wi(t,Zi(ta(t,e)[2])),t}function ta(t,e){null==e&&(e=10);var r=Gi(t),n=r[1]-r[0],i=Math.pow(10,Math.floor(Math.log(n/e)/Math.LN10)),a=e/n*i;return.15>=a?i*=10:.35>=a?i*=5:.75>=a&&(i*=2),r[0]=Math.ceil(r[0]/i)*i,r[1]=Math.floor(r[1]/i)*i+.5*i,r[2]=i,r}function ea(t,e){return uo.range.apply(uo,ta(t,e))}function ra(t,e,r){var n=ta(t,e);if(r){var i=ds.exec(r);if(i.shift(),"s"===i[8]){var a=uo.formatPrefix(Math.max(wo(n[0]),wo(n[1])));return i[7]||(i[7]="."+na(a.scale(n[2]))),i[8]="f",r=uo.format(i.join("")),function(t){return r(a.scale(t))+a.symbol}}i[7]||(i[7]="."+ia(i[8],n)),r=i.join("")}else r=",."+na(n[2])+"f";return uo.format(r)}function na(t){return-Math.floor(Math.log(t)/Math.LN10+.01)}function ia(t,e){var r=na(e[2]);return t in Tl?Math.abs(r-na(Math.max(wo(e[0]),wo(e[1]))))+ +("e"!==t):r-2*("%"===t)}function aa(t,e,r,n){function i(t){return(r?Math.log(0>t?0:t):-Math.log(t>0?0:-t))/Math.log(e)}function a(t){return r?Math.pow(e,t):-Math.pow(e,-t)}function o(e){return t(i(e))}return o.invert=function(e){return a(t.invert(e))},o.domain=function(e){return arguments.length?(r=e[0]>=0,t.domain((n=e.map(Number)).map(i)),o):n},o.base=function(r){return arguments.length?(e=+r,t.domain(n.map(i)),o):e},o.nice=function(){var e=Wi(n.map(i),r?Math:Ll);return t.domain(e),n=e.map(a),o},o.ticks=function(){var t=Gi(n),o=[],s=t[0],l=t[1],u=Math.floor(i(s)),c=Math.ceil(i(l)),h=e%1?2:e;if(isFinite(c-u)){if(r){for(;c>u;u++)for(var f=1;h>f;f++)o.push(a(u)*f);o.push(a(u))}else for(o.push(a(u));u++<c;)for(var f=h-1;f>0;f--)o.push(a(u)*f);for(u=0;o[u]<s;u++);for(c=o.length;o[c-1]>l;c--);o=o.slice(u,c)}return o},o.tickFormat=function(t,r){if(!arguments.length)return El;arguments.length<2?r=El:"function"!=typeof r&&(r=uo.format(r));var n=Math.max(1,e*t/o.ticks().length);return function(t){var o=t/a(Math.round(i(t)));return e-.5>o*e&&(o*=e),n>=o?r(t):""}},o.copy=function(){return aa(t.copy(),e,r,n)},Qi(o,t)}function oa(t,e,r){function n(e){return t(i(e))}var i=sa(e),a=sa(1/e);return n.invert=function(e){return a(t.invert(e))},n.domain=function(e){return arguments.length?(t.domain((r=e.map(Number)).map(i)),n):r},n.ticks=function(t){return ea(r,t)},n.tickFormat=function(t,e){return ra(r,t,e)},n.nice=function(t){return n.domain(Ji(r,t))},n.exponent=function(o){return arguments.length?(i=sa(e=o),a=sa(1/e),t.domain(r.map(i)),n):e},n.copy=function(){return oa(t.copy(),e,r)},Qi(n,t)}function sa(t){return function(e){return 0>e?-Math.pow(-e,t):Math.pow(e,t)}}function la(t,e){function r(r){return a[((i.get(r)||("range"===e.t?i.set(r,t.push(r)):NaN))-1)%a.length]}function n(e,r){return uo.range(t.length).map(function(t){return e+r*t})}var i,a,o;return r.domain=function(n){if(!arguments.length)return t;t=[],i=new h;for(var a,o=-1,s=n.length;++o<s;)i.has(a=n[o])||i.set(a,t.push(a));return r[e.t].apply(r,e.a)},r.range=function(t){return arguments.length?(a=t,o=0,e={t:"range",a:arguments},r):a},r.rangePoints=function(i,s){arguments.length<2&&(s=0);var l=i[0],u=i[1],c=t.length<2?(l=(l+u)/2,0):(u-l)/(t.length-1+s);return a=n(l+c*s/2,c),o=0,e={t:"rangePoints",a:arguments},r},r.rangeRoundPoints=function(i,s){arguments.length<2&&(s=0);var l=i[0],u=i[1],c=t.length<2?(l=u=Math.round((l+u)/2),0):(u-l)/(t.length-1+s)|0;return a=n(l+Math.round(c*s/2+(u-l-(t.length-1+s)*c)/2),c),o=0,e={t:"rangeRoundPoints",a:arguments},r},r.rangeBands=function(i,s,l){arguments.length<2&&(s=0),arguments.length<3&&(l=s);var u=i[1]<i[0],c=i[u-0],h=i[1-u],f=(h-c)/(t.length-s+2*l);return a=n(c+f*l,f),u&&a.reverse(),o=f*(1-s),e={t:"rangeBands",a:arguments},r},r.rangeRoundBands=function(i,s,l){arguments.length<2&&(s=0),arguments.length<3&&(l=s);var u=i[1]<i[0],c=i[u-0],h=i[1-u],f=Math.floor((h-c)/(t.length-s+2*l));return a=n(c+Math.round((h-c-(t.length-s)*f)/2),f),u&&a.reverse(),o=Math.round(f*(1-s)),e={t:"rangeRoundBands",a:arguments},r},r.rangeBand=function(){return o},r.rangeExtent=function(){return Gi(e.a[0])},r.copy=function(){return la(t,e)},r.domain(t)}function ua(t,e){function r(){var r=0,i=e.length;for(s=[];++r<i;)s[r-1]=uo.quantile(t,r/i);return n}function n(t){return isNaN(t=+t)?void 0:e[uo.bisect(s,t)]}var s;return n.domain=function(e){return arguments.length?(t=e.map(a).filter(o).sort(i),r()):t},n.range=function(t){return arguments.length?(e=t,r()):e},n.quantiles=function(){return s},n.invertExtent=function(r){return r=e.indexOf(r),0>r?[NaN,NaN]:[r>0?s[r-1]:t[0],r<s.length?s[r]:t[t.length-1]]},n.copy=function(){return ua(t,e)},r()}function ca(t,e,r){function n(e){return r[Math.max(0,Math.min(o,Math.floor(a*(e-t))))]}function i(){return a=r.length/(e-t),o=r.length-1,n}var a,o;return n.domain=function(r){return arguments.length?(t=+r[0],e=+r[r.length-1],i()):[t,e]},n.range=function(t){return arguments.length?(r=t,i()):r},n.invertExtent=function(e){return e=r.indexOf(e),e=0>e?NaN:e/a+t,[e,e+1/a]},n.copy=function(){return ca(t,e,r)},i()}function ha(t,e){function r(r){return r>=r?e[uo.bisect(t,r)]:void 0}return r.domain=function(e){return arguments.length?(t=e,r):t},r.range=function(t){return arguments.length?(e=t,r):e},r.invertExtent=function(r){return r=e.indexOf(r),[t[r-1],t[r]]},r.copy=function(){return ha(t,e)},r}function fa(t){function e(t){return+t}return e.invert=e,e.domain=e.range=function(r){return arguments.length?(t=r.map(e),e):t},e.ticks=function(e){return ea(t,e)},e.tickFormat=function(e,r){return ra(t,e,r)},e.copy=function(){return fa(t)},e}function da(){return 0}function pa(t){return t.innerRadius}function ga(t){return t.outerRadius}function va(t){return t.startAngle}function ma(t){return t.endAngle}function ya(t){return t&&t.padAngle}function ba(t,e,r,n){return(t-r)*e-(e-n)*t>0?0:1}function xa(t,e,r,n,i){var a=t[0]-e[0],o=t[1]-e[1],s=(i?n:-n)/Math.sqrt(a*a+o*o),l=s*o,u=-s*a,c=t[0]+l,h=t[1]+u,f=e[0]+l,d=e[1]+u,p=(c+f)/2,g=(h+d)/2,v=f-c,m=d-h,y=v*v+m*m,b=r-n,x=c*d-f*h,_=(0>m?-1:1)*Math.sqrt(Math.max(0,b*b*y-x*x)),w=(x*m-v*_)/y,A=(-x*v-m*_)/y,k=(x*m+v*_)/y,M=(-x*v+m*_)/y,T=w-p,E=A-g,L=k-p,S=M-g;return T*T+E*E>L*L+S*S&&(w=k,A=M),[[w-l,A-u],[w*r/b,A*r/b]]}function _a(t){function e(e){function o(){u.push("M",a(t(c),s))}for(var l,u=[],c=[],h=-1,f=e.length,d=Lt(r),p=Lt(n);++h<f;)i.call(this,l=e[h],h)?c.push([+d.call(this,l,h),+p.call(this,l,h)]):c.length&&(o(),c=[]);return c.length&&o(),u.length?u.join(""):null}var r=Cr,n=Pr,i=Pe,a=wa,o=a.key,s=.7;return e.x=function(t){return arguments.length?(r=t,e):r},e.y=function(t){return arguments.length?(n=t,e):n},e.defined=function(t){return arguments.length?(i=t,e):i},e.interpolate=function(t){return arguments.length?(o="function"==typeof t?a=t:(a=Ol.get(t)||wa).key,e):o},e.tension=function(t){return arguments.length?(s=t,e):s},e}function wa(t){return t.length>1?t.join("L"):t+"Z"}function Aa(t){return t.join("L")+"Z"}function ka(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e<r;)i.push("H",(n[0]+(n=t[e])[0])/2,"V",n[1]);return r>1&&i.push("H",n[0]),i.join("")}function Ma(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e<r;)i.push("V",(n=t[e])[1],"H",n[0]);return i.join("")}function Ta(t){for(var e=0,r=t.length,n=t[0],i=[n[0],",",n[1]];++e<r;)i.push("H",(n=t[e])[0],"V",n[1]);return i.join("")}function Ea(t,e){return t.length<4?wa(t):t[1]+Ca(t.slice(1,-1),Pa(t,e))}function La(t,e){return t.length<3?Aa(t):t[0]+Ca((t.push(t[0]),t),Pa([t[t.length-2]].concat(t,[t[1]]),e))}function Sa(t,e){return t.length<3?wa(t):t[0]+Ca(t,Pa(t,e))}function Ca(t,e){if(e.length<1||t.length!=e.length&&t.length!=e.length+2)return wa(t);var r=t.length!=e.length,n="",i=t[0],a=t[1],o=e[0],s=o,l=1;if(r&&(n+="Q"+(a[0]-2*o[0]/3)+","+(a[1]-2*o[1]/3)+","+a[0]+","+a[1],i=t[1],l=2),e.length>1){s=e[1],a=t[l],l++,n+="C"+(i[0]+o[0])+","+(i[1]+o[1])+","+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1];for(var u=2;u<e.length;u++,l++)a=t[l],s=e[u],n+="S"+(a[0]-s[0])+","+(a[1]-s[1])+","+a[0]+","+a[1]}if(r){var c=t[l];n+="Q"+(a[0]+2*s[0]/3)+","+(a[1]+2*s[1]/3)+","+c[0]+","+c[1]}return n}function Pa(t,e){for(var r,n=[],i=(1-e)/2,a=t[0],o=t[1],s=1,l=t.length;++s<l;)r=a,a=o,o=t[s],n.push([i*(o[0]-r[0]),i*(o[1]-r[1])]);return n}function za(t){if(t.length<3)return wa(t);var e=1,r=t.length,n=t[0],i=n[0],a=n[1],o=[i,i,i,(n=t[1])[0]],s=[a,a,a,n[1]],l=[i,",",a,"L",ja(Nl,o),",",ja(Nl,s)];for(t.push(t[r-1]);++e<=r;)n=t[e],o.shift(),o.push(n[0]),s.shift(),s.push(n[1]),Na(l,o,s);return t.pop(),l.push("L",n),l.join("")}function Ra(t){if(t.length<4)return wa(t);for(var e,r=[],n=-1,i=t.length,a=[0],o=[0];++n<3;)e=t[n],a.push(e[0]),o.push(e[1]);for(r.push(ja(Nl,a)+","+ja(Nl,o)),--n;++n<i;)e=t[n],a.shift(),a.push(e[0]),o.shift(),o.push(e[1]),Na(r,a,o);return r.join("")}function Oa(t){for(var e,r,n=-1,i=t.length,a=i+4,o=[],s=[];++n<4;)r=t[n%i],o.push(r[0]),s.push(r[1]);for(e=[ja(Nl,o),",",ja(Nl,s)],--n;++n<a;)r=t[n%i],o.shift(),o.push(r[0]),s.shift(),s.push(r[1]),Na(e,o,s);return e.join("")}function Ia(t,e){var r=t.length-1;if(r)for(var n,i,a=t[0][0],o=t[0][1],s=t[r][0]-a,l=t[r][1]-o,u=-1;++u<=r;)n=t[u],i=u/r,n[0]=e*n[0]+(1-e)*(a+i*s),n[1]=e*n[1]+(1-e)*(o+i*l);return za(t)}function ja(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Na(t,e,r){t.push("C",ja(Il,e),",",ja(Il,r),",",ja(jl,e),",",ja(jl,r),",",ja(Nl,e),",",ja(Nl,r))}function Fa(t,e){return(e[1]-t[1])/(e[0]-t[0])}function Ba(t){for(var e=0,r=t.length-1,n=[],i=t[0],a=t[1],o=n[0]=Fa(i,a);++e<r;)n[e]=(o+(o=Fa(i=a,a=t[e+1])))/2;return n[e]=o,n}function Da(t){for(var e,r,n,i,a=[],o=Ba(t),s=-1,l=t.length-1;++s<l;)e=Fa(t[s],t[s+1]),wo(e)<Fo?o[s]=o[s+1]=0:(r=o[s]/e,n=o[s+1]/e,i=r*r+n*n,i>9&&(i=3*e/Math.sqrt(i),o[s]=i*r,o[s+1]=i*n));for(s=-1;++s<=l;)i=(t[Math.min(l,s+1)][0]-t[Math.max(0,s-1)][0])/(6*(1+o[s]*o[s])),a.push([i||0,o[s]*i||0]);return a}function Ua(t){return t.length<3?wa(t):t[0]+Ca(t,Da(t))}function Va(t){for(var e,r,n,i=-1,a=t.length;++i<a;)e=t[i],r=e[0],n=e[1]-qo,e[0]=r*Math.cos(n),e[1]=r*Math.sin(n);return t}function qa(t){function e(e){function l(){g.push("M",s(t(m),h),c,u(t(v.reverse()),h),"Z")}for(var f,d,p,g=[],v=[],m=[],y=-1,b=e.length,x=Lt(r),_=Lt(i),w=r===n?function(){return d}:Lt(n),A=i===a?function(){return p}:Lt(a);++y<b;)o.call(this,f=e[y],y)?(v.push([d=+x.call(this,f,y),p=+_.call(this,f,y)]),m.push([+w.call(this,f,y),+A.call(this,f,y)])):v.length&&(l(),v=[],m=[]);return v.length&&l(),g.length?g.join(""):null}var r=Cr,n=Cr,i=0,a=Pr,o=Pe,s=wa,l=s.key,u=s,c="L",h=.7;return e.x=function(t){return arguments.length?(r=n=t,e):n},e.x0=function(t){return arguments.length?(r=t,e):r},e.x1=function(t){return arguments.length?(n=t,e):n},e.y=function(t){return arguments.length?(i=a=t,e):a},e.y0=function(t){return arguments.length?(i=t,e):i},e.y1=function(t){return arguments.length?(a=t,e):a},e.defined=function(t){return arguments.length?(o=t,e):o},e.interpolate=function(t){return arguments.length?(l="function"==typeof t?s=t:(s=Ol.get(t)||wa).key,u=s.reverse||s,c=s.closed?"M":"L",e):l},e.tension=function(t){return arguments.length?(h=t,e):h},e}function Ha(t){return t.radius}function Ga(t){return[t.x,t.y]}function Ya(t){return function(){var e=t.apply(this,arguments),r=e[0],n=e[1]-qo;return[r*Math.cos(n),r*Math.sin(n)]}}function Xa(){return 64}function Wa(){return"circle"}function Za(t){var e=Math.sqrt(t/Do);return"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+-e+"A"+e+","+e+" 0 1,1 0,"+e+"Z"}function $a(t){return function(){var e,r,n;(e=this[t])&&(n=e[r=e.active])&&(n.timer.c=null,n.timer.t=NaN,--e.count?delete e[r]:delete this[t],e.active+=.5,n.event&&n.event.interrupt.call(this,this.__data__,n.index))}}function Ka(t,e,r){return Eo(t,Hl),t.namespace=e,t.id=r,t}function Qa(t,e,r,n){var i=t.id,a=t.namespace;return G(t,"function"==typeof r?function(t,o,s){t[a][i].tween.set(e,n(r.call(t,t.__data__,o,s)))}:(r=n(r),function(t){t[a][i].tween.set(e,r)}))}function Ja(t){return null==t&&(t=""),function(){this.textContent=t}}function to(t){return null==t?"__transition__":"__transition_"+t+"__"}function eo(t,e,r,n,i){function a(t){var e=g.delay;return u.t=e+l,t>=e?o(t-e):void(u.c=o)}function o(r){var i=p.active,a=p[i];a&&(a.timer.c=null,a.timer.t=NaN,--p.count,delete p[i],a.event&&a.event.interrupt.call(t,t.__data__,a.index));for(var o in p)if(n>+o){var h=p[o];h.timer.c=null,h.timer.t=NaN,--p.count,delete p[o]}u.c=s,Rt(function(){return u.c&&s(r||1)&&(u.c=null,u.t=NaN),1},0,l),p.active=n,g.event&&g.event.start.call(t,t.__data__,e),d=[],g.tween.forEach(function(r,n){(n=n.call(t,t.__data__,e))&&d.push(n)}),f=g.ease,c=g.duration}function s(i){for(var a=i/c,o=f(a),s=d.length;s>0;)d[--s].call(t,o);return a>=1?(g.event&&g.event.end.call(t,t.__data__,e),--p.count?delete p[n]:delete t[r],1):void 0}var l,u,c,f,d,p=t[r]||(t[r]={active:0,count:0}),g=p[n];g||(l=i.time,u=Rt(a,0,l),g=p[n]={tween:new h,time:l,timer:u,delay:i.delay,duration:i.duration,ease:i.ease,index:e},i=null,++p.count)}function ro(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate("+(isFinite(n)?n:r(t))+",0)"})}function no(t,e,r){t.attr("transform",function(t){var n=e(t);return"translate(0,"+(isFinite(n)?n:r(t))+")"})}function io(t){return t.toISOString()}function ao(t,e,r){function n(e){return t(e)}function i(t,r){var n=t[1]-t[0],i=n/r,a=uo.bisect(Jl,i);return a==Jl.length?[e.year,ta(t.map(function(t){return t/31536e6}),r)[2]]:a?e[i/Jl[a-1]<Jl[a]/i?a-1:a]:[ru,ta(t,r)[2]]}return n.invert=function(e){return oo(t.invert(e))},n.domain=function(e){return arguments.length?(t.domain(e),n):t.domain().map(oo)},n.nice=function(t,e){function r(r){return!isNaN(r)&&!t.range(r,oo(+r+1),e).length}var a=n.domain(),o=Gi(a),s=null==t?i(o,10):"number"==typeof t&&i(o,t);return s&&(t=s[0],e=s[1]),n.domain(Wi(a,e>1?{floor:function(e){for(;r(e=t.floor(e));)e=oo(e-1);return e},ceil:function(e){for(;r(e=t.ceil(e));)e=oo(+e+1);return e}}:t))},n.ticks=function(t,e){var r=Gi(n.domain()),a=null==t?i(r,10):"number"==typeof t?i(r,t):!t.range&&[{range:t},e];return a&&(t=a[0],e=a[1]),t.range(r[0],oo(+r[1]+1),1>e?1:e)},n.tickFormat=function(){return r},n.copy=function(){return ao(t.copy(),e,r)},Qi(n,t)}function oo(t){return new Date(t)}function so(t){return JSON.parse(t.responseText)}function lo(t){var e=fo.createRange();return e.selectNode(fo.body),e.createContextualFragment(t.responseText)}var uo={version:"3.5.13"},co=[].slice,ho=function(t){return co.call(t)},fo=this.document;if(fo)try{ho(fo.documentElement.childNodes)[0].nodeType}catch(po){ho=function(t){for(var e=t.length,r=new Array(e);e--;)r[e]=t[e];return r}}if(Date.now||(Date.now=function(){return+new Date}),fo)try{fo.createElement("DIV").style.setProperty("opacity",0,"")}catch(go){var vo=this.Element.prototype,mo=vo.setAttribute,yo=vo.setAttributeNS,bo=this.CSSStyleDeclaration.prototype,xo=bo.setProperty;vo.setAttribute=function(t,e){mo.call(this,t,e+"")},vo.setAttributeNS=function(t,e,r){yo.call(this,t,e,r+"")},bo.setProperty=function(t,e,r){xo.call(this,t,e+"",r)}}uo.ascending=i,uo.descending=function(t,e){return t>e?-1:e>t?1:e>=t?0:NaN},uo.min=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i<a;)if(null!=(n=t[i])&&n>=n){r=n;break}for(;++i<a;)null!=(n=t[i])&&r>n&&(r=n)}else{for(;++i<a;)if(null!=(n=e.call(t,t[i],i))&&n>=n){r=n;break}for(;++i<a;)null!=(n=e.call(t,t[i],i))&&r>n&&(r=n)}return r},uo.max=function(t,e){var r,n,i=-1,a=t.length;if(1===arguments.length){for(;++i<a;)if(null!=(n=t[i])&&n>=n){r=n;break}for(;++i<a;)null!=(n=t[i])&&n>r&&(r=n)}else{for(;++i<a;)if(null!=(n=e.call(t,t[i],i))&&n>=n){r=n;break}for(;++i<a;)null!=(n=e.call(t,t[i],i))&&n>r&&(r=n)}return r},uo.extent=function(t,e){var r,n,i,a=-1,o=t.length;if(1===arguments.length){for(;++a<o;)if(null!=(n=t[a])&&n>=n){r=i=n;break}for(;++a<o;)null!=(n=t[a])&&(r>n&&(r=n),n>i&&(i=n))}else{for(;++a<o;)if(null!=(n=e.call(t,t[a],a))&&n>=n){
+r=i=n;break}for(;++a<o;)null!=(n=e.call(t,t[a],a))&&(r>n&&(r=n),n>i&&(i=n))}return[r,i]},uo.sum=function(t,e){var r,n=0,i=t.length,a=-1;if(1===arguments.length)for(;++a<i;)o(r=+t[a])&&(n+=r);else for(;++a<i;)o(r=+e.call(t,t[a],a))&&(n+=r);return n},uo.mean=function(t,e){var r,n=0,i=t.length,s=-1,l=i;if(1===arguments.length)for(;++s<i;)o(r=a(t[s]))?n+=r:--l;else for(;++s<i;)o(r=a(e.call(t,t[s],s)))?n+=r:--l;return l?n/l:void 0},uo.quantile=function(t,e){var r=(t.length-1)*e+1,n=Math.floor(r),i=+t[n-1],a=r-n;return a?i+a*(t[n]-i):i},uo.median=function(t,e){var r,n=[],s=t.length,l=-1;if(1===arguments.length)for(;++l<s;)o(r=a(t[l]))&&n.push(r);else for(;++l<s;)o(r=a(e.call(t,t[l],l)))&&n.push(r);return n.length?uo.quantile(n.sort(i),.5):void 0},uo.variance=function(t,e){var r,n,i=t.length,s=0,l=0,u=-1,c=0;if(1===arguments.length)for(;++u<i;)o(r=a(t[u]))&&(n=r-s,s+=n/++c,l+=n*(r-s));else for(;++u<i;)o(r=a(e.call(t,t[u],u)))&&(n=r-s,s+=n/++c,l+=n*(r-s));return c>1?l/(c-1):void 0},uo.deviation=function(){var t=uo.variance.apply(this,arguments);return t?Math.sqrt(t):t};var _o=s(i);uo.bisectLeft=_o.left,uo.bisect=uo.bisectRight=_o.right,uo.bisector=function(t){return s(1===t.length?function(e,r){return i(t(e),r)}:t)},uo.shuffle=function(t,e,r){(a=arguments.length)<3&&(r=t.length,2>a&&(e=0));for(var n,i,a=r-e;a;)i=Math.random()*a--|0,n=t[a+e],t[a+e]=t[i+e],t[i+e]=n;return t},uo.permute=function(t,e){for(var r=e.length,n=new Array(r);r--;)n[r]=t[e[r]];return n},uo.pairs=function(t){for(var e,r=0,n=t.length-1,i=t[0],a=new Array(0>n?0:n);n>r;)a[r]=[e=i,i=t[++r]];return a},uo.zip=function(){if(!(n=arguments.length))return[];for(var t=-1,e=uo.min(arguments,l),r=new Array(e);++t<e;)for(var n,i=-1,a=r[t]=new Array(n);++i<n;)a[i]=arguments[i][t];return r},uo.transpose=function(t){return uo.zip.apply(uo,t)},uo.keys=function(t){var e=[];for(var r in t)e.push(r);return e},uo.values=function(t){var e=[];for(var r in t)e.push(t[r]);return e},uo.entries=function(t){var e=[];for(var r in t)e.push({key:r,value:t[r]});return e},uo.merge=function(t){for(var e,r,n,i=t.length,a=-1,o=0;++a<i;)o+=t[a].length;for(r=new Array(o);--i>=0;)for(n=t[i],e=n.length;--e>=0;)r[--o]=n[e];return r};var wo=Math.abs;uo.range=function(t,e,r){if(arguments.length<3&&(r=1,arguments.length<2&&(e=t,t=0)),(e-t)/r===1/0)throw new Error("infinite range");var n,i=[],a=u(wo(r)),o=-1;if(t*=a,e*=a,r*=a,0>r)for(;(n=t+r*++o)>e;)i.push(n/a);else for(;(n=t+r*++o)<e;)i.push(n/a);return i},uo.map=function(t,e){var r=new h;if(t instanceof h)t.forEach(function(t,e){r.set(t,e)});else if(Array.isArray(t)){var n,i=-1,a=t.length;if(1===arguments.length)for(;++i<a;)r.set(i,t[i]);else for(;++i<a;)r.set(e.call(t,n=t[i],i),n)}else for(var o in t)r.set(o,t[o]);return r};var Ao="__proto__",ko="\x00";c(h,{has:p,get:function(t){return this._[f(t)]},set:function(t,e){return this._[f(t)]=e},remove:g,keys:v,values:function(){var t=[];for(var e in this._)t.push(this._[e]);return t},entries:function(){var t=[];for(var e in this._)t.push({key:d(e),value:this._[e]});return t},size:m,empty:y,forEach:function(t){for(var e in this._)t.call(this,d(e),this._[e])}}),uo.nest=function(){function t(e,o,s){if(s>=a.length)return n?n.call(i,o):r?o.sort(r):o;for(var l,u,c,f,d=-1,p=o.length,g=a[s++],v=new h;++d<p;)(f=v.get(l=g(u=o[d])))?f.push(u):v.set(l,[u]);return e?(u=e(),c=function(r,n){u.set(r,t(e,n,s))}):(u={},c=function(r,n){u[r]=t(e,n,s)}),v.forEach(c),u}function e(t,r){if(r>=a.length)return t;var n=[],i=o[r++];return t.forEach(function(t,i){n.push({key:t,values:e(i,r)})}),i?n.sort(function(t,e){return i(t.key,e.key)}):n}var r,n,i={},a=[],o=[];return i.map=function(e,r){return t(r,e,0)},i.entries=function(r){return e(t(uo.map,r,0),0)},i.key=function(t){return a.push(t),i},i.sortKeys=function(t){return o[a.length-1]=t,i},i.sortValues=function(t){return r=t,i},i.rollup=function(t){return n=t,i},i},uo.set=function(t){var e=new b;if(t)for(var r=0,n=t.length;n>r;++r)e.add(t[r]);return e},c(b,{has:p,add:function(t){return this._[f(t+="")]=!0,t},remove:g,values:v,size:m,empty:y,forEach:function(t){for(var e in this._)t.call(this,d(e))}}),uo.behavior={},uo.rebind=function(t,e){for(var r,n=1,i=arguments.length;++n<i;)t[r=arguments[n]]=_(t,e,e[r]);return t};var Mo=["webkit","ms","moz","Moz","o","O"];uo.dispatch=function(){for(var t=new k,e=-1,r=arguments.length;++e<r;)t[arguments[e]]=M(t);return t},k.prototype.on=function(t,e){var r=t.indexOf("."),n="";if(r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),t)return arguments.length<2?this[t].on(n):this[t].on(n,e);if(2===arguments.length){if(null==e)for(t in this)this.hasOwnProperty(t)&&this[t].on(n,null);return this}},uo.event=null,uo.requote=function(t){return t.replace(To,"\\$&")};var To=/[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g,Eo={}.__proto__?function(t,e){t.__proto__=e}:function(t,e){for(var r in e)t[r]=e[r]},Lo=function(t,e){return e.querySelector(t)},So=function(t,e){return e.querySelectorAll(t)},Co=function(t,e){var r=t.matches||t[w(t,"matchesSelector")];return(Co=function(t,e){return r.call(t,e)})(t,e)};"function"==typeof Sizzle&&(Lo=function(t,e){return Sizzle(t,e)[0]||null},So=Sizzle,Co=Sizzle.matchesSelector),uo.selection=function(){return uo.select(fo.documentElement)};var Po=uo.selection.prototype=[];Po.select=function(t){var e,r,n,i,a=[];t=C(t);for(var o=-1,s=this.length;++o<s;){a.push(e=[]),e.parentNode=(n=this[o]).parentNode;for(var l=-1,u=n.length;++l<u;)(i=n[l])?(e.push(r=t.call(i,i.__data__,l,o)),r&&"__data__"in i&&(r.__data__=i.__data__)):e.push(null)}return S(a)},Po.selectAll=function(t){var e,r,n=[];t=P(t);for(var i=-1,a=this.length;++i<a;)for(var o=this[i],s=-1,l=o.length;++s<l;)(r=o[s])&&(n.push(e=ho(t.call(r,r.__data__,s,i))),e.parentNode=r);return S(n)};var zo={svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};uo.ns={prefix:zo,qualify:function(t){var e=t.indexOf(":"),r=t;return e>=0&&"xmlns"!==(r=t.slice(0,e))&&(t=t.slice(e+1)),zo.hasOwnProperty(r)?{space:zo[r],local:t}:t}},Po.attr=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node();return t=uo.ns.qualify(t),t.local?r.getAttributeNS(t.space,t.local):r.getAttribute(t)}for(e in t)this.each(z(e,t[e]));return this}return this.each(z(t,e))},Po.classed=function(t,e){if(arguments.length<2){if("string"==typeof t){var r=this.node(),n=(t=I(t)).length,i=-1;if(e=r.classList){for(;++i<n;)if(!e.contains(t[i]))return!1}else for(e=r.getAttribute("class");++i<n;)if(!O(t[i]).test(e))return!1;return!0}for(e in t)this.each(j(e,t[e]));return this}return this.each(j(t,e))},Po.style=function(t,e,r){var i=arguments.length;if(3>i){if("string"!=typeof t){2>i&&(e="");for(r in t)this.each(F(r,t[r],e));return this}if(2>i){var a=this.node();return n(a).getComputedStyle(a,null).getPropertyValue(t)}r=""}return this.each(F(t,e,r))},Po.property=function(t,e){if(arguments.length<2){if("string"==typeof t)return this.node()[t];for(e in t)this.each(B(e,t[e]));return this}return this.each(B(t,e))},Po.text=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.textContent=null==e?"":e}:null==t?function(){this.textContent=""}:function(){this.textContent=t}):this.node().textContent},Po.html=function(t){return arguments.length?this.each("function"==typeof t?function(){var e=t.apply(this,arguments);this.innerHTML=null==e?"":e}:null==t?function(){this.innerHTML=""}:function(){this.innerHTML=t}):this.node().innerHTML},Po.append=function(t){return t=D(t),this.select(function(){return this.appendChild(t.apply(this,arguments))})},Po.insert=function(t,e){return t=D(t),e=C(e),this.select(function(){return this.insertBefore(t.apply(this,arguments),e.apply(this,arguments)||null)})},Po.remove=function(){return this.each(U)},Po.data=function(t,e){function r(t,r){var n,i,a,o=t.length,c=r.length,f=Math.min(o,c),d=new Array(c),p=new Array(c),g=new Array(o);if(e){var v,m=new h,y=new Array(o);for(n=-1;++n<o;)(i=t[n])&&(m.has(v=e.call(i,i.__data__,n))?g[n]=i:m.set(v,i),y[n]=v);for(n=-1;++n<c;)(i=m.get(v=e.call(r,a=r[n],n)))?i!==!0&&(d[n]=i,i.__data__=a):p[n]=V(a),m.set(v,!0);for(n=-1;++n<o;)n in y&&m.get(y[n])!==!0&&(g[n]=t[n])}else{for(n=-1;++n<f;)i=t[n],a=r[n],i?(i.__data__=a,d[n]=i):p[n]=V(a);for(;c>n;++n)p[n]=V(r[n]);for(;o>n;++n)g[n]=t[n]}p.update=d,p.parentNode=d.parentNode=g.parentNode=t.parentNode,s.push(p),l.push(d),u.push(g)}var n,i,a=-1,o=this.length;if(!arguments.length){for(t=new Array(o=(n=this[0]).length);++a<o;)(i=n[a])&&(t[a]=i.__data__);return t}var s=Y([]),l=S([]),u=S([]);if("function"==typeof t)for(;++a<o;)r(n=this[a],t.call(n,n.parentNode.__data__,a));else for(;++a<o;)r(n=this[a],t);return l.enter=function(){return s},l.exit=function(){return u},l},Po.datum=function(t){return arguments.length?this.property("__data__",t):this.property("__data__")},Po.filter=function(t){var e,r,n,i=[];"function"!=typeof t&&(t=q(t));for(var a=0,o=this.length;o>a;a++){i.push(e=[]),e.parentNode=(r=this[a]).parentNode;for(var s=0,l=r.length;l>s;s++)(n=r[s])&&t.call(n,n.__data__,s,a)&&e.push(n)}return S(i)},Po.order=function(){for(var t=-1,e=this.length;++t<e;)for(var r,n=this[t],i=n.length-1,a=n[i];--i>=0;)(r=n[i])&&(a&&a!==r.nextSibling&&a.parentNode.insertBefore(r,a),a=r);return this},Po.sort=function(t){t=H.apply(this,arguments);for(var e=-1,r=this.length;++e<r;)this[e].sort(t);return this.order()},Po.each=function(t){return G(this,function(e,r,n){t.call(e,e.__data__,r,n)})},Po.call=function(t){var e=ho(arguments);return t.apply(e[0]=this,e),this},Po.empty=function(){return!this.node()},Po.node=function(){for(var t=0,e=this.length;e>t;t++)for(var r=this[t],n=0,i=r.length;i>n;n++){var a=r[n];if(a)return a}return null},Po.size=function(){var t=0;return G(this,function(){++t}),t};var Ro=[];uo.selection.enter=Y,uo.selection.enter.prototype=Ro,Ro.append=Po.append,Ro.empty=Po.empty,Ro.node=Po.node,Ro.call=Po.call,Ro.size=Po.size,Ro.select=function(t){for(var e,r,n,i,a,o=[],s=-1,l=this.length;++s<l;){n=(i=this[s]).update,o.push(e=[]),e.parentNode=i.parentNode;for(var u=-1,c=i.length;++u<c;)(a=i[u])?(e.push(n[u]=r=t.call(i.parentNode,a.__data__,u,s)),r.__data__=a.__data__):e.push(null)}return S(o)},Ro.insert=function(t,e){return arguments.length<2&&(e=X(this)),Po.insert.call(this,t,e)},uo.select=function(t){var r;return"string"==typeof t?(r=[Lo(t,fo)],r.parentNode=fo.documentElement):(r=[t],r.parentNode=e(t)),S([r])},uo.selectAll=function(t){var e;return"string"==typeof t?(e=ho(So(t,fo)),e.parentNode=fo.documentElement):(e=ho(t),e.parentNode=null),S([e])},Po.on=function(t,e,r){var n=arguments.length;if(3>n){if("string"!=typeof t){2>n&&(e=!1);for(r in t)this.each(W(r,t[r],e));return this}if(2>n)return(n=this.node()["__on"+t])&&n._;r=!1}return this.each(W(t,e,r))};var Oo=uo.map({mouseenter:"mouseover",mouseleave:"mouseout"});fo&&Oo.forEach(function(t){"on"+t in fo&&Oo.remove(t)});var Io,jo=0;uo.mouse=function(t){return Q(t,E())};var No=this.navigator&&/WebKit/.test(this.navigator.userAgent)?-1:0;uo.touch=function(t,e,r){if(arguments.length<3&&(r=e,e=E().changedTouches),e)for(var n,i=0,a=e.length;a>i;++i)if((n=e[i]).identifier===r)return Q(t,n)},uo.behavior.drag=function(){function t(){this.on("mousedown.drag",a).on("touchstart.drag",o)}function e(t,e,n,a,o){return function(){function s(){var t,r,n=e(f,g);n&&(t=n[0]-b[0],r=n[1]-b[1],p|=t|r,b=n,d({type:"drag",x:n[0]+u[0],y:n[1]+u[1],dx:t,dy:r}))}function l(){e(f,g)&&(m.on(a+v,null).on(o+v,null),y(p),d({type:"dragend"}))}var u,c=this,h=uo.event.target,f=c.parentNode,d=r.of(c,arguments),p=0,g=t(),v=".drag"+(null==g?"":"-"+g),m=uo.select(n(h)).on(a+v,s).on(o+v,l),y=K(h),b=e(f,g);i?(u=i.apply(c,arguments),u=[u.x-b[0],u.y-b[1]]):u=[0,0],d({type:"dragstart"})}}var r=L(t,"drag","dragstart","dragend"),i=null,a=e(A,uo.mouse,n,"mousemove","mouseup"),o=e(J,uo.touch,x,"touchmove","touchend");return t.origin=function(e){return arguments.length?(i=e,t):i},uo.rebind(t,r,"on")},uo.touches=function(t,e){return arguments.length<2&&(e=E().touches),e?ho(e).map(function(e){var r=Q(t,e);return r.identifier=e.identifier,r}):[]};var Fo=1e-6,Bo=Fo*Fo,Do=Math.PI,Uo=2*Do,Vo=Uo-Fo,qo=Do/2,Ho=Do/180,Go=180/Do,Yo=Math.SQRT2,Xo=2,Wo=4;uo.interpolateZoom=function(t,e){var r,n,i=t[0],a=t[1],o=t[2],s=e[0],l=e[1],u=e[2],c=s-i,h=l-a,f=c*c+h*h;if(Bo>f)n=Math.log(u/o)/Yo,r=function(t){return[i+t*c,a+t*h,o*Math.exp(Yo*t*n)]};else{var d=Math.sqrt(f),p=(u*u-o*o+Wo*f)/(2*o*Xo*d),g=(u*u-o*o-Wo*f)/(2*u*Xo*d),v=Math.log(Math.sqrt(p*p+1)-p),m=Math.log(Math.sqrt(g*g+1)-g);n=(m-v)/Yo,r=function(t){var e=t*n,r=at(v),s=o/(Xo*d)*(r*ot(Yo*e+v)-it(v));return[i+s*c,a+s*h,o*r/at(Yo*e+v)]}}return r.duration=1e3*n,r},uo.behavior.zoom=function(){function t(t){t.on(P,h).on($o+".zoom",d).on("dblclick.zoom",p).on(O,f)}function e(t){return[(t[0]-k.x)/k.k,(t[1]-k.y)/k.k]}function r(t){return[t[0]*k.k+k.x,t[1]*k.k+k.y]}function i(t){k.k=Math.max(E[0],Math.min(E[1],t))}function a(t,e){e=r(e),k.x+=t[0]-e[0],k.y+=t[1]-e[1]}function o(e,r,n,o){e.__chart__={x:k.x,y:k.y,k:k.k},i(Math.pow(2,o)),a(v=r,n),e=uo.select(e),S>0&&(e=e.transition().duration(S)),e.call(t.event)}function s(){_&&_.domain(x.range().map(function(t){return(t-k.x)/k.k}).map(x.invert)),A&&A.domain(w.range().map(function(t){return(t-k.y)/k.k}).map(w.invert))}function l(t){C++||t({type:"zoomstart"})}function u(t){s(),t({type:"zoom",scale:k.k,translate:[k.x,k.y]})}function c(t){--C||(t({type:"zoomend"}),v=null)}function h(){function t(){s=1,a(uo.mouse(i),f),u(o)}function r(){h.on(z,null).on(R,null),d(s),c(o)}var i=this,o=I.of(i,arguments),s=0,h=uo.select(n(i)).on(z,t).on(R,r),f=e(uo.mouse(i)),d=K(i);ql.call(i),l(o)}function f(){function t(){var t=uo.touches(p);return d=k.k,t.forEach(function(t){t.identifier in v&&(v[t.identifier]=e(t))}),t}function r(){var e=uo.event.target;uo.select(e).on(x,n).on(_,s),w.push(e);for(var r=uo.event.changedTouches,i=0,a=r.length;a>i;++i)v[r[i].identifier]=null;var l=t(),u=Date.now();if(1===l.length){if(500>u-b){var c=l[0];o(p,c,v[c.identifier],Math.floor(Math.log(k.k)/Math.LN2)+1),T()}b=u}else if(l.length>1){var c=l[0],h=l[1],f=c[0]-h[0],d=c[1]-h[1];m=f*f+d*d}}function n(){var t,e,r,n,o=uo.touches(p);ql.call(p);for(var s=0,l=o.length;l>s;++s,n=null)if(r=o[s],n=v[r.identifier]){if(e)break;t=r,e=n}if(n){var c=(c=r[0]-t[0])*c+(c=r[1]-t[1])*c,h=m&&Math.sqrt(c/m);t=[(t[0]+r[0])/2,(t[1]+r[1])/2],e=[(e[0]+n[0])/2,(e[1]+n[1])/2],i(h*d)}b=null,a(t,e),u(g)}function s(){if(uo.event.touches.length){for(var e=uo.event.changedTouches,r=0,n=e.length;n>r;++r)delete v[e[r].identifier];for(var i in v)return void t()}uo.selectAll(w).on(y,null),A.on(P,h).on(O,f),M(),c(g)}var d,p=this,g=I.of(p,arguments),v={},m=0,y=".zoom-"+uo.event.changedTouches[0].identifier,x="touchmove"+y,_="touchend"+y,w=[],A=uo.select(p),M=K(p);r(),l(g),A.on(P,null).on(O,r)}function d(){var t=I.of(this,arguments);y?clearTimeout(y):(ql.call(this),g=e(v=m||uo.mouse(this)),l(t)),y=setTimeout(function(){y=null,c(t)},50),T(),i(Math.pow(2,.002*Zo())*k.k),a(v,g),u(t)}function p(){var t=uo.mouse(this),r=Math.log(k.k)/Math.LN2;o(this,t,e(t),uo.event.shiftKey?Math.ceil(r)-1:Math.floor(r)+1)}var g,v,m,y,b,x,_,w,A,k={x:0,y:0,k:1},M=[960,500],E=Ko,S=250,C=0,P="mousedown.zoom",z="mousemove.zoom",R="mouseup.zoom",O="touchstart.zoom",I=L(t,"zoomstart","zoom","zoomend");return $o||($o="onwheel"in fo?(Zo=function(){return-uo.event.deltaY*(uo.event.deltaMode?120:1)},"wheel"):"onmousewheel"in fo?(Zo=function(){return uo.event.wheelDelta},"mousewheel"):(Zo=function(){return-uo.event.detail},"MozMousePixelScroll")),t.event=function(t){t.each(function(){var t=I.of(this,arguments),e=k;Ul?uo.select(this).transition().each("start.zoom",function(){k=this.__chart__||{x:0,y:0,k:1},l(t)}).tween("zoom:zoom",function(){var r=M[0],n=M[1],i=v?v[0]:r/2,a=v?v[1]:n/2,o=uo.interpolateZoom([(i-k.x)/k.k,(a-k.y)/k.k,r/k.k],[(i-e.x)/e.k,(a-e.y)/e.k,r/e.k]);return function(e){var n=o(e),s=r/n[2];this.__chart__=k={x:i-n[0]*s,y:a-n[1]*s,k:s},u(t)}}).each("interrupt.zoom",function(){c(t)}).each("end.zoom",function(){c(t)}):(this.__chart__=k,l(t),u(t),c(t))})},t.translate=function(e){return arguments.length?(k={x:+e[0],y:+e[1],k:k.k},s(),t):[k.x,k.y]},t.scale=function(e){return arguments.length?(k={x:k.x,y:k.y,k:null},i(+e),s(),t):k.k},t.scaleExtent=function(e){return arguments.length?(E=null==e?Ko:[+e[0],+e[1]],t):E},t.center=function(e){return arguments.length?(m=e&&[+e[0],+e[1]],t):m},t.size=function(e){return arguments.length?(M=e&&[+e[0],+e[1]],t):M},t.duration=function(e){return arguments.length?(S=+e,t):S},t.x=function(e){return arguments.length?(_=e,x=e.copy(),k={x:0,y:0,k:1},t):_},t.y=function(e){return arguments.length?(A=e,w=e.copy(),k={x:0,y:0,k:1},t):A},uo.rebind(t,I,"on")};var Zo,$o,Ko=[0,1/0];uo.color=lt,lt.prototype.toString=function(){return this.rgb()+""},uo.hsl=ut;var Qo=ut.prototype=new lt;Qo.brighter=function(t){return t=Math.pow(.7,arguments.length?t:1),new ut(this.h,this.s,this.l/t)},Qo.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new ut(this.h,this.s,t*this.l)},Qo.rgb=function(){return ct(this.h,this.s,this.l)},uo.hcl=ht;var Jo=ht.prototype=new lt;Jo.brighter=function(t){return new ht(this.h,this.c,Math.min(100,this.l+ts*(arguments.length?t:1)))},Jo.darker=function(t){return new ht(this.h,this.c,Math.max(0,this.l-ts*(arguments.length?t:1)))},Jo.rgb=function(){return ft(this.h,this.c,this.l).rgb()},uo.lab=dt;var ts=18,es=.95047,rs=1,ns=1.08883,is=dt.prototype=new lt;is.brighter=function(t){return new dt(Math.min(100,this.l+ts*(arguments.length?t:1)),this.a,this.b)},is.darker=function(t){return new dt(Math.max(0,this.l-ts*(arguments.length?t:1)),this.a,this.b)},is.rgb=function(){return pt(this.l,this.a,this.b)},uo.rgb=bt;var as=bt.prototype=new lt;as.brighter=function(t){t=Math.pow(.7,arguments.length?t:1);var e=this.r,r=this.g,n=this.b,i=30;return e||r||n?(e&&i>e&&(e=i),r&&i>r&&(r=i),n&&i>n&&(n=i),new bt(Math.min(255,e/t),Math.min(255,r/t),Math.min(255,n/t))):new bt(i,i,i)},as.darker=function(t){return t=Math.pow(.7,arguments.length?t:1),new bt(t*this.r,t*this.g,t*this.b)},as.hsl=function(){return kt(this.r,this.g,this.b)},as.toString=function(){return"#"+wt(this.r)+wt(this.g)+wt(this.b)};var os=uo.map({aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074});os.forEach(function(t,e){os.set(t,xt(e))}),uo.functor=Lt,uo.xhr=St(x),uo.dsv=function(t,e){function r(t,r,a){arguments.length<3&&(a=r,r=null);var o=Ct(t,e,null==r?n:i(r),a);return o.row=function(t){return arguments.length?o.response(null==(r=t)?n:i(t)):r},o}function n(t){return r.parse(t.responseText)}function i(t){return function(e){return r.parse(e.responseText,t)}}function a(e){return e.map(o).join(t)}function o(t){return s.test(t)?'"'+t.replace(/\"/g,'""')+'"':t}var s=new RegExp('["'+t+"\n]"),l=t.charCodeAt(0);return r.parse=function(t,e){var n;return r.parseRows(t,function(t,r){if(n)return n(t,r-1);var i=new Function("d","return {"+t.map(function(t,e){return JSON.stringify(t)+": d["+e+"]"}).join(",")+"}");n=e?function(t,r){return e(i(t),r)}:i})},r.parseRows=function(t,e){function r(){if(c>=u)return o;if(i)return i=!1,a;var e=c;if(34===t.charCodeAt(e)){for(var r=e;r++<u;)if(34===t.charCodeAt(r)){if(34!==t.charCodeAt(r+1))break;++r}c=r+2;var n=t.charCodeAt(r+1);return 13===n?(i=!0,10===t.charCodeAt(r+2)&&++c):10===n&&(i=!0),t.slice(e+1,r).replace(/""/g,'"')}for(;u>c;){var n=t.charCodeAt(c++),s=1;if(10===n)i=!0;else if(13===n)i=!0,10===t.charCodeAt(c)&&(++c,++s);else if(n!==l)continue;return t.slice(e,c-s)}return t.slice(e)}for(var n,i,a={},o={},s=[],u=t.length,c=0,h=0;(n=r())!==o;){for(var f=[];n!==a&&n!==o;)f.push(n),n=r();e&&null==(f=e(f,h++))||s.push(f)}return s},r.format=function(e){if(Array.isArray(e[0]))return r.formatRows(e);var n=new b,i=[];return e.forEach(function(t){for(var e in t)n.has(e)||i.push(n.add(e))}),[i.map(o).join(t)].concat(e.map(function(e){return i.map(function(t){return o(e[t])}).join(t)})).join("\n")},r.formatRows=function(t){return t.map(a).join("\n")},r},uo.csv=uo.dsv(",","text/csv"),uo.tsv=uo.dsv("	","text/tab-separated-values");var ss,ls,us,cs,hs=this[w(this,"requestAnimationFrame")]||function(t){setTimeout(t,17)};uo.timer=function(){Rt.apply(this,arguments)},uo.timer.flush=function(){It(),jt()},uo.round=function(t,e){return e?Math.round(t*(e=Math.pow(10,e)))/e:Math.round(t)};var fs=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"].map(Ft);uo.formatPrefix=function(t,e){var r=0;return(t=+t)&&(0>t&&(t*=-1),e&&(t=uo.round(t,Nt(t,e))),r=1+Math.floor(1e-12+Math.log(t)/Math.LN10),r=Math.max(-24,Math.min(24,3*Math.floor((r-1)/3)))),fs[8+r/3]};var ds=/(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i,ps=uo.map({b:function(t){return t.toString(2)},c:function(t){return String.fromCharCode(t)},o:function(t){return t.toString(8)},x:function(t){return t.toString(16)},X:function(t){return t.toString(16).toUpperCase()},g:function(t,e){return t.toPrecision(e)},e:function(t,e){return t.toExponential(e)},f:function(t,e){return t.toFixed(e)},r:function(t,e){return(t=uo.round(t,Nt(t,e))).toFixed(Math.max(0,Math.min(20,Nt(t*(1+1e-15),e))))}}),gs=uo.time={},vs=Date;Ut.prototype={getDate:function(){return this._.getUTCDate()},getDay:function(){return this._.getUTCDay()},getFullYear:function(){return this._.getUTCFullYear()},getHours:function(){return this._.getUTCHours()},getMilliseconds:function(){return this._.getUTCMilliseconds()},getMinutes:function(){return this._.getUTCMinutes()},getMonth:function(){return this._.getUTCMonth()},getSeconds:function(){return this._.getUTCSeconds()},getTime:function(){return this._.getTime()},getTimezoneOffset:function(){return 0},valueOf:function(){return this._.valueOf()},setDate:function(){ms.setUTCDate.apply(this._,arguments)},setDay:function(){ms.setUTCDay.apply(this._,arguments)},setFullYear:function(){ms.setUTCFullYear.apply(this._,arguments)},setHours:function(){ms.setUTCHours.apply(this._,arguments)},setMilliseconds:function(){ms.setUTCMilliseconds.apply(this._,arguments)},setMinutes:function(){ms.setUTCMinutes.apply(this._,arguments)},setMonth:function(){ms.setUTCMonth.apply(this._,arguments)},setSeconds:function(){ms.setUTCSeconds.apply(this._,arguments)},setTime:function(){ms.setTime.apply(this._,arguments)}};var ms=Date.prototype;gs.year=Vt(function(t){return t=gs.day(t),t.setMonth(0,1),t},function(t,e){t.setFullYear(t.getFullYear()+e)},function(t){return t.getFullYear()}),gs.years=gs.year.range,gs.years.utc=gs.year.utc.range,gs.day=Vt(function(t){var e=new vs(2e3,0);return e.setFullYear(t.getFullYear(),t.getMonth(),t.getDate()),e},function(t,e){t.setDate(t.getDate()+e)},function(t){return t.getDate()-1}),gs.days=gs.day.range,gs.days.utc=gs.day.utc.range,gs.dayOfYear=function(t){var e=gs.year(t);return Math.floor((t-e-6e4*(t.getTimezoneOffset()-e.getTimezoneOffset()))/864e5)},["sunday","monday","tuesday","wednesday","thursday","friday","saturday"].forEach(function(t,e){e=7-e;var r=gs[t]=Vt(function(t){return(t=gs.day(t)).setDate(t.getDate()-(t.getDay()+e)%7),t},function(t,e){t.setDate(t.getDate()+7*Math.floor(e))},function(t){var r=gs.year(t).getDay();return Math.floor((gs.dayOfYear(t)+(r+e)%7)/7)-(r!==e)});gs[t+"s"]=r.range,gs[t+"s"].utc=r.utc.range,gs[t+"OfYear"]=function(t){var r=gs.year(t).getDay();return Math.floor((gs.dayOfYear(t)+(r+e)%7)/7)}}),gs.week=gs.sunday,gs.weeks=gs.sunday.range,gs.weeks.utc=gs.sunday.utc.range,gs.weekOfYear=gs.sundayOfYear;var ys={"-":"",_:" ",0:"0"},bs=/^\s*\d+/,xs=/^%/;uo.locale=function(t){return{numberFormat:Bt(t),timeFormat:Ht(t)}};var _s=uo.locale({decimal:".",thousands:",",grouping:[3],currency:["$",""],dateTime:"%a %b %e %X %Y",date:"%m/%d/%Y",time:"%H:%M:%S",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"]});uo.format=_s.numberFormat,uo.geo={},he.prototype={s:0,t:0,add:function(t){fe(t,this.t,ws),fe(ws.s,this.s,this),this.s?this.t+=ws.t:this.s=ws.t},reset:function(){this.s=this.t=0},valueOf:function(){return this.s}};var ws=new he;uo.geo.stream=function(t,e){t&&As.hasOwnProperty(t.type)?As[t.type](t,e):de(t,e)};var As={Feature:function(t,e){de(t.geometry,e)},FeatureCollection:function(t,e){for(var r=t.features,n=-1,i=r.length;++n<i;)de(r[n].geometry,e)}},ks={Sphere:function(t,e){e.sphere()},Point:function(t,e){t=t.coordinates,e.point(t[0],t[1],t[2])},MultiPoint:function(t,e){for(var r=t.coordinates,n=-1,i=r.length;++n<i;)t=r[n],e.point(t[0],t[1],t[2])},LineString:function(t,e){pe(t.coordinates,e,0)},MultiLineString:function(t,e){for(var r=t.coordinates,n=-1,i=r.length;++n<i;)pe(r[n],e,0)},Polygon:function(t,e){ge(t.coordinates,e)},MultiPolygon:function(t,e){for(var r=t.coordinates,n=-1,i=r.length;++n<i;)ge(r[n],e)},GeometryCollection:function(t,e){for(var r=t.geometries,n=-1,i=r.length;++n<i;)de(r[n],e)}};uo.geo.area=function(t){return Ms=0,uo.geo.stream(t,Es),Ms};var Ms,Ts=new he,Es={sphere:function(){Ms+=4*Do},point:A,lineStart:A,lineEnd:A,polygonStart:function(){Ts.reset(),Es.lineStart=ve},polygonEnd:function(){var t=2*Ts;Ms+=0>t?4*Do+t:t,Es.lineStart=Es.lineEnd=Es.point=A}};uo.geo.bounds=function(){function t(t,e){b.push(x=[c=t,f=t]),h>e&&(h=e),e>d&&(d=e)}function e(e,r){var n=me([e*Ho,r*Ho]);if(m){var i=be(m,n),a=[i[1],-i[0],0],o=be(a,i);we(o),o=Ae(o);var l=e-p,u=l>0?1:-1,g=o[0]*Go*u,v=wo(l)>180;if(v^(g>u*p&&u*e>g)){var y=o[1]*Go;y>d&&(d=y)}else if(g=(g+360)%360-180,v^(g>u*p&&u*e>g)){var y=-o[1]*Go;h>y&&(h=y)}else h>r&&(h=r),r>d&&(d=r);v?p>e?s(c,e)>s(c,f)&&(f=e):s(e,f)>s(c,f)&&(c=e):f>=c?(c>e&&(c=e),e>f&&(f=e)):e>p?s(c,e)>s(c,f)&&(f=e):s(e,f)>s(c,f)&&(c=e)}else t(e,r);m=n,p=e}function r(){_.point=e}function n(){x[0]=c,x[1]=f,_.point=t,m=null}function i(t,r){if(m){var n=t-p;y+=wo(n)>180?n+(n>0?360:-360):n}else g=t,v=r;Es.point(t,r),e(t,r)}function a(){Es.lineStart()}function o(){i(g,v),Es.lineEnd(),wo(y)>Fo&&(c=-(f=180)),x[0]=c,x[1]=f,m=null}function s(t,e){return(e-=t)<0?e+360:e}function l(t,e){return t[0]-e[0]}function u(t,e){return e[0]<=e[1]?e[0]<=t&&t<=e[1]:t<e[0]||e[1]<t}var c,h,f,d,p,g,v,m,y,b,x,_={point:t,lineStart:r,lineEnd:n,polygonStart:function(){_.point=i,_.lineStart=a,_.lineEnd=o,y=0,Es.polygonStart()},polygonEnd:function(){Es.polygonEnd(),_.point=t,_.lineStart=r,_.lineEnd=n,0>Ts?(c=-(f=180),h=-(d=90)):y>Fo?d=90:-Fo>y&&(h=-90),x[0]=c,x[1]=f}};return function(t){d=f=-(c=h=1/0),b=[],uo.geo.stream(t,_);var e=b.length;if(e){b.sort(l);for(var r,n=1,i=b[0],a=[i];e>n;++n)r=b[n],u(r[0],i)||u(r[1],i)?(s(i[0],r[1])>s(i[0],i[1])&&(i[1]=r[1]),s(r[0],i[1])>s(i[0],i[1])&&(i[0]=r[0])):a.push(i=r);for(var o,r,p=-(1/0),e=a.length-1,n=0,i=a[e];e>=n;i=r,++n)r=a[n],(o=s(i[1],r[0]))>p&&(p=o,c=r[0],f=i[1])}return b=x=null,c===1/0||h===1/0?[[NaN,NaN],[NaN,NaN]]:[[c,h],[f,d]]}}(),uo.geo.centroid=function(t){Ls=Ss=Cs=Ps=zs=Rs=Os=Is=js=Ns=Fs=0,uo.geo.stream(t,Bs);var e=js,r=Ns,n=Fs,i=e*e+r*r+n*n;return Bo>i&&(e=Rs,r=Os,n=Is,Fo>Ss&&(e=Cs,r=Ps,n=zs),i=e*e+r*r+n*n,Bo>i)?[NaN,NaN]:[Math.atan2(r,e)*Go,nt(n/Math.sqrt(i))*Go]};var Ls,Ss,Cs,Ps,zs,Rs,Os,Is,js,Ns,Fs,Bs={sphere:A,point:Me,lineStart:Ee,lineEnd:Le,polygonStart:function(){Bs.lineStart=Se},polygonEnd:function(){Bs.lineStart=Ee}},Ds=Ie(Pe,Be,Ue,[-Do,-Do/2]),Us=1e9;uo.geo.clipExtent=function(){var t,e,r,n,i,a,o={stream:function(t){return i&&(i.valid=!1),i=a(t),i.valid=!0,i},extent:function(s){return arguments.length?(a=Ge(t=+s[0][0],e=+s[0][1],r=+s[1][0],n=+s[1][1]),i&&(i.valid=!1,i=null),o):[[t,e],[r,n]]}};return o.extent([[0,0],[960,500]])},(uo.geo.conicEqualArea=function(){return Ye(Xe)}).raw=Xe,uo.geo.albers=function(){return uo.geo.conicEqualArea().rotate([96,0]).center([-.6,38.7]).parallels([29.5,45.5]).scale(1070)},uo.geo.albersUsa=function(){function t(t){var a=t[0],o=t[1];return e=null,r(a,o),e||(n(a,o),e)||i(a,o),e}var e,r,n,i,a=uo.geo.albers(),o=uo.geo.conicEqualArea().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s=uo.geo.conicEqualArea().rotate([157,0]).center([-3,19.9]).parallels([8,18]),l={point:function(t,r){e=[t,r]}};return t.invert=function(t){var e=a.scale(),r=a.translate(),n=(t[0]-r[0])/e,i=(t[1]-r[1])/e;return(i>=.12&&.234>i&&n>=-.425&&-.214>n?o:i>=.166&&.234>i&&n>=-.214&&-.115>n?s:a).invert(t)},t.stream=function(t){var e=a.stream(t),r=o.stream(t),n=s.stream(t);return{point:function(t,i){e.point(t,i),r.point(t,i),n.point(t,i)},sphere:function(){e.sphere(),r.sphere(),n.sphere()},lineStart:function(){e.lineStart(),r.lineStart(),n.lineStart()},lineEnd:function(){e.lineEnd(),r.lineEnd(),n.lineEnd()},polygonStart:function(){e.polygonStart(),r.polygonStart(),n.polygonStart()},polygonEnd:function(){e.polygonEnd(),r.polygonEnd(),n.polygonEnd()}}},t.precision=function(e){return arguments.length?(a.precision(e),o.precision(e),s.precision(e),t):a.precision()},t.scale=function(e){return arguments.length?(a.scale(e),o.scale(.35*e),s.scale(e),t.translate(a.translate())):a.scale()},t.translate=function(e){if(!arguments.length)return a.translate();var u=a.scale(),c=+e[0],h=+e[1];return r=a.translate(e).clipExtent([[c-.455*u,h-.238*u],[c+.455*u,h+.238*u]]).stream(l).point,n=o.translate([c-.307*u,h+.201*u]).clipExtent([[c-.425*u+Fo,h+.12*u+Fo],[c-.214*u-Fo,h+.234*u-Fo]]).stream(l).point,
+i=s.translate([c-.205*u,h+.212*u]).clipExtent([[c-.214*u+Fo,h+.166*u+Fo],[c-.115*u-Fo,h+.234*u-Fo]]).stream(l).point,t},t.scale(1070)};var Vs,qs,Hs,Gs,Ys,Xs,Ws={point:A,lineStart:A,lineEnd:A,polygonStart:function(){qs=0,Ws.lineStart=We},polygonEnd:function(){Ws.lineStart=Ws.lineEnd=Ws.point=A,Vs+=wo(qs/2)}},Zs={point:Ze,lineStart:A,lineEnd:A,polygonStart:A,polygonEnd:A},$s={point:Qe,lineStart:Je,lineEnd:tr,polygonStart:function(){$s.lineStart=er},polygonEnd:function(){$s.point=Qe,$s.lineStart=Je,$s.lineEnd=tr}};uo.geo.path=function(){function t(t){return t&&("function"==typeof s&&a.pointRadius(+s.apply(this,arguments)),o&&o.valid||(o=i(a)),uo.geo.stream(t,o)),a.result()}function e(){return o=null,t}var r,n,i,a,o,s=4.5;return t.area=function(t){return Vs=0,uo.geo.stream(t,i(Ws)),Vs},t.centroid=function(t){return Cs=Ps=zs=Rs=Os=Is=js=Ns=Fs=0,uo.geo.stream(t,i($s)),Fs?[js/Fs,Ns/Fs]:Is?[Rs/Is,Os/Is]:zs?[Cs/zs,Ps/zs]:[NaN,NaN]},t.bounds=function(t){return Ys=Xs=-(Hs=Gs=1/0),uo.geo.stream(t,i(Zs)),[[Hs,Gs],[Ys,Xs]]},t.projection=function(t){return arguments.length?(i=(r=t)?t.stream||ir(t):x,e()):r},t.context=function(t){return arguments.length?(a=null==(n=t)?new $e:new rr(t),"function"!=typeof s&&a.pointRadius(s),e()):n},t.pointRadius=function(e){return arguments.length?(s="function"==typeof e?e:(a.pointRadius(+e),+e),t):s},t.projection(uo.geo.albersUsa()).context(null)},uo.geo.transform=function(t){return{stream:function(e){var r=new ar(e);for(var n in t)r[n]=t[n];return r}}},ar.prototype={point:function(t,e){this.stream.point(t,e)},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()}},uo.geo.projection=sr,uo.geo.projectionMutator=lr,(uo.geo.equirectangular=function(){return sr(cr)}).raw=cr.invert=cr,uo.geo.rotation=function(t){function e(e){return e=t(e[0]*Ho,e[1]*Ho),e[0]*=Go,e[1]*=Go,e}return t=fr(t[0]%360*Ho,t[1]*Ho,t.length>2?t[2]*Ho:0),e.invert=function(e){return e=t.invert(e[0]*Ho,e[1]*Ho),e[0]*=Go,e[1]*=Go,e},e},hr.invert=cr,uo.geo.circle=function(){function t(){var t="function"==typeof n?n.apply(this,arguments):n,e=fr(-t[0]*Ho,-t[1]*Ho,0).invert,i=[];return r(null,null,1,{point:function(t,r){i.push(t=e(t,r)),t[0]*=Go,t[1]*=Go}}),{type:"Polygon",coordinates:[i]}}var e,r,n=[0,0],i=6;return t.origin=function(e){return arguments.length?(n=e,t):n},t.angle=function(n){return arguments.length?(r=vr((e=+n)*Ho,i*Ho),t):e},t.precision=function(n){return arguments.length?(r=vr(e*Ho,(i=+n)*Ho),t):i},t.angle(90)},uo.geo.distance=function(t,e){var r,n=(e[0]-t[0])*Ho,i=t[1]*Ho,a=e[1]*Ho,o=Math.sin(n),s=Math.cos(n),l=Math.sin(i),u=Math.cos(i),c=Math.sin(a),h=Math.cos(a);return Math.atan2(Math.sqrt((r=h*o)*r+(r=u*c-l*h*s)*r),l*c+u*h*s)},uo.geo.graticule=function(){function t(){return{type:"MultiLineString",coordinates:e()}}function e(){return uo.range(Math.ceil(a/v)*v,i,v).map(f).concat(uo.range(Math.ceil(u/m)*m,l,m).map(d)).concat(uo.range(Math.ceil(n/p)*p,r,p).filter(function(t){return wo(t%v)>Fo}).map(c)).concat(uo.range(Math.ceil(s/g)*g,o,g).filter(function(t){return wo(t%m)>Fo}).map(h))}var r,n,i,a,o,s,l,u,c,h,f,d,p=10,g=p,v=90,m=360,y=2.5;return t.lines=function(){return e().map(function(t){return{type:"LineString",coordinates:t}})},t.outline=function(){return{type:"Polygon",coordinates:[f(a).concat(d(l).slice(1),f(i).reverse().slice(1),d(u).reverse().slice(1))]}},t.extent=function(e){return arguments.length?t.majorExtent(e).minorExtent(e):t.minorExtent()},t.majorExtent=function(e){return arguments.length?(a=+e[0][0],i=+e[1][0],u=+e[0][1],l=+e[1][1],a>i&&(e=a,a=i,i=e),u>l&&(e=u,u=l,l=e),t.precision(y)):[[a,u],[i,l]]},t.minorExtent=function(e){return arguments.length?(n=+e[0][0],r=+e[1][0],s=+e[0][1],o=+e[1][1],n>r&&(e=n,n=r,r=e),s>o&&(e=s,s=o,o=e),t.precision(y)):[[n,s],[r,o]]},t.step=function(e){return arguments.length?t.majorStep(e).minorStep(e):t.minorStep()},t.majorStep=function(e){return arguments.length?(v=+e[0],m=+e[1],t):[v,m]},t.minorStep=function(e){return arguments.length?(p=+e[0],g=+e[1],t):[p,g]},t.precision=function(e){return arguments.length?(y=+e,c=yr(s,o,90),h=br(n,r,y),f=yr(u,l,90),d=br(a,i,y),t):y},t.majorExtent([[-180,-90+Fo],[180,90-Fo]]).minorExtent([[-180,-80-Fo],[180,80+Fo]])},uo.geo.greatArc=function(){function t(){return{type:"LineString",coordinates:[e||n.apply(this,arguments),r||i.apply(this,arguments)]}}var e,r,n=xr,i=_r;return t.distance=function(){return uo.geo.distance(e||n.apply(this,arguments),r||i.apply(this,arguments))},t.source=function(r){return arguments.length?(n=r,e="function"==typeof r?null:r,t):n},t.target=function(e){return arguments.length?(i=e,r="function"==typeof e?null:e,t):i},t.precision=function(){return arguments.length?t:0},t},uo.geo.interpolate=function(t,e){return wr(t[0]*Ho,t[1]*Ho,e[0]*Ho,e[1]*Ho)},uo.geo.length=function(t){return Ks=0,uo.geo.stream(t,Qs),Ks};var Ks,Qs={sphere:A,point:A,lineStart:Ar,lineEnd:A,polygonStart:A,polygonEnd:A},Js=kr(function(t){return Math.sqrt(2/(1+t))},function(t){return 2*Math.asin(t/2)});(uo.geo.azimuthalEqualArea=function(){return sr(Js)}).raw=Js;var tl=kr(function(t){var e=Math.acos(t);return e&&e/Math.sin(e)},x);(uo.geo.azimuthalEquidistant=function(){return sr(tl)}).raw=tl,(uo.geo.conicConformal=function(){return Ye(Mr)}).raw=Mr,(uo.geo.conicEquidistant=function(){return Ye(Tr)}).raw=Tr;var el=kr(function(t){return 1/t},Math.atan);(uo.geo.gnomonic=function(){return sr(el)}).raw=el,Er.invert=function(t,e){return[t,2*Math.atan(Math.exp(e))-qo]},(uo.geo.mercator=function(){return Lr(Er)}).raw=Er;var rl=kr(function(){return 1},Math.asin);(uo.geo.orthographic=function(){return sr(rl)}).raw=rl;var nl=kr(function(t){return 1/(1+t)},function(t){return 2*Math.atan(t)});(uo.geo.stereographic=function(){return sr(nl)}).raw=nl,Sr.invert=function(t,e){return[-e,2*Math.atan(Math.exp(t))-qo]},(uo.geo.transverseMercator=function(){var t=Lr(Sr),e=t.center,r=t.rotate;return t.center=function(t){return t?e([-t[1],t[0]]):(t=e(),[t[1],-t[0]])},t.rotate=function(t){return t?r([t[0],t[1],t.length>2?t[2]+90:90]):(t=r(),[t[0],t[1],t[2]-90])},r([0,0,90])}).raw=Sr,uo.geom={},uo.geom.hull=function(t){function e(t){if(t.length<3)return[];var e,i=Lt(r),a=Lt(n),o=t.length,s=[],l=[];for(e=0;o>e;e++)s.push([+i.call(this,t[e],e),+a.call(this,t[e],e),e]);for(s.sort(Rr),e=0;o>e;e++)l.push([s[e][0],-s[e][1]]);var u=zr(s),c=zr(l),h=c[0]===u[0],f=c[c.length-1]===u[u.length-1],d=[];for(e=u.length-1;e>=0;--e)d.push(t[s[u[e]][2]]);for(e=+h;e<c.length-f;++e)d.push(t[s[c[e]][2]]);return d}var r=Cr,n=Pr;return arguments.length?e(t):(e.x=function(t){return arguments.length?(r=t,e):r},e.y=function(t){return arguments.length?(n=t,e):n},e)},uo.geom.polygon=function(t){return Eo(t,il),t};var il=uo.geom.polygon.prototype=[];il.area=function(){for(var t,e=-1,r=this.length,n=this[r-1],i=0;++e<r;)t=n,n=this[e],i+=t[1]*n[0]-t[0]*n[1];return.5*i},il.centroid=function(t){var e,r,n=-1,i=this.length,a=0,o=0,s=this[i-1];for(arguments.length||(t=-1/(6*this.area()));++n<i;)e=s,s=this[n],r=e[0]*s[1]-s[0]*e[1],a+=(e[0]+s[0])*r,o+=(e[1]+s[1])*r;return[a*t,o*t]},il.clip=function(t){for(var e,r,n,i,a,o,s=jr(t),l=-1,u=this.length-jr(this),c=this[u-1];++l<u;){for(e=t.slice(),t.length=0,i=this[l],a=e[(n=e.length-s)-1],r=-1;++r<n;)o=e[r],Or(o,c,i)?(Or(a,c,i)||t.push(Ir(a,o,c,i)),t.push(o)):Or(a,c,i)&&t.push(Ir(a,o,c,i)),a=o;s&&t.push(t[0]),c=i}return t};var al,ol,sl,ll,ul,cl=[],hl=[];Hr.prototype.prepare=function(){for(var t,e=this.edges,r=e.length;r--;)t=e[r].edge,t.b&&t.a||e.splice(r,1);return e.sort(Yr),e.length},rn.prototype={start:function(){return this.edge.l===this.site?this.edge.a:this.edge.b},end:function(){return this.edge.l===this.site?this.edge.b:this.edge.a}},nn.prototype={insert:function(t,e){var r,n,i;if(t){if(e.P=t,e.N=t.N,t.N&&(t.N.P=e),t.N=e,t.R){for(t=t.R;t.L;)t=t.L;t.L=e}else t.R=e;r=t}else this._?(t=ln(this._),e.P=null,e.N=t,t.P=t.L=e,r=t):(e.P=e.N=null,this._=e,r=null);for(e.L=e.R=null,e.U=r,e.C=!0,t=e;r&&r.C;)n=r.U,r===n.L?(i=n.R,i&&i.C?(r.C=i.C=!1,n.C=!0,t=n):(t===r.R&&(on(this,r),t=r,r=t.U),r.C=!1,n.C=!0,sn(this,n))):(i=n.L,i&&i.C?(r.C=i.C=!1,n.C=!0,t=n):(t===r.L&&(sn(this,r),t=r,r=t.U),r.C=!1,n.C=!0,on(this,n))),r=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 e,r,n,i=t.U,a=t.L,o=t.R;if(r=a?o?ln(o):a:o,i?i.L===t?i.L=r:i.R=r:this._=r,a&&o?(n=r.C,r.C=t.C,r.L=a,a.U=r,r!==o?(i=r.U,r.U=t.U,t=r.R,i.L=t,r.R=o,o.U=r):(r.U=i,i=r,t=r.R)):(n=t.C,t=r),t&&(t.U=i),!n){if(t&&t.C)return void(t.C=!1);do{if(t===this._)break;if(t===i.L){if(e=i.R,e.C&&(e.C=!1,i.C=!0,on(this,i),e=i.R),e.L&&e.L.C||e.R&&e.R.C){e.R&&e.R.C||(e.L.C=!1,e.C=!0,sn(this,e),e=i.R),e.C=i.C,i.C=e.R.C=!1,on(this,i),t=this._;break}}else if(e=i.L,e.C&&(e.C=!1,i.C=!0,sn(this,i),e=i.L),e.L&&e.L.C||e.R&&e.R.C){e.L&&e.L.C||(e.R.C=!1,e.C=!0,on(this,e),e=i.L),e.C=i.C,i.C=e.L.C=!1,sn(this,i),t=this._;break}e.C=!0,t=i,i=i.U}while(!t.C);t&&(t.C=!1)}}},uo.geom.voronoi=function(t){function e(t){var e=new Array(t.length),n=s[0][0],i=s[0][1],a=s[1][0],o=s[1][1];return un(r(t),s).cells.forEach(function(r,s){var l=r.edges,u=r.site,c=e[s]=l.length?l.map(function(t){var e=t.start();return[e.x,e.y]}):u.x>=n&&u.x<=a&&u.y>=i&&u.y<=o?[[n,o],[a,o],[a,i],[n,i]]:[];c.point=t[s]}),e}function r(t){return t.map(function(t,e){return{x:Math.round(a(t,e)/Fo)*Fo,y:Math.round(o(t,e)/Fo)*Fo,i:e}})}var n=Cr,i=Pr,a=n,o=i,s=fl;return t?e(t):(e.links=function(t){return un(r(t)).edges.filter(function(t){return t.l&&t.r}).map(function(e){return{source:t[e.l.i],target:t[e.r.i]}})},e.triangles=function(t){var e=[];return un(r(t)).cells.forEach(function(r,n){for(var i,a,o=r.site,s=r.edges.sort(Yr),l=-1,u=s.length,c=s[u-1].edge,h=c.l===o?c.r:c.l;++l<u;)i=c,a=h,c=s[l].edge,h=c.l===o?c.r:c.l,n<a.i&&n<h.i&&hn(o,a,h)<0&&e.push([t[n],t[a.i],t[h.i]])}),e},e.x=function(t){return arguments.length?(a=Lt(n=t),e):n},e.y=function(t){return arguments.length?(o=Lt(i=t),e):i},e.clipExtent=function(t){return arguments.length?(s=null==t?fl:t,e):s===fl?null:s},e.size=function(t){return arguments.length?e.clipExtent(t&&[[0,0],t]):s===fl?null:s&&s[1]},e)};var fl=[[-1e6,-1e6],[1e6,1e6]];uo.geom.delaunay=function(t){return uo.geom.voronoi().triangles(t)},uo.geom.quadtree=function(t,e,r,n,i){function a(t){function a(t,e,r,n,i,a,o,s){if(!isNaN(r)&&!isNaN(n))if(t.leaf){var l=t.x,c=t.y;if(null!=l)if(wo(l-r)+wo(c-n)<.01)u(t,e,r,n,i,a,o,s);else{var h=t.point;t.x=t.y=t.point=null,u(t,h,l,c,i,a,o,s),u(t,e,r,n,i,a,o,s)}else t.x=r,t.y=n,t.point=e}else u(t,e,r,n,i,a,o,s)}function u(t,e,r,n,i,o,s,l){var u=.5*(i+s),c=.5*(o+l),h=r>=u,f=n>=c,d=f<<1|h;t.leaf=!1,t=t.nodes[d]||(t.nodes[d]=pn()),h?i=u:s=u,f?o=c:l=c,a(t,e,r,n,i,o,s,l)}var c,h,f,d,p,g,v,m,y,b=Lt(s),x=Lt(l);if(null!=e)g=e,v=r,m=n,y=i;else if(m=y=-(g=v=1/0),h=[],f=[],p=t.length,o)for(d=0;p>d;++d)c=t[d],c.x<g&&(g=c.x),c.y<v&&(v=c.y),c.x>m&&(m=c.x),c.y>y&&(y=c.y),h.push(c.x),f.push(c.y);else for(d=0;p>d;++d){var _=+b(c=t[d],d),w=+x(c,d);g>_&&(g=_),v>w&&(v=w),_>m&&(m=_),w>y&&(y=w),h.push(_),f.push(w)}var A=m-g,k=y-v;A>k?y=v+A:m=g+k;var M=pn();if(M.add=function(t){a(M,t,+b(t,++d),+x(t,d),g,v,m,y)},M.visit=function(t){gn(t,M,g,v,m,y)},M.find=function(t){return vn(M,t[0],t[1],g,v,m,y)},d=-1,null==e){for(;++d<p;)a(M,t[d],h[d],f[d],g,v,m,y);--d}else t.forEach(M.add);return h=f=t=c=null,M}var o,s=Cr,l=Pr;return(o=arguments.length)?(s=fn,l=dn,3===o&&(i=r,n=e,r=e=0),a(t)):(a.x=function(t){return arguments.length?(s=t,a):s},a.y=function(t){return arguments.length?(l=t,a):l},a.extent=function(t){return arguments.length?(null==t?e=r=n=i=null:(e=+t[0][0],r=+t[0][1],n=+t[1][0],i=+t[1][1]),a):null==e?null:[[e,r],[n,i]]},a.size=function(t){return arguments.length?(null==t?e=r=n=i=null:(e=r=0,n=+t[0],i=+t[1]),a):null==e?null:[n-e,i-r]},a)},uo.interpolateRgb=mn,uo.interpolateObject=yn,uo.interpolateNumber=bn,uo.interpolateString=xn;var dl=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,pl=new RegExp(dl.source,"g");uo.interpolate=_n,uo.interpolators=[function(t,e){var r=typeof e;return("string"===r?os.has(e.toLowerCase())||/^(#|rgb\(|hsl\()/i.test(e)?mn:xn:e instanceof lt?mn:Array.isArray(e)?wn:"object"===r&&isNaN(e)?yn:bn)(t,e)}],uo.interpolateArray=wn;var gl=function(){return x},vl=uo.map({linear:gl,poly:Sn,quad:function(){return Tn},cubic:function(){return En},sin:function(){return Cn},exp:function(){return Pn},circle:function(){return zn},elastic:Rn,back:On,bounce:function(){return In}}),ml=uo.map({"in":x,out:kn,"in-out":Mn,"out-in":function(t){return Mn(kn(t))}});uo.ease=function(t){var e=t.indexOf("-"),r=e>=0?t.slice(0,e):t,n=e>=0?t.slice(e+1):"in";return r=vl.get(r)||gl,n=ml.get(n)||x,An(n(r.apply(null,co.call(arguments,1))))},uo.interpolateHcl=jn,uo.interpolateHsl=Nn,uo.interpolateLab=Fn,uo.interpolateRound=Bn,uo.transform=function(t){var e=fo.createElementNS(uo.ns.prefix.svg,"g");return(uo.transform=function(t){if(null!=t){e.setAttribute("transform",t);var r=e.transform.baseVal.consolidate()}return new Dn(r?r.matrix:yl)})(t)},Dn.prototype.toString=function(){return"translate("+this.translate+")rotate("+this.rotate+")skewX("+this.skew+")scale("+this.scale+")"};var yl={a:1,b:0,c:0,d:1,e:0,f:0};uo.interpolateTransform=Zn,uo.layout={},uo.layout.bundle=function(){return function(t){for(var e=[],r=-1,n=t.length;++r<n;)e.push(Qn(t[r]));return e}},uo.layout.chord=function(){function t(){var t,u,h,f,d,p={},g=[],v=uo.range(a),m=[];for(r=[],n=[],t=0,f=-1;++f<a;){for(u=0,d=-1;++d<a;)u+=i[f][d];g.push(u),m.push(uo.range(a)),t+=u}for(o&&v.sort(function(t,e){return o(g[t],g[e])}),s&&m.forEach(function(t,e){t.sort(function(t,r){return s(i[e][t],i[e][r])})}),t=(Uo-c*a)/t,u=0,f=-1;++f<a;){for(h=u,d=-1;++d<a;){var y=v[f],b=m[y][d],x=i[y][b],_=u,w=u+=x*t;p[y+"-"+b]={index:y,subindex:b,startAngle:_,endAngle:w,value:x}}n[y]={index:y,startAngle:h,endAngle:u,value:g[y]},u+=c}for(f=-1;++f<a;)for(d=f-1;++d<a;){var A=p[f+"-"+d],k=p[d+"-"+f];(A.value||k.value)&&r.push(A.value<k.value?{source:k,target:A}:{source:A,target:k})}l&&e()}function e(){r.sort(function(t,e){return l((t.source.value+t.target.value)/2,(e.source.value+e.target.value)/2)})}var r,n,i,a,o,s,l,u={},c=0;return u.matrix=function(t){return arguments.length?(a=(i=t)&&i.length,r=n=null,u):i},u.padding=function(t){return arguments.length?(c=t,r=n=null,u):c},u.sortGroups=function(t){return arguments.length?(o=t,r=n=null,u):o},u.sortSubgroups=function(t){return arguments.length?(s=t,r=null,u):s},u.sortChords=function(t){return arguments.length?(l=t,r&&e(),u):l},u.chords=function(){return r||t(),r},u.groups=function(){return n||t(),n},u},uo.layout.force=function(){function t(t){return function(e,r,n,i){if(e.point!==t){var a=e.cx-t.x,o=e.cy-t.y,s=i-r,l=a*a+o*o;if(l>s*s/m){if(g>l){var u=e.charge/l;t.px-=a*u,t.py-=o*u}return!0}if(e.point&&l&&g>l){var u=e.pointCharge/l;t.px-=a*u,t.py-=o*u}}return!e.charge}}function e(t){t.px=uo.event.x,t.py=uo.event.y,l.resume()}var r,n,i,a,o,s,l={},u=uo.dispatch("start","tick","end"),c=[1,1],h=.9,f=bl,d=xl,p=-30,g=_l,v=.1,m=.64,y=[],b=[];return l.tick=function(){if((i*=.99)<.005)return r=null,u.end({type:"end",alpha:i=0}),!0;var e,n,l,f,d,g,m,x,_,w=y.length,A=b.length;for(n=0;A>n;++n)l=b[n],f=l.source,d=l.target,x=d.x-f.x,_=d.y-f.y,(g=x*x+_*_)&&(g=i*o[n]*((g=Math.sqrt(g))-a[n])/g,x*=g,_*=g,d.x-=x*(m=f.weight+d.weight?f.weight/(f.weight+d.weight):.5),d.y-=_*m,f.x+=x*(m=1-m),f.y+=_*m);if((m=i*v)&&(x=c[0]/2,_=c[1]/2,n=-1,m))for(;++n<w;)l=y[n],l.x+=(x-l.x)*m,l.y+=(_-l.y)*m;if(p)for(ai(e=uo.geom.quadtree(y),i,s),n=-1;++n<w;)(l=y[n]).fixed||e.visit(t(l));for(n=-1;++n<w;)l=y[n],l.fixed?(l.x=l.px,l.y=l.py):(l.x-=(l.px-(l.px=l.x))*h,l.y-=(l.py-(l.py=l.y))*h);u.tick({type:"tick",alpha:i})},l.nodes=function(t){return arguments.length?(y=t,l):y},l.links=function(t){return arguments.length?(b=t,l):b},l.size=function(t){return arguments.length?(c=t,l):c},l.linkDistance=function(t){return arguments.length?(f="function"==typeof t?t:+t,l):f},l.distance=l.linkDistance,l.linkStrength=function(t){return arguments.length?(d="function"==typeof t?t:+t,l):d},l.friction=function(t){return arguments.length?(h=+t,l):h},l.charge=function(t){return arguments.length?(p="function"==typeof t?t:+t,l):p},l.chargeDistance=function(t){return arguments.length?(g=t*t,l):Math.sqrt(g)},l.gravity=function(t){return arguments.length?(v=+t,l):v},l.theta=function(t){return arguments.length?(m=t*t,l):Math.sqrt(m)},l.alpha=function(t){return arguments.length?(t=+t,i?t>0?i=t:(r.c=null,r.t=NaN,r=null,u.end({type:"end",alpha:i=0})):t>0&&(u.start({type:"start",alpha:i=t}),r=Rt(l.tick)),l):i},l.start=function(){function t(t,n){if(!r){for(r=new Array(i),l=0;i>l;++l)r[l]=[];for(l=0;u>l;++l){var a=b[l];r[a.source.index].push(a.target),r[a.target.index].push(a.source)}}for(var o,s=r[e],l=-1,c=s.length;++l<c;)if(!isNaN(o=s[l][t]))return o;return Math.random()*n}var e,r,n,i=y.length,u=b.length,h=c[0],g=c[1];for(e=0;i>e;++e)(n=y[e]).index=e,n.weight=0;for(e=0;u>e;++e)n=b[e],"number"==typeof n.source&&(n.source=y[n.source]),"number"==typeof n.target&&(n.target=y[n.target]),++n.source.weight,++n.target.weight;for(e=0;i>e;++e)n=y[e],isNaN(n.x)&&(n.x=t("x",h)),isNaN(n.y)&&(n.y=t("y",g)),isNaN(n.px)&&(n.px=n.x),isNaN(n.py)&&(n.py=n.y);if(a=[],"function"==typeof f)for(e=0;u>e;++e)a[e]=+f.call(this,b[e],e);else for(e=0;u>e;++e)a[e]=f;if(o=[],"function"==typeof d)for(e=0;u>e;++e)o[e]=+d.call(this,b[e],e);else for(e=0;u>e;++e)o[e]=d;if(s=[],"function"==typeof p)for(e=0;i>e;++e)s[e]=+p.call(this,y[e],e);else for(e=0;i>e;++e)s[e]=p;return l.resume()},l.resume=function(){return l.alpha(.1)},l.stop=function(){return l.alpha(0)},l.drag=function(){return n||(n=uo.behavior.drag().origin(x).on("dragstart.force",ei).on("drag.force",e).on("dragend.force",ri)),arguments.length?void this.on("mouseover.force",ni).on("mouseout.force",ii).call(n):n},uo.rebind(l,u,"on")};var bl=20,xl=1,_l=1/0;uo.layout.hierarchy=function(){function t(i){var a,o=[i],s=[];for(i.depth=0;null!=(a=o.pop());)if(s.push(a),(u=r.call(t,a,a.depth))&&(l=u.length)){for(var l,u,c;--l>=0;)o.push(c=u[l]),c.parent=a,c.depth=a.depth+1;n&&(a.value=0),a.children=u}else n&&(a.value=+n.call(t,a,a.depth)||0),delete a.children;return li(i,function(t){var r,i;e&&(r=t.children)&&r.sort(e),n&&(i=t.parent)&&(i.value+=t.value)}),s}var e=hi,r=ui,n=ci;return t.sort=function(r){return arguments.length?(e=r,t):e},t.children=function(e){return arguments.length?(r=e,t):r},t.value=function(e){return arguments.length?(n=e,t):n},t.revalue=function(e){return n&&(si(e,function(t){t.children&&(t.value=0)}),li(e,function(e){var r;e.children||(e.value=+n.call(t,e,e.depth)||0),(r=e.parent)&&(r.value+=e.value)})),e},t},uo.layout.partition=function(){function t(e,r,n,i){var a=e.children;if(e.x=r,e.y=e.depth*i,e.dx=n,e.dy=i,a&&(o=a.length)){var o,s,l,u=-1;for(n=e.value?n/e.value:0;++u<o;)t(s=a[u],r,l=s.value*n,i),r+=l}}function e(t){var r=t.children,n=0;if(r&&(i=r.length))for(var i,a=-1;++a<i;)n=Math.max(n,e(r[a]));return 1+n}function r(r,a){var o=n.call(this,r,a);return t(o[0],0,i[0],i[1]/e(o[0])),o}var n=uo.layout.hierarchy(),i=[1,1];return r.size=function(t){return arguments.length?(i=t,r):i},oi(r,n)},uo.layout.pie=function(){function t(o){var s,l=o.length,u=o.map(function(r,n){return+e.call(t,r,n)}),c=+("function"==typeof n?n.apply(this,arguments):n),h=("function"==typeof i?i.apply(this,arguments):i)-c,f=Math.min(Math.abs(h)/l,+("function"==typeof a?a.apply(this,arguments):a)),d=f*(0>h?-1:1),p=uo.sum(u),g=p?(h-l*d)/p:0,v=uo.range(l),m=[];return null!=r&&v.sort(r===wl?function(t,e){return u[e]-u[t]}:function(t,e){return r(o[t],o[e])}),v.forEach(function(t){m[t]={data:o[t],value:s=u[t],startAngle:c,endAngle:c+=s*g+d,padAngle:f}}),m}var e=Number,r=wl,n=0,i=Uo,a=0;return t.value=function(r){return arguments.length?(e=r,t):e},t.sort=function(e){return arguments.length?(r=e,t):r},t.startAngle=function(e){return arguments.length?(n=e,t):n},t.endAngle=function(e){return arguments.length?(i=e,t):i},t.padAngle=function(e){return arguments.length?(a=e,t):a},t};var wl={};uo.layout.stack=function(){function t(s,l){if(!(f=s.length))return s;var u=s.map(function(r,n){return e.call(t,r,n)}),c=u.map(function(e){return e.map(function(e,r){return[a.call(t,e,r),o.call(t,e,r)]})}),h=r.call(t,c,l);u=uo.permute(u,h),c=uo.permute(c,h);var f,d,p,g,v=n.call(t,c,l),m=u[0].length;for(p=0;m>p;++p)for(i.call(t,u[0][p],g=v[p],c[0][p][1]),d=1;f>d;++d)i.call(t,u[d][p],g+=c[d-1][p][1],c[d][p][1]);return s}var e=x,r=vi,n=mi,i=gi,a=di,o=pi;return t.values=function(r){return arguments.length?(e=r,t):e},t.order=function(e){return arguments.length?(r="function"==typeof e?e:Al.get(e)||vi,t):r},t.offset=function(e){return arguments.length?(n="function"==typeof e?e:kl.get(e)||mi,t):n},t.x=function(e){return arguments.length?(a=e,t):a},t.y=function(e){return arguments.length?(o=e,t):o},t.out=function(e){return arguments.length?(i=e,t):i},t};var Al=uo.map({"inside-out":function(t){var e,r,n=t.length,i=t.map(yi),a=t.map(bi),o=uo.range(n).sort(function(t,e){return i[t]-i[e]}),s=0,l=0,u=[],c=[];for(e=0;n>e;++e)r=o[e],l>s?(s+=a[r],u.push(r)):(l+=a[r],c.push(r));return c.reverse().concat(u)},reverse:function(t){return uo.range(t.length).reverse()},"default":vi}),kl=uo.map({silhouette:function(t){var e,r,n,i=t.length,a=t[0].length,o=[],s=0,l=[];for(r=0;a>r;++r){for(e=0,n=0;i>e;e++)n+=t[e][r][1];n>s&&(s=n),o.push(n)}for(r=0;a>r;++r)l[r]=(s-o[r])/2;return l},wiggle:function(t){var e,r,n,i,a,o,s,l,u,c=t.length,h=t[0],f=h.length,d=[];for(d[0]=l=u=0,r=1;f>r;++r){for(e=0,i=0;c>e;++e)i+=t[e][r][1];for(e=0,a=0,s=h[r][0]-h[r-1][0];c>e;++e){for(n=0,o=(t[e][r][1]-t[e][r-1][1])/(2*s);e>n;++n)o+=(t[n][r][1]-t[n][r-1][1])/s;a+=o*t[e][r][1]}d[r]=l-=i?a/i*s:0,u>l&&(u=l)}for(r=0;f>r;++r)d[r]-=u;return d},expand:function(t){var e,r,n,i=t.length,a=t[0].length,o=1/i,s=[];for(r=0;a>r;++r){for(e=0,n=0;i>e;e++)n+=t[e][r][1];if(n)for(e=0;i>e;e++)t[e][r][1]/=n;else for(e=0;i>e;e++)t[e][r][1]=o}for(r=0;a>r;++r)s[r]=0;return s},zero:mi});uo.layout.histogram=function(){function t(t,a){for(var o,s,l=[],u=t.map(r,this),c=n.call(this,u,a),h=i.call(this,c,u,a),a=-1,f=u.length,d=h.length-1,p=e?1:1/f;++a<d;)o=l[a]=[],o.dx=h[a+1]-(o.x=h[a]),o.y=0;if(d>0)for(a=-1;++a<f;)s=u[a],s>=c[0]&&s<=c[1]&&(o=l[uo.bisect(h,s,1,d)-1],o.y+=p,o.push(t[a]));return l}var e=!0,r=Number,n=Ai,i=_i;return t.value=function(e){return arguments.length?(r=e,t):r},t.range=function(e){return arguments.length?(n=Lt(e),t):n},t.bins=function(e){return arguments.length?(i="number"==typeof e?function(t){return wi(t,e)}:Lt(e),t):i},t.frequency=function(r){return arguments.length?(e=!!r,t):e},t},uo.layout.pack=function(){function t(t,a){var o=r.call(this,t,a),s=o[0],l=i[0],u=i[1],c=null==e?Math.sqrt:"function"==typeof e?e:function(){return e};if(s.x=s.y=0,li(s,function(t){t.r=+c(t.value)}),li(s,Li),n){var h=n*(e?1:Math.max(2*s.r/l,2*s.r/u))/2;li(s,function(t){t.r+=h}),li(s,Li),li(s,function(t){t.r-=h})}return Pi(s,l/2,u/2,e?1:1/Math.max(2*s.r/l,2*s.r/u)),o}var e,r=uo.layout.hierarchy().sort(ki),n=0,i=[1,1];return t.size=function(e){return arguments.length?(i=e,t):i},t.radius=function(r){return arguments.length?(e=null==r||"function"==typeof r?r:+r,t):e},t.padding=function(e){return arguments.length?(n=+e,t):n},oi(t,r)},uo.layout.tree=function(){function t(t,i){var c=o.call(this,t,i),h=c[0],f=e(h);if(li(f,r),f.parent.m=-f.z,si(f,n),u)si(h,a);else{var d=h,p=h,g=h;si(h,function(t){t.x<d.x&&(d=t),t.x>p.x&&(p=t),t.depth>g.depth&&(g=t)});var v=s(d,p)/2-d.x,m=l[0]/(p.x+s(p,d)/2+v),y=l[1]/(g.depth||1);si(h,function(t){t.x=(t.x+v)*m,t.y=t.depth*y})}return c}function e(t){for(var e,r={A:null,children:[t]},n=[r];null!=(e=n.pop());)for(var i,a=e.children,o=0,s=a.length;s>o;++o)n.push((a[o]=i={_:a[o],parent:e,children:(i=a[o].children)&&i.slice()||[],A:null,a:null,z:0,m:0,c:0,s:0,t:null,i:o}).a=i);return r.children[0]}function r(t){var e=t.children,r=t.parent.children,n=t.i?r[t.i-1]:null;if(e.length){Ni(t);var a=(e[0].z+e[e.length-1].z)/2;n?(t.z=n.z+s(t._,n._),t.m=t.z-a):t.z=a}else n&&(t.z=n.z+s(t._,n._));t.parent.A=i(t,n,t.parent.A||r[0])}function n(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function i(t,e,r){if(e){for(var n,i=t,a=t,o=e,l=i.parent.children[0],u=i.m,c=a.m,h=o.m,f=l.m;o=Ii(o),i=Oi(i),o&&i;)l=Oi(l),a=Ii(a),a.a=t,n=o.z+h-i.z-u+s(o._,i._),n>0&&(ji(Fi(o,t,r),t,n),u+=n,c+=n),h+=o.m,u+=i.m,f+=l.m,c+=a.m;o&&!Ii(a)&&(a.t=o,a.m+=h-c),i&&!Oi(l)&&(l.t=i,l.m+=u-f,r=t)}return r}function a(t){t.x*=l[0],t.y=t.depth*l[1]}var o=uo.layout.hierarchy().sort(null).value(null),s=Ri,l=[1,1],u=null;return t.separation=function(e){return arguments.length?(s=e,t):s},t.size=function(e){return arguments.length?(u=null==(l=e)?a:null,t):u?null:l},t.nodeSize=function(e){return arguments.length?(u=null==(l=e)?null:a,t):u?l:null},oi(t,o)},uo.layout.cluster=function(){function t(t,a){var o,s=e.call(this,t,a),l=s[0],u=0;li(l,function(t){var e=t.children;e&&e.length?(t.x=Di(e),t.y=Bi(e)):(t.x=o?u+=r(t,o):0,t.y=0,o=t)});var c=Ui(l),h=Vi(l),f=c.x-r(c,h)/2,d=h.x+r(h,c)/2;return li(l,i?function(t){t.x=(t.x-l.x)*n[0],t.y=(l.y-t.y)*n[1]}:function(t){t.x=(t.x-f)/(d-f)*n[0],t.y=(1-(l.y?t.y/l.y:1))*n[1]}),s}var e=uo.layout.hierarchy().sort(null).value(null),r=Ri,n=[1,1],i=!1;return t.separation=function(e){return arguments.length?(r=e,t):r},t.size=function(e){return arguments.length?(i=null==(n=e),t):i?null:n},t.nodeSize=function(e){return arguments.length?(i=null!=(n=e),t):i?n:null},oi(t,e)},uo.layout.treemap=function(){function t(t,e){for(var r,n,i=-1,a=t.length;++i<a;)n=(r=t[i]).value*(0>e?0:e),r.area=isNaN(n)||0>=n?0:n}function e(r){var a=r.children;if(a&&a.length){var o,s,l,u=h(r),c=[],f=a.slice(),p=1/0,g="slice"===d?u.dx:"dice"===d?u.dy:"slice-dice"===d?1&r.depth?u.dy:u.dx:Math.min(u.dx,u.dy);for(t(f,u.dx*u.dy/r.value),c.area=0;(l=f.length)>0;)c.push(o=f[l-1]),c.area+=o.area,"squarify"!==d||(s=n(c,g))<=p?(f.pop(),p=s):(c.area-=c.pop().area,i(c,g,u,!1),g=Math.min(u.dx,u.dy),c.length=c.area=0,p=1/0);c.length&&(i(c,g,u,!0),c.length=c.area=0),a.forEach(e)}}function r(e){var n=e.children;if(n&&n.length){var a,o=h(e),s=n.slice(),l=[];for(t(s,o.dx*o.dy/e.value),l.area=0;a=s.pop();)l.push(a),l.area+=a.area,null!=a.z&&(i(l,a.z?o.dx:o.dy,o,!s.length),l.length=l.area=0);n.forEach(r)}}function n(t,e){for(var r,n=t.area,i=0,a=1/0,o=-1,s=t.length;++o<s;)(r=t[o].area)&&(a>r&&(a=r),r>i&&(i=r));return n*=n,e*=e,n?Math.max(e*i*p/n,n/(e*a*p)):1/0}function i(t,e,r,n){var i,a=-1,o=t.length,s=r.x,u=r.y,c=e?l(t.area/e):0;if(e==r.dx){for((n||c>r.dy)&&(c=r.dy);++a<o;)i=t[a],i.x=s,i.y=u,i.dy=c,s+=i.dx=Math.min(r.x+r.dx-s,c?l(i.area/c):0);i.z=!0,i.dx+=r.x+r.dx-s,r.y+=c,r.dy-=c}else{for((n||c>r.dx)&&(c=r.dx);++a<o;)i=t[a],i.x=s,i.y=u,i.dx=c,u+=i.dy=Math.min(r.y+r.dy-u,c?l(i.area/c):0);i.z=!1,i.dy+=r.y+r.dy-u,r.x+=c,r.dx-=c}}function a(n){var i=o||s(n),a=i[0];return a.x=a.y=0,a.value?(a.dx=u[0],a.dy=u[1]):a.dx=a.dy=0,o&&s.revalue(a),t([a],a.dx*a.dy/a.value),(o?r:e)(a),f&&(o=i),i}var o,s=uo.layout.hierarchy(),l=Math.round,u=[1,1],c=null,h=qi,f=!1,d="squarify",p=.5*(1+Math.sqrt(5));return a.size=function(t){return arguments.length?(u=t,a):u},a.padding=function(t){function e(e){var r=t.call(a,e,e.depth);return null==r?qi(e):Hi(e,"number"==typeof r?[r,r,r,r]:r)}function r(e){return Hi(e,t)}if(!arguments.length)return c;var n;return h=null==(c=t)?qi:"function"==(n=typeof t)?e:"number"===n?(t=[t,t,t,t],r):r,a},a.round=function(t){return arguments.length?(l=t?Math.round:Number,a):l!=Number},a.sticky=function(t){return arguments.length?(f=t,o=null,a):f},a.ratio=function(t){return arguments.length?(p=t,a):p},a.mode=function(t){return arguments.length?(d=t+"",a):d},oi(a,s)},uo.random={normal:function(t,e){var r=arguments.length;return 2>r&&(e=1),1>r&&(t=0),function(){var r,n,i;do r=2*Math.random()-1,n=2*Math.random()-1,i=r*r+n*n;while(!i||i>1);return t+e*r*Math.sqrt(-2*Math.log(i)/i)}},logNormal:function(){var t=uo.random.normal.apply(uo,arguments);return function(){return Math.exp(t())}},bates:function(t){var e=uo.random.irwinHall(t);return function(){return e()/t}},irwinHall:function(t){return function(){for(var e=0,r=0;t>r;r++)e+=Math.random();return e}}},uo.scale={};var Ml={floor:x,ceil:x};uo.scale.linear=function(){return Ki([0,1],[0,1],_n,!1)};var Tl={s:1,g:1,p:1,r:1,e:1};uo.scale.log=function(){return aa(uo.scale.linear().domain([0,1]),10,!0,[1,10])};var El=uo.format(".0e"),Ll={floor:function(t){return-Math.ceil(-t)},ceil:function(t){return-Math.floor(-t)}};uo.scale.pow=function(){return oa(uo.scale.linear(),1,[0,1])},uo.scale.sqrt=function(){return uo.scale.pow().exponent(.5)},uo.scale.ordinal=function(){return la([],{t:"range",a:[[]]})},uo.scale.category10=function(){return uo.scale.ordinal().range(Sl)},uo.scale.category20=function(){return uo.scale.ordinal().range(Cl)},uo.scale.category20b=function(){return uo.scale.ordinal().range(Pl)},uo.scale.category20c=function(){return uo.scale.ordinal().range(zl)};var Sl=[2062260,16744206,2924588,14034728,9725885,9197131,14907330,8355711,12369186,1556175].map(_t),Cl=[2062260,11454440,16744206,16759672,2924588,10018698,14034728,16750742,9725885,12955861,9197131,12885140,14907330,16234194,8355711,13092807,12369186,14408589,1556175,10410725].map(_t),Pl=[3750777,5395619,7040719,10264286,6519097,9216594,11915115,13556636,9202993,12426809,15186514,15190932,8666169,11356490,14049643,15177372,8077683,10834324,13528509,14589654].map(_t),zl=[3244733,7057110,10406625,13032431,15095053,16616764,16625259,16634018,3253076,7652470,10607003,13101504,7695281,10394312,12369372,14342891,6513507,9868950,12434877,14277081].map(_t);uo.scale.quantile=function(){return ua([],[])},uo.scale.quantize=function(){return ca(0,1,[0,1])},uo.scale.threshold=function(){return ha([.5],[0,1])},uo.scale.identity=function(){return fa([0,1])},uo.svg={},uo.svg.arc=function(){function t(){var t=Math.max(0,+r.apply(this,arguments)),u=Math.max(0,+n.apply(this,arguments)),c=o.apply(this,arguments)-qo,h=s.apply(this,arguments)-qo,f=Math.abs(h-c),d=c>h?0:1;if(t>u&&(p=u,u=t,t=p),f>=Vo)return e(u,d)+(t?e(t,1-d):"")+"Z";var p,g,v,m,y,b,x,_,w,A,k,M,T=0,E=0,L=[];if((m=(+l.apply(this,arguments)||0)/2)&&(v=a===Rl?Math.sqrt(t*t+u*u):+a.apply(this,arguments),d||(E*=-1),u&&(E=nt(v/u*Math.sin(m))),t&&(T=nt(v/t*Math.sin(m)))),u){y=u*Math.cos(c+E),b=u*Math.sin(c+E),x=u*Math.cos(h-E),_=u*Math.sin(h-E);var S=Math.abs(h-c-2*E)<=Do?0:1;if(E&&ba(y,b,x,_)===d^S){var C=(c+h)/2;y=u*Math.cos(C),b=u*Math.sin(C),x=_=null}}else y=b=0;if(t){w=t*Math.cos(h-T),A=t*Math.sin(h-T),k=t*Math.cos(c+T),M=t*Math.sin(c+T);var P=Math.abs(c-h+2*T)<=Do?0:1;if(T&&ba(w,A,k,M)===1-d^P){var z=(c+h)/2;w=t*Math.cos(z),A=t*Math.sin(z),k=M=null}}else w=A=0;if(f>Fo&&(p=Math.min(Math.abs(u-t)/2,+i.apply(this,arguments)))>.001){g=u>t^d?0:1;var R=p,O=p;if(Do>f){var I=null==k?[w,A]:null==x?[y,b]:Ir([y,b],[k,M],[x,_],[w,A]),j=y-I[0],N=b-I[1],F=x-I[0],B=_-I[1],D=1/Math.sin(Math.acos((j*F+N*B)/(Math.sqrt(j*j+N*N)*Math.sqrt(F*F+B*B)))/2),U=Math.sqrt(I[0]*I[0]+I[1]*I[1]);O=Math.min(p,(t-U)/(D-1)),R=Math.min(p,(u-U)/(D+1))}if(null!=x){var V=xa(null==k?[w,A]:[k,M],[y,b],u,R,d),q=xa([x,_],[w,A],u,R,d);p===R?L.push("M",V[0],"A",R,",",R," 0 0,",g," ",V[1],"A",u,",",u," 0 ",1-d^ba(V[1][0],V[1][1],q[1][0],q[1][1]),",",d," ",q[1],"A",R,",",R," 0 0,",g," ",q[0]):L.push("M",V[0],"A",R,",",R," 0 1,",g," ",q[0])}else L.push("M",y,",",b);if(null!=k){var H=xa([y,b],[k,M],t,-O,d),G=xa([w,A],null==x?[y,b]:[x,_],t,-O,d);p===O?L.push("L",G[0],"A",O,",",O," 0 0,",g," ",G[1],"A",t,",",t," 0 ",d^ba(G[1][0],G[1][1],H[1][0],H[1][1]),",",1-d," ",H[1],"A",O,",",O," 0 0,",g," ",H[0]):L.push("L",G[0],"A",O,",",O," 0 0,",g," ",H[0])}else L.push("L",w,",",A)}else L.push("M",y,",",b),null!=x&&L.push("A",u,",",u," 0 ",S,",",d," ",x,",",_),L.push("L",w,",",A),null!=k&&L.push("A",t,",",t," 0 ",P,",",1-d," ",k,",",M);return L.push("Z"),L.join("")}function e(t,e){return"M0,"+t+"A"+t+","+t+" 0 1,"+e+" 0,"+-t+"A"+t+","+t+" 0 1,"+e+" 0,"+t}var r=pa,n=ga,i=da,a=Rl,o=va,s=ma,l=ya;return t.innerRadius=function(e){return arguments.length?(r=Lt(e),t):r},t.outerRadius=function(e){return arguments.length?(n=Lt(e),
+t):n},t.cornerRadius=function(e){return arguments.length?(i=Lt(e),t):i},t.padRadius=function(e){return arguments.length?(a=e==Rl?Rl:Lt(e),t):a},t.startAngle=function(e){return arguments.length?(o=Lt(e),t):o},t.endAngle=function(e){return arguments.length?(s=Lt(e),t):s},t.padAngle=function(e){return arguments.length?(l=Lt(e),t):l},t.centroid=function(){var t=(+r.apply(this,arguments)+ +n.apply(this,arguments))/2,e=(+o.apply(this,arguments)+ +s.apply(this,arguments))/2-qo;return[Math.cos(e)*t,Math.sin(e)*t]},t};var Rl="auto";uo.svg.line=function(){return _a(x)};var Ol=uo.map({linear:wa,"linear-closed":Aa,step:ka,"step-before":Ma,"step-after":Ta,basis:za,"basis-open":Ra,"basis-closed":Oa,bundle:Ia,cardinal:Sa,"cardinal-open":Ea,"cardinal-closed":La,monotone:Ua});Ol.forEach(function(t,e){e.key=t,e.closed=/-closed$/.test(t)});var Il=[0,2/3,1/3,0],jl=[0,1/3,2/3,0],Nl=[0,1/6,2/3,1/6];uo.svg.line.radial=function(){var t=_a(Va);return t.radius=t.x,delete t.x,t.angle=t.y,delete t.y,t},Ma.reverse=Ta,Ta.reverse=Ma,uo.svg.area=function(){return qa(x)},uo.svg.area.radial=function(){var t=qa(Va);return t.radius=t.x,delete t.x,t.innerRadius=t.x0,delete t.x0,t.outerRadius=t.x1,delete t.x1,t.angle=t.y,delete t.y,t.startAngle=t.y0,delete t.y0,t.endAngle=t.y1,delete t.y1,t},uo.svg.chord=function(){function t(t,s){var l=e(this,a,t,s),u=e(this,o,t,s);return"M"+l.p0+n(l.r,l.p1,l.a1-l.a0)+(r(l,u)?i(l.r,l.p1,l.r,l.p0):i(l.r,l.p1,u.r,u.p0)+n(u.r,u.p1,u.a1-u.a0)+i(u.r,u.p1,l.r,l.p0))+"Z"}function e(t,e,r,n){var i=e.call(t,r,n),a=s.call(t,i,n),o=l.call(t,i,n)-qo,c=u.call(t,i,n)-qo;return{r:a,a0:o,a1:c,p0:[a*Math.cos(o),a*Math.sin(o)],p1:[a*Math.cos(c),a*Math.sin(c)]}}function r(t,e){return t.a0==e.a0&&t.a1==e.a1}function n(t,e,r){return"A"+t+","+t+" 0 "+ +(r>Do)+",1 "+e}function i(t,e,r,n){return"Q 0,0 "+n}var a=xr,o=_r,s=Ha,l=va,u=ma;return t.radius=function(e){return arguments.length?(s=Lt(e),t):s},t.source=function(e){return arguments.length?(a=Lt(e),t):a},t.target=function(e){return arguments.length?(o=Lt(e),t):o},t.startAngle=function(e){return arguments.length?(l=Lt(e),t):l},t.endAngle=function(e){return arguments.length?(u=Lt(e),t):u},t},uo.svg.diagonal=function(){function t(t,i){var a=e.call(this,t,i),o=r.call(this,t,i),s=(a.y+o.y)/2,l=[a,{x:a.x,y:s},{x:o.x,y:s},o];return l=l.map(n),"M"+l[0]+"C"+l[1]+" "+l[2]+" "+l[3]}var e=xr,r=_r,n=Ga;return t.source=function(r){return arguments.length?(e=Lt(r),t):e},t.target=function(e){return arguments.length?(r=Lt(e),t):r},t.projection=function(e){return arguments.length?(n=e,t):n},t},uo.svg.diagonal.radial=function(){var t=uo.svg.diagonal(),e=Ga,r=t.projection;return t.projection=function(t){return arguments.length?r(Ya(e=t)):e},t},uo.svg.symbol=function(){function t(t,n){return(Fl.get(e.call(this,t,n))||Za)(r.call(this,t,n))}var e=Wa,r=Xa;return t.type=function(r){return arguments.length?(e=Lt(r),t):e},t.size=function(e){return arguments.length?(r=Lt(e),t):r},t};var Fl=uo.map({circle:Za,cross:function(t){var e=Math.sqrt(t/5)/2;return"M"+-3*e+","+-e+"H"+-e+"V"+-3*e+"H"+e+"V"+-e+"H"+3*e+"V"+e+"H"+e+"V"+3*e+"H"+-e+"V"+e+"H"+-3*e+"Z"},diamond:function(t){var e=Math.sqrt(t/(2*Dl)),r=e*Dl;return"M0,"+-e+"L"+r+",0 0,"+e+" "+-r+",0Z"},square:function(t){var e=Math.sqrt(t)/2;return"M"+-e+","+-e+"L"+e+","+-e+" "+e+","+e+" "+-e+","+e+"Z"},"triangle-down":function(t){var e=Math.sqrt(t/Bl),r=e*Bl/2;return"M0,"+r+"L"+e+","+-r+" "+-e+","+-r+"Z"},"triangle-up":function(t){var e=Math.sqrt(t/Bl),r=e*Bl/2;return"M0,"+-r+"L"+e+","+r+" "+-e+","+r+"Z"}});uo.svg.symbolTypes=Fl.keys();var Bl=Math.sqrt(3),Dl=Math.tan(30*Ho);Po.transition=function(t){for(var e,r,n=Ul||++Gl,i=to(t),a=[],o=Vl||{time:Date.now(),ease:Ln,delay:0,duration:250},s=-1,l=this.length;++s<l;){a.push(e=[]);for(var u=this[s],c=-1,h=u.length;++c<h;)(r=u[c])&&eo(r,c,i,n,o),e.push(r)}return Ka(a,i,n)},Po.interrupt=function(t){return this.each(null==t?ql:$a(to(t)))};var Ul,Vl,ql=$a(to()),Hl=[],Gl=0;Hl.call=Po.call,Hl.empty=Po.empty,Hl.node=Po.node,Hl.size=Po.size,uo.transition=function(t,e){return t&&t.transition?Ul?t.transition(e):t:uo.selection().transition(t)},uo.transition.prototype=Hl,Hl.select=function(t){var e,r,n,i=this.id,a=this.namespace,o=[];t=C(t);for(var s=-1,l=this.length;++s<l;){o.push(e=[]);for(var u=this[s],c=-1,h=u.length;++c<h;)(n=u[c])&&(r=t.call(n,n.__data__,c,s))?("__data__"in n&&(r.__data__=n.__data__),eo(r,c,a,i,n[a][i]),e.push(r)):e.push(null)}return Ka(o,a,i)},Hl.selectAll=function(t){var e,r,n,i,a,o=this.id,s=this.namespace,l=[];t=P(t);for(var u=-1,c=this.length;++u<c;)for(var h=this[u],f=-1,d=h.length;++f<d;)if(n=h[f]){a=n[s][o],r=t.call(n,n.__data__,f,u),l.push(e=[]);for(var p=-1,g=r.length;++p<g;)(i=r[p])&&eo(i,p,s,o,a),e.push(i)}return Ka(l,s,o)},Hl.filter=function(t){var e,r,n,i=[];"function"!=typeof t&&(t=q(t));for(var a=0,o=this.length;o>a;a++){i.push(e=[]);for(var r=this[a],s=0,l=r.length;l>s;s++)(n=r[s])&&t.call(n,n.__data__,s,a)&&e.push(n)}return Ka(i,this.namespace,this.id)},Hl.tween=function(t,e){var r=this.id,n=this.namespace;return arguments.length<2?this.node()[n][r].tween.get(t):G(this,null==e?function(e){e[n][r].tween.remove(t)}:function(i){i[n][r].tween.set(t,e)})},Hl.attr=function(t,e){function r(){this.removeAttribute(s)}function n(){this.removeAttributeNS(s.space,s.local)}function i(t){return null==t?r:(t+="",function(){var e,r=this.getAttribute(s);return r!==t&&(e=o(r,t),function(t){this.setAttribute(s,e(t))})})}function a(t){return null==t?n:(t+="",function(){var e,r=this.getAttributeNS(s.space,s.local);return r!==t&&(e=o(r,t),function(t){this.setAttributeNS(s.space,s.local,e(t))})})}if(arguments.length<2){for(e in t)this.attr(e,t[e]);return this}var o="transform"==t?Zn:_n,s=uo.ns.qualify(t);return Qa(this,"attr."+t,e,s.local?a:i)},Hl.attrTween=function(t,e){function r(t,r){var n=e.call(this,t,r,this.getAttribute(i));return n&&function(t){this.setAttribute(i,n(t))}}function n(t,r){var n=e.call(this,t,r,this.getAttributeNS(i.space,i.local));return n&&function(t){this.setAttributeNS(i.space,i.local,n(t))}}var i=uo.ns.qualify(t);return this.tween("attr."+t,i.local?n:r)},Hl.style=function(t,e,r){function i(){this.style.removeProperty(t)}function a(e){return null==e?i:(e+="",function(){var i,a=n(this).getComputedStyle(this,null).getPropertyValue(t);return a!==e&&(i=_n(a,e),function(e){this.style.setProperty(t,i(e),r)})})}var o=arguments.length;if(3>o){if("string"!=typeof t){2>o&&(e="");for(r in t)this.style(r,t[r],e);return this}r=""}return Qa(this,"style."+t,e,a)},Hl.styleTween=function(t,e,r){function i(i,a){var o=e.call(this,i,a,n(this).getComputedStyle(this,null).getPropertyValue(t));return o&&function(e){this.style.setProperty(t,o(e),r)}}return arguments.length<3&&(r=""),this.tween("style."+t,i)},Hl.text=function(t){return Qa(this,"text",t,Ja)},Hl.remove=function(){var t=this.namespace;return this.each("end.transition",function(){var e;this[t].count<2&&(e=this.parentNode)&&e.removeChild(this)})},Hl.ease=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].ease:("function"!=typeof t&&(t=uo.ease.apply(uo,arguments)),G(this,function(n){n[r][e].ease=t}))},Hl.delay=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].delay:G(this,"function"==typeof t?function(n,i,a){n[r][e].delay=+t.call(n,n.__data__,i,a)}:(t=+t,function(n){n[r][e].delay=t}))},Hl.duration=function(t){var e=this.id,r=this.namespace;return arguments.length<1?this.node()[r][e].duration:G(this,"function"==typeof t?function(n,i,a){n[r][e].duration=Math.max(1,t.call(n,n.__data__,i,a))}:(t=Math.max(1,t),function(n){n[r][e].duration=t}))},Hl.each=function(t,e){var r=this.id,n=this.namespace;if(arguments.length<2){var i=Vl,a=Ul;try{Ul=r,G(this,function(e,i,a){Vl=e[n][r],t.call(e,e.__data__,i,a)})}finally{Vl=i,Ul=a}}else G(this,function(i){var a=i[n][r];(a.event||(a.event=uo.dispatch("start","end","interrupt"))).on(t,e)});return this},Hl.transition=function(){for(var t,e,r,n,i=this.id,a=++Gl,o=this.namespace,s=[],l=0,u=this.length;u>l;l++){s.push(t=[]);for(var e=this[l],c=0,h=e.length;h>c;c++)(r=e[c])&&(n=r[o][i],eo(r,c,o,a,{time:n.time,ease:n.ease,delay:n.delay+n.duration,duration:n.duration})),t.push(r)}return Ka(s,o,a)},uo.svg.axis=function(){function t(t){t.each(function(){var t,u=uo.select(this),c=this.__chart__||r,h=this.__chart__=r.copy(),f=null==l?h.ticks?h.ticks.apply(h,s):h.domain():l,d=null==e?h.tickFormat?h.tickFormat.apply(h,s):x:e,p=u.selectAll(".tick").data(f,h),g=p.enter().insert("g",".domain").attr("class","tick").style("opacity",Fo),v=uo.transition(p.exit()).style("opacity",Fo).remove(),m=uo.transition(p.order()).style("opacity",1),y=Math.max(i,0)+o,b=Yi(h),_=u.selectAll(".domain").data([0]),w=(_.enter().append("path").attr("class","domain"),uo.transition(_));g.append("line"),g.append("text");var A,k,M,T,E=g.select("line"),L=m.select("line"),S=p.select("text").text(d),C=g.select("text"),P=m.select("text"),z="top"===n||"left"===n?-1:1;if("bottom"===n||"top"===n?(t=ro,A="x",M="y",k="x2",T="y2",S.attr("dy",0>z?"0em":".71em").style("text-anchor","middle"),w.attr("d","M"+b[0]+","+z*a+"V0H"+b[1]+"V"+z*a)):(t=no,A="y",M="x",k="y2",T="x2",S.attr("dy",".32em").style("text-anchor",0>z?"end":"start"),w.attr("d","M"+z*a+","+b[0]+"H0V"+b[1]+"H"+z*a)),E.attr(T,z*i),C.attr(M,z*y),L.attr(k,0).attr(T,z*i),P.attr(A,0).attr(M,z*y),h.rangeBand){var R=h,O=R.rangeBand()/2;c=h=function(t){return R(t)+O}}else c.rangeBand?c=h:v.call(t,h,c);g.call(t,c,h),m.call(t,h,h)})}var e,r=uo.scale.linear(),n=Yl,i=6,a=6,o=3,s=[10],l=null;return t.scale=function(e){return arguments.length?(r=e,t):r},t.orient=function(e){return arguments.length?(n=e in Xl?e+"":Yl,t):n},t.ticks=function(){return arguments.length?(s=ho(arguments),t):s},t.tickValues=function(e){return arguments.length?(l=e,t):l},t.tickFormat=function(r){return arguments.length?(e=r,t):e},t.tickSize=function(e){var r=arguments.length;return r?(i=+e,a=+arguments[r-1],t):i},t.innerTickSize=function(e){return arguments.length?(i=+e,t):i},t.outerTickSize=function(e){return arguments.length?(a=+e,t):a},t.tickPadding=function(e){return arguments.length?(o=+e,t):o},t.tickSubdivide=function(){return arguments.length&&t},t};var Yl="bottom",Xl={top:1,right:1,bottom:1,left:1};uo.svg.brush=function(){function t(n){n.each(function(){var n=uo.select(this).style("pointer-events","all").style("-webkit-tap-highlight-color","rgba(0,0,0,0)").on("mousedown.brush",a).on("touchstart.brush",a),o=n.selectAll(".background").data([0]);o.enter().append("rect").attr("class","background").style("visibility","hidden").style("cursor","crosshair"),n.selectAll(".extent").data([0]).enter().append("rect").attr("class","extent").style("cursor","move");var s=n.selectAll(".resize").data(g,x);s.exit().remove(),s.enter().append("g").attr("class",function(t){return"resize "+t}).style("cursor",function(t){return Wl[t]}).append("rect").attr("x",function(t){return/[ew]$/.test(t)?-3:null}).attr("y",function(t){return/^[ns]/.test(t)?-3:null}).attr("width",6).attr("height",6).style("visibility","hidden"),s.style("display",t.empty()?"none":null);var l,h=uo.transition(n),f=uo.transition(o);u&&(l=Yi(u),f.attr("x",l[0]).attr("width",l[1]-l[0]),r(h)),c&&(l=Yi(c),f.attr("y",l[0]).attr("height",l[1]-l[0]),i(h)),e(h)})}function e(t){t.selectAll(".resize").attr("transform",function(t){return"translate("+h[+/e$/.test(t)]+","+f[+/^s/.test(t)]+")"})}function r(t){t.select(".extent").attr("x",h[0]),t.selectAll(".extent,.n>rect,.s>rect").attr("width",h[1]-h[0])}function i(t){t.select(".extent").attr("y",f[0]),t.selectAll(".extent,.e>rect,.w>rect").attr("height",f[1]-f[0])}function a(){function a(){32==uo.event.keyCode&&(S||(b=null,P[0]-=h[1],P[1]-=f[1],S=2),T())}function g(){32==uo.event.keyCode&&2==S&&(P[0]+=h[1],P[1]+=f[1],S=0,T())}function v(){var t=uo.mouse(_),n=!1;x&&(t[0]+=x[0],t[1]+=x[1]),S||(uo.event.altKey?(b||(b=[(h[0]+h[1])/2,(f[0]+f[1])/2]),P[0]=h[+(t[0]<b[0])],P[1]=f[+(t[1]<b[1])]):b=null),E&&m(t,u,0)&&(r(k),n=!0),L&&m(t,c,1)&&(i(k),n=!0),n&&(e(k),A({type:"brush",mode:S?"move":"resize"}))}function m(t,e,r){var n,i,a=Yi(e),l=a[0],u=a[1],c=P[r],g=r?f:h,v=g[1]-g[0];return S&&(l-=c,u-=v+c),n=(r?p:d)?Math.max(l,Math.min(u,t[r])):t[r],S?i=(n+=c)+v:(b&&(c=Math.max(l,Math.min(u,2*b[r]-n))),n>c?(i=n,n=c):i=c),g[0]!=n||g[1]!=i?(r?s=null:o=null,g[0]=n,g[1]=i,!0):void 0}function y(){v(),k.style("pointer-events","all").selectAll(".resize").style("display",t.empty()?"none":null),uo.select("body").style("cursor",null),z.on("mousemove.brush",null).on("mouseup.brush",null).on("touchmove.brush",null).on("touchend.brush",null).on("keydown.brush",null).on("keyup.brush",null),C(),A({type:"brushend"})}var b,x,_=this,w=uo.select(uo.event.target),A=l.of(_,arguments),k=uo.select(_),M=w.datum(),E=!/^(n|s)$/.test(M)&&u,L=!/^(e|w)$/.test(M)&&c,S=w.classed("extent"),C=K(_),P=uo.mouse(_),z=uo.select(n(_)).on("keydown.brush",a).on("keyup.brush",g);if(uo.event.changedTouches?z.on("touchmove.brush",v).on("touchend.brush",y):z.on("mousemove.brush",v).on("mouseup.brush",y),k.interrupt().selectAll("*").interrupt(),S)P[0]=h[0]-P[0],P[1]=f[0]-P[1];else if(M){var R=+/w$/.test(M),O=+/^n/.test(M);x=[h[1-R]-P[0],f[1-O]-P[1]],P[0]=h[R],P[1]=f[O]}else uo.event.altKey&&(b=P.slice());k.style("pointer-events","none").selectAll(".resize").style("display",null),uo.select("body").style("cursor",w.style("cursor")),A({type:"brushstart"}),v()}var o,s,l=L(t,"brushstart","brush","brushend"),u=null,c=null,h=[0,0],f=[0,0],d=!0,p=!0,g=Zl[0];return t.event=function(t){t.each(function(){var t=l.of(this,arguments),e={x:h,y:f,i:o,j:s},r=this.__chart__||e;this.__chart__=e,Ul?uo.select(this).transition().each("start.brush",function(){o=r.i,s=r.j,h=r.x,f=r.y,t({type:"brushstart"})}).tween("brush:brush",function(){var r=wn(h,e.x),n=wn(f,e.y);return o=s=null,function(i){h=e.x=r(i),f=e.y=n(i),t({type:"brush",mode:"resize"})}}).each("end.brush",function(){o=e.i,s=e.j,t({type:"brush",mode:"resize"}),t({type:"brushend"})}):(t({type:"brushstart"}),t({type:"brush",mode:"resize"}),t({type:"brushend"}))})},t.x=function(e){return arguments.length?(u=e,g=Zl[!u<<1|!c],t):u},t.y=function(e){return arguments.length?(c=e,g=Zl[!u<<1|!c],t):c},t.clamp=function(e){return arguments.length?(u&&c?(d=!!e[0],p=!!e[1]):u?d=!!e:c&&(p=!!e),t):u&&c?[d,p]:u?d:c?p:null},t.extent=function(e){var r,n,i,a,l;return arguments.length?(u&&(r=e[0],n=e[1],c&&(r=r[0],n=n[0]),o=[r,n],u.invert&&(r=u(r),n=u(n)),r>n&&(l=r,r=n,n=l),(r!=h[0]||n!=h[1])&&(h=[r,n])),c&&(i=e[0],a=e[1],u&&(i=i[1],a=a[1]),s=[i,a],c.invert&&(i=c(i),a=c(a)),i>a&&(l=i,i=a,a=l),(i!=f[0]||a!=f[1])&&(f=[i,a])),t):(u&&(o?(r=o[0],n=o[1]):(r=h[0],n=h[1],u.invert&&(r=u.invert(r),n=u.invert(n)),r>n&&(l=r,r=n,n=l))),c&&(s?(i=s[0],a=s[1]):(i=f[0],a=f[1],c.invert&&(i=c.invert(i),a=c.invert(a)),i>a&&(l=i,i=a,a=l))),u&&c?[[r,i],[n,a]]:u?[r,n]:c&&[i,a])},t.clear=function(){return t.empty()||(h=[0,0],f=[0,0],o=s=null),t},t.empty=function(){return!!u&&h[0]==h[1]||!!c&&f[0]==f[1]},uo.rebind(t,l,"on")};var Wl={n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},Zl=[["n","e","s","w","nw","ne","se","sw"],["e","w"],["n","s"],[]],$l=gs.format=_s.timeFormat,Kl=$l.utc,Ql=Kl("%Y-%m-%dT%H:%M:%S.%LZ");$l.iso=Date.prototype.toISOString&&+new Date("2000-01-01T00:00:00.000Z")?io:Ql,io.parse=function(t){var e=new Date(t);return isNaN(e)?null:e},io.toString=Ql.toString,gs.second=Vt(function(t){return new vs(1e3*Math.floor(t/1e3))},function(t,e){t.setTime(t.getTime()+1e3*Math.floor(e))},function(t){return t.getSeconds()}),gs.seconds=gs.second.range,gs.seconds.utc=gs.second.utc.range,gs.minute=Vt(function(t){return new vs(6e4*Math.floor(t/6e4))},function(t,e){t.setTime(t.getTime()+6e4*Math.floor(e))},function(t){return t.getMinutes()}),gs.minutes=gs.minute.range,gs.minutes.utc=gs.minute.utc.range,gs.hour=Vt(function(t){var e=t.getTimezoneOffset()/60;return new vs(36e5*(Math.floor(t/36e5-e)+e))},function(t,e){t.setTime(t.getTime()+36e5*Math.floor(e))},function(t){return t.getHours()}),gs.hours=gs.hour.range,gs.hours.utc=gs.hour.utc.range,gs.month=Vt(function(t){return t=gs.day(t),t.setDate(1),t},function(t,e){t.setMonth(t.getMonth()+e)},function(t){return t.getMonth()}),gs.months=gs.month.range,gs.months.utc=gs.month.utc.range;var Jl=[1e3,5e3,15e3,3e4,6e4,3e5,9e5,18e5,36e5,108e5,216e5,432e5,864e5,1728e5,6048e5,2592e6,7776e6,31536e6],tu=[[gs.second,1],[gs.second,5],[gs.second,15],[gs.second,30],[gs.minute,1],[gs.minute,5],[gs.minute,15],[gs.minute,30],[gs.hour,1],[gs.hour,3],[gs.hour,6],[gs.hour,12],[gs.day,1],[gs.day,2],[gs.week,1],[gs.month,1],[gs.month,3],[gs.year,1]],eu=$l.multi([[".%L",function(t){return t.getMilliseconds()}],[":%S",function(t){return t.getSeconds()}],["%I:%M",function(t){return t.getMinutes()}],["%I %p",function(t){return t.getHours()}],["%a %d",function(t){return t.getDay()&&1!=t.getDate()}],["%b %d",function(t){return 1!=t.getDate()}],["%B",function(t){return t.getMonth()}],["%Y",Pe]]),ru={range:function(t,e,r){return uo.range(Math.ceil(t/r)*r,+e,r).map(oo)},floor:x,ceil:x};tu.year=gs.year,gs.scale=function(){return ao(uo.scale.linear(),tu,eu)};var nu=tu.map(function(t){return[t[0].utc,t[1]]}),iu=Kl.multi([[".%L",function(t){return t.getUTCMilliseconds()}],[":%S",function(t){return t.getUTCSeconds()}],["%I:%M",function(t){return t.getUTCMinutes()}],["%I %p",function(t){return t.getUTCHours()}],["%a %d",function(t){return t.getUTCDay()&&1!=t.getUTCDate()}],["%b %d",function(t){return 1!=t.getUTCDate()}],["%B",function(t){return t.getUTCMonth()}],["%Y",Pe]]);nu.year=gs.year.utc,gs.scale.utc=function(){return ao(uo.scale.linear(),nu,iu)},uo.text=St(function(t){return t.responseText}),uo.json=function(t,e){return Ct(t,"application/json",so,e)},uo.html=function(t,e){return Ct(t,"text/html",lo,e)},uo.xml=St(function(t){return t.responseXML}),"function"==typeof t&&t.amd?(this.d3=uo,t(uo)):"object"==typeof r&&r.exports?r.exports=uo:this.d3=uo}()},{}],71:[function(t,e,r){"use strict";function n(t,e){this.point=t,this.index=e}function i(t,e){for(var r=t.point,n=e.point,i=r.length,a=0;i>a;++a){var o=n[a]-r[a];if(o)return o}return 0}function a(t,e,r){if(1===t)return r?[[-1,0]]:[];var n=e.map(function(t,e){return[t[0],e]});n.sort(function(t,e){return t[0]-e[0]});for(var i=new Array(t-1),a=1;t>a;++a){var o=n[a-1],s=n[a];i[a-1]=[o[1],s[1]]}return r&&i.push([-1,i[0][1]],[i[t-1][1],-1]),i}function o(t,e){var r=t.length;if(0===r)return[];var o=t[0].length;if(1>o)return[];if(1===o)return a(r,t,e);for(var u=new Array(r),c=1,h=0;r>h;++h){for(var f=t[h],d=new Array(o+1),p=0,g=0;o>g;++g){var v=f[g];d[g]=v,p+=v*v}d[o]=p,u[h]=new n(d,h),c=Math.max(p,c)}l(u,i),r=u.length;for(var m=new Array(r+o+1),y=new Array(r+o+1),b=(o+1)*(o+1)*c,x=new Array(o+1),h=0;o>=h;++h)x[h]=0;x[o]=b,m[0]=x.slice(),y[0]=-1;for(var h=0;o>=h;++h){var d=x.slice();d[h]=1,m[h+1]=d,y[h+1]=-1}for(var h=0;r>h;++h){var _=u[h];m[h+o+1]=_.point,y[h+o+1]=_.index}var w=s(m,!1);if(w=e?w.filter(function(t){for(var e=0,r=0;o>=r;++r){var n=y[t[r]];if(0>n&&++e>=2)return!1;t[r]=n}return!0}):w.filter(function(t){for(var e=0;o>=e;++e){var r=y[t[e]];if(0>r)return!1;t[e]=r}return!0}),1&o)for(var h=0;h<w.length;++h){var _=w[h],d=_[0];_[0]=_[1],_[1]=d}return w}var s=t("incremental-convex-hull"),l=t("uniq");e.exports=o},{"incremental-convex-hull":191,uniq:234}],72:[function(t,e,r){"use strict";function n(t,e,r){var i=0|t[r];if(0>=i)return[];var a,o=new Array(i);if(r===t.length-1)for(a=0;i>a;++a)o[a]=e;else for(a=0;i>a;++a)o[a]=n(t,e,r+1);return o}function i(t,e){var r,n;for(r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function a(t,e){switch("undefined"==typeof e&&(e=0),typeof t){case"number":if(t>0)return i(0|t,e);break;case"object":if("number"==typeof t.length)return n(t,e,0)}return[]}e.exports=a},{}],73:[function(e,r,n){(function(n,i){(function(){"use strict";function a(t){return"function"==typeof t||"object"==typeof t&&null!==t}function o(t){return"function"==typeof t}function s(t){return"object"==typeof t&&null!==t}function l(t){Y=t}function u(t){$=t}function c(){return function(){n.nextTick(g)}}function h(){return function(){G(g)}}function f(){var t=0,e=new J(g),r=document.createTextNode("");return e.observe(r,{characterData:!0}),function(){r.data=t=++t%2}}function d(){var t=new MessageChannel;return t.port1.onmessage=g,function(){t.port2.postMessage(0)}}function p(){return function(){setTimeout(g,1)}}function g(){for(var t=0;Z>t;t+=2){var e=rt[t],r=rt[t+1];e(r),rt[t]=void 0,rt[t+1]=void 0}Z=0}function v(){try{var t=e,r=t("vertx");return G=r.runOnLoop||r.runOnContext,h()}catch(n){return p()}}function m(){}function y(){return new TypeError("You cannot resolve a promise with itself")}function b(){return new TypeError("A promises callback cannot return that same promise.")}function x(t){try{return t.then}catch(e){return ot.error=e,ot}}function _(t,e,r,n){try{t.call(e,r,n)}catch(i){return i}}function w(t,e,r){$(function(t){var n=!1,i=_(r,e,function(r){n||(n=!0,e!==r?M(t,r):E(t,r))},function(e){n||(n=!0,L(t,e))},"Settle: "+(t._label||" unknown promise"));!n&&i&&(n=!0,L(t,i))},t)}function A(t,e){e._state===it?E(t,e._result):e._state===at?L(t,e._result):S(e,void 0,function(e){M(t,e)},function(e){L(t,e)})}function k(t,e){if(e.constructor===t.constructor)A(t,e);else{var r=x(e);r===ot?L(t,ot.error):void 0===r?E(t,e):o(r)?w(t,e,r):E(t,e)}}function M(t,e){t===e?L(t,y()):a(e)?k(t,e):E(t,e)}function T(t){t._onerror&&t._onerror(t._result),C(t)}function E(t,e){t._state===nt&&(t._result=e,t._state=it,0!==t._subscribers.length&&$(C,t))}function L(t,e){t._state===nt&&(t._state=at,t._result=e,$(T,t))}function S(t,e,r,n){var i=t._subscribers,a=i.length;t._onerror=null,i[a]=e,i[a+it]=r,i[a+at]=n,0===a&&t._state&&$(C,t)}function C(t){var e=t._subscribers,r=t._state;if(0!==e.length){for(var n,i,a=t._result,o=0;o<e.length;o+=3)n=e[o],i=e[o+r],n?R(r,n,i,a):i(a);t._subscribers.length=0}}function P(){this.error=null}function z(t,e){try{return t(e)}catch(r){return st.error=r,st}}function R(t,e,r,n){var i,a,s,l,u=o(r);if(u){if(i=z(r,n),i===st?(l=!0,a=i.error,i=null):s=!0,e===i)return void L(e,b())}else i=n,s=!0;e._state!==nt||(u&&s?M(e,i):l?L(e,a):t===it?E(e,i):t===at&&L(e,i))}function O(t,e){try{e(function(e){M(t,e)},function(e){L(t,e)})}catch(r){L(t,r)}}function I(t,e){var r=this;r._instanceConstructor=t,r.promise=new t(m),r._validateInput(e)?(r._input=e,r.length=e.length,r._remaining=e.length,r._init(),0===r.length?E(r.promise,r._result):(r.length=r.length||0,r._enumerate(),0===r._remaining&&E(r.promise,r._result))):L(r.promise,r._validationError())}function j(t){return new lt(this,t).promise}function N(t){function e(t){M(i,t)}function r(t){L(i,t)}var n=this,i=new n(m);if(!W(t))return L(i,new TypeError("You must pass an array to race.")),i;for(var a=t.length,o=0;i._state===nt&&a>o;o++)S(n.resolve(t[o]),void 0,e,r);return i}function F(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var r=new e(m);return M(r,t),r}function B(t){var e=this,r=new e(m);return L(r,t),r}function D(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function U(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function V(t){this._id=dt++,this._state=void 0,this._result=void 0,this._subscribers=[],m!==t&&(o(t)||D(),this instanceof V||U(),O(this,t))}function q(){var t;if("undefined"!=typeof i)t=i;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var r=t.Promise;(!r||"[object Promise]"!==Object.prototype.toString.call(r.resolve())||r.cast)&&(t.Promise=pt)}var H;H=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var G,Y,X,W=H,Z=0,$=({}.toString,function(t,e){rt[Z]=t,rt[Z+1]=e,Z+=2,2===Z&&(Y?Y(g):X())}),K="undefined"!=typeof window?window:void 0,Q=K||{},J=Q.MutationObserver||Q.WebKitMutationObserver,tt="undefined"!=typeof n&&"[object process]"==={}.toString.call(n),et="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,rt=new Array(1e3);X=tt?c():J?f():et?d():void 0===K&&"function"==typeof e?v():p();var nt=void 0,it=1,at=2,ot=new P,st=new P;I.prototype._validateInput=function(t){return W(t)},I.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")},I.prototype._init=function(){this._result=new Array(this.length)};var lt=I;I.prototype._enumerate=function(){for(var t=this,e=t.length,r=t.promise,n=t._input,i=0;r._state===nt&&e>i;i++)t._eachEntry(n[i],i)},I.prototype._eachEntry=function(t,e){var r=this,n=r._instanceConstructor;s(t)?t.constructor===n&&t._state!==nt?(t._onerror=null,r._settledAt(t._state,e,t._result)):r._willSettleAt(n.resolve(t),e):(r._remaining--,r._result[e]=t)},I.prototype._settledAt=function(t,e,r){var n=this,i=n.promise;i._state===nt&&(n._remaining--,t===at?L(i,r):n._result[e]=r),0===n._remaining&&E(i,n._result)},I.prototype._willSettleAt=function(t,e){var r=this;S(t,void 0,function(t){r._settledAt(it,e,t)},function(t){r._settledAt(at,e,t)})};var ut=j,ct=N,ht=F,ft=B,dt=0,pt=V;V.all=ut,V.race=ct,V.resolve=ht,V.reject=ft,V._setScheduler=l,V._setAsap=u,V._asap=$,V.prototype={constructor:V,then:function(t,e){var r=this,n=r._state;if(n===it&&!t||n===at&&!e)return this;var i=new this.constructor(m),a=r._result;if(n){var o=arguments[n-1];$(function(){R(n,i,o,a)})}else S(r,i,t,e);return i},"catch":function(t){return this.then(null,t)}};var gt=q,vt={Promise:pt,polyfill:gt};"function"==typeof t&&t.amd?t(function(){return vt}):"undefined"!=typeof r&&r.exports?r.exports=vt:"undefined"!=typeof this&&(this.ES6Promise=vt),gt()}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:55}],74:[function(t,e,r){"use strict";function n(t){for(var e,r=t.length,n=0;r>n;n++)if(e=t.charCodeAt(n),(9>e||e>13)&&32!==e&&133!==e&&160!==e&&5760!==e&&6158!==e&&(8192>e||e>8205)&&8232!==e&&8233!==e&&8239!==e&&8287!==e&&8288!==e&&12288!==e&&65279!==e)return!1;return!0}e.exports=function(t){var e=typeof t;if("string"===e){var r=t;if(t=+t,0===t&&n(r))return!1}else if("number"!==e)return!1;return 1>t-t}},{}],75:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.gl=t,this.type=e,this.handle=r,this.length=n,this.usage=i}function i(t,e,r,n,i,a){var o=i.length*i.BYTES_PER_ELEMENT;if(0>a)return t.bufferData(e,i,n),o;if(o+a>r)throw new Error("gl-buffer: If resizing buffer, must not specify offset");return t.bufferSubData(e,a,i),r}function a(t,e){for(var r=l.malloc(t.length,e),n=t.length,i=0;n>i;++i)r[i]=t[i];return r}function o(t,e){for(var r=1,n=e.length-1;n>=0;--n){if(e[n]!==r)return!1;r*=t[n]}return!0}function s(t,e,r,i){if(r=r||t.ARRAY_BUFFER,i=i||t.DYNAMIC_DRAW,r!==t.ARRAY_BUFFER&&r!==t.ELEMENT_ARRAY_BUFFER)throw new Error("gl-buffer: Invalid type for webgl buffer, must be either gl.ARRAY_BUFFER or gl.ELEMENT_ARRAY_BUFFER");if(i!==t.DYNAMIC_DRAW&&i!==t.STATIC_DRAW&&i!==t.STREAM_DRAW)throw new Error("gl-buffer: Invalid usage for buffer, must be either gl.DYNAMIC_DRAW, gl.STATIC_DRAW or gl.STREAM_DRAW");var a=t.createBuffer(),o=new n(t,r,a,0,i);return o.update(e),o}var l=t("typedarray-pool"),u=t("ndarray-ops"),c=t("ndarray"),h=["uint8","uint8_clamped","uint16","uint32","int8","int16","int32","float32"],f=n.prototype;f.bind=function(){this.gl.bindBuffer(this.type,this.handle)},f.unbind=function(){this.gl.bindBuffer(this.type,null)},f.dispose=function(){this.gl.deleteBuffer(this.handle)},f.update=function(t,e){if("number"!=typeof e&&(e=-1),this.bind(),"object"==typeof t&&"undefined"!=typeof t.shape){var r=t.dtype;if(h.indexOf(r)<0&&(r="float32"),this.type===this.gl.ELEMENT_ARRAY_BUFFER){var n=gl.getExtension("OES_element_index_uint");r=n&&"uint16"!==r?"uint32":"uint16"}if(r===t.dtype&&o(t.shape,t.stride))0===t.offset&&t.data.length===t.shape[0]?this.length=i(this.gl,this.type,this.length,this.usage,t.data,e):this.length=i(this.gl,this.type,this.length,this.usage,t.data.subarray(t.offset,t.shape[0]),e);else{var s=l.malloc(t.size,r),f=c(s,t.shape);u.assign(f,t),0>e?this.length=i(this.gl,this.type,this.length,this.usage,s,e):this.length=i(this.gl,this.type,this.length,this.usage,s.subarray(0,t.size),e),l.free(s)}}else if(Array.isArray(t)){var d;d=this.type===this.gl.ELEMENT_ARRAY_BUFFER?a(t,"uint16"):a(t,"float32"),0>e?this.length=i(this.gl,this.type,this.length,this.usage,d,e):this.length=i(this.gl,this.type,this.length,this.usage,d.subarray(0,t.length),e),l.free(d)}else if("object"==typeof t&&"number"==typeof t.length)this.length=i(this.gl,this.type,this.length,this.usage,t,e);else{if("number"!=typeof t&&void 0!==t)throw new Error("gl-buffer: Invalid data type");if(e>=0)throw new Error("gl-buffer: Cannot specify offset when resizing buffer");t=0|t,0>=t&&(t=1),this.gl.bufferData(this.type,0|t,this.usage),this.length=t}},e.exports=s},{ndarray:208,"ndarray-ops":207,"typedarray-pool":233}],76:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.shader=e,this.buffer=r,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.numPoints=0,this.color=[0,0,0,1]}function i(t,e){var r=a(t.gl,l.vertex,l.fragment),i=o(t.gl),s=new n(t,r,i);return s.update(e),t.addObject(s),s}var a=t("gl-shader"),o=t("gl-buffer"),s=t("typedarray-pool"),l=t("./lib/shaders");e.exports=i;var u=[[1,0,0,1,0,0],[1,0,0,-1,0,0],[-1,0,0,-1,0,0],[-1,0,0,-1,0,0],[-1,0,0,1,0,0],[1,0,0,1,0,0],[1,0,-1,0,0,1],[1,0,-1,0,0,-1],[1,0,1,0,0,-1],[1,0,1,0,0,-1],[1,0,1,0,0,1],[1,0,-1,0,0,1],[-1,0,-1,0,0,1],[-1,0,-1,0,0,-1],[-1,0,1,0,0,-1],[-1,0,1,0,0,-1],[-1,0,1,0,0,1],[-1,0,-1,0,0,1],[0,1,1,0,0,0],[0,1,-1,0,0,0],[0,-1,-1,0,0,0],[0,-1,-1,0,0,0],[0,1,1,0,0,0],[0,-1,1,0,0,0],[0,1,0,-1,1,0],[0,1,0,-1,-1,0],[0,1,0,1,-1,0],[0,1,0,1,1,0],[0,1,0,-1,1,0],[0,1,0,1,-1,0],[0,-1,0,-1,1,0],[0,-1,0,-1,-1,0],[0,-1,0,1,-1,0],[0,-1,0,1,1,0],[0,-1,0,-1,1,0],[0,-1,0,1,-1,0]],c=n.prototype;c.draw=function(){var t=[1,0,0,0,1,0,0,0,1],e=[1,1];return function(){var r=this.plot,n=this.shader,i=this.buffer,a=this.bounds,o=this.numPoints,s=(this.color,r.gl),l=r.dataBox,c=r.viewBox,h=r.pixelRatio,f=a[2]-a[0],d=a[3]-a[1],p=l[2]-l[0],g=l[3]-l[1];t[0]=2*f/p,t[4]=2*d/g,t[6]=2*(a[0]-l[0])/p-1,t[7]=2*(a[1]-l[1])/g-1;var v=c[2]-c[0],m=c[3]-c[1];e[0]=2*h/v,e[1]=2*h/m,i.bind(),n.bind(),n.uniforms.viewTransform=t,n.uniforms.pixelScale=e,n.uniforms.color=this.color,n.attributes.position.pointer(s.FLOAT,!1,16,0),n.attributes.pixelOffset.pointer(s.FLOAT,!1,16,8),s.drawArrays(s.TRIANGLES,0,o*u.length)}}(),c.drawPick=function(t){return t},c.pick=function(t,e){return null},c.update=function(t){t=t||{};var e=t.positions||[],r=t.errors||[],n=1;"lineWidth"in t&&(n=+t.lineWidth);var i=5;"capSize"in t&&(i=+t.capSize),this.color=(t.color||[0,0,0,1]).slice();for(var a=this.bounds=[1/0,1/0,-(1/0),-(1/0)],o=this.numPoints=e.length>>1,l=0;o>l;++l){var c=e[2*l],h=e[2*l+1];a[0]=Math.min(c,a[0]),a[1]=Math.min(h,a[1]),a[2]=Math.max(c,a[2]),a[3]=Math.max(h,a[3])}a[2]===a[0]&&(a[2]+=1),a[3]===a[1]&&(a[3]+=1);for(var f=1/(a[2]-a[0]),d=1/(a[3]-a[1]),p=a[0],g=a[1],v=s.mallocFloat32(o*u.length*4),m=0,l=0;o>l;++l)for(var c=e[2*l],h=e[2*l+1],y=r[4*l],b=r[4*l+1],x=r[4*l+2],_=r[4*l+3],w=0;w<u.length;++w){var A=u[w],k=A[0],M=A[1];0>k?k*=y:k>0&&(k*=b),0>M?M*=x:M>0&&(M*=_),v[m++]=f*(c-p+k),v[m++]=d*(h-g+M),v[m++]=n*A[2]+(i+n)*A[4],v[m++]=n*A[3]+(i+n)*A[5]}this.buffer.update(v),s.free(v)},c.dispose=function(){this.plot.removeObject(this),this.shader.dispose(),this.buffer.dispose()}},{"./lib/shaders":77,"gl-buffer":75,"gl-shader":154,"typedarray-pool":233}],77:[function(t,e,r){e.exports={vertex:"#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 position;\nattribute vec2 pixelOffset;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvoid main() {\n  vec3 scrPosition = viewTransform * vec3(position, 1);\n  gl_Position = vec4(\n    scrPosition.xy + scrPosition.z * pixelScale * pixelOffset,\n    0,\n    scrPosition.z);\n}\n",
+fragment:"#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 color;\n\nvoid main() {\n  gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n"}},{}],78:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.shader=n,this.buffer=e,this.vao=r,this.pixelRatio=1,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.lineWidth=[1,1,1],this.capSize=[10,10,10],this.lineCount=[0,0,0],this.lineOffset=[0,0,0],this.opacity=1}function i(t,e){for(var r=0;3>r;++r)t[0][r]=Math.min(t[0][r],e[r]),t[1][r]=Math.max(t[1][r],e[r])}function a(t,e,r,n){for(var i=f[n],a=0;a<i.length;++a){var o=i[a];t.push(e[0],e[1],e[2],r[0],r[1],r[2],r[3],o[0],o[1],o[2])}return i.length}function o(t){var e=t.gl,r=s(e),i=l(e,[{buffer:r,type:e.FLOAT,size:3,offset:0,stride:40},{buffer:r,type:e.FLOAT,size:4,offset:12,stride:40},{buffer:r,type:e.FLOAT,size:3,offset:28,stride:40}]),a=u(e);a.attributes.position.location=0,a.attributes.color.location=1,a.attributes.offset.location=2;var o=new n(e,r,i,a);return o.update(t),o}e.exports=o;var s=t("gl-buffer"),l=t("gl-vao"),u=t("./shaders/index"),c=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],h=n.prototype;h.isOpaque=function(){return this.opacity>=1},h.isTransparent=function(){return this.opacity<1},h.drawTransparent=h.draw=function(t){var e=this.gl,r=this.shader.uniforms;this.shader.bind();var n=r.view=t.view||c,i=r.projection=t.projection||c;r.model=t.model||c,r.clipBounds=this.clipBounds,r.opacity=this.opacity;var a=n[12],o=n[13],s=n[14],l=n[15],u=this.pixelRatio*(i[3]*a+i[7]*o+i[11]*s+i[15]*l)/e.drawingBufferHeight;this.vao.bind();for(var h=0;3>h;++h)e.lineWidth(this.lineWidth[h]),r.capSize=this.capSize[h]*u,e.drawArrays(e.LINES,this.lineOffset[h],this.lineCount[h]);this.vao.unbind()};var f=function(){for(var t=new Array(3),e=0;3>e;++e){for(var r=[],n=1;2>=n;++n)for(var i=-1;1>=i;i+=2){var a=(n+e)%3,o=[0,0,0];o[a]=i,r.push(o)}t[e]=r}return t}();h.update=function(t){t=t||{},"lineWidth"in t&&(this.lineWidth=t.lineWidth,Array.isArray(this.lineWidth)||(this.lineWidth=[this.lineWidth,this.lineWidth,this.lineWidth])),"capSize"in t&&(this.capSize=t.capSize,Array.isArray(this.capSize)||(this.capSize=[this.capSize,this.capSize,this.capSize])),"opacity"in t&&(this.opacity=t.opacity);var e=t.color||[[0,0,0],[0,0,0],[0,0,0]],r=t.position,n=t.error;if(Array.isArray(e[0])||(e=[e,e,e]),r&&n){var o=[],s=r.length,l=0;this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.lineCount=[0,0,0];for(var u=0;3>u;++u){this.lineOffset[u]=l;t:for(var c=0;s>c;++c){for(var h=r[c],f=0;3>f;++f)if(isNaN(h[f])||!isFinite(h[f]))continue t;var d=n[c],p=e[u];if(Array.isArray(p[0])&&(p=e[c]),3===p.length&&(p=[p[0],p[1],p[2],1]),!isNaN(d[0][u])&&!isNaN(d[1][u])){if(d[0][u]<0){var g=h.slice();g[u]+=d[0][u],o.push(h[0],h[1],h[2],p[0],p[1],p[2],p[3],0,0,0,g[0],g[1],g[2],p[0],p[1],p[2],p[3],0,0,0),i(this.bounds,g),l+=2+a(o,g,p,u)}if(d[1][u]>0){var g=h.slice();g[u]+=d[1][u],o.push(h[0],h[1],h[2],p[0],p[1],p[2],p[3],0,0,0,g[0],g[1],g[2],p[0],p[1],p[2],p[3],0,0,0),i(this.bounds,g),l+=2+a(o,g,p,u)}}}this.lineCount[u]=l-this.lineOffset[u]}this.buffer.update(o)}},h.dispose=function(){this.shader.dispose(),this.buffer.dispose(),this.vao.dispose()}},{"./shaders/index":79,"gl-buffer":75,"gl-vao":189}],79:[function(t,e,r){"use strict";var n=t("gl-shader"),i="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position, offset;\nattribute vec4 color;\nuniform mat4 model, view, projection;\nuniform float capSize;\nvarying vec4 fragColor;\nvarying vec3 fragPosition;\n\nvoid main() {\n  vec4 worldPosition  = model * vec4(position, 1.0);\n  worldPosition       = (worldPosition / worldPosition.w) + vec4(capSize * offset, 0.0);\n  gl_Position         = projection * view * worldPosition;\n  fragColor           = color;\n  fragPosition        = position;\n}",a="#define GLSLIFY 1\nprecision mediump float;\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n  if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\n    discard;\n  }\n  gl_FragColor = opacity * fragColor;\n}";e.exports=function(t){return n(t,i,a,null,[{name:"position",type:"vec3"},{name:"offset",type:"vec3"},{name:"color",type:"vec4"}])}},{"gl-shader":154}],80:[function(t,e,r){"use strict";function n(t){var e=t.getParameter(t.FRAMEBUFFER_BINDING),r=t.getParameter(t.RENDERBUFFER_BINDING),n=t.getParameter(t.TEXTURE_BINDING_2D);return[e,r,n]}function i(t,e){t.bindFramebuffer(t.FRAMEBUFFER,e[0]),t.bindRenderbuffer(t.RENDERBUFFER,e[1]),t.bindTexture(t.TEXTURE_2D,e[2])}function a(t,e){var r=t.getParameter(e.MAX_COLOR_ATTACHMENTS_WEBGL);y=new Array(r+1);for(var n=0;r>=n;++n){for(var i=new Array(r),a=0;n>a;++a)i[a]=t.COLOR_ATTACHMENT0+a;for(var a=n;r>a;++a)i[a]=t.NONE;y[n]=i}}function o(t){switch(t){case p:throw new Error("gl-fbo: Framebuffer unsupported");case g:throw new Error("gl-fbo: Framebuffer incomplete attachment");case v:throw new Error("gl-fbo: Framebuffer incomplete dimensions");case m:throw new Error("gl-fbo: Framebuffer incomplete missing attachment");default:throw new Error("gl-fbo: Framebuffer failed for unspecified reason")}}function s(t,e,r,n,i,a){if(!n)return null;var o=d(t,e,r,i,n);return o.magFilter=t.NEAREST,o.minFilter=t.NEAREST,o.mipSamples=1,o.bind(),t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,o.handle,0),o}function l(t,e,r,n,i){var a=t.createRenderbuffer();return t.bindRenderbuffer(t.RENDERBUFFER,a),t.renderbufferStorage(t.RENDERBUFFER,n,e,r),t.framebufferRenderbuffer(t.FRAMEBUFFER,i,t.RENDERBUFFER,a),a}function u(t){var e=n(t.gl),r=t.gl,a=t.handle=r.createFramebuffer(),u=t._shape[0],c=t._shape[1],h=t.color.length,f=t._ext,d=t._useStencil,p=t._useDepth,g=t._colorType;r.bindFramebuffer(r.FRAMEBUFFER,a);for(var v=0;h>v;++v)t.color[v]=s(r,u,c,g,r.RGBA,r.COLOR_ATTACHMENT0+v);0===h?(t._color_rb=l(r,u,c,r.RGBA4,r.COLOR_ATTACHMENT0),f&&f.drawBuffersWEBGL(y[0])):h>1&&f.drawBuffersWEBGL(y[h]);var m=r.getExtension("WEBGL_depth_texture");m?d?t.depth=s(r,u,c,m.UNSIGNED_INT_24_8_WEBGL,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):p&&(t.depth=s(r,u,c,r.UNSIGNED_SHORT,r.DEPTH_COMPONENT,r.DEPTH_ATTACHMENT)):p&&d?t._depth_rb=l(r,u,c,r.DEPTH_STENCIL,r.DEPTH_STENCIL_ATTACHMENT):p?t._depth_rb=l(r,u,c,r.DEPTH_COMPONENT16,r.DEPTH_ATTACHMENT):d&&(t._depth_rb=l(r,u,c,r.STENCIL_INDEX,r.STENCIL_ATTACHMENT));var b=r.checkFramebufferStatus(r.FRAMEBUFFER);if(b!==r.FRAMEBUFFER_COMPLETE){t._destroyed=!0,r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteFramebuffer(t.handle),t.handle=null,t.depth&&(t.depth.dispose(),t.depth=null),t._depth_rb&&(r.deleteRenderbuffer(t._depth_rb),t._depth_rb=null);for(var v=0;v<t.color.length;++v)t.color[v].dispose(),t.color[v]=null;t._color_rb&&(r.deleteRenderbuffer(t._color_rb),t._color_rb=null),i(r,e),o(b)}i(r,e)}function c(t,e,r,n,i,a,o,s){this.gl=t,this._shape=[0|e,0|r],this._destroyed=!1,this._ext=s,this.color=new Array(i);for(var l=0;i>l;++l)this.color[l]=null;this._color_rb=null,this.depth=null,this._depth_rb=null,this._colorType=n,this._useDepth=a,this._useStencil=o;var c=this,h=[0|e,0|r];Object.defineProperties(h,{0:{get:function(){return c._shape[0]},set:function(t){return c.width=t}},1:{get:function(){return c._shape[1]},set:function(t){return c.height=t}}}),this._shapeVector=h,u(this)}function h(t,e,r){if(t._destroyed)throw new Error("gl-fbo: Can't resize destroyed FBO");if(t._shape[0]!==e||t._shape[1]!==r){var a=t.gl,s=a.getParameter(a.MAX_RENDERBUFFER_SIZE);if(0>e||e>s||0>r||r>s)throw new Error("gl-fbo: Can't resize FBO, invalid dimensions");t._shape[0]=e,t._shape[1]=r;for(var l=n(a),u=0;u<t.color.length;++u)t.color[u].shape=t._shape;t._color_rb&&(a.bindRenderbuffer(a.RENDERBUFFER,t._color_rb),a.renderbufferStorage(a.RENDERBUFFER,a.RGBA4,t._shape[0],t._shape[1])),t.depth&&(t.depth.shape=t._shape),t._depth_rb&&(a.bindRenderbuffer(a.RENDERBUFFER,t._depth_rb),t._useDepth&&t._useStencil?a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_STENCIL,t._shape[0],t._shape[1]):t._useDepth?a.renderbufferStorage(a.RENDERBUFFER,a.DEPTH_COMPONENT16,t._shape[0],t._shape[1]):t._useStencil&&a.renderbufferStorage(a.RENDERBUFFER,a.STENCIL_INDEX,t._shape[0],t._shape[1])),a.bindFramebuffer(a.FRAMEBUFFER,t.handle);var c=a.checkFramebufferStatus(a.FRAMEBUFFER);c!==a.FRAMEBUFFER_COMPLETE&&(t.dispose(),i(a,l),o(c)),i(a,l)}}function f(t,e,r,n){p||(p=t.FRAMEBUFFER_UNSUPPORTED,g=t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT,v=t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS,m=t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);var i=t.getExtension("WEBGL_draw_buffers");if(!y&&i&&a(t,i),Array.isArray(e)&&(n=r,r=0|e[1],e=0|e[0]),"number"!=typeof e)throw new Error("gl-fbo: Missing shape parameter");var o=t.getParameter(t.MAX_RENDERBUFFER_SIZE);if(0>e||e>o||0>r||r>o)throw new Error("gl-fbo: Parameters are too large for FBO");n=n||{};var s=1;if("color"in n){if(s=Math.max(0|n.color,0),0>s)throw new Error("gl-fbo: Must specify a nonnegative number of colors");if(s>1){if(!i)throw new Error("gl-fbo: Multiple draw buffer extension not supported");if(s>t.getParameter(i.MAX_COLOR_ATTACHMENTS_WEBGL))throw new Error("gl-fbo: Context does not support "+s+" draw buffers")}}var l=t.UNSIGNED_BYTE,u=t.getExtension("OES_texture_float");if(n.float&&s>0){if(!u)throw new Error("gl-fbo: Context does not support floating point textures");l=t.FLOAT}else n.preferFloat&&s>0&&u&&(l=t.FLOAT);var h=!0;"depth"in n&&(h=!!n.depth);var f=!1;return"stencil"in n&&(f=!!n.stencil),new c(t,e,r,l,s,h,f,i)}var d=t("gl-texture2d");e.exports=f;var p,g,v,m,y=null,b=c.prototype;Object.defineProperties(b,{shape:{get:function(){return this._destroyed?[0,0]:this._shapeVector},set:function(t){if(Array.isArray(t)||(t=[0|t,0|t]),2!==t.length)throw new Error("gl-fbo: Shape vector must be length 2");var e=0|t[0],r=0|t[1];return h(this,e,r),[e,r]},enumerable:!1},width:{get:function(){return this._destroyed?0:this._shape[0]},set:function(t){return t=0|t,h(this,t,this._shape[1]),t},enumerable:!1},height:{get:function(){return this._destroyed?0:this._shape[1]},set:function(t){return t=0|t,h(this,this._shape[0],t),t},enumerable:!1}}),b.bind=function(){if(!this._destroyed){var t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.handle),t.viewport(0,0,this._shape[0],this._shape[1])}},b.dispose=function(){if(!this._destroyed){this._destroyed=!0;var t=this.gl;t.deleteFramebuffer(this.handle),this.handle=null,this.depth&&(this.depth.dispose(),this.depth=null),this._depth_rb&&(t.deleteRenderbuffer(this._depth_rb),this._depth_rb=null);for(var e=0;e<this.color.length;++e)this.color[e].dispose(),this.color[e]=null;this._color_rb&&(t.deleteRenderbuffer(this._color_rb),this._color_rb=null)}}},{"gl-texture2d":185}],81:[function(t,e,r){r.lineVertex="#define GLSLIFY 1\nprecision mediump float;\n\nfloat inverse_1_0(float m) {\n  return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n  return mat2(m[1][1],-m[0][1],\n             -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n  float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n  float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n  float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n  float b01 = a22 * a11 - a12 * a21;\n  float b11 = -a22 * a10 + a12 * a20;\n  float b21 = a21 * a10 - a11 * a20;\n\n  float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n  return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n              b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n              b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n  float\n      a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n      a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n      a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n      a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n      b00 = a00 * a11 - a01 * a10,\n      b01 = a00 * a12 - a02 * a10,\n      b02 = a00 * a13 - a03 * a10,\n      b03 = a01 * a12 - a02 * a11,\n      b04 = a01 * a13 - a03 * a11,\n      b05 = a02 * a13 - a03 * a12,\n      b06 = a20 * a31 - a21 * a30,\n      b07 = a20 * a32 - a22 * a30,\n      b08 = a20 * a33 - a23 * a30,\n      b09 = a21 * a32 - a22 * a31,\n      b10 = a21 * a33 - a23 * a31,\n      b11 = a22 * a33 - a23 * a32,\n\n      det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n  return mat4(\n      a11 * b11 - a12 * b10 + a13 * b09,\n      a02 * b10 - a01 * b11 - a03 * b09,\n      a31 * b05 - a32 * b04 + a33 * b03,\n      a22 * b04 - a21 * b05 - a23 * b03,\n      a12 * b08 - a10 * b11 - a13 * b07,\n      a00 * b11 - a02 * b08 + a03 * b07,\n      a32 * b02 - a30 * b05 - a33 * b01,\n      a20 * b05 - a22 * b02 + a23 * b01,\n      a10 * b10 - a11 * b08 + a13 * b06,\n      a01 * b08 - a00 * b10 - a03 * b06,\n      a30 * b04 - a31 * b02 + a33 * b00,\n      a21 * b02 - a20 * b04 - a23 * b00,\n      a11 * b07 - a10 * b09 - a12 * b06,\n      a00 * b09 - a01 * b07 + a02 * b06,\n      a31 * b01 - a30 * b03 - a32 * b00,\n      a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec2 direction;\n\nvoid main() {\n  vec2 dir = (matrix * vec3(d, 0)).xy;\n  vec3 base = matrix * vec3(a, 1);\n  vec2 n = 0.5 * width *\n    normalize(screenShape.yx * vec2(dir.y, -dir.x)) / screenShape.xy;\n  vec2 tangent = normalize(screenShape.xy * dir);\n  if(dir.x < 0.0 || (dir.x == 0.0 && dir.y < 0.0)) {\n    direction = -tangent;\n  } else {\n    direction = tangent;\n  }\n  gl_Position = vec4(base.xy/base.z + n, 0, 1);\n}\n",r.lineFragment="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 color;\nuniform vec2 screenShape;\nuniform sampler2D dashPattern;\nuniform float dashLength;\n\nvarying vec2 direction;\n\nvoid main() {\n  float t = fract(dot(direction, gl_FragCoord.xy) / dashLength);\n  vec4 pcolor = color * texture2D(dashPattern, vec2(t, 0.0)).r;\n  gl_FragColor = vec4(pcolor.rgb * pcolor.a, pcolor.a);\n}\n",r.mitreVertex="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 p;\n\nuniform mat3  matrix;\nuniform vec2 screenShape;\nuniform float radius;\n\nvoid main() {\n  vec3 pp = matrix * vec3(p, 1);\n  gl_Position  = vec4(pp.xy, 0, pp.z);\n  gl_PointSize = radius;\n}\n",r.mitreFragment="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 color;\n\nvoid main() {\n  if(length(gl_PointCoord.xy - 0.5) > 0.25) {\n    discard;\n  }\n  gl_FragColor = vec4(color.rgb, color.a);\n}\n",r.pickVertex="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 a, d;\nattribute vec4 pick0, pick1;\n\nuniform mat3 matrix;\nuniform vec2 screenShape;\nuniform float width;\n\nvarying vec4 pickA, pickB;\n\nfloat inverse_1_0(float m) {\n  return 1.0 / m;\n}\n\nmat2 inverse_1_0(mat2 m) {\n  return mat2(m[1][1],-m[0][1],\n             -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n}\n\nmat3 inverse_1_0(mat3 m) {\n  float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n  float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n  float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n  float b01 = a22 * a11 - a12 * a21;\n  float b11 = -a22 * a10 + a12 * a20;\n  float b21 = a21 * a10 - a11 * a20;\n\n  float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n  return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n              b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n              b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n}\n\nmat4 inverse_1_0(mat4 m) {\n  float\n      a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n      a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n      a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n      a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n      b00 = a00 * a11 - a01 * a10,\n      b01 = a00 * a12 - a02 * a10,\n      b02 = a00 * a13 - a03 * a10,\n      b03 = a01 * a12 - a02 * a11,\n      b04 = a01 * a13 - a03 * a11,\n      b05 = a02 * a13 - a03 * a12,\n      b06 = a20 * a31 - a21 * a30,\n      b07 = a20 * a32 - a22 * a30,\n      b08 = a20 * a33 - a23 * a30,\n      b09 = a21 * a32 - a22 * a31,\n      b10 = a21 * a33 - a23 * a31,\n      b11 = a22 * a33 - a23 * a32,\n\n      det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n  return mat4(\n      a11 * b11 - a12 * b10 + a13 * b09,\n      a02 * b10 - a01 * b11 - a03 * b09,\n      a31 * b05 - a32 * b04 + a33 * b03,\n      a22 * b04 - a21 * b05 - a23 * b03,\n      a12 * b08 - a10 * b11 - a13 * b07,\n      a00 * b11 - a02 * b08 + a03 * b07,\n      a32 * b02 - a30 * b05 - a33 * b01,\n      a20 * b05 - a22 * b02 + a23 * b01,\n      a10 * b10 - a11 * b08 + a13 * b06,\n      a01 * b08 - a00 * b10 - a03 * b06,\n      a30 * b04 - a31 * b02 + a33 * b00,\n      a21 * b02 - a20 * b04 - a23 * b00,\n      a11 * b07 - a10 * b09 - a12 * b06,\n      a00 * b09 - a01 * b07 + a02 * b06,\n      a31 * b01 - a30 * b03 - a32 * b00,\n      a20 * b03 - a21 * b01 + a22 * b00) / det;\n}\n\n\n\nvoid main() {\n  vec3 base = matrix * vec3(a, 1);\n  vec2 n = width *\n    normalize(screenShape.yx * vec2(d.y, -d.x)) / screenShape.xy;\n  gl_Position = vec4(base.xy/base.z + n, 0, 1);\n  pickA = pick0;\n  pickB = pick1;\n}\n",r.pickFragment="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 pickOffset;\n\nvarying vec4 pickA, pickB;\n\nvoid main() {\n  vec4 fragId = vec4(pickA.xyz, 0.0);\n  if(pickB.w > pickA.w) {\n    fragId.xyz = pickB.xyz;\n  }\n\n  fragId += pickOffset;\n\n  fragId.y += floor(fragId.x / 256.0);\n  fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n  fragId.z += floor(fragId.y / 256.0);\n  fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n  fragId.w += floor(fragId.z / 256.0);\n  fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n  gl_FragColor = fragId / 255.0;\n}\n",r.fillVertex="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 a, d;\n\nuniform mat3 matrix;\nuniform vec2 projectAxis;\nuniform float projectValue;\nuniform float depth;\n\nvoid main() {\n  vec3 base = matrix * vec3(a, 1);\n  vec2 p = base.xy / base.z;\n  if(d.y < 0.0 || (d.y == 0.0 && d.x < 0.0)) {\n    if(dot(p, projectAxis) < projectValue) {\n      p = p * (1.0 - abs(projectAxis)) + projectAxis * projectValue;\n    }\n  }\n  gl_Position = vec4(p, depth, 1);\n}\n",r.fillFragment="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 color;\n\nvoid main() {\n  gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n"},{}],82:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s){this.plot=t,this.dashPattern=e,this.lineBuffer=r,this.pickBuffer=n,this.lineShader=i,this.mitreShader=a,this.fillShader=o,this.pickShader=s,this.usingDashes=!1,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.width=1,this.color=[0,0,1,1],this.fill=[!1,!1,!1,!1],this.fillColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.data=null,this.numPoints=0,this.vertCount=0,this.pickOffset=0,this.lodBuffer=[]}function i(t){return t.map(function(t){return t.slice()})}function a(t,e){var r=t.gl,i=s(r),a=s(r),u=l(r,[1,1]),c=o(r,h.lineVertex,h.lineFragment),f=o(r,h.mitreVertex,h.mitreFragment),d=o(r,h.fillVertex,h.fillFragment),p=o(r,h.pickVertex,h.pickFragment),g=new n(t,u,i,a,c,f,d,p);return t.addObject(g),g.update(e),g}e.exports=a;var o=t("gl-shader"),s=t("gl-buffer"),l=t("gl-texture2d"),u=t("ndarray"),c=t("typedarray-pool"),h=t("./lib/shaders"),f=n.prototype;f.draw=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0],r=[1,0],n=[-1,0],i=[0,1],a=[0,-1];return function(){var o=this.plot,s=this.color,l=this.width,u=(this.numPoints,this.bounds),c=this.vertCount,h=o.gl,f=o.viewBox,d=o.dataBox,p=o.pixelRatio,g=u[2]-u[0],v=u[3]-u[1],m=d[2]-d[0],y=d[3]-d[1],b=f[2]-f[0],x=f[3]-f[1];t[0]=2*g/m,t[4]=2*v/y,t[6]=2*(u[0]-d[0])/m-1,t[7]=2*(u[1]-d[1])/y-1,e[0]=b,e[1]=x;var _=this.lineBuffer;_.bind();var w=this.fill;if(w[0]||w[1]||w[2]||w[3]){var A=this.fillShader;A.bind();var k=A.uniforms;k.matrix=t,k.depth=o.nextDepthValue();var M=A.attributes;M.a.pointer(h.FLOAT,!1,16,0),M.d.pointer(h.FLOAT,!1,16,8),h.depthMask(!0),h.enable(h.DEPTH_TEST);var T=this.fillColor;w[0]&&(k.color=T[0],k.projectAxis=n,k.projectValue=1,h.drawArrays(h.TRIANGLES,0,c)),w[1]&&(k.color=T[1],k.projectAxis=a,k.projectValue=1,h.drawArrays(h.TRIANGLES,0,c)),w[2]&&(k.color=T[2],k.projectAxis=r,k.projectValue=1,h.drawArrays(h.TRIANGLES,0,c)),w[3]&&(k.color=T[3],k.projectAxis=i,k.projectValue=1,h.drawArrays(h.TRIANGLES,0,c)),h.depthMask(!1),h.disable(h.DEPTH_TEST)}var E=this.lineShader;E.bind();var L=E.uniforms;L.matrix=t,L.color=s,L.width=l*p,L.screenShape=e,L.dashPattern=this.dashPattern.bind(),L.dashLength=this.dashLength*p;var S=E.attributes;if(S.a.pointer(h.FLOAT,!1,16,0),S.d.pointer(h.FLOAT,!1,16,8),h.drawArrays(h.TRIANGLES,0,c),l>2&&!this.usingDashes){var C=this.mitreShader;C.bind();var P=C.uniforms;P.matrix=t,P.color=s,P.screenShape=e,P.radius=l*p,C.attributes.p.pointer(h.FLOAT,!1,48,0),h.drawArrays(h.POINTS,0,c/3|0)}}}(),f.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0],r=[0,0,0,0];return function(n){var i=this.plot,a=this.pickShader,o=this.lineBuffer,s=this.pickBuffer,l=this.width,u=this.numPoints,c=this.bounds,h=this.vertCount,f=i.gl,d=i.viewBox,p=i.dataBox,g=i.pickPixelRatio,v=c[2]-c[0],m=c[3]-c[1],y=p[2]-p[0],b=p[3]-p[1],x=d[2]-d[0],_=d[3]-d[1];this.pickOffset=n,t[0]=2*v/y,t[4]=2*m/b,t[6]=2*(c[0]-p[0])/y-1,t[7]=2*(c[1]-p[1])/b-1,e[0]=x,e[1]=_,r[0]=255&n,r[1]=n>>>8&255,r[2]=n>>>16&255,r[3]=n>>>24,a.bind();var w=a.uniforms;w.matrix=t,w.width=l*g,w.pickOffset=r,w.screenShape=e;var A=a.attributes;return o.bind(),A.a.pointer(f.FLOAT,!1,16,0),A.d.pointer(f.FLOAT,!1,16,8),s.bind(),A.pick0.pointer(f.UNSIGNED_BYTE,!1,8,0),A.pick1.pointer(f.UNSIGNED_BYTE,!1,8,4),f.drawArrays(f.TRIANGLES,0,h),n+u}}(),f.pick=function(t,e,r){var n=this.pickOffset,i=this.numPoints;if(n>r||r>=n+i)return null;var a=r-n,o=this.data;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}},f.update=function(t){t=t||{};var e=this.plot.gl;this.color=(t.color||[0,0,1,1]).slice(),this.width=+(t.width||1),this.fill=(t.fill||[!1,!1,!1,!1]).slice(),this.fillColor=i(t.fillColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]);for(var r=t.dashes||[1],n=0,a=0;a<r.length;++a)n+=r[a];for(var o=c.mallocUint8(n),s=0,h=255,a=0;a<r.length;++a){for(var f=0;f<r[a];++f)o[s++]=h;h^=255}this.dashPattern.dispose(),this.usingDashes=r.length>1,this.dashPattern=l(e,u(o,[n,1,4],[1,0,0])),this.dashPattern.minFilter=e.NEAREST,this.dashPattern.magFilter=e.NEAREST,this.dashLength=n,c.free(o);var d=t.positions;this.data=d;var p=this.bounds;p[0]=p[1]=1/0,p[2]=p[3]=-(1/0);var g=this.numPoints=d.length>>>1;if(0!==g){for(var a=0;g>a;++a){var v=d[2*a],m=d[2*a+1];p[0]=Math.min(p[0],v),p[1]=Math.min(p[1],m),p[2]=Math.max(p[2],v),p[3]=Math.max(p[3],m)}p[0]===p[2]&&(p[2]+=1),p[3]===p[1]&&(p[3]+=1);var y=c.mallocFloat32(24*(g-1)),b=c.mallocUint32(12*(g-1)),x=y.length,_=b.length,s=g;for(this.vertCount=6*(g-1);s>1;){var w=--s,v=d[2*s],m=d[2*s+1];v=(v-p[0])/(p[2]-p[0]),m=(m-p[1])/(p[3]-p[1]);var A=w-1,k=d[2*A],M=d[2*A+1];k=(k-p[0])/(p[2]-p[0]),M=(M-p[1])/(p[3]-p[1]);var T=k-v,E=M-m,L=w|1<<24,S=w-1,C=w,P=w-1|1<<24;y[--x]=-E,y[--x]=-T,y[--x]=m,y[--x]=v,b[--_]=L,b[--_]=S,y[--x]=E,y[--x]=T,y[--x]=M,y[--x]=k,b[--_]=C,b[--_]=P,y[--x]=-E,y[--x]=-T,y[--x]=M,y[--x]=k,b[--_]=C,b[--_]=P,y[--x]=E,y[--x]=T,y[--x]=M,y[--x]=k,b[--_]=C,b[--_]=P,y[--x]=-E,y[--x]=-T,y[--x]=m,y[--x]=v,b[--_]=L,b[--_]=S,y[--x]=E,y[--x]=T,y[--x]=m,y[--x]=v,b[--_]=L,b[--_]=S}this.lineBuffer.update(y),this.pickBuffer.update(b),c.free(y),c.free(b)}},f.dispose=function(){this.plot.removeObject(this),this.lineBuffer.dispose(),this.pickBuffer.dispose(),this.lineShader.dispose(),this.mitreShader.dispose(),this.fillShader.dispose(),this.pickShader.dispose(),this.dashPattern.dispose()}},{"./lib/shaders":81,"gl-buffer":75,"gl-shader":154,"gl-texture2d":185,ndarray:208,"typedarray-pool":233}],83:[function(t,e,r){var n=t("gl-shader"),i="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position, nextPosition;\nattribute float arcLength, lineWidth;\nattribute vec4 color;\n\nuniform vec2 screenShape;\nuniform float pixelRatio;\nuniform mat4 model, view, projection;\n\nvarying vec4 fragColor;\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\n\nvoid main() {\n  vec4 projected = projection * view * model * vec4(position, 1.0);\n  vec4 tangentClip = projection * view * model * vec4(nextPosition - position, 0.0);\n  vec2 tangent = normalize(screenShape * tangentClip.xy);\n  vec2 offset = 0.5 * pixelRatio * lineWidth * vec2(tangent.y, -tangent.x) / screenShape;\n\n  gl_Position = vec4(projected.xy + projected.w * offset, projected.zw);\n\n  worldPosition = position;\n  pixelArcLength = arcLength;\n  fragColor = color;\n}\n",a="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec3      clipBounds[2];\nuniform sampler2D dashTexture;\nuniform float     dashScale;\nuniform float     opacity;\n\nvarying vec3    worldPosition;\nvarying float   pixelArcLength;\nvarying vec4    fragColor;\n\nvoid main() {\n  if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n    discard;\n  }\n  float dashWeight = texture2D(dashTexture, vec2(dashScale * pixelArcLength, 0)).r;\n  if(dashWeight < 0.5) {\n    discard;\n  }\n  gl_FragColor = fragColor * opacity;\n}\n",o="#define GLSLIFY 1\nprecision mediump float;\n\n#define FLOAT_MAX  1.70141184e38\n#define FLOAT_MIN  1.17549435e-38\n\nlowp vec4 encode_float_1_0(highp float v) {\n  highp float av = abs(v);\n\n  //Handle special cases\n  if(av < FLOAT_MIN) {\n    return vec4(0.0, 0.0, 0.0, 0.0);\n  } else if(v > FLOAT_MAX) {\n    return vec4(127.0, 128.0, 0.0, 0.0) / 255.0;\n  } else if(v < -FLOAT_MAX) {\n    return vec4(255.0, 128.0, 0.0, 0.0) / 255.0;\n  }\n\n  highp vec4 c = vec4(0,0,0,0);\n\n  //Compute exponent and mantissa\n  highp float e = floor(log2(av));\n  highp float m = av * pow(2.0, -e) - 1.0;\n  \n  //Unpack mantissa\n  c[1] = floor(128.0 * m);\n  m -= c[1] / 128.0;\n  c[2] = floor(32768.0 * m);\n  m -= c[2] / 32768.0;\n  c[3] = floor(8388608.0 * m);\n  \n  //Unpack exponent\n  highp float ebias = e + 127.0;\n  c[0] = floor(ebias / 2.0);\n  ebias -= c[0] * 2.0;\n  c[1] += floor(ebias) * 128.0; \n\n  //Unpack sign bit\n  c[0] += 128.0 * step(0.0, -v);\n\n  //Scale back to range\n  return c / 255.0;\n}\n\n\n\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n  if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n    discard;\n  }\n  gl_FragColor = vec4(pickId/255.0, encode_float_1_0(pixelArcLength).xyz);\n}",s=[{name:"position",type:"vec3"},{name:"nextPosition",type:"vec3"},{name:"arcLength",type:"float"},{name:"lineWidth",type:"float"},{name:"color",type:"vec4"}];r.createShader=function(t){return n(t,i,a,null,s)},r.createPickShader=function(t){return n(t,i,o,null,s)}},{"gl-shader":154}],84:[function(t,e,r){"use strict";function n(t,e){for(var r=0,n=0;3>n;++n){var i=t[n]-e[n];r+=i*i}return Math.sqrt(r)}function i(t){for(var e=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],r=0;3>r;++r)e[0][r]=Math.max(t[0][r],e[0][r]),e[1][r]=Math.min(t[1][r],e[1][r]);return e}function a(t,e,r,n){this.arcLength=t,this.position=e,this.index=r,this.dataCoordinate=n}function o(t,e,r,n,i,a){this.gl=t,this.shader=e,this.pickShader=r,this.buffer=n,this.vao=i,this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.points=[],this.arcLength=[],this.vertexCount=0,this.bounds=[[0,0,0],[0,0,0]],this.pickId=0,this.lineWidth=1,this.texture=a,this.dashScale=1,this.opacity=1,this.dirty=!0,this.pixelRatio=1}function s(t){var e=t.gl||t.scene&&t.scene.gl,r=g(e);r.attributes.position.location=0,r.attributes.nextPosition.location=1,r.attributes.arcLength.location=2,r.attributes.lineWidth.location=3,r.attributes.color.location=4;var n=v(e);n.attributes.position.location=0,n.attributes.nextPosition.location=1,n.attributes.arcLength.location=2,n.attributes.lineWidth.location=3,n.attributes.color.location=4;for(var i=l(e),a=u(e,[{buffer:i,size:3,offset:0,stride:48},{buffer:i,size:3,offset:12,stride:48},{buffer:i,size:1,offset:24,stride:48},{buffer:i,size:1,offset:28,stride:48},{buffer:i,size:4,offset:32,stride:48}]),s=d(new Array(1024),[256,1,4]),h=0;1024>h;++h)s.data[h]=255;var f=c(e,s);f.wrap=e.REPEAT;var p=new o(e,r,n,i,a,f);return p.update(t),p}e.exports=s;var l=t("gl-buffer"),u=t("gl-vao"),c=t("gl-texture2d"),h=t("glsl-read-float"),f=t("binary-search-bounds"),d=t("ndarray"),p=t("./lib/shaders"),g=p.createShader,v=p.createPickShader,m=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],y=o.prototype;y.isTransparent=function(){return this.opacity<1},y.isOpaque=function(){return this.opacity>=1},y.pickSlots=1,y.setPickBase=function(t){this.pickId=t},y.drawTransparent=y.draw=function(t){var e=this.gl,r=this.shader,n=this.vao;r.bind(),r.uniforms={model:t.model||m,view:t.view||m,projection:t.projection||m,clipBounds:i(this.clipBounds),dashTexture:this.texture.bind(),dashScale:this.dashScale/this.arcLength[this.arcLength.length-1],opacity:this.opacity,screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount)},y.drawPick=function(t){var e=this.gl,r=this.pickShader,n=this.vao;r.bind(),r.uniforms={model:t.model||m,view:t.view||m,projection:t.projection||m,pickId:this.pickId,clipBounds:i(this.clipBounds),screenShape:[e.drawingBufferWidth,e.drawingBufferHeight],pixelRatio:this.pixelRatio},n.bind(),n.draw(e.TRIANGLE_STRIP,this.vertexCount)},y.update=function(t){this.dirty=!0,"dashScale"in t&&(this.dashScale=t.dashScale),"opacity"in t&&(this.opacity=+t.opacity);var e=t.position||t.positions;if(e){var r=t.color||t.colors||[0,0,0,1],i=t.lineWidth||1,a=[],o=[],s=[],l=0,u=0,c=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]];t:for(var h=1;h<e.length;++h){var p=e[h-1],g=e[h];o.push(l),s.push(p.slice());for(var v=0;3>v;++v){if(isNaN(p[v])||isNaN(g[v])||!isFinite(p[v])||!isFinite(g[v]))continue t;c[0][v]=Math.min(c[0][v],p[v],g[v]),c[1][v]=Math.max(c[1][v],p[v],g[v])}var m,y;Array.isArray(r[0])?(m=r[h-1],y=r[h]):m=y=r,3===m.length&&(m=[m[0],m[1],m[2],1]),3===y.length&&(y=[y[0],y[1],y[2],1]);var b,x;Array.isArray(i)?(b=i[h-1],x=lineWidht[h]):b=x=i;var _=l;l+=n(p,g),a.push(p[0],p[1],p[2],g[0],g[1],g[2],_,b,m[0],m[1],m[2],m[3],p[0],p[1],p[2],g[0],g[1],g[2],_,-b,m[0],m[1],m[2],m[3],g[0],g[1],g[2],p[0],p[1],p[2],l,-b,y[0],y[1],y[2],y[3],g[0],g[1],g[2],p[0],p[1],p[2],l,b,y[0],y[1],y[2],y[3]),u+=4}if(this.buffer.update(a),o.push(l),s.push(e[e.length-1].slice()),this.bounds=c,this.vertexCount=u,this.points=s,this.arcLength=o,"dashes"in t){var w=t.dashes,A=w.slice();A.unshift(0);for(var h=1;h<A.length;++h)A[h]=A[h-1]+A[h];for(var k=d(new Array(1024),[256,1,4]),h=0;256>h;++h){for(var v=0;4>v;++v)k.set(h,0,v,0);1&f.le(A,A[A.length-1]*h/255)?k.set(h,0,0,0):k.set(h,0,0,255)}this.texture.setPixels(k)}}},y.dispose=function(){this.shader.dispose(),this.vao.dispose(),this.buffer.dispose()},y.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=h(t.value[0],t.value[1],t.value[2],0),r=f.le(this.arcLength,e);if(0>r)return null;if(r===this.arcLength.length-1)return new a(this.arcLength[this.arcLength.length-1],this.points[this.points.length-1].slice(),r);for(var n=this.points[r],i=this.points[Math.min(r+1,this.points.length-1)],o=(e-this.arcLength[r])/(this.arcLength[r+1]-this.arcLength[r]),s=1-o,l=[0,0,0],u=0;3>u;++u)l[u]=s*n[u]+o*i[u];var c=Math.min(.5>o?r:r+1,this.points.length-1);return new a(e,l,c,this.points[c])}},{"./lib/shaders":83,"binary-search-bounds":85,"gl-buffer":75,"gl-texture2d":185,"gl-vao":189,"glsl-read-float":86,ndarray:208}],85:[function(t,e,r){arguments[4][20][0].apply(r,arguments)},{dup:20}],86:[function(t,e,r){function n(t,e,r,n){return i[0]=n,i[1]=r,i[2]=e,i[3]=t,a[0]}e.exports=n;var i=new Uint8Array(4),a=new Float32Array(i.buffer)},{}],87:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],u=e[7],c=e[8],h=c*o-s*u,f=-c*a+s*l,d=u*a-o*l,p=r*h+n*f+i*d;
+return p?(p=1/p,t[0]=h*p,t[1]=(-c*n+i*u)*p,t[2]=(s*n-i*o)*p,t[3]=f*p,t[4]=(c*r-i*l)*p,t[5]=(-s*r+i*a)*p,t[6]=d*p,t[7]=(-u*r+n*l)*p,t[8]=(o*r-n*a)*p,t):null}e.exports=n},{}],88:[function(t,e,r){function n(t){var e=new Float32Array(16);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}e.exports=n},{}],89:[function(t,e,r){function n(){var t=new Float32Array(16);return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],90:[function(t,e,r){function n(t){var e=t[0],r=t[1],n=t[2],i=t[3],a=t[4],o=t[5],s=t[6],l=t[7],u=t[8],c=t[9],h=t[10],f=t[11],d=t[12],p=t[13],g=t[14],v=t[15],m=e*o-r*a,y=e*s-n*a,b=e*l-i*a,x=r*s-n*o,_=r*l-i*o,w=n*l-i*s,A=u*p-c*d,k=u*g-h*d,M=u*v-f*d,T=c*g-h*p,E=c*v-f*p,L=h*v-f*g;return m*L-y*E+b*T+x*M-_*k+w*A}e.exports=n},{}],91:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r+r,s=n+n,l=i+i,u=r*o,c=n*o,h=n*s,f=i*o,d=i*s,p=i*l,g=a*o,v=a*s,m=a*l;return t[0]=1-h-p,t[1]=c+m,t[2]=f-v,t[3]=0,t[4]=c-m,t[5]=1-u-p,t[6]=d+g,t[7]=0,t[8]=f+v,t[9]=d-g,t[10]=1-u-h,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],92:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=n+n,l=i+i,u=a+a,c=n*s,h=n*l,f=n*u,d=i*l,p=i*u,g=a*u,v=o*s,m=o*l,y=o*u;return t[0]=1-(d+g),t[1]=h+y,t[2]=f-m,t[3]=0,t[4]=h-y,t[5]=1-(c+g),t[6]=p+v,t[7]=0,t[8]=f+m,t[9]=p-v,t[10]=1-(c+d),t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}e.exports=n},{}],93:[function(t,e,r){function n(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}e.exports=n},{}],94:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=e[4],s=e[5],l=e[6],u=e[7],c=e[8],h=e[9],f=e[10],d=e[11],p=e[12],g=e[13],v=e[14],m=e[15],y=r*s-n*o,b=r*l-i*o,x=r*u-a*o,_=n*l-i*s,w=n*u-a*s,A=i*u-a*l,k=c*g-h*p,M=c*v-f*p,T=c*m-d*p,E=h*v-f*g,L=h*m-d*g,S=f*m-d*v,C=y*S-b*L+x*E+_*T-w*M+A*k;return C?(C=1/C,t[0]=(s*S-l*L+u*E)*C,t[1]=(i*L-n*S-a*E)*C,t[2]=(g*A-v*w+m*_)*C,t[3]=(f*w-h*A-d*_)*C,t[4]=(l*T-o*S-u*M)*C,t[5]=(r*S-i*T+a*M)*C,t[6]=(v*x-p*A-m*b)*C,t[7]=(c*A-f*x+d*b)*C,t[8]=(o*L-s*T+u*k)*C,t[9]=(n*T-r*L-a*k)*C,t[10]=(p*w-g*x+m*y)*C,t[11]=(h*x-c*w-d*y)*C,t[12]=(s*M-o*E-l*k)*C,t[13]=(r*E-n*M+i*k)*C,t[14]=(g*b-p*_-v*y)*C,t[15]=(c*_-h*b+f*y)*C,t):null}e.exports=n},{}],95:[function(t,e,r){function n(t,e,r,n){var a,o,s,l,u,c,h,f,d,p,g=e[0],v=e[1],m=e[2],y=n[0],b=n[1],x=n[2],_=r[0],w=r[1],A=r[2];return Math.abs(g-_)<1e-6&&Math.abs(v-w)<1e-6&&Math.abs(m-A)<1e-6?i(t):(h=g-_,f=v-w,d=m-A,p=1/Math.sqrt(h*h+f*f+d*d),h*=p,f*=p,d*=p,a=b*d-x*f,o=x*h-y*d,s=y*f-b*h,p=Math.sqrt(a*a+o*o+s*s),p?(p=1/p,a*=p,o*=p,s*=p):(a=0,o=0,s=0),l=f*s-d*o,u=d*a-h*s,c=h*o-f*a,p=Math.sqrt(l*l+u*u+c*c),p?(p=1/p,l*=p,u*=p,c*=p):(l=0,u=0,c=0),t[0]=a,t[1]=l,t[2]=h,t[3]=0,t[4]=o,t[5]=u,t[6]=f,t[7]=0,t[8]=s,t[9]=c,t[10]=d,t[11]=0,t[12]=-(a*g+o*v+s*m),t[13]=-(l*g+u*v+c*m),t[14]=-(h*g+f*v+d*m),t[15]=1,t)}var i=t("./identity");e.exports=n},{"./identity":93}],96:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],u=e[6],c=e[7],h=e[8],f=e[9],d=e[10],p=e[11],g=e[12],v=e[13],m=e[14],y=e[15],b=r[0],x=r[1],_=r[2],w=r[3];return t[0]=b*n+x*s+_*h+w*g,t[1]=b*i+x*l+_*f+w*v,t[2]=b*a+x*u+_*d+w*m,t[3]=b*o+x*c+_*p+w*y,b=r[4],x=r[5],_=r[6],w=r[7],t[4]=b*n+x*s+_*h+w*g,t[5]=b*i+x*l+_*f+w*v,t[6]=b*a+x*u+_*d+w*m,t[7]=b*o+x*c+_*p+w*y,b=r[8],x=r[9],_=r[10],w=r[11],t[8]=b*n+x*s+_*h+w*g,t[9]=b*i+x*l+_*f+w*v,t[10]=b*a+x*u+_*d+w*m,t[11]=b*o+x*c+_*p+w*y,b=r[12],x=r[13],_=r[14],w=r[15],t[12]=b*n+x*s+_*h+w*g,t[13]=b*i+x*l+_*f+w*v,t[14]=b*a+x*u+_*d+w*m,t[15]=b*o+x*c+_*p+w*y,t}e.exports=n},{}],97:[function(t,e,r){function n(t,e,r,n,i){var a=1/Math.tan(e/2),o=1/(n-i);return t[0]=a/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=a,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=(i+n)*o,t[11]=-1,t[12]=0,t[13]=0,t[14]=2*i*n*o,t[15]=0,t}e.exports=n},{}],98:[function(t,e,r){function n(t,e,r,n){var i,a,o,s,l,u,c,h,f,d,p,g,v,m,y,b,x,_,w,A,k,M,T,E,L=n[0],S=n[1],C=n[2],P=Math.sqrt(L*L+S*S+C*C);return Math.abs(P)<1e-6?null:(P=1/P,L*=P,S*=P,C*=P,i=Math.sin(r),a=Math.cos(r),o=1-a,s=e[0],l=e[1],u=e[2],c=e[3],h=e[4],f=e[5],d=e[6],p=e[7],g=e[8],v=e[9],m=e[10],y=e[11],b=L*L*o+a,x=S*L*o+C*i,_=C*L*o-S*i,w=L*S*o-C*i,A=S*S*o+a,k=C*S*o+L*i,M=L*C*o+S*i,T=S*C*o-L*i,E=C*C*o+a,t[0]=s*b+h*x+g*_,t[1]=l*b+f*x+v*_,t[2]=u*b+d*x+m*_,t[3]=c*b+p*x+y*_,t[4]=s*w+h*A+g*k,t[5]=l*w+f*A+v*k,t[6]=u*w+d*A+m*k,t[7]=c*w+p*A+y*k,t[8]=s*M+h*T+g*E,t[9]=l*M+f*T+v*E,t[10]=u*M+d*T+m*E,t[11]=c*M+p*T+y*E,e!==t&&(t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t)}e.exports=n},{}],99:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[4],o=e[5],s=e[6],l=e[7],u=e[8],c=e[9],h=e[10],f=e[11];return e!==t&&(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[4]=a*i+u*n,t[5]=o*i+c*n,t[6]=s*i+h*n,t[7]=l*i+f*n,t[8]=u*i-a*n,t[9]=c*i-o*n,t[10]=h*i-s*n,t[11]=f*i-l*n,t}e.exports=n},{}],100:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],u=e[8],c=e[9],h=e[10],f=e[11];return e!==t&&(t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i-u*n,t[1]=o*i-c*n,t[2]=s*i-h*n,t[3]=l*i-f*n,t[8]=a*n+u*i,t[9]=o*n+c*i,t[10]=s*n+h*i,t[11]=l*n+f*i,t}e.exports=n},{}],101:[function(t,e,r){function n(t,e,r){var n=Math.sin(r),i=Math.cos(r),a=e[0],o=e[1],s=e[2],l=e[3],u=e[4],c=e[5],h=e[6],f=e[7];return e!==t&&(t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15]),t[0]=a*i+u*n,t[1]=o*i+c*n,t[2]=s*i+h*n,t[3]=l*i+f*n,t[4]=u*i-a*n,t[5]=c*i-o*n,t[6]=h*i-s*n,t[7]=f*i-l*n,t}e.exports=n},{}],102:[function(t,e,r){function n(t,e,r){var n=r[0],i=r[1],a=r[2];return t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t[3]=e[3]*n,t[4]=e[4]*i,t[5]=e[5]*i,t[6]=e[6]*i,t[7]=e[7]*i,t[8]=e[8]*a,t[9]=e[9]*a,t[10]=e[10]*a,t[11]=e[11]*a,t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}e.exports=n},{}],103:[function(t,e,r){function n(t,e,r){var n,i,a,o,s,l,u,c,h,f,d,p,g=r[0],v=r[1],m=r[2];return e===t?(t[12]=e[0]*g+e[4]*v+e[8]*m+e[12],t[13]=e[1]*g+e[5]*v+e[9]*m+e[13],t[14]=e[2]*g+e[6]*v+e[10]*m+e[14],t[15]=e[3]*g+e[7]*v+e[11]*m+e[15]):(n=e[0],i=e[1],a=e[2],o=e[3],s=e[4],l=e[5],u=e[6],c=e[7],h=e[8],f=e[9],d=e[10],p=e[11],t[0]=n,t[1]=i,t[2]=a,t[3]=o,t[4]=s,t[5]=l,t[6]=u,t[7]=c,t[8]=h,t[9]=f,t[10]=d,t[11]=p,t[12]=n*g+s*v+h*m+e[12],t[13]=i*g+l*v+f*m+e[13],t[14]=a*g+u*v+d*m+e[14],t[15]=o*g+c*v+p*m+e[15]),t}e.exports=n},{}],104:[function(t,e,r){function n(t,e){if(t===e){var r=e[1],n=e[2],i=e[3],a=e[6],o=e[7],s=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=r,t[6]=e[9],t[7]=e[13],t[8]=n,t[9]=a,t[11]=e[14],t[12]=i,t[13]=o,t[14]=s}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}e.exports=n},{}],105:[function(t,e,r){"use strict";function n(t,e){for(var r=[0,0,0,0],n=0;4>n;++n)for(var i=0;4>i;++i)r[i]+=t[4*n+i]*e[n];return r}function i(t,e,r,i,a){for(var o=n(i,n(r,n(e,[t[0],t[1],t[2],1]))),s=0;3>s;++s)o[s]/=o[3];return[.5*a[0]*(1+o[0]),.5*a[1]*(1-o[1])]}function a(t,e){if(2===t.length){for(var r=0,n=0,i=0;2>i;++i)r+=Math.pow(e[i]-t[0][i],2),n+=Math.pow(e[i]-t[1][i],2);return r=Math.sqrt(r),n=Math.sqrt(n),1e-6>r+n?[1,0]:[n/(r+n),r/(n+r)]}if(3===t.length){var a=[0,0];return u(t[0],t[1],t[2],e,a),l(t,a)}return[]}function o(t,e){for(var r=[0,0,0],n=0;n<t.length;++n)for(var i=t[n],a=e[n],o=0;3>o;++o)r[o]+=a*i[o];return r}function s(t,e,r,n,s,l){if(1===t.length)return[0,t[0].slice()];for(var u=new Array(t.length),c=0;c<t.length;++c)u[c]=i(t[c],r,n,s,l);for(var h=0,f=1/0,c=0;c<u.length;++c){for(var d=0,p=0;2>p;++p)d+=Math.pow(u[c][p]-e[p],2);f>d&&(f=d,h=c)}for(var g=a(u,e),v=0,c=0;3>c;++c){if(g[c]<-.001||g[c]>1.0001)return null;v+=g[c]}return Math.abs(v-1)>.001?null:[h,o(t,g),g]}var l=t("barycentric"),u=t("polytope-closest-point/lib/closest_point_2d.js");e.exports=s},{barycentric:108,"polytope-closest-point/lib/closest_point_2d.js":110}],106:[function(t,e,r){var n="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model\n           , view\n           , projection;\nuniform vec3 eyePosition\n           , lightPosition;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  vec4 m_position  = model * vec4(position, 1.0);\n  vec4 t_position  = view * m_position;\n  gl_Position      = projection * t_position;\n  f_color          = color;\n  f_normal         = normal;\n  f_data           = position;\n  f_eyeDirection   = eyePosition   - position;\n  f_lightDirection = lightPosition - position;\n  f_uv             = uv;\n}",i="#define GLSLIFY 1\nprecision mediump float;\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat cookTorranceSpecular_1_1(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness,\n  float fresnel) {\n\n  float VdotN = max(dot(viewDirection, surfaceNormal), 0.0);\n  float LdotN = max(dot(lightDirection, surfaceNormal), 0.0);\n\n  //Half angle vector\n  vec3 H = normalize(lightDirection + viewDirection);\n\n  //Geometric term\n  float NdotH = max(dot(surfaceNormal, H), 0.0);\n  float VdotH = max(dot(viewDirection, H), 0.000001);\n  float LdotH = max(dot(lightDirection, H), 0.000001);\n  float G1 = (2.0 * NdotH * VdotN) / VdotH;\n  float G2 = (2.0 * NdotH * LdotN) / LdotH;\n  float G = min(1.0, min(G1, G2));\n  \n  //Distribution term\n  float D = beckmannDistribution_2_0(NdotH, roughness);\n\n  //Fresnel term\n  float F = pow(1.0 - VdotN, fresnel);\n\n  //Multiply terms and done\n  return  G * F * D / max(3.14159265 * VdotN, 0.000001);\n}\n\n\n\nuniform vec3 clipBounds[2];\nuniform float roughness\n            , fresnel\n            , kambient\n            , kdiffuse\n            , kspecular\n            , opacity;\nuniform sampler2D texture;\n\nvarying vec3 f_normal\n           , f_lightDirection\n           , f_eyeDirection\n           , f_data;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if(any(lessThan(f_data, clipBounds[0])) || \n     any(greaterThan(f_data, clipBounds[1]))) {\n    discard;\n  }\n\n  vec3 N = normalize(f_normal);\n  vec3 L = normalize(f_lightDirection);\n  vec3 V = normalize(f_eyeDirection);\n  \n  if(!gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = cookTorranceSpecular_1_1(L, V, N, roughness, fresnel);\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  vec4 surfaceColor = f_color * texture2D(texture, f_uv);\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = litColor * opacity;\n}",a="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\n\nuniform mat4 model, view, projection;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n  f_color = color;\n  f_data  = position;\n  f_uv    = uv;\n}",o="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec3 clipBounds[2];\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec3 f_data;\nvarying vec2 f_uv;\n\nvoid main() {\n  if(any(lessThan(f_data, clipBounds[0])) || \n     any(greaterThan(f_data, clipBounds[1]))) {\n    discard;\n  }\n\n  gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}",s="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 uv;\nattribute float pointSize;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  if(any(lessThan(position, clipBounds[0])) || \n     any(greaterThan(position, clipBounds[1]))) {\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    gl_Position = projection * view * model * vec4(position, 1.0);\n  }\n  gl_PointSize = pointSize;\n  f_color = color;\n  f_uv = uv;\n}",l="#define GLSLIFY 1\nprecision mediump float;\n\nuniform sampler2D texture;\nuniform float opacity;\n\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n  vec2 pointR = gl_PointCoord.xy - vec2(0.5,0.5);\n  if(dot(pointR, pointR) > 0.25) {\n    discard;\n  }\n  gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}",u="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n  f_id        = id;\n  f_position  = position;\n}",c="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec3  clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if(any(lessThan(f_position, clipBounds[0])) || \n     any(greaterThan(f_position, clipBounds[1]))) {\n    discard;\n  }\n  gl_FragColor = vec4(pickId, f_id.xyz);\n}",h="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3  position;\nattribute float pointSize;\nattribute vec4  id;\n\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n  if(any(lessThan(position, clipBounds[0])) || \n     any(greaterThan(position, clipBounds[1]))) {\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    gl_Position  = projection * view * model * vec4(position, 1.0);\n    gl_PointSize = pointSize;\n  }\n  f_id         = id;\n  f_position   = position;\n}",f="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\n\nvoid main() {\n  gl_Position = projection * view * model * vec4(position, 1.0);\n}",d="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec3 contourColor;\n\nvoid main() {\n  gl_FragColor = vec4(contourColor,1);\n}\n";r.meshShader={vertex:n,fragment:i,attributes:[{name:"position",type:"vec3"},{name:"normal",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.wireShader={vertex:a,fragment:o,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"}]},r.pointShader={vertex:s,fragment:l,attributes:[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"uv",type:"vec2"},{name:"pointSize",type:"float"}]},r.pickShader={vertex:u,fragment:c,attributes:[{name:"position",type:"vec3"},{name:"id",type:"vec4"}]},r.pointPickShader={vertex:h,fragment:c,attributes:[{name:"position",type:"vec3"},{name:"pointSize",type:"float"},{name:"id",type:"vec4"}]},r.contourShader={vertex:f,fragment:d,attributes:[{name:"position",type:"vec3"}]}},{}],107:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s,l,u,c,h,f,d,p,g,v,m,y,b,x,_,w,A,k,M,T){this.gl=t,this.cells=[],this.positions=[],this.intensity=[],this.texture=e,this.dirty=!0,this.triShader=r,this.lineShader=n,this.pointShader=i,this.pickShader=a,this.pointPickShader=o,this.contourShader=s,this.trianglePositions=l,this.triangleColors=c,this.triangleNormals=f,this.triangleUVs=h,this.triangleIds=u,this.triangleVAO=d,this.triangleCount=0,this.lineWidth=1,this.edgePositions=p,this.edgeColors=v,this.edgeUVs=m,this.edgeIds=g,this.edgeVAO=y,this.edgeCount=0,this.pointPositions=b,this.pointColors=_,this.pointUVs=w,this.pointSizes=A,this.pointIds=x,this.pointVAO=k,this.pointCount=0,this.contourLineWidth=1,this.contourPositions=M,this.contourVAO=T,this.contourCount=0,this.contourColor=[0,0,0],this.contourEnable=!0,this.pickId=1,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.lightPosition=[1e5,1e5,0],this.ambientLight=.8,this.diffuseLight=.8,this.specularLight=2,this.roughness=.5,this.fresnel=1.5,this.opacity=1,this._model=R,this._view=R,this._projection=R,this._resolution=[1,1]}function i(t){for(var e=w({colormap:t,nshades:256,format:"rgba"}),r=new Uint8Array(1024),n=0;256>n;++n){for(var i=e[n],a=0;3>a;++a)r[4*n+a]=i[a];r[4*n+3]=255*i[3]}return _(r,[256,256,4],[4,0,1])}function a(t,e,r){for(var n=new Array(e),i=0;e>i;++i)n[i]=0;for(var a=t.length,i=0;a>i;++i)for(var o=t[i],s=0;s<o.length;++s)n[o[s]]=r[i];return n}function o(t){for(var e=t.length,r=new Array(e),n=0;e>n;++n)r[n]=t[n][2];return r}function s(t){var e=p(t,E);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.normal.location=4,e}function l(t){var e=p(t,L);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e}function u(t){var e=p(t,S);return e.attributes.position.location=0,e.attributes.color.location=2,e.attributes.uv.location=3,e.attributes.pointSize.location=4,e}function c(t){var e=p(t,C);return e.attributes.position.location=0,e.attributes.id.location=1,e}function h(t){var e=p(t,P);return e.attributes.position.location=0,e.attributes.id.location=1,e.attributes.pointSize.location=4,e}function f(t){var e=p(t,z);return e.attributes.position.location=0,e}function d(t){var e=t.gl,r=s(e),i=l(e),a=u(e),o=c(e),d=h(e),p=f(e),y=m(e,_(new Uint8Array([255,255,255,255]),[1,1,4]));y.generateMipmap(),y.minFilter=e.LINEAR_MIPMAP_LINEAR,y.magFilter=e.LINEAR;var b=g(e),x=g(e),w=g(e),A=g(e),k=g(e),M=v(e,[{buffer:b,type:e.FLOAT,size:3},{buffer:k,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:x,type:e.FLOAT,size:4},{buffer:w,type:e.FLOAT,size:2},{buffer:A,type:e.FLOAT,size:3}]),T=g(e),E=g(e),L=g(e),S=g(e),C=v(e,[{buffer:T,type:e.FLOAT,size:3},{buffer:S,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:E,type:e.FLOAT,size:4},{buffer:L,type:e.FLOAT,size:2}]),P=g(e),z=g(e),R=g(e),O=g(e),I=g(e),j=v(e,[{buffer:P,type:e.FLOAT,size:3},{buffer:I,type:e.UNSIGNED_BYTE,size:4,normalized:!0},{buffer:z,type:e.FLOAT,size:4},{buffer:R,type:e.FLOAT,size:2},{buffer:O,type:e.FLOAT,size:1}]),N=g(e),F=v(e,[{buffer:N,type:e.FLOAT,size:3}]),B=new n(e,y,r,i,a,o,d,p,b,k,x,w,A,M,T,S,E,L,C,P,I,z,R,O,j,N,F);return B.update(t),B}var p=t("gl-shader"),g=t("gl-buffer"),v=t("gl-vao"),m=t("gl-texture2d"),y=t("normals"),b=t("gl-mat4/multiply"),x=t("gl-mat4/invert"),_=t("ndarray"),w=t("colormap"),A=t("simplicial-complex-contour"),k=t("typedarray-pool"),M=t("./lib/shaders"),T=t("./lib/closest-point"),E=M.meshShader,L=M.wireShader,S=M.pointShader,C=M.pickShader,P=M.pointPickShader,z=M.contourShader,R=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],O=n.prototype;O.isOpaque=function(){return this.opacity>=1},O.isTransparent=function(){return this.opacity<1},O.pickSlots=1,O.setPickBase=function(t){this.pickId=t},O.highlight=function(t){if(!t||!this.contourEnable)return void(this.contourCount=0);for(var e=A(this.cells,this.intensity,t.intensity),r=e.cells,n=e.vertexIds,i=e.vertexWeights,a=r.length,o=k.mallocFloat32(6*a),s=0,l=0;a>l;++l)for(var u=r[l],c=0;2>c;++c){var h=u[0];2===u.length&&(h=u[c]);for(var f=n[h][0],d=n[h][1],p=i[h],g=1-p,v=this.positions[f],m=this.positions[d],y=0;3>y;++y)o[s++]=p*v[y]+g*m[y]}this.contourCount=s/3|0,this.contourPositions.update(o.subarray(0,s)),k.free(o)},O.update=function(t){t=t||{};var e=this.gl;this.dirty=!0,"contourEnable"in t&&(this.contourEnable=t.contourEnable),"contourColor"in t&&(this.contourColor=t.contourColor),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"opacity"in t&&(this.opacity=t.opacity),t.texture?(this.texture.dispose(),this.texture=m(e,t.texture)):t.colormap&&(this.texture.shape=[256,256],this.texture.minFilter=e.LINEAR_MIPMAP_LINEAR,this.texture.magFilter=e.LINEAR,this.texture.setPixels(i(t.colormap)),this.texture.generateMipmap());var r=t.cells,n=t.positions;if(n&&r){var s=[],l=[],u=[],c=[],h=[],f=[],d=[],p=[],g=[],v=[],b=[],x=[],_=[],w=[];this.cells=r,this.positions=n;var A=t.vertexNormals,k=t.cellNormals;t.useFacetNormals&&!k&&(k=y.faceNormals(r,n)),k||A||(A=y.vertexNormals(r,n));var M=t.vertexColors,T=t.cellColors,E=t.meshColor||[1,1,1,1],L=t.vertexUVs,S=t.vertexIntensity,C=t.cellUVs,P=t.cellIntensity,z=1/0,R=-(1/0);if(!L&&!C)if(S)for(var O=0;O<S.length;++O){var I=S[O];z=Math.min(z,I),R=Math.max(R,I)}else if(P)for(var O=0;O<P.length;++O){var I=P[O];z=Math.min(z,I),R=Math.max(R,I)}else for(var O=0;O<n.length;++O){var I=n[O][2];z=Math.min(z,I),R=Math.max(R,I)}S?this.intensity=S:P?this.intensity=a(r,n.length,P):this.intensity=o(n);var j=t.pointSizes,N=t.pointSize||1;this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]];for(var O=0;O<n.length;++O)for(var F=n[O],B=0;3>B;++B)!isNaN(F[B])&&isFinite(F[B])&&(this.bounds[0][B]=Math.min(this.bounds[0][B],F[B]),this.bounds[1][B]=Math.max(this.bounds[1][B],F[B]));var D=0,U=0,V=0;t:for(var O=0;O<r.length;++O){var q=r[O];switch(q.length){case 1:for(var H=q[0],F=n[H],B=0;3>B;++B)if(isNaN(F[B])||!isFinite(F[B]))continue t;v.push(F[0],F[1],F[2]);var G;G=M?M[H]:T?T[O]:E,3===G.length?b.push(G[0],G[1],G[2],1):b.push(G[0],G[1],G[2],G[3]);var Y;Y=L?L[H]:S?[(S[H]-z)/(R-z),0]:C?C[O]:P?[(P[O]-z)/(R-z),0]:[(F[2]-z)/(R-z),0],x.push(Y[0],Y[1]),j?_.push(j[H]):_.push(N),w.push(O),V+=1;break;case 2:for(var B=0;2>B;++B)for(var H=q[B],F=n[H],X=0;3>X;++X)if(isNaN(F[X])||!isFinite(F[X]))continue t;for(var B=0;2>B;++B){var H=q[B],F=n[H];f.push(F[0],F[1],F[2]);var G;G=M?M[H]:T?T[O]:E,3===G.length?d.push(G[0],G[1],G[2],1):d.push(G[0],G[1],G[2],G[3]);var Y;Y=L?L[H]:S?[(S[H]-z)/(R-z),0]:C?C[O]:P?[(P[O]-z)/(R-z),0]:[(F[2]-z)/(R-z),0],p.push(Y[0],Y[1]),g.push(O)}U+=1;break;case 3:for(var B=0;3>B;++B)for(var H=q[B],F=n[H],X=0;3>X;++X)if(isNaN(F[X])||!isFinite(F[X]))continue t;for(var B=0;3>B;++B){var H=q[B],F=n[H];s.push(F[0],F[1],F[2]);var G;G=M?M[H]:T?T[O]:E,3===G.length?l.push(G[0],G[1],G[2],1):l.push(G[0],G[1],G[2],G[3]);var Y;Y=L?L[H]:S?[(S[H]-z)/(R-z),0]:C?C[O]:P?[(P[O]-z)/(R-z),0]:[(F[2]-z)/(R-z),0],c.push(Y[0],Y[1]);var W;W=A?A[H]:k[O],u.push(W[0],W[1],W[2]),h.push(O)}D+=1}}this.pointCount=V,this.edgeCount=U,this.triangleCount=D,this.pointPositions.update(v),this.pointColors.update(b),this.pointUVs.update(x),this.pointSizes.update(_),this.pointIds.update(new Uint32Array(w)),this.edgePositions.update(f),this.edgeColors.update(d),this.edgeUVs.update(p),this.edgeIds.update(new Uint32Array(g)),this.trianglePositions.update(s),this.triangleColors.update(l),this.triangleUVs.update(c),this.triangleNormals.update(u),this.triangleIds.update(new Uint32Array(h))}},O.drawTransparent=O.draw=function(t){t=t||{};for(var e=this.gl,r=t.model||R,n=t.view||R,i=t.projection||R,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;3>o;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);var s={model:r,view:n,projection:i,clipBounds:a,kambient:this.ambientLight,kdiffuse:this.diffuseLight,kspecular:this.specularLight,roughness:this.roughness,fresnel:this.fresnel,eyePosition:[0,0,0],lightPosition:[0,0,0],opacity:this.opacity,contourColor:this.contourColor,texture:0};this.texture.bind(0);var l=new Array(16);b(l,s.view,s.model),b(l,s.projection,l),x(l,l);for(var o=0;3>o;++o)s.eyePosition[o]=l[12+o]/l[15];for(var u=l[15],o=0;3>o;++o)u+=this.lightPosition[o]*l[4*o+3];for(var o=0;3>o;++o){for(var c=l[12+o],h=0;3>h;++h)c+=l[4*h+o]*this.lightPosition[h];s.lightPosition[o]=c/u}if(this.triangleCount>0){var f=this.triShader;f.bind(),f.uniforms=s,this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()}if(this.edgeCount>0&&this.lineWidth>0){var f=this.lineShader;f.bind(),f.uniforms=s,this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()}if(this.pointCount>0){var f=this.pointShader;f.bind(),f.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind()}if(this.contourEnable&&this.contourCount>0&&this.contourLineWidth>0){var f=this.contourShader;f.bind(),f.uniforms=s,this.contourVAO.bind(),e.drawArrays(e.LINES,0,this.contourCount),this.contourVAO.unbind()}},O.drawPick=function(t){t=t||{};for(var e=this.gl,r=t.model||R,n=t.view||R,i=t.projection||R,a=[[-1e6,-1e6,-1e6],[1e6,1e6,1e6]],o=0;3>o;++o)a[0][o]=Math.max(a[0][o],this.clipBounds[0][o]),a[1][o]=Math.min(a[1][o],this.clipBounds[1][o]);this._model=[].slice.call(r),this._view=[].slice.call(n),this._projection=[].slice.call(i),this._resolution=[e.drawingBufferWidth,e.drawingBufferHeight];var s={model:r,view:n,projection:i,clipBounds:a,pickId:this.pickId/255},l=this.pickShader;if(l.bind(),l.uniforms=s,this.triangleCount>0&&(this.triangleVAO.bind(),e.drawArrays(e.TRIANGLES,0,3*this.triangleCount),this.triangleVAO.unbind()),this.edgeCount>0&&(this.edgeVAO.bind(),e.lineWidth(this.lineWidth),e.drawArrays(e.LINES,0,2*this.edgeCount),this.edgeVAO.unbind()),this.pointCount>0){var l=this.pointPickShader;l.bind(),l.uniforms=s,this.pointVAO.bind(),e.drawArrays(e.POINTS,0,this.pointCount),this.pointVAO.unbind()}},O.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;for(var e=t.value[0]+256*t.value[1]+65536*t.value[2],r=this.cells[e],n=this.positions,i=new Array(r.length),a=0;a<r.length;++a)i[a]=n[r[a]];var o=T(i,[t.coord[0],this._resolution[1]-t.coord[1]],this._model,this._view,this._projection,this._resolution);if(!o)return null;for(var s=o[2],l=0,a=0;a<r.length;++a)l+=s[a]*this.intensity[r[a]];return{position:o[1],index:r[o[0]],cell:r,cellId:e,intensity:l,dataCoordinate:this.positions[r[o[0]]]}},O.dispose=function(){this.texture.dispose(),this.triShader.dispose(),this.lineShader.dispose(),this.pointShader.dispose(),this.pickShader.dispose(),this.pointPickShader.dispose(),this.triangleVAO.dispose(),this.trianglePositions.dispose(),this.triangleColors.dispose(),this.triangleUVs.dispose(),this.triangleNormals.dispose(),this.triangleIds.dispose(),this.edgeVAO.dispose(),this.edgePositions.dispose(),this.edgeColors.dispose(),this.edgeUVs.dispose(),this.edgeIds.dispose(),this.pointVAO.dispose(),this.pointPositions.dispose(),this.pointColors.dispose(),this.pointUVs.dispose(),this.pointSizes.dispose(),this.pointIds.dispose(),this.contourVAO.dispose(),this.contourPositions.dispose(),this.contourShader.dispose()},e.exports=d},{"./lib/closest-point":105,"./lib/shaders":106,colormap:57,"gl-buffer":75,"gl-mat4/invert":94,"gl-mat4/multiply":96,"gl-shader":154,"gl-texture2d":185,"gl-vao":189,ndarray:208,normals:109,"simplicial-complex-contour":111,"typedarray-pool":233}],108:[function(t,e,r){"use strict";function n(t){for(var e=0,r=0;r<t.length;++r)e+=t[r];return e}function i(t,e){for(var r=e.length,i=new Array(r+1),o=0;r>o;++o){for(var s=new Array(r+1),l=0;r>=l;++l)s[l]=t[l][o];i[o]=s}i[r]=new Array(r+1);for(var o=0;r>=o;++o)i[r][o]=1;for(var u=new Array(r+1),o=0;r>o;++o)u[o]=e[o];u[r]=1;var c=a(i,u),h=n(c[r+1]);0===h&&(h=1);for(var f=new Array(r+1),o=0;r>=o;++o)f[o]=n(c[o])/h;return f}e.exports=i;var a=t("robust-linear-solve")},{"robust-linear-solve":211}],109:[function(t,e,r){var n=1e-6;r.vertexNormals=function(t,e){for(var r=e.length,i=new Array(r),a=0;r>a;++a)i[a]=[0,0,0];for(var a=0;a<t.length;++a)for(var o=t[a],s=0,l=o[o.length-1],u=o[0],c=0;c<o.length;++c){s=l,l=u,u=o[(c+1)%o.length];for(var h=e[s],f=e[l],d=e[u],p=new Array(3),g=0,v=new Array(3),m=0,y=0;3>y;++y)p[y]=h[y]-f[y],g+=p[y]*p[y],v[y]=d[y]-f[y],m+=v[y]*v[y];if(g*m>n)for(var b=i[l],x=1/Math.sqrt(g*m),y=0;3>y;++y){var _=(y+1)%3,w=(y+2)%3;b[y]+=x*(v[_]*p[w]-v[w]*p[_])}}for(var a=0;r>a;++a){for(var b=i[a],A=0,y=0;3>y;++y)A+=b[y]*b[y];if(A>n)for(var x=1/Math.sqrt(A),y=0;3>y;++y)b[y]*=x;else for(var y=0;3>y;++y)b[y]=0}return i},r.faceNormals=function(t,e){for(var r=t.length,i=new Array(r),a=0;r>a;++a){for(var o=t[a],s=new Array(3),l=0;3>l;++l)s[l]=e[o[l]];for(var u=new Array(3),c=new Array(3),l=0;3>l;++l)u[l]=s[1][l]-s[0][l],c[l]=s[2][l]-s[0][l];for(var h=new Array(3),f=0,l=0;3>l;++l){var d=(l+1)%3,p=(l+2)%3;h[l]=u[d]*c[p]-u[p]*c[d],f+=h[l]*h[l]}f=f>n?1/Math.sqrt(f):0;for(var l=0;3>l;++l)h[l]*=f;i[a]=h}return i}},{}],110:[function(t,e,r){"use strict";function n(t,e,r,n,s){i.length<n.length&&(i=new Float64Array(n.length),a=new Float64Array(n.length),o=new Float64Array(n.length));for(var l=0;l<n.length;++l)i[l]=t[l]-n[l],a[l]=e[l]-t[l],o[l]=r[l]-t[l];for(var u=0,c=0,h=0,f=0,d=0,p=0,l=0;l<n.length;++l){var g=a[l],v=o[l],m=i[l];u+=g*g,c+=g*v,h+=v*v,f+=m*g,d+=m*v,p+=m*m}var y,b=Math.abs(u*h-c*c),x=c*d-h*f,_=c*f-u*d;if(b>=x+_)if(0>x)0>_&&0>f?(_=0,-f>=u?(x=1,y=u+2*f+p):(x=-f/u,y=f*x+p)):(x=0,d>=0?(_=0,y=p):-d>=h?(_=1,y=h+2*d+p):(_=-d/h,y=d*_+p));else if(0>_)_=0,f>=0?(x=0,y=p):-f>=u?(x=1,y=u+2*f+p):(x=-f/u,y=f*x+p);else{var w=1/b;x*=w,_*=w,y=x*(u*x+c*_+2*f)+_*(c*x+h*_+2*d)+p}else{var A,k,M,T;0>x?(A=c+f,k=h+d,k>A?(M=k-A,T=u-2*c+h,M>=T?(x=1,_=0,y=u+2*f+p):(x=M/T,_=1-x,y=x*(u*x+c*_+2*f)+_*(c*x+h*_+2*d)+p)):(x=0,0>=k?(_=1,y=h+2*d+p):d>=0?(_=0,y=p):(_=-d/h,y=d*_+p))):0>_?(A=c+d,k=u+f,k>A?(M=k-A,T=u-2*c+h,M>=T?(_=1,x=0,y=h+2*d+p):(_=M/T,x=1-_,y=x*(u*x+c*_+2*f)+_*(c*x+h*_+2*d)+p)):(_=0,0>=k?(x=1,y=u+2*f+p):f>=0?(x=0,y=p):(x=-f/u,y=f*x+p))):(M=h+d-c-f,0>=M?(x=0,_=1,y=h+2*d+p):(T=u-2*c+h,M>=T?(x=1,_=0,y=u+2*f+p):(x=M/T,_=1-x,y=x*(u*x+c*_+2*f)+_*(c*x+h*_+2*d)+p)))}for(var E=1-x-_,l=0;l<n.length;++l)s[l]=E*t[l]+x*e[l]+_*r[l];return 0>y?0:y}var i=new Float64Array(4),a=new Float64Array(4),o=new Float64Array(4);e.exports=n},{}],111:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=0,n=0;e>n;++n)r=0|Math.max(r,t[n].length);return r-1}function i(t,e){for(var r=t.length,n=h.mallocUint8(r),i=0;r>i;++i)n[i]=t[i]<e|0;return n}function a(t,e){for(var r=t.length,n=e*(e+1)/2*r|0,i=h.mallocUint32(2*n),a=0,o=0;r>o;++o)for(var s=t[o],e=s.length,l=0;e>l;++l)for(var u=0;l>u;++u){var d=s[u],p=s[l];i[a++]=0|Math.min(d,p),i[a++]=0|Math.max(d,p)}var g=a/2|0;f(c(i,[g,2]));for(var v=2,o=2;a>o;o+=2)(i[o-2]!==i[o]||i[o-1]!==i[o+1])&&(i[v++]=i[o],i[v++]=i[o+1]);return c(i,[v/2|0,2])}function o(t,e,r,n){for(var i=t.data,a=t.shape[0],o=h.mallocDouble(a),s=0,l=0;a>l;++l){var u=i[2*l],f=i[2*l+1];if(r[u]!==r[f]){var d=e[u],p=e[f];i[2*s]=u,i[2*s+1]=f,o[s++]=(p-n)/(p-d)}}return t.shape[0]=s,c(o,[s])}function s(t,e){var r=h.mallocInt32(2*e),n=t.shape[0],i=t.data;r[0]=0;for(var a=0,o=0;n>o;++o){var s=i[2*o];if(s!==a){for(r[2*a+1]=o;++a<s;)r[2*a]=o,r[2*a+1]=o;r[2*a]=o}}for(r[2*a+1]=n;++a<e;)r[2*a]=r[2*a+1]=n;return r}function l(t){for(var e=0|t.shape[0],r=t.data,n=new Array(e),i=0;e>i;++i)n[i]=[r[2*i],r[2*i+1]];return n}function u(t,e,r,u){r=r||0,"undefined"==typeof u&&(u=n(t));var c=t.length;if(0===c||1>u)return{cells:[],vertexIds:[],vertexWeights:[]};var f=i(e,+r),p=a(t,u),g=o(p,e,f,+r),v=s(p,0|e.length),m=d(u)(t,p.data,v,f),y=l(p),b=[].slice.call(g.data,0,g.shape[0]);return h.free(f),h.free(p.data),h.free(g.data),h.free(v),{cells:m,vertexIds:y,vertexWeights:b}}e.exports=u;var c=t("ndarray"),h=t("typedarray-pool"),f=t("ndarray-sort"),d=t("./lib/codegen")},{"./lib/codegen":112,ndarray:208,"ndarray-sort":115,"typedarray-pool":233}],112:[function(t,e,r){"use strict";function n(t){function e(t){if(!(t.length<=0)){u.push("R.push(");for(var e=0;e<t.length;++e){var r=t[e];e>0&&u.push(","),u.push("[");for(var n=0;n<r.length;++n){var i=r[n];n>0&&u.push(","),u.push("B(C,E,c[",i[0],"],c[",i[1],"])")}u.push("]")}u.push(");")}}var r=0,n=new Array(t+1);n[0]=[[]];for(var i=1;t>=i;++i)for(var s=n[i]=o(i),l=0;l<s.length;++l)r=Math.max(r,s[i].length);for(var u=["function B(C,E,i,j){","var a=Math.min(i,j)|0,b=Math.max(i,j)|0,l=C[2*a],h=C[2*a+1];","while(l<h){","var m=(l+h)>>1,v=E[2*m+1];","if(v===b){return m}","if(b<v){h=m}else{l=m+1}","}","return l;","};","function getContour",t,"d(F,E,C,S){","var n=F.length,R=[];","for(var i=0;i<n;++i){var c=F[i],l=c.length;"],i=t+1;i>1;--i){t+1>i&&u.push("else "),u.push("if(l===",i,"){");
+for(var c=[],l=0;i>l;++l)c.push("(S[c["+l+"]]<<"+l+")");u.push("var M=",c.join("+"),";if(M===0||M===",(1<<i)-1,"){continue}switch(M){");for(var s=n[i-1],l=0;l<s.length;++l)u.push("case ",l,":"),e(s[l]),u.push("break;");u.push("}}")}u.push("}return R;};return getContour",t,"d");var h=new Function("pool",u.join(""));return h(a)}function i(t){var e=s[t];return e||(e=s[t]=n(t)),e}e.exports=i;var a=t("typedarray-pool"),o=t("marching-simplex-table"),s={}},{"marching-simplex-table":113,"typedarray-pool":233}],113:[function(t,e,r){"use strict";function n(t,e,r){for(var n=new Array(t),i=0;t>i;++i)n[i]=0,i===e&&(n[i]+=.5),i===r&&(n[i]+=.5);return n}function i(t,e){if(0===e||e===(1<<t+1)-1)return[];for(var r=[],i=[],a=0;t>=a;++a)if(e&1<<a){r.push(n(t,a-1,a-1)),i.push(null);for(var s=0;t>=s;++s)~e&1<<s&&(r.push(n(t,a-1,s-1)),i.push([a,s]))}var l=o(r),u=[];t:for(var a=0;a<l.length;++a){for(var c=l[a],h=[],s=0;s<c.length;++s){if(!i[c[s]])continue t;h.push(i[c[s]].slice())}u.push(h)}return u}function a(t){for(var e=1<<t+1,r=new Array(e),n=0;e>n;++n)r[n]=i(t,n);return r}e.exports=a;var o=t("convex-hull")},{"convex-hull":60}],114:[function(t,e,r){"use strict";function n(t){switch(t){case"uint8":return[l.mallocUint8,l.freeUint8];case"uint16":return[l.mallocUint16,l.freeUint16];case"uint32":return[l.mallocUint32,l.freeUint32];case"int8":return[l.mallocInt8,l.freeInt8];case"int16":return[l.mallocInt16,l.freeInt16];case"int32":return[l.mallocInt32,l.freeInt32];case"float32":return[l.mallocFloat,l.freeFloat];case"float64":return[l.mallocDouble,l.freeDouble];default:return null}}function i(t){for(var e=[],r=0;t>r;++r)e.push("s"+r);for(var r=0;t>r;++r)e.push("n"+r);for(var r=1;t>r;++r)e.push("d"+r);for(var r=1;t>r;++r)e.push("e"+r);for(var r=1;t>r;++r)e.push("f"+r);return e}function a(t,e){function r(t){return"generic"===e?["data.get(",t,")"].join(""):["data[",t,"]"].join("")}function a(t,r){return"generic"===e?["data.set(",t,",",r,")"].join(""):["data[",t,"]=",r].join("")}var o=["'use strict'"],s=["ndarrayInsertionSort",t.join("d"),e].join(""),l=["left","right","data","offset"].concat(i(t.length)),u=n(e),c=["i,j,cptr,ptr=left*s0+offset"];if(t.length>1){for(var h=[],f=1;f<t.length;++f)c.push("i"+f),h.push("n"+f);u?c.push("scratch=malloc("+h.join("*")+")"):c.push("scratch=new Array("+h.join("*")+")"),c.push("dptr","sptr","a","b")}else c.push("scratch");if(o.push(["function ",s,"(",l.join(","),"){var ",c.join(",")].join(""),"for(i=left+1;i<=right;++i){","j=i;ptr+=s0","cptr=ptr"),t.length>1){o.push("dptr=0;sptr=ptr");for(var f=t.length-1;f>=0;--f){var d=t[f];0!==d&&o.push(["for(i",d,"=0;i",d,"<n",d,";++i",d,"){"].join(""))}o.push("scratch[dptr++]=",r("sptr"));for(var f=0;f<t.length;++f){var d=t[f];0!==d&&o.push("sptr+=d"+d,"}")}o.push("__g:while(j-->left){","dptr=0","sptr=cptr-s0");for(var f=1;f<t.length;++f)1===f&&o.push("__l:"),o.push(["for(i",f,"=0;i",f,"<n",f,";++i",f,"){"].join(""));o.push(["a=",r("sptr"),"\nb=scratch[dptr]\nif(a<b){break __g}\nif(a>b){break __l}"].join(""));for(var f=t.length-1;f>=1;--f)o.push("sptr+=e"+f,"dptr+=f"+f,"}");o.push("dptr=cptr;sptr=cptr-s0");for(var f=t.length-1;f>=0;--f){var d=t[f];0!==d&&o.push(["for(i",d,"=0;i",d,"<n",d,";++i",d,"){"].join(""))}o.push(a("dptr",r("sptr")));for(var f=0;f<t.length;++f){var d=t[f];0!==d&&o.push(["dptr+=d",d,";sptr+=d",d].join(""),"}")}o.push("cptr-=s0\n}"),o.push("dptr=cptr;sptr=0");for(var f=t.length-1;f>=0;--f){var d=t[f];0!==d&&o.push(["for(i",d,"=0;i",d,"<n",d,";++i",d,"){"].join(""))}o.push(a("dptr","scratch[sptr++]"));for(var f=0;f<t.length;++f){var d=t[f];0!==d&&o.push("dptr+=d"+d,"}")}}else o.push("scratch="+r("ptr"),"while((j-->left)&&("+r("cptr-s0")+">scratch)){",a("cptr",r("cptr-s0")),"cptr-=s0","}",a("cptr","scratch"));if(o.push("}"),t.length>1&&u&&o.push("free(scratch)"),o.push("} return "+s),u){var p=new Function("malloc","free",o.join("\n"));return p(u[0],u[1])}var p=new Function(o.join("\n"));return p()}function o(t,e,r){function a(t){return["(offset+",t,"*s0)"].join("")}function o(t){return"generic"===e?["data.get(",t,")"].join(""):["data[",t,"]"].join("")}function s(t,r){return"generic"===e?["data.set(",t,",",r,")"].join(""):["data[",t,"]=",r].join("")}function l(e,r,n){if(1===e.length)_.push("ptr0="+a(e[0]));else for(var i=0;i<e.length;++i)_.push(["b_ptr",i,"=s0*",e[i]].join(""));r&&_.push("pivot_ptr=0"),_.push("ptr_shift=offset");for(var i=t.length-1;i>=0;--i){var o=t[i];0!==o&&_.push(["for(i",o,"=0;i",o,"<n",o,";++i",o,"){"].join(""))}if(e.length>1)for(var i=0;i<e.length;++i)_.push(["ptr",i,"=b_ptr",i,"+ptr_shift"].join(""));_.push(n),r&&_.push("++pivot_ptr");for(var i=0;i<t.length;++i){var o=t[i];0!==o&&(e.length>1?_.push("ptr_shift+=d"+o):_.push("ptr0+=d"+o),_.push("}"))}}function c(e,r,n,i){if(1===r.length)_.push("ptr0="+a(r[0]));else{for(var o=0;o<r.length;++o)_.push(["b_ptr",o,"=s0*",r[o]].join(""));_.push("ptr_shift=offset")}n&&_.push("pivot_ptr=0"),e&&_.push(e+":");for(var o=1;o<t.length;++o)_.push(["for(i",o,"=0;i",o,"<n",o,";++i",o,"){"].join(""));if(r.length>1)for(var o=0;o<r.length;++o)_.push(["ptr",o,"=b_ptr",o,"+ptr_shift"].join(""));_.push(i);for(var o=t.length-1;o>=1;--o)n&&_.push("pivot_ptr+=f"+o),r.length>1?_.push("ptr_shift+=e"+o):_.push("ptr0+=e"+o),_.push("}")}function h(){t.length>1&&k&&_.push("free(pivot1)","free(pivot2)")}function f(e,r){var n="el"+e,i="el"+r;if(t.length>1){var s="__l"+ ++M;c(s,[n,i],!1,["comp=",o("ptr0"),"-",o("ptr1"),"\n","if(comp>0){tmp0=",n,";",n,"=",i,";",i,"=tmp0;break ",s,"}\n","if(comp<0){break ",s,"}"].join(""))}else _.push(["if(",o(a(n)),">",o(a(i)),"){tmp0=",n,";",n,"=",i,";",i,"=tmp0}"].join(""))}function d(e,r){t.length>1?l([e,r],!1,s("ptr0",o("ptr1"))):_.push(s(a(e),o(a(r))))}function p(e,r,n){if(t.length>1){var i="__l"+ ++M;c(i,[r],!0,[e,"=",o("ptr0"),"-pivot",n,"[pivot_ptr]\n","if(",e,"!==0){break ",i,"}"].join(""))}else _.push([e,"=",o(a(r)),"-pivot",n].join(""))}function g(e,r){t.length>1?l([e,r],!1,["tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1","tmp")].join("")):_.push(["ptr0=",a(e),"\n","ptr1=",a(r),"\n","tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1","tmp")].join(""))}function v(e,r,n){t.length>1?(l([e,r,n],!1,["tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1",o("ptr2")),"\n",s("ptr2","tmp")].join("")),_.push("++"+r,"--"+n)):_.push(["ptr0=",a(e),"\n","ptr1=",a(r),"\n","ptr2=",a(n),"\n","++",r,"\n","--",n,"\n","tmp=",o("ptr0"),"\n",s("ptr0",o("ptr1")),"\n",s("ptr1",o("ptr2")),"\n",s("ptr2","tmp")].join(""))}function m(t,e){g(t,e),_.push("--"+e)}function y(e,r,n){t.length>1?l([e,r],!0,[s("ptr0",o("ptr1")),"\n",s("ptr1",["pivot",n,"[pivot_ptr]"].join(""))].join("")):_.push(s(a(e),o(a(r))),s(a(r),"pivot"+n))}function b(e,r){_.push(["if((",r,"-",e,")<=",u,"){\n","insertionSort(",e,",",r,",data,offset,",i(t.length).join(","),")\n","}else{\n",w,"(",e,",",r,",data,offset,",i(t.length).join(","),")\n","}"].join(""))}function x(e,r,n){t.length>1?(_.push(["__l",++M,":while(true){"].join("")),l([e],!0,["if(",o("ptr0"),"!==pivot",r,"[pivot_ptr]){break __l",M,"}"].join("")),_.push(n,"}")):_.push(["while(",o(a(e)),"===pivot",r,"){",n,"}"].join(""))}var _=["'use strict'"],w=["ndarrayQuickSort",t.join("d"),e].join(""),A=["left","right","data","offset"].concat(i(t.length)),k=n(e),M=0;_.push(["function ",w,"(",A.join(","),"){"].join(""));var T=["sixth=((right-left+1)/6)|0","index1=left+sixth","index5=right-sixth","index3=(left+right)>>1","index2=index3-sixth","index4=index3+sixth","el1=index1","el2=index2","el3=index3","el4=index4","el5=index5","less=left+1","great=right-1","pivots_are_equal=true","tmp","tmp0","x","y","z","k","ptr0","ptr1","ptr2","comp_pivot1=0","comp_pivot2=0","comp=0"];if(t.length>1){for(var E=[],L=1;L<t.length;++L)E.push("n"+L),T.push("i"+L);for(var L=0;8>L;++L)T.push("b_ptr"+L);T.push("ptr3","ptr4","ptr5","ptr6","ptr7","pivot_ptr","ptr_shift","elementSize="+E.join("*")),k?T.push("pivot1=malloc(elementSize)","pivot2=malloc(elementSize)"):T.push("pivot1=new Array(elementSize),pivot2=new Array(elementSize)")}else T.push("pivot1","pivot2");if(_.push("var "+T.join(",")),f(1,2),f(4,5),f(1,3),f(2,3),f(1,4),f(3,4),f(2,5),f(2,3),f(4,5),t.length>1?l(["el1","el2","el3","el4","el5","index1","index3","index5"],!0,["pivot1[pivot_ptr]=",o("ptr1"),"\n","pivot2[pivot_ptr]=",o("ptr3"),"\n","pivots_are_equal=pivots_are_equal&&(pivot1[pivot_ptr]===pivot2[pivot_ptr])\n","x=",o("ptr0"),"\n","y=",o("ptr2"),"\n","z=",o("ptr4"),"\n",s("ptr5","x"),"\n",s("ptr6","y"),"\n",s("ptr7","z")].join("")):_.push(["pivot1=",o(a("el2")),"\n","pivot2=",o(a("el4")),"\n","pivots_are_equal=pivot1===pivot2\n","x=",o(a("el1")),"\n","y=",o(a("el3")),"\n","z=",o(a("el5")),"\n",s(a("index1"),"x"),"\n",s(a("index3"),"y"),"\n",s(a("index5"),"z")].join("")),d("index2","left"),d("index4","right"),_.push("if(pivots_are_equal){"),_.push("for(k=less;k<=great;++k){"),p("comp","k",1),_.push("if(comp===0){continue}"),_.push("if(comp<0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),_.push("while(true){"),p("comp","great",1),_.push("if(comp>0){"),_.push("great--"),_.push("}else if(comp<0){"),v("k","less","great"),_.push("break"),_.push("}else{"),m("k","great"),_.push("break"),_.push("}"),_.push("}"),_.push("}"),_.push("}"),_.push("}else{"),_.push("for(k=less;k<=great;++k){"),p("comp_pivot1","k",1),_.push("if(comp_pivot1<0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),p("comp_pivot2","k",2),_.push("if(comp_pivot2>0){"),_.push("while(true){"),p("comp","great",2),_.push("if(comp>0){"),_.push("if(--great<k){break}"),_.push("continue"),_.push("}else{"),p("comp","great",1),_.push("if(comp<0){"),v("k","less","great"),_.push("}else{"),m("k","great"),_.push("}"),_.push("break"),_.push("}"),_.push("}"),_.push("}"),_.push("}"),_.push("}"),_.push("}"),y("left","(less-1)",1),y("right","(great+1)",2),b("left","(less-2)"),b("(great+2)","right"),_.push("if(pivots_are_equal){"),h(),_.push("return"),_.push("}"),_.push("if(less<index1&&great>index5){"),x("less",1,"++less"),x("great",2,"--great"),_.push("for(k=less;k<=great;++k){"),p("comp_pivot1","k",1),_.push("if(comp_pivot1===0){"),_.push("if(k!==less){"),g("k","less"),_.push("}"),_.push("++less"),_.push("}else{"),p("comp_pivot2","k",2),_.push("if(comp_pivot2===0){"),_.push("while(true){"),p("comp","great",2),_.push("if(comp===0){"),_.push("if(--great<k){break}"),_.push("continue"),_.push("}else{"),p("comp","great",1),_.push("if(comp<0){"),v("k","less","great"),_.push("}else{"),m("k","great"),_.push("}"),_.push("break"),_.push("}"),_.push("}"),_.push("}"),_.push("}"),_.push("}"),_.push("}"),h(),b("less","great"),_.push("}return "+w),t.length>1&&k){var S=new Function("insertionSort","malloc","free",_.join("\n"));return S(r,k[0],k[1])}var S=new Function("insertionSort",_.join("\n"));return S(r)}function s(t,e){var r=["'use strict'"],n=["ndarraySortWrapper",t.join("d"),e].join(""),s=["array"];r.push(["function ",n,"(",s.join(","),"){"].join(""));for(var l=["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"],c=0;c<t.length;++c)l.push(["s",c,"=stride[",c,"]|0,n",c,"=shape[",c,"]|0"].join(""));for(var h=new Array(t.length),f=[],c=0;c<t.length;++c){var d=t[c];0!==d&&(0===f.length?h[d]="1":h[d]=f.join("*"),f.push("n"+d))}for(var p=-1,g=-1,c=0;c<t.length;++c){var v=t[c];0!==v&&(p>0?l.push(["d",v,"=s",v,"-d",p,"*n",p].join("")):l.push(["d",v,"=s",v].join("")),p=v);var d=t.length-1-c;0!==d&&(g>0?l.push(["e",d,"=s",d,"-e",g,"*n",g,",f",d,"=",h[d],"-f",g,"*n",g].join("")):l.push(["e",d,"=s",d,",f",d,"=",h[d]].join("")),g=d)}r.push("var "+l.join(","));var m=["0","n0-1","data","offset"].concat(i(t.length));r.push(["if(n0<=",u,"){","insertionSort(",m.join(","),")}else{","quickSort(",m.join(","),")}"].join("")),r.push("}return "+n);var y=new Function("insertionSort","quickSort",r.join("\n")),b=a(t,e),x=o(t,e,b);return y(b,x)}var l=t("typedarray-pool"),u=32;e.exports=s},{"typedarray-pool":233}],115:[function(t,e,r){"use strict";function n(t){var e=t.order,r=t.dtype,n=[e,r],o=n.join(":"),s=a[o];return s||(a[o]=s=i(e,r)),s(t),t}var i=t("./lib/compile_sort.js"),a={};e.exports=n},{"./lib/compile_sort.js":114}],116:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r}function i(t){var e=t.gl,r=a(e,[0,0,0,1,1,0,1,1]),i=o(e,s.boxVert,s.lineFrag);return new n(t,r,i)}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("./shaders"),l=n.prototype;l.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},l.drawBox=function(){var t=[0,0],e=[0,0];return function(r,n,i,a,o){var s=this.plot,l=this.shader,u=s.gl;t[0]=r,t[1]=n,e[0]=i,e[1]=a,l.uniforms.lo=t,l.uniforms.hi=e,l.uniforms.color=o,u.drawArrays(u.TRIANGLE_STRIP,0,4)}}(),l.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":119,"gl-buffer":75,"gl-shader":154}],117:[function(t,e,r){"use strict";function n(t,e,r,n){this.plot=t,this.vbo=e,this.shader=r,this.tickShader=n,this.ticks=[[],[]]}function i(t,e){return t-e}function a(t){var e=t.gl,r=o(e),i=s(e,u.gridVert,u.gridFrag),a=s(e,u.tickVert,u.gridFrag),l=new n(t,r,i,a);return l}e.exports=a;var o=t("gl-buffer"),s=t("gl-shader"),l=t("binary-search-bounds"),u=t("./shaders"),c=n.prototype;c.draw=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){for(var n=this.plot,i=this.vbo,a=this.shader,o=this.ticks,s=n.gl,l=n._tickBounds,u=n.dataBox,c=n.viewBox,h=n.gridLineWidth,f=n.gridLineColor,d=n.gridLineEnable,p=n.pixelRatio,g=0;2>g;++g){var v=l[g],m=l[g+2],y=m-v,b=.5*(u[g+2]+u[g]),x=u[g+2]-u[g];e[g]=2*y/x,t[g]=2*(v-b)/x}a.bind(),i.bind(),a.attributes.dataCoord.pointer(),a.uniforms.dataShift=t,a.uniforms.dataScale=e;for(var _=0,g=0;2>g;++g){r[0]=r[1]=0,r[g]=1,a.uniforms.dataAxis=r,a.uniforms.lineWidth=h[g]/(c[g+2]-c[g])*p,a.uniforms.color=f[g];var w=6*o[g].length;d[g]&&s.drawArrays(s.TRIANGLES,_,w),_+=w}}}(),c.drawTickMarks=function(){var t=[0,0],e=[0,0],r=[1,0],n=[0,1],a=[0,0],o=[0,0];return function(){for(var s=this.plot,u=this.vbo,c=this.tickShader,h=this.ticks,f=s.gl,d=s._tickBounds,p=s.dataBox,g=s.viewBox,v=s.pixelRatio,m=s.screenBox,y=m[2]-m[0],b=m[3]-m[1],x=g[2]-g[0],_=g[3]-g[1],w=0;2>w;++w){var A=d[w],k=d[w+2],M=k-A,T=.5*(p[w+2]+p[w]),E=p[w+2]-p[w];e[w]=2*M/E,t[w]=2*(A-T)/E}e[0]*=x/y,t[0]*=x/y,e[1]*=_/b,t[1]*=_/b,c.bind(),u.bind(),c.attributes.dataCoord.pointer();var L=c.uniforms;L.dataShift=t,L.dataScale=e;var S=s.tickMarkLength,C=s.tickMarkWidth,P=s.tickMarkColor,z=0,R=6*h[0].length,O=Math.min(l.ge(h[0],(p[0]-d[0])/(d[2]-d[0]),i),h[0].length),I=Math.min(l.gt(h[0],(p[2]-d[0])/(d[2]-d[0]),i),h[0].length),j=z+6*O,N=6*Math.max(0,I-O),F=Math.min(l.ge(h[1],(p[1]-d[1])/(d[3]-d[1]),i),h[1].length),B=Math.min(l.gt(h[1],(p[3]-d[1])/(d[3]-d[1]),i),h[1].length),D=R+6*F,U=6*Math.max(0,B-F);a[0]=2*(g[0]-S[1])/y-1,a[1]=(g[3]+g[1])/b-1,o[0]=S[1]*v/y,o[1]=C[1]*v/b,L.color=P[1],L.tickScale=o,L.dataAxis=n,L.screenOffset=a,f.drawArrays(f.TRIANGLES,D,U),a[0]=(g[2]+g[0])/y-1,a[1]=2*(g[1]-S[0])/b-1,o[0]=C[0]*v/y,o[1]=S[0]*v/b,L.color=P[0],L.tickScale=o,L.dataAxis=r,L.screenOffset=a,f.drawArrays(f.TRIANGLES,j,N),a[0]=2*(g[2]+S[3])/y-1,a[1]=(g[3]+g[1])/b-1,o[0]=S[3]*v/y,o[1]=C[3]*v/b,L.color=P[3],L.tickScale=o,L.dataAxis=n,L.screenOffset=a,f.drawArrays(f.TRIANGLES,D,U),a[0]=(g[2]+g[0])/y-1,a[1]=2*(g[3]+S[2])/b-1,o[0]=C[2]*v/y,o[1]=S[2]*v/b,L.color=P[2],L.tickScale=o,L.dataAxis=r,L.screenOffset=a,f.drawArrays(f.TRIANGLES,j,N)}}(),c.update=function(){var t=[1,1,-1,-1,1,-1],e=[1,-1,1,1,-1,-1];return function(r){for(var n=r.ticks,i=r.bounds,a=new Float32Array(18*(n[0].length+n[1].length)),o=(this.plot.zeroLineEnable,0),s=[[],[]],l=0;2>l;++l)for(var u=s[l],c=n[l],h=i[l],f=i[l+2],d=0;d<c.length;++d){var p=(c[d].x-h)/(f-h);u.push(p);for(var g=0;6>g;++g)a[o++]=p,a[o++]=t[g],a[o++]=e[g]}this.ticks=s,this.vbo.update(a)}}(),c.dispose=function(){this.vbo.dispose(),this.shader.dispose(),this.tickShader.dispose()}},{"./shaders":119,"binary-search-bounds":121,"gl-buffer":75,"gl-shader":154}],118:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r}function i(t){var e=t.gl,r=a(e,[-1,-1,-1,1,1,-1,1,1]),i=o(e,s.lineVert,s.lineFrag),l=new n(t,r,i);return l}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("./shaders"),l=n.prototype;l.bind=function(){var t=this.shader;this.vbo.bind(),this.shader.bind(),t.attributes.coord.pointer(),t.uniforms.screenBox=this.plot.screenBox},l.drawLine=function(){var t=[0,0],e=[0,0];return function(r,n,i,a,o,s){var l=this.plot,u=this.shader,c=l.gl;t[0]=r,t[1]=n,e[0]=i,e[1]=a,u.uniforms.start=t,u.uniforms.end=e,u.uniforms.width=o*l.pixelRatio,u.uniforms.color=s,c.drawArrays(c.TRIANGLE_STRIP,0,4)}}(),l.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":119,"gl-buffer":75,"gl-shader":154}],119:[function(t,e,r){"use strict";var n="#define GLSLIFY 1\nprecision lowp float;\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = vec4(color.xyz * color.w, color.w);\n}\n";e.exports={lineVert:"#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 start, end;\nuniform float width;\n\nvec2 perp(vec2 v) {\n  return vec2(v.y, -v.x);\n}\n\nvec2 screen(vec2 v) {\n  return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n  vec2 delta = normalize(perp(start - end));\n  vec2 offset = mix(start, end, 0.5 * (coord.y+1.0));\n  gl_Position = vec4(screen(offset + 0.5 * width * delta * coord.x), 0, 1);\n}\n",lineFrag:n,textVert:"#define GLSLIFY 1\nattribute vec3 textCoordinate;\n\nuniform vec2 dataScale, dataShift, dataAxis, screenOffset, textScale;\nuniform float angle;\n\nvoid main() {\n  float dataOffset  = textCoordinate.z;\n  vec2 glyphOffset  = textCoordinate.xy;\n  mat2 glyphMatrix = mat2(cos(angle), sin(angle), -sin(angle), cos(angle));\n  vec2 screenCoordinate = dataAxis * (dataScale * dataOffset + dataShift) +\n    glyphMatrix * glyphOffset * textScale + screenOffset;\n  gl_Position = vec4(screenCoordinate, 0, 1);\n}\n",textFrag:n,gridVert:"#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale;\nuniform float lineWidth;\n\nvoid main() {\n  vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n  pos += 10.0 * dataCoord.y * vec2(dataAxis.y, -dataAxis.x) + dataCoord.z * lineWidth;\n  gl_Position = vec4(pos, 0, 1);\n}\n",gridFrag:n,boxVert:"#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 coord;\n\nuniform vec4 screenBox;\nuniform vec2 lo, hi;\n\nvec2 screen(vec2 v) {\n  return 2.0 * (v - screenBox.xy) / (screenBox.zw - screenBox.xy) - 1.0;\n}\n\nvoid main() {\n  gl_Position = vec4(screen(mix(lo, hi, coord)), 0, 1);\n}\n",tickVert:"#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 dataCoord;\n\nuniform vec2 dataAxis, dataShift, dataScale, screenOffset, tickScale;\n\nvoid main() {\n  vec2 pos = dataAxis * (dataScale * dataCoord.x + dataShift);\n  gl_Position = vec4(pos + tickScale*dataCoord.yz + screenOffset, 0, 1);\n}\n"}},{}],120:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.vbo=e,this.shader=r,this.tickOffset=[[],[]],this.tickX=[[],[]],this.labelOffset=[0,0],this.labelCount=[0,0]}function i(t){var e=t.gl,r=a(e),i=o(e,u.textVert,u.textFrag),s=new n(t,r,i);return s}e.exports=i;var a=t("gl-buffer"),o=t("gl-shader"),s=t("text-cache"),l=t("binary-search-bounds"),u=t("./shaders"),c=n.prototype;c.drawTicks=function(){var t=[0,0],e=[0,0],r=[0,0];return function(n){var i=this.plot,a=this.shader,o=this.tickX[n],s=this.tickOffset[n],u=i.gl,c=i.viewBox,h=i.dataBox,f=i.screenBox,d=i.pixelRatio,p=i.tickEnable,g=i.tickPad,v=i.tickColor,m=i.tickAngle,y=(i.tickMarkLength,i.labelEnable),b=i.labelPad,x=i.labelColor,_=i.labelAngle,w=this.labelOffset[n],A=this.labelCount[n],k=l.lt(o,h[n]),M=l.le(o,h[n+2]);t[0]=t[1]=0,t[n]=1,e[n]=(c[2+n]+c[n])/(f[2+n]-f[n])-1;var T=2/f[2+(1^n)]-f[1^n];e[1^n]=T*c[1^n]-1,p[n]&&(e[1^n]-=T*d*g[n],M>k&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=v[n],a.uniforms.angle=m[n],u.drawArrays(u.TRIANGLES,s[k],s[M]-s[k]))),y[n]&&(e[1^n]-=T*d*b[n],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n],a.uniforms.angle=_[n],u.drawArrays(u.TRIANGLES,w,A)),e[1^n]=T*c[2+(1^n)]-1,p[n+2]&&(e[1^n]+=T*d*g[n+2],M>k&&(a.uniforms.dataAxis=t,a.uniforms.screenOffset=e,a.uniforms.color=v[n+2],a.uniforms.angle=m[n+2],u.drawArrays(u.TRIANGLES,s[k],s[M]-s[k]))),y[n+2]&&(e[1^n]+=T*d*b[n+2],a.uniforms.dataAxis=r,a.uniforms.screenOffset=e,a.uniforms.color=x[n+2],a.uniforms.angle=_[n+2],u.drawArrays(u.TRIANGLES,w,A))}}(),c.drawTitle=function(){var t=[0,0],e=[0,0];return function(){for(var r=this.plot,n=this.shader,i=r.gl,a=r.screenBox,o=r.titleCenter,s=r.titleAngle,l=r.titleColor,o=r.titleCenter,u=r.pixelRatio,c=0;2>c;++c)e[c]=2*(o[c]*u-a[c])/(a[2+c]-a[c])-1;n.bind(),n.uniforms.dataAxis=t,n.uniforms.screenOffset=e,n.uniforms.angle=s,n.uniforms.color=l,i.drawArrays(i.TRIANGLES,this.titleOffset,this.titleCount)}}(),c.bind=function(){var t=[0,0],e=[0,0],r=[0,0];return function(){var n=this.plot,i=this.shader,a=n._tickBounds,o=n.dataBox,s=n.screenBox,l=n.viewBox;i.bind();for(var u=0;2>u;++u){var c=a[u],h=a[u+2],f=h-c,d=.5*(o[u+2]+o[u]),p=o[u+2]-o[u],g=l[u],v=l[u+2],m=v-g,y=s[u],b=s[u+2],x=b-y;e[u]=2*f/p*m/x,t[u]=2*(c-d)/p*m/x}r[1]=2*n.pixelRatio/(s[3]-s[1]),r[0]=r[1]*(s[3]-s[1])/(s[2]-s[0]),i.uniforms.dataScale=e,i.uniforms.dataShift=t,i.uniforms.textScale=r,this.vbo.bind(),i.attributes.textCoordinate.pointer()}}(),c.update=function(t){for(var e=[],r=t.ticks,n=t.bounds,i=0;2>i;++i){for(var a=[Math.floor(e.length/3)],o=[-(1/0)],l=r[i],u=0;u<l.length;++u){for(var c=l[u],h=c.x,f=c.text,d=c.font||"sans-serif",p=c.fontSize||12,g=s(d,f).data,v=1/(n[i+2]-n[i]),m=n[i],y=0;y<g.length;y+=2)e.push(g[y]*p,-g[y+1]*p,(h-m)*v);a.push(Math.floor(e.length/3)),o.push(h)}this.tickOffset[i]=a,this.tickX[i]=o}for(var i=0;2>i;++i){this.labelOffset[i]=Math.floor(e.length/3);for(var g=s(t.labelFont[i],t.labels[i]).data,p=t.labelSize[i],u=0;u<g.length;u+=2)e.push(g[u]*p,-g[u+1]*p,0);this.labelCount[i]=Math.floor(e.length/3)-this.labelOffset[i]}this.titleOffset=Math.floor(e.length/3);for(var g=s(t.titleFont,t.title).data,p=t.titleSize,u=0;u<g.length;u+=2)e.push(g[u]*p,-g[u+1]*p,0);this.titleCount=Math.floor(e.length/3)-this.titleOffset,this.vbo.update(e)},c.dispose=function(){this.vbo.dispose(),this.shader.dispose()}},{"./shaders":119,"binary-search-bounds":121,"gl-buffer":75,"gl-shader":154,"text-cache":228}],121:[function(t,e,r){"use strict";function n(t,e,r,n,i){var a=["function ",t,"(a,l,h,",n.join(","),"){",i?"":"var i=",r?"l-1":"h+1",";while(l<=h){var m=(l+h)>>>1,x=a[m]"];return i?e.indexOf("c")<0?a.push(";if(x===y){return m}else if(x<=y){"):a.push(";var p=c(x,y);if(p===0){return m}else if(p<=0){"):a.push(";if(",e,"){i=m;"),r?a.push("l=m+1}else{h=m-1}"):a.push("h=m-1}else{l=m+1}"),a.push("}"),i?a.push("return -1};"):a.push("return i};"),a.join("")}function i(t,e,r,i){var a=new Function([n("A","x"+t+"y",e,["y"],i),n("P","c(x,y)"+t+"0",e,["y","c"],i),"function dispatchBsearch",r,"(a,y,c,l,h){if(typeof(c)==='function'){return P(a,(l===void 0)?0:l|0,(h===void 0)?a.length-1:h|0,y,c)}else{return A(a,(c===void 0)?0:c|0,(l===void 0)?a.length-1:l|0,y)}}return dispatchBsearch",r].join(""));return a()}e.exports={ge:i(">=",!1,"GE"),gt:i(">",!1,"GT"),lt:i("<",!0,"LT"),le:i("<=",!0,"LE"),eq:i("-",!0,"EQ",!0)}},{}],122:[function(t,e,r){"use strict";function n(t,e){this.gl=t,this.pickBuffer=e,this.screenBox=[0,0,t.drawingBufferWidth,t.drawingBufferHeight],this.viewBox=[0,0,0,0],this.dataBox=[-10,-10,10,10],this.gridLineEnable=[!0,!0],this.gridLineWidth=[1,1],this.gridLineColor=[[0,0,0,1],[0,0,0,1]],this.pixelRatio=1,this.tickMarkLength=[0,0,0,0],this.tickMarkWidth=[0,0,0,0],this.tickMarkColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickPad=[15,15,15,15],this.tickAngle=[0,0,0,0],this.tickEnable=[!0,!0,!0,!0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[15,15,15,15],this.labelAngle=[0,Math.PI/2,0,3*Math.PI/2],this.labelEnable=[!0,!0,!0,!0],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.titleCenter=[0,0],this.titleEnable=!0,this.titleAngle=0,this.titleColor=[0,0,0,1],this.borderColor=[0,0,0,0],this.backgroundColor=[0,0,0,0],this.zeroLineEnable=[!0,!0],this.zeroLineWidth=[4,4],this.zeroLineColor=[[0,0,0,1],[0,0,0,1]],this.borderLineEnable=[!0,!0,!0,!0],this.borderLineWidth=[2,2,2,2],this.borderLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.grid=null,this.text=null,this.line=null,this.box=null,this.objects=[],this.overlays=[],this._tickBounds=[1/0,1/0,-(1/0),-(1/0)],this.dirty=!1,this.pickDirty=!1,this.pickDelay=120,this.pickRadius=10,this._pickTimeout=null,this._drawPick=this.drawPick.bind(this),this._depthCounter=0}function i(t){for(var e=t.slice(),r=0;r<e.length;++r)e[r]=e[r].slice();return e}function a(t,e){return t.x-e.x}function o(t){var e=t.gl,r=s(e,[e.drawingBufferWidth,e.drawingBufferHeight]),i=new n(e,r);return i.grid=l(i),i.text=u(i),i.line=c(i),i.box=h(i),i.update(t),i}e.exports=o;var s=t("gl-select-static"),l=t("./lib/grid"),u=t("./lib/text"),c=t("./lib/line"),h=t("./lib/box"),f=n.prototype;f.setDirty=function(){this.dirty=this.pickDirty=!0},f.setOverlayDirty=function(){this.dirty=!0},f.nextDepthValue=function(){return this._depthCounter++/65536},f.draw=function(){return function(){var t=this.gl,e=this.screenBox,r=this.viewBox,n=this.dataBox,i=this.pixelRatio,a=this.grid,o=this.line,s=this.text,l=this.objects;if(this._depthCounter=0,this.pickDirty&&(this._pickTimeout&&clearTimeout(this._pickTimeout),this.pickDirty=!1,this._pickTimeout=setTimeout(this._drawPick,this.pickDelay)),this.dirty){this.dirty=!1,t.bindFramebuffer(t.FRAMEBUFFER,null),t.enable(t.SCISSOR_TEST),t.disable(t.DEPTH_TEST),t.depthFunc(t.LESS),t.depthMask(!1),t.enable(t.BLEND),t.blendEquation(t.FUNC_ADD,t.FUNC_ADD),t.blendFunc(t.ONE,t.ONE_MINUS_SRC_ALPHA),t.scissor(e[0],e[1],e[2]-e[0],e[3]-e[1]);var u=this.borderColor;t.clearColor(u[0]*u[3],u[1]*u[3],u[2]*u[3],u[3]),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT),t.scissor(r[0],r[1],r[2]-r[0],r[3]-r[1]),t.viewport(r[0],r[1],r[2]-r[0],r[3]-r[1]);var c=this.backgroundColor;t.clearColor(c[0]*c[3],c[1]*c[3],c[2]*c[3],c[3]),t.clear(t.COLOR_BUFFER_BIT),a.draw();var h=this.zeroLineEnable,f=this.zeroLineColor,d=this.zeroLineWidth;if(h[0]||h[1]){o.bind();for(var p=0;2>p;++p)if(h[p]&&n[p]<=0&&n[p+2]>=0){var g=e[p]-n[p]*(e[p+2]-e[p])/(n[p+2]-n[p]);0===p?o.drawLine(g,e[1],g,e[3],d[p],f[p]):o.drawLine(e[0],g,e[2],g,d[p],f[p])}}for(var p=0;p<l.length;++p)l[p].draw();t.viewport(e[0],e[1],e[2]-e[0],e[3]-e[1]),t.scissor(e[0],e[1],e[2]-e[0],e[3]-e[1]),this.grid.drawTickMarks(),o.bind();var v=this.borderLineEnable,m=this.borderLineWidth,y=this.borderLineColor;v[1]&&o.drawLine(r[0],r[1]-.5*m[1]*i,r[0],r[3]+.5*m[3]*i,m[1],y[1]),v[0]&&o.drawLine(r[0]-.5*m[0]*i,r[1],r[2]+.5*m[2]*i,r[1],m[0],y[0]),v[3]&&o.drawLine(r[2],r[1]-.5*m[1]*i,r[2],r[3]+.5*m[3]*i,m[3],y[3]),v[2]&&o.drawLine(r[0]-.5*m[0]*i,r[3],r[2]+.5*m[2]*i,r[3],m[2],y[2]),s.bind();for(var p=0;2>p;++p)s.drawTicks(p);this.titleEnable&&s.drawTitle();for(var b=this.overlays,p=0;p<b.length;++p)b[p].draw();t.disable(t.SCISSOR_TEST),t.disable(t.BLEND),t.depthMask(!0)}}}(),f.drawPick=function(){return function(){var t=this.pickBuffer;this.gl;this._pickTimeout=null,t.begin();for(var e=1,r=this.objects,n=0;n<r.length;++n)e=r[n].drawPick(e);t.end()}}(),f.pick=function(){return function(t,e){var r=this.pixelRatio,n=this.pickPixelRatio,i=this.viewBox,a=0|Math.round((t-i[0]/r)*n),o=0|Math.round((e-i[1]/r)*n),s=this.pickBuffer.query(a,o,this.pickRadius);if(!s)return null;for(var l=s.id+(s.value[0]<<8)+(s.value[1]<<16)+(s.value[2]<<24),u=this.objects,c=0;c<u.length;++c){var h=u[c].pick(a,o,l);if(h)return h}return null}}(),f.setScreenBox=function(t){var e=this.screenBox,r=this.pixelRatio;e[0]=0|Math.round(t[0]*r),e[1]=0|Math.round(t[1]*r),e[2]=0|Math.round(t[2]*r),e[3]=0|Math.round(t[3]*r),this.setDirty()},f.setDataBox=function(t){var e=this.dataBox,r=e[0]!==t[0]||e[1]!==t[1]||e[2]!==t[2]||e[3]!==t[3];r&&(e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],this.setDirty())},f.setViewBox=function(t){var e=this.pixelRatio,r=this.viewBox;r[0]=0|Math.round(t[0]*e),r[1]=0|Math.round(t[1]*e),r[2]=0|Math.round(t[2]*e),r[3]=0|Math.round(t[3]*e);var n=this.pickPixelRatio;this.pickBuffer.shape=[0|Math.round((t[2]-t[0])*n),0|Math.round((t[3]-t[1])*n)],this.setDirty()},f.update=function(t){t=t||{};var e=this.gl;this.pixelRatio=t.pixelRatio||1;var r=this.pixelRatio;this.pickPixelRatio=Math.max(r,1),this.setScreenBox(t.screenBox||[0,0,e.drawingBufferWidth/r,e.drawingBufferHeight/r]);this.screenBox;this.setViewBox(t.viewBox||[.125*(this.screenBox[2]-this.screenBox[0])/r,.125*(this.screenBox[3]-this.screenBox[1])/r,.875*(this.screenBox[2]-this.screenBox[0])/r,.875*(this.screenBox[3]-this.screenBox[1])/r]);var n=this.viewBox,o=(n[2]-n[0])/(n[3]-n[1]);this.setDataBox(t.dataBox||[-10,-10/o,10,10/o]),this.borderColor=(t.borderColor||[0,0,0,0]).slice(),this.backgroundColor=(t.backgroundColor||[0,0,0,0]).slice(),this.gridLineEnable=(t.gridLineEnable||[!0,!0]).slice(),this.gridLineWidth=(t.gridLineWidth||[1,1]).slice(),this.gridLineColor=i(t.gridLineColor||[[.5,.5,.5,1],[.5,.5,.5,1]]),this.zeroLineEnable=(t.zeroLineEnable||[!0,!0]).slice(),this.zeroLineWidth=(t.zeroLineWidth||[4,4]).slice(),this.zeroLineColor=i(t.zeroLineColor||[[0,0,0,1],[0,0,0,1]]),this.tickMarkLength=(t.tickMarkLength||[0,0,0,0]).slice(),this.tickMarkWidth=(t.tickMarkWidth||[0,0,0,0]).slice(),this.tickMarkColor=i(t.tickMarkColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]),this.titleCenter=(t.titleCenter||[.5*(n[0]+n[2])/r,(n[3]+120)/r]).slice(),this.titleEnable=!("titleEnable"in t&&!t.titleEnable),this.titleAngle=t.titleAngle||0,this.titleColor=(t.titleColor||[0,0,0,1]).slice(),this.labelPad=(t.labelPad||[15,15,15,15]).slice(),this.labelAngle=(t.labelAngle||[0,Math.PI/2,0,3*Math.PI/2]).slice(),this.labelEnable=(t.labelEnable||[!0,!0,!0,!0]).slice(),this.labelColor=i(t.labelColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]),this.tickPad=(t.tickPad||[15,15,15,15]).slice(),this.tickAngle=(t.tickAngle||[0,0,0,0]).slice(),this.tickEnable=(t.tickEnable||[!0,!0,!0,!0]).slice(),this.tickColor=i(t.tickColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]),this.borderLineEnable=(t.borderLineEnable||[!0,!0,!0,!0]).slice(),this.borderLineWidth=(t.borderLineWidth||[2,2,2,2]).slice(),this.borderLineColor=i(t.borderLineColor||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]);var s=t.ticks||[[],[]],l=this._tickBounds;l[0]=l[1]=1/0,l[2]=l[3]=-(1/0);for(var u=0;2>u;++u){var c=s[u].slice(0);0!==c.length&&(c.sort(a),l[u]=Math.min(l[u],c[0].x),l[u+2]=Math.max(l[u+2],c[c.length-1].x))}this.grid.update({bounds:l,ticks:s}),this.text.update({bounds:l,ticks:s,labels:t.labels||["x","y"],labelSize:t.labelSize||[12,12],labelFont:t.labelFont||["sans-serif","sans-serif"],title:t.title||"",titleSize:t.titleSize||18,titleFont:t.titleFont||"sans-serif"}),this.setDirty()},f.dispose=function(){this.box.dispose(),this.grid.dispose(),this.text.dispose(),this.line.dispose();for(var t=this.objects.length-1;t>=0;--t)this.objects[t].dispose();this.objects.length=0;for(var t=this.overlays.length-1;t>=0;--t)this.overlays[t].dispose();this.overlays.length=0,this.gl=null},f.addObject=function(t){this.objects.indexOf(t)<0&&(this.objects.push(t),this.setDirty())},f.removeObject=function(t){for(var e=this.objects,r=0;r<e.length;++r)if(e[r]===t){e.splice(r,1),this.setDirty();break}},f.addOverlay=function(t){this.overlays.indexOf(t)<0&&(this.overlays.push(t),this.setOverlayDirty())},f.removeOverlay=function(t){for(var e=this.overlays,r=0;r<e.length;++r)if(e[r]===t){e.splice(r,1),this.setOverlayDirty();break}}},{"./lib/box":116,"./lib/grid":117,"./lib/line":118,"./lib/text":120,"gl-select-static":153}],123:[function(t,e,r){var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\nattribute vec2 position;\nvarying vec2 uv;\nvoid main() {\n  uv = position;\n  gl_Position = vec4(position, 0, 1);\n}",a="precision mediump float;\n#define GLSLIFY 1\n\nuniform sampler2D accumBuffer;\nvarying vec2 uv;\n\nvoid main() {\n  vec4 accum = texture2D(accumBuffer, 0.5 * (uv + 1.0));\n  gl_FragColor = min(vec4(1,1,1,1), accum);\n}";
+e.exports=function(t){return n(t,i,a,null,[{name:"position",type:"vec2"}])}},{"gl-shader":154}],124:[function(t,e,r){"use strict";function n(t,e){t=t||document.body,e=e||{};var r=[.01,1/0];"distanceLimits"in e&&(r[0]=e.distanceLimits[0],r[1]=e.distanceLimits[1]),"zoomMin"in e&&(r[0]=e.zoomMin),"zoomMax"in e&&(r[1]=e.zoomMax);var n=a({center:e.center||[0,0,0],up:e.up||[0,1,0],eye:e.eye||[0,0,10],mode:e.mode||"orbit",distanceLimits:r}),l=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],u=0,c=t.clientWidth,h=t.clientHeight,f={view:n,element:t,delay:e.delay||16,rotateSpeed:e.rotateSpeed||1,zoomSpeed:e.zoomSpeed||1,translateSpeed:e.translateSpeed||1,flipX:!!e.flipX,flipY:!!e.flipY,modes:n.modes,tick:function(){var e=i(),r=this.delay;n.idle(e-r),n.flush(e-(100+2*r));var a=e-2*r;n.recalcMatrix(a);for(var o=!0,s=n.computedMatrix,f=0;16>f;++f)o=o&&l[f]===s[f],l[f]=s[f];var d=t.clientWidth===c&&t.clientHeight===h;return c=t.clientWidth,h=t.clientHeight,o?!d:(u=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(f,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){return n.setMode(t),n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return u},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var d=0,p=0;return o(t,function(e,r,a,o){var s=1/t.clientHeight,l=s*(r-d),c=s*(a-p),h=f.flipX?1:-1,g=f.flipY?1:-1,v=Math.PI*f.rotateSpeed,m=i();if(1&e)o.shift?n.rotate(m,0,0,-l*v):n.rotate(m,h*v*l,-g*v*c,0);else if(2&e)n.pan(m,-f.translateSpeed*l*u,f.translateSpeed*c*u,0);else if(4&e){var y=f.zoomSpeed*c/window.innerHeight*(m-n.lastT())*50;n.pan(m,0,0,u*(Math.exp(y)-1))}d=r,p=a}),s(t,function(t,e,r){var a=f.flipX?1:-1,o=f.flipY?1:-1,s=i();if(Math.abs(t)>Math.abs(e))n.rotate(s,0,0,-t*a*Math.PI*f.rotateSpeed/window.innerWidth);else{var l=f.zoomSpeed*o*e/window.innerHeight*(s-n.lastT())/100;n.pan(s,0,0,u*(Math.exp(l)-1))}},!0),f}e.exports=n;var i=t("right-now"),a=t("3d-view"),o=t("mouse-change"),s=t("mouse-wheel")},{"3d-view":38,"mouse-change":196,"mouse-wheel":200,"right-now":210}],125:[function(t,e,r){!function(){"use strict";function t(e){e.permitHostObjects___&&e.permitHostObjects___(t)}function r(t){return!(t.substr(0,d.length)==d&&"___"===t.substr(t.length-3))}function n(t){if(t!==Object(t))throw new TypeError("Not an object: "+t);var e=t[p];if(e&&e.key===t)return e;if(f(t)){e={key:t};try{return h(t,p,{value:e,writable:!1,enumerable:!1,configurable:!1}),e}catch(r){return}}}function i(t){return t.prototype=null,Object.freeze(t)}function a(){y||"undefined"==typeof console||(y=!0,console.warn("WeakMap should be invoked as new WeakMap(), not WeakMap(). This will be an error in the future."))}if("undefined"==typeof ses||!ses.ok||ses.ok()){"undefined"!=typeof ses&&(ses.weakMapPermitHostObjects=t);var o=!1;if("function"==typeof WeakMap){var s=WeakMap;if("undefined"!=typeof navigator&&/Firefox/.test(navigator.userAgent));else{var l=new s,u=Object.freeze({});if(l.set(u,1),1===l.get(u))return void(e.exports=WeakMap);o=!0}}var c=(Object.prototype.hasOwnProperty,Object.getOwnPropertyNames),h=Object.defineProperty,f=Object.isExtensible,d="weakmap:",p=d+"ident:"+Math.random()+"___";if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues&&"function"==typeof ArrayBuffer&&"function"==typeof Uint8Array){var g=new ArrayBuffer(25),v=new Uint8Array(g);crypto.getRandomValues(v),p=d+"rand:"+Array.prototype.map.call(v,function(t){return(t%36).toString(36)}).join("")+"___"}if(h(Object,"getOwnPropertyNames",{value:function(t){return c(t).filter(r)}}),"getPropertyNames"in Object){var m=Object.getPropertyNames;h(Object,"getPropertyNames",{value:function(t){return m(t).filter(r)}})}!function(){var t=Object.freeze;h(Object,"freeze",{value:function(e){return n(e),t(e)}});var e=Object.seal;h(Object,"seal",{value:function(t){return n(t),e(t)}});var r=Object.preventExtensions;h(Object,"preventExtensions",{value:function(t){return n(t),r(t)}})}();var y=!1,b=0,x=function(){function t(t,e){var r,i=n(t);return i?u in i?i[u]:e:(r=s.indexOf(t),r>=0?l[r]:e)}function e(t){var e=n(t);return e?u in e:s.indexOf(t)>=0}function r(t,e){var r,i=n(t);return i?i[u]=e:(r=s.indexOf(t),r>=0?l[r]=e:(r=s.length,l[r]=e,s[r]=t)),this}function o(t){var e,r,i=n(t);return i?u in i&&delete i[u]:(e=s.indexOf(t),0>e?!1:(r=s.length-1,s[e]=void 0,l[e]=l[r],s[e]=s[r],s.length=r,l.length=r,!0))}this instanceof x||a();var s=[],l=[],u=b++;return Object.create(x.prototype,{get___:{value:i(t)},has___:{value:i(e)},set___:{value:i(r)},delete___:{value:i(o)}})};x.prototype=Object.create(Object.prototype,{get:{value:function(t,e){return this.get___(t,e)},writable:!0,configurable:!0},has:{value:function(t){return this.has___(t)},writable:!0,configurable:!0},set:{value:function(t,e){return this.set___(t,e)},writable:!0,configurable:!0},"delete":{value:function(t){return this.delete___(t)},writable:!0,configurable:!0}}),"function"==typeof s?!function(){function r(){function e(t,e){return c?u.has(t)?u.get(t):c.get___(t,e):u.get(t,e)}function r(t){return u.has(t)||(c?c.has___(t):!1)}function n(t){var e=!!u.delete(t);return c?c.delete___(t)||e:e}this instanceof x||a();var l,u=new s,c=void 0,h=!1;return l=o?function(t,e){return u.set(t,e),u.has(t)||(c||(c=new x),c.set(t,e)),this}:function(t,e){if(h)try{u.set(t,e)}catch(r){c||(c=new x),c.set___(t,e)}else u.set(t,e);return this},Object.create(x.prototype,{get___:{value:i(e)},has___:{value:i(r)},set___:{value:i(l)},delete___:{value:i(n)},permitHostObjects___:{value:i(function(e){if(e!==t)throw new Error("bogus call to permitHostObjects___");h=!0})}})}o&&"undefined"!=typeof Proxy&&(Proxy=void 0),r.prototype=x.prototype,e.exports=r,Object.defineProperty(WeakMap.prototype,"constructor",{value:WeakMap,enumerable:!1,configurable:!0,writable:!0})}():("undefined"!=typeof Proxy&&(Proxy=void 0),e.exports=x)}}()},{}],126:[function(t,e,r){"use strict";function n(t){var e=s.get(t);if(!e||!t.isBuffer(e._triangleBuffer.buffer)){var r=a(t,new Float32Array([-1,-1,-1,4,4,-1]));e=o(t,[{buffer:r,type:t.FLOAT,size:2}]),e._triangleBuffer=r,s.set(t,e)}e.bind(),t.drawArrays(t.TRIANGLES,0,3),e.unbind()}var i="undefined"==typeof WeakMap?t("weak-map"):WeakMap,a=t("gl-buffer"),o=t("gl-vao"),s=new i;e.exports=n},{"gl-buffer":75,"gl-vao":189,"weak-map":125}],127:[function(t,e,r){"use strict";function n(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function i(t){this.gl=t,this.pixelRatio=1,this.bounds=[[-10,-10,-10],[10,10,10]],this.ticks=[[],[],[]],this.autoTicks=!0,this.tickSpacing=[1,1,1],this.tickEnable=[!0,!0,!0],this.tickFont=["sans-serif","sans-serif","sans-serif"],this.tickSize=[12,12,12],this.tickAngle=[0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickPad=[10,10,10],this.lastCubeProps={cubeEdges:[0,0,0],axis:[0,0,0]},this.labels=["x","y","z"],this.labelEnable=[!0,!0,!0],this.labelFont="sans-serif",this.labelSize=[20,20,20],this.labelAngle=[0,0,0],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[10,10,10],this.lineEnable=[!0,!0,!0],this.lineMirror=[!1,!1,!1],this.lineWidth=[1,1,1],this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.lineTickEnable=[!0,!0,!0],this.lineTickMirror=[!1,!1,!1],this.lineTickLength=[0,0,0],this.lineTickWidth=[1,1,1],this.lineTickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.gridEnable=[!0,!0,!0],this.gridWidth=[1,1,1],this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroEnable=[!0,!0,!0],this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroLineWidth=[2,2,2],this.backgroundEnable=[!1,!1,!1],this.backgroundColor=[[.8,.8,.8,.5],[.8,.8,.8,.5],[.8,.8,.8,.5]],this._firstInit=!0,this._text=null,this._lines=null,this._background=c(t)}function a(){this.primalOffset=[0,0,0],this.primalMinor=[0,0,0],this.mirrorOffset=[0,0,0],this.mirrorMinor=[0,0,0]}function o(t,e,r,n,i){for(var a=t.primalOffset,o=t.primalMinor,s=t.mirrorOffset,l=t.mirrorMinor,u=n[e],c=0;3>c;++c)if(e!==c){var h=a,f=s,d=o,p=l;u&1<<c&&(h=s,f=a,d=l,p=o),h[c]=r[0][c],f[c]=r[1][c],i[c]>0?(d[c]=-1,p[c]=0):(d[c]=0,p[c]=1)}}function s(t,e){var r=new i(t);return r.update(e),r}e.exports=s;var l=t("./lib/text.js"),u=t("./lib/lines.js"),c=t("./lib/background.js"),h=t("./lib/cube.js"),f=t("./lib/ticks.js"),d=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),p=i.prototype;p.update=function(t){function e(e,r,n){if(n in t){var i,a=t[n],o=this[n];(e?Array.isArray(a)&&Array.isArray(a[0]):Array.isArray(a))?this[n]=i=[r(a[0]),r(a[1]),r(a[2])]:this[n]=i=[r(a),r(a),r(a)];for(var s=0;3>s;++s)if(i[s]!==o[s])return!0}return!1}t=t||{};var r,n=e.bind(this,!1,Number),i=e.bind(this,!1,Boolean),a=e.bind(this,!1,String),o=e.bind(this,!0,function(t){if(Array.isArray(t)){if(3===t.length)return[+t[0],+t[1],+t[2],1];if(4===t.length)return[+t[0],+t[1],+t[2],+t[3]]}return[0,0,0,1]}),s=!1,c=!1;if("bounds"in t)for(var h=t.bounds,d=0;2>d;++d)for(var p=0;3>p;++p)h[d][p]!==this.bounds[d][p]&&(c=!0),this.bounds[d][p]=h[d][p];if("ticks"in t){r=t.ticks,s=!0,this.autoTicks=!1;for(var d=0;3>d;++d)this.tickSpacing[d]=0}else n("tickSpacing")&&(this.autoTicks=!0,c=!0);if(this._firstInit&&("ticks"in t||"tickSpacing"in t||(this.autoTicks=!0),c=!0,s=!0,this._firstInit=!1),c&&this.autoTicks&&(r=f.create(this.bounds,this.tickSpacing),s=!0),s){for(var d=0;3>d;++d)r[d].sort(function(t,e){return t.x-e.x});f.equal(r,this.ticks)?s=!1:this.ticks=r}i("tickEnable"),a("tickFont")&&(s=!0),n("tickSize"),n("tickAngle"),n("tickPad"),o("tickColor");var g=a("labels");a("labelFont")&&(g=!0),i("labelEnable"),n("labelSize"),n("labelPad"),o("labelColor"),i("lineEnable"),i("lineMirror"),n("lineWidth"),o("lineColor"),i("lineTickEnable"),i("lineTickMirror"),n("lineTickLength"),n("lineTickWidth"),o("lineTickColor"),i("gridEnable"),n("gridWidth"),o("gridColor"),i("zeroEnable"),o("zeroLineColor"),n("zeroLineWidth"),i("backgroundEnable"),o("backgroundColor"),this._text?this._text&&(g||s)&&this._text.update(this.bounds,this.labels,this.labelFont,this.ticks,this.tickFont):this._text=l(this.gl,this.bounds,this.labels,this.labelFont,this.ticks,this.tickFont),this._lines&&s&&(this._lines.dispose(),this._lines=null),this._lines||(this._lines=u(this.gl,this.bounds,this.ticks))};var g=[new a,new a,new a],v=[0,0,0],m={model:d,view:d,projection:d};p.isOpaque=function(){return!0},p.isTransparent=function(){return!1},p.drawTransparent=function(t){};var y=[0,0,0],b=[0,0,0],x=[0,0,0];p.draw=function(t){t=t||m;for(var e=this.gl,r=t.model||d,i=t.view||d,a=t.projection||d,s=this.bounds,l=h(r,i,a,s),u=l.cubeEdges,c=l.axis,f=i[12],p=i[13],_=i[14],w=i[15],A=this.pixelRatio*(a[3]*f+a[7]*p+a[11]*_+a[15]*w)/e.drawingBufferHeight,k=0;3>k;++k)this.lastCubeProps.cubeEdges[k]=u[k],this.lastCubeProps.axis[k]=c[k];for(var M=g,k=0;3>k;++k)o(g[k],k,this.bounds,u,c);for(var e=this.gl,T=v,k=0;3>k;++k)this.backgroundEnable[k]?T[k]=c[k]:T[k]=0;this._background.draw(r,i,a,s,T,this.backgroundColor),this._lines.bind(r,i,a,this);for(var k=0;3>k;++k){var E=[0,0,0];c[k]>0?E[k]=s[1][k]:E[k]=s[0][k];for(var L=0;2>L;++L){var S=(k+1+L)%3,C=(k+1+(1^L))%3;this.gridEnable[S]&&this._lines.drawGrid(S,C,this.bounds,E,this.gridColor[S],this.gridWidth[S]*this.pixelRatio)}for(var L=0;2>L;++L){var S=(k+1+L)%3,C=(k+1+(1^L))%3;this.zeroEnable[C]&&s[0][C]<=0&&s[1][C]>=0&&this._lines.drawZero(S,C,this.bounds,E,this.zeroLineColor[C],this.zeroLineWidth[C]*this.pixelRatio)}}for(var k=0;3>k;++k){this.lineEnable[k]&&this._lines.drawAxisLine(k,this.bounds,M[k].primalOffset,this.lineColor[k],this.lineWidth[k]*this.pixelRatio),this.lineMirror[k]&&this._lines.drawAxisLine(k,this.bounds,M[k].mirrorOffset,this.lineColor[k],this.lineWidth[k]*this.pixelRatio);for(var P=n(y,M[k].primalMinor),z=n(b,M[k].mirrorMinor),R=this.lineTickLength,L=0;3>L;++L){var O=A/r[5*L];P[L]*=R[L]*O,z[L]*=R[L]*O}this.lineTickEnable[k]&&this._lines.drawAxisTicks(k,M[k].primalOffset,P,this.lineTickColor[k],this.lineTickWidth[k]*this.pixelRatio),this.lineTickMirror[k]&&this._lines.drawAxisTicks(k,M[k].mirrorOffset,z,this.lineTickColor[k],this.lineTickWidth[k]*this.pixelRatio)}this._text.bind(r,i,a,this.pixelRatio);for(var k=0;3>k;++k){for(var I=M[k].primalMinor,j=n(x,M[k].primalOffset),L=0;3>L;++L)this.lineTickEnable[k]&&(j[L]+=A*I[L]*Math.max(this.lineTickLength[L],0)/r[5*L]);if(this.tickEnable[k]){for(var L=0;3>L;++L)j[L]+=A*I[L]*this.tickPad[L]/r[5*L];this._text.drawTicks(k,this.tickSize[k],this.tickAngle[k],j,this.tickColor[k])}if(this.labelEnable[k]){for(var L=0;3>L;++L)j[L]+=A*I[L]*this.labelPad[L]/r[5*L];j[k]+=.5*(s[0][k]+s[1][k]),this._text.drawLabel(k,this.labelSize[k],this.labelAngle[k],j,this.labelColor[k])}}},p.dispose=function(){this._text.dispose(),this._lines.dispose(),this._background.dispose(),this._lines=null,this._text=null,this._background=null,this.gl=null}},{"./lib/background.js":128,"./lib/cube.js":129,"./lib/lines.js":130,"./lib/text.js":132,"./lib/ticks.js":133}],128:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n}function i(t){for(var e=[],r=[],i=0,l=0;3>l;++l)for(var u=(l+1)%3,c=(l+2)%3,h=[0,0,0],f=[0,0,0],d=-1;1>=d;d+=2){r.push(i,i+2,i+1,i+1,i+2,i+3),h[l]=d,f[l]=d;for(var p=-1;1>=p;p+=2){h[u]=p;for(var g=-1;1>=g;g+=2)h[c]=g,e.push(h[0],h[1],h[2],f[0],f[1],f[2]),i+=1}var v=u;u=c,c=v}var m=a(t,new Float32Array(e)),y=a(t,new Uint16Array(r),t.ELEMENT_ARRAY_BUFFER),b=o(t,[{buffer:m,type:t.FLOAT,size:3,offset:0,stride:24},{buffer:m,type:t.FLOAT,size:3,offset:12,stride:24}],y),x=s(t);return x.attributes.position.location=0,x.attributes.normal.location=1,new n(t,m,b,x)}e.exports=i;var a=t("gl-buffer"),o=t("gl-vao"),s=t("./shaders").bg,l=n.prototype;l.draw=function(t,e,r,n,i,a){for(var o=!1,s=0;3>s;++s)o=o||i[s];if(o){var l=this.gl;l.enable(l.POLYGON_OFFSET_FILL),l.polygonOffset(1,2),this.shader.bind(),this.shader.uniforms={model:t,view:e,projection:r,bounds:n,enable:i,colors:a},this.vao.bind(),this.vao.draw(this.gl.TRIANGLES,36),l.disable(l.POLYGON_OFFSET_FILL)}},l.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders":131,"gl-buffer":75,"gl-vao":189}],129:[function(t,e,r){"use strict";function n(t,e,r){for(var n=0;4>n;++n){t[n]=r[12+n];for(var i=0;3>i;++i)t[n]+=e[i]*r[4*i+n]}}function i(t){for(var e=0;e<g.length;++e)if(t=l.positive(t,g[e]),t.length<3)return 0;for(var r=t[0],n=r[0]/r[3],i=r[1]/r[3],a=0,e=1;e+1<t.length;++e){var o=t[e],s=t[e+1],u=o[0]/o[3],c=o[1]/o[3],h=s[0]/s[3],f=s[1]/s[3],d=u-n,p=c-i,v=h-n,m=f-i;a+=Math.abs(d*m-p*v)}return a}function a(t,e,r,a){s(c,e,t),s(c,r,c);for(var l=0,g=0;2>g;++g){d[2]=a[g][2];for(var b=0;2>b;++b){d[1]=a[b][1];for(var x=0;2>x;++x)d[0]=a[x][0],n(h[l],d,c),l+=1}}for(var _=-1,g=0;8>g;++g){for(var w=h[g][3],A=0;3>A;++A)f[g][A]=h[g][A]/w;0>w&&(0>_?_=g:f[g][2]<f[_][2]&&(_=g))}if(0>_){_=0;for(var k=0;3>k;++k){for(var M=(k+2)%3,T=(k+1)%3,E=-1,L=-1,S=0;2>S;++S){var C=S<<k,P=C+(S<<M)+(1-S<<T),z=C+(1-S<<M)+(S<<T);u(f[C],f[P],f[z],p)<0||(S?E=1:L=1)}if(0>E||0>L)L>E&&(_|=1<<k);else{for(var S=0;2>S;++S){var C=S<<k,P=C+(S<<M)+(1-S<<T),z=C+(1-S<<M)+(S<<T),R=i([h[C],h[P],h[z],h[C+(1<<M)+(1<<T)]]);S?E=R:L=R}L>E&&(_|=1<<k)}}}for(var O=7^_,I=-1,g=0;8>g;++g)g!==_&&g!==O&&(0>I?I=g:f[I][1]>f[g][1]&&(I=g));for(var j=-1,g=0;3>g;++g){var N=I^1<<g;if(N!==_&&N!==O){0>j&&(j=N);var T=f[N];T[0]<f[j][0]&&(j=N)}}for(var F=-1,g=0;3>g;++g){var N=I^1<<g;if(N!==_&&N!==O&&N!==j){0>F&&(F=N);var T=f[N];T[0]>f[F][0]&&(F=N)}}var B=v;B[0]=B[1]=B[2]=0,B[o.log2(j^I)]=I&j,B[o.log2(I^F)]=I&F;var D=7^F;D===_||D===O?(D=7^j,B[o.log2(F^D)]=D&F):B[o.log2(j^D)]=D&j;for(var U=m,V=_,k=0;3>k;++k)V&1<<k?U[k]=-1:U[k]=1;return y}e.exports=a;var o=t("bit-twiddle"),s=t("gl-mat4/multiply"),l=(t("gl-mat4/invert"),t("split-polygon")),u=t("robust-orientation"),c=new Array(16),h=(new Array(16),new Array(8)),f=new Array(8),d=new Array(3),p=[0,0,0];!function(){for(var t=0;8>t;++t)h[t]=[1,1,1,1],f[t]=[1,1,1]}();var g=[[0,0,1,0,0],[0,0,-1,1,0],[0,-1,0,1,0],[0,1,0,1,0],[-1,0,0,1,0],[1,0,0,1,0]],v=[1,1,1],m=[0,0,0],y={cubeEdges:v,axis:m}},{"bit-twiddle":49,"gl-mat4/invert":94,"gl-mat4/multiply":96,"robust-orientation":214,"split-polygon":135}],130:[function(t,e,r){"use strict";function n(t){return t[0]=t[1]=t[2]=0,t}function i(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t}function a(t,e,r,n,i,a,o,s){this.gl=t,this.vertBuffer=e,this.vao=r,this.shader=n,this.tickCount=i,this.tickOffset=a,this.gridCount=o,this.gridOffset=s}function o(t,e,r){var n=[],i=[0,0,0],o=[0,0,0],c=[0,0,0],h=[0,0,0];n.push(0,0,1,0,1,1,0,0,-1,0,0,-1,0,1,1,0,1,-1);for(var f=0;3>f;++f){for(var d=n.length/3|0,p=0;p<r[f].length;++p){var g=+r[f][p].x;n.push(g,0,1,g,1,1,g,0,-1,g,0,-1,g,1,1,g,1,-1)}var v=n.length/3|0;i[f]=d,o[f]=v-d;for(var d=n.length/3|0,m=0;m<r[f].length;++m){var g=+r[f][m].x;n.push(g,0,1,g,1,1,g,0,-1,g,0,-1,g,1,1,g,1,-1)}var v=n.length/3|0;c[f]=d,h[f]=v-d}var y=s(t,new Float32Array(n)),b=l(t,[{buffer:y,type:t.FLOAT,size:3,stride:0,offset:0}]),x=u(t);return x.attributes.position.location=0,new a(t,y,b,x,o,i,h,c)}e.exports=o;var s=t("gl-buffer"),l=t("gl-vao"),u=t("./shaders").line,c=[0,0,0],h=[0,0,0],f=[0,0,0],d=[0,0,0],p=[1,1],g=a.prototype;g.bind=function(t,e,r){this.shader.bind(),this.shader.uniforms.model=t,this.shader.uniforms.view=e,this.shader.uniforms.projection=r,p[0]=this.gl.drawingBufferWidth,p[1]=this.gl.drawingBufferHeight,this.shader.uniforms.screenShape=p,this.vao.bind()},g.drawAxisLine=function(t,e,r,a,o){var s=n(h);this.shader.uniforms.majorAxis=h,s[t]=e[1][t]-e[0][t],this.shader.uniforms.minorAxis=s;var l=i(d,r);l[t]+=e[0][t],this.shader.uniforms.offset=l,this.shader.uniforms.lineWidth=o,this.shader.uniforms.color=a;var u=n(f);u[(t+2)%3]=1,this.shader.uniforms.screenAxis=u,this.vao.draw(this.gl.TRIANGLES,6);var u=n(f);u[(t+1)%3]=1,this.shader.uniforms.screenAxis=u,this.vao.draw(this.gl.TRIANGLES,6)},g.drawAxisTicks=function(t,e,r,i,a){var o=n(c);o[t]=1,this.shader.uniforms.majorAxis=o,this.shader.uniforms.offset=e,this.shader.uniforms.minorAxis=r,this.shader.uniforms.color=i,this.shader.uniforms.lineWidth=a;var s=n(f);s[t]=1,this.shader.uniforms.screenAxis=s,this.vao.draw(this.gl.TRIANGLES,this.tickCount[t],this.tickOffset[t])},g.drawGrid=function(t,e,r,a,o,s){var l=n(h);l[e]=r[1][e]-r[0][e],this.shader.uniforms.minorAxis=l;var u=i(d,a);u[e]+=r[0][e],this.shader.uniforms.offset=u;var p=n(c);p[t]=1,this.shader.uniforms.majorAxis=p;var g=n(f);g[t]=1,this.shader.uniforms.screenAxis=g,this.shader.uniforms.lineWidth=s,this.shader.uniforms.color=o,this.vao.draw(this.gl.TRIANGLES,this.gridCount[t],this.gridOffset[t])},g.drawZero=function(t,e,r,a,o,s){var l=n(h);this.shader.uniforms.majorAxis=l,l[t]=r[1][t]-r[0][t],this.shader.uniforms.minorAxis=l;var u=i(d,a);u[t]+=r[0][t],this.shader.uniforms.offset=u;var c=n(f);c[e]=1,this.shader.uniforms.screenAxis=c,this.shader.uniforms.lineWidth=s,this.shader.uniforms.color=o,this.vao.draw(this.gl.TRIANGLES,6)},g.dispose=function(){this.vao.dispose(),this.vertBuffer.dispose(),this.shader.dispose()}},{"./shaders":131,"gl-buffer":75,"gl-vao":189}],131:[function(t,e,r){"use strict";var n=t("gl-shader"),i="#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, majorAxis, minorAxis, screenAxis;\nuniform float lineWidth;\nuniform vec2 screenShape;\n\nvec3 project(vec3 p) {\n  vec4 pp = projection * view * model * vec4(p, 1.0);\n  return pp.xyz / max(pp.w, 0.0001);\n}\n\nvoid main() {\n  vec3 major = position.x * majorAxis;\n  vec3 minor = position.y * minorAxis;\n\n  vec3 vPosition = major + minor + offset;\n  vec3 pPosition = project(vPosition);\n  vec3 offset = project(vPosition + screenAxis * position.z);\n\n  vec2 screen = normalize((offset - pPosition).xy * screenShape) / screenShape;\n\n  gl_Position = vec4(pPosition + vec3(0.5 * screen * lineWidth, 0), 1.0);\n}\n",a="precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}";r.line=function(t){return n(t,i,a,null,[{name:"position",type:"vec3"}])};var o="#define GLSLIFY 1\nattribute vec3 position;\n\nuniform mat4 model, view, projection;\nuniform vec3 offset, axis;\nuniform float scale, angle, pixelScale;\nuniform vec2 resolution;\n\nvoid main() {  \n  //Compute plane offset\n  vec2 planeCoord = position.xy * pixelScale;\n  mat2 planeXform = scale * mat2(cos(angle), sin(angle),\n                                -sin(angle), cos(angle));\n  vec2 viewOffset = 2.0 * planeXform * planeCoord / resolution;\n\n  //Compute world offset\n  float axisDistance = position.z;\n  vec3 dataPosition = axisDistance * axis + offset;\n  vec4 worldPosition = model * vec4(dataPosition, 1);\n  \n  //Compute clip position\n  vec4 viewPosition = view * worldPosition;\n  vec4 clipPosition = projection * viewPosition;\n  clipPosition /= clipPosition.w;\n\n  //Apply text offset in clip coordinates\n  clipPosition += vec4(viewOffset, 0, 0);\n\n  //Done\n  gl_Position = clipPosition;\n}",s="precision mediump float;\n#define GLSLIFY 1\nuniform vec4 color;\nvoid main() {\n  gl_FragColor = color;\n}";r.text=function(t){return n(t,o,s,null,[{name:"position",type:"vec3"}])};var l="#define GLSLIFY 1\nattribute vec3 position;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection;\nuniform vec3 enable;\nuniform vec3 bounds[2];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n  if(dot(normal, enable) > 0.0) {\n    vec3 nPosition = mix(bounds[0], bounds[1], 0.5 * (position + 1.0));\n    gl_Position = projection * view * model * vec4(nPosition, 1.0);\n  } else {\n    gl_Position = vec4(0,0,0,0);\n  }\n  colorChannel = abs(normal);\n}",u="precision mediump float;\n#define GLSLIFY 1\n\nuniform vec4 colors[3];\n\nvarying vec3 colorChannel;\n\nvoid main() {\n  gl_FragColor = colorChannel.x * colors[0] + \n                 colorChannel.y * colors[1] +\n                 colorChannel.z * colors[2];\n}";r.bg=function(t){return n(t,l,u,null,[{name:"position",type:"vec3"},{name:"normal",type:"vec3"}])}},{"gl-shader":154}],132:[function(t,e,r){(function(r){"use strict";function n(t,e,r,n){this.gl=t,this.shader=e,this.buffer=r,this.vao=n,this.tickOffset=this.tickCount=this.labelOffset=this.labelCount=null}function i(t,e){try{return l(t,e)}catch(r){return console.warn("error vectorizing text:",r),{cells:[],positions:[]}}}function a(t,e,r,i,a,l){var c=o(t),h=s(t,[{buffer:c,size:3}]),f=u(t);f.attributes.position.location=0;var d=new n(t,f,c,h);return d.update(e,r,i,a,l),d}e.exports=a;var o=t("gl-buffer"),s=t("gl-vao"),l=t("vectorize-text"),u=t("./shaders").text,c=window||r.global||{},h=c.__TEXT_CACHE||{};c.__TEXT_CACHE={};var f=3,d=n.prototype,p=[0,0];d.bind=function(t,e,r,n){this.vao.bind(),this.shader.bind();var i=this.shader.uniforms;i.model=t,i.view=e,i.projection=r,i.pixelScale=n,p[0]=this.gl.drawingBufferWidth,p[1]=this.gl.drawingBufferHeight,this.shader.uniforms.resolution=p},d.update=function(t,e,r,n,a){function o(t,e,r,n){var a=h[r];a||(a=h[r]={});var o=a[e];o||(o=a[e]=i(e,{triangles:!0,font:r,textAlign:"center",textBaseline:"middle"}));for(var l=(n||12)/12,u=o.positions,c=o.cells,f=0,d=c.length;d>f;++f)for(var p=c[f],g=2;g>=0;--g){var v=u[p[g]];s.push(l*v[0],-l*v[1],t)}}for(var s=(this.gl,[]),l=[0,0,0],u=[0,0,0],c=[0,0,0],d=[0,0,0],p=0;3>p;++p){c[p]=s.length/f|0,o(.5*(t[0][p]+t[1][p]),e[p],r),d[p]=(s.length/f|0)-c[p],l[p]=s.length/f|0;for(var g=0;g<n[p].length;++g)n[p][g].text&&o(n[p][g].x,n[p][g].text,n[p][g].font||a,n[p][g].fontSize||12);u[p]=(s.length/f|0)-l[p]}this.buffer.update(s),this.tickOffset=l,this.tickCount=u,this.labelOffset=c,this.labelCount=d};var g=[0,0,0];d.drawTicks=function(t,e,r,n,i){var a=g;a[0]=a[1]=a[2]=0,a[t]=1,this.shader.uniforms.axis=a,this.shader.uniforms.color=i,this.shader.uniforms.angle=r,this.shader.uniforms.scale=e,this.shader.uniforms.offset=n,this.vao.draw(this.gl.TRIANGLES,this.tickCount[t],this.tickOffset[t])};var v=[0,0,0];d.drawLabel=function(t,e,r,n,i){this.shader.uniforms.axis=v,this.shader.uniforms.color=i,this.shader.uniforms.angle=r,this.shader.uniforms.scale=e,this.shader.uniforms.offset=n,this.vao.draw(this.gl.TRIANGLES,this.labelCount[t],this.labelOffset[t])},d.dispose=function(){this.shader.dispose(),this.vao.dispose(),this.buffer.dispose()}}).call(this,t("_process"))},{"./shaders":131,_process:55,"gl-buffer":75,"gl-vao":189,"vectorize-text":235}],133:[function(t,e,r){"use strict";function n(t,e){var r=t+"",n=r.indexOf("."),i=0;n>=0&&(i=r.length-n-1);var a=Math.pow(10,i),o=Math.round(t*e*a),s=o+"";if(s.indexOf("e")>=0)return s;var l=o/a,u=o%a;0>o?(l=0|-Math.ceil(l),u=0|-u):(l=0|Math.floor(l),u=0|u);var c=""+l;if(0>o&&(c="-"+c),i){for(var h=""+u;h.length<i;)h="0"+h;return c+"."+h}return c}function i(t,e){for(var r=[],i=0;3>i;++i){for(var a=[],o=(.5*(t[0][i]+t[1][i]),0);o*e[i]<=t[1][i];++o)a.push({x:o*e[i],text:n(e[i],o)});for(var o=-1;o*e[i]>=t[0][i];--o)a.push({x:o*e[i],text:n(e[i],o)});r.push(a)}return r}function a(t,e){for(var r=0;3>r;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;n<t[r].length;++n){var i=t[r][n],a=e[r][n];if(i.x!==a.x||i.text!==a.text)return!1}}return!0}r.create=i,r.equal=a},{}],134:[function(t,e,r){"use strict";function n(t,e,r){var n=e||0,i=r||1;return[[t[12]+t[0],t[13]+t[1],t[14]+t[2],t[15]+t[3]],[t[12]-t[0],t[13]-t[1],t[14]-t[2],t[15]-t[3]],[t[12]+t[4],t[13]+t[5],t[14]+t[6],t[15]+t[7]],[t[12]-t[4],t[13]-t[5],t[14]-t[6],t[15]-t[7]],[n*t[12]+t[8],n*t[13]+t[9],n*t[14]+t[10],n*t[15]+t[11]],[i*t[12]-t[8],i*t[13]-t[9],i*t[14]-t[10],i*t[15]-t[11]]]}e.exports=n},{}],135:[function(t,e,r){"use strict";function n(t,e){var r=u(l(t,e),[e[e.length-1]]);return r[r.length-1]}function i(t,e,r,n){var i=n-e,a=-e/i;0>a?a=0:a>1&&(a=1);for(var o=1-a,s=t.length,l=new Array(s),u=0;s>u;++u)l[u]=a*t[u]+o*r[u];return l}function a(t,e){for(var r=[],a=[],o=n(t[t.length-1],e),s=t[t.length-1],l=t[0],u=0;u<t.length;++u,s=l){l=t[u];var c=n(l,e);if(0>o&&c>0||o>0&&0>c){var h=i(s,c,l,o);r.push(h),a.push(h.slice())}0>c?a.push(l.slice()):c>0?r.push(l.slice()):(r.push(l.slice()),a.push(l.slice())),o=c}return{positive:r,negative:a}}function o(t,e){for(var r=[],a=n(t[t.length-1],e),o=t[t.length-1],s=t[0],l=0;l<t.length;++l,o=s){s=t[l];var u=n(s,e);(0>a&&u>0||a>0&&0>u)&&r.push(i(o,u,s,a)),u>=0&&r.push(s.slice()),a=u}return r}function s(t,e){for(var r=[],a=n(t[t.length-1],e),o=t[t.length-1],s=t[0],l=0;l<t.length;++l,o=s){s=t[l];var u=n(s,e);(0>a&&u>0||a>0&&0>u)&&r.push(i(o,u,s,a)),0>=u&&r.push(s.slice()),a=u}return r}var l=t("robust-dot-product"),u=t("robust-sum");e.exports=a,e.exports.positive=o,e.exports.negative=s},{"robust-dot-product":136,"robust-sum":217}],136:[function(t,e,r){"use strict";function n(t,e){for(var r=i(t[0],e[0]),n=1;n<t.length;++n)r=a(r,i(t[n],e[n]));return r}var i=t("two-product"),a=t("robust-sum");e.exports=n},{"robust-sum":217,"two-product":231}],137:[function(t,e,r){"use strict";function n(t,e,r){this.lo=t,this.hi=e,this.pixelsPerDataUnit=r}function i(t,e,r,n,i){for(var a=0;3>a;++a){for(var o=p,s=g,l=0;3>l;++l)s[l]=o[l]=r[l];s[3]=o[3]=1,s[a]+=1,h(s,s,e),s[3]<0&&(t[a]=1/0),o[a]-=1,h(o,o,e),o[3]<0&&(t[a]=1/0);var u=(o[0]/o[3]-s[0]/s[3])*n,c=(o[1]/o[3]-s[1]/s[3])*i;t[a]=.25*Math.sqrt(u*u+c*c)}return t}function a(t,e,r,n,a){var h=e.model||f,p=e.view||f,g=e.projection||f,y=t.bounds,a=a||l(h,p,g,y),b=a.axis;a.edges;u(d,p,h),u(d,g,d);for(var x=v,_=0;3>_;++_)x[_].lo=1/0,x[_].hi=-(1/0),x[_].pixelsPerDataUnit=1/0;var w=o(c(d,d));c(d,d);for(var A=0;3>A;++A){var k=(A+1)%3,M=(A+2)%3,T=m;t:for(var _=0;2>_;++_){var E=[];if(b[A]<0!=!!_){T[A]=y[_][A];for(var L=0;2>L;++L){T[k]=y[L^_][k];for(var S=0;2>S;++S)T[M]=y[S^L^_][M],E.push(T.slice())}for(var L=0;L<w.length;++L){if(0===E.length)continue t;E=s.positive(E,w[L])}for(var L=0;L<E.length;++L)for(var M=E[L],C=i(m,d,M,r,n),S=0;3>S;++S)x[S].lo=Math.min(x[S].lo,M[S]),x[S].hi=Math.max(x[S].hi,M[S]),S!==A&&(x[S].pixelsPerDataUnit=Math.min(x[S].pixelsPerDataUnit,Math.abs(C[S])))}}}return x}e.exports=a;var o=t("extract-frustum-planes"),s=t("split-polygon"),l=t("./lib/cube.js"),u=t("gl-mat4/multiply"),c=t("gl-mat4/transpose"),h=t("gl-vec4/transformMat4"),f=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),d=new Float32Array(16),p=[0,0,0,1],g=[0,0,0,1],v=[new n(1/0,-(1/0),1/0),new n(1/0,-(1/0),1/0),new n(1/0,-(1/0),1/0)],m=[0,0,0]},{"./lib/cube.js":129,"extract-frustum-planes":134,"gl-mat4/multiply":96,"gl-mat4/transpose":104,"gl-vec4/transformMat4":190,"split-polygon":135}],138:[function(t,e,r){"use strict";var n=t("gl-shader"),i="precision mediump float;\n#define GLSLIFY 1\n\nattribute vec3 position, color;\nattribute float weight;\n\nuniform mat4 model, view, projection;\nuniform vec3 coordinates[3];\nuniform vec4 colors[3];\nuniform vec2 screenShape;\nuniform float lineWidth;\n\nvarying vec4 fragColor;\n\nvoid main() {\n  vec3 vertexPosition = mix(coordinates[0],\n    mix(coordinates[2], coordinates[1], 0.5 * (position + 1.0)), abs(position));\n\n  vec4 clipPos = projection * view * model * vec4(vertexPosition, 1.0);\n  vec2 clipOffset = (projection * view * model * vec4(color, 0.0)).xy;\n  vec2 delta = weight * clipOffset * screenShape;\n  vec2 lineOffset = normalize(vec2(delta.y, -delta.x)) / screenShape;\n\n  gl_Position   = vec4(clipPos.xy + clipPos.w * 0.5 * lineWidth * lineOffset, clipPos.z, clipPos.w);\n  fragColor     = color.x * colors[0] + color.y * colors[1] + color.z * colors[2];\n}\n",a="precision mediump float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor;\n\nvoid main() {\n  gl_FragColor = fragColor;\n}";e.exports=function(t){return n(t,i,a,null,[{name:"position",type:"vec3"},{name:"color",type:"vec3"},{name:"weight",type:"float"}])}},{"gl-shader":154}],139:[function(t,e,r){"use strict";function n(t,e,r,n){this.gl=t,this.buffer=e,this.vao=r,this.shader=n,this.pixelRatio=1,this.bounds=[[-1e3,-1e3,-1e3],[1e3,1e3,1e3]],this.position=[0,0,0],this.lineWidth=[2,2,2],this.colors=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.enabled=[!0,!0,!0],this.drawSides=[!0,!0,!0],this.axes=null}function i(t,e){function r(t,e,r,n,a,o){var s=[t,e,r,0,0,0,1];s[n+3]=1,s[n]=a,i.push.apply(i,s),s[6]=-1,i.push.apply(i,s),s[n]=o,i.push.apply(i,s),i.push.apply(i,s),s[6]=1,i.push.apply(i,s),s[n]=a,i.push.apply(i,s)}var i=[];r(0,0,0,0,0,1),r(0,0,0,1,0,1),r(0,0,0,2,0,1),r(1,0,0,1,-1,1),r(1,0,0,2,-1,1),r(0,1,0,0,-1,1),r(0,1,0,2,-1,1),r(0,0,1,0,-1,1),r(0,0,1,1,-1,1);var l=a(t,i),u=o(t,[{type:t.FLOAT,buffer:l,size:3,offset:0,stride:28},{type:t.FLOAT,buffer:l,size:3,offset:12,stride:28},{type:t.FLOAT,buffer:l,size:1,offset:24,stride:28}]),c=s(t);c.attributes.position.location=0,c.attributes.color.location=1,c.attributes.weight.location=2;var h=new n(t,l,u,c);return h.update(e),h}var a=t("gl-buffer"),o=t("gl-vao"),s=t("./shaders/index");e.exports=i;var l=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],u=n.prototype,c=[0,0,0],h=[0,0,0],f=[0,0];u.isTransparent=function(){return!1},u.drawTransparent=function(t){},u.draw=function(t){var e=this.gl,r=this.vao,n=this.shader;r.bind(),n.bind();var i,a=t.model||l,o=t.view||l,s=t.projection||l;this.axes&&(i=this.axes.lastCubeProps.axis);for(var u=c,d=h,p=0;3>p;++p)i&&i[p]<0?(u[p]=this.bounds[0][p],d[p]=this.bounds[1][p]):(u[p]=this.bounds[1][p],d[p]=this.bounds[0][p]);f[0]=e.drawingBufferWidth,f[1]=e.drawingBufferHeight,n.uniforms.model=a,n.uniforms.view=o,n.uniforms.projection=s,n.uniforms.coordinates=[this.position,u,d],n.uniforms.colors=this.colors,n.uniforms.screenShape=f;for(var p=0;3>p;++p)n.uniforms.lineWidth=this.lineWidth[p]*this.pixelRatio,
+this.enabled[p]&&(r.draw(e.TRIANGLES,6,6*p),this.drawSides[p]&&r.draw(e.TRIANGLES,12,18+12*p));r.unbind()},u.update=function(t){t&&("bounds"in t&&(this.bounds=t.bounds),"position"in t&&(this.position=t.position),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"colors"in t&&(this.colors=t.colors),"enabled"in t&&(this.enabled=t.enabled),"drawSides"in t&&(this.drawSides=t.drawSides))},u.dispose=function(){this.vao.dispose(),this.buffer.dispose(),this.shader.dispose()}},{"./shaders/index":138,"gl-buffer":75,"gl-vao":189}],140:[function(t,e,r){"use strict";function n(){this.mouse=[-1,-1],this.screen=null,this.distance=1/0,this.index=null,this.dataCoordinate=null,this.dataPosition=null,this.object=null,this.data=null}function i(t,e){var r=null;try{r=t.getContext("webgl",e),r||(r=t.getContext("experimental-webgl",e))}catch(n){return null}return r}function a(t){var e=Math.round(Math.log(Math.abs(t))/Math.log(10));if(0>e){var r=Math.round(Math.pow(10,-e));return Math.ceil(t*r)/r}if(e>0){var r=Math.round(Math.pow(10,e));return Math.ceil(t/r)*r}return Math.ceil(t)}function o(t){return"boolean"==typeof t?t:!0}function s(t){function e(){if(!_&&H.autoResize){var t=w.parentNode,e=1,r=1;t&&t!==document.body?(e=t.clientWidth,r=t.clientHeight):(e=window.innerWidth,r=window.innerHeight);var n=0|Math.ceil(e*H.pixelRatio),i=0|Math.ceil(r*H.pixelRatio);if(n!==w.width||i!==w.height){w.width=n,w.height=i;var a=w.style;a.position=a.position||"absolute",a.left="0px",a.top="0px",a.width=e+"px",a.height=r+"px",F=!0}}}function r(){for(var t=O.length,e=N.length,r=0;e>r;++r)j[r]=0;t:for(var r=0;t>r;++r){var n=O[r],i=n.pickSlots;if(i){for(var a=0;e>a;++a)if(j[a]+i<255){I[r]=a,n.setPickBase(j[a]+1),j[a]+=i;continue t}var o=f(k,q);I[r]=e,N.push(o),j.push(i),n.setPickBase(1),e+=1}else I[r]=-1}for(;e>0&&0===j[e-1];)j.pop(),N.pop().dispose()}function s(){return H.contextLost?!0:void(k.isContextLost()&&(H.contextLost=!0,H.mouseListener.enabled=!1,H.selection.object=null,H.oncontextloss&&H.oncontextloss()))}function y(){if(!s()){k.colorMask(!0,!0,!0,!0),k.depthMask(!0),k.disable(k.BLEND),k.enable(k.DEPTH_TEST);for(var t=O.length,e=N.length,r=0;e>r;++r){var n=N[r];n.shape=G,n.begin();for(var i=0;t>i;++i)if(I[i]===r){var a=O[i];a.drawPick&&(a.pixelRatio=1,a.drawPick(V))}n.end()}}}function b(){if(!s()){e();var t=H.camera.tick();V.view=H.camera.matrix,F=F||t,B=B||t,P.pixelRatio=H.pixelRatio,R.pixelRatio=H.pixelRatio;var r=O.length,n=W[0],i=W[1];n[0]=n[1]=n[2]=1/0,i[0]=i[1]=i[2]=-(1/0);for(var o=0;r>o;++o){var l=O[o];l.pixelRatio=H.pixelRatio,l.axes=H.axes,F=F||!!l.dirty,B=B||!!l.dirty;var u=l.bounds;if(u)for(var h=u[0],f=u[1],d=0;3>d;++d)n[d]=Math.min(n[d],h[d]),i[d]=Math.max(i[d],f[d])}var g=H.bounds;if(H.autoBounds)for(var d=0;3>d;++d){if(i[d]<n[d])n[d]=-1,i[d]=1;else{n[d]===i[d]&&(n[d]-=1,i[d]+=1);var m=.05*(i[d]-n[d]);n[d]=n[d]-m,i[d]=i[d]+m}g[0][d]=n[d],g[1][d]=i[d]}for(var b=!1,d=0;3>d;++d)b=b||Z[0][d]!==g[0][d]||Z[1][d]!==g[1][d],Z[0][d]=g[0][d],Z[1][d]=g[1][d];if(b){for(var x=[0,0,0],o=0;3>o;++o)x[o]=a((g[1][o]-g[0][o])/10);P.autoTicks?P.update({bounds:g,tickSpacing:x}):P.update({bounds:g})}B=B||b,F=F||b;var _=k.drawingBufferWidth,w=k.drawingBufferHeight;q[0]=_,q[1]=w,G[0]=0|Math.max(_/H.pixelRatio,1),G[1]=0|Math.max(w/H.pixelRatio,1),v(D,H.fovy,_/w,H.zNear,H.zFar);for(var o=0;16>o;++o)U[o]=0;U[15]=1;for(var A=0,o=0;3>o;++o)A=Math.max(A,g[1][o]-g[0][o]);for(var o=0;3>o;++o)H.autoScale?U[5*o]=H.aspect[o]/(g[1][o]-g[0][o]):U[5*o]=1/A,H.autoCenter&&(U[12+o]=.5*-U[5*o]*(g[0][o]+g[1][o]));for(var o=0;r>o;++o){var l=O[o];l.axesBounds=g,H.clipToBounds&&(l.clipBounds=g)}if(T.object&&(H.snapToData?R.position=T.dataCoordinate:R.position=T.dataPosition,R.bounds=g),B&&(B=!1,y()),F){H.axesPixels=c(H.axes,V,_,w),H.onrender&&H.onrender(),k.bindFramebuffer(k.FRAMEBUFFER,null),k.viewport(0,0,_,w);var M=H.clearColor;k.clearColor(M[0],M[1],M[2],M[3]),k.clear(k.COLOR_BUFFER_BIT|k.DEPTH_BUFFER_BIT),k.depthMask(!0),k.colorMask(!0,!0,!0,!0),k.enable(k.DEPTH_TEST),k.depthFunc(k.LEQUAL),k.disable(k.BLEND),k.disable(k.CULL_FACE);var S=!1;P.enable&&(S=S||P.isTransparent(),P.draw(V)),R.axes=P,T.object&&R.draw(V),k.disable(k.CULL_FACE);for(var o=0;r>o;++o){var l=O[o];l.axes=P,l.pixelRatio=H.pixelRatio,l.isOpaque&&l.isOpaque()&&l.draw(V),l.isTransparent&&l.isTransparent()&&(S=!0)}if(S){E.shape=q,E.bind(),k.clear(k.DEPTH_BUFFER_BIT),k.colorMask(!1,!1,!1,!1),k.depthMask(!0),k.depthFunc(k.LESS),P.enable&&P.isTransparent()&&P.drawTransparent(V);for(var o=0;r>o;++o){var l=O[o];l.isOpaque&&l.isOpaque()&&l.draw(V)}k.enable(k.BLEND),k.blendEquation(k.FUNC_ADD),k.blendFunc(k.ONE,k.ONE_MINUS_SRC_ALPHA),k.colorMask(!0,!0,!0,!0),k.depthMask(!1),k.clearColor(0,0,0,0),k.clear(k.COLOR_BUFFER_BIT),P.isTransparent()&&P.drawTransparent(V);for(var o=0;r>o;++o){var l=O[o];l.isTransparent&&l.isTransparent()&&l.drawTransparent(V)}k.bindFramebuffer(k.FRAMEBUFFER,null),k.blendFunc(k.ONE,k.ONE_MINUS_SRC_ALPHA),k.disable(k.DEPTH_TEST),L.bind(),E.color[0].bind(0),L.uniforms.accumBuffer=0,p(k),k.disable(k.BLEND)}F=!1;for(var o=0;r>o;++o)O[o].dirty=!1}}}function x(){_||H.contextLost||(requestAnimationFrame(x),b())}t=t||{};var _=!1,w=(t.pixelRatio||parseFloat(window.devicePixelRatio),t.canvas);if(!w)if(w=document.createElement("canvas"),t.container){var A=t.container;A.appendChild(w)}else document.body.appendChild(w);var k=t.gl;if(k||(k=i(w,t.glOptions||{premultipliedAlpha:!0,antialias:!0})),!k)throw new Error("webgl not supported");var M=t.bounds||[[-10,-10,-10],[10,10,10]],T=new n,E=d(k,[k.drawingBufferWidth,k.drawingBufferHeight],{preferFloat:!0}),L=m(k),S=t.camera||{eye:[2,0,0],center:[0,0,0],up:[0,1,0],zoomMin:.1,zoomMax:100,mode:"turntable"},C=t.axes||{},P=u(k,C);P.enable=!C.disable;var z=t.spikes||{},R=h(k,z),O=[],I=[],j=[],N=[],F=!0,B=!0,D=new Array(16),U=new Array(16),V={view:null,projection:D,model:U},B=!0,q=[k.drawingBufferWidth,k.drawingBufferHeight],H={gl:k,contextLost:!1,pixelRatio:t.pixelRatio||parseFloat(window.devicePixelRatio),canvas:w,selection:T,camera:l(w,S),axes:P,axesPixels:null,spikes:R,bounds:M,objects:O,shape:q,aspect:t.aspectRatio||[1,1,1],pickRadius:t.pickRadius||10,zNear:t.zNear||.01,zFar:t.zFar||1e3,fovy:t.fovy||Math.PI/4,clearColor:t.clearColor||[0,0,0,0],autoResize:o(t.autoResize),autoBounds:o(t.autoBounds),autoScale:!!t.autoScale,autoCenter:o(t.autoCenter),clipToBounds:o(t.clipToBounds),snapToData:!!t.snapToData,onselect:t.onselect||null,onrender:t.onrender||null,onclick:t.onclick||null,cameraParams:V,oncontextloss:null,mouseListener:null},G=[k.drawingBufferWidth/H.pixelRatio|0,k.drawingBufferHeight/H.pixelRatio|0];H.autoResize&&e(),window.addEventListener("resize",e),H.update=function(t){_||(t=t||{},F=!0,B=!0)},H.add=function(t){_||(t.axes=P,O.push(t),I.push(-1),F=!0,B=!0,r())},H.remove=function(t){if(!_){var e=O.indexOf(t);0>e||(O.splice(e,1),I.pop(),F=!0,B=!0,r())}},H.dispose=function(){if(!_&&(_=!0,window.removeEventListener("resize",e),w.removeEventListener("webglcontextlost",s),H.mouseListener.enabled=!1,!H.contextLost)){P.dispose(),R.dispose();for(var t=0;t<O.length;++t)O[t].dispose();E.dispose();for(var t=0;t<N.length;++t)N[t].dispose();L.dispose(),k=null,P=null,R=null,O=[]}};var Y=!1,X=0;H.mouseListener=g(w,function(t,e,r){if(!_){var n=N.length,i=O.length,a=T.object;T.distance=1/0,T.mouse[0]=e,T.mouse[1]=r,T.object=null,T.screen=null,T.dataCoordinate=T.dataPosition=null;var o=!1;if(t&&X)Y=!0;else{Y&&(B=!0),Y=!1;for(var s=0;n>s;++s){var l=N[s].query(e,G[1]-r-1,H.pickRadius);if(l){if(l.distance>T.distance)continue;for(var u=0;i>u;++u){var c=O[u];if(I[u]===s){var h=c.pick(l);h&&(T.buttons=t,T.screen=l.coord,T.distance=l.distance,T.object=c,T.index=h.distance,T.dataPosition=h.position,T.dataCoordinate=h.dataCoordinate,T.data=h,o=!0)}}}}}a&&a!==T.object&&(a.highlight&&a.highlight(null),F=!0),T.object&&(T.object.highlight&&T.object.highlight(T.data),F=!0),o=o||T.object!==a,o&&H.onselect&&H.onselect(T),1&t&&!(1&X)&&H.onclick&&H.onclick(T),X=t}}),w.addEventListener("webglcontextlost",s);var W=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],Z=[W[0].slice(),W[1].slice()];return x(),H.redraw=function(){_||(F=!0,b())},H}e.exports=s;var l=t("3d-view-controls"),u=t("gl-axes3d"),c=t("gl-axes3d/properties"),h=t("gl-spikes3d"),f=t("gl-select-static"),d=t("gl-fbo"),p=t("a-big-triangle"),g=t("mouse-change"),v=t("gl-mat4/perspective"),m=t("./lib/shader")},{"./lib/shader":123,"3d-view-controls":124,"a-big-triangle":126,"gl-axes3d":127,"gl-axes3d/properties":137,"gl-fbo":80,"gl-mat4/perspective":97,"gl-select-static":153,"gl-spikes3d":139,"mouse-change":196}],141:[function(t,e,r){"use strict";e.exports={vertex:"#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 color;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n  vec3 xposition = view * vec3(position, 1.0);\n  return vec4(\n    xposition.xy + scale * offset * xposition.z,\n    0,\n    xposition.z);\n}\n\n\n\n\nvoid main() {\n  fragColor = color;\n\n  gl_Position = computePosition_1_0(\n    position,\n    offset,\n    viewTransform,\n    pixelScale);\n}\n",fragment:"#define GLSLIFY 1\nprecision lowp float;\nvarying vec4 fragColor;\nvoid main() {\n  gl_FragColor = vec4(fragColor.rgb * fragColor.a, fragColor.a);\n}\n",pickVertex:"#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 position;\nattribute vec2 offset;\nattribute vec4 id;\n\nuniform mat3 viewTransform;\nuniform vec2 pixelScale;\nuniform vec4 pickOffset;\n\nvarying vec4 fragColor;\n\nvec4 computePosition_1_0(vec2 position, vec2 offset, mat3 view, vec2 scale) {\n  vec3 xposition = view * vec3(position, 1.0);\n  return vec4(\n    xposition.xy + scale * offset * xposition.z,\n    0,\n    xposition.z);\n}\n\n\n\n\nvoid main() {\n  vec4 fragId = id + pickOffset;\n\n  fragId.y += floor(fragId.x / 256.0);\n  fragId.x -= floor(fragId.x / 256.0) * 256.0;\n\n  fragId.z += floor(fragId.y / 256.0);\n  fragId.y -= floor(fragId.y / 256.0) * 256.0;\n\n  fragId.w += floor(fragId.z / 256.0);\n  fragId.z -= floor(fragId.z / 256.0) * 256.0;\n\n  fragColor = fragId / 255.0;\n\n  gl_Position = computePosition_1_0(\n    position,\n    offset,\n    viewTransform,\n    pixelScale);\n}\n",pickFragment:"#define GLSLIFY 1\nprecision lowp float;\nvarying vec4 fragColor;\nvoid main() {\n  gl_FragColor = fragColor;\n}\n"}},{}],142:[function(t,e,r){"use strict";function n(t){if(t in f)return f[t];var e=c(t,{polygons:!0,font:"sans-serif",textAlign:"left",textBaseline:"alphabetic"}),r=[],n=[];e.forEach(function(t){t.forEach(function(t){for(var e=0;e<t.length;++e){var i=t[(e+t.length-1)%t.length],a=t[e],o=t[(e+1)%t.length],s=t[(e+2)%t.length],l=a[0]-i[0],u=a[1]-i[1],c=Math.sqrt(l*l+u*u);l/=c,u/=c,r.push(i[0],i[1]+1.4),n.push(u,-l),r.push(i[0],i[1]+1.4),n.push(-u,l),r.push(a[0],a[1]+1.4),n.push(-u,l),r.push(a[0],a[1]+1.4),n.push(-u,l),r.push(i[0],i[1]+1.4),n.push(u,-l),r.push(a[0],a[1]+1.4),n.push(u,-l);var h=s[0]-o[0],f=s[1]-o[1],d=Math.sqrt(h*h+f*f);h/=d,f/=d,r.push(a[0],a[1]+1.4),n.push(u,-l),r.push(a[0],a[1]+1.4),n.push(-u,l),r.push(o[0],o[1]+1.4),n.push(-f,h),r.push(o[0],o[1]+1.4),n.push(-f,h),r.push(a[0],a[1]+1.4),n.push(f,-h),r.push(o[0],o[1]+1.4),n.push(f,-h)}})});for(var i=[1/0,1/0,-(1/0),-(1/0)],a=0;a<r.length;a+=2)for(var o=0;2>o;++o)i[o]=Math.min(i[o],r[a+o]),i[2+o]=Math.max(i[2+o],r[a+o]);return f[t]={coords:r,normals:n,bounds:i}}function i(t,e,r,n,i,a,o){this.plot=t,this.shader=e,this.pickShader=r,this.positionBuffer=n,this.offsetBuffer=i,this.colorBuffer=a,this.idBuffer=o,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.numPoints=0,this.numVertices=0,this.pickOffset=0,this.points=null}function a(t,e){var r=t.gl,n=o(r,h.vertex,h.fragment),a=o(r,h.pickVertex,h.pickFragment),l=s(r),u=s(r),c=s(r),f=s(r),d=new i(t,n,a,l,u,c,f);return d.update(e),t.addObject(d),d}e.exports=a;var o=t("gl-shader"),s=t("gl-buffer"),l=t("text-cache"),u=t("typedarray-pool"),c=t("vectorize-text"),h=t("./lib/shaders"),f={},d=i.prototype;!function(){function t(){var t=this.plot,n=this.bounds,i=t.viewBox,a=t.dataBox,o=t.pixelRatio,s=n[2]-n[0],l=n[3]-n[1],u=a[2]-a[0],c=a[3]-a[1];e[0]=2*s/u,e[4]=2*l/c,e[6]=2*(n[0]-a[0])/u-1,e[7]=2*(n[1]-a[1])/c-1;var h=i[2]-i[0],f=i[3]-i[1];r[0]=2*o/h,r[1]=2*o/f}var e=[1,0,0,0,1,0,0,0,1],r=[1,1];d.draw=function(){var n=this.plot,i=this.shader,a=this.numVertices,o=n.gl;t.call(this),i.bind(),i.uniforms.pixelScale=r,i.uniforms.viewTransform=e,this.positionBuffer.bind(),i.attributes.position.pointer(),this.offsetBuffer.bind(),i.attributes.offset.pointer(),this.colorBuffer.bind(),i.attributes.color.pointer(o.UNSIGNED_BYTE,!0),o.drawArrays(o.TRIANGLES,0,a)};var n=[0,0,0,0];d.drawPick=function(i){var a=this.plot,o=this.pickShader,s=this.numVertices,l=a.gl;this.pickOffset=i;for(var u=0;4>u;++u)n[u]=i>>8*u&255;return t.call(this),o.bind(),o.uniforms.pixelScale=r,o.uniforms.viewTransform=e,o.uniforms.pickOffset=n,this.positionBuffer.bind(),o.attributes.position.pointer(),this.offsetBuffer.bind(),o.attributes.offset.pointer(),this.idBuffer.bind(),o.attributes.id.pointer(l.UNSIGNED_BYTE,!1),l.drawArrays(l.TRIANGLES,0,s),i+this.numPoints}}(),d.pick=function(t,e,r){var n=this.pickOffset,i=this.numPoints;if(n>r||r>=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}},d.update=function(t){t=t||{};var e=t.positions||[],r=t.colors||[],i=t.glyphs||[],a=t.sizes||[],o=t.borderWidths||[],s=t.borderColors||[];this.points=e;for(var c=this.bounds=[1/0,1/0,-(1/0),-(1/0)],h=0,f=0;f<i.length;++f){h+=l("sans-serif",i[f]).data.length+n(i[f]).coords.length>>1;for(var d=0;2>d;++d)c[d]=Math.min(c[d],e[2*f+d]),c[2+d]=Math.max(c[2+d],e[2*f+d])}c[0]===c[2]&&(c[2]+=1),c[3]===c[1]&&(c[3]+=1);for(var p=1/(c[2]-c[0]),g=1/(c[3]-c[1]),v=c[0],m=c[1],y=u.mallocFloat32(2*h),b=u.mallocFloat32(2*h),x=u.mallocUint8(4*h),_=u.mallocUint32(h),w=0,f=0;f<i.length;++f){for(var A=l("sans-serif",i[f]),k=n(i[f]),M=p*(e[2*f]-v),T=g*(e[2*f+1]-m),E=a[f],L=255*r[4*f],S=255*r[4*f+1],C=255*r[4*f+2],P=255*r[4*f+3],z=.5*(k.bounds[0]+k.bounds[2]),R=.5*(k.bounds[1]+k.bounds[3]),d=0;d<A.data.length;d+=2)y[2*w]=M,y[2*w+1]=T,b[2*w]=-E*(A.data[d]-z),b[2*w+1]=-E*(A.data[d+1]-R),x[4*w]=L,x[4*w+1]=S,x[4*w+2]=C,x[4*w+3]=P,_[w]=f,w+=1;var O=o[f];L=255*s[4*f],S=255*s[4*f+1],C=255*s[4*f+2],P=255*s[4*f+3];for(var d=0;d<k.coords.length;d+=2)y[2*w]=M,y[2*w+1]=T,b[2*w]=-(E*(k.coords[d]-z)+O*k.normals[d]),b[2*w+1]=-(E*(k.coords[d+1]-R)+O*k.normals[d+1]),x[4*w]=L,x[4*w+1]=S,x[4*w+2]=C,x[4*w+3]=P,_[w]=f,w+=1}this.numPoints=i.length,this.numVertices=h,this.positionBuffer.update(y),this.offsetBuffer.update(b),this.colorBuffer.update(x),this.idBuffer.update(_),u.free(y),u.free(b),u.free(x),u.free(_)},d.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.positionBuffer.dispose(),this.offsetBuffer.dispose(),this.colorBuffer.dispose(),this.idBuffer.dispose(),this.plot.removeObject(this)}},{"./lib/shaders":141,"gl-buffer":75,"gl-shader":154,"text-cache":228,"typedarray-pool":233,"vectorize-text":235}],143:[function(t,e,r){r.pointVertex="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 position;\nattribute float weight;\n\nuniform mat3 matrix;\nuniform float pointSize, useWeight;\n\nvarying float fragWeight;\n\nvoid main() {\n  vec3 hgPosition = matrix * vec3(position, 1);\n  gl_Position  = vec4(hgPosition.xy, 0, hgPosition.z);\n  gl_PointSize = pointSize;\n  fragWeight = mix(1.0, weight, useWeight);\n}\n",r.pointFragment="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 color, borderColor;\nuniform float centerFraction;\n\nvarying float fragWeight;\n\nfloat smoothStep(float x, float y) {\n  return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n  float radius = length(2.0*gl_PointCoord.xy-1.0);\n  if(radius > 1.0) {\n    discard;\n  }\n  vec4 baseColor = mix(borderColor, color, smoothStep(radius, centerFraction));\n  float alpha = 1.0 - pow(1.0 - baseColor.a, fragWeight);\n  gl_FragColor = vec4(baseColor.rgb * alpha, alpha);\n}\n",r.pickVertex="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 position;\nattribute vec4 pickId;\n\nuniform mat3 matrix;\nuniform float pointSize;\nuniform vec4 pickOffset;\n\nvarying vec4 fragId;\n\nvoid main() {\n  vec3 hgPosition = matrix * vec3(position, 1);\n  gl_Position  = vec4(hgPosition.xy, 0, hgPosition.z);\n  gl_PointSize = pointSize;\n\n  vec4 id = pickId + pickOffset;\n  id.y += floor(id.x / 256.0);\n  id.x -= floor(id.x / 256.0) * 256.0;\n\n  id.z += floor(id.y / 256.0);\n  id.y -= floor(id.y / 256.0) * 256.0;\n\n  id.w += floor(id.z / 256.0);\n  id.z -= floor(id.z / 256.0) * 256.0;\n\n  fragId = id;\n}\n",r.pickFragment="#define GLSLIFY 1\nprecision mediump float;\n\nvarying vec4 fragId;\n\nvoid main() {\n  float radius = length(2.0*gl_PointCoord.xy-1.0);\n  if(radius > 1.0) {\n    discard;\n  }\n  gl_FragColor = fragId / 255.0;\n}\n"},{}],144:[function(t,e,r){arguments[4][121][0].apply(r,arguments)},{dup:121}],145:[function(t,e,r){"use strict";function n(t,e,r,n,a){4*f>=a?i(0,a-1,t,e,r,n):h(0,a-1,t,e,r,n)}function i(t,e,r,n,i,a){for(var o=t+1;e>=o;++o){for(var s=r[o],l=n[2*o],u=n[2*o+1],c=i[o],h=a[o],f=o;f>t;){var d=r[f-1],p=n[2*(f-1)];if((d-s||l-p)>=0)break;r[f]=d,n[2*f]=p,n[2*f+1]=n[2*f-1],i[f]=i[f-1],a[f]=a[f-1],f-=1}r[f]=s,n[2*f]=l,n[2*f+1]=u,i[f]=c,a[f]=h}}function a(t,e,r,n,i,a){var o=r[t],s=n[2*t],l=n[2*t+1],u=i[t],c=a[t];r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e],r[e]=o,n[2*e]=s,n[2*e+1]=l,i[e]=u,a[e]=c}function o(t,e,r,n,i,a){r[t]=r[e],n[2*t]=n[2*e],n[2*t+1]=n[2*e+1],i[t]=i[e],a[t]=a[e]}function s(t,e,r,n,i,a,o){var s=n[t],l=i[2*t],u=i[2*t+1],c=a[t],h=o[t];n[t]=n[e],i[2*t]=i[2*e],i[2*t+1]=i[2*e+1],a[t]=a[e],o[t]=o[e],n[e]=n[r],i[2*e]=i[2*r],i[2*e+1]=i[2*r+1],a[e]=a[r],o[e]=o[r],n[r]=s,i[2*r]=l,i[2*r+1]=u,a[r]=c,o[r]=h}function l(t,e,r,n,i,a,o,s,l,u,c){s[t]=s[e],l[2*t]=l[2*e],l[2*t+1]=l[2*e+1],u[t]=u[e],c[t]=c[e],s[e]=r,l[2*e]=n,l[2*e+1]=i,u[e]=a,c[e]=o}function u(t,e,r,n,i){return(r[t]-r[e]||n[2*e]-n[2*t]||i[t]-i[e])<0}function c(t,e,r,n,i,a,o,s){return(e-a[t]||o[2*t]-r||i-s[t])<0}function h(t,e,r,n,d,p){var g=(e-t+1)/6|0,v=t+g,m=e-g,y=t+e>>1,b=y-g,x=y+g,_=v,w=b,A=y,k=x,M=m,T=t+1,E=e-1,L=0;u(_,w,r,n,d,p)&&(L=_,_=w,w=L),u(k,M,r,n,d,p)&&(L=k,k=M,M=L),u(_,A,r,n,d,p)&&(L=_,_=A,A=L),u(w,A,r,n,d,p)&&(L=w,w=A,A=L),u(_,k,r,n,d,p)&&(L=_,_=k,k=L),u(A,k,r,n,d,p)&&(L=A,A=k,k=L),u(w,M,r,n,d,p)&&(L=w,w=M,M=L),u(w,A,r,n,d,p)&&(L=w,w=A,A=L),u(k,M,r,n,d,p)&&(L=k,k=M,M=L);var S=r[w],C=n[2*w],P=n[2*w+1],z=d[w],R=p[w],O=r[k],I=n[2*k],j=n[2*k+1],N=d[k],F=p[k],B=_,D=A,U=M,V=v,q=y,H=m,G=r[B],Y=r[D],X=r[U];r[V]=G,r[q]=Y,r[H]=X;for(var W=0;2>W;++W){var Z=n[2*B+W],$=n[2*D+W],K=n[2*U+W];n[2*V+W]=Z,n[2*q+W]=$,n[2*H+W]=K}var Q=d[B],J=d[D],tt=d[U];d[V]=Q,d[q]=J,d[H]=tt;var et=p[B],rt=p[D],nt=p[U];p[V]=et,p[q]=rt,p[H]=nt,o(b,t,r,n,d,p),o(x,e,r,n,d,p);for(var it=T;E>=it;++it)if(c(it,S,C,P,z,r,n,d))it!==T&&a(it,T,r,n,d,p),++T;else if(!c(it,O,I,j,N,r,n,d))for(;;){if(c(E,O,I,j,N,r,n,d)){c(E,S,C,P,z,r,n,d)?(s(it,T,E,r,n,d,p),++T,--E):(a(it,E,r,n,d,p),--E);break}if(--E<it)break}l(t,T-1,S,C,P,z,R,r,n,d,p),l(e,E+1,O,I,j,N,F,r,n,d,p),f>=T-2-t?i(t,T-2,r,n,d,p):h(t,T-2,r,n,d,p),f>=e-(E+2)?i(E+2,e,r,n,d,p):h(E+2,e,r,n,d,p),f>=E-T?i(T,E,r,n,d,p):h(T,E,r,n,d,p)}e.exports=n;var f=32},{}],146:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o,s){for(var l=r,u=r;n>u;++u){var c=t[2*u],h=t[2*u+1],f=e[u];c>=i&&o>=c&&h>=a&&s>=h&&(u===l?l+=1:(t[2*u]=t[2*l],t[2*u+1]=t[2*l+1],e[u]=e[l],t[2*l]=c,t[2*l+1]=h,e[l]=f,l+=1))}return l}function i(t,e,r){this.pixelSize=t,this.offset=e,this.count=r}function a(t,e,r,a){function l(i,a,o,s,u,c){var h=.5*o,f=s+1,d=u-s;r[_]=d,x[_++]=c;for(var p=0;2>p;++p)for(var g=0;2>g;++g){var v=i+p*h,m=a+g*h,y=n(t,e,f,u,v,m,v+h,m+h);if(y!==f){if(y-f>=Math.max(.9*d,32)){var b=u+s>>>1;l(v,m,h,f,b,c+1),f=b}l(v,m,h,f,y,c+1),f=y}}}var u=t.length>>>1;if(1>u)return[];for(var c=1/0,h=1/0,f=-(1/0),d=-(1/0),p=0;u>p;++p){var g=t[2*p],v=t[2*p+1];c=Math.min(c,g),f=Math.max(f,g),h=Math.min(h,v),d=Math.max(d,v),e[p]=p}c===f&&(f+=1+Math.abs(f)),h===d&&(d+=1+Math.abs(f));var m=1/(f-c),y=1/(d-h),b=Math.max(f-c,d-h);a=a||[0,0,0,0],a[0]=c,a[1]=h,a[2]=f,a[3]=d;var x=o.mallocInt32(u),_=0;l(c,h,b,0,u,0),s(x,t,e,r,u);for(var w=[],A=0,k=u,_=u-1;_>=0;--_){t[2*_]=(t[2*_]-c)*m,t[2*_+1]=(t[2*_+1]-h)*y;var M=x[_];M!==A&&(w.push(new i(b*Math.pow(.5,M),_+1,k-(_+1))),k=_+1,A=M)}return w.push(new i(b*Math.pow(.5,M+1),0,k)),o.free(x),w}var o=t("typedarray-pool"),s=t("./lib/sort");e.exports=a},{"./lib/sort":145,"typedarray-pool":233}],147:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this.plot=t,this.offsetBuffer=e,this.pickBuffer=r,this.weightBuffer=n,this.shader=i,this.pickShader=a,this.scales=[],this.size=12,this.borderSize=1,this.pointCount=0,this.color=[1,0,0,1],this.borderColor=[0,0,0,1],this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.pickOffset=0,this.points=null,this.xCoords=null}function i(t,e){var r=t.gl,i=o(r),s=o(r),l=o(r),u=a(r,c.pointVertex,c.pointFragment),h=a(r,c.pickVertex,c.pickFragment),f=new n(t,i,s,l,u,h);return f.update(e),t.addObject(f),f}var a=t("gl-shader"),o=t("gl-buffer"),s=t("binary-search-bounds"),l=t("snap-points-2d"),u=t("typedarray-pool"),c=t("./lib/shader");e.exports=i;var h=n.prototype;h.dispose=function(){this.shader.dispose(),this.pickShader.dispose(),this.offsetBuffer.dispose(),this.pickBuffer.dispose(),this.xCoords&&u.free(this.xCoords),this.plot.removeObject(this)},h.update=function(t){function e(e,r){return e in t?t[e]:r}t=t||{},this.size=e("size",12),this.color=e("color",[1,0,0,1]).slice(),this.borderSize=e("borderSize",1),this.borderColor=e("borderColor",[0,0,0,1]).slice(),this.xCoords&&u.free(this.xCoords);var r=t.positions,n=u.mallocFloat32(r.length),i=u.mallocInt32(r.length>>>1);n.set(r);var a=u.mallocFloat32(r.length);this.points=r,this.scales=l(n,i,a,this.bounds),this.offsetBuffer.update(n),this.pickBuffer.update(i),this.weightBuffer.update(a);for(var o=u.mallocFloat32(r.length>>>1),s=0,c=0;s<r.length;s+=2,++c)o[c]=n[s];u.free(i),u.free(n),u.free(a),this.xCoords=o,this.pointCount=r.length>>>1,this.pickOffset=0},h.drawPick=function(){var t=[1,0,0,0,1,0,0,0,1],e=[0,0,0,0];return function(r){var n=this.plot,i=this.pickShader,a=this.scales,o=this.offsetBuffer,l=this.pickBuffer,u=this.bounds,c=this.size,h=this.borderSize,f=n.gl,d=n.pickPixelRatio,p=n.viewBox,g=n.dataBox;if(0===this.pointCount)return r;var v=u[2]-u[0],m=u[3]-u[1],y=g[2]-g[0],b=g[3]-g[1],x=(p[2]-p[0])*d/n.pixelRatio,_=(p[3]-p[1])*d/n.pixelRatio,w=Math.min(y/x,b/_);t[0]=2*v/y,t[4]=2*m/b,t[6]=2*(u[0]-g[0])/y-1,t[7]=2*(u[1]-g[1])/b-1,this.pickOffset=r,e[0]=255&r,e[1]=r>>8&255,e[2]=r>>16&255,e[3]=r>>24&255,i.bind(),i.uniforms.matrix=t,i.uniforms.color=this.color,i.uniforms.borderColor=this.borderColor,i.uniforms.pointSize=d*(c+h),i.uniforms.pickOffset=e,0===this.borderSize?i.uniforms.centerFraction=2:i.uniforms.centerFraction=c/(c+h+1.25),o.bind(),i.attributes.position.pointer(),l.bind(),i.attributes.pickId.pointer(f.UNSIGNED_BYTE);for(var A=this.xCoords,k=(g[0]-u[0]-w*c*d)/v,M=(g[2]-u[0]+w*c*d)/v,T=a.length-1;T>=0;--T){var E=a[T];if(!(E.pixelSize<w&&T>1)){var L=E.offset,S=E.count+L,C=s.ge(A,k,L,S-1),P=s.lt(A,M,C,S-1)+1;f.drawArrays(f.POINTS,C,P-C)}}return r+this.pointCount}}(),h.draw=function(){var t=[1,0,0,0,1,0,0,0,1];return function(){var e=this.plot,r=this.shader,n=this.scales,i=this.offsetBuffer,a=this.bounds,o=this.size,l=this.borderSize,u=e.gl,c=e.pixelRatio,h=e.viewBox,f=e.dataBox;if(0!==this.pointCount){var d=a[2]-a[0],p=a[3]-a[1],g=f[2]-f[0],v=f[3]-f[1],m=h[2]-h[0],y=h[3]-h[1],b=Math.min(g/m,v/y);t[0]=2*d/g,t[4]=2*p/v,t[6]=2*(a[0]-f[0])/g-1,t[7]=2*(a[1]-f[1])/v-1,r.bind(),r.uniforms.matrix=t,r.uniforms.color=this.color,r.uniforms.borderColor=this.borderColor,r.uniforms.pointSize=c*(o+l),r.uniforms.useWeight=1,0===this.borderSize?r.uniforms.centerFraction=2:r.uniforms.centerFraction=o/(o+l+1.25),i.bind(),r.attributes.position.pointer(),this.weightBuffer.bind(),r.attributes.weight.pointer();for(var x=this.xCoords,_=(f[0]-a[0]-b*o*c)/d,w=(f[2]-a[0]+b*o*c)/d,A=!0,k=n.length-1;k>=0;--k){var M=n[k];if(!(M.pixelSize<b&&k>1)){var T=M.offset,E=M.count+T,L=s.ge(x,_,T,E-1),S=s.lt(x,w,L,E-1)+1;u.drawArrays(u.POINTS,L,S-L),A&&(A=!1,r.uniforms.useWeight=0)}}}}}(),h.pick=function(t,e,r){var n=this.pickOffset,i=this.pointCount;if(n>r||r>=n+i)return null;var a=r-n,o=this.points;return{object:this,pointId:a,dataCoord:[o[2*a],o[2*a+1]]}}},{"./lib/shader":143,"binary-search-bounds":144,"gl-buffer":75,"gl-shader":154,"snap-points-2d":146,"typedarray-pool":233}],148:[function(t,e,r){"use strict";function n(t,e){var r=a[e];if(r||(r=a[e]={}),t in r)return r[t];for(var n=i(t,{textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),o=i(t,{triangles:!0,textAlign:"center",textBaseline:"middle",lineHeight:1,font:e}),s=[[1/0,1/0],[-(1/0),-(1/0)]],l=0;l<n.positions.length;++l)for(var u=n.positions[l],c=0;2>c;++c)s[0][c]=Math.min(s[0][c],u[c]),s[1][c]=Math.max(s[1][c],u[c]);return r[t]=[o,n,s]}var i=t("vectorize-text");e.exports=n;var a={}},{"vectorize-text":235}],149:[function(t,e,r){function n(t,e){var r=i(t,e),n=r.attributes;return n.position.location=0,n.color.location=1,n.glyph.location=2,n.id.location=3,r}var i=t("gl-shader"),a="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\n\nuniform vec4 highlightId;\nuniform float highlightScale;\nuniform mat4 model, view, projection;\nuniform vec3 clipBounds[2];\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if(any(lessThan(position, clipBounds[0]))   || \n     any(greaterThan(position, clipBounds[1])) ) {\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float scale = 1.0;\n    if(distance(highlightId, id) < 0.0001) {\n      scale = highlightScale;\n    }\n\n    vec4 worldPosition = model * vec4(position, 1);\n    vec4 viewPosition = view * worldPosition;\n    viewPosition = viewPosition / viewPosition.w;\n    vec4 clipPosition = projection * (viewPosition + scale * vec4(glyph.x, -glyph.y, 0, 0));\n    \n    gl_Position = clipPosition;\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = position;\n  }\n}",o="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float highlightScale, pixelRatio;\nuniform vec4 highlightId;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if(any(lessThan(position, clipBounds[0])) || any(greaterThan(position, clipBounds[1]))) {\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float scale = pixelRatio;\n    if(distance(highlightId.bgr, id.bgr) < 0.001) {\n      scale *= highlightScale;\n    }\n\n    vec4 worldPosition = model * vec4(position, 1.0);\n    vec4 viewPosition = view * worldPosition;\n    vec4 clipPosition = projection * viewPosition;\n    clipPosition /= clipPosition.w;\n    \n    gl_Position = clipPosition + vec4(screenSize * scale * vec2(glyph.x, -glyph.y), 0.0, 0.0);\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = position;\n  }\n}",s="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec2 glyph;\nattribute vec4 id;\n\nuniform float highlightScale;\nuniform vec4 highlightId;\nuniform vec3 axes[2];\nuniform mat4 model, view, projection;\nuniform vec2 screenSize;\nuniform vec3 clipBounds[2];\nuniform float scale, pixelRatio;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if(any(lessThan(position, clipBounds[0]))   ||\n     any(greaterThan(position, clipBounds[1])) ) {\n    gl_Position = vec4(0,0,0,0);\n  } else {\n    float lscale = pixelRatio * scale;\n    if(distance(highlightId, id) < 0.0001) {\n      lscale *= highlightScale;\n    }\n\n    vec4 clipCenter   = projection * view * model * vec4(position, 1);\n    vec3 dataPosition = position + 0.5*lscale*(axes[0] * glyph.x + axes[1] * glyph.y) * clipCenter.w * screenSize.y;\n    vec4 clipPosition = projection * view * model * vec4(dataPosition, 1);\n\n    gl_Position = clipPosition;\n    interpColor = color;\n    pickId = id;\n    dataCoordinate = dataPosition;\n  }\n}\n",l="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec3 fragClipBounds[2];\nuniform float opacity;\n\nvarying vec4 interpColor;\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if(any(lessThan(dataCoordinate, fragClipBounds[0]))   ||\n     any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n    discard;\n  } else {\n    gl_FragColor = interpColor * opacity;\n  }\n}\n",u="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec3 fragClipBounds[2];\nuniform float pickGroup;\n\nvarying vec4 pickId;\nvarying vec3 dataCoordinate;\n\nvoid main() {\n  if(any(lessThan(dataCoordinate, fragClipBounds[0]))   || \n     any(greaterThan(dataCoordinate, fragClipBounds[1])) ) {\n    discard;\n  } else {\n    gl_FragColor = vec4(pickGroup, pickId.bgr);\n  }\n}",c=[{name:"position",type:"vec3"},{name:"color",type:"vec4"},{name:"glyph",type:"vec2"},{name:"id",type:"vec4"}],h={vertex:a,fragment:l,attributes:c},f={vertex:o,fragment:l,attributes:c},d={vertex:s,fragment:l,attributes:c},p={vertex:a,fragment:u,attributes:c},g={vertex:o,fragment:u,attributes:c},v={vertex:s,fragment:u,attributes:c};r.createPerspective=function(t){return n(t,h)},r.createOrtho=function(t){return n(t,f)},r.createProject=function(t){return n(t,d)},r.createPickPerspective=function(t){return n(t,p)},r.createPickOrtho=function(t){return n(t,g)},r.createPickProject=function(t){return n(t,v)}},{"gl-shader":154}],150:[function(t,e,r){"use strict";function n(t,e){var r=t[0],n=t[1],i=t[2],a=t[3];return t[0]=e[0]*r+e[4]*n+e[8]*i+e[12]*a,t[1]=e[1]*r+e[5]*n+e[9]*i+e[13]*a,t[2]=e[2]*r+e[6]*n+e[10]*i+e[14]*a,t[3]=e[3]*r+e[7]*n+e[11]*i+e[15]*a,t}function i(t,e,r,i){return n(i,i,r),n(i,i,e),n(i,i,t)}function a(t,e){this.index=t,this.dataCoordinate=this.position=e}function o(t,e,r,n,i,o,s,l,u,c,h,f){this.gl=t,this.pixelRatio=1,this.shader=e,this.orthoShader=r,this.projectShader=n,this.pointBuffer=i,this.colorBuffer=o,this.glyphBuffer=s,this.idBuffer=l,this.vao=u,this.vertexCount=0,this.lineVertexCount=0,this.opacity=1,this.lineWidth=0,this.projectScale=[2/3,2/3,2/3],this.projectOpacity=[1,1,1],this.pickId=0,this.pickPerspectiveShader=c,this.pickOrthoShader=h,this.pickProjectShader=f,this.points=[],this._selectResult=new a(0,[0,0,0]),this.useOrtho=!0,this.bounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.axesProject=[!0,!0,!0],this.axesBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.highlightId=[1,1,1,1],this.highlightScale=2,this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.dirty=!0}function s(t){return t[0]=t[1]=t[2]=0,t}function l(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t}function u(t,e,r,n){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[r]=n,t}function c(t){for(var e=S,r=0;2>r;++r)for(var n=0;3>n;++n)e[r][n]=Math.max(Math.min(t[r][n],1e8),-1e8);return e}function h(t,e,r,n,a){var o,h=e.axesProject,f=e.gl,d=t.uniforms,p=r.model||x,g=r.view||x,v=r.projection||x,y=e.axesBounds,b=c(e.clipBounds);o=e.axes?e.axes.lastCubeProps.axis:[1,1,1],w[0]=2/f.drawingBufferWidth,w[1]=2/f.drawingBufferHeight,t.bind(),d.view=g,d.projection=v,d.screenSize=w,d.highlightId=e.highlightId,d.highlightScale=e.highlightScale,d.clipBounds=b,d.pickGroup=e.pickId/255,d.pixelRatio=e.pixelRatio;for(var _=0;3>_;++_)if(h[_]&&e.projectOpacity[_]<1===n){d.scale=e.projectScale[_],d.opacity=e.projectOpacity[_];for(var S=E,C=0;16>C;++C)S[C]=0;for(var C=0;4>C;++C)S[5*C]=1;S[5*_]=0,o[_]<0?S[12+_]=y[0][_]:S[12+_]=y[1][_],m(S,p,S),d.model=S;var P=(_+1)%3,z=(_+2)%3,R=s(A),O=s(k);R[P]=1,O[z]=1;var I=i(v,g,p,l(M,R)),j=i(v,g,p,l(T,O));if(Math.abs(I[1])>Math.abs(j[1])){var N=I;I=j,j=N,N=R,R=O,O=N;var F=P;P=z,z=F;
+}I[0]<0&&(R[P]=-1),j[1]>0&&(O[z]=-1);for(var B=0,D=0,C=0;4>C;++C)B+=Math.pow(p[4*P+C],2),D+=Math.pow(p[4*z+C],2);R[P]/=Math.sqrt(B),O[z]/=Math.sqrt(D),d.axes[0]=R,d.axes[1]=O,d.fragClipBounds[0]=u(L,b[0],_,-1e8),d.fragClipBounds[1]=u(L,b[1],_,1e8),e.vao.draw(f.TRIANGLES,e.vertexCount),e.lineWidth>0&&(f.lineWidth(e.lineWidth),e.vao.draw(f.LINES,e.lineVertexCount,e.vertexCount))}}function f(t,e,r,n,i,a){var o=r.gl;if(r.vao.bind(),i===r.opacity<1||a){t.bind();var s=t.uniforms;s.model=n.model||x,s.view=n.view||x,s.projection=n.projection||x,w[0]=2/o.drawingBufferWidth,w[1]=2/o.drawingBufferHeight,s.screenSize=w,s.highlightId=r.highlightId,s.highlightScale=r.highlightScale,s.fragClipBounds=z,s.clipBounds=r.axes.bounds,s.opacity=r.opacity,s.pickGroup=r.pickId/255,s.pixelRatio=r.pixelRatio,r.vao.draw(o.TRIANGLES,r.vertexCount),r.lineWidth>0&&(o.lineWidth(r.lineWidth),r.vao.draw(o.LINES,r.lineVertexCount,r.vertexCount))}h(e,r,n,i,a),r.vao.unbind()}function d(t){var e=t.gl,r=y.createPerspective(e),n=y.createOrtho(e),i=y.createProject(e),a=y.createPickPerspective(e),s=y.createPickOrtho(e),l=y.createPickProject(e),u=p(e),c=p(e),h=p(e),f=p(e),d=g(e,[{buffer:u,size:3,type:e.FLOAT},{buffer:c,size:4,type:e.FLOAT},{buffer:h,size:2,type:e.FLOAT},{buffer:f,size:4,type:e.UNSIGNED_BYTE,normalized:!0}]),v=new o(e,r,n,i,u,c,h,f,d,a,s,l);return v.update(t),v}var p=t("gl-buffer"),g=t("gl-vao"),v=t("typedarray-pool"),m=t("gl-mat4/multiply"),y=t("./lib/shaders"),b=t("./lib/glyphs"),x=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];e.exports=d;var _=o.prototype;_.pickSlots=1,_.setPickBase=function(t){this.pickId=t},_.isTransparent=function(){if(this.opacity<1)return!0;for(var t=0;3>t;++t)if(this.axesProject[t]&&this.projectOpacity[t]<1)return!0;return!1},_.isOpaque=function(){if(this.opacity>=1)return!0;for(var t=0;3>t;++t)if(this.axesProject[t]&&this.projectOpacity[t]>=1)return!0;return!1};var w=[0,0],A=[0,0,0],k=[0,0,0],M=[0,0,0,1],T=[0,0,0,1],E=x.slice(),L=[0,0,0],S=[[0,0,0],[0,0,0]],C=[-1e8,-1e8,-1e8],P=[1e8,1e8,1e8],z=[C,P];_.draw=function(t){var e=this.useOrtho?this.orthoShader:this.shader;f(e,this.projectShader,this,t,!1,!1)},_.drawTransparent=function(t){var e=this.useOrtho?this.orthoShader:this.shader;f(e,this.projectShader,this,t,!0,!1)},_.drawPick=function(t){var e=this.useOrtho?this.pickOrthoShader:this.pickPerspectiveShader;f(e,this.pickProjectShader,this,t,!1,!0)},_.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=t.value[2]+(t.value[1]<<8)+(t.value[0]<<16);if(e>=this.pointCount||0>e)return null;var r=this.points[e],n=this._selectResult;n.index=e;for(var i=0;3>i;++i)n.position[i]=n.dataCoordinate[i]=r[i];return n},_.highlight=function(t){if(t){var e=t.index,r=255&e,n=e>>8&255,i=e>>16&255;this.highlightId=[r/255,n/255,i/255,0]}else this.highlightId=[1,1,1,1]},_.update=function(t){if(t=t||{},"perspective"in t&&(this.useOrtho=!t.perspective),"orthographic"in t&&(this.useOrtho=!!t.orthographic),"lineWidth"in t&&(this.lineWidth=t.lineWidth),"project"in t)if(Array.isArray(t.project))this.axesProject=t.project;else{var e=!!t.project;this.axesProject=[e,e,e]}if("projectScale"in t)if(Array.isArray(t.projectScale))this.projectScale=t.projectScale.slice();else{var r=+t.projectScale;this.projectScale=[r,r,r]}if("projectOpacity"in t)if(Array.isArray(t.projectOpacity))this.projectOpacity=t.projectOpacity.slice();else{var r=+t.projectOpacity;this.projectOpacity=[r,r,r]}"opacity"in t&&(this.opacity=t.opacity),this.dirty=!0;var n=t.position;if(n){var i=t.font||"normal",a=t.alignment||[0,0],o=[1/0,1/0,1/0],s=[-(1/0),-(1/0),-(1/0)],l=t.glyph,u=t.color,c=t.size,h=t.angle,f=t.lineColor,d=0,p=0,g=0,m=n.length;t:for(var y=0;m>y;++y){for(var x=n[y],_=0;3>_;++_)if(isNaN(x[_])||!isFinite(x[_]))continue t;var w;w=Array.isArray(l)?b(l[y],i):l?b(l,i):b("\u25cf",i);var A=w[0],k=w[1],M=w[2];p+=3*A.cells.length,g+=2*k.edges.length}var T=p+g,E=v.mallocFloat(3*T),L=v.mallocFloat(4*T),S=v.mallocFloat(2*T),C=v.mallocUint32(T),P=[0,a[1]],z=0,R=p,O=[0,0,0,1],I=[0,0,0,1],j=Array.isArray(u)&&Array.isArray(u[0]),N=Array.isArray(f)&&Array.isArray(f[0]);t:for(var y=0;m>y;++y){for(var x=n[y],_=0;3>_;++_){if(isNaN(x[_])||!isFinite(x[_])){d+=1;continue t}s[_]=Math.max(s[_],x[_]),o[_]=Math.min(o[_],x[_])}var w;w=Array.isArray(l)?b(l[y],i):l?b(l,i):b("\u25cf",i);var A=w[0],k=w[1],M=w[2];if(Array.isArray(u)){var F;if(F=j?u[y]:u,3===F.length){for(var _=0;3>_;++_)O[_]=F[_];O[3]=1}else if(4===F.length)for(var _=0;4>_;++_)O[_]=F[_]}else O[0]=O[1]=O[2]=0,O[3]=1;if(Array.isArray(f)){var F;if(F=N?f[y]:f,3===F.length){for(var _=0;3>_;++_)I[_]=F[_];I[_]=1}else if(4===F.length)for(var _=0;4>_;++_)I[_]=F[_]}else I[0]=I[1]=I[2]=0,I[3]=1;var B=.5;Array.isArray(c)?B=+c[y]:c?B=+c:this.useOrtho&&(B=12);var D=0;Array.isArray(h)?D=+h[y]:h&&(D=+h);for(var U=Math.cos(D),V=Math.sin(D),x=n[y],_=0;3>_;++_)s[_]=Math.max(s[_],x[_]),o[_]=Math.min(o[_],x[_]);a[0]<0?P[0]=a[0]*(1+M[1][0]):a[0]>0&&(P[0]=-a[0]*(1+M[0][0]));for(var q=A.cells,H=A.positions,_=0;_<q.length;++_)for(var G=q[_],Y=0;3>Y;++Y){for(var X=0;3>X;++X)E[3*z+X]=x[X];for(var X=0;4>X;++X)L[4*z+X]=O[X];C[z]=d;var W=H[G[Y]];S[2*z]=B*(U*W[0]-V*W[1]+P[0]),S[2*z+1]=B*(V*W[0]+U*W[1]+P[1]),z+=1}for(var q=k.edges,H=k.positions,_=0;_<q.length;++_)for(var G=q[_],Y=0;2>Y;++Y){for(var X=0;3>X;++X)E[3*R+X]=x[X];for(var X=0;4>X;++X)L[4*R+X]=I[X];C[R]=d;var W=H[G[Y]];S[2*R]=B*(U*W[0]-V*W[1]+P[0]),S[2*R+1]=B*(V*W[0]+U*W[1]+P[1]),R+=1}d+=1}this.vertexCount=p,this.lineVertexCount=g,this.pointBuffer.update(E),this.colorBuffer.update(L),this.glyphBuffer.update(S),this.idBuffer.update(new Uint32Array(C)),v.free(E),v.free(L),v.free(S),v.free(C),this.bounds=[o,s],this.points=n,this.pointCount=n.length}},_.dispose=function(){this.shader.dispose(),this.orthoShader.dispose(),this.pickPerspectiveShader.dispose(),this.pickOrthoShader.dispose(),this.vao.dispose(),this.pointBuffer.dispose(),this.colorBuffer.dispose(),this.glyphBuffer.dispose(),this.idBuffer.dispose()}},{"./lib/glyphs":148,"./lib/shaders":149,"gl-buffer":75,"gl-mat4/multiply":96,"gl-vao":189,"typedarray-pool":233}],151:[function(t,e,r){"use strict";r.boxVertex="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec2 vertex;\n\nuniform vec2 cornerA, cornerB;\n\nvoid main() {\n  gl_Position = vec4(mix(cornerA, cornerB, vertex), 0, 1);\n}\n",r.boxFragment="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec4 color;\n\nvoid main() {\n  gl_FragColor = color;\n}\n"},{}],152:[function(t,e,r){"use strict";function n(t,e,r){this.plot=t,this.boxBuffer=e,this.boxShader=r,this.enabled=!0,this.selectBox=[1/0,1/0,-(1/0),-(1/0)],this.borderColor=[0,0,0,1],this.innerFill=!1,this.innerColor=[0,0,0,.25],this.outerFill=!0,this.outerColor=[0,0,0,.5],this.borderWidth=10}function i(t,e){var r=t.gl,i=o(r,[0,0,0,1,1,0,1,1]),l=a(r,s.boxVertex,s.boxFragment),u=new n(t,i,l);return u.update(e),t.addOverlay(u),u}var a=t("gl-shader"),o=t("gl-buffer"),s=t("./lib/shaders");e.exports=i;var l=n.prototype;l.draw=function(){if(this.enabled){var t=this.plot,e=this.selectBox,r=this.borderWidth,n=(this.innerFill,this.innerColor),i=(this.outerFill,this.outerColor),a=this.borderColor,o=t.box,s=t.screenBox,l=t.dataBox,u=t.viewBox,c=t.pixelRatio,h=(e[0]-l[0])*(u[2]-u[0])/(l[2]-l[0])+u[0],f=(e[1]-l[1])*(u[3]-u[1])/(l[3]-l[1])+u[1],d=(e[2]-l[0])*(u[2]-u[0])/(l[2]-l[0])+u[0],p=(e[3]-l[1])*(u[3]-u[1])/(l[3]-l[1])+u[1];if(h=Math.max(h,u[0]),f=Math.max(f,u[1]),d=Math.min(d,u[2]),p=Math.min(p,u[3]),!(h>d||f>p)){o.bind();var g=s[2]-s[0],v=s[3]-s[1];if(this.outerFill&&(o.drawBox(0,0,g,f,i),o.drawBox(0,f,h,p,i),o.drawBox(0,p,g,v,i),o.drawBox(d,f,g,p,i)),this.innerFill&&o.drawBox(h,f,d,p,n),r>0){var m=r*c;o.drawBox(h-m,f-m,d+m,f+m,a),o.drawBox(h-m,p-m,d+m,p+m,a),o.drawBox(h-m,f-m,h+m,p+m,a),o.drawBox(d-m,f-m,d+m,p+m,a)}}}},l.update=function(t){t=t||{},this.innerFill=!!t.innerFill,this.outerFill=!!t.outerFill,this.innerColor=(t.innerColor||[0,0,0,.5]).slice(),this.outerColor=(t.outerColor||[0,0,0,.5]).slice(),this.borderColor=(t.borderColor||[0,0,0,1]).slice(),this.borderWidth=t.borderWidth||0,this.selectBox=(t.selectBox||this.selectBox).slice()},l.dispose=function(){this.boxBuffer.dispose(),this.boxShader.dispose(),this.plot.removeOverlay(this)}},{"./lib/shaders":151,"gl-buffer":75,"gl-shader":154}],153:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.coord=[t,e],this.id=r,this.value=n,this.distance=i}function i(t,e,r){this.gl=t,this.fbo=e,this.buffer=r,this._readTimeout=null;var n=this;this._readCallback=function(){n.gl&&(e.bind(),t.readPixels(0,0,e.shape[0],e.shape[1],t.RGBA,t.UNSIGNED_BYTE,n.buffer),n._readTimeout=null)}}function a(t,e){var r=o(t,e),n=s.mallocUint8(e[0]*e[1]*4);return new i(t,r,n)}e.exports=a;var o=t("gl-fbo"),s=t("typedarray-pool"),l=t("ndarray"),u=t("bit-twiddle").nextPow2,c=t("cwise/lib/wrapper")({args:["array",{offset:[0,0,1],array:0},{offset:[0,0,2],array:0},{offset:[0,0,3],array:0},"scalar","scalar","index"],pre:{body:"{this_closestD2=1e8,this_closestX=-1,this_closestY=-1}",args:[],thisVars:["this_closestD2","this_closestX","this_closestY"],localVars:[]},body:{body:"{if(255>_inline_31_arg0_||255>_inline_31_arg1_||255>_inline_31_arg2_||255>_inline_31_arg3_){var _inline_31_l=_inline_31_arg4_-_inline_31_arg6_[0],_inline_31_a=_inline_31_arg5_-_inline_31_arg6_[1],_inline_31_f=_inline_31_l*_inline_31_l+_inline_31_a*_inline_31_a;_inline_31_f<this_closestD2&&(this_closestD2=_inline_31_f,this_closestX=_inline_31_arg6_[0],this_closestY=_inline_31_arg6_[1])}}",args:[{name:"_inline_31_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_31_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_31_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_31_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_31_arg4_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_31_arg5_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_31_arg6_",lvalue:!1,rvalue:!0,count:4}],thisVars:["this_closestD2","this_closestX","this_closestY"],localVars:["_inline_31_a","_inline_31_f","_inline_31_l"]},post:{body:"{return[this_closestX,this_closestY,this_closestD2]}",args:[],thisVars:["this_closestD2","this_closestX","this_closestY"],localVars:[]},debug:!1,funcName:"cwise",blockSize:64}),h=i.prototype;Object.defineProperty(h,"shape",{get:function(){return this.gl?this.fbo.shape.slice():[0,0]},set:function(t){if(this.gl){this.fbo.shape=t;var e=this.fbo.shape[0],r=this.fbo.shape[1];if(r*e*4>this.buffer.length){s.free(this.buffer);for(var n=this.buffer=s.mallocUint8(u(r*e*4)),i=0;r*e*4>i;++i)n[i]=255}return t}}}),h.begin=function(){var t=this.gl;this.shape;t&&(this.fbo.bind(),t.clearColor(1,1,1,1),t.clear(t.COLOR_BUFFER_BIT|t.DEPTH_BUFFER_BIT))},h.end=function(){var t=this.gl;t&&(t.bindFramebuffer(t.FRAMEBUFFER,null),this._readTimeout||clearTimeout(this._readTimeout),this._readTimeout=setTimeout(this._readCallback,1))},h.query=function(t,e,r){if(!this.gl)return null;var i=this.fbo.shape.slice();t=0|t,e=0|e,"number"!=typeof r&&(r=1);var a=0|Math.min(Math.max(t-r,0),i[0]),o=0|Math.min(Math.max(t+r,0),i[0]),s=0|Math.min(Math.max(e-r,0),i[1]),u=0|Math.min(Math.max(e+r,0),i[1]);if(a>=o||s>=u)return null;var h=[o-a,u-s],f=l(this.buffer,[h[0],h[1],4],[4,4*i[0],1],4*(a+i[0]*s)),d=c(f.hi(h[0],h[1],1),r,r),p=d[0],g=d[1];if(0>p||Math.pow(this.radius,2)<d[2])return null;var v=f.get(p,g,0),m=f.get(p,g,1),y=f.get(p,g,2),b=f.get(p,g,3);return new n(p+a|0,g+s|0,v,[m,y,b],Math.sqrt(d[2]))},h.dispose=function(){this.gl&&(this.fbo.dispose(),s.free(this.buffer),this.gl=null,this._readTimeout&&clearTimeout(this._readTimeout))}},{"bit-twiddle":49,"cwise/lib/wrapper":69,"gl-fbo":80,ndarray:208,"typedarray-pool":233}],154:[function(t,e,r){"use strict";function n(t){this.gl=t,this._vref=this._fref=this._relink=this.vertShader=this.fragShader=this.program=this.attributes=this.uniforms=this.types=null}function i(t,e){return t.name<e.name?-1:1}function a(t,e,r,i,a){var o=new n(t);return o.update(e,r,i,a),o}var o=t("./lib/create-uniforms"),s=t("./lib/create-attributes"),l=t("./lib/reflect"),u=t("./lib/shader-cache"),c=t("./lib/runtime-reflect"),h=t("./lib/GLError"),f=n.prototype;f.bind=function(){this.program||this._relink(),this.gl.useProgram(this.program)},f.dispose=function(){this._fref&&this._fref.dispose(),this._vref&&this._vref.dispose(),this.attributes=this.types=this.vertShader=this.fragShader=this.program=this._relink=this._fref=this._vref=null},f.update=function(t,e,r,n){function a(){d.program=u.program(p,d._vref,d._fref,x,_);for(var t=0;t<r.length;++t)L[t]=p.getUniformLocation(d.program,r[t].name)}if(!e||1===arguments.length){var f=t;t=f.vertex,e=f.fragment,r=f.uniforms,n=f.attributes}var d=this,p=d.gl,g=d._vref;d._vref=u.shader(p,p.VERTEX_SHADER,t),g&&g.dispose(),d.vertShader=d._vref.shader;var v=this._fref;if(d._fref=u.shader(p,p.FRAGMENT_SHADER,e),v&&v.dispose(),d.fragShader=d._fref.shader,!r||!n){var m=p.createProgram();if(p.attachShader(m,d.fragShader),p.attachShader(m,d.vertShader),p.linkProgram(m),!p.getProgramParameter(m,p.LINK_STATUS)){var y=p.getProgramInfoLog(m);throw new h(y,"Error linking program:"+y)}r=r||c.uniforms(p,m),n=n||c.attributes(p,m),p.deleteProgram(m)}n=n.slice(),n.sort(i);for(var b=[],x=[],_=[],w=0;w<n.length;++w){var A=n[w];if(A.type.indexOf("mat")>=0){for(var k=0|A.type.charAt(A.type.length-1),M=new Array(k),T=0;k>T;++T)M[T]=_.length,x.push(A.name+"["+T+"]"),"number"==typeof A.location?_.push(A.location+T):Array.isArray(A.location)&&A.location.length===k&&"number"==typeof A.location[T]?_.push(0|A.location[T]):_.push(-1);b.push({name:A.name,type:A.type,locations:M})}else b.push({name:A.name,type:A.type,locations:[_.length]}),x.push(A.name),"number"==typeof A.location?_.push(0|A.location):_.push(-1)}for(var E=0,w=0;w<_.length;++w)if(_[w]<0){for(;_.indexOf(E)>=0;)E+=1;_[w]=E}var L=new Array(r.length);a(),d._relink=a,d.types={uniforms:l(r),attributes:l(n)},d.attributes=s(p,d,b,_),Object.defineProperty(d,"uniforms",o(p,d,r,L))},e.exports=a},{"./lib/GLError":155,"./lib/create-attributes":156,"./lib/create-uniforms":157,"./lib/reflect":158,"./lib/runtime-reflect":159,"./lib/shader-cache":160}],155:[function(t,e,r){function n(t,e,r){this.shortMessage=e||"",this.longMessage=r||"",this.rawError=t||"",this.message="gl-shader: "+(e||t||"")+(r?"\n"+r:""),this.stack=(new Error).stack}n.prototype=new Error,n.prototype.name="GLError",n.prototype.constructor=n,e.exports=n},{}],156:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this._gl=t,this._wrapper=e,this._index=r,this._locations=n,this._dimension=i,this._constFunc=a}function i(t,e,r,i,a,o,s){for(var l=["gl","v"],u=[],c=0;a>c;++c)l.push("x"+c),u.push("x"+c);l.push("if(x0.length===void 0){return gl.vertexAttrib"+a+"f(v,"+u.join()+")}else{return gl.vertexAttrib"+a+"fv(v,x0)}");var h=Function.apply(null,l),f=new n(t,e,r,i,a,h);Object.defineProperty(o,s,{set:function(e){return t.disableVertexAttribArray(i[r]),h(t,i[r],e),e},get:function(){return f},enumerable:!0})}function a(t,e,r,n,a,o,s){for(var l=new Array(a),u=new Array(a),c=0;a>c;++c)i(t,e,r[c],n,a,l,c),u[c]=l[c];Object.defineProperty(l,"location",{set:function(t){if(Array.isArray(t))for(var e=0;a>e;++e)u[e].location=t[e];else for(var e=0;a>e;++e)u[e].location=t+e;return t},get:function(){for(var t=new Array(a),e=0;a>e;++e)t[e]=n[r[e]];return t},enumerable:!0}),l.pointer=function(e,i,o,s){e=e||t.FLOAT,i=!!i,o=o||a*a,s=s||0;for(var l=0;a>l;++l){var u=n[r[l]];t.vertexAttribPointer(u,a,e,i,o,s+l*a),t.enableVertexAttribArray(u)}};var h=new Array(a),f=t["vertexAttrib"+a+"fv"];Object.defineProperty(o,s,{set:function(e){for(var i=0;a>i;++i){var o=n[r[i]];if(t.disableVertexAttribArray(o),Array.isArray(e[0]))f.call(t,o,e[i]);else{for(var s=0;a>s;++s)h[s]=e[a*i+s];f.call(t,o,h)}}return e},get:function(){return l},enumerable:!0})}function o(t,e,r,n){for(var o={},l=0,u=r.length;u>l;++l){var c=r[l],h=c.name,f=c.type,d=c.locations;switch(f){case"bool":case"int":case"float":i(t,e,d[0],n,1,o,h);break;default:if(f.indexOf("vec")>=0){var p=f.charCodeAt(f.length-1)-48;if(2>p||p>4)throw new s("","Invalid data type for attribute "+h+": "+f);i(t,e,d[0],n,p,o,h)}else{if(!(f.indexOf("mat")>=0))throw new s("","Unknown data type for attribute "+h+": "+f);var p=f.charCodeAt(f.length-1)-48;if(2>p||p>4)throw new s("","Invalid data type for attribute "+h+": "+f);a(t,e,d,n,p,o,h)}}}return o}e.exports=o;var s=t("./GLError"),l=n.prototype;l.pointer=function(t,e,r,n){var i=this,a=i._gl,o=i._locations[i._index];a.vertexAttribPointer(o,i._dimension,t||a.FLOAT,!!e,r||0,n||0),a.enableVertexAttribArray(o)},l.set=function(t,e,r,n){return this._constFunc(this._locations[this._index],t,e,r,n)},Object.defineProperty(l,"location",{get:function(){return this._locations[this._index]},set:function(t){return t!==this._locations[this._index]&&(this._locations[this._index]=0|t,this._wrapper.program=null),0|t}})},{"./GLError":155}],157:[function(t,e,r){"use strict";function n(t){var e=new Function("y","return function(){return y}");return e(t)}function i(t,e){for(var r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function a(t,e,r,a){function l(r){var n=new Function("gl","wrapper","locations","return function(){return gl.getUniform(wrapper.program,locations["+r+"])}");return n(t,e,a)}function u(t,e,r){switch(r){case"bool":case"int":case"sampler2D":case"samplerCube":return"gl.uniform1i(locations["+e+"],obj"+t+")";case"float":return"gl.uniform1f(locations["+e+"],obj"+t+")";default:var n=r.indexOf("vec");if(!(n>=0&&1>=n&&r.length===4+n)){if(0===r.indexOf("mat")&&4===r.length){var i=r.charCodeAt(r.length-1)-48;if(2>i||i>4)throw new s("","Invalid uniform dimension type for matrix "+name+": "+r);return"gl.uniformMatrix"+i+"fv(locations["+e+"],false,obj"+t+")"}throw new s("","Unknown uniform data type for "+name+": "+r)}var i=r.charCodeAt(r.length-1)-48;if(2>i||i>4)throw new s("","Invalid data type");switch(r.charAt(0)){case"b":case"i":return"gl.uniform"+i+"iv(locations["+e+"],obj"+t+")";case"v":return"gl.uniform"+i+"fv(locations["+e+"],obj"+t+")";default:throw new s("","Unrecognized data type for vector "+name+": "+r)}}}function c(t,e){if("object"!=typeof e)return[[t,e]];var r=[];for(var n in e){var i=e[n],a=t;a+=parseInt(n)+""===n?"["+n+"]":"."+n,"object"==typeof i?r.push.apply(r,c(a,i)):r.push([a,i])}return r}function h(e){for(var n=["return function updateProperty(obj){"],i=c("",e),o=0;o<i.length;++o){var s=i[o],l=s[0],h=s[1];a[h]&&n.push(u(l,h,r[h].type))}n.push("return obj}");var f=new Function("gl","locations",n.join("\n"));return f(t,a)}function f(t){switch(t){case"bool":return!1;case"int":case"sampler2D":case"samplerCube":return 0;case"float":return 0;default:var e=t.indexOf("vec");if(e>=0&&1>=e&&t.length===4+e){var r=t.charCodeAt(t.length-1)-48;if(2>r||r>4)throw new s("","Invalid data type");return"b"===t.charAt(0)?i(r,!1):i(r,0)}if(0===t.indexOf("mat")&&4===t.length){var r=t.charCodeAt(t.length-1)-48;if(2>r||r>4)throw new s("","Invalid uniform dimension type for matrix "+name+": "+t);return i(r*r,0)}throw new s("","Unknown uniform data type for "+name+": "+t)}}function d(t,e,i){if("object"==typeof i){var o=p(i);Object.defineProperty(t,e,{get:n(o),set:h(i),enumerable:!0,configurable:!1})}else a[i]?Object.defineProperty(t,e,{get:l(i),set:h(i),enumerable:!0,configurable:!1}):t[e]=f(r[i].type)}function p(t){var e;if(Array.isArray(t)){e=new Array(t.length);for(var r=0;r<t.length;++r)d(e,r,t[r])}else{e={};for(var n in t)d(e,n,t[n])}return e}var g=o(r,!0);return{get:n(p(g)),set:h(g),enumerable:!0,configurable:!0}}var o=t("./reflect"),s=t("./GLError");e.exports=a},{"./GLError":155,"./reflect":158}],158:[function(t,e,r){"use strict";function n(t,e){for(var r={},n=0;n<t.length;++n)for(var i=t[n].name,a=i.split("."),o=r,s=0;s<a.length;++s){var l=a[s].split("[");if(l.length>1){l[0]in o||(o[l[0]]=[]),o=o[l[0]];for(var u=1;u<l.length;++u){var c=parseInt(l[u]);u<l.length-1||s<a.length-1?(c in o||(u<l.length-1?o[c]=[]:o[c]={}),o=o[c]):e?o[c]=n:o[c]=t[n].type}}else s<a.length-1?(l[0]in o||(o[l[0]]={}),o=o[l[0]]):e?o[l[0]]=n:o[l[0]]=t[n].type}return r}e.exports=n},{}],159:[function(t,e,r){"use strict";function n(t,e){if(!s){var r=Object.keys(o);s={};for(var n=0;n<r.length;++n){var i=r[n];s[t[i]]=o[i]}}return s[e]}function i(t,e){for(var r=t.getProgramParameter(e,t.ACTIVE_UNIFORMS),i=[],a=0;r>a;++a){var o=t.getActiveUniform(e,a);if(o){var s=n(t,o.type);if(o.size>1)for(var l=0;l<o.size;++l)i.push({name:o.name.replace("[0]","["+l+"]"),type:s});else i.push({name:o.name,type:s})}}return i}function a(t,e){for(var r=t.getProgramParameter(e,t.ACTIVE_ATTRIBUTES),i=[],a=0;r>a;++a){var o=t.getActiveAttrib(e,a);o&&i.push({name:o.name,type:n(t,o.type)})}return i}r.uniforms=i,r.attributes=a;var o={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube"},s=null},{}],160:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o){this.id=t,this.src=e,this.type=r,this.shader=n,this.count=a,this.programs=[],this.cache=o}function i(t){this.gl=t,this.shaders=[{},{}],this.programs={}}function a(t,e,r){var n=t.createShader(e);if(t.shaderSource(n,r),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS)){var i=t.getShaderInfoLog(n);try{var a=h(i,r,e)}catch(o){throw console.warn("Failed to format compiler error: "+o),new c(i,"Error compiling shader:\n"+i)}throw new c(i,a.short,a.long)}return n}function o(t,e,r,n,i){var a=t.createProgram();t.attachShader(a,e),t.attachShader(a,r);for(var o=0;o<n.length;++o)t.bindAttribLocation(a,i[o],n[o]);if(t.linkProgram(a),!t.getProgramParameter(a,t.LINK_STATUS)){var s=t.getProgramInfoLog(a);throw new c(s,"Error linking program: "+s)}return a}function s(t){var e=d.get(t);return e||(e=new i(t),d.set(t,e)),e}function l(t,e,r){return s(t).getShaderReference(e,r)}function u(t,e,r,n,i){return s(t).getProgram(e,r,n,i)}r.shader=l,r.program=u;var c=t("./GLError"),h=t("gl-format-compiler-error"),f="undefined"==typeof WeakMap?t("weakmap-shim"):WeakMap,d=new f,p=0;n.prototype.dispose=function(){if(0===--this.count){for(var t=this.cache,e=t.gl,r=this.programs,n=0,i=r.length;i>n;++n){var a=t.programs[r[n]];a&&(delete t.programs[n],e.deleteProgram(a))}e.deleteShader(this.shader),delete t.shaders[this.type===e.FRAGMENT_SHADER|0][this.src]}};var g=i.prototype;g.getShaderReference=function(t,e){var r=this.gl,i=this.shaders[t===r.FRAGMENT_SHADER|0],o=i[e];if(o&&r.isShader(o.shader))o.count+=1;else{var s=a(r,t,e);o=i[e]=new n(p++,e,t,s,[],1,this)}return o},g.getProgram=function(t,e,r,n){var i=[t.id,e.id,r.join(":"),n.join(":")].join("@"),a=this.programs[i];return a&&this.gl.isProgram(a)||(this.programs[i]=a=o(this.gl,t.shader,e.shader,r,n),t.programs.push(i),e.programs.push(i)),a}},{"./GLError":155,"gl-format-compiler-error":161,"weakmap-shim":177}],161:[function(t,e,r){function n(t,e,r){"use strict";var n=o(e)||"of unknown name (see npm glsl-shader-name)",l="unknown type";void 0!==r&&(l=r===a.FRAGMENT_SHADER?"fragment":"vertex");for(var u=i("Error compiling %s shader %s:\n",l,n),c=i("%s%s",u,t),h=t.split("\n"),f={},d=0;d<h.length;d++){var p=h[d];if(""!==p){var g=parseInt(p.split(":")[2]);if(isNaN(g))throw new Error(i("Could not parse error: %s",p));f[g]=p}}for(var v=s(e).split("\n"),d=0;d<v.length;d++)if(f[d+3]||f[d+2]||f[d+1]){var m=v[d];if(u+=m+"\n",f[d+1]){var y=f[d+1];y=y.substr(y.split(":",3).join(":").length+1).trim(),u+=i("^^^ %s\n\n",y)}}return{"long":u.trim(),"short":c.trim()}}var i=t("sprintf-js").sprintf,a=t("gl-constants/lookup"),o=t("glsl-shader-name"),s=t("add-line-numbers");e.exports=n},{"add-line-numbers":162,"gl-constants/lookup":166,"glsl-shader-name":167,"sprintf-js":174}],162:[function(t,e,r){function n(t,e,r){e="number"==typeof e?e:1,r=r||": ";var n=t.split(/\r?\n/),a=String(n.length+e-1).length;return n.map(function(t,n){var o=n+e,s=String(o).length,l=i(o,a-s);return l+r+t}).join("\n")}var i=t("pad-left");e.exports=n},{"pad-left":163}],163:[function(t,e,r){"use strict";var n=t("repeat-string");e.exports=function(t,e,r){return r="undefined"!=typeof r?r+"":" ",n(r,e)+t}},{"repeat-string":164}],164:[function(t,e,r){"use strict";function n(t,e){if("string"!=typeof t)throw new TypeError("repeat-string expects a string.");if(1===e)return t;if(2===e)return t+t;var r=t.length*e;for((i!==t||"undefined"==typeof i)&&(i=t,a="");r>a.length&&e>0&&(1&e&&(a+=t),e>>=1);)t+=t;return a.substr(0,r)}e.exports=n;var i,a=""},{}],165:[function(t,e,r){e.exports={0:"NONE",1:"ONE",2:"LINE_LOOP",3:"LINE_STRIP",4:"TRIANGLES",5:"TRIANGLE_STRIP",6:"TRIANGLE_FAN",256:"DEPTH_BUFFER_BIT",512:"NEVER",513:"LESS",514:"EQUAL",515:"LEQUAL",516:"GREATER",517:"NOTEQUAL",518:"GEQUAL",519:"ALWAYS",768:"SRC_COLOR",769:"ONE_MINUS_SRC_COLOR",770:"SRC_ALPHA",771:"ONE_MINUS_SRC_ALPHA",772:"DST_ALPHA",773:"ONE_MINUS_DST_ALPHA",774:"DST_COLOR",775:"ONE_MINUS_DST_COLOR",776:"SRC_ALPHA_SATURATE",1024:"STENCIL_BUFFER_BIT",1028:"FRONT",1029:"BACK",1032:"FRONT_AND_BACK",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",2304:"CW",2305:"CCW",2849:"LINE_WIDTH",2884:"CULL_FACE",2885:"CULL_FACE_MODE",2886:"FRONT_FACE",2928:"DEPTH_RANGE",2929:"DEPTH_TEST",2930:"DEPTH_WRITEMASK",2931:"DEPTH_CLEAR_VALUE",2932:"DEPTH_FUNC",2960:"STENCIL_TEST",2961:"STENCIL_CLEAR_VALUE",2962:"STENCIL_FUNC",2963:"STENCIL_VALUE_MASK",2964:"STENCIL_FAIL",2965:"STENCIL_PASS_DEPTH_FAIL",2966:"STENCIL_PASS_DEPTH_PASS",2967:"STENCIL_REF",2968:"STENCIL_WRITEMASK",2978:"VIEWPORT",3024:"DITHER",3042:"BLEND",3088:"SCISSOR_BOX",3089:"SCISSOR_TEST",3106:"COLOR_CLEAR_VALUE",3107:"COLOR_WRITEMASK",3317:"UNPACK_ALIGNMENT",3333:"PACK_ALIGNMENT",3379:"MAX_TEXTURE_SIZE",3386:"MAX_VIEWPORT_DIMS",3408:"SUBPIXEL_BITS",3410:"RED_BITS",3411:"GREEN_BITS",3412:"BLUE_BITS",3413:"ALPHA_BITS",3414:"DEPTH_BITS",3415:"STENCIL_BITS",3553:"TEXTURE_2D",4352:"DONT_CARE",4353:"FASTEST",4354:"NICEST",5120:"BYTE",5121:"UNSIGNED_BYTE",5122:"SHORT",5123:"UNSIGNED_SHORT",5124:"INT",5125:"UNSIGNED_INT",5126:"FLOAT",5386:"INVERT",5890:"TEXTURE",6401:"STENCIL_INDEX",6402:"DEPTH_COMPONENT",6406:"ALPHA",6407:"RGB",6408:"RGBA",6409:"LUMINANCE",6410:"LUMINANCE_ALPHA",7680:"KEEP",7681:"REPLACE",7682:"INCR",7683:"DECR",7936:"VENDOR",7937:"RENDERER",7938:"VERSION",9728:"NEAREST",9729:"LINEAR",9984:"NEAREST_MIPMAP_NEAREST",9985:"LINEAR_MIPMAP_NEAREST",9986:"NEAREST_MIPMAP_LINEAR",9987:"LINEAR_MIPMAP_LINEAR",10240:"TEXTURE_MAG_FILTER",10241:"TEXTURE_MIN_FILTER",10242:"TEXTURE_WRAP_S",10243:"TEXTURE_WRAP_T",10497:"REPEAT",10752:"POLYGON_OFFSET_UNITS",16384:"COLOR_BUFFER_BIT",32769:"CONSTANT_COLOR",32770:"ONE_MINUS_CONSTANT_COLOR",32771:"CONSTANT_ALPHA",32772:"ONE_MINUS_CONSTANT_ALPHA",32773:"BLEND_COLOR",32774:"FUNC_ADD",32777:"BLEND_EQUATION_RGB",32778:"FUNC_SUBTRACT",32779:"FUNC_REVERSE_SUBTRACT",32819:"UNSIGNED_SHORT_4_4_4_4",32820:"UNSIGNED_SHORT_5_5_5_1",32823:"POLYGON_OFFSET_FILL",32824:"POLYGON_OFFSET_FACTOR",32854:"RGBA4",32855:"RGB5_A1",32873:"TEXTURE_BINDING_2D",32926:"SAMPLE_ALPHA_TO_COVERAGE",32928:"SAMPLE_COVERAGE",32936:"SAMPLE_BUFFERS",32937:"SAMPLES",32938:"SAMPLE_COVERAGE_VALUE",32939:"SAMPLE_COVERAGE_INVERT",32968:"BLEND_DST_RGB",32969:"BLEND_SRC_RGB",32970:"BLEND_DST_ALPHA",32971:"BLEND_SRC_ALPHA",33071:"CLAMP_TO_EDGE",33170:"GENERATE_MIPMAP_HINT",33189:"DEPTH_COMPONENT16",33306:"DEPTH_STENCIL_ATTACHMENT",33635:"UNSIGNED_SHORT_5_6_5",33648:"MIRRORED_REPEAT",33901:"ALIASED_POINT_SIZE_RANGE",33902:"ALIASED_LINE_WIDTH_RANGE",33984:"TEXTURE0",33985:"TEXTURE1",33986:"TEXTURE2",33987:"TEXTURE3",33988:"TEXTURE4",33989:"TEXTURE5",33990:"TEXTURE6",33991:"TEXTURE7",33992:"TEXTURE8",33993:"TEXTURE9",33994:"TEXTURE10",33995:"TEXTURE11",33996:"TEXTURE12",33997:"TEXTURE13",33998:"TEXTURE14",33999:"TEXTURE15",34e3:"TEXTURE16",34001:"TEXTURE17",34002:"TEXTURE18",34003:"TEXTURE19",34004:"TEXTURE20",34005:"TEXTURE21",34006:"TEXTURE22",34007:"TEXTURE23",34008:"TEXTURE24",34009:"TEXTURE25",34010:"TEXTURE26",34011:"TEXTURE27",34012:"TEXTURE28",34013:"TEXTURE29",34014:"TEXTURE30",34015:"TEXTURE31",34016:"ACTIVE_TEXTURE",34024:"MAX_RENDERBUFFER_SIZE",34041:"DEPTH_STENCIL",34055:"INCR_WRAP",34056:"DECR_WRAP",34067:"TEXTURE_CUBE_MAP",34068:"TEXTURE_BINDING_CUBE_MAP",34069:"TEXTURE_CUBE_MAP_POSITIVE_X",34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z",34076:"MAX_CUBE_MAP_TEXTURE_SIZE",34338:"VERTEX_ATTRIB_ARRAY_ENABLED",34339:"VERTEX_ATTRIB_ARRAY_SIZE",34340:"VERTEX_ATTRIB_ARRAY_STRIDE",34341:"VERTEX_ATTRIB_ARRAY_TYPE",34342:"CURRENT_VERTEX_ATTRIB",34373:"VERTEX_ATTRIB_ARRAY_POINTER",34466:"NUM_COMPRESSED_TEXTURE_FORMATS",34467:"COMPRESSED_TEXTURE_FORMATS",34660:"BUFFER_SIZE",34661:"BUFFER_USAGE",34816:"STENCIL_BACK_FUNC",34817:"STENCIL_BACK_FAIL",34818:"STENCIL_BACK_PASS_DEPTH_FAIL",34819:"STENCIL_BACK_PASS_DEPTH_PASS",34877:"BLEND_EQUATION_ALPHA",34921:"MAX_VERTEX_ATTRIBS",34922:"VERTEX_ATTRIB_ARRAY_NORMALIZED",34930:"MAX_TEXTURE_IMAGE_UNITS",34962:"ARRAY_BUFFER",34963:"ELEMENT_ARRAY_BUFFER",34964:"ARRAY_BUFFER_BINDING",34965:"ELEMENT_ARRAY_BUFFER_BINDING",34975:"VERTEX_ATTRIB_ARRAY_BUFFER_BINDING",35040:"STREAM_DRAW",35044:"STATIC_DRAW",35048:"DYNAMIC_DRAW",35632:"FRAGMENT_SHADER",35633:"VERTEX_SHADER",35660:"MAX_VERTEX_TEXTURE_IMAGE_UNITS",35661:"MAX_COMBINED_TEXTURE_IMAGE_UNITS",35663:"SHADER_TYPE",35664:"FLOAT_VEC2",35665:"FLOAT_VEC3",35666:"FLOAT_VEC4",35667:"INT_VEC2",35668:"INT_VEC3",35669:"INT_VEC4",35670:"BOOL",35671:"BOOL_VEC2",35672:"BOOL_VEC3",35673:"BOOL_VEC4",35674:"FLOAT_MAT2",35675:"FLOAT_MAT3",35676:"FLOAT_MAT4",35678:"SAMPLER_2D",35680:"SAMPLER_CUBE",35712:"DELETE_STATUS",35713:"COMPILE_STATUS",35714:"LINK_STATUS",35715:"VALIDATE_STATUS",35716:"INFO_LOG_LENGTH",35717:"ATTACHED_SHADERS",35718:"ACTIVE_UNIFORMS",35719:"ACTIVE_UNIFORM_MAX_LENGTH",35720:"SHADER_SOURCE_LENGTH",35721:"ACTIVE_ATTRIBUTES",35722:"ACTIVE_ATTRIBUTE_MAX_LENGTH",35724:"SHADING_LANGUAGE_VERSION",35725:"CURRENT_PROGRAM",36003:"STENCIL_BACK_REF",36004:"STENCIL_BACK_VALUE_MASK",36005:"STENCIL_BACK_WRITEMASK",36006:"FRAMEBUFFER_BINDING",36007:"RENDERBUFFER_BINDING",36048:"FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE",36049:"FRAMEBUFFER_ATTACHMENT_OBJECT_NAME",36050:"FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL",36051:"FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE",36053:"FRAMEBUFFER_COMPLETE",36054:"FRAMEBUFFER_INCOMPLETE_ATTACHMENT",36055:"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT",36057:"FRAMEBUFFER_INCOMPLETE_DIMENSIONS",36061:"FRAMEBUFFER_UNSUPPORTED",36064:"COLOR_ATTACHMENT0",36096:"DEPTH_ATTACHMENT",36128:"STENCIL_ATTACHMENT",36160:"FRAMEBUFFER",36161:"RENDERBUFFER",36162:"RENDERBUFFER_WIDTH",36163:"RENDERBUFFER_HEIGHT",36164:"RENDERBUFFER_INTERNAL_FORMAT",36168:"STENCIL_INDEX8",36176:"RENDERBUFFER_RED_SIZE",36177:"RENDERBUFFER_GREEN_SIZE",36178:"RENDERBUFFER_BLUE_SIZE",36179:"RENDERBUFFER_ALPHA_SIZE",36180:"RENDERBUFFER_DEPTH_SIZE",36181:"RENDERBUFFER_STENCIL_SIZE",36194:"RGB565",36336:"LOW_FLOAT",36337:"MEDIUM_FLOAT",36338:"HIGH_FLOAT",36339:"LOW_INT",36340:"MEDIUM_INT",36341:"HIGH_INT",36346:"SHADER_COMPILER",36347:"MAX_VERTEX_UNIFORM_VECTORS",36348:"MAX_VARYING_VECTORS",36349:"MAX_FRAGMENT_UNIFORM_VECTORS",37440:"UNPACK_FLIP_Y_WEBGL",37441:"UNPACK_PREMULTIPLY_ALPHA_WEBGL",37442:"CONTEXT_LOST_WEBGL",37443:"UNPACK_COLORSPACE_CONVERSION_WEBGL",37444:"BROWSER_DEFAULT_WEBGL"}},{}],166:[function(t,e,r){var n=t("./1.0/numbers");e.exports=function(t){return n[t]}},{"./1.0/numbers":165}],167:[function(t,e,r){function n(t){for(var e=Array.isArray(t)?t:i(t),r=0;r<e.length;r++){var n=e[r];if("preprocessor"===n.type){var o=n.data.match(/\#define\s+SHADER_NAME(_B64)?\s+(.+)$/);if(o&&o[2]){var s=o[1],l=o[2];return(s?a(l):l).trim()}}}}var i=t("glsl-tokenizer"),a=t("atob-lite");e.exports=n},{"atob-lite":168,"glsl-tokenizer":173}],168:[function(t,e,r){e.exports=function(t){return atob(t)}},{}],169:[function(t,e,r){function n(){function t(t){t.length&&B.push({type:_[N],data:t,position:V,line:D,column:U})}function e(t){
+I=0,G+=t,O=G.length;for(var e;z=G[I],O>I;){switch(e=I,N){case u:I=M();break;case c:I=k();break;case h:I=A();break;case f:I=T();break;case d:I=S();break;case x:I=L();break;case p:I=C();break;case l:I=P();break;case y:I=w();break;case s:I=n()}if(e!==I)switch(G[e]){case"\n":U=0,++D;break;default:++U}}return j+=I,G=G.slice(I),B}function r(e){return F.length&&t(F.join("")),N=b,t("(eof)"),B}function n(){return F=F.length?[]:F,"/"===R&&"*"===z?(V=j+I-1,N=u,R=z,I+1):"/"===R&&"/"===z?(V=j+I-1,N=c,R=z,I+1):"#"===z?(N=h,V=j+I,I):/\s/.test(z)?(N=y,V=j+I,I):(q=/\d/.test(z),H=/[^\w_]/.test(z),V=j+I,N=q?d:H?f:l,I)}function w(){return/[^\s]/g.test(z)?(t(F.join("")),N=s,I):(F.push(z),R=z,I+1)}function A(){return"\n"===z&&"\\"!==R?(t(F.join("")),N=s,I):(F.push(z),R=z,I+1)}function k(){return A()}function M(){return"/"===z&&"*"===R?(F.push(z),t(F.join("")),N=s,I+1):(F.push(z),R=z,I+1)}function T(){if("."===R&&/\d/.test(z))return N=p,I;if("/"===R&&"*"===z)return N=u,I;if("/"===R&&"/"===z)return N=c,I;if("."===z&&F.length){for(;E(F););return N=p,I}if(";"===z||")"===z||"("===z){if(F.length)for(;E(F););return t(z),N=s,I+1}var e=2===F.length&&"="!==z;if(/[\w_\d\s]/.test(z)||e){for(;E(F););return N=s,I}return F.push(z),R=z,I+1}function E(e){for(var r,n,i=0;;){if(r=a.indexOf(e.slice(0,e.length+i).join("")),n=a[r],-1===r){if(i--+e.length>0)continue;n=e.slice(0,1).join("")}return t(n),V+=n.length,F=F.slice(n.length),F.length}}function L(){return/[^a-fA-F0-9]/.test(z)?(t(F.join("")),N=s,I):(F.push(z),R=z,I+1)}function S(){return"."===z?(F.push(z),N=p,R=z,I+1):/[eE]/.test(z)?(F.push(z),N=p,R=z,I+1):"x"===z&&1===F.length&&"0"===F[0]?(N=x,F.push(z),R=z,I+1):/[^\d]/.test(z)?(t(F.join("")),N=s,I):(F.push(z),R=z,I+1)}function C(){return"f"===z&&(F.push(z),R=z,I+=1),/[eE]/.test(z)?(F.push(z),R=z,I+1):/[^\d]/.test(z)?(t(F.join("")),N=s,I):(F.push(z),R=z,I+1)}function P(){if(/[^\d\w_]/.test(z)){var e=F.join("");return N=i.indexOf(e)>-1?m:o.indexOf(e)>-1?v:g,t(F.join("")),N=s,I}return F.push(z),R=z,I+1}var z,R,O,I=0,j=0,N=s,F=[],B=[],D=1,U=0,V=0,q=!1,H=!1,G="";return function(t){return B=[],null!==t?e(t):r()}}e.exports=n;var i=t("./lib/literals"),a=t("./lib/operators"),o=t("./lib/builtins"),s=999,l=9999,u=0,c=1,h=2,f=3,d=4,p=5,g=6,v=7,m=8,y=9,b=10,x=11,_=["block-comment","line-comment","preprocessor","operator","integer","float","ident","builtin","keyword","whitespace","eof","integer"]},{"./lib/builtins":170,"./lib/literals":171,"./lib/operators":172}],170:[function(t,e,r){e.exports=["gl_Position","gl_PointSize","gl_ClipVertex","gl_FragCoord","gl_FrontFacing","gl_FragColor","gl_FragData","gl_FragDepth","gl_Color","gl_SecondaryColor","gl_Normal","gl_Vertex","gl_MultiTexCoord0","gl_MultiTexCoord1","gl_MultiTexCoord2","gl_MultiTexCoord3","gl_MultiTexCoord4","gl_MultiTexCoord5","gl_MultiTexCoord6","gl_MultiTexCoord7","gl_FogCoord","gl_MaxLights","gl_MaxClipPlanes","gl_MaxTextureUnits","gl_MaxTextureCoords","gl_MaxVertexAttribs","gl_MaxVertexUniformComponents","gl_MaxVaryingFloats","gl_MaxVertexTextureImageUnits","gl_MaxCombinedTextureImageUnits","gl_MaxTextureImageUnits","gl_MaxFragmentUniformComponents","gl_MaxDrawBuffers","gl_ModelViewMatrix","gl_ProjectionMatrix","gl_ModelViewProjectionMatrix","gl_TextureMatrix","gl_NormalMatrix","gl_ModelViewMatrixInverse","gl_ProjectionMatrixInverse","gl_ModelViewProjectionMatrixInverse","gl_TextureMatrixInverse","gl_ModelViewMatrixTranspose","gl_ProjectionMatrixTranspose","gl_ModelViewProjectionMatrixTranspose","gl_TextureMatrixTranspose","gl_ModelViewMatrixInverseTranspose","gl_ProjectionMatrixInverseTranspose","gl_ModelViewProjectionMatrixInverseTranspose","gl_TextureMatrixInverseTranspose","gl_NormalScale","gl_DepthRangeParameters","gl_DepthRange","gl_ClipPlane","gl_PointParameters","gl_Point","gl_MaterialParameters","gl_FrontMaterial","gl_BackMaterial","gl_LightSourceParameters","gl_LightSource","gl_LightModelParameters","gl_LightModel","gl_LightModelProducts","gl_FrontLightModelProduct","gl_BackLightModelProduct","gl_LightProducts","gl_FrontLightProduct","gl_BackLightProduct","gl_FogParameters","gl_Fog","gl_TextureEnvColor","gl_EyePlaneS","gl_EyePlaneT","gl_EyePlaneR","gl_EyePlaneQ","gl_ObjectPlaneS","gl_ObjectPlaneT","gl_ObjectPlaneR","gl_ObjectPlaneQ","gl_FrontColor","gl_BackColor","gl_FrontSecondaryColor","gl_BackSecondaryColor","gl_TexCoord","gl_FogFragCoord","gl_Color","gl_SecondaryColor","gl_TexCoord","gl_FogFragCoord","gl_PointCoord","radians","degrees","sin","cos","tan","asin","acos","atan","pow","exp","log","exp2","log2","sqrt","inversesqrt","abs","sign","floor","ceil","fract","mod","min","max","clamp","mix","step","smoothstep","length","distance","dot","cross","normalize","faceforward","reflect","refract","matrixCompMult","lessThan","lessThanEqual","greaterThan","greaterThanEqual","equal","notEqual","any","all","not","texture2D","texture2DProj","texture2DLod","texture2DProjLod","textureCube","textureCubeLod","dFdx","dFdy"]},{}],171:[function(t,e,r){e.exports=["precision","highp","mediump","lowp","attribute","const","uniform","varying","break","continue","do","for","while","if","else","in","out","inout","float","int","void","bool","true","false","discard","return","mat2","mat3","mat4","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","sampler1D","sampler2D","sampler3D","samplerCube","sampler1DShadow","sampler2DShadow","struct","asm","class","union","enum","typedef","template","this","packed","goto","switch","default","inline","noinline","volatile","public","static","extern","external","interface","long","short","double","half","fixed","unsigned","input","output","hvec2","hvec3","hvec4","dvec2","dvec3","dvec4","fvec2","fvec3","fvec4","sampler2DRect","sampler3DRect","sampler2DRectShadow","sizeof","cast","namespace","using"]},{}],172:[function(t,e,r){e.exports=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"]},{}],173:[function(t,e,r){function n(t){var e=i(),r=[];return r=r.concat(e(t)),r=r.concat(e(null))}var i=t("./index");e.exports=n},{"./index":169}],174:[function(e,r,n){!function(e){function r(){var t=arguments[0],e=r.cache;return e[t]&&e.hasOwnProperty(t)||(e[t]=r.parse(t)),r.format.call(null,e[t],arguments)}function i(t){return Object.prototype.toString.call(t).slice(8,-1).toLowerCase()}function a(t,e){return Array(e+1).join(t)}var o={not_string:/[^s]/,number:/[diefg]/,json:/[j]/,not_json:/[^j]/,text:/^[^\x25]+/,modulo:/^\x25{2}/,placeholder:/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijosuxX])/,key:/^([a-z_][a-z_\d]*)/i,key_access:/^\.([a-z_][a-z_\d]*)/i,index_access:/^\[(\d+)\]/,sign:/^[\+\-]/};r.format=function(t,e){var n,s,l,u,c,h,f,d=1,p=t.length,g="",v=[],m=!0,y="";for(s=0;p>s;s++)if(g=i(t[s]),"string"===g)v[v.length]=t[s];else if("array"===g){if(u=t[s],u[2])for(n=e[d],l=0;l<u[2].length;l++){if(!n.hasOwnProperty(u[2][l]))throw new Error(r("[sprintf] property '%s' does not exist",u[2][l]));n=n[u[2][l]]}else n=u[1]?e[u[1]]:e[d++];if("function"==i(n)&&(n=n()),o.not_string.test(u[8])&&o.not_json.test(u[8])&&"number"!=i(n)&&isNaN(n))throw new TypeError(r("[sprintf] expecting number but found %s",i(n)));switch(o.number.test(u[8])&&(m=n>=0),u[8]){case"b":n=n.toString(2);break;case"c":n=String.fromCharCode(n);break;case"d":case"i":n=parseInt(n,10);break;case"j":n=JSON.stringify(n,null,u[6]?parseInt(u[6]):0);break;case"e":n=u[7]?n.toExponential(u[7]):n.toExponential();break;case"f":n=u[7]?parseFloat(n).toFixed(u[7]):parseFloat(n);break;case"g":n=u[7]?parseFloat(n).toPrecision(u[7]):parseFloat(n);break;case"o":n=n.toString(8);break;case"s":n=(n=String(n))&&u[7]?n.substring(0,u[7]):n;break;case"u":n>>>=0;break;case"x":n=n.toString(16);break;case"X":n=n.toString(16).toUpperCase()}o.json.test(u[8])?v[v.length]=n:(!o.number.test(u[8])||m&&!u[3]?y="":(y=m?"+":"-",n=n.toString().replace(o.sign,"")),h=u[4]?"0"===u[4]?"0":u[4].charAt(1):" ",f=u[6]-(y+n).length,c=u[6]&&f>0?a(h,f):"",v[v.length]=u[5]?y+n+c:"0"===h?y+c+n:c+y+n)}return v.join("")},r.cache={},r.parse=function(t){for(var e=t,r=[],n=[],i=0;e;){if(null!==(r=o.text.exec(e)))n[n.length]=r[0];else if(null!==(r=o.modulo.exec(e)))n[n.length]="%";else{if(null===(r=o.placeholder.exec(e)))throw new SyntaxError("[sprintf] unexpected placeholder");if(r[2]){i|=1;var a=[],s=r[2],l=[];if(null===(l=o.key.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");for(a[a.length]=l[1];""!==(s=s.substring(l[0].length));)if(null!==(l=o.key_access.exec(s)))a[a.length]=l[1];else{if(null===(l=o.index_access.exec(s)))throw new SyntaxError("[sprintf] failed to parse named argument key");a[a.length]=l[1]}r[2]=a}else i|=2;if(3===i)throw new Error("[sprintf] mixing positional and named placeholders is not (yet) supported");n[n.length]=r}e=e.substring(r[0].length)}return n};var s=function(t,e,n){return n=(e||[]).slice(0),n.splice(0,0,t),r.apply(null,n)};"undefined"!=typeof n?(n.sprintf=r,n.vsprintf=s):(e.sprintf=r,e.vsprintf=s,"function"==typeof t&&t.amd&&t(function(){return{sprintf:r,vsprintf:s}}))}("undefined"==typeof window?this:window)},{}],175:[function(t,e,r){function n(){var t={};return function(e){if(("object"!=typeof e||null===e)&&"function"!=typeof e)throw new Error("Weakmap-shim: Key must be object");var r=e.valueOf(t);return r&&r.identity===t?r:i(e,t)}}var i=t("./hidden-store.js");e.exports=n},{"./hidden-store.js":176}],176:[function(t,e,r){function n(t,e){var r={identity:e},n=t.valueOf;return Object.defineProperty(t,"valueOf",{value:function(t){return t!==e?n.apply(this,arguments):r},writable:!0}),r}e.exports=n},{}],177:[function(t,e,r){function n(){var t=i();return{get:function(e,r){var n=t(e);return n.hasOwnProperty("value")?n.value:r},set:function(e,r){t(e).value=r},has:function(e){return"value"in t(e)},"delete":function(e){return delete t(e).value}}}var i=t("./create-store.js");e.exports=n},{"./create-store.js":175}],178:[function(t,e,r){"use strict";function n(t){this.plot=t,this.enable=[!0,!0,!1,!1],this.width=[1,1,1,1],this.color=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.center=[1/0,1/0]}function i(t,e){var r=new n(t);return r.update(e),t.addOverlay(r),r}e.exports=i;var a=n.prototype;a.update=function(t){t=t||{},this.enable=(t.enable||[!0,!0,!1,!1]).slice(),this.width=(t.width||[1,1,1,1]).slice(),this.color=(t.color||[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]]).map(function(t){return t.slice()}),this.center=(t.center||[1/0,1/0]).slice(),this.plot.setOverlayDirty()},a.draw=function(){var t=this.enable,e=this.width,r=this.color,n=this.center,i=this.plot,a=i.line,o=i.dataBox,s=i.viewBox;if(a.bind(),o[0]<=n[0]&&n[0]<=o[2]&&o[1]<=n[1]&&n[1]<=o[3]){var l=s[0]+(n[0]-o[0])/(o[2]-o[0])*(s[2]-s[0]),u=s[1]+(n[1]-o[1])/(o[3]-o[1])*(s[3]-s[1]);t[0]&&a.drawLine(l,u,s[0],u,e[0],r[0]),t[1]&&a.drawLine(l,u,l,s[1],e[1],r[1]),t[2]&&a.drawLine(l,u,s[2],u,e[2],r[2]),t[3]&&a.drawLine(l,u,l,s[3],e[3],r[3])}},a.dispose=function(){this.plot.removeOverlay(this)}},{}],179:[function(t,e,r){var n=t("gl-shader"),i="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec4 uv;\nattribute vec2 f;\nattribute vec3 normal;\n\nuniform mat4 model, view, projection, inverseModel;\nuniform vec3 lightPosition, eyePosition;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n  worldCoordinate = vec3(uv.zw, f.x);\n  vec4 worldPosition = model * vec4(worldCoordinate, 1.0);\n  vec4 clipPosition = projection * view * worldPosition;\n  gl_Position = clipPosition;\n  value = f.x;\n  kill = f.y;\n  planeCoordinate = uv.xy;\n  \n  //Lighting geometry parameters\n  vec4 cameraCoordinate = view * worldPosition;\n  cameraCoordinate.xyz /= cameraCoordinate.w;\n  lightDirection = lightPosition - cameraCoordinate.xyz;\n  eyeDirection   = eyePosition - cameraCoordinate.xyz;\n  surfaceNormal  = normalize((vec4(normal,0) * inverseModel).xyz);\n}",a="#define GLSLIFY 1\nprecision mediump float;\n\nfloat beckmannDistribution_2_0(float x, float roughness) {\n  float NdotH = max(x, 0.0001);\n  float cos2Alpha = NdotH * NdotH;\n  float tan2Alpha = (cos2Alpha - 1.0) / cos2Alpha;\n  float roughness2 = roughness * roughness;\n  float denom = 3.141592653589793 * roughness2 * cos2Alpha * cos2Alpha;\n  return exp(tan2Alpha / roughness2) / denom;\n}\n\n\n\nfloat beckmannSpecular_1_1(\n  vec3 lightDirection,\n  vec3 viewDirection,\n  vec3 surfaceNormal,\n  float roughness) {\n  return beckmannDistribution_2_0(dot(surfaceNormal, normalize(lightDirection + viewDirection)), roughness);\n}\n\n\n\nuniform vec3 lowerBound, upperBound;\nuniform float contourTint;\nuniform vec4 contourColor;\nuniform sampler2D colormap;\nuniform vec3 clipBounds[2];\nuniform float roughness, fresnel, kambient, kdiffuse, kspecular, opacity;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n  if(kill > 0.0 ||\n    any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n    discard;\n  }\n\n  vec3 N = normalize(surfaceNormal);\n  vec3 V = normalize(eyeDirection);\n  vec3 L = normalize(lightDirection);\n\n  if(gl_FrontFacing) {\n    N = -N;\n  }\n\n  float specular = beckmannSpecular_1_1(L, V, N, roughness);\n  float diffuse  = min(kambient + kdiffuse * max(dot(N, L), 0.0), 1.0);\n\n  float interpValue = (value - lowerBound.z) / (upperBound.z - lowerBound.z);\n  vec4 surfaceColor = texture2D(colormap, vec2(interpValue, interpValue));\n  vec4 litColor = surfaceColor.a * vec4(diffuse * surfaceColor.rgb + kspecular * vec3(1,1,1) * specular,  1.0);\n\n  gl_FragColor = mix(litColor, contourColor, contourTint) * opacity;\n}\n",o="#define GLSLIFY 1\nprecision mediump float;\n\nattribute vec4 uv;\n\nuniform mat3 permutation;\nuniform mat4 model, view, projection;\nuniform float height, zOffset;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 lightDirection, eyeDirection, surfaceNormal;\n\nvoid main() {\n  vec3 dataCoordinate = permutation * vec3(uv.xy, height);\n  vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n  vec4 clipPosition = projection * view * worldPosition;\n  clipPosition.z = clipPosition.z + zOffset;\n\n  gl_Position = clipPosition;\n  value = dataCoordinate.z;\n  kill = -1.0;\n  worldCoordinate = dataCoordinate;\n  planeCoordinate = uv.zw;\n\n  //Don't do lighting for contours\n  surfaceNormal   = vec3(1,0,0);\n  eyeDirection    = vec3(0,1,0);\n  lightDirection  = vec3(0,0,1);\n}\n",s="#define GLSLIFY 1\nprecision mediump float;\n\nuniform vec2 shape;\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying float value, kill;\nvarying vec3 worldCoordinate;\nvarying vec2 planeCoordinate;\nvarying vec3 surfaceNormal;\n\nvec2 splitFloat(float v) {\n  float vh = 255.0 * v;\n  float upper = floor(vh);\n  float lower = fract(vh);\n  return vec2(upper / 255.0, floor(lower * 16.0) / 16.0);\n}\n\nvoid main() {\n  if(kill > 0.0 || \n    any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n    discard;\n  }\n  vec2 ux = splitFloat(planeCoordinate.x / shape.x);\n  vec2 uy = splitFloat(planeCoordinate.y / shape.y);\n  gl_FragColor = vec4(pickId, ux.x, uy.x, ux.y + (uy.y/16.0));\n}";r.createShader=function(t){var e=n(t,i,a,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec2"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createPickShader=function(t){var e=n(t,i,s,null,[{name:"uv",type:"vec4"},{name:"f",type:"vec2"},{name:"normal",type:"vec3"}]);return e.attributes.uv.location=0,e.attributes.f.location=1,e.attributes.normal.location=2,e},r.createContourShader=function(t){var e=n(t,o,a,null,[{name:"uv",type:"vec4"}]);return e.attributes.uv.location=0,e},r.createPickContourShader=function(t){var e=n(t,o,s,null,[{name:"uv",type:"vec4"}]);return e.attributes.uv.location=0,e}},{"gl-shader":154}],180:[function(t,e,r){arguments[4][20][0].apply(r,arguments)},{dup:20}],181:[function(t,e,r){"use strict";function n(t){if(t in l)return l[t];for(var e=[],r=0;t>r;++r)e.push("out",r,"s=0.5*(inp",r,"l-inp",r,"r);");for(var n=["array"],i=["junk"],r=0;t>r;++r){n.push("array"),i.push("out"+r+"s");var a=o(t);a[r]=-1,n.push({array:0,offset:a.slice()}),a[r]=1,n.push({array:0,offset:a.slice()}),i.push("inp"+r+"l","inp"+r+"r")}return l[t]=s({args:n,pre:c,post:c,body:{body:e.join(""),args:i.map(function(t){return{name:t,lvalue:0===t.indexOf("out"),rvalue:0===t.indexOf("inp"),count:"junk"!==t|0}}),thisVars:[],localVars:[]},funcName:"fdTemplate"+t})}function i(t){function e(e){for(var r=a-e.length,n=[],i=[],s=[],l=0;a>l;++l)e.indexOf(l+1)>=0?s.push("0"):e.indexOf(-(l+1))>=0?s.push("s["+l+"]-1"):(s.push("-1"),n.push("1"),i.push("s["+l+"]-2"));var u=".lo("+n.join()+").hi("+i.join()+")";if(0===n.length&&(u=""),r>0){o.push("if(1");for(var l=0;a>l;++l)e.indexOf(l+1)>=0||e.indexOf(-(l+1))>=0||o.push("&&s[",l,"]>2");o.push("){grad",r,"(src.pick(",s.join(),")",u);for(var l=0;a>l;++l)e.indexOf(l+1)>=0||e.indexOf(-(l+1))>=0||o.push(",dst.pick(",s.join(),",",l,")",u);o.push(");")}for(var l=0;l<e.length;++l){var c=Math.abs(e[l])-1,h="dst.pick("+s.join()+","+c+")"+u;switch(t[c]){case"clamp":var f=s.slice(),d=s.slice();e[l]<0?f[c]="s["+c+"]-2":d[c]="1",0===r?o.push("if(s[",c,"]>1){dst.set(",s.join(),",",c,",0.5*(src.get(",f.join(),")-src.get(",d.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):o.push("if(s[",c,"]>1){diff(",h,",src.pick(",f.join(),")",u,",src.pick(",d.join(),")",u,");}else{zero(",h,");};");break;case"mirror":0===r?o.push("dst.set(",s.join(),",",c,",0);"):o.push("zero(",h,");");break;case"wrap":var p=s.slice(),g=s.slice();e[l]<0?(p[c]="s["+c+"]-2",g[c]="0"):(p[c]="s["+c+"]-1",g[c]="1"),0===r?o.push("if(s[",c,"]>2){dst.set(",s.join(),",",c,",0.5*(src.get(",p.join(),")-src.get(",g.join(),")))}else{dst.set(",s.join(),",",c,",0)};"):o.push("if(s[",c,"]>2){diff(",h,",src.pick(",p.join(),")",u,",src.pick(",g.join(),")",u,");}else{zero(",h,");};");break;default:throw new Error("ndarray-gradient: Invalid boundary condition")}}r>0&&o.push("};")}var r=t.join(),i=u[r];if(i)return i;for(var a=t.length,o=["function gradient(dst,src){var s=src.shape.slice();"],s=0;1<<a>s;++s){for(var c=[],d=0;a>d;++d)s&1<<d&&c.push(d+1);for(var p=0;p<1<<c.length;++p){for(var g=c.slice(),d=0;d<c.length;++d)p&1<<d&&(g[d]=-g[d]);e(g)}}o.push("return dst;};return gradient");for(var v=["diff","zero"],m=[h,f],s=1;a>=s;++s)v.push("grad"+s),m.push(n(s));v.push(o.join(""));var y=Function.apply(void 0,v),i=y.apply(void 0,m);return l[r]=i,i}function a(t,e,r){if(Array.isArray(r)){if(r.length!==e.dimension)throw new Error("ndarray-gradient: invalid boundary conditions")}else r="string"==typeof r?o(e.dimension,r):o(e.dimension,"clamp");if(t.dimension!==e.dimension+1)throw new Error("ndarray-gradient: output dimension must be +1 input dimension");if(t.shape[e.dimension]!==e.dimension)throw new Error("ndarray-gradient: output shape must match input shape");for(var n=0;n<e.dimension;++n)if(t.shape[n]!==e.shape[n])throw new Error("ndarray-gradient: shape mismatch");if(0===e.size)return t;if(e.dimension<=0)return t.set(0),t;var a=i(r);return a(t,e)}e.exports=a;var o=t("dup"),s=t("cwise-compiler"),l={},u={},c={body:"",args:[],thisVars:[],localVars:[]},h=s({args:["array","array","array"],pre:c,post:c,body:{args:[{name:"out",lvalue:!0,rvalue:!1,count:1},{name:"left",lvalue:!1,rvalue:!0,count:1},{name:"right",lvalue:!1,rvalue:!0,count:1}],body:"out=0.5*(left-right)",thisVars:[],localVars:[]},funcName:"cdiff"}),f=s({args:["array"],pre:c,post:c,body:{args:[{name:"out",lvalue:!0,rvalue:!1,count:1}],body:"out=0",thisVars:[],localVars:[]},funcName:"zero"})},{"cwise-compiler":66,dup:72}],182:[function(t,e,r){"use strict";var n=t("ndarray"),i=t("./doConvert.js");e.exports=function(t,e){for(var r=[],a=t,o=1;a instanceof Array;)r.push(a.length),o*=a.length,a=a[0];return 0===r.length?n():(e||(e=n(new Float64Array(o),r)),i(e,t),e)}},{"./doConvert.js":183,ndarray:208}],183:[function(t,e,r){e.exports=t("cwise-compiler")({args:["array","scalar","index"],pre:{body:"{}",args:[],thisVars:[],localVars:[]},body:{body:"{\nvar _inline_1_v=_inline_1_arg1_,_inline_1_i\nfor(_inline_1_i=0;_inline_1_i<_inline_1_arg2_.length-1;++_inline_1_i) {\n_inline_1_v=_inline_1_v[_inline_1_arg2_[_inline_1_i]]\n}\n_inline_1_arg0_=_inline_1_v[_inline_1_arg2_[_inline_1_arg2_.length-1]]\n}",args:[{name:"_inline_1_arg0_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:4}],thisVars:[],localVars:["_inline_1_i","_inline_1_v"]},post:{body:"{}",args:[],thisVars:[],localVars:[]},funcName:"convert",blockSize:64})},{"cwise-compiler":66}],184:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.position=t,this.index=e,this.uv=r,this.level=n,this.dataCoordinate=i}function i(t){var e=x([y({colormap:t,nshades:j,format:"rgba"}).map(function(t){return[t[0],t[1],t[2],255*t[3]]})]);return b.divseq(e,255),e}function a(t,e,r,i,a,o,s,l,u,c,h,f,d,p){this.gl=t,this.shape=e,this.bounds=r,this._shader=i,this._pickShader=a,this._coordinateBuffer=o,this._vao=s,this._colorMap=l,this._contourShader=u,this._contourPickShader=c,this._contourBuffer=h,this._contourVAO=f,this._contourOffsets=[[],[],[]],this._contourCounts=[[],[],[]],this._vertexCount=0,this._pickResult=new n([0,0,0],[0,0],[0,0],[0,0,0],[0,0,0]),this._dynamicBuffer=d,this._dynamicVAO=p,this._dynamicOffsets=[0,0,0],this._dynamicCounts=[0,0,0],this.contourWidth=[1,1,1],this.contourLevels=[[1],[1],[1]],this.contourTint=[0,0,0],this.contourColor=[[.5,.5,.5,1],[.5,.5,.5,1],[.5,.5,.5,1]],this.showContour=!0,this.showSurface=!0,this.enableHighlight=[!0,!0,!0],this.highlightColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.highlightTint=[1,1,1],this.highlightLevel=[-1,-1,-1],this.enableDynamic=[!0,!0,!0],this.dynamicLevel=[NaN,NaN,NaN],this.dynamicColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.dynamicTint=[1,1,1],this.dynamicWidth=[1,1,1],this.axesBounds=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],this.surfaceProject=[!1,!1,!1],this.contourProject=[[!1,!1,!1],[!1,!1,!1],[!1,!1,!1]],this.colorBounds=[!1,!1],this._field=[_(m.mallocFloat(1024),[0,0]),_(m.mallocFloat(1024),[0,0]),_(m.mallocFloat(1024),[0,0])],this.pickId=1,this.clipBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.snapToData=!1,this.opacity=1,this.lightPosition=[10,1e4,0],this.ambientLight=.8,this.diffuseLight=.8,this.specularLight=2,this.roughness=.5,this.fresnel=1.5,this.dirty=!0}function o(t,e){for(var r=e.axes&&e.axes.lastCubeProps.axis||F,n=e.showSurface,i=e.showContour,a=0;3>a;++a){n=n||e.surfaceProject[a];for(var o=0;3>o;++o)i=i||e.contourProject[a][o]}for(var a=0;3>a;++a){for(var s=B.projections[a],o=0;16>o;++o)s[o]=0;for(var o=0;4>o;++o)s[5*o]=1;s[5*a]=0,s[12+a]=e.axesBounds[+(r[a]>0)][a],A(s,t.model,s);for(var l=B.clipBounds[a],u=0;2>u;++u)for(var o=0;3>o;++o)l[u][o]=t.clipBounds[u][o];l[0][a]=-1e8,l[1][a]=1e8}return B.showSurface=n,B.showContour=i,B}function s(t,e){t=t||{};var r=this.gl;r.disable(r.CULL_FACE),this._colorMap.bind(0);var n=D;n.model=t.model||R,n.view=t.view||R,n.projection=t.projection||R,n.lowerBound=[this.bounds[0][0],this.bounds[0][1],this.colorBounds[0]||this.bounds[0][2]],n.upperBound=[this.bounds[1][0],this.bounds[1][1],this.colorBounds[1]||this.bounds[1][2]],n.contourColor=this.contourColor[0],n.inverseModel=k(n.inverseModel,n.model);for(var i=0;2>i;++i)for(var a=n.clipBounds[i],s=0;3>s;++s)a[s]=Math.min(Math.max(this.clipBounds[i][s],-1e8),1e8);n.kambient=this.ambientLight,n.kdiffuse=this.diffuseLight,n.kspecular=this.specularLight,n.shape=n.roughness=this.roughness,n.fresnel=this.fresnel,n.opacity=this.opacity,n.height=0,n.permutation=V;var l=U;A(l,n.view,n.model),A(l,n.projection,l),k(l,l);for(var i=0;3>i;++i)n.eyePosition[i]=l[12+i]/l[15];for(var u=l[15],i=0;3>i;++i)u+=this.lightPosition[i]*l[4*i+3];for(var i=0;3>i;++i){for(var c=l[12+i],s=0;3>s;++s)c+=l[4*s+i]*this.lightPosition[s];n.lightPosition[i]=c/u}var h=o(n,this);if(h.showSurface&&e===this.opacity<1){this._shader.bind(),this._shader.uniforms=n,this._vao.bind(),this.showSurface&&this._vao.draw(r.TRIANGLES,this._vertexCount);for(var i=0;3>i;++i)this.surfaceProject[i]&&(this._shader.uniforms.model=h.projections[i],this._shader.uniforms.clipBounds=h.clipBounds[i],this._vao.draw(r.TRIANGLES,this._vertexCount));this._vao.unbind()}if(h.showContour&&!e){var f=this._contourShader;n.kambient=1,n.kdiffuse=0,n.kspecular=0,n.opacity=1,f.bind(),f.uniforms=n;var d=this._contourVAO;d.bind();for(var i=0;3>i;++i){f.uniforms.permutation=I[i],r.lineWidth(this.contourWidth[i]);for(var s=0;s<this.contourLevels[i].length;++s)s===this.highlightLevel[i]?(f.uniforms.contourColor=this.highlightColor[i],f.uniforms.contourTint=this.highlightTint[i]):(0===s||s-1===this.highlightLevel[i])&&(f.uniforms.contourColor=this.contourColor[i],f.uniforms.contourTint=this.contourTint[i]),f.uniforms.height=this.contourLevels[i][s],d.draw(r.LINES,this._contourCounts[i][s],this._contourOffsets[i][s])}for(var i=0;3>i;++i){f.uniforms.model=h.projections[i],f.uniforms.clipBounds=h.clipBounds[i];for(var s=0;3>s;++s)if(this.contourProject[i][s]){f.uniforms.permutation=I[s],r.lineWidth(this.contourWidth[s]);for(var p=0;p<this.contourLevels[s].length;++p)p===this.highlightLevel[s]?(f.uniforms.contourColor=this.highlightColor[s],f.uniforms.contourTint=this.highlightTint[s]):(0===p||p-1===this.highlightLevel[s])&&(f.uniforms.contourColor=this.contourColor[s],f.uniforms.contourTint=this.contourTint[s]),f.uniforms.height=this.contourLevels[s][p],d.draw(r.LINES,this._contourCounts[s][p],this._contourOffsets[s][p])}}d=this._dynamicVAO,d.bind();for(var i=0;3>i;++i)if(0!==this._dynamicCounts[i]){f.uniforms.model=n.model,f.uniforms.clipBounds=n.clipBounds,f.uniforms.permutation=I[i],r.lineWidth(this.dynamicWidth[i]),f.uniforms.contourColor=this.dynamicColor[i],f.uniforms.contourTint=this.dynamicTint[i],f.uniforms.height=this.dynamicLevel[i],d.draw(r.LINES,this._dynamicCounts[i],this._dynamicOffsets[i]);for(var s=0;3>s;++s)this.contourProject[s][i]&&(f.uniforms.model=h.projections[s],f.uniforms.clipBounds=h.clipBounds[s],d.draw(r.LINES,this._dynamicCounts[i],this._dynamicOffsets[i]))}d.unbind()}}function l(t,e){var r=e.shape.slice(),n=t.shape.slice();b.assign(t.lo(1,1).hi(r[0],r[1]),e),b.assign(t.lo(1).hi(r[0],1),e.hi(r[0],1)),b.assign(t.lo(1,n[1]-1).hi(r[0],1),e.lo(0,r[1]-1).hi(r[0],1)),b.assign(t.lo(0,1).hi(1,r[1]),e.hi(1)),b.assign(t.lo(n[0]-1,1).hi(1,r[1]),e.lo(r[0]-1)),t.set(0,0,e.get(0,0)),t.set(0,n[1]-1,e.get(0,r[1]-1)),t.set(n[0]-1,0,e.get(r[0]-1,0)),t.set(n[0]-1,n[1]-1,e.get(r[0]-1,r[1]-1))}function u(t,e){return Array.isArray(t)?[e(t[0]),e(t[1]),e(t[2])]:[e(t),e(t),e(t)]}function c(t){return Array.isArray(t)?3===t.length?[t[0],t[1],t[2],1]:[t[0],t[1],t[2],t[3]]:[0,0,0,1]}function h(t){if(Array.isArray(t)){if(Array.isArray(t))return[c(t[0]),c(t[1]),c(t[2])];var e=c(t);return[e.slice(),e.slice(),e.slice()]}}function f(t){var e=t.gl,r=(t.field||t.coords&&t.coords[2]||_([],[0,0]),L(e)),n=C(e),i=S(e),o=P(e),s=p(e),l=g(e,[{buffer:s,size:4,stride:z,offset:0},{buffer:s,size:2,stride:z,offset:16},{buffer:s,size:3,stride:z,offset:24}]),u=p(e),c=g(e,[{buffer:u,size:4}]),h=p(e),f=g(e,[{buffer:h,size:2,type:e.FLOAT}]),d=v(e,1,j,e.RGBA,e.UNSIGNED_BYTE);d.minFilter=e.LINEAR,d.magFilter=e.LINEAR;var m=new a(e,[0,0],[[0,0,0],[0,0,0]],r,n,s,l,d,i,o,u,c,h,f),y={levels:[[],[],[]]};for(var b in t)y[b]=t[b];return y.colormap=y.colormap||"jet",m.update(y),m}e.exports=f;var d=t("bit-twiddle"),p=t("gl-buffer"),g=t("gl-vao"),v=t("gl-texture2d"),m=t("typedarray-pool"),y=t("colormap"),b=t("ndarray-ops"),x=t("ndarray-pack"),_=t("ndarray"),w=t("surface-nets"),A=t("gl-mat4/multiply"),k=t("gl-mat4/invert"),M=t("binary-search-bounds"),T=t("ndarray-gradient"),_=t("ndarray"),E=t("./lib/shaders"),L=E.createShader,S=E.createContourShader,C=E.createPickShader,P=E.createPickContourShader,z=36,R=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],O=[[0,0],[0,1],[1,0],[1,1],[1,0],[0,1]],I=[[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]];!function(){for(var t=0;3>t;++t){var e=I[t],r=(t+1)%3,n=(t+2)%3;e[r+0]=1,e[n+3]=1,e[t+6]=1}}();var j=265,N=a.prototype;N.isTransparent=function(){return this.opacity<1},N.isOpaque=function(){if(this.opacity>=1)return!0;for(var t=0;3>t;++t)if(this._contourCounts[t].length>0||this._dynamicCounts[t]>0)return!0;return!1},N.pickSlots=1,N.setPickBase=function(t){this.pickId=t};var F=[0,0,0],B={showSurface:!1,showContour:!1,projections:[R.slice(),R.slice(),R.slice()],clipBounds:[[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]],[[0,0,0],[0,0,0]]]},D={model:R,view:R,projection:R,inverseModel:R.slice(),lowerBound:[0,0,0],upperBound:[0,0,0],colorMap:0,clipBounds:[[0,0,0],[0,0,0]],height:0,contourTint:0,contourColor:[0,0,0,1],permutation:[1,0,0,0,1,0,0,0,1],zOffset:-1e-4,kambient:1,kdiffuse:1,kspecular:1,lightPosition:[1e3,1e3,1e3],eyePosition:[0,0,0],roughness:1,fresnel:1,opacity:1},U=R.slice(),V=[1,0,0,0,1,0,0,0,1];N.draw=function(t){return s.call(this,t,!1)},N.drawTransparent=function(t){return s.call(this,t,!0)};var q={model:R,view:R,projection:R,inverseModel:R,clipBounds:[[0,0,0],[0,0,0]],height:0,shape:[0,0],pickId:0,lowerBound:[0,0,0],upperBound:[0,0,0],zOffset:0,permutation:[1,0,0,0,1,0,0,0,1],lightPosition:[0,0,0],eyePosition:[0,0,0]};N.drawPick=function(t){t=t||{};var e=this.gl;e.disable(e.CULL_FACE);var r=q;r.model=t.model||R,r.view=t.view||R,r.projection=t.projection||R,r.shape=this._field[2].shape,r.pickId=this.pickId/255,r.lowerBound=this.bounds[0],r.upperBound=this.bounds[1],r.permutation=V;for(var n=0;2>n;++n)for(var i=r.clipBounds[n],a=0;3>a;++a)i[a]=Math.min(Math.max(this.clipBounds[n][a],-1e8),1e8);var s=o(r,this);if(s.showSurface){this._pickShader.bind(),this._pickShader.uniforms=r,this._vao.bind(),this._vao.draw(e.TRIANGLES,this._vertexCount);for(var n=0;3>n;++n)this.surfaceProject[n]&&(this._pickShader.uniforms.model=s.projections[n],this._pickShader.uniforms.clipBounds=s.clipBounds[n],this._vao.draw(e.TRIANGLES,this._vertexCount));this._vao.unbind()}if(s.showContour){var l=this._contourPickShader;l.bind(),l.uniforms=r;var u=this._contourVAO;u.bind();for(var a=0;3>a;++a){e.lineWidth(this.contourWidth[a]),l.uniforms.permutation=I[a];for(var n=0;n<this.contourLevels[a].length;++n)l.uniforms.height=this.contourLevels[a][n],u.draw(e.LINES,this._contourCounts[a][n],this._contourOffsets[a][n])}for(var n=0;3>n;++n){l.uniforms.model=s.projections[n],l.uniforms.clipBounds=s.clipBounds[n];for(var a=0;3>a;++a)if(this.contourProject[n][a]){l.uniforms.permutation=I[a],e.lineWidth(this.contourWidth[a]);for(var c=0;c<this.contourLevels[a].length;++c)l.uniforms.height=this.contourLevels[a][c],u.draw(e.LINES,this._contourCounts[a][c],this._contourOffsets[a][c])}}u.unbind()}},N.pick=function(t){if(!t)return null;if(t.id!==this.pickId)return null;var e=this._field[2].shape,r=this._pickResult,n=e[0]*(t.value[0]+(t.value[2]>>4)/16)/255,i=Math.floor(n),a=n-i,o=e[1]*(t.value[1]+(15&t.value[2])/16)/255,s=Math.floor(o),l=o-s;i+=1,s+=1;var u=r.position;u[0]=u[1]=u[2]=0;for(var c=0;2>c;++c)for(var h=c?a:1-a,f=0;2>f;++f)for(var d=f?l:1-l,p=i+c,g=s+f,v=h*d,m=0;3>m;++m)u[m]+=this._field[m].get(p,g)*v;for(var y=this._pickResult.level,b=0;3>b;++b)if(y[b]=M.le(this.contourLevels[b],u[b]),y[b]<0)this.contourLevels[b].length>0&&(y[b]=0);else if(y[b]<this.contourLevels[b].length-1){var x=this.contourLevels[b][y[b]],_=this.contourLevels[b][y[b]+1];Math.abs(x-u[b])>Math.abs(_-u[b])&&(y[b]+=1)}r.index[0]=.5>a?i:i+1,r.index[1]=.5>l?s:s+1,r.uv[0]=n/e[0],r.uv[1]=o/e[1];for(var m=0;3>m;++m)r.dataCoordinate[m]=this._field[m].get(r.index[0],r.index[1]);return r},N.update=function(t){t=t||{},this.dirty=!0,"contourWidth"in t&&(this.contourWidth=u(t.contourWidth,Number)),"showContour"in t&&(this.showContour=u(t.showContour,Boolean)),"showSurface"in t&&(this.showSurface=!!t.showSurface),
+"contourTint"in t&&(this.contourTint=u(t.contourTint,Boolean)),"contourColor"in t&&(this.contourColor=h(t.contourColor)),"contourProject"in t&&(this.contourProject=u(t.contourProject,function(t){return u(t,Boolean)})),"surfaceProject"in t&&(this.surfaceProject=t.surfaceProject),"dynamicColor"in t&&(this.dynamicColor=h(t.dynamicColor)),"dynamicTint"in t&&(this.dynamicTint=u(t.dynamicTint,Number)),"dynamicWidth"in t&&(this.dynamicWidth=u(t.dynamicWidth,Number)),"opacity"in t&&(this.opacity=t.opacity),"colorBounds"in t&&(this.colorBounds=t.colorBounds);var e=t.field||t.coords&&t.coords[2]||null;if(e||(e=this._field[2].shape[0]||this._field[2].shape[2]?this._field[2].lo(1,1).hi(this._field[2].shape[0]-2,this._field[2].shape[1]-2):this._field[2].hi(0,0)),"field"in t||"coords"in t){var r=(e.shape[0]+2)*(e.shape[1]+2);r>this._field[2].data.length&&(m.freeFloat(this._field[2].data),this._field[2].data=m.mallocFloat(d.nextPow2(r))),this._field[2]=_(this._field[2].data,[e.shape[0]+2,e.shape[1]+2]),l(this._field[2],e),this.shape=e.shape.slice();for(var n=this.shape,a=0;2>a;++a)this._field[2].size>this._field[a].data.length&&(m.freeFloat(this._field[a].data),this._field[a].data=m.mallocFloat(this._field[2].size)),this._field[a]=_(this._field[a].data,[n[0]+2,n[1]+2]);if(t.coords){var o=t.coords;if(!Array.isArray(o)||3!==o.length)throw new Error("gl-surface: invalid coordinates for x/y");for(var a=0;2>a;++a){for(var s=o[a],c=0;2>c;++c)if(s.shape[c]!==n[c])throw new Error("gl-surface: coords have incorrect shape");l(this._field[a],s)}}else if(t.ticks){var f=t.ticks;if(!Array.isArray(f)||2!==f.length)throw new Error("gl-surface: invalid ticks");for(var a=0;2>a;++a){var p=f[a];if((Array.isArray(p)||p.length)&&(p=_(p)),p.shape[0]!==n[a])throw new Error("gl-surface: invalid tick length");var g=_(p.data,n);g.stride[a]=p.stride[0],g.stride[1^a]=0,l(this._field[a],g)}}else{for(var a=0;2>a;++a){var v=[0,0];v[a]=1,this._field[a]=_(this._field[a].data,[n[0]+2,n[1]+2],v,0)}this._field[0].set(0,0,0);for(var c=0;c<n[0];++c)this._field[0].set(c+1,0,c);this._field[0].set(n[0]+1,0,n[0]-1),this._field[1].set(0,0,0);for(var c=0;c<n[1];++c)this._field[1].set(0,c+1,c);this._field[1].set(0,n[1]+1,n[1]-1)}for(var y=this._field,b=(y[2].size,_(m.mallocFloat(3*y[2].size*2),[3,n[0]+2,n[1]+2,2])),a=0;3>a;++a)T(b.pick(a),y[a],"mirror");for(var x=_(m.mallocFloat(3*y[2].size),[n[0]+2,n[1]+2,3]),a=0;a<n[0]+2;++a)for(var c=0;c<n[1]+2;++c){var A=b.get(0,a,c,0),k=b.get(0,a,c,1),M=b.get(1,a,c,0),E=b.get(1,a,c,1),L=b.get(2,a,c,0),S=b.get(2,a,c,1),C=M*S-E*L,P=L*k-S*A,z=A*E-k*M,R=Math.sqrt(C*C+P*P+z*z);1e-8>R?(R=Math.max(Math.abs(C),Math.abs(P),Math.abs(z)),1e-8>R?(z=1,P=C=0,R=1):R=1/R):R=1/Math.sqrt(R),x.set(a,c,0,C*R),x.set(a,c,1,P*R),x.set(a,c,2,z*R)}m.free(b.data);for(var I=[1/0,1/0,1/0],j=[-(1/0),-(1/0),-(1/0)],N=(n[0]-1)*(n[1]-1)*6,F=m.mallocFloat(d.nextPow2(9*N)),B=0,D=0,a=0;a<n[0]-1;++a)t:for(var c=0;c<n[1]-1;++c){for(var U=0;2>U;++U)for(var V=0;2>V;++V)for(var q=0;3>q;++q){var H=this._field[q].get(1+a+U,1+c+V);if(isNaN(H)||!isFinite(H))continue t}for(var q=0;6>q;++q){var G=a+O[q][0],Y=c+O[q][1],X=this._field[0].get(G+1,Y+1),W=this._field[1].get(G+1,Y+1),H=this._field[2].get(G+1,Y+1),C=x.get(G+1,Y+1,0),P=x.get(G+1,Y+1,1),z=x.get(G+1,Y+1,2);F[B++]=G,F[B++]=Y,F[B++]=X,F[B++]=W,F[B++]=H,F[B++]=0,F[B++]=C,F[B++]=P,F[B++]=z,I[0]=Math.min(I[0],X),I[1]=Math.min(I[1],W),I[2]=Math.min(I[2],H),j[0]=Math.max(j[0],X),j[1]=Math.max(j[1],W),j[2]=Math.max(j[2],H),D+=1}}this._vertexCount=D,this._coordinateBuffer.update(F.subarray(0,B)),m.freeFloat(F),m.free(x.data),this.bounds=[I,j]}var Z=!1;if("levels"in t){var $=t.levels;$=Array.isArray($[0])?$.slice():[[],[],$];for(var a=0;3>a;++a)$[a]=$[a].slice(),$.sort(function(t,e){return t-e});t:for(var a=0;3>a;++a){if($[a].length!==this.contourLevels[a].length){Z=!0;break}for(var c=0;c<$[a].length;++c)if($[a][c]!==this.contourLevels[a][c]){Z=!0;break t}}this.contourLevels=$}if(Z){for(var y=this._field,n=this.shape,K=[],Q=0;3>Q;++Q){for(var $=this.contourLevels[Q],J=[],tt=[],et=[0,0],a=0;a<$.length;++a){var rt=w(this._field[Q],$[a]);J.push(K.length/4|0);var D=0;t:for(var c=0;c<rt.cells.length;++c)for(var nt=rt.cells[c],q=0;2>q;++q){var it=rt.positions[nt[q]],at=it[0],ot=0|Math.floor(at),st=at-ot,lt=it[1],ut=0|Math.floor(lt),ct=lt-ut,ht=!1;e:for(var ft=0;2>ft;++ft){et[ft]=0;for(var dt=(Q+ft+1)%3,U=0;2>U;++U)for(var pt=U?st:1-st,G=0|Math.min(Math.max(ot+U,0),n[0]),V=0;2>V;++V){var gt=V?ct:1-ct,Y=0|Math.min(Math.max(ut+V,0),n[1]),H=this._field[dt].get(G,Y);if(!isFinite(H)||isNaN(H)){ht=!0;break e}var vt=pt*gt;et[ft]+=vt*H}}if(ht){if(q>0){for(var mt=0;4>mt;++mt)K.pop();D-=1}continue t}K.push(et[0],et[1],it[0],it[1]),D+=1}tt.push(D)}this._contourOffsets[Q]=J,this._contourCounts[Q]=tt}for(var yt=m.mallocFloat(K.length),a=0;a<K.length;++a)yt[a]=K[a];this._contourBuffer.update(yt),m.freeFloat(yt)}t.colormap&&this._colorMap.setPixels(i(t.colormap))},N.dispose=function(){this._shader.dispose(),this._vao.dispose(),this._coordinateBuffer.dispose(),this._colorMap.dispose(),this._contourBuffer.dispose(),this._contourVAO.dispose(),this._contourShader.dispose(),this._contourPickShader.dispose(),this._dynamicBuffer.dispose(),this._dynamicVAO.dispose();for(var t=0;3>t;++t)m.freeFloat(this._field[t].data)},N.highlight=function(t){if(!t)return this._dynamicCounts=[0,0,0],this.dyanamicLevel=[NaN,NaN,NaN],void(this.highlightLevel=[-1,-1,-1]);for(var e=0;3>e;++e)this.enableHighlight[e]?this.highlightLevel[e]=t.level[e]:this.highlightLevel[e]=-1;var r;if(r=this.snapToData?t.dataCoordinate:t.position,this.enableDynamic[0]&&r[0]!==this.dynamicLevel[0]||this.enableDynamic[1]&&r[1]!==this.dynamicLevel[1]||this.enableDynamic[2]&&r[2]!==this.dynamicLevel[2]){for(var n=0,i=this.shape,a=m.mallocFloat(12*i[0]*i[1]),o=0;3>o;++o)if(this.enableDynamic[o]){this.dynamicLevel[o]=r[o];var s=(o+1)%3,l=(o+2)%3,u=this._field[o],c=this._field[s],h=this._field[l],f=w(u,r[o]),d=f.cells,p=f.positions;this._dynamicOffsets[o]=n;for(var e=0;e<d.length;++e)for(var g=d[e],v=0;2>v;++v){var y=p[g[v]],b=+y[0],x=0|b,_=0|Math.min(x+1,i[0]),A=b-x,k=1-A,M=+y[1],T=0|M,E=0|Math.min(T+1,i[1]),L=M-T,S=1-L,C=k*S,P=k*L,z=A*S,R=A*L,O=C*c.get(x,T)+P*c.get(x,E)+z*c.get(_,T)+R*c.get(_,E),I=C*h.get(x,T)+P*h.get(x,E)+z*h.get(_,T)+R*h.get(_,E);if(isNaN(O)||isNaN(I)){v&&(n-=1);break}a[2*n+0]=O,a[2*n+1]=I,n+=1}this._dynamicCounts[o]=n-this._dynamicOffsets[o]}else this.dynamicLevel[o]=NaN,this._dynamicCounts[o]=0;this._dynamicBuffer.update(a.subarray(0,2*n)),m.freeFloat(a)}}},{"./lib/shaders":179,"binary-search-bounds":180,"bit-twiddle":49,colormap:57,"gl-buffer":75,"gl-mat4/invert":94,"gl-mat4/multiply":96,"gl-texture2d":185,"gl-vao":189,ndarray:208,"ndarray-gradient":181,"ndarray-ops":207,"ndarray-pack":182,"surface-nets":227,"typedarray-pool":233}],185:[function(t,e,r){"use strict";function n(t){v=[t.LINEAR,t.NEAREST_MIPMAP_LINEAR,t.LINEAR_MIPMAP_NEAREST,t.LINEAR_MIPMAP_NEAREST],m=[t.NEAREST,t.LINEAR,t.NEAREST_MIPMAP_NEAREST,t.NEAREST_MIPMAP_LINEAR,t.LINEAR_MIPMAP_NEAREST,t.LINEAR_MIPMAP_LINEAR],y=[t.REPEAT,t.CLAMP_TO_EDGE,t.MIRRORED_REPEAT]}function i(t,e,r){var n=t.gl,i=n.getParameter(n.MAX_TEXTURE_SIZE);if(0>e||e>i||0>r||r>i)throw new Error("gl-texture2d: Invalid texture size");return t._shape=[e,r],t.bind(),n.texImage2D(n.TEXTURE_2D,0,t.format,e,r,0,t.format,t.type,null),t._mipLevels=[0],t}function a(t,e,r,n,i,a){this.gl=t,this.handle=e,this.format=i,this.type=a,this._shape=[r,n],this._mipLevels=[0],this._magFilter=t.NEAREST,this._minFilter=t.NEAREST,this._wrapS=t.CLAMP_TO_EDGE,this._wrapT=t.CLAMP_TO_EDGE,this._anisoSamples=1;var o=this,s=[this._wrapS,this._wrapT];Object.defineProperties(s,[{get:function(){return o._wrapS},set:function(t){return o.wrapS=t}},{get:function(){return o._wrapT},set:function(t){return o.wrapT=t}}]),this._wrapVector=s;var l=[this._shape[0],this._shape[1]];Object.defineProperties(l,[{get:function(){return o._shape[0]},set:function(t){return o.width=t}},{get:function(){return o._shape[1]},set:function(t){return o.height=t}}]),this._shapeVector=l}function o(t,e){return 3===t.length?1===e[2]&&e[1]===t[0]*t[2]&&e[0]===t[2]:1===e[0]&&e[1]===t[0]}function s(t,e,r,n,i,a,s,l){var u=l.dtype,c=l.shape.slice();if(c.length<2||c.length>3)throw new Error("gl-texture2d: Invalid ndarray, must be 2d or 3d");var h=0,f=0,v=o(c,l.stride.slice());"float32"===u?h=t.FLOAT:"float64"===u?(h=t.FLOAT,v=!1,u="float32"):"uint8"===u?h=t.UNSIGNED_BYTE:(h=t.UNSIGNED_BYTE,v=!1,u="uint8");var m=1;if(2===c.length)f=t.LUMINANCE,c=[c[0],c[1],1],l=d(l.data,c,[l.stride[0],l.stride[1],1],l.offset);else{if(3!==c.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===c[2])f=t.ALPHA;else if(2===c[2])f=t.LUMINANCE_ALPHA;else if(3===c[2])f=t.RGB;else{if(4!==c[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");f=t.RGBA}m=c[2]}if(f!==t.LUMINANCE&&f!==t.ALPHA||i!==t.LUMINANCE&&i!==t.ALPHA||(f=i),f!==i)throw new Error("gl-texture2d: Incompatible texture format for setPixels");var y=l.size,x=s.indexOf(n)<0;if(x&&s.push(n),h===a&&v)0===l.offset&&l.data.length===y?x?t.texImage2D(t.TEXTURE_2D,n,i,c[0],c[1],0,i,a,l.data):t.texSubImage2D(t.TEXTURE_2D,n,e,r,c[0],c[1],i,a,l.data):x?t.texImage2D(t.TEXTURE_2D,n,i,c[0],c[1],0,i,a,l.data.subarray(l.offset,l.offset+y)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,c[0],c[1],i,a,l.data.subarray(l.offset,l.offset+y));else{var _;_=a===t.FLOAT?g.mallocFloat32(y):g.mallocUint8(y);var w=d(_,c,[c[2],c[2]*c[0],1]);h===t.FLOAT&&a===t.UNSIGNED_BYTE?b(w,l):p.assign(w,l),x?t.texImage2D(t.TEXTURE_2D,n,i,c[0],c[1],0,i,a,_.subarray(0,y)):t.texSubImage2D(t.TEXTURE_2D,n,e,r,c[0],c[1],i,a,_.subarray(0,y)),a===t.FLOAT?g.freeFloat32(_):g.freeUint8(_)}}function l(t){var e=t.createTexture();return t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),e}function u(t,e,r,n,i){var o=t.getParameter(t.MAX_TEXTURE_SIZE);if(0>e||e>o||0>r||r>o)throw new Error("gl-texture2d: Invalid texture shape");if(i===t.FLOAT&&!t.getExtension("OES_texture_float"))throw new Error("gl-texture2d: Floating point textures not supported on this platform");var s=l(t);return t.texImage2D(t.TEXTURE_2D,0,n,e,r,0,n,i,null),new a(t,s,e,r,n,i)}function c(t,e,r,n){var i=l(t);return t.texImage2D(t.TEXTURE_2D,0,r,r,n,e),new a(t,i,0|e.width,0|e.height,r,n)}function h(t,e){var r=e.dtype,n=e.shape.slice(),i=t.getParameter(t.MAX_TEXTURE_SIZE);if(n[0]<0||n[0]>i||n[1]<0||n[1]>i)throw new Error("gl-texture2d: Invalid texture size");var s=o(n,e.stride.slice()),u=0;"float32"===r?u=t.FLOAT:"float64"===r?(u=t.FLOAT,s=!1,r="float32"):"uint8"===r?u=t.UNSIGNED_BYTE:(u=t.UNSIGNED_BYTE,s=!1,r="uint8");var c=0;if(2===n.length)c=t.LUMINANCE,n=[n[0],n[1],1],e=d(e.data,n,[e.stride[0],e.stride[1],1],e.offset);else{if(3!==n.length)throw new Error("gl-texture2d: Invalid shape for texture");if(1===n[2])c=t.ALPHA;else if(2===n[2])c=t.LUMINANCE_ALPHA;else if(3===n[2])c=t.RGB;else{if(4!==n[2])throw new Error("gl-texture2d: Invalid shape for pixel coords");c=t.RGBA}}u!==t.FLOAT||t.getExtension("OES_texture_float")||(u=t.UNSIGNED_BYTE,s=!1);var h,f,v=e.size;if(s)h=0===e.offset&&e.data.length===v?e.data:e.data.subarray(e.offset,e.offset+v);else{var m=[n[2],n[2]*n[0],1];f=g.malloc(v,r);var y=d(f,n,m,0);"float32"!==r&&"float64"!==r||u!==t.UNSIGNED_BYTE?p.assign(y,e):b(y,e),h=f.subarray(0,v)}var x=l(t);return t.texImage2D(t.TEXTURE_2D,0,c,n[0],n[1],0,c,u,h),s||g.free(f),new a(t,x,n[0],n[1],c,u)}function f(t){if(arguments.length<=1)throw new Error("gl-texture2d: Missing arguments for texture2d constructor");if(v||n(t),"number"==typeof arguments[1])return u(t,arguments[1],arguments[2],arguments[3]||t.RGBA,arguments[4]||t.UNSIGNED_BYTE);if(Array.isArray(arguments[1]))return u(t,0|arguments[1][0],0|arguments[1][1],arguments[2]||t.RGBA,arguments[3]||t.UNSIGNED_BYTE);if("object"==typeof arguments[1]){var e=arguments[1];if(e instanceof HTMLCanvasElement||e instanceof HTMLImageElement||e instanceof HTMLVideoElement||e instanceof ImageData)return c(t,e,arguments[2]||t.RGBA,arguments[3]||t.UNSIGNED_BYTE);if(e.shape&&e.data&&e.stride)return h(t,e)}throw new Error("gl-texture2d: Invalid arguments for texture2d constructor")}var d=t("ndarray"),p=t("ndarray-ops"),g=t("typedarray-pool");e.exports=f;var v=null,m=null,y=null,b=function(t,e){p.muls(t,e,255)},x=a.prototype;Object.defineProperties(x,{minFilter:{get:function(){return this._minFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&v.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),m.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t),this._minFilter=t}},magFilter:{get:function(){return this._magFilter},set:function(t){this.bind();var e=this.gl;if(this.type===e.FLOAT&&v.indexOf(t)>=0&&(e.getExtension("OES_texture_float_linear")||(t=e.NEAREST)),m.indexOf(t)<0)throw new Error("gl-texture2d: Unknown filter mode "+t);return e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t),this._magFilter=t}},mipSamples:{get:function(){return this._anisoSamples},set:function(t){var e=this._anisoSamples;if(this._anisoSamples=0|Math.max(t,1),e!==this._anisoSamples){var r=gl.getExtension("EXT_texture_filter_anisotropic");r&&this.gl.texParameterf(this.gl.TEXTURE_2D,r.TEXTURE_MAX_ANISOTROPY_EXT,this._anisoSamples)}return this._anisoSamples}},wrapS:{get:function(){return this._wrapS},set:function(t){if(this.bind(),y.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,t),this._wrapS=t}},wrapT:{get:function(){return this._wrapT},set:function(t){if(this.bind(),y.indexOf(t)<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);return this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,t),this._wrapT=t}},wrap:{get:function(){return this._wrapVector},set:function(t){if(Array.isArray(t)||(t=[t,t]),2!==t.length)throw new Error("gl-texture2d: Must specify wrap mode for rows and columns");for(var e=0;2>e;++e)if(y.indexOf(t[e])<0)throw new Error("gl-texture2d: Unknown wrap mode "+t);this._wrapS=t[0],this._wrapT=t[1];var r=this.gl;return this.bind(),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,this._wrapS),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,this._wrapT),t}},shape:{get:function(){return this._shapeVector},set:function(t){if(Array.isArray(t)){if(2!==t.length)throw new Error("gl-texture2d: Invalid texture shape")}else t=[0|t,0|t];return i(this,0|t[0],0|t[1]),[0|t[0],0|t[1]]}},width:{get:function(){return this._shape[0]},set:function(t){return t=0|t,i(this,t,this._shape[1]),t}},height:{get:function(){return this._shape[1]},set:function(t){return t=0|t,i(this,this._shape[0],t),t}}}),x.bind=function(t){var e=this.gl;return void 0!==t&&e.activeTexture(e.TEXTURE0+(0|t)),e.bindTexture(e.TEXTURE_2D,this.handle),void 0!==t?0|t:e.getParameter(e.ACTIVE_TEXTURE)-e.TEXTURE0},x.dispose=function(){this.gl.deleteTexture(this.handle)},x.generateMipmap=function(){this.bind(),this.gl.generateMipmap(this.gl.TEXTURE_2D);for(var t=Math.min(this._shape[0],this._shape[1]),e=0;t>0;++e,t>>>=1)this._mipLevels.indexOf(e)<0&&this._mipLevels.push(e)},x.setPixels=function(t,e,r,n){var i=this.gl;if(this.bind(),Array.isArray(e)?(n=r,r=0|e[1],e=0|e[0]):(e=e||0,r=r||0),n=n||0,t instanceof HTMLCanvasElement||t instanceof ImageData||t instanceof HTMLImageElement||t instanceof HTMLVideoElement){var a=this._mipLevels.indexOf(n)<0;a?(i.texImage2D(i.TEXTURE_2D,0,this.format,this.format,this.type,t),this._mipLevels.push(n)):i.texSubImage2D(i.TEXTURE_2D,n,e,r,this.format,this.type,t)}else{if(!(t.shape&&t.stride&&t.data))throw new Error("gl-texture2d: Unsupported data type");if(t.shape.length<2||e+t.shape[1]>this._shape[1]>>>n||r+t.shape[0]>this._shape[0]>>>n||0>e||0>r)throw new Error("gl-texture2d: Texture dimensions are out of bounds");s(i,e,r,n,this.format,this.type,this._mipLevels,t)}}},{ndarray:208,"ndarray-ops":207,"typedarray-pool":233}],186:[function(t,e,r){"use strict";function n(t,e,r){e?e.bind():t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null);var n=0|t.getParameter(t.MAX_VERTEX_ATTRIBS);if(r){if(r.length>n)throw new Error("gl-vao: Too many vertex attributes");for(var i=0;i<r.length;++i){var a=r[i];if(a.buffer){var o=a.buffer,s=a.size||4,l=a.type||t.FLOAT,u=!!a.normalized,c=a.stride||0,h=a.offset||0;o.bind(),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,s,l,u,c,h)}else{if("number"==typeof a)t.vertexAttrib1f(i,a);else if(1===a.length)t.vertexAttrib1f(i,a[0]);else if(2===a.length)t.vertexAttrib2f(i,a[0],a[1]);else if(3===a.length)t.vertexAttrib3f(i,a[0],a[1],a[2]);else{if(4!==a.length)throw new Error("gl-vao: Invalid vertex attribute");t.vertexAttrib4f(i,a[0],a[1],a[2],a[3])}t.disableVertexAttribArray(i)}}for(;n>i;++i)t.disableVertexAttribArray(i)}else{t.bindBuffer(t.ARRAY_BUFFER,null);for(var i=0;n>i;++i)t.disableVertexAttribArray(i)}}e.exports=n},{}],187:[function(t,e,r){"use strict";function n(t){this.gl=t,this._elements=null,this._attributes=null,this._elementsType=t.UNSIGNED_SHORT}function i(t){return new n(t)}var a=t("./do-bind.js");n.prototype.bind=function(){a(this.gl,this._elements,this._attributes)},n.prototype.update=function(t,e,r){this._elements=e,this._attributes=t,this._elementsType=r||this.gl.UNSIGNED_SHORT},n.prototype.dispose=function(){},n.prototype.unbind=function(){},n.prototype.draw=function(t,e,r){r=r||0;var n=this.gl;this._elements?n.drawElements(t,e,this._elementsType,r):n.drawArrays(t,r,e)},e.exports=i},{"./do-bind.js":186}],188:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this.location=t,this.dimension=e,this.a=r,this.b=n,this.c=i,this.d=a}function i(t,e,r){this.gl=t,this._ext=e,this.handle=r,this._attribs=[],this._useElements=!1,this._elementsType=t.UNSIGNED_SHORT}function a(t,e){return new i(t,e,e.createVertexArrayOES())}var o=t("./do-bind.js");n.prototype.bind=function(t){switch(this.dimension){case 1:t.vertexAttrib1f(this.location,this.a);break;case 2:t.vertexAttrib2f(this.location,this.a,this.b);break;case 3:t.vertexAttrib3f(this.location,this.a,this.b,this.c);break;case 4:t.vertexAttrib4f(this.location,this.a,this.b,this.c,this.d)}},i.prototype.bind=function(){this._ext.bindVertexArrayOES(this.handle);for(var t=0;t<this._attribs.length;++t)this._attribs[t].bind(this.gl)},i.prototype.unbind=function(){this._ext.bindVertexArrayOES(null)},i.prototype.dispose=function(){this._ext.deleteVertexArrayOES(this.handle)},i.prototype.update=function(t,e,r){if(this.bind(),o(this.gl,e,t),this.unbind(),this._attribs.length=0,t)for(var i=0;i<t.length;++i){var a=t[i];"number"==typeof a?this._attribs.push(new n(i,1,a)):Array.isArray(a)&&this._attribs.push(new n(i,a.length,a[0],a[1],a[2],a[3]))}this._useElements=!!e,this._elementsType=r||this.gl.UNSIGNED_SHORT},i.prototype.draw=function(t,e,r){r=r||0;var n=this.gl;this._useElements?n.drawElements(t,e,this._elementsType,r):n.drawArrays(t,r,e)},e.exports=a},{"./do-bind.js":186}],189:[function(t,e,r){"use strict";function n(t,e,r,n){var o,s=t.getExtension("OES_vertex_array_object");return o=s?i(t,s):a(t),o.update(e,r,n),o}var i=t("./lib/vao-native.js"),a=t("./lib/vao-emulated.js");e.exports=n},{"./lib/vao-emulated.js":187,"./lib/vao-native.js":188}],190:[function(t,e,r){function n(t,e,r){var n=e[0],i=e[1],a=e[2],o=e[3];return t[0]=r[0]*n+r[4]*i+r[8]*a+r[12]*o,t[1]=r[1]*n+r[5]*i+r[9]*a+r[13]*o,t[2]=r[2]*n+r[6]*i+r[10]*a+r[14]*o,t[3]=r[3]*n+r[7]*i+r[11]*a+r[15]*o,t}e.exports=n},{}],191:[function(t,e,r){"use strict";function n(t,e,r){this.vertices=t,this.adjacent=e,this.boundary=r,this.lastVisited=-1}function i(t,e,r){this.vertices=t,this.cell=e,this.index=r}function a(t,e){return c(t.vertices,e.vertices)}function o(t){for(var e=["function orient(){var tuple=this.tuple;return test("],r=0;t>=r;++r)r>0&&e.push(","),e.push("tuple[",r,"]");e.push(")}return orient");var n=new Function("test",e.join("")),i=u[t+1];return i||(i=u),n(i)}function s(t,e,r){this.dimension=t,this.vertices=e,this.simplices=r,this.interior=r.filter(function(t){return!t.boundary}),this.tuple=new Array(t+1);for(var n=0;t>=n;++n)this.tuple[n]=this.vertices[n];var i=h[t];i||(i=h[t]=o(t)),this.orient=i}function l(t,e){var r=t.length;if(0===r)throw new Error("Must have at least d+1 points");var i=t[0].length;if(i>=r)throw new Error("Must input at least d+1 points");var a=t.slice(0,i+1),o=u.apply(void 0,a);if(0===o)throw new Error("Input not in general position");for(var l=new Array(i+1),c=0;i>=c;++c)l[c]=c;0>o&&(l[0]=1,l[1]=0);for(var h=new n(l,new Array(i+1),!1),f=h.adjacent,d=new Array(i+2),c=0;i>=c;++c){for(var p=l.slice(),g=0;i>=g;++g)g===c&&(p[g]=-1);var v=p[0];p[0]=p[1],p[1]=v;var m=new n(p,new Array(i+1),!0);f[c]=m,d[c]=m}d[i+1]=h;for(var c=0;i>=c;++c)for(var p=f[c].vertices,y=f[c].adjacent,g=0;i>=g;++g){var b=p[g];if(0>b)y[g]=h;else for(var x=0;i>=x;++x)f[x].vertices.indexOf(b)<0&&(y[g]=f[x])}for(var _=new s(i,a,d),w=!!e,c=i+1;r>c;++c)_.insert(t[c],w);return _.boundary()}e.exports=l;var u=t("robust-orientation"),c=t("simplicial-complex").compareCells;n.prototype.flip=function(){var t=this.vertices[0];this.vertices[0]=this.vertices[1],this.vertices[1]=t;var e=this.adjacent[0];this.adjacent[0]=this.adjacent[1],this.adjacent[1]=e};var h=[],f=s.prototype;f.handleBoundaryDegeneracy=function(t,e){var r=this.dimension,n=this.vertices.length-1,i=this.tuple,a=this.vertices,o=[t];for(t.lastVisited=-n;o.length>0;){t=o.pop();for(var s=(t.vertices,t.adjacent),l=0;r>=l;++l){var u=s[l];if(u.boundary&&!(u.lastVisited<=-n)){for(var c=u.vertices,h=0;r>=h;++h){var f=c[h];0>f?i[h]=e:i[h]=a[f]}var d=this.orient();if(d>0)return u;u.lastVisited=-n,0===d&&o.push(u)}}}return null},f.walk=function(t,e){var r=this.vertices.length-1,n=this.dimension,i=this.vertices,a=this.tuple,o=e?this.interior.length*Math.random()|0:this.interior.length-1,s=this.interior[o];t:for(;!s.boundary;){for(var l=s.vertices,u=s.adjacent,c=0;n>=c;++c)a[c]=i[l[c]];s.lastVisited=r;for(var c=0;n>=c;++c){var h=u[c];if(!(h.lastVisited>=r)){var f=a[c];a[c]=t;var d=this.orient();if(a[c]=f,0>d){s=h;continue t}h.boundary?h.lastVisited=-r:h.lastVisited=r}}return}return s},f.addPeaks=function(t,e){var r=this.vertices.length-1,o=this.dimension,s=this.vertices,l=this.tuple,u=this.interior,c=this.simplices,h=[e];e.lastVisited=r,e.vertices[e.vertices.indexOf(-1)]=r,e.boundary=!1,u.push(e);for(var f=[];h.length>0;){var e=h.pop(),d=e.vertices,p=e.adjacent,g=d.indexOf(r);if(!(0>g))for(var v=0;o>=v;++v)if(v!==g){var m=p[v];if(m.boundary&&!(m.lastVisited>=r)){var y=m.vertices;if(m.lastVisited!==-r){for(var b=0,x=0;o>=x;++x)y[x]<0?(b=x,l[x]=t):l[x]=s[y[x]];var _=this.orient();if(_>0){y[b]=r,m.boundary=!1,u.push(m),h.push(m),m.lastVisited=r;continue}m.lastVisited=-r}var w=m.adjacent,A=d.slice(),k=p.slice(),M=new n(A,k,!0);c.push(M);var T=w.indexOf(e);if(!(0>T)){w[T]=M,k[g]=m,A[v]=-1,k[v]=e,p[v]=M,M.flip();for(var x=0;o>=x;++x){var E=A[x];if(!(0>E||E===r)){for(var L=new Array(o-1),S=0,C=0;o>=C;++C){var P=A[C];0>P||C===x||(L[S++]=P)}f.push(new i(L,M,x))}}}}}}f.sort(a);for(var v=0;v+1<f.length;v+=2){var z=f[v],R=f[v+1],O=z.index,I=R.index;0>O||0>I||(z.cell.adjacent[z.index]=R.cell,R.cell.adjacent[R.index]=z.cell)}},f.insert=function(t,e){var r=this.vertices;r.push(t);var n=this.walk(t,e);if(n){for(var i=this.dimension,a=this.tuple,o=0;i>=o;++o){var s=n.vertices[o];0>s?a[o]=t:a[o]=r[s]}var l=this.orient(a);0>l||(0!==l||(n=this.handleBoundaryDegeneracy(n,t)))&&this.addPeaks(t,n)}},f.boundary=function(){for(var t=this.dimension,e=[],r=this.simplices,n=r.length,i=0;n>i;++i){var a=r[i];if(a.boundary){for(var o=new Array(t),s=a.vertices,l=0,u=0,c=0;t>=c;++c)s[c]>=0?o[l++]=s[c]:u=1&c;if(u===(1&t)){var h=o[0];o[0]=o[1],o[1]=h}e.push(o)}}return e}},{"robust-orientation":214,"simplicial-complex":194}],192:[function(t,e,r){arguments[4][49][0].apply(r,arguments)},{dup:49}],193:[function(t,e,r){"use strict";"use restrict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;t>e;++e)this.roots[e]=e,this.ranks[e]=0}e.exports=n;var i=n.prototype;Object.defineProperty(i,"length",{get:function(){return this.roots.length}}),i.makeSet=function(){var t=this.roots.length;return this.roots.push(t),this.ranks.push(0),t},i.find=function(t){for(var e=t,r=this.roots;r[t]!==t;)t=r[t];for(;r[e]!==t;){var n=r[e];r[e]=t,e=n}return t},i.link=function(t,e){var r=this.find(t),n=this.find(e);if(r!==n){var i=this.ranks,a=this.roots,o=i[r],s=i[n];s>o?a[r]=n:o>s?a[n]=r:(a[n]=r,++i[r])}}},{}],194:[function(t,e,r){"use strict";"use restrict";function n(t){for(var e=0,r=Math.max,n=0,i=t.length;i>n;++n)e=r(e,t[n].length);return e-1}function i(t){for(var e=-1,r=Math.max,n=0,i=t.length;i>n;++n)for(var a=t[n],o=0,s=a.length;s>o;++o)e=r(e,a[o]);return e+1}function a(t){for(var e=new Array(t.length),r=0,n=t.length;n>r;++r)e[r]=t[r].slice(0);return e}function o(t,e){var r=t.length,n=t.length-e.length,i=Math.min;if(n)return n;switch(r){case 0:return 0;case 1:return t[0]-e[0];case 2:var a=t[0]+t[1]-e[0]-e[1];return a?a:i(t[0],t[1])-i(e[0],e[1]);case 3:var o=t[0]+t[1],s=e[0]+e[1];if(a=o+t[2]-(s+e[2]))return a;var l=i(t[0],t[1]),u=i(e[0],e[1]),a=i(l,t[2])-i(u,e[2]);return a?a:i(l+t[2],o)-i(u+e[2],s);default:var c=t.slice(0);c.sort();var h=e.slice(0);h.sort();for(var f=0;r>f;++f)if(n=c[f]-h[f])return n;return 0}}function s(t,e){return o(t[0],e[0])}function l(t,e){if(e){for(var r=t.length,n=new Array(r),i=0;r>i;++i)n[i]=[t[i],e[i]];n.sort(s);for(var i=0;r>i;++i)t[i]=n[i][0],e[i]=n[i][1];return t}return t.sort(o),t}function u(t){if(0===t.length)return[];for(var e=1,r=t.length,n=1;r>n;++n){var i=t[n];if(o(i,t[n-1])){if(n===e){e++;continue}t[e++]=i}}return t.length=e,t}function c(t,e){for(var r=0,n=t.length-1,i=-1;n>=r;){var a=r+n>>1,s=o(t[a],e);0>=s?(0===s&&(i=a),r=a+1):s>0&&(n=a-1)}return i}function h(t,e){for(var r=new Array(t.length),n=0,i=r.length;i>n;++n)r[n]=[];for(var a=[],n=0,s=e.length;s>n;++n)for(var l=e[n],u=l.length,h=1,f=1<<u;f>h;++h){a.length=b.popCount(h);for(var d=0,p=0;u>p;++p)h&1<<p&&(a[d++]=l[p]);var g=c(t,a);if(!(0>g))for(;;)if(r[g++].push(n),g>=t.length||0!==o(t[g],a))break}return r}function f(t,e){if(!e)return h(u(p(t,0)),t,0);for(var r=new Array(e),n=0;e>n;++n)r[n]=[];for(var n=0,i=t.length;i>n;++n)for(var a=t[n],o=0,s=a.length;s>o;++o)r[a[o]].push(n);return r}function d(t){for(var e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0|i.length,o=1,s=1<<a;s>o;++o){for(var u=[],c=0;a>c;++c)o>>>c&1&&u.push(i[c]);e.push(u)}return l(e)}function p(t,e){if(0>e)return[];for(var r=[],n=(1<<e+1)-1,i=0;i<t.length;++i)for(var a=t[i],o=n;o<1<<a.length;o=b.nextCombination(o)){for(var s=new Array(e+1),u=0,c=0;c<a.length;++c)o&1<<c&&(s[u++]=a[c]);r.push(s)}return l(r)}function g(t){for(var e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0,o=i.length;o>a;++a){for(var s=new Array(i.length-1),u=0,c=0;o>u;++u)u!==a&&(s[c++]=i[u]);e.push(s)}return l(e)}function v(t,e){for(var r=new x(e),n=0;n<t.length;++n)for(var i=t[n],a=0;a<i.length;++a)for(var o=a+1;o<i.length;++o)r.link(i[a],i[o]);for(var s=[],l=r.ranks,n=0;n<l.length;++n)l[n]=-1;for(var n=0;n<t.length;++n){var u=r.find(t[n][0]);l[u]<0?(l[u]=s.length,s.push([t[n].slice(0)])):s[l[u]].push(t[n].slice(0))}return s}function m(t){for(var e=u(l(p(t,0))),r=new x(e.length),n=0;n<t.length;++n)for(var i=t[n],a=0;a<i.length;++a)for(var o=c(e,[i[a]]),s=a+1;s<i.length;++s)r.link(o,c(e,[i[s]]));for(var h=[],f=r.ranks,n=0;n<f.length;++n)f[n]=-1;for(var n=0;n<t.length;++n){var d=r.find(c(e,[t[n][0]]));f[d]<0?(f[d]=h.length,h.push([t[n].slice(0)])):h[f[d]].push(t[n].slice(0))}return h}function y(t,e){return e?v(t,e):m(t)}var b=t("bit-twiddle"),x=t("union-find");r.dimension=n,r.countVertices=i,r.cloneCells=a,r.compareCells=o,r.normalize=l,r.unique=u,r.findCell=c,r.incidence=h,r.dual=f,r.explode=d,r.skeleton=p,r.boundary=g,r.connectedComponents=y},{"bit-twiddle":192,"union-find":193}],195:[function(t,e,r){"use strict";function n(t){for(var e=new Array(t),r=0;t>r;++r)e[r]=r;return e}e.exports=n},{}],196:[function(t,e,r){"use strict";function n(t,e){function r(t){var e=!1;return"altKey"in t&&(e=e||t.altKey!==g.alt,g.alt=!!t.altKey),"shiftKey"in t&&(e=e||t.shiftKey!==g.shift,g.shift=!!t.shiftKey),"ctrlKey"in t&&(e=e||t.ctrlKey!==g.control,g.control=!!t.ctrlKey),"metaKey"in t&&(e=e||t.metaKey!==g.meta,g.meta=!!t.metaKey),e}function n(t,n){var a=i.x(n),o=i.y(n);"buttons"in n&&(t=0|n.buttons),(t!==f||a!==d||o!==p||r(n))&&(f=0|t,d=a||0,p=o||0,e(f,d,p,g))}function a(t){n(0,t)}function o(){(f||d||p||g.shift||g.alt||g.meta||g.control)&&(d=p=0,f=0,g.shift=g.alt=g.control=g.meta=!1,e(0,0,0,g))}function s(t){r(t)&&e(f,d,p,g)}function l(t){0===i.buttons(t)?n(0,t):n(f,t)}function u(t){n(f|i.buttons(t),t)}function c(t){n(f&~i.buttons(t),t)}function h(){v||(v=!0,t.addEventListener("mousemove",l),t.addEventListener("mousedown",u),t.addEventListener("mouseup",c),t.addEventListener("mouseleave",a),t.addEventListener("mouseenter",a),t.addEventListener("mouseout",a),t.addEventListener("mouseover",a),t.addEventListener("blur",o),t.addEventListener("keyup",s),t.addEventListener("keydown",s),t.addEventListener("keypress",s),t!==window&&(window.addEventListener("blur",o),window.addEventListener("keyup",s),window.addEventListener("keydown",s),window.addEventListener("keypress",s)))}e||(e=t,t=window);var f=0,d=0,p=0,g={shift:!1,alt:!1,control:!1,meta:!1},v=!1;h();var m={element:t};return Object.defineProperties(m,{enabled:{get:function(){return v},set:function(t){t&&h()},enumerable:!0},buttons:{get:function(){return f},enumerable:!0},x:{get:function(){return d},enumerable:!0},y:{get:function(){return p},enumerable:!0},mods:{get:function(){return g},enumerable:!0}}),m}e.exports=n;var i=t("mouse-event")},{"mouse-event":197}],197:[function(t,e,r){"use strict";function n(t){if("object"==typeof t){if("buttons"in t)return t.buttons;if("which"in t){var e=t.which;if(2===e)return 4;if(3===e)return 2;if(e>0)return 1<<e-1}else if("button"in t){var e=t.button;if(1===e)return 4;if(2===e)return 2;if(e>=0)return 1<<e}}return 0}function i(t){return t.target||t.srcElement||window}function a(t){if("object"==typeof t){if("offsetX"in t)return t.offsetX;var e=i(t),r=e.getBoundingClientRect();return t.clientX-r.left}return 0}function o(t){if("object"==typeof t){if("offsetY"in t)return t.offsetY;var e=i(t),r=e.getBoundingClientRect();return t.clientY-r.top}return 0}r.buttons=n,r.element=i,r.x=a,r.y=o},{}],198:[function(t,e,r){e.exports=function(t,e){e||(e=[0,""]),t=String(t);var r=parseFloat(t,10);return e[0]=r,e[1]=t.match(/[\d.\-\+]*\s*(.*)/)[1]||"",e}},{}],199:[function(t,e,r){"use strict";function n(t,e){var r=o(getComputedStyle(t).getPropertyValue(e));return r[0]*a(r[1],t)}function i(t,e){var r=document.createElement("div");r.style["font-size"]="128"+t,e.appendChild(r);var i=n(r,"font-size")/128;return e.removeChild(r),i}function a(t,e){switch(e=e||document.body,t=(t||"px").trim().toLowerCase(),(e===window||e===document)&&(e=document.body),t){case"%":return e.clientHeight/100;case"ch":case"ex":return i(t,e);case"em":return n(e,"font-size");case"rem":return n(document.body,"font-size");case"vw":return window.innerWidth/100;case"vh":return window.innerHeight/100;case"vmin":return Math.min(window.innerWidth,window.innerHeight)/100;case"vmax":return Math.max(window.innerWidth,window.innerHeight)/100;case"in":return s;case"cm":return s/2.54;case"mm":return s/25.4;case"pt":return s/72;case"pc":return s/6}return 1}var o=t("parse-unit");e.exports=a;var s=96},{"parse-unit":198}],200:[function(t,e,r){"use strict";function n(t,e,r){"function"==typeof t&&(r=!!e,e=t,t=window);var n=i("ex",t);t.addEventListener("wheel",function(t){r&&t.preventDefault();var i=t.deltaX||0,a=t.deltaY||0,o=t.deltaZ||0,s=t.deltaMode,l=1;switch(s){case 1:l=n;break;case 2:l=window.innerHeight}return i*=l,a*=l,o*=l,i||a||o?e(i,a,o):void 0})}var i=t("to-px");e.exports=n},{"to-px":199}],201:[function(t,e,r){"use strict";var n=t("cwise/lib/wrapper")({
+args:["index","array","scalar"],pre:{body:"{}",args:[],thisVars:[],localVars:[]},body:{body:"{_inline_1_arg1_=_inline_1_arg2_.apply(void 0,_inline_1_arg0_)}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"cwise",blockSize:64});e.exports=function(t,e){return n(t,e),t}},{"cwise/lib/wrapper":69}],202:[function(t,e,r){"use strict";function n(t,e){switch(e.length){case 0:break;case 1:t[0]=1/e[0];break;case 4:i(t,e);break;case 9:a(t,e);break;case 16:o(t,e);break;default:throw new Error("currently supports matrices up to 4x4")}return t}e.exports=n;var i=t("gl-mat2/invert"),a=t("gl-mat3/invert"),o=t("gl-mat4/invert")},{"gl-mat2/invert":203,"gl-mat3/invert":87,"gl-mat4/invert":94}],203:[function(t,e,r){function n(t,e){var r=e[0],n=e[1],i=e[2],a=e[3],o=r*a-i*n;return o?(o=1/o,t[0]=a*o,t[1]=-n*o,t[2]=-i*o,t[3]=r*o,t):null}e.exports=n},{}],204:[function(t,e,r){"use strict";function n(t,e){var r=Math.floor(e),n=e-r,i=r>=0&&r<t.shape[0],a=r+1>=0&&r+1<t.shape[0],o=i?+t.get(r):0,s=a?+t.get(r+1):0;return(1-n)*o+n*s}function i(t,e,r){var n=Math.floor(e),i=e-n,a=n>=0&&n<t.shape[0],o=n+1>=0&&n+1<t.shape[0],s=Math.floor(r),l=r-s,u=s>=0&&s<t.shape[1],c=s+1>=0&&s+1<t.shape[1],h=a&&u?t.get(n,s):0,f=a&&c?t.get(n,s+1):0,d=o&&u?t.get(n+1,s):0,p=o&&c?t.get(n+1,s+1):0;return(1-l)*((1-i)*h+i*d)+l*((1-i)*f+i*p)}function a(t,e,r,n){var i=Math.floor(e),a=e-i,o=i>=0&&i<t.shape[0],s=i+1>=0&&i+1<t.shape[0],l=Math.floor(r),u=r-l,c=l>=0&&l<t.shape[1],h=l+1>=0&&l+1<t.shape[1],f=Math.floor(n),d=n-f,p=f>=0&&f<t.shape[2],g=f+1>=0&&f+1<t.shape[2],v=o&&c&&p?t.get(i,l,f):0,m=o&&h&&p?t.get(i,l+1,f):0,y=s&&c&&p?t.get(i+1,l,f):0,b=s&&h&&p?t.get(i+1,l+1,f):0,x=o&&c&&g?t.get(i,l,f+1):0,_=o&&h&&g?t.get(i,l+1,f+1):0,w=s&&c&&g?t.get(i+1,l,f+1):0,A=s&&h&&g?t.get(i+1,l+1,f+1):0;return(1-d)*((1-u)*((1-a)*v+a*y)+u*((1-a)*m+a*b))+d*((1-u)*((1-a)*x+a*w)+u*((1-a)*_+a*A))}function o(t){var e,r,n=0|t.shape.length,i=new Array(n),a=new Array(n),o=new Array(n),s=new Array(n);for(e=0;n>e;++e)r=+arguments[e+1],i[e]=Math.floor(r),a[e]=r-i[e],o[e]=0<=i[e]&&i[e]<t.shape[e],s[e]=0<=i[e]+1&&i[e]+1<t.shape[e];var l,u,c,h=0;t:for(e=0;1<<n>e;++e){for(u=1,c=t.offset,l=0;n>l;++l)if(e&1<<l){if(!s[l])continue t;u*=a[l],c+=t.stride[l]*(i[l]+1)}else{if(!o[l])continue t;u*=1-a[l],c+=t.stride[l]*i[l]}h+=u*t.data[c]}return h}function s(t,e,r,s){switch(t.shape.length){case 0:return 0;case 1:return n(t,e);case 2:return i(t,e,r);case 3:return a(t,e,r,s);default:return o.apply(void 0,arguments)}}e.exports=s,e.exports.d1=n,e.exports.d2=i,e.exports.d3=a},{}],205:[function(t,e,r){"use strict";var n=t("ndarray-linear-interpolate"),i=t("cwise/lib/wrapper")({args:["index","array","scalar","scalar","scalar"],pre:{body:"{this_warped=new Array(_inline_6_arg4_)}",args:[{name:"_inline_6_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_6_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_6_arg2_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_6_arg3_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_6_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},body:{body:"{_inline_7_arg2_(this_warped,_inline_7_arg0_),_inline_7_arg1_=_inline_7_arg3_.apply(void 0,this_warped)}",args:[{name:"_inline_7_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_7_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_7_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_7_arg3_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"warpND",blockSize:64}),a=t("cwise/lib/wrapper")({args:["index","array","scalar","scalar","scalar"],pre:{body:"{this_warped=[0]}",args:[],thisVars:["this_warped"],localVars:[]},body:{body:"{_inline_10_arg2_(this_warped,_inline_10_arg0_),_inline_10_arg1_=_inline_10_arg3_(_inline_10_arg4_,this_warped[0])}",args:[{name:"_inline_10_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_10_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_10_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_10_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_10_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"warp1D",blockSize:64}),o=t("cwise/lib/wrapper")({args:["index","array","scalar","scalar","scalar"],pre:{body:"{this_warped=[0,0]}",args:[],thisVars:["this_warped"],localVars:[]},body:{body:"{_inline_13_arg2_(this_warped,_inline_13_arg0_),_inline_13_arg1_=_inline_13_arg3_(_inline_13_arg4_,this_warped[0],this_warped[1])}",args:[{name:"_inline_13_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_13_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_13_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_13_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_13_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"warp2D",blockSize:64}),s=t("cwise/lib/wrapper")({args:["index","array","scalar","scalar","scalar"],pre:{body:"{this_warped=[0,0,0]}",args:[],thisVars:["this_warped"],localVars:[]},body:{body:"{_inline_16_arg2_(this_warped,_inline_16_arg0_),_inline_16_arg1_=_inline_16_arg3_(_inline_16_arg4_,this_warped[0],this_warped[1],this_warped[2])}",args:[{name:"_inline_16_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_16_arg1_",lvalue:!0,rvalue:!1,count:1},{name:"_inline_16_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_16_arg3_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_16_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_warped"],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},debug:!1,funcName:"warp3D",blockSize:64});e.exports=function(t,e,r){switch(e.shape.length){case 1:a(t,r,n.d1,e);break;case 2:o(t,r,n.d2,e);break;case 3:s(t,r,n.d3,e);break;default:i(t,r,n.bind(void 0,e),e.shape.length)}return t}},{"cwise/lib/wrapper":69,"ndarray-linear-interpolate":204}],206:[function(t,e,r){"use strict";function n(t,e,r){var n=e.dimension,o=a([],r);return i(t,e,function(t,e){for(var r=0;n>r;++r){t[r]=o[(n+1)*n+r];for(var i=0;n>i;++i)t[r]+=o[(n+1)*i+r]*e[i]}for(var a=o[(n+1)*(n+1)-1],i=0;n>i;++i)a+=o[(n+1)*i+n]*e[i];for(var s=1/a,r=0;n>r;++r)t[r]*=s;return t}),t}var i=t("ndarray-warp"),a=t("gl-matrix-invert");e.exports=n},{"gl-matrix-invert":202,"ndarray-warp":205}],207:[function(t,e,r){"use strict";function n(t){if(!t)return s;for(var e=0;e<t.args.length;++e){var r=t.args[e];0===e?t.args[e]={name:r,lvalue:!0,rvalue:!!t.rvalue,count:t.count||1}:t.args[e]={name:r,lvalue:!1,rvalue:!0,count:1}}return t.thisVars||(t.thisVars=[]),t.localVars||(t.localVars=[]),t}function i(t){return o({args:t.args,pre:n(t.pre),body:n(t.body),post:n(t.proc),funcName:t.funcName})}function a(t){for(var e=[],r=0;r<t.args.length;++r)e.push("a"+r);var n=new Function("P",["return function ",t.funcName,"_ndarrayops(",e.join(","),") {P(",e.join(","),");return a0}"].join(""));return n(i(t))}var o=t("cwise-compiler"),s={body:"",args:[],thisVars:[],localVars:[]},l={add:"+",sub:"-",mul:"*",div:"/",mod:"%",band:"&",bor:"|",bxor:"^",lshift:"<<",rshift:">>",rrshift:">>>"};!function(){for(var t in l){var e=l[t];r[t]=a({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"eq"]=a({args:["array","array"],body:{args:["a","b"],body:"a"+e+"=b"},rvalue:!0,funcName:t+"eq"}),r[t+"s"]=a({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"seq"]=a({args:["array","scalar"],body:{args:["a","s"],body:"a"+e+"=s"},rvalue:!0,funcName:t+"seq"})}}();var u={not:"!",bnot:"~",neg:"-",recip:"1.0/"};!function(){for(var t in u){var e=u[t];r[t]=a({args:["array","array"],body:{args:["a","b"],body:"a="+e+"b"},funcName:t}),r[t+"eq"]=a({args:["array"],body:{args:["a"],body:"a="+e+"a"},rvalue:!0,count:2,funcName:t+"eq"})}}();var c={and:"&&",or:"||",eq:"===",neq:"!==",lt:"<",gt:">",leq:"<=",geq:">="};!function(){for(var t in c){var e=c[t];r[t]=a({args:["array","array","array"],body:{args:["a","b","c"],body:"a=b"+e+"c"},funcName:t}),r[t+"s"]=a({args:["array","array","scalar"],body:{args:["a","b","s"],body:"a=b"+e+"s"},funcName:t+"s"}),r[t+"eq"]=a({args:["array","array"],body:{args:["a","b"],body:"a=a"+e+"b"},rvalue:!0,count:2,funcName:t+"eq"}),r[t+"seq"]=a({args:["array","scalar"],body:{args:["a","s"],body:"a=a"+e+"s"},rvalue:!0,count:2,funcName:t+"seq"})}}();var h=["abs","acos","asin","atan","ceil","cos","exp","floor","log","round","sin","sqrt","tan"];!function(){for(var t=0;t<h.length;++t){var e=h[t];r[e]=a({args:["array","array"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b)",thisVars:["this_f"]},funcName:e}),r[e+"eq"]=a({args:["array"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a"],body:"a=this_f(a)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:e+"eq"})}}();var f=["max","min","atan2","pow"];!function(){for(var t=0;t<f.length;++t){var e=f[t];r[e]=a({args:["array","array","array"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(b,c)",thisVars:["this_f"]},funcName:e}),r[e+"s"]=a({args:["array","array","scalar"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(b,c)",thisVars:["this_f"]},funcName:e+"s"}),r[e+"eq"]=a({args:["array","array"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(a,b)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:e+"eq"}),r[e+"seq"]=a({args:["array","scalar"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(a,b)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:e+"seq"})}}();var d=["atan2","pow"];!function(){for(var t=0;t<d.length;++t){var e=d[t];r[e+"op"]=a({args:["array","array","array"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(c,b)",thisVars:["this_f"]},funcName:e+"op"}),r[e+"ops"]=a({args:["array","array","scalar"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b","c"],body:"a=this_f(c,b)",thisVars:["this_f"]},funcName:e+"ops"}),r[e+"opeq"]=a({args:["array","array"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b,a)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:e+"opeq"}),r[e+"opseq"]=a({args:["array","scalar"],pre:{args:[],body:"this_f=Math."+e,thisVars:["this_f"]},body:{args:["a","b"],body:"a=this_f(b,a)",thisVars:["this_f"]},rvalue:!0,count:2,funcName:e+"opseq"})}}(),r.any=o({args:["array"],pre:s,body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"if(a){return true}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return false"},funcName:"any"}),r.all=o({args:["array"],pre:s,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1}],body:"if(!x){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"all"}),r.sum=o({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"this_s+=a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"sum"}),r.prod=o({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=1"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:1}],body:"this_s*=a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"prod"}),r.norm2squared=o({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:2}],body:"this_s+=a*a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm2squared"}),r.norm2=o({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:2}],body:"this_s+=a*a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return Math.sqrt(this_s)"},funcName:"norm2"}),r.norminf=o({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:4}],body:"if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norminf"}),r.norm1=o({args:["array"],pre:{args:[],localVars:[],thisVars:["this_s"],body:"this_s=0"},body:{args:[{name:"a",lvalue:!1,rvalue:!0,count:3}],body:"this_s+=a<0?-a:a",localVars:[],thisVars:["this_s"]},post:{args:[],localVars:[],thisVars:["this_s"],body:"return this_s"},funcName:"norm1"}),r.sup=o({args:["array"],pre:{body:"this_h=-Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.inf=o({args:["array"],pre:{body:"this_h=Infinity",args:[],thisVars:["this_h"],localVars:[]},body:{body:"if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_h"],localVars:[]},post:{body:"return this_h",args:[],thisVars:["this_h"],localVars:[]}}),r.argmin=o({args:["index","array","shape"],pre:{body:"{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}",args:[{name:"_inline_0_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_i","this_v"],localVars:[]},body:{body:"{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.argmax=o({args:["index","array","shape"],pre:{body:"{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}",args:[{name:"_inline_0_arg0_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg1_",lvalue:!1,rvalue:!1,count:0},{name:"_inline_0_arg2_",lvalue:!1,rvalue:!0,count:1}],thisVars:["this_i","this_v"],localVars:[]},body:{body:"{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:2}],thisVars:["this_i","this_v"],localVars:["_inline_1_k"]},post:{body:"{return this_i}",args:[],thisVars:["this_i"],localVars:[]}}),r.random=a({args:["array"],pre:{args:[],body:"this_f=Math.random",thisVars:["this_f"]},body:{args:["a"],body:"a=this_f()",thisVars:["this_f"]},funcName:"random"}),r.assign=a({args:["array","array"],body:{args:["a","b"],body:"a=b"},funcName:"assign"}),r.assigns=a({args:["array","scalar"],body:{args:["a","b"],body:"a=b"},funcName:"assigns"}),r.equals=o({args:["array","array"],pre:s,body:{args:[{name:"x",lvalue:!1,rvalue:!0,count:1},{name:"y",lvalue:!1,rvalue:!0,count:1}],body:"if(x!==y){return false}",localVars:[],thisVars:[]},post:{args:[],localVars:[],thisVars:[],body:"return true"},funcName:"equals"})},{"cwise-compiler":66}],208:[function(t,e,r){function n(t,e){return t[0]-e[0]}function i(){var t,e=this.stride,r=new Array(e.length);for(t=0;t<r.length;++t)r[t]=[Math.abs(e[t]),t];r.sort(n);var i=new Array(r.length);for(t=0;t<i.length;++t)i[t]=r[t][1];return i}function a(t,e){var r=["View",e,"d",t].join("");0>e&&(r="View_Nil"+t);var n="generic"===t;if(-1===e){var a="function "+r+"(a){this.data=a;};var proto="+r+".prototype;proto.dtype='"+t+"';proto.index=function(){return -1};proto.size=0;proto.dimension=-1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function(){return new "+r+"(this.data);};proto.get=proto.set=function(){};proto.pick=function(){return null};return function construct_"+r+"(a){return new "+r+"(a);}",o=new Function(a);return o()}if(0===e){var a="function "+r+"(a,d) {this.data = a;this.offset = d};var proto="+r+".prototype;proto.dtype='"+t+"';proto.index=function(){return this.offset};proto.dimension=0;proto.size=1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function "+r+"_copy() {return new "+r+"(this.data,this.offset)};proto.pick=function "+r+"_pick(){return TrivialArray(this.data);};proto.valueOf=proto.get=function "+r+"_get(){return "+(n?"this.data.get(this.offset)":"this.data[this.offset]")+"};proto.set=function "+r+"_set(v){return "+(n?"this.data.set(this.offset,v)":"this.data[this.offset]=v")+"};return function construct_"+r+"(a,b,c,d){return new "+r+"(a,d)}",o=new Function("TrivialArray",a);return o(h[t][0])}var a=["'use strict'"],s=l(e),u=s.map(function(t){return"i"+t}),c="this.offset+"+s.map(function(t){return"this.stride["+t+"]*i"+t}).join("+"),f=s.map(function(t){return"b"+t}).join(","),d=s.map(function(t){return"c"+t}).join(",");a.push("function "+r+"(a,"+f+","+d+",d){this.data=a","this.shape=["+f+"]","this.stride=["+d+"]","this.offset=d|0}","var proto="+r+".prototype","proto.dtype='"+t+"'","proto.dimension="+e),a.push("Object.defineProperty(proto,'size',{get:function "+r+"_size(){return "+s.map(function(t){return"this.shape["+t+"]"}).join("*"),"}})"),1===e?a.push("proto.order=[0]"):(a.push("Object.defineProperty(proto,'order',{get:"),4>e?(a.push("function "+r+"_order(){"),2===e?a.push("return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})"):3===e&&a.push("var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})")):a.push("ORDER})")),a.push("proto.set=function "+r+"_set("+u.join(",")+",v){"),n?a.push("return this.data.set("+c+",v)}"):a.push("return this.data["+c+"]=v}"),a.push("proto.get=function "+r+"_get("+u.join(",")+"){"),n?a.push("return this.data.get("+c+")}"):a.push("return this.data["+c+"]}"),a.push("proto.index=function "+r+"_index(",u.join(),"){return "+c+"}"),a.push("proto.hi=function "+r+"_hi("+u.join(",")+"){return new "+r+"(this.data,"+s.map(function(t){return["(typeof i",t,"!=='number'||i",t,"<0)?this.shape[",t,"]:i",t,"|0"].join("")}).join(",")+","+s.map(function(t){return"this.stride["+t+"]"}).join(",")+",this.offset)}");var p=s.map(function(t){return"a"+t+"=this.shape["+t+"]"}),g=s.map(function(t){return"c"+t+"=this.stride["+t+"]"});a.push("proto.lo=function "+r+"_lo("+u.join(",")+"){var b=this.offset,d=0,"+p.join(",")+","+g.join(","));for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'&&i"+v+">=0){d=i"+v+"|0;b+=c"+v+"*d;a"+v+"-=d}");a.push("return new "+r+"(this.data,"+s.map(function(t){return"a"+t}).join(",")+","+s.map(function(t){return"c"+t}).join(",")+",b)}"),a.push("proto.step=function "+r+"_step("+u.join(",")+"){var "+s.map(function(t){return"a"+t+"=this.shape["+t+"]"}).join(",")+","+s.map(function(t){return"b"+t+"=this.stride["+t+"]"}).join(",")+",c=this.offset,d=0,ceil=Math.ceil");for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'){d=i"+v+"|0;if(d<0){c+=b"+v+"*(a"+v+"-1);a"+v+"=ceil(-a"+v+"/d)}else{a"+v+"=ceil(a"+v+"/d)}b"+v+"*=d}");a.push("return new "+r+"(this.data,"+s.map(function(t){return"a"+t}).join(",")+","+s.map(function(t){return"b"+t}).join(",")+",c)}");for(var m=new Array(e),y=new Array(e),v=0;e>v;++v)m[v]="a[i"+v+"]",y[v]="b[i"+v+"]";a.push("proto.transpose=function "+r+"_transpose("+u+"){"+u.map(function(t,e){return t+"=("+t+"===undefined?"+e+":"+t+"|0)"}).join(";"),"var a=this.shape,b=this.stride;return new "+r+"(this.data,"+m.join(",")+","+y.join(",")+",this.offset)}"),a.push("proto.pick=function "+r+"_pick("+u+"){var a=[],b=[],c=this.offset");for(var v=0;e>v;++v)a.push("if(typeof i"+v+"==='number'&&i"+v+">=0){c=(c+this.stride["+v+"]*i"+v+")|0}else{a.push(this.shape["+v+"]);b.push(this.stride["+v+"])}");a.push("var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}"),a.push("return function construct_"+r+"(data,shape,stride,offset){return new "+r+"(data,"+s.map(function(t){return"shape["+t+"]"}).join(",")+","+s.map(function(t){return"stride["+t+"]"}).join(",")+",offset)}");var o=new Function("CTOR_LIST","ORDER",a.join("\n"));return o(h[t],i)}function o(t){if(u(t))return"buffer";if(c)switch(Object.prototype.toString.call(t)){case"[object Float64Array]":return"float64";case"[object Float32Array]":return"float32";case"[object Int8Array]":return"int8";case"[object Int16Array]":return"int16";case"[object Int32Array]":return"int32";case"[object Uint8Array]":return"uint8";case"[object Uint16Array]":return"uint16";case"[object Uint32Array]":return"uint32";case"[object Uint8ClampedArray]":return"uint8_clamped"}return Array.isArray(t)?"array":"generic"}function s(t,e,r,n){if(void 0===t){var i=h.array[0];return i([])}"number"==typeof t&&(t=[t]),void 0===e&&(e=[t.length]);var s=e.length;if(void 0===r){r=new Array(s);for(var l=s-1,u=1;l>=0;--l)r[l]=u,u*=e[l]}if(void 0===n){n=0;for(var l=0;s>l;++l)r[l]<0&&(n-=(e[l]-1)*r[l])}for(var c=o(t),f=h[c];f.length<=s+1;)f.push(a(c,f.length-1));var i=f[s+1];return i(t,e,r,n)}var l=t("iota-array"),u=t("is-buffer"),c="undefined"!=typeof Float64Array,h={float32:[],float64:[],int8:[],int16:[],int32:[],uint8:[],uint16:[],uint32:[],array:[],uint8_clamped:[],buffer:[],generic:[]};e.exports=s},{"iota-array":195,"is-buffer":209}],209:[function(t,e,r){e.exports=function(t){return!(null==t||!(t._isBuffer||t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)))}},{}],210:[function(t,e,r){(function(t){e.exports=t.performance&&t.performance.now?function(){return performance.now()}:Date.now||function(){return+new Date}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],211:[function(t,e,r){"use strict";function n(t){for(var e="robustLinearSolve"+t+"d",r=["function ",e,"(A,b){return ["],n=0;t>n;++n){r.push("det([");for(var i=0;t>i;++i){i>0&&r.push(","),r.push("[");for(var a=0;t>a;++a)a>0&&r.push(","),a===n?r.push("+b[",i,"]"):r.push("+A[",i,"][",a,"]");r.push("]")}r.push("]),")}r.push("det(A)]}return ",e);var o=new Function("det",r.join(""));return o(6>t?s[t]:s)}function i(){return[0]}function a(t,e){return[[e[0]],[t[0][0]]]}function o(){for(;u.length<l;)u.push(n(u.length));for(var t=[],r=["function dispatchLinearSolve(A,b){switch(A.length){"],i=0;l>i;++i)t.push("s"+i),r.push("case ",i,":return s",i,"(A,b);");r.push("}var s=CACHE[A.length];if(!s)s=CACHE[A.length]=g(A.length);return s(A,b)}return dispatchLinearSolve"),t.push("CACHE","g",r.join(""));var a=Function.apply(void 0,t);e.exports=a.apply(void 0,u.concat([u,n]));for(var i=0;l>i;++i)e.exports[i]=u[i]}var s=t("robust-determinant"),l=6,u=[i,a];o()},{"robust-determinant":213}],212:[function(t,e,r){"use strict";function n(t){for(var e=t.length,r=t[t.length-1],n=e,i=e-2;i>=0;--i){var a=r,o=t[i];r=a+o;var s=r-a,l=o-s;l&&(t[--n]=r,r=l)}for(var u=0,i=n;e>i;++i){var a=t[i],o=r;r=a+o;var s=r-a,l=o-s;l&&(t[u++]=l)}return t[u++]=r,t.length=u,t}e.exports=n},{}],213:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t.length-1),n=1;n<t.length;++n)for(var i=r[n-1]=new Array(t.length-1),a=0,o=0;a<t.length;++a)a!==e&&(i[o++]=t[n][a]);return r}function i(t){for(var e=new Array(t),r=0;t>r;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m[",r,"][",n,"]"].join("")}return e}function a(t){return 1&t?"-":""}function o(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",o(t.slice(0,e)),",",o(t.slice(e)),")"].join("")}function s(t){if(2===t.length)return["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("");for(var e=[],r=0;r<t.length;++r)e.push(["scale(",s(n(t,r)),",",a(r),t[0][r],")"].join(""));return o(e)}function l(t){var e=new Function("sum","scale","prod","compress",["function robustDeterminant",t,"(m){return compress(",s(i(t)),")};return robustDeterminant",t].join(""));return e(h,f,c,d)}function u(){for(;g.length<p;)g.push(l(g.length));for(var t=[],r=["function robustDeterminant(m){switch(m.length){"],n=0;p>n;++n)t.push("det"+n),r.push("case ",n,":return det",n,"(m);");r.push("}var det=CACHE[m.length];if(!det)det=CACHE[m.length]=gen(m.length);return det(m);}return robustDeterminant"),t.push("CACHE","gen",r.join(""));var i=Function.apply(void 0,t);e.exports=i.apply(void 0,g.concat([g,l]));for(var n=0;n<g.length;++n)e.exports[n]=g[n]}var c=t("two-product"),h=t("robust-sum"),f=t("robust-scale"),d=t("robust-compress"),p=6,g=[function(){return[0]},function(t){return[t[0][0]]}];u()},{"robust-compress":212,"robust-scale":215,"robust-sum":217,"two-product":231}],214:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t.length-1),n=1;n<t.length;++n)for(var i=r[n-1]=new Array(t.length-1),a=0,o=0;a<t.length;++a)a!==e&&(i[o++]=t[n][a]);return r}function i(t){for(var e=new Array(t),r=0;t>r;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m",n,"[",t-r-1,"]"].join("")}return e}function a(t){return 1&t?"-":""}function o(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",o(t.slice(0,e)),",",o(t.slice(e)),")"].join("")}function s(t){if(2===t.length)return[["sum(prod(",t[0][0],",",t[1][1],"),prod(-",t[0][1],",",t[1][0],"))"].join("")];for(var e=[],r=0;r<t.length;++r)e.push(["scale(",o(s(n(t,r))),",",a(r),t[0][r],")"].join(""));return e}function l(t){for(var e=[],r=[],a=i(t),l=[],u=0;t>u;++u)0===(1&u)?e.push.apply(e,s(n(a,u))):r.push.apply(r,s(n(a,u))),l.push("m"+u);var c=o(e),g=o(r),v="orientation"+t+"Exact",m=["function ",v,"(",l.join(),"){var p=",c,",n=",g,",d=sub(p,n);return d[d.length-1];};return ",v].join(""),y=new Function("sum","prod","scale","sub",m);return y(f,h,d,p)}function u(t){var e=_[t.length];return e||(e=_[t.length]=l(t.length)),e.apply(void 0,t)}function c(){for(;_.length<=g;)_.push(l(_.length));for(var t=[],r=["slow"],n=0;g>=n;++n)t.push("a"+n),r.push("o"+n);for(var i=["function getOrientation(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"],n=2;g>=n;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i<arguments.length;++i){s[i]=arguments[i]};return slow(s);}return getOrientation"),r.push(i.join(""));var a=Function.apply(void 0,r);e.exports=a.apply(void 0,[u].concat(_));for(var n=0;g>=n;++n)e.exports[n]=_[n]}var h=t("two-product"),f=t("robust-sum"),d=t("robust-scale"),p=t("robust-subtract"),g=5,v=1.1102230246251565e-16,m=(3+16*v)*v,y=(7+56*v)*v,b=l(3),x=l(4),_=[function(){return 0},function(){return 0},function(t,e){return e[0]-t[0]},function(t,e,r){var n,i=(t[1]-r[1])*(e[0]-r[0]),a=(t[0]-r[0])*(e[1]-r[1]),o=i-a;if(i>0){if(0>=a)return o;n=i+a}else{if(!(0>i))return o;if(a>=0)return o;n=-(i+a)}var s=m*n;return o>=s||-s>=o?o:b(t,e,r)},function(t,e,r,n){var i=t[0]-n[0],a=e[0]-n[0],o=r[0]-n[0],s=t[1]-n[1],l=e[1]-n[1],u=r[1]-n[1],c=t[2]-n[2],h=e[2]-n[2],f=r[2]-n[2],d=a*u,p=o*l,g=o*s,v=i*u,m=i*l,b=a*s,_=c*(d-p)+h*(g-v)+f*(m-b),w=(Math.abs(d)+Math.abs(p))*Math.abs(c)+(Math.abs(g)+Math.abs(v))*Math.abs(h)+(Math.abs(m)+Math.abs(b))*Math.abs(f),A=y*w;return _>A||-_>A?_:x(t,e,r,n)}];c()},{"robust-scale":215,"robust-subtract":216,"robust-sum":217,"two-product":231}],215:[function(t,e,r){"use strict";function n(t,e){var r=t.length;if(1===r){var n=i(t[0],e);return n[0]?n:[n[1]]}var o=new Array(2*r),s=[.1,.1],l=[.1,.1],u=0;i(t[0],e,s),s[0]&&(o[u++]=s[0]);for(var c=1;r>c;++c){i(t[c],e,l);var h=s[1];a(h,l[0],s),s[0]&&(o[u++]=s[0]);var f=l[1],d=s[1],p=f+d,g=p-f,v=d-g;s[1]=p,v&&(o[u++]=v)}return s[1]&&(o[u++]=s[1]),0===u&&(o[u++]=0),o.length=u,o}var i=t("two-product"),a=t("two-sum");e.exports=n},{"two-product":231,"two-sum":232}],216:[function(t,e,r){"use strict";function n(t,e){var r=t+e,n=r-t,i=r-n,a=e-n,o=t-i,s=o+a;return s?[s,r]:[r]}function i(t,e){var r=0|t.length,i=0|e.length;if(1===r&&1===i)return n(t[0],-e[0]);var a,o,s=r+i,l=new Array(s),u=0,c=0,h=0,f=Math.abs,d=t[c],p=f(d),g=-e[h],v=f(g);v>p?(o=d,c+=1,r>c&&(d=t[c],p=f(d))):(o=g,h+=1,i>h&&(g=-e[h],v=f(g))),r>c&&v>p||h>=i?(a=d,c+=1,r>c&&(d=t[c],p=f(d))):(a=g,h+=1,i>h&&(g=-e[h],v=f(g)));for(var m,y,b,x,_,w=a+o,A=w-a,k=o-A,M=k,T=w;r>c&&i>h;)v>p?(a=d,c+=1,r>c&&(d=t[c],p=f(d))):(a=g,h+=1,i>h&&(g=-e[h],v=f(g))),o=M,w=a+o,A=w-a,k=o-A,k&&(l[u++]=k),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m;for(;r>c;)a=d,o=M,w=a+o,A=w-a,k=o-A,k&&(l[u++]=k),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,c+=1,r>c&&(d=t[c]);for(;i>h;)a=g,o=M,w=a+o,A=w-a,k=o-A,k&&(l[u++]=k),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,h+=1,i>h&&(g=-e[h]);return M&&(l[u++]=M),T&&(l[u++]=T),u||(l[u++]=0),l.length=u,l}e.exports=i},{}],217:[function(t,e,r){"use strict";function n(t,e){var r=t+e,n=r-t,i=r-n,a=e-n,o=t-i,s=o+a;return s?[s,r]:[r]}function i(t,e){var r=0|t.length,i=0|e.length;if(1===r&&1===i)return n(t[0],e[0]);var a,o,s=r+i,l=new Array(s),u=0,c=0,h=0,f=Math.abs,d=t[c],p=f(d),g=e[h],v=f(g);v>p?(o=d,c+=1,r>c&&(d=t[c],p=f(d))):(o=g,h+=1,i>h&&(g=e[h],v=f(g))),r>c&&v>p||h>=i?(a=d,c+=1,r>c&&(d=t[c],p=f(d))):(a=g,h+=1,i>h&&(g=e[h],v=f(g)));for(var m,y,b,x,_,w=a+o,A=w-a,k=o-A,M=k,T=w;r>c&&i>h;)v>p?(a=d,c+=1,r>c&&(d=t[c],p=f(d))):(a=g,h+=1,i>h&&(g=e[h],v=f(g))),o=M,w=a+o,A=w-a,k=o-A,k&&(l[u++]=k),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m;for(;r>c;)a=d,o=M,w=a+o,A=w-a,k=o-A,k&&(l[u++]=k),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,c+=1,r>c&&(d=t[c]);for(;i>h;)a=g,o=M,w=a+o,A=w-a,k=o-A,k&&(l[u++]=k),m=T+w,y=m-T,b=m-y,x=w-y,_=T-b,M=_+x,T=m,h+=1,i>h&&(g=e[h]);return M&&(l[u++]=M),T&&(l[u++]=T),u||(l[u++]=0),l.length=u,l}e.exports=i},{}],218:[function(t,e,r){"use strict";function n(t){return t.split("").map(function(t){return t in i?i[t]:""}).join("")}e.exports=n;var i={" ":" ",0:"\u2070",1:"\xb9",2:"\xb2",3:"\xb3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207a","-":"\u207b",a:"\u1d43",b:"\u1d47",c:"\u1d9c",d:"\u1d48",e:"\u1d49",f:"\u1da0",g:"\u1d4d",h:"\u02b0",i:"\u2071",j:"\u02b2",k:"\u1d4f",l:"\u02e1",m:"\u1d50",n:"\u207f",o:"\u1d52",p:"\u1d56",r:"\u02b3",s:"\u02e2",t:"\u1d57",u:"\u1d58",v:"\u1d5b",w:"\u02b7",x:"\u02e3",y:"\u02b8",z:"\u1dbb"}},{}],219:[function(t,e,r){"use strict";function n(t){return"a"+t}function i(t){return"d"+t}function a(t,e){return"c"+t+"_"+e}function o(t){return"s"+t}function s(t,e){return"t"+t+"_"+e}function l(t){return"o"+t}function u(t){return"x"+t}function c(t){return"p"+t}function h(t,e){return"d"+t+"_"+e}function f(t){return"i"+t}function d(t,e){return"u"+t+"_"+e}function p(t){return"b"+t}function g(t){return"y"+t}function v(t){return"e"+t}function m(t){return"v"+t}function y(t,e,r){for(var n=0,i=0;t>i;++i)e&1<<i&&(n|=1<<r[i]);return n}function b(t,e,r,b,x,L){function S(t,e){F.push("for(",f(x[t]),"=",e,";",f(x[t]),"<",o(x[t]),";","++",f(x[t]),"){")}function C(t){for(var e=0;I>e;++e)F.push(c(e),"+=",d(e,x[t]),";");F.push("}")}function P(t){for(var e=t-1;e>=0;--e)S(e,0);for(var r=[],e=0;I>e;++e)L[e]?r.push(i(e)+".get("+c(e)+")"):r.push(i(e)+"["+c(e)+"]");for(var e=0;b>e;++e)r.push(u(e));F.push(A,"[",T,"++]=phase(",r.join(),");");for(var e=0;t>e;++e)C(e);for(var n=0;I>n;++n)F.push(c(n),"+=",d(n,x[t]),";")}function z(t){for(var e=0;I>e;++e)L[e]?F.push(a(e,0),"=",i(e),".get(",c(e),");"):F.push(a(e,0),"=",i(e),"[",c(e),"];");for(var r=[],e=0;I>e;++e)r.push(a(e,0));for(var e=0;b>e;++e)r.push(u(e));F.push(p(0),"=",A,"[",T,"]=phase(",r.join(),");");for(var n=1;1<<j>n;++n)F.push(p(n),"=",A,"[",T,"+",v(n),"];");for(var o=[],n=1;1<<j>n;++n)o.push("("+p(0)+"!=="+p(n)+")");
+F.push("if(",o.join("||"),"){");for(var s=[],e=0;j>e;++e)s.push(f(e));for(var e=0;I>e;++e){s.push(a(e,0));for(var n=1;1<<j>n;++n)L[e]?F.push(a(e,n),"=",i(e),".get(",c(e),"+",h(e,n),");"):F.push(a(e,n),"=",i(e),"[",c(e),"+",h(e,n),"];"),s.push(a(e,n))}for(var e=0;1<<j>e;++e)s.push(p(e));for(var e=0;b>e;++e)s.push(u(e));F.push("vertex(",s.join(),");",m(0),"=",w,"[",T,"]=",k,"++;");for(var l=(1<<j)-1,d=p(l),n=0;j>n;++n)if(0===(t&~(1<<n))){for(var g=l^1<<n,y=p(g),x=[],_=g;_>0;_=_-1&g)x.push(w+"["+T+"+"+v(_)+"]");x.push(m(0));for(var _=0;I>_;++_)1&n?x.push(a(_,l),a(_,g)):x.push(a(_,g),a(_,l));1&n?x.push(d,y):x.push(y,d);for(var _=0;b>_;++_)x.push(u(_));F.push("if(",d,"!==",y,"){","face(",x.join(),")}")}F.push("}",T,"+=1;")}function R(){for(var t=1;1<<j>t;++t)F.push(E,"=",v(t),";",v(t),"=",g(t),";",g(t),"=",E,";")}function O(t,e){if(0>t)return void z(e);P(t),F.push("if(",o(x[t]),">0){",f(x[t]),"=1;"),O(t-1,e|1<<x[t]);for(var r=0;I>r;++r)F.push(c(r),"+=",d(r,x[t]),";");t===j-1&&(F.push(T,"=0;"),R()),S(t,2),O(t-1,e),t===j-1&&(F.push("if(",f(x[j-1]),"&1){",T,"=0;}"),R()),C(t),F.push("}")}var I=L.length,j=x.length;if(2>j)throw new Error("ndarray-extract-contour: Dimension must be at least 2");for(var N="extractContour"+x.join("_"),F=[],B=[],D=[],U=0;I>U;++U)D.push(n(U));for(var U=0;b>U;++U)D.push(u(U));for(var U=0;j>U;++U)B.push(o(U)+"="+n(0)+".shape["+U+"]|0");for(var U=0;I>U;++U){B.push(i(U)+"="+n(U)+".data",l(U)+"="+n(U)+".offset|0");for(var V=0;j>V;++V)B.push(s(U,V)+"="+n(U)+".stride["+V+"]|0")}for(var U=0;I>U;++U){B.push(c(U)+"="+l(U)),B.push(a(U,0));for(var V=1;1<<j>V;++V){for(var q=[],H=0;j>H;++H)V&1<<H&&q.push("-"+s(U,H));B.push(h(U,V)+"=("+q.join("")+")|0"),B.push(a(U,V)+"=0")}}for(var U=0;I>U;++U)for(var V=0;j>V;++V){var G=[s(U,x[V])];V>0&&G.push(s(U,x[V-1])+"*"+o(x[V-1])),B.push(d(U,x[V])+"=("+G.join("-")+")|0")}for(var U=0;j>U;++U)B.push(f(U)+"=0");B.push(k+"=0");for(var Y=["2"],U=j-2;U>=0;--U)Y.push(o(x[U]));B.push(M+"=("+Y.join("*")+")|0",A+"=mallocUint32("+M+")",w+"=mallocUint32("+M+")",T+"=0"),B.push(p(0)+"=0");for(var V=1;1<<j>V;++V){for(var X=[],W=[],H=0;j>H;++H)V&1<<H&&(0===W.length?X.push("1"):X.unshift(W.join("*"))),W.push(o(x[H]));var Z="";X[0].indexOf(o(x[j-2]))<0&&(Z="-");var $=y(j,V,x);B.push(v($)+"=(-"+X.join("-")+")|0",g($)+"=("+Z+X.join("-")+")|0",p($)+"=0")}B.push(m(0)+"=0",E+"=0"),O(j-1,0),F.push("freeUint32(",w,");freeUint32(",A,");");var K=["'use strict';","function ",N,"(",D.join(),"){","var ",B.join(),";",F.join(""),"}","return ",N].join(""),Q=new Function("vertex","face","phase","mallocUint32","freeUint32",K);return Q(t,e,r,_.mallocUint32,_.freeUint32)}function x(t){function e(t){throw new Error("ndarray-extract-contour: "+t)}"object"!=typeof t&&e("Must specify arguments");var r=t.order;Array.isArray(r)||e("Must specify order");var n=t.arrayArguments||1;1>n&&e("Must have at least one array argument");var i=t.scalarArguments||0;0>i&&e("Scalar arg count must be > 0"),"function"!=typeof t.vertex&&e("Must specify vertex creation function"),"function"!=typeof t.cell&&e("Must specify cell creation function"),"function"!=typeof t.phase&&e("Must specify phase function");for(var a=t.getters||[],o=new Array(n),s=0;n>s;++s)a.indexOf(s)>=0?o[s]=!0:o[s]=!1;return b(t.vertex,t.cell,t.phase,i,r,o)}var _=t("typedarray-pool");e.exports=x;var w="V",A="P",k="N",M="Q",T="X",E="T"},{"typedarray-pool":233}],220:[function(t,e,r){function n(t){if(0>t)return Number("0/0");for(var e=s[0],r=s.length-1;r>0;--r)e+=s[r]/(t+r);var n=t+o+.5;return.5*Math.log(2*Math.PI)+(t+.5)*Math.log(n)-n+Math.log(e)-Math.log(t)}var i=7,a=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7],o=607/128,s=[.9999999999999971,57.15623566586292,-59.59796035547549,14.136097974741746,-.4919138160976202,3399464998481189e-20,4652362892704858e-20,-9837447530487956e-20,.0001580887032249125,-.00021026444172410488,.00021743961811521265,-.0001643181065367639,8441822398385275e-20,-26190838401581408e-21,36899182659531625e-22];e.exports=function l(t){if(.5>t)return Math.PI/(Math.sin(Math.PI*t)*l(1-t));if(t>100)return Math.exp(n(t));t-=1;for(var e=a[0],r=1;i+2>r;r++)e+=a[r]/(t+r);var o=t+i+.5;return Math.sqrt(2*Math.PI)*Math.pow(o,t+.5)*Math.exp(-o)*e},e.exports.log=n},{}],221:[function(t,e,r){"use strict";function n(t){var e=t.length;if(i>e){for(var r=1,n=0;e>n;++n)for(var o=0;n>o;++o)if(t[n]<t[o])r=-r;else if(t[n]===t[o])return 0;return r}for(var s=a.mallocUint8(e),n=0;e>n;++n)s[n]=0;for(var r=1,n=0;e>n;++n)if(!s[n]){var l=1;s[n]=1;for(var o=t[n];o!==n;o=t[o]){if(s[o])return a.freeUint8(s),0;l+=1,s[o]=1}1&l||(r=-r)}return a.freeUint8(s),r}e.exports=n;var i=32,a=t("typedarray-pool")},{"typedarray-pool":233}],222:[function(t,e,r){"use strict";function n(t){var e=t.length;switch(e){case 0:case 1:return 0;case 2:return t[1]}var r,n,i,s=a.mallocUint32(e),l=a.mallocUint32(e),u=0;for(o(t,l),i=0;e>i;++i)s[i]=t[i];for(i=e-1;i>0;--i)n=l[i],r=s[i],s[i]=s[n],s[n]=r,l[i]=l[r],l[r]=n,u=(u+r)*i;return a.freeUint32(l),a.freeUint32(s),u}function i(t,e,r){switch(t){case 0:return r?r:[];case 1:return r?(r[0]=0,r):[0];case 2:return r?(e?(r[0]=0,r[1]=1):(r[0]=1,r[1]=0),r):e?[0,1]:[1,0]}r=r||new Array(t);var n,i,a,o=1;for(r[0]=0,a=1;t>a;++a)r[a]=a,o=o*a|0;for(a=t-1;a>0;--a)n=e/o|0,e=e-n*o|0,o=o/a|0,i=0|r[a],r[a]=0|r[n],r[n]=0|i;return r}var a=t("typedarray-pool"),o=t("invert-permutation");r.rank=n,r.unrank=i},{"invert-permutation":223,"typedarray-pool":233}],223:[function(t,e,r){"use strict";function n(t,e){e=e||new Array(t.length);for(var r=0;r<t.length;++r)e[t[r]]=r;return e}e.exports=n},{}],224:[function(t,e,r){"use strict";function n(t){if(0>t)return[];if(0===t)return[[0]];for(var e=0|Math.round(o(t+1)),r=[],n=0;e>n;++n){for(var s=i.unrank(t,n),l=[0],u=0,c=0;c<s.length;++c)u+=1<<s[c],l.push(u);a(s)<1&&(l[0]=u,l[t]=0),r.push(l)}return r}e.exports=n;var i=t("permutation-rank"),a=t("permutation-parity"),o=t("gamma")},{gamma:220,"permutation-parity":221,"permutation-rank":222}],225:[function(t,e,r){e.exports=t("cwise-compiler")({args:["array",{offset:[1],array:0},"scalar","scalar","index"],pre:{body:"{}",args:[],thisVars:[],localVars:[]},post:{body:"{}",args:[],thisVars:[],localVars:[]},body:{body:"{\n        var _inline_1_da = _inline_1_arg0_ - _inline_1_arg3_\n        var _inline_1_db = _inline_1_arg1_ - _inline_1_arg3_\n        if((_inline_1_da >= 0) !== (_inline_1_db >= 0)) {\n          _inline_1_arg2_.push(_inline_1_arg4_[0] + 0.5 + 0.5 * (_inline_1_da + _inline_1_db) / (_inline_1_da - _inline_1_db))\n        }\n      }",args:[{name:"_inline_1_arg0_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg1_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg2_",lvalue:!1,rvalue:!0,count:1},{name:"_inline_1_arg3_",lvalue:!1,rvalue:!0,count:2},{name:"_inline_1_arg4_",lvalue:!1,rvalue:!0,count:1}],thisVars:[],localVars:["_inline_1_da","_inline_1_db"]},funcName:"zeroCrossings"})},{"cwise-compiler":66}],226:[function(t,e,r){"use strict";function n(t,e){var r=[];return e=+e||0,i(t.hi(t.shape[0]-1),r,e),r}e.exports=n;var i=t("./lib/zc-core")},{"./lib/zc-core":225}],227:[function(t,e,r){"use strict";function n(t,e){var r=t.length,n=["'use strict';"],i="surfaceNets"+t.join("_")+"d"+e;n.push("var contour=genContour({","order:[",t.join(),"],","scalarArguments: 3,","phase:function phaseFunc(p,a,b,c) { return (p > c)|0 },"),"generic"===e&&n.push("getters:[0],");for(var a=[],l=[],u=0;r>u;++u)a.push("d"+u),l.push("d"+u);for(var u=0;1<<r>u;++u)a.push("v"+u),l.push("v"+u);for(var u=0;1<<r>u;++u)a.push("p"+u),l.push("p"+u);a.push("a","b","c"),l.push("a","c"),n.push("vertex:function vertexFunc(",a.join(),"){");for(var c=[],u=0;1<<r>u;++u)c.push("(p"+u+"<<"+u+")");n.push("var m=(",c.join("+"),")|0;if(m===0||m===",(1<<(1<<r))-1,"){return}");var h=[],f=[];128>=1<<(1<<r)?(n.push("switch(m){"),f=n):n.push("switch(m>>>7){");for(var u=0;1<<(1<<r)>u;++u){if(1<<(1<<r)>128&&u%128===0){h.length>0&&f.push("}}");var d="vExtra"+h.length;n.push("case ",u>>>7,":",d,"(m&0x7f,",l.join(),");break;"),f=["function ",d,"(m,",l.join(),"){switch(m){"],h.push(f)}f.push("case ",127&u,":");for(var p=new Array(r),g=new Array(r),v=new Array(r),m=new Array(r),y=0,b=0;r>b;++b)p[b]=[],g[b]=[],v[b]=0,m[b]=0;for(var b=0;1<<r>b;++b)for(var x=0;r>x;++x){var _=b^1<<x;if(!(_>b)&&!(u&1<<_)!=!(u&1<<b)){var w=1;u&1<<_?g[x].push("v"+_+"-v"+b):(g[x].push("v"+b+"-v"+_),w=-w),0>w?(p[x].push("-v"+b+"-v"+_),v[x]+=2):(p[x].push("v"+b+"+v"+_),v[x]-=2),y+=1;for(var A=0;r>A;++A)A!==x&&(_&1<<A?m[A]+=1:m[A]-=1)}}for(var k=[],x=0;r>x;++x)if(0===p[x].length)k.push("d"+x+"-0.5");else{var M="";v[x]<0?M=v[x]+"*c":v[x]>0&&(M="+"+v[x]+"*c");var T=.5*(p[x].length/y),E=.5+.5*(m[x]/y);k.push("d"+x+"-"+E+"-"+T+"*("+p[x].join("+")+M+")/("+g[x].join("+")+")")}f.push("a.push([",k.join(),"]);","break;")}n.push("}},"),h.length>0&&f.push("}}");for(var L=[],u=0;1<<r-1>u;++u)L.push("v"+u);L.push("c0","c1","p0","p1","a","b","c"),n.push("cell:function cellFunc(",L.join(),"){");var S=s(r-1);n.push("if(p0){b.push(",S.map(function(t){return"["+t.map(function(t){return"v"+t})+"]"}).join(),")}else{b.push(",S.map(function(t){var e=t.slice();return e.reverse(),"["+e.map(function(t){return"v"+t})+"]"}).join(),")}}});function ",i,"(array,level){var verts=[],cells=[];contour(array,verts,cells,level);return {positions:verts,cells:cells};} return ",i,";");for(var u=0;u<h.length;++u)n.push(h[u].join(""));var C=new Function("genContour",n.join(""));return C(o)}function i(t,e){for(var r=l(t,e),n=r.length,i=new Array(n),a=new Array(n),o=0;n>o;++o)i[o]=[r[o]],a[o]=[o];return{positions:i,cells:a}}function a(t,e){if(t.dimension<=0)return{positions:[],cells:[]};if(1===t.dimension)return i(t,e);var r=t.order.join()+"-"+t.dtype,a=u[r],e=+e||0;return a||(a=u[r]=n(t.order,t.dtype)),a(t,e)}e.exports=a;var o=t("ndarray-extract-contour"),s=t("triangulate-hypercube"),l=t("zero-crossings"),u={}},{"ndarray-extract-contour":219,"triangulate-hypercube":224,"zero-crossings":226}],228:[function(t,e,r){(function(r){"use strict";function n(t){for(var e=t.cells,r=t.positions,n=new Float32Array(6*e.length),i=0,a=0,o=0;o<e.length;++o)for(var s=e[o],l=0;3>l;++l){var u=r[s[l]];n[i++]=u[0],n[i++]=u[1]+1.4,a=Math.max(u[0],a)}return{data:n,shape:a}}function i(t,e){var r=s[t];r||(r=s[t]={" ":{data:new Float32Array(0),shape:.2}});var o=r[e];if(!o)if(e.length<=1||!/\d/.test(e))o=r[e]=n(a(e,{triangles:!0,font:t,textAlign:"left",textBaseline:"alphabetic"}));else{for(var l=e.split(/(\d|\s)/),u=new Array(l.length),c=0,h=0,f=0;f<l.length;++f)u[f]=i(t,l[f]),c+=u[f].data.length,h+=u[f].shape,f>0&&(h+=.02);for(var d=new Float32Array(c),p=0,g=-.5*h,f=0;f<u.length;++f){for(var v=u[f].data,m=0;m<v.length;m+=2)d[p++]=v[m]+g,d[p++]=v[m+1];g+=u[f].shape+.02}o=r[e]={data:d,shape:h}}return o}e.exports=i;var a=t("vectorize-text"),o=window||r.global||{},s=o.__TEXT_CACHE||{};o.__TEXT_CACHE={}}).call(this,t("_process"))},{_process:55,"vectorize-text":235}],229:[function(e,r,n){!function(){function e(t,r){if(t=t?t:"",r=r||{},t instanceof e)return t;if(!(this instanceof e))return new e(t,r);var i=n(t);this._originalInput=t,this._r=i.r,this._g=i.g,this._b=i.b,this._a=i.a,this._roundA=U(100*this._a)/100,this._format=r.format||i.format,this._gradientType=r.gradientType,this._r<1&&(this._r=U(this._r)),this._g<1&&(this._g=U(this._g)),this._b<1&&(this._b=U(this._b)),this._ok=i.ok,this._tc_id=B++}function n(t){var e={r:0,g:0,b:0},r=1,n=!1,a=!1;return"string"==typeof t&&(t=I(t)),"object"==typeof t&&(t.hasOwnProperty("r")&&t.hasOwnProperty("g")&&t.hasOwnProperty("b")?(e=i(t.r,t.g,t.b),n=!0,a="%"===String(t.r).substr(-1)?"prgb":"rgb"):t.hasOwnProperty("h")&&t.hasOwnProperty("s")&&t.hasOwnProperty("v")?(t.s=z(t.s),t.v=z(t.v),e=l(t.h,t.s,t.v),n=!0,a="hsv"):t.hasOwnProperty("h")&&t.hasOwnProperty("s")&&t.hasOwnProperty("l")&&(t.s=z(t.s),t.l=z(t.l),e=o(t.h,t.s,t.l),n=!0,a="hsl"),t.hasOwnProperty("a")&&(r=t.a)),r=M(r),{ok:n,format:t.format||a,r:V(255,q(e.r,0)),g:V(255,q(e.g,0)),b:V(255,q(e.b,0)),a:r}}function i(t,e,r){return{r:255*T(t,255),g:255*T(e,255),b:255*T(r,255)}}function a(t,e,r){t=T(t,255),e=T(e,255),r=T(r,255);var n,i,a=q(t,e,r),o=V(t,e,r),s=(a+o)/2;if(a==o)n=i=0;else{var l=a-o;switch(i=s>.5?l/(2-a-o):l/(a+o),a){case t:n=(e-r)/l+(r>e?6:0);break;case e:n=(r-t)/l+2;break;case r:n=(t-e)/l+4}n/=6}return{h:n,s:i,l:s}}function o(t,e,r){function n(t,e,r){return 0>r&&(r+=1),r>1&&(r-=1),1/6>r?t+6*(e-t)*r:.5>r?e:2/3>r?t+(e-t)*(2/3-r)*6:t}var i,a,o;if(t=T(t,360),e=T(e,100),r=T(r,100),0===e)i=a=o=r;else{var s=.5>r?r*(1+e):r+e-r*e,l=2*r-s;i=n(l,s,t+1/3),a=n(l,s,t),o=n(l,s,t-1/3)}return{r:255*i,g:255*a,b:255*o}}function s(t,e,r){t=T(t,255),e=T(e,255),r=T(r,255);var n,i,a=q(t,e,r),o=V(t,e,r),s=a,l=a-o;if(i=0===a?0:l/a,a==o)n=0;else{switch(a){case t:n=(e-r)/l+(r>e?6:0);break;case e:n=(r-t)/l+2;break;case r:n=(t-e)/l+4}n/=6}return{h:n,s:i,v:s}}function l(t,e,r){t=6*T(t,360),e=T(e,100),r=T(r,100);var n=D.floor(t),i=t-n,a=r*(1-e),o=r*(1-i*e),s=r*(1-(1-i)*e),l=n%6,u=[r,o,a,a,s,r][l],c=[s,r,r,o,a,a][l],h=[a,a,s,r,r,o][l];return{r:255*u,g:255*c,b:255*h}}function u(t,e,r,n){var i=[P(U(t).toString(16)),P(U(e).toString(16)),P(U(r).toString(16))];return n&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)?i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0):i.join("")}function c(t,e,r,n){var i=[P(R(n)),P(U(t).toString(16)),P(U(e).toString(16)),P(U(r).toString(16))];return i.join("")}function h(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.s-=r/100,n.s=E(n.s),e(n)}function f(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.s+=r/100,n.s=E(n.s),e(n)}function d(t){return e(t).desaturate(100)}function p(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.l+=r/100,n.l=E(n.l),e(n)}function g(t,r){r=0===r?0:r||10;var n=e(t).toRgb();return n.r=q(0,V(255,n.r-U(255*-(r/100)))),n.g=q(0,V(255,n.g-U(255*-(r/100)))),n.b=q(0,V(255,n.b-U(255*-(r/100)))),e(n)}function v(t,r){r=0===r?0:r||10;var n=e(t).toHsl();return n.l-=r/100,n.l=E(n.l),e(n)}function m(t,r){var n=e(t).toHsl(),i=(U(n.h)+r)%360;return n.h=0>i?360+i:i,e(n)}function y(t){var r=e(t).toHsl();return r.h=(r.h+180)%360,e(r)}function b(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+120)%360,s:r.s,l:r.l}),e({h:(n+240)%360,s:r.s,l:r.l})]}function x(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+90)%360,s:r.s,l:r.l}),e({h:(n+180)%360,s:r.s,l:r.l}),e({h:(n+270)%360,s:r.s,l:r.l})]}function _(t){var r=e(t).toHsl(),n=r.h;return[e(t),e({h:(n+72)%360,s:r.s,l:r.l}),e({h:(n+216)%360,s:r.s,l:r.l})]}function w(t,r,n){r=r||6,n=n||30;var i=e(t).toHsl(),a=360/n,o=[e(t)];for(i.h=(i.h-(a*r>>1)+720)%360;--r;)i.h=(i.h+a)%360,o.push(e(i));return o}function A(t,r){r=r||6;for(var n=e(t).toHsv(),i=n.h,a=n.s,o=n.v,s=[],l=1/r;r--;)s.push(e({h:i,s:a,v:o})),o=(o+l)%1;return s}function k(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[t[r]]=r);return e}function M(t){return t=parseFloat(t),(isNaN(t)||0>t||t>1)&&(t=1),t}function T(t,e){S(t)&&(t="100%");var r=C(t);return t=V(e,q(0,parseFloat(t))),r&&(t=parseInt(t*e,10)/100),D.abs(t-e)<1e-6?1:t%e/parseFloat(e)}function E(t){return V(1,q(0,t))}function L(t){return parseInt(t,16)}function S(t){return"string"==typeof t&&-1!=t.indexOf(".")&&1===parseFloat(t)}function C(t){return"string"==typeof t&&-1!=t.indexOf("%")}function P(t){return 1==t.length?"0"+t:""+t}function z(t){return 1>=t&&(t=100*t+"%"),t}function R(t){return Math.round(255*parseFloat(t)).toString(16)}function O(t){return L(t)/255}function I(t){t=t.replace(N,"").replace(F,"").toLowerCase();var e=!1;if(G[t])t=G[t],e=!0;else if("transparent"==t)return{r:0,g:0,b:0,a:0,format:"name"};var r;return(r=X.rgb.exec(t))?{r:r[1],g:r[2],b:r[3]}:(r=X.rgba.exec(t))?{r:r[1],g:r[2],b:r[3],a:r[4]}:(r=X.hsl.exec(t))?{h:r[1],s:r[2],l:r[3]}:(r=X.hsla.exec(t))?{h:r[1],s:r[2],l:r[3],a:r[4]}:(r=X.hsv.exec(t))?{h:r[1],s:r[2],v:r[3]}:(r=X.hsva.exec(t))?{h:r[1],s:r[2],v:r[3],a:r[4]}:(r=X.hex8.exec(t))?{a:O(r[1]),r:L(r[2]),g:L(r[3]),b:L(r[4]),format:e?"name":"hex8"}:(r=X.hex6.exec(t))?{r:L(r[1]),g:L(r[2]),b:L(r[3]),format:e?"name":"hex"}:(r=X.hex3.exec(t))?{r:L(r[1]+""+r[1]),g:L(r[2]+""+r[2]),b:L(r[3]+""+r[3]),format:e?"name":"hex"}:!1}function j(t){var e,r;return t=t||{level:"AA",size:"small"},e=(t.level||"AA").toUpperCase(),r=(t.size||"small").toLowerCase(),"AA"!==e&&"AAA"!==e&&(e="AA"),"small"!==r&&"large"!==r&&(r="small"),{level:e,size:r}}var N=/^\s+/,F=/\s+$/,B=0,D=Math,U=D.round,V=D.min,q=D.max,H=D.random;e.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var t=this.toRgb();return(299*t.r+587*t.g+114*t.b)/1e3},getLuminance:function(){var t,e,r,n,i,a,o=this.toRgb();return t=o.r/255,e=o.g/255,r=o.b/255,n=.03928>=t?t/12.92:Math.pow((t+.055)/1.055,2.4),i=.03928>=e?e/12.92:Math.pow((e+.055)/1.055,2.4),a=.03928>=r?r/12.92:Math.pow((r+.055)/1.055,2.4),.2126*n+.7152*i+.0722*a},setAlpha:function(t){return this._a=M(t),this._roundA=U(100*this._a)/100,this},toHsv:function(){var t=s(this._r,this._g,this._b);return{h:360*t.h,s:t.s,v:t.v,a:this._a}},toHsvString:function(){var t=s(this._r,this._g,this._b),e=U(360*t.h),r=U(100*t.s),n=U(100*t.v);return 1==this._a?"hsv("+e+", "+r+"%, "+n+"%)":"hsva("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHsl:function(){var t=a(this._r,this._g,this._b);return{h:360*t.h,s:t.s,l:t.l,a:this._a}},toHslString:function(){var t=a(this._r,this._g,this._b),e=U(360*t.h),r=U(100*t.s),n=U(100*t.l);return 1==this._a?"hsl("+e+", "+r+"%, "+n+"%)":"hsla("+e+", "+r+"%, "+n+"%, "+this._roundA+")"},toHex:function(t){return u(this._r,this._g,this._b,t)},toHexString:function(t){return"#"+this.toHex(t)},toHex8:function(){return c(this._r,this._g,this._b,this._a)},toHex8String:function(){return"#"+this.toHex8()},toRgb:function(){return{r:U(this._r),g:U(this._g),b:U(this._b),a:this._a}},toRgbString:function(){return 1==this._a?"rgb("+U(this._r)+", "+U(this._g)+", "+U(this._b)+")":"rgba("+U(this._r)+", "+U(this._g)+", "+U(this._b)+", "+this._roundA+")"},toPercentageRgb:function(){return{r:U(100*T(this._r,255))+"%",g:U(100*T(this._g,255))+"%",b:U(100*T(this._b,255))+"%",a:this._a}},toPercentageRgbString:function(){return 1==this._a?"rgb("+U(100*T(this._r,255))+"%, "+U(100*T(this._g,255))+"%, "+U(100*T(this._b,255))+"%)":"rgba("+U(100*T(this._r,255))+"%, "+U(100*T(this._g,255))+"%, "+U(100*T(this._b,255))+"%, "+this._roundA+")"},toName:function(){return 0===this._a?"transparent":this._a<1?!1:Y[u(this._r,this._g,this._b,!0)]||!1},toFilter:function(t){var r="#"+c(this._r,this._g,this._b,this._a),n=r,i=this._gradientType?"GradientType = 1, ":"";if(t){var a=e(t);n=a.toHex8String()}return"progid:DXImageTransform.Microsoft.gradient("+i+"startColorstr="+r+",endColorstr="+n+")"},toString:function(t){var e=!!t;t=t||this._format;var r=!1,n=this._a<1&&this._a>=0,i=!e&&n&&("hex"===t||"hex6"===t||"hex3"===t||"name"===t);return i?"name"===t&&0===this._a?this.toName():this.toRgbString():("rgb"===t&&(r=this.toRgbString()),"prgb"===t&&(r=this.toPercentageRgbString()),("hex"===t||"hex6"===t)&&(r=this.toHexString()),"hex3"===t&&(r=this.toHexString(!0)),"hex8"===t&&(r=this.toHex8String()),"name"===t&&(r=this.toName()),"hsl"===t&&(r=this.toHslString()),"hsv"===t&&(r=this.toHsvString()),r||this.toHexString())},clone:function(){return e(this.toString())},_applyModification:function(t,e){var r=t.apply(null,[this].concat([].slice.call(e)));return this._r=r._r,this._g=r._g,this._b=r._b,this.setAlpha(r._a),this},lighten:function(){return this._applyModification(p,arguments)},brighten:function(){return this._applyModification(g,arguments)},darken:function(){return this._applyModification(v,arguments)},desaturate:function(){return this._applyModification(h,arguments)},saturate:function(){return this._applyModification(f,arguments)},greyscale:function(){return this._applyModification(d,arguments)},spin:function(){return this._applyModification(m,arguments)},_applyCombination:function(t,e){return t.apply(null,[this].concat([].slice.call(e)))},analogous:function(){return this._applyCombination(w,arguments)},complement:function(){return this._applyCombination(y,arguments)},monochromatic:function(){return this._applyCombination(A,arguments)},splitcomplement:function(){return this._applyCombination(_,arguments)},triad:function(){return this._applyCombination(b,arguments)},tetrad:function(){return this._applyCombination(x,arguments)}},e.fromRatio=function(t,r){if("object"==typeof t){var n={};for(var i in t)t.hasOwnProperty(i)&&("a"===i?n[i]=t[i]:n[i]=z(t[i]));t=n}return e(t,r)},e.equals=function(t,r){return t&&r?e(t).toRgbString()==e(r).toRgbString():!1},e.random=function(){return e.fromRatio({r:H(),g:H(),b:H()})},e.mix=function(t,r,n){n=0===n?0:n||50;var i,a=e(t).toRgb(),o=e(r).toRgb(),s=n/100,l=2*s-1,u=o.a-a.a;i=l*u==-1?l:(l+u)/(1+l*u),i=(i+1)/2;var c=1-i,h={r:o.r*i+a.r*c,g:o.g*i+a.g*c,b:o.b*i+a.b*c,a:o.a*s+a.a*(1-s)};return e(h)},e.readability=function(t,r){var n=e(t),i=e(r);return(Math.max(n.getLuminance(),i.getLuminance())+.05)/(Math.min(n.getLuminance(),i.getLuminance())+.05)},e.isReadable=function(t,r,n){var i,a,o=e.readability(t,r);switch(a=!1,i=j(n),i.level+i.size){case"AAsmall":case"AAAlarge":a=o>=4.5;break;case"AAlarge":a=o>=3;break;case"AAAsmall":a=o>=7}return a},e.mostReadable=function(t,r,n){var i,a,o,s,l=null,u=0;n=n||{},a=n.includeFallbackColors,o=n.level,s=n.size;for(var c=0;c<r.length;c++)i=e.readability(t,r[c]),i>u&&(u=i,l=e(r[c]));return e.isReadable(t,l,{level:o,size:s})||!a?l:(n.includeFallbackColors=!1,e.mostReadable(t,["#fff","#000"],n))};var G=e.names={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"0ff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"00f",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",burntsienna:"ea7e5d",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"0ff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"f0f",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"663399",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},Y=e.hexNames=k(G),X=function(){var t="[-\\+]?\\d+%?",e="[-\\+]?\\d*\\.\\d+%?",r="(?:"+e+")|(?:"+t+")",n="[\\s|\\(]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")\\s*\\)?",i="[\\s|\\(]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")[,|\\s]+("+r+")\\s*\\)?";return{rgb:new RegExp("rgb"+n),rgba:new RegExp("rgba"+i),hsl:new RegExp("hsl"+n),hsla:new RegExp("hsla"+i),hsv:new RegExp("hsv"+n),hsva:new RegExp("hsva"+i),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}}();"undefined"!=typeof r&&r.exports?r.exports=e:"function"==typeof t&&t.amd?t(function(){return e}):window.tinycolor=e}()},{}],230:[function(e,r,n){!function(){function e(t,e){function r(e){var r,n=t.arcs[0>e?~e:e],i=n[0];return t.transform?(r=[0,0],n.forEach(function(t){r[0]+=t[0],r[1]+=t[1]})):r=n[n.length-1],0>e?[r,i]:[i,r]}function n(t,e){for(var r in t){var n=t[r];delete e[n.start],delete n.start,delete n.end,n.forEach(function(t){i[0>t?~t:t]=1}),s.push(n)}}var i={},a={},o={},s=[],l=-1;return e.forEach(function(r,n){var i,a=t.arcs[0>r?~r:r];a.length<3&&!a[1][0]&&!a[1][1]&&(i=e[++l],e[l]=r,e[n]=i)}),e.forEach(function(t){var e,n,i=r(t),s=i[0],l=i[1];if(e=o[s])if(delete o[e.end],e.push(t),e.end=l,n=a[l]){delete a[n.start];var u=n===e?e:e.concat(n);a[u.start=e.start]=o[u.end=n.end]=u}else a[e.start]=o[e.end]=e;else if(e=a[l])if(delete a[e.start],e.unshift(t),e.start=s,n=o[s]){delete o[n.end];var c=n===e?e:n.concat(e);a[c.start=n.start]=o[c.end=e.end]=c}else a[e.start]=o[e.end]=e;else e=[t],a[e.start=s]=o[e.end=l]=e}),n(o,a),n(a,o),e.forEach(function(t){i[0>t?~t:t]||s.push([t])}),s}function n(t,r,n){function i(t){var e=0>t?~t:t;(c[e]||(c[e]=[])).push({i:t,g:u})}function a(t){t.forEach(i)}function o(t){t.forEach(a)}function s(t){"GeometryCollection"===t.type?t.geometries.forEach(s):t.type in h&&(u=t,h[t.type](t.arcs))}var l=[];if(arguments.length>1){var u,c=[],h={LineString:a,MultiLineString:o,Polygon:o,MultiPolygon:function(t){t.forEach(o)}};s(r),c.forEach(arguments.length<3?function(t){l.push(t[0].i)}:function(t){n(t[0].g,t[t.length-1].g)&&l.push(t[0].i)})}else for(var f=0,d=t.arcs.length;d>f;++f)l.push(f);return{type:"MultiLineString",arcs:e(t,l)}}function i(t,r){function n(t){t.forEach(function(e){e.forEach(function(e){(a[e=0>e?~e:e]||(a[e]=[])).push(t)})}),o.push(t)}function i(e){return f(s(t,{type:"Polygon",arcs:[e]}).coordinates[0])>0}var a={},o=[],l=[];return r.forEach(function(t){"Polygon"===t.type?n(t.arcs):"MultiPolygon"===t.type&&t.arcs.forEach(n)}),o.forEach(function(t){if(!t._){var e=[],r=[t];for(t._=1,l.push(e);t=r.pop();)e.push(t),t.forEach(function(t){t.forEach(function(t){a[0>t?~t:t].forEach(function(t){t._||(t._=1,r.push(t))})})})}}),o.forEach(function(t){delete t._}),{type:"MultiPolygon",arcs:l.map(function(r){var n,o=[];if(r.forEach(function(t){t.forEach(function(t){t.forEach(function(t){a[0>t?~t:t].length<2&&o.push(t)})})}),o=e(t,o),(n=o.length)>1)for(var s,l=i(r[0][0]),u=0;n>u;++u)if(l===i(o[u])){s=o[0],o[0]=o[u],o[u]=s;break}return o})}}function a(t,e){return"GeometryCollection"===e.type?{type:"FeatureCollection",features:e.geometries.map(function(e){return o(t,e)})}:o(t,e)}function o(t,e){var r={type:"Feature",id:e.id,properties:e.properties||{},geometry:s(t,e)};return null==e.id&&delete r.id,r}function s(t,e){function r(t,e){e.length&&e.pop();for(var r,n=c[0>t?~t:t],i=0,a=n.length;a>i;++i)e.push(r=n[i].slice()),u(r,i);0>t&&l(e,a)}function n(t){return t=t.slice(),u(t,0),t}function i(t){for(var e=[],n=0,i=t.length;i>n;++n)r(t[n],e);return e.length<2&&e.push(e[0].slice()),e}function a(t){for(var e=i(t);e.length<4;)e.push(e[0].slice());return e}function o(t){return t.map(a)}function s(t){var e=t.type;return"GeometryCollection"===e?{type:e,geometries:t.geometries.map(s)}:e in h?{type:e,coordinates:h[e](t)}:null}var u=v(t.transform),c=t.arcs,h={Point:function(t){return n(t.coordinates)},MultiPoint:function(t){return t.coordinates.map(n)},LineString:function(t){return i(t.arcs)},MultiLineString:function(t){return t.arcs.map(i)},Polygon:function(t){return o(t.arcs)},MultiPolygon:function(t){return t.arcs.map(o)}};return s(e)}function l(t,e){for(var r,n=t.length,i=n-e;i<--n;)r=t[i],t[i++]=t[n],t[n]=r}function u(t,e){for(var r=0,n=t.length;n>r;){var i=r+n>>>1;t[i]<e?r=i+1:n=i}return r}function c(t){function e(t,e){t.forEach(function(t){0>t&&(t=~t);var r=i[t];r?r.push(e):i[t]=[e]})}function r(t,r){t.forEach(function(t){e(t,r)})}function n(t,e){"GeometryCollection"===t.type?t.geometries.forEach(function(t){n(t,e)}):t.type in o&&o[t.type](t.arcs,e)}var i={},a=t.map(function(){return[]}),o={LineString:e,MultiLineString:r,Polygon:r,MultiPolygon:function(t,e){t.forEach(function(t){r(t,e)})}};t.forEach(n);for(var s in i)for(var l=i[s],c=l.length,h=0;c>h;++h)for(var f=h+1;c>f;++f){var d,p=l[h],g=l[f];(d=a[p])[s=u(d,g)]!==g&&d.splice(s,0,g),(d=a[g])[s=u(d,p)]!==p&&d.splice(s,0,p)}return a}function h(t,e){function r(t){a.remove(t),t[1][2]=e(t),a.push(t)}var n=v(t.transform),i=m(t.transform),a=g();return e||(e=d),t.arcs.forEach(function(t){for(var o,s,l=[],u=0,c=0,h=t.length;h>c;++c)s=t[c],n(t[c]=[s[0],s[1],1/0],c);for(var c=1,h=t.length-1;h>c;++c)o=t.slice(c-1,c+2),o[1][2]=e(o),l.push(o),a.push(o);for(var c=0,h=l.length;h>c;++c)o=l[c],o.previous=l[c-1],o.next=l[c+1];for(;o=a.pop();){var f=o.previous,d=o.next;o[1][2]<u?o[1][2]=u:u=o[1][2],f&&(f.next=d,f[2]=o[2],r(f)),d&&(d.previous=f,d[0]=o[0],r(d))}t.forEach(i)}),t}function f(t){for(var e,r=-1,n=t.length,i=t[n-1],a=0;++r<n;)e=i,i=t[r],a+=e[0]*i[1]-e[1]*i[0];return a/2}function d(t){var e=t[0],r=t[1],n=t[2];return Math.abs((e[0]-n[0])*(r[1]-e[1])-(e[0]-r[0])*(n[1]-e[1]))}function p(t,e){return t[1][2]-e[1][2]}function g(){function t(t,e){for(;e>0;){var r=(e+1>>1)-1,i=n[r];if(p(t,i)>=0)break;n[i._=e]=i,n[t._=e=r]=t}}function e(t,e){for(;;){var r=e+1<<1,a=r-1,o=e,s=n[o];if(i>a&&p(n[a],s)<0&&(s=n[o=a]),i>r&&p(n[r],s)<0&&(s=n[o=r]),o===e)break;n[s._=e]=s,n[t._=e=o]=t}}var r={},n=[],i=0;return r.push=function(e){return t(n[e._=i]=e,i++),i},r.pop=function(){if(!(0>=i)){var t,r=n[0];return--i>0&&(t=n[i],e(n[t._=0]=t,0)),r}},r.remove=function(r){var a,o=r._;if(n[o]===r)return o!==--i&&(a=n[i],(p(a,r)<0?t:e)(n[a._=o]=a,o)),o},r}function v(t){if(!t)return y;var e,r,n=t.scale[0],i=t.scale[1],a=t.translate[0],o=t.translate[1];return function(t,s){s||(e=r=0),t[0]=(e+=t[0])*n+a,t[1]=(r+=t[1])*i+o}}function m(t){if(!t)return y;var e,r,n=t.scale[0],i=t.scale[1],a=t.translate[0],o=t.translate[1];return function(t,s){s||(e=r=0);var l=(t[0]-a)/n|0,u=(t[1]-o)/i|0;t[0]=l-e,t[1]=u-r,e=l,r=u}}function y(){}var b={version:"1.6.20",mesh:function(t){return s(t,n.apply(this,arguments))},meshArcs:n,merge:function(t){return s(t,i.apply(this,arguments))},mergeArcs:i,feature:a,neighbors:c,presimplify:h};"function"==typeof t&&t.amd?t(b):"object"==typeof r&&r.exports?r.exports=b:this.topojson=b}()},{}],231:[function(t,e,r){"use strict";function n(t,e,r){var n=t*e,a=i*t,o=a-t,s=a-o,l=t-s,u=i*e,c=u-e,h=u-c,f=e-h,d=n-s*h,p=d-l*h,g=p-s*f,v=l*f-g;return r?(r[0]=v,r[1]=n,r):[v,n]}e.exports=n;var i=+(Math.pow(2,27)+1)},{}],232:[function(t,e,r){"use strict";function n(t,e,r){var n=t+e,i=n-t,a=n-i,o=e-i,s=t-a;return r?(r[0]=s+o,r[1]=n,r):[s+o,n]}e.exports=n},{}],233:[function(t,e,r){(function(e,n){"use strict";function i(t){if(t){var e=t.length||t.byteLength,r=y.log2(e);w[r].push(t)}}function a(t){i(t.buffer)}function o(t){var t=y.nextPow2(t),e=y.log2(t),r=w[e];return r.length>0?r.pop():new ArrayBuffer(t);
+}function s(t){return new Uint8Array(o(t),0,t)}function l(t){return new Uint16Array(o(2*t),0,t)}function u(t){return new Uint32Array(o(4*t),0,t)}function c(t){return new Int8Array(o(t),0,t)}function h(t){return new Int16Array(o(2*t),0,t)}function f(t){return new Int32Array(o(4*t),0,t)}function d(t){return new Float32Array(o(4*t),0,t)}function p(t){return new Float64Array(o(8*t),0,t)}function g(t){return x?new Uint8ClampedArray(o(t),0,t):s(t)}function v(t){return new DataView(o(t),0,t)}function m(t){t=y.nextPow2(t);var e=y.log2(t),r=A[e];return r.length>0?r.pop():new n(t)}var y=t("bit-twiddle"),b=t("dup");e.__TYPEDARRAY_POOL||(e.__TYPEDARRAY_POOL={UINT8:b([32,0]),UINT16:b([32,0]),UINT32:b([32,0]),INT8:b([32,0]),INT16:b([32,0]),INT32:b([32,0]),FLOAT:b([32,0]),DOUBLE:b([32,0]),DATA:b([32,0]),UINT8C:b([32,0]),BUFFER:b([32,0])});var x="undefined"!=typeof Uint8ClampedArray,_=e.__TYPEDARRAY_POOL;_.UINT8C||(_.UINT8C=b([32,0])),_.BUFFER||(_.BUFFER=b([32,0]));var w=_.DATA,A=_.BUFFER;r.free=function(t){if(n.isBuffer(t))A[y.log2(t.length)].push(t);else{if("[object ArrayBuffer]"!==Object.prototype.toString.call(t)&&(t=t.buffer),!t)return;var e=t.length||t.byteLength,r=0|y.log2(e);w[r].push(t)}},r.freeUint8=r.freeUint16=r.freeUint32=r.freeInt8=r.freeInt16=r.freeInt32=r.freeFloat32=r.freeFloat=r.freeFloat64=r.freeDouble=r.freeUint8Clamped=r.freeDataView=a,r.freeArrayBuffer=i,r.freeBuffer=function(t){A[y.log2(t.length)].push(t)},r.malloc=function(t,e){if(void 0===e||"arraybuffer"===e)return o(t);switch(e){case"uint8":return s(t);case"uint16":return l(t);case"uint32":return u(t);case"int8":return c(t);case"int16":return h(t);case"int32":return f(t);case"float":case"float32":return d(t);case"double":case"float64":return p(t);case"uint8_clamped":return g(t);case"buffer":return m(t);case"data":case"dataview":return v(t);default:return null}return null},r.mallocArrayBuffer=o,r.mallocUint8=s,r.mallocUint16=l,r.mallocUint32=u,r.mallocInt8=c,r.mallocInt16=h,r.mallocInt32=f,r.mallocFloat32=r.mallocFloat=d,r.mallocFloat64=r.mallocDouble=p,r.mallocUint8Clamped=g,r.mallocDataView=v,r.mallocBuffer=m,r.clearCache=function(){for(var t=0;32>t;++t)_.UINT8[t].length=0,_.UINT16[t].length=0,_.UINT32[t].length=0,_.INT8[t].length=0,_.INT16[t].length=0,_.INT32[t].length=0,_.FLOAT[t].length=0,_.DOUBLE[t].length=0,_.UINT8C[t].length=0,w[t].length=0,A[t].length=0}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},t("buffer").Buffer)},{"bit-twiddle":49,buffer:50,dup:72}],234:[function(t,e,r){"use strict";function n(t,e){for(var r=1,n=t.length,i=t[0],a=t[0],o=1;n>o;++o)if(a=i,i=t[o],e(i,a)){if(o===r){r++;continue}t[r++]=i}return t.length=r,t}function i(t){for(var e=1,r=t.length,n=t[0],i=t[0],a=1;r>a;++a,i=n)if(i=n,n=t[a],n!==i){if(a===e){e++;continue}t[e++]=n}return t.length=e,t}function a(t,e,r){return 0===t.length?t:e?(r||t.sort(e),n(t,e)):(r||t.sort(),i(t))}e.exports=a},{}],235:[function(t,e,r){"use strict";function n(t,e){return("object"!=typeof e||null===e)&&(e={}),i(t,e.canvas||a,e.context||o,e)}e.exports=n;var i=t("./lib/vtext"),a=null,o=null;"undefined"!=typeof document&&(a=document.createElement("canvas"),a.width=8192,a.height=1024,o=a.getContext("2d"))},{"./lib/vtext":236}],236:[function(t,e,r){"use strict";function n(t,e,r){for(var n=e.textAlign||"start",i=e.textBaseline||"alphabetic",a=[1<<30,1<<30],o=[0,0],s=t.length,l=0;s>l;++l)for(var u=t[l],c=0;2>c;++c)a[c]=0|Math.min(a[c],u[c]),o[c]=0|Math.max(o[c],u[c]);var h=0;switch(n){case"center":h=-.5*(a[0]+o[0]);break;case"right":case"end":h=-o[0];break;case"left":case"start":h=-a[0];break;default:throw new Error("vectorize-text: Unrecognized textAlign: '"+n+"'")}var f=0;switch(i){case"hanging":case"top":f=-a[1];break;case"middle":f=-.5*(a[1]+o[1]);break;case"alphabetic":case"ideographic":f=-3*r;break;case"bottom":f=-o[1];break;default:throw new Error("vectorize-text: Unrecoginized textBaseline: '"+i+"'")}var d=1/r;return"lineHeight"in e?d*=+e.lineHeight:"width"in e?d=e.width/(o[0]-a[0]):"height"in e&&(d=e.height/(o[1]-a[1])),t.map(function(t){return[d*(t[0]+h),d*(t[1]+f)]})}function i(t,e,r,n){var i=0|Math.ceil(e.measureText(r).width+2*n);if(i>8192)throw new Error("vectorize-text: String too long (sorry, this will get fixed later)");var a=3*n;t.height<a&&(t.height=a),e.fillStyle="#000",e.fillRect(0,0,t.width,t.height),e.fillStyle="#fff",e.fillText(r,n,2*n);var o=e.getImageData(0,0,i,a),s=c(o.data,[a,i,4]);return s.pick(-1,-1,0).transpose(1,0)}function a(t,e){var r=u(t,128);return e?h(r.cells,r.positions,.25):{edges:r.cells,positions:r.positions}}function o(t,e,r,i){var o=a(t,i),s=n(o.positions,e,r),l=o.edges,u="ccw"===e.orientation;if(f(s,l),e.polygons||e.polygon||e.polyline){for(var c=p(l,s),h=new Array(c.length),g=0;g<c.length;++g){for(var v=c[g],m=new Array(v.length),y=0;y<v.length;++y){for(var b=v[y],x=new Array(b.length),_=0;_<b.length;++_)x[_]=s[b[_]].slice();u&&x.reverse(),m[y]=x}h[g]=m}return h}return e.triangles||e.triangulate||e.triangle?{cells:d(s,l,{delaunay:!1,exterior:!1,interior:!0}),positions:s}:{edges:l,positions:s}}function s(t,e,r){try{return o(t,e,r,!0)}catch(n){}try{return o(t,e,r,!1)}catch(n){}return e.polygons||e.polyline||e.polygon?[]:e.triangles||e.triangulate||e.triangle?{cells:[],positions:[]}:{edges:[],positions:[]}}function l(t,e,r,n){var a=n.size||64,o=n.font||"normal";r.font=a+"px "+o,r.textAlign="start",r.textBaseline="alphabetic",r.direction="ltr";var l=i(e,r,t,a);return s(l,n,a)}e.exports=l,e.exports.processPixels=s;var u=t("surface-nets"),c=t("ndarray"),h=t("simplify-planar-graph"),f=t("clean-pslg"),d=t("cdt2d"),p=t("planar-graph-to-polyline")},{cdt2d:237,"clean-pslg":244,ndarray:208,"planar-graph-to-polyline":290,"simplify-planar-graph":294,"surface-nets":227}],237:[function(t,e,r){"use strict";function n(t){return[Math.min(t[0],t[1]),Math.max(t[0],t[1])]}function i(t,e){return t[0]-e[0]||t[1]-e[1]}function a(t){return t.map(n).sort(i)}function o(t,e,r){return e in t?t[e]:r}function s(t,e,r){Array.isArray(e)?(r=r||{},e=e||[]):(r=e||{},e=[]);var n=!!o(r,"delaunay",!0),i=!!o(r,"interior",!0),s=!!o(r,"exterior",!0),f=!!o(r,"infinity",!1);if(!i&&!s||0===t.length)return[];var d=l(t,e);if(n||i!==s||f){for(var p=u(t.length,a(e)),g=0;g<d.length;++g){var v=d[g];p.addTriangle(v[0],v[1],v[2])}return n&&c(t,p),s?i?f?h(p,0,f):p.cells():h(p,1,f):h(p,-1)}return d}var l=t("./lib/monotone"),u=t("./lib/triangulation"),c=t("./lib/delaunay"),h=t("./lib/filter");e.exports=s},{"./lib/delaunay":238,"./lib/filter":239,"./lib/monotone":240,"./lib/triangulation":241}],238:[function(t,e,r){"use strict";function n(t,e,r,n,i,o){var s=e.opposite(n,i);if(!(0>s)){if(n>i){var l=n;n=i,i=l,l=o,o=s,s=l}e.isConstraint(n,i)||a(t[n],t[i],t[o],t[s])<0&&r.push(n,i)}}function i(t,e){for(var r=[],i=t.length,o=e.stars,s=0;i>s;++s)for(var l=o[s],u=1;u<l.length;u+=2){var c=l[u];if(!(s>c||e.isConstraint(s,c))){for(var h=l[u-1],f=-1,d=1;d<l.length;d+=2)if(l[d-1]===c){f=l[d];break}0>f||a(t[s],t[c],t[h],t[f])<0&&r.push(s,c)}}for(;r.length>0;){for(var c=r.pop(),s=r.pop(),h=-1,f=-1,l=o[s],p=1;p<l.length;p+=2){var g=l[p-1],v=l[p];g===c?f=v:v===c&&(h=g)}0>h||0>f||a(t[s],t[c],t[h],t[f])>=0||(e.flip(s,c),n(t,e,r,h,s,f),n(t,e,r,s,f,h),n(t,e,r,f,c,h),n(t,e,r,c,h,f))}}var a=t("robust-in-sphere")[4];t("binary-search-bounds");e.exports=i},{"binary-search-bounds":242,"robust-in-sphere":243}],239:[function(t,e,r){"use strict";function n(t,e,r,n,i,a,o){this.cells=t,this.neighbor=e,this.flags=n,this.constraint=r,this.active=i,this.next=a,this.boundary=o}function i(t,e){return t[0]-e[0]||t[1]-e[1]||t[2]-e[2]}function a(t,e){for(var r=t.cells(),a=r.length,o=0;a>o;++o){var s=r[o],l=s[0],u=s[1],c=s[2];c>u?l>u&&(s[0]=u,s[1]=c,s[2]=l):l>c&&(s[0]=c,s[1]=l,s[2]=u)}r.sort(i);for(var h=new Array(a),o=0;o<h.length;++o)h[o]=0;var f=[],d=[],p=new Array(3*a),g=new Array(3*a),v=null;e&&(v=[]);for(var m=new n(r,p,g,h,f,d,v),o=0;a>o;++o)for(var s=r[o],y=0;3>y;++y){var l=s[y],u=s[(y+1)%3],b=p[3*o+y]=m.locate(u,l,t.opposite(u,l)),x=g[3*o+y]=t.isConstraint(l,u);0>b&&(x?d.push(o):(f.push(o),h[o]=1),e&&v.push([u,l,-1]))}return m}function o(t,e,r){for(var n=0,i=0;i<t.length;++i)e[i]===r&&(t[n++]=t[i]);return t.length=n,t}function s(t,e,r){var n=a(t,r);if(0===e)return r?n.cells.concat(n.boundary):n.cells;for(var i=1,s=n.active,l=n.next,u=n.flags,c=n.cells,h=n.constraint,f=n.neighbor;s.length>0||l.length>0;){for(;s.length>0;){var d=s.pop();if(u[d]!==-i){u[d]=i;for(var p=(c[d],0);3>p;++p){var g=f[3*d+p];g>=0&&0===u[g]&&(h[3*d+p]?l.push(g):(s.push(g),u[g]=i))}}}var v=l;l=s,s=v,l.length=0,i=-i}var m=o(c,u,e);return r?m.concat(n.boundary):m}var l=t("binary-search-bounds");e.exports=s;var u=n.prototype;u.locate=function(){var t=[0,0,0];return function(e,r,n){var a=e,o=r,s=n;return n>r?e>r&&(a=r,o=n,s=e):e>n&&(a=n,o=e,s=r),0>a?-1:(t[0]=a,t[1]=o,t[2]=s,l.eq(this.cells,t,i))}}()},{"binary-search-bounds":242}],240:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.a=t,this.b=e,this.idx=r,this.lowerIds=n,this.upperIds=i}function i(t,e,r,n){this.a=t,this.b=e,this.type=r,this.idx=n}function a(t,e){var r=t.a[0]-e.a[0]||t.a[1]-e.a[1]||t.type-e.type;return r?r:t.type!==p&&(r=d(t.a,t.b,e.b))?r:t.idx-e.idx}function o(t,e){return d(t.a,t.b,e)}function s(t,e,r,n,i){for(var a=f.lt(e,n,o),s=f.gt(e,n,o),l=a;s>l;++l){for(var u=e[l],c=u.lowerIds,h=c.length;h>1&&d(r[c[h-2]],r[c[h-1]],n)>0;)t.push([c[h-1],c[h-2],i]),h-=1;c.length=h,c.push(i);for(var p=u.upperIds,h=p.length;h>1&&d(r[p[h-2]],r[p[h-1]],n)<0;)t.push([p[h-2],p[h-1],i]),h-=1;p.length=h,p.push(i)}}function l(t,e){var r;return(r=t.a[0]<e.a[0]?d(t.a,t.b,e.a):d(e.b,e.a,t.a))?r:(r=e.b[0]<t.b[0]?d(t.a,t.b,e.b):d(e.b,e.a,t.b),r||t.idx-e.idx)}function u(t,e,r){var i=f.le(t,r,l),a=t[i],o=a.upperIds,s=o[o.length-1];a.upperIds=[s],t.splice(i+1,0,new n(r.a,r.b,r.idx,[s],o))}function c(t,e,r){var n=r.a;r.a=r.b,r.b=n;var i=f.eq(t,r,l),a=t[i],o=t[i-1];o.upperIds=a.upperIds,t.splice(i,1)}function h(t,e){for(var r=t.length,o=e.length,l=[],h=0;r>h;++h)l.push(new i(t[h],null,p,h));for(var h=0;o>h;++h){var f=e[h],d=t[f[0]],m=t[f[1]];d[0]<m[0]?l.push(new i(d,m,v,h),new i(m,d,g,h)):d[0]>m[0]&&l.push(new i(m,d,v,h),new i(d,m,g,h))}l.sort(a);for(var y=l[0].a[0]-(1+Math.abs(l[0].a[0]))*Math.pow(2,-52),b=[new n([y,1],[y,0],-1,[],[],[],[])],x=[],h=0,_=l.length;_>h;++h){var w=l[h],A=w.type;A===p?s(x,b,t,w.a,w.idx):A===v?u(b,t,w):c(b,t,w)}return x}var f=t("binary-search-bounds"),d=t("robust-orientation")[3],p=0,g=1,v=2;e.exports=h},{"binary-search-bounds":242,"robust-orientation":214}],241:[function(t,e,r){"use strict";function n(t,e){this.stars=t,this.edges=e}function i(t,e,r){for(var n=1,i=t.length;i>n;n+=2)if(t[n-1]===e&&t[n]===r)return t[n-1]=t[i-2],t[n]=t[i-1],void(t.length=i-2)}function a(t,e){for(var r=new Array(t),i=0;t>i;++i)r[i]=[];return new n(r,e)}var o=t("binary-search-bounds");e.exports=a;var s=n.prototype;s.isConstraint=function(){function t(t,e){return t[0]-e[0]||t[1]-e[1]}var e=[0,0];return function(r,n){return e[0]=Math.min(r,n),e[1]=Math.max(r,n),o.eq(this.edges,e,t)>=0}}(),s.removeTriangle=function(t,e,r){var n=this.stars;i(n[t],e,r),i(n[e],r,t),i(n[r],t,e)},s.addTriangle=function(t,e,r){var n=this.stars;n[t].push(e,r),n[e].push(r,t),n[r].push(t,e)},s.opposite=function(t,e){for(var r=this.stars[e],n=1,i=r.length;i>n;n+=2)if(r[n]===t)return r[n-1];return-1},s.flip=function(t,e){var r=this.opposite(t,e),n=this.opposite(e,t);this.removeTriangle(t,e,r),this.removeTriangle(e,t,n),this.addTriangle(t,n,r),this.addTriangle(e,r,n)},s.edges=function(){for(var t=this.stars,e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0,o=i.length;o>a;a+=2)e.push([i[a],i[a+1]]);return e},s.cells=function(){for(var t=this.stars,e=[],r=0,n=t.length;n>r;++r)for(var i=t[r],a=0,o=i.length;o>a;a+=2){var s=i[a],l=i[a+1];r<Math.min(s,l)&&e.push([r,s,l])}return e}},{"binary-search-bounds":242}],242:[function(t,e,r){arguments[4][121][0].apply(r,arguments)},{dup:121}],243:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t.length-1),n=1;n<t.length;++n)for(var i=r[n-1]=new Array(t.length-1),a=0,o=0;a<t.length;++a)a!==e&&(i[o++]=t[n][a]);return r}function i(t){for(var e=new Array(t),r=0;t>r;++r){e[r]=new Array(t);for(var n=0;t>n;++n)e[r][n]=["m",n,"[",t-r-2,"]"].join("")}return e}function a(t){if(1===t.length)return t[0];if(2===t.length)return["sum(",t[0],",",t[1],")"].join("");var e=t.length>>1;return["sum(",a(t.slice(0,e)),",",a(t.slice(e)),")"].join("")}function o(t,e){if("m"===t.charAt(0)){if("w"===e.charAt(0)){var r=t.split("[");return["w",e.substr(1),"m",r[0].substr(1)].join("")}return["prod(",t,",",e,")"].join("")}return o(e,t)}function s(t){return t&!0?"-":""}function l(t){if(2===t.length)return[["diff(",o(t[0][0],t[1][1]),",",o(t[1][0],t[0][1]),")"].join("")];for(var e=[],r=0;r<t.length;++r)e.push(["scale(",a(l(n(t,r))),",",s(r),t[0][r],")"].join(""));return e}function u(t,e){for(var r=[],n=0;e-2>n;++n)r.push(["prod(m",t,"[",n,"],m",t,"[",n,"])"].join(""));return a(r)}function c(t){for(var e=[],r=[],o=i(t),s=0;t>s;++s)o[0][s]="1",o[t-1][s]="w"+s;for(var s=0;t>s;++s)0===(1&s)?e.push.apply(e,l(n(o,s))):r.push.apply(r,l(n(o,s)));for(var c=a(e),h=a(r),f="exactInSphere"+t,d=[],s=0;t>s;++s)d.push("m"+s);for(var p=["function ",f,"(",d.join(),"){"],s=0;t>s;++s){p.push("var w",s,"=",u(s,t),";");for(var g=0;t>g;++g)g!==s&&p.push("var w",s,"m",g,"=scale(w",s,",m",g,"[0]);")}p.push("var p=",c,",n=",h,",d=diff(p,n);return d[d.length-1];}return ",f);var x=new Function("sum","diff","prod","scale",p.join(""));return x(m,y,v,b)}function h(){return 0}function f(){return 0}function d(){return 0}function p(t){var e=_[t.length];return e||(e=_[t.length]=c(t.length)),e.apply(void 0,t)}function g(){for(;_.length<=x;)_.push(c(_.length));for(var t=[],r=["slow"],n=0;x>=n;++n)t.push("a"+n),r.push("o"+n);for(var i=["function testInSphere(",t.join(),"){switch(arguments.length){case 0:case 1:return 0;"],n=2;x>=n;++n)i.push("case ",n,":return o",n,"(",t.slice(0,n).join(),");");i.push("}var s=new Array(arguments.length);for(var i=0;i<arguments.length;++i){s[i]=arguments[i]};return slow(s);}return testInSphere"),r.push(i.join(""));var a=Function.apply(void 0,r);e.exports=a.apply(void 0,[p].concat(_));for(var n=0;x>=n;++n)e.exports[n]=_[n]}var v=t("two-product"),m=t("robust-sum"),y=t("robust-subtract"),b=t("robust-scale"),x=6,_=[h,f,d];g()},{"robust-scale":215,"robust-subtract":216,"robust-sum":217,"two-product":231}],244:[function(t,e,r){"use strict";function n(t){var e=x(t),r=b(y(e),t);return 0>r?[e,w(e,1/0)]:r>0?[w(e,-(1/0)),e]:[e,e]}function i(t,e){for(var r=new Array(e.length),n=0;n<e.length;++n){var i=e[n],a=t[i[0]],o=t[i[1]];r[n]=[Math.min(a[0],o[0]),Math.min(a[1],o[1]),Math.max(a[0],o[0]),Math.max(a[1],o[1])]}return r}function a(t){for(var e=new Array(t.length),r=0;r<t.length;++r){var n=t[r];e[r]=[n[0],n[1],n[0],n[1]]}return e}function o(t,e,r){var n=[];return v(r,function(r,i){var a=e[r],o=e[i];if(a[0]!==o[0]&&a[0]!==o[1]&&a[1]!==o[0]&&a[1]!==o[1]){var s=t[a[0]],l=t[a[1]],u=t[o[0]],c=t[o[1]];m(s,l,u,c)&&n.push([r,i])}}),n}function s(t,e,r,n){var i=[];return v(r,n,function(r,n){var a=e[r];if(a[0]!==n&&a[1]!==n){var o=t[n],s=t[a[0]],l=t[a[1]];m(s,l,o,o)&&i.push([r,n])}}),i}function l(t,e,r,n,i){function a(e){if(e>=t.length)return o[e-t.length];var r=t[e];return[y(r[0]),y(r[1])]}for(var o=[],s=0;s<r.length;++s){var l=r[s],u=l[0],c=l[1],h=e[u],f=e[c],d=A(_(t[h[0]]),_(t[h[1]]),_(t[f[0]]),_(t[f[1]]));if(d){var p=o.length+t.length;o.push(d),n.push([u,p],[c,p])}}n.sort(function(t,e){if(t[0]!==e[0])return t[0]-e[0];var r=a(t[1]),n=a(e[1]);return b(r[0],n[0])||b(r[1],n[1])});for(var s=n.length-1;s>=0;--s){var g=n[s],u=g[0],v=e[u],m=v[0],x=v[1],w=t[m],k=t[x];if((w[0]-k[0]||w[1]-k[1])<0){var M=m;m=x,x=M}v[0]=m;var T,E=v[1]=g[1];for(i&&(T=v[2]);s>0&&n[s-1][0]===u;){var g=n[--s],L=g[1];i?e.push([E,L,T]):e.push([E,L]),E=L}i?e.push([E,x,T]):e.push([E,x])}return o}function u(t,e,r){for(var i=t.length+e.length,a=new g(i),o=r,s=0;s<e.length;++s){var l=e[s],u=n(l[0]),c=n(l[1]);o.push([u[0],c[0],u[1],c[1]]),t.push([x(l[0]),x(l[1])])}v(o,function(t,e){a.link(t,e)});for(var h=0,f=!0,d=new Array(i),s=0;i>s;++s){var p=a.find(s);p===s?(d[s]=h,t[h++]=t[s]):(f=!1,d[s]=-1)}if(t.length=h,f)return null;for(var s=0;i>s;++s)d[s]<0&&(d[s]=d[a.find(s)]);return d}function c(t,e){return t[0]-e[0]||t[1]-e[1]}function h(t,e){var r=t[0]-e[0]||t[1]-e[1];return r?r:t[2]<e[2]?-1:t[2]>e[2]?1:0}function f(t,e,r){if(0!==t.length){if(e)for(var n=0;n<t.length;++n){var i=t[n],a=e[i[0]],o=e[i[1]];i[0]=Math.min(a,o),i[1]=Math.max(a,o)}else for(var n=0;n<t.length;++n){var i=t[n],a=i[0],o=i[1];i[0]=Math.min(a,o),i[1]=Math.max(a,o)}r?t.sort(h):t.sort(c);for(var s=1,n=1;n<t.length;++n){var l=t[n-1],u=t[n];(u[0]!==l[0]||u[1]!==l[1]||r&&u[2]!==l[2])&&(t[s++]=u)}t.length=s}}function d(t,e,r){var n=i(t,e),c=o(t,e,n),h=a(t),d=s(t,e,n,h),p=l(t,e,c,d,r),g=u(t,p,h);return f(e,g,r),g?!0:c.length>0||d.length>0}function p(t,e,r){var n,i=!1;if(r){n=e;for(var a=new Array(e.length),o=0;o<e.length;++o){var s=e[o];a[o]=[s[0],s[1],r[o]]}e=a}for(;d(t,e,!!r);)i=!0;if(r&&i){n.length=0,r.length=0;for(var o=0;o<e.length;++o){var s=e[o];n.push([s[0],s[1]]),r.push(s[2])}}return i}e.exports=p;var g=t("union-find"),v=t("box-intersect"),m=(t("compare-cell"),t("robust-segment-intersect")),y=t("big-rat"),b=t("big-rat/cmp"),x=t("big-rat/to-float"),_=t("rat-vec"),w=t("nextafter"),A=t("./lib/rat-seg-intersect")},{"./lib/rat-seg-intersect":245,"big-rat":249,"big-rat/cmp":247,"big-rat/to-float":262,"box-intersect":263,"compare-cell":59,nextafter:271,"rat-vec":273,"robust-segment-intersect":276,"union-find":277}],245:[function(t,e,r){"use strict";function n(t,e){return s(a(t[0],e[1]),a(t[1],e[0]))}function i(t,e,r,i){var a=u(e,t),s=u(i,r),f=n(a,s);if(0===l(f))return null;var d=u(t,r),p=n(s,d),g=o(p,f);return c(t,h(a,g))}e.exports=i;var a=t("big-rat/mul"),o=t("big-rat/div"),s=t("big-rat/sub"),l=t("big-rat/sign"),u=t("rat-vec/sub"),c=t("rat-vec/add"),h=t("rat-vec/muls");t("big-rat/to-float")},{"big-rat/div":248,"big-rat/mul":258,"big-rat/sign":260,"big-rat/sub":261,"big-rat/to-float":262,"rat-vec/add":272,"rat-vec/muls":274,"rat-vec/sub":275}],246:[function(t,e,r){"use strict";function n(t,e){return i(t[0].mul(e[1]).add(e[0].mul(t[1])),t[1].mul(e[1]))}var i=t("./lib/rationalize");e.exports=n},{"./lib/rationalize":256}],247:[function(t,e,r){"use strict";function n(t,e){return t[0].mul(e[1]).cmp(e[0].mul(t[1]))}e.exports=n},{}],248:[function(t,e,r){"use strict";function n(t,e){return i(t[0].mul(e[1]),t[1].mul(e[0]))}var i=t("./lib/rationalize");e.exports=n},{"./lib/rationalize":256}],249:[function(t,e,r){"use strict";function n(t,e){if(i(t))return e?u(t,n(e)):[t[0].clone(),t[1].clone()];var r,c,h=0;if(a(t))r=t.clone();else if("string"==typeof t)r=s(t);else{if(0===t)return[o(0),o(1)];if(t===Math.floor(t))r=o(t);else{for(;t!==Math.floor(t);)t*=Math.pow(2,256),h-=256;r=o(t)}}if(i(e))r.mul(e[1]),c=e[0].clone();else if(a(e))c=e.clone();else if("string"==typeof e)c=s(e);else if(e)if(e===Math.floor(e))c=o(e);else{for(;e!==Math.floor(e);)e*=Math.pow(2,256),h+=256;c=o(e)}else c=o(1);return h>0?r=r.shln(h):0>h&&(c=c.shln(-h)),l(r,c)}var i=t("./is-rat"),a=t("./lib/is-bn"),o=t("./lib/num-to-bn"),s=t("./lib/str-to-bn"),l=t("./lib/rationalize"),u=t("./div");e.exports=n},{"./div":248,"./is-rat":250,"./lib/is-bn":254,"./lib/num-to-bn":255,"./lib/rationalize":256,"./lib/str-to-bn":257}],250:[function(t,e,r){"use strict";function n(t){return Array.isArray(t)&&2===t.length&&i(t[0])&&i(t[1])}var i=t("./lib/is-bn");e.exports=n},{"./lib/is-bn":254}],251:[function(t,e,r){"use strict";function n(t){return t.cmp(new i(0))}var i=t("bn.js");e.exports=n},{"bn.js":259}],252:[function(t,e,r){"use strict";function n(t){var e=t.length,r=t.words,n=0;if(1===e)n=r[0];else if(2===e)n=r[0]+67108864*r[1];else for(var n=0,i=0;e>i;i++){var a=r[i];n+=a*Math.pow(67108864,i)}return t.sign?-n:n}e.exports=n},{}],253:[function(t,e,r){"use strict";function n(t){var e=a(i.lo(t));if(32>e)return e;var r=a(i.hi(t));return r>20?52:r+32}var i=t("double-bits"),a=t("bit-twiddle").countTrailingZeros;e.exports=n},{"bit-twiddle":49,"double-bits":270}],254:[function(t,e,r){"use strict";function n(t){return t&&"object"==typeof t&&Boolean(t.words)}t("bn.js");e.exports=n},{"bn.js":259}],255:[function(t,e,r){"use strict";function n(t){var e=a.exponent(t);return 52>e?new i(t):new i(t*Math.pow(2,52-e)).shln(e-52)}var i=t("bn.js"),a=t("double-bits");e.exports=n},{"bn.js":259,"double-bits":270}],256:[function(t,e,r){"use strict";function n(t,e){var r=a(t),n=a(e);if(0===r)return[i(0),i(1)];if(0===n)return[i(0),i(0)];0>n&&(t=t.neg(),e=e.neg());var o=t.gcd(e);return o.cmpn(1)?[t.div(o),e.div(o)]:[t,e]}var i=t("./num-to-bn"),a=t("./bn-sign");e.exports=n},{"./bn-sign":251,"./num-to-bn":255}],257:[function(t,e,r){"use strict";function n(t){return new i(t)}var i=t("bn.js");e.exports=n},{"bn.js":259}],258:[function(t,e,r){"use strict";function n(t,e){return i(t[0].mul(e[0]),t[1].mul(e[1]))}var i=t("./lib/rationalize");e.exports=n},{"./lib/rationalize":256}],259:[function(t,e,r){!function(t,e){"use strict";function r(t,e){if(!t)throw new Error(e||"Assertion failed")}function n(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}function i(t,e,r){return null!==t&&"object"==typeof t&&Array.isArray(t.words)?t:(this.sign=!1,this.words=null,this.length=0,this.red=null,("le"===e||"be"===e)&&(r=e,e=10),void(null!==t&&this._init(t||0,e||10,r||"be")))}function a(t,e,r){for(var n=0,i=Math.min(t.length,r),a=e;i>a;a++){var o=t.charCodeAt(a)-48;n<<=4,n|=o>=49&&54>=o?o-49+10:o>=17&&22>=o?o-17+10:15&o}return n}function o(t,e,r,n){for(var i=0,a=Math.min(t.length,r),o=e;a>o;o++){var s=t.charCodeAt(o)-48;i*=n,i+=s>=49?s-49+10:s>=17?s-17+10:s}return i}function s(t,e){this.name=t,this.p=new i(e,16),this.n=this.p.bitLength(),this.k=new i(1).ishln(this.n).isub(this.p),this.tmp=this._tmp()}function l(){s.call(this,"k256","ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f")}function u(){s.call(this,"p224","ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001")}function c(){s.call(this,"p192","ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff")}function h(){s.call(this,"25519","7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed")}function f(t){if("string"==typeof t){var e=i._prime(t);this.m=e.p,this.prime=e}else this.m=t,this.prime=null}function d(t){f.call(this,t),this.shift=this.m.bitLength(),this.shift%26!==0&&(this.shift+=26-this.shift%26),this.r=new i(1).ishln(this.shift),this.r2=this.imod(this.r.sqr()),this.rinv=this.r._invmp(this.m),this.minv=this.rinv.mul(this.r).isubn(1).div(this.m),this.minv.sign=!0,this.minv=this.minv.mod(this.r)}"object"==typeof t?t.exports=i:e.BN=i,i.BN=i,i.wordSize=26,i.prototype._init=function(t,e,n){if("number"==typeof t)return this._initNumber(t,e,n);if("object"==typeof t)return this._initArray(t,e,n);"hex"===e&&(e=16),r(e===(0|e)&&e>=2&&36>=e),t=t.toString().replace(/\s+/g,"");var i=0;"-"===t[0]&&i++,16===e?this._parseHex(t,i):this._parseBase(t,e,i),"-"===t[0]&&(this.sign=!0),this.strip(),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initNumber=function(t,e,n){0>t&&(this.sign=!0,t=-t),67108864>t?(this.words=[67108863&t],this.length=1):4503599627370496>t?(this.words=[67108863&t,t/67108864&67108863],this.length=2):(r(9007199254740992>t),this.words=[67108863&t,t/67108864&67108863,1],this.length=3),"le"===n&&this._initArray(this.toArray(),e,n)},i.prototype._initArray=function(t,e,n){if(r("number"==typeof t.length),t.length<=0)return this.words=[0],this.length=1,this;this.length=Math.ceil(t.length/3),this.words=new Array(this.length);for(var i=0;i<this.length;i++)this.words[i]=0;var a=0;if("be"===n)for(var i=t.length-1,o=0;i>=0;i-=3){var s=t[i]|t[i-1]<<8|t[i-2]<<16;this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,a+=24,a>=26&&(a-=26,o++)}else if("le"===n)for(var i=0,o=0;i<t.length;i+=3){var s=t[i]|t[i+1]<<8|t[i+2]<<16;this.words[o]|=s<<a&67108863,this.words[o+1]=s>>>26-a&67108863,a+=24,a>=26&&(a-=26,o++)}return this.strip()},i.prototype._parseHex=function(t,e){this.length=Math.ceil((t.length-e)/6),this.words=new Array(this.length);for(var r=0;r<this.length;r++)this.words[r]=0;for(var n=0,r=t.length-6,i=0;r>=e;r-=6){var o=a(t,r,r+6);this.words[i]|=o<<n&67108863,this.words[i+1]|=o>>>26-n&4194303,n+=24,n>=26&&(n-=26,i++)}if(r+6!==e){var o=a(t,e,r+6);this.words[i]|=o<<n&67108863,this.words[i+1]|=o>>>26-n&4194303}this.strip()},i.prototype._parseBase=function(t,e,r){this.words=[0],this.length=1;for(var n=0,i=1;67108863>=i;i*=e)n++;n--,i=i/e|0;for(var a=t.length-r,s=a%n,l=Math.min(a,a-s)+r,u=0,c=r;l>c;c+=n)u=o(t,c,c+n,e),this.imuln(i),this.words[0]+u<67108864?this.words[0]+=u:this._iaddn(u);if(0!==s){for(var h=1,u=o(t,c,t.length,e),c=0;s>c;c++)h*=e;this.imuln(h),this.words[0]+u<67108864?this.words[0]+=u:this._iaddn(u)}},i.prototype.copy=function(t){t.words=new Array(this.length);for(var e=0;e<this.length;e++)t.words[e]=this.words[e];t.length=this.length,t.sign=this.sign,t.red=this.red},i.prototype.clone=function(){var t=new i(null);return this.copy(t),t},i.prototype.strip=function(){for(;this.length>1&&0===this.words[this.length-1];)this.length--;return this._normSign()},i.prototype._normSign=function(){return 1===this.length&&0===this.words[0]&&(this.sign=!1),this},i.prototype.inspect=function(){return(this.red?"<BN-R: ":"<BN: ")+this.toString(16)+">"};var p=["","0","00","000","0000","00000","000000","0000000","00000000","000000000","0000000000","00000000000","000000000000","0000000000000","00000000000000","000000000000000","0000000000000000","00000000000000000","000000000000000000","0000000000000000000","00000000000000000000","000000000000000000000","0000000000000000000000","00000000000000000000000","000000000000000000000000","0000000000000000000000000"],g=[0,0,25,16,12,11,10,9,8,8,7,7,7,7,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5],v=[0,0,33554432,43046721,16777216,48828125,60466176,40353607,16777216,43046721,1e7,19487171,35831808,62748517,7529536,11390625,16777216,24137569,34012224,47045881,64e6,4084101,5153632,6436343,7962624,9765625,11881376,14348907,17210368,20511149,243e5,28629151,33554432,39135393,45435424,52521875,60466176];i.prototype.toString=function(t,e){if(t=t||10,16===t||"hex"===t){for(var n="",i=0,e=0|e||1,a=0,o=0;o<this.length;o++){var s=this.words[o],l=(16777215&(s<<i|a)).toString(16);a=s>>>24-i&16777215,n=0!==a||o!==this.length-1?p[6-l.length]+l+n:l+n,i+=2,i>=26&&(i-=26,o--)}for(0!==a&&(n=a.toString(16)+n);n.length%e!==0;)n="0"+n;return this.sign&&(n="-"+n),n}if(t===(0|t)&&t>=2&&36>=t){var u=g[t],c=v[t],n="",h=this.clone();for(h.sign=!1;0!==h.cmpn(0);){var f=h.modn(c).toString(t);h=h.idivn(c),n=0!==h.cmpn(0)?p[u-f.length]+f+n:f+n}return 0===this.cmpn(0)&&(n="0"+n),this.sign&&(n="-"+n),n}r(!1,"Base should be between 2 and 36")},i.prototype.toJSON=function(){return this.toString(16)},i.prototype.toArray=function(t){this.strip();var e=new Array(this.byteLength());e[0]=0;var r=this.clone();if("le"!==t)for(var n=0;0!==r.cmpn(0);n++){var i=r.andln(255);r.ishrn(8),e[e.length-n-1]=i}else for(var n=0;0!==r.cmpn(0);n++){var i=r.andln(255);r.ishrn(8),e[n]=i}return e},Math.clz32?i.prototype._countBits=function(t){return 32-Math.clz32(t)}:i.prototype._countBits=function(t){var e=t,r=0;return e>=4096&&(r+=13,e>>>=13),e>=64&&(r+=7,e>>>=7),e>=8&&(r+=4,e>>>=4),e>=2&&(r+=2,e>>>=2),r+e},i.prototype._zeroBits=function(t){if(0===t)return 26;var e=t,r=0;return 0===(8191&e)&&(r+=13,e>>>=13),0===(127&e)&&(r+=7,e>>>=7),0===(15&e)&&(r+=4,e>>>=4),0===(3&e)&&(r+=2,e>>>=2),0===(1&e)&&r++,r},i.prototype.bitLength=function(){var t=0,e=this.words[this.length-1],t=this._countBits(e);return 26*(this.length-1)+t},i.prototype.zeroBits=function(){if(0===this.cmpn(0))return 0;for(var t=0,e=0;e<this.length;e++){var r=this._zeroBits(this.words[e]);if(t+=r,26!==r)break}return t},i.prototype.byteLength=function(){return Math.ceil(this.bitLength()/8)},i.prototype.neg=function(){if(0===this.cmpn(0))return this.clone();var t=this.clone();return t.sign=!this.sign,t},i.prototype.ior=function(t){for(this.sign=this.sign||t.sign;this.length<t.length;)this.words[this.length++]=0;for(var e=0;e<t.length;e++)this.words[e]=this.words[e]|t.words[e];return this.strip()},i.prototype.or=function(t){return this.length>t.length?this.clone().ior(t):t.clone().ior(this)},i.prototype.iand=function(t){this.sign=this.sign&&t.sign;var e;e=this.length>t.length?t:this;for(var r=0;r<e.length;r++)this.words[r]=this.words[r]&t.words[r];return this.length=e.length,this.strip()},i.prototype.and=function(t){return this.length>t.length?this.clone().iand(t):t.clone().iand(this)},i.prototype.ixor=function(t){this.sign=this.sign||t.sign;var e,r;this.length>t.length?(e=this,r=t):(e=t,r=this);for(var n=0;n<r.length;n++)this.words[n]=e.words[n]^r.words[n];if(this!==e)for(;n<e.length;n++)this.words[n]=e.words[n];return this.length=e.length,this.strip()},i.prototype.xor=function(t){return this.length>t.length?this.clone().ixor(t):t.clone().ixor(this)},i.prototype.setn=function(t,e){r("number"==typeof t&&t>=0);for(var n=t/26|0,i=t%26;this.length<=n;)this.words[this.length++]=0;return e?this.words[n]=this.words[n]|1<<i:this.words[n]=this.words[n]&~(1<<i),this.strip()},i.prototype.iadd=function(t){if(this.sign&&!t.sign){this.sign=!1;var e=this.isub(t);return this.sign=!this.sign,this._normSign()}if(!this.sign&&t.sign){t.sign=!1;var e=this.isub(t);return t.sign=!0,e._normSign()}var r,n;this.length>t.length?(r=this,n=t):(r=t,n=this);for(var i=0,a=0;a<n.length;a++){var e=r.words[a]+n.words[a]+i;this.words[a]=67108863&e,i=e>>>26}for(;0!==i&&a<r.length;a++){var e=r.words[a]+i;this.words[a]=67108863&e,i=e>>>26}if(this.length=r.length,0!==i)this.words[this.length]=i,this.length++;else if(r!==this)for(;a<r.length;a++)this.words[a]=r.words[a];return this},i.prototype.add=function(t){if(t.sign&&!this.sign){t.sign=!1;var e=this.sub(t);return t.sign=!0,e}if(!t.sign&&this.sign){this.sign=!1;var e=t.sub(this);return this.sign=!0,e}return this.length>t.length?this.clone().iadd(t):t.clone().iadd(this)},i.prototype.isub=function(t){if(t.sign){t.sign=!1;var e=this.iadd(t);return t.sign=!0,e._normSign()}if(this.sign)return this.sign=!1,this.iadd(t),this.sign=!0,this._normSign();var r=this.cmp(t);if(0===r)return this.sign=!1,this.length=1,this.words[0]=0,this;var n,i;r>0?(n=this,i=t):(n=t,i=this);for(var a=0,o=0;o<i.length;o++){var e=n.words[o]-i.words[o]+a;a=e>>26,this.words[o]=67108863&e}for(;0!==a&&o<n.length;o++){var e=n.words[o]+a;a=e>>26,this.words[o]=67108863&e}if(0===a&&o<n.length&&n!==this)for(;o<n.length;o++)this.words[o]=n.words[o];return this.length=Math.max(this.length,o),n!==this&&(this.sign=!0),this.strip()},i.prototype.sub=function(t){return this.clone().isub(t)},i.prototype._smallMulTo=function(t,e){e.sign=t.sign!==this.sign,e.length=this.length+t.length;for(var r=0,n=0;n<e.length-1;n++){for(var i=r>>>26,a=67108863&r,o=Math.min(n,t.length-1),s=Math.max(0,n-this.length+1);o>=s;s++){var l=n-s,u=0|this.words[l],c=0|t.words[s],h=u*c,f=67108863&h;i=i+(h/67108864|0)|0,f=f+a|0,a=67108863&f,i=i+(f>>>26)|0}e.words[n]=a,r=i}return 0!==r?e.words[n]=r:e.length--,e.strip()},i.prototype._bigMulTo=function(t,e){e.sign=t.sign!==this.sign,e.length=this.length+t.length;for(var r=0,n=0,i=0;i<e.length-1;i++){var a=n;n=0;for(var o=67108863&r,s=Math.min(i,t.length-1),l=Math.max(0,i-this.length+1);s>=l;l++){var u=i-l,c=0|this.words[u],h=0|t.words[l],f=c*h,d=67108863&f;a=a+(f/67108864|0)|0,d=d+o|0,o=67108863&d,a=a+(d>>>26)|0,n+=a>>>26,a&=67108863}e.words[i]=o,r=a,a=n}return 0!==r?e.words[i]=r:e.length--,e.strip()},i.prototype.mulTo=function(t,e){var r;return r=this.length+t.length<63?this._smallMulTo(t,e):this._bigMulTo(t,e)},i.prototype.mul=function(t){var e=new i(null);return e.words=new Array(this.length+t.length),this.mulTo(t,e)},i.prototype.imul=function(t){if(0===this.cmpn(0)||0===t.cmpn(0))return this.words[0]=0,this.length=1,this;var e=this.length,r=t.length;this.sign=t.sign!==this.sign,
+this.length=this.length+t.length,this.words[this.length-1]=0;for(var n=this.length-2;n>=0;n--){for(var i=0,a=0,o=Math.min(n,r-1),s=Math.max(0,n-e+1);o>=s;s++){var l=n-s,u=this.words[l],c=t.words[s],h=u*c,f=67108863&h;i+=h/67108864|0,f+=a,a=67108863&f,i+=f>>>26}this.words[n]=a,this.words[n+1]+=i,i=0}for(var i=0,l=1;l<this.length;l++){var d=this.words[l]+i;this.words[l]=67108863&d,i=d>>>26}return this.strip()},i.prototype.imuln=function(t){r("number"==typeof t);for(var e=0,n=0;n<this.length;n++){var i=this.words[n]*t,a=(67108863&i)+(67108863&e);e>>=26,e+=i/67108864|0,e+=a>>>26,this.words[n]=67108863&a}return 0!==e&&(this.words[n]=e,this.length++),this},i.prototype.muln=function(t){return this.clone().imuln(t)},i.prototype.sqr=function(){return this.mul(this)},i.prototype.isqr=function(){return this.mul(this)},i.prototype.ishln=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=67108863>>>26-e<<26-e;if(0!==e){for(var a=0,o=0;o<this.length;o++){var s=this.words[o]&i,l=this.words[o]-s<<e;this.words[o]=l|a,a=s>>>26-e}a&&(this.words[o]=a,this.length++)}if(0!==n){for(var o=this.length-1;o>=0;o--)this.words[o+n]=this.words[o];for(var o=0;n>o;o++)this.words[o]=0;this.length+=n}return this.strip()},i.prototype.ishrn=function(t,e,n){r("number"==typeof t&&t>=0);var i;i=e?(e-e%26)/26:0;var a=t%26,o=Math.min((t-a)/26,this.length),s=67108863^67108863>>>a<<a,l=n;if(i-=o,i=Math.max(0,i),l){for(var u=0;o>u;u++)l.words[u]=this.words[u];l.length=o}if(0===o);else if(this.length>o){this.length-=o;for(var u=0;u<this.length;u++)this.words[u]=this.words[u+o]}else this.words[0]=0,this.length=1;for(var c=0,u=this.length-1;u>=0&&(0!==c||u>=i);u--){var h=this.words[u];this.words[u]=c<<26-a|h>>>a,c=h&s}return l&&0!==c&&(l.words[l.length++]=c),0===this.length&&(this.words[0]=0,this.length=1),this.strip(),this},i.prototype.shln=function(t){return this.clone().ishln(t)},i.prototype.shrn=function(t){return this.clone().ishrn(t)},i.prototype.testn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26,i=1<<e;if(this.length<=n)return!1;var a=this.words[n];return!!(a&i)},i.prototype.imaskn=function(t){r("number"==typeof t&&t>=0);var e=t%26,n=(t-e)/26;if(r(!this.sign,"imaskn works only with positive numbers"),0!==e&&n++,this.length=Math.min(n,this.length),0!==e){var i=67108863^67108863>>>e<<e;this.words[this.length-1]&=i}return this.strip()},i.prototype.maskn=function(t){return this.clone().imaskn(t)},i.prototype.iaddn=function(t){return r("number"==typeof t),0>t?this.isubn(-t):this.sign?1===this.length&&this.words[0]<t?(this.words[0]=t-this.words[0],this.sign=!1,this):(this.sign=!1,this.isubn(t),this.sign=!0,this):this._iaddn(t)},i.prototype._iaddn=function(t){this.words[0]+=t;for(var e=0;e<this.length&&this.words[e]>=67108864;e++)this.words[e]-=67108864,e===this.length-1?this.words[e+1]=1:this.words[e+1]++;return this.length=Math.max(this.length,e+1),this},i.prototype.isubn=function(t){if(r("number"==typeof t),0>t)return this.iaddn(-t);if(this.sign)return this.sign=!1,this.iaddn(t),this.sign=!0,this;this.words[0]-=t;for(var e=0;e<this.length&&this.words[e]<0;e++)this.words[e]+=67108864,this.words[e+1]-=1;return this.strip()},i.prototype.addn=function(t){return this.clone().iaddn(t)},i.prototype.subn=function(t){return this.clone().isubn(t)},i.prototype.iabs=function(){return this.sign=!1,this},i.prototype.abs=function(){return this.clone().iabs()},i.prototype._ishlnsubmul=function(t,e,n){var i,a=t.length+n;if(this.words.length<a){for(var o=new Array(a),i=0;i<this.length;i++)o[i]=this.words[i];this.words=o}else i=this.length;for(this.length=Math.max(this.length,a);i<this.length;i++)this.words[i]=0;for(var s=0,i=0;i<t.length;i++){var l=this.words[i+n]+s,u=t.words[i]*e;l-=67108863&u,s=(l>>26)-(u/67108864|0),this.words[i+n]=67108863&l}for(;i<this.length-n;i++){var l=this.words[i+n]+s;s=l>>26,this.words[i+n]=67108863&l}if(0===s)return this.strip();r(-1===s),s=0;for(var i=0;i<this.length;i++){var l=-this.words[i]+s;s=l>>26,this.words[i]=67108863&l}return this.sign=!0,this.strip()},i.prototype._wordDiv=function(t,e){var r=this.length-t.length,n=this.clone(),a=t,o=a.words[a.length-1],s=this._countBits(o);r=26-s,0!==r&&(a=a.shln(r),n.ishln(r),o=a.words[a.length-1]);var l,u=n.length-a.length;if("mod"!==e){l=new i(null),l.length=u+1,l.words=new Array(l.length);for(var c=0;c<l.length;c++)l.words[c]=0}var h=n.clone()._ishlnsubmul(a,1,u);h.sign||(n=h,l&&(l.words[u]=1));for(var f=u-1;f>=0;f--){var d=67108864*n.words[a.length+f]+n.words[a.length+f-1];for(d=Math.min(d/o|0,67108863),n._ishlnsubmul(a,d,f);n.sign;)d--,n.sign=!1,n._ishlnsubmul(a,1,f),0!==n.cmpn(0)&&(n.sign=!n.sign);l&&(l.words[f]=d)}return l&&l.strip(),n.strip(),"div"!==e&&0!==r&&n.ishrn(r),{div:l?l:null,mod:n}},i.prototype.divmod=function(t,e){if(r(0!==t.cmpn(0)),this.sign&&!t.sign){var n,a,o=this.neg().divmod(t,e);return"mod"!==e&&(n=o.div.neg()),"div"!==e&&(a=0===o.mod.cmpn(0)?o.mod:t.sub(o.mod)),{div:n,mod:a}}if(!this.sign&&t.sign){var n,o=this.divmod(t.neg(),e);return"mod"!==e&&(n=o.div.neg()),{div:n,mod:o.mod}}return this.sign&&t.sign?this.neg().divmod(t.neg(),e):t.length>this.length||this.cmp(t)<0?{div:new i(0),mod:this}:1===t.length?"div"===e?{div:this.divn(t.words[0]),mod:null}:"mod"===e?{div:null,mod:new i(this.modn(t.words[0]))}:{div:this.divn(t.words[0]),mod:new i(this.modn(t.words[0]))}:this._wordDiv(t,e)},i.prototype.div=function(t){return this.divmod(t,"div").div},i.prototype.mod=function(t){return this.divmod(t,"mod").mod},i.prototype.divRound=function(t){var e=this.divmod(t);if(0===e.mod.cmpn(0))return e.div;var r=e.div.sign?e.mod.isub(t):e.mod,n=t.shrn(1),i=t.andln(1),a=r.cmp(n);return 0>a||1===i&&0===a?e.div:e.div.sign?e.div.isubn(1):e.div.iaddn(1)},i.prototype.modn=function(t){r(67108863>=t);for(var e=(1<<26)%t,n=0,i=this.length-1;i>=0;i--)n=(e*n+this.words[i])%t;return n},i.prototype.idivn=function(t){r(67108863>=t);for(var e=0,n=this.length-1;n>=0;n--){var i=this.words[n]+67108864*e;this.words[n]=i/t|0,e=i%t}return this.strip()},i.prototype.divn=function(t){return this.clone().idivn(t)},i.prototype.egcd=function(t){r(!t.sign),r(0!==t.cmpn(0));var e=this,n=t.clone();e=e.sign?e.mod(t):e.clone();for(var a=new i(1),o=new i(0),s=new i(0),l=new i(1),u=0;e.isEven()&&n.isEven();)e.ishrn(1),n.ishrn(1),++u;for(var c=n.clone(),h=e.clone();0!==e.cmpn(0);){for(;e.isEven();)e.ishrn(1),a.isEven()&&o.isEven()?(a.ishrn(1),o.ishrn(1)):(a.iadd(c).ishrn(1),o.isub(h).ishrn(1));for(;n.isEven();)n.ishrn(1),s.isEven()&&l.isEven()?(s.ishrn(1),l.ishrn(1)):(s.iadd(c).ishrn(1),l.isub(h).ishrn(1));e.cmp(n)>=0?(e.isub(n),a.isub(s),o.isub(l)):(n.isub(e),s.isub(a),l.isub(o))}return{a:s,b:l,gcd:n.ishln(u)}},i.prototype._invmp=function(t){r(!t.sign),r(0!==t.cmpn(0));var e=this,n=t.clone();e=e.sign?e.mod(t):e.clone();for(var a=new i(1),o=new i(0),s=n.clone();e.cmpn(1)>0&&n.cmpn(1)>0;){for(;e.isEven();)e.ishrn(1),a.isEven()?a.ishrn(1):a.iadd(s).ishrn(1);for(;n.isEven();)n.ishrn(1),o.isEven()?o.ishrn(1):o.iadd(s).ishrn(1);e.cmp(n)>=0?(e.isub(n),a.isub(o)):(n.isub(e),o.isub(a))}return 0===e.cmpn(1)?a:o},i.prototype.gcd=function(t){if(0===this.cmpn(0))return t.clone();if(0===t.cmpn(0))return this.clone();var e=this.clone(),r=t.clone();e.sign=!1,r.sign=!1;for(var n=0;e.isEven()&&r.isEven();n++)e.ishrn(1),r.ishrn(1);for(;;){for(;e.isEven();)e.ishrn(1);for(;r.isEven();)r.ishrn(1);var i=e.cmp(r);if(0>i){var a=e;e=r,r=a}else if(0===i||0===r.cmpn(1))break;e.isub(r)}return r.ishln(n)},i.prototype.invm=function(t){return this.egcd(t).a.mod(t)},i.prototype.isEven=function(){return 0===(1&this.words[0])},i.prototype.isOdd=function(){return 1===(1&this.words[0])},i.prototype.andln=function(t){return this.words[0]&t},i.prototype.bincn=function(t){r("number"==typeof t);var e=t%26,n=(t-e)/26,i=1<<e;if(this.length<=n){for(var a=this.length;n+1>a;a++)this.words[a]=0;return this.words[n]|=i,this.length=n+1,this}for(var o=i,a=n;0!==o&&a<this.length;a++){var s=this.words[a];s+=o,o=s>>>26,s&=67108863,this.words[a]=s}return 0!==o&&(this.words[a]=o,this.length++),this},i.prototype.cmpn=function(t){var e=0>t;if(e&&(t=-t),this.sign&&!e)return-1;if(!this.sign&&e)return 1;t&=67108863,this.strip();var r;if(this.length>1)r=1;else{var n=this.words[0];r=n===t?0:t>n?-1:1}return this.sign&&(r=-r),r},i.prototype.cmp=function(t){if(this.sign&&!t.sign)return-1;if(!this.sign&&t.sign)return 1;var e=this.ucmp(t);return this.sign?-e:e},i.prototype.ucmp=function(t){if(this.length>t.length)return 1;if(this.length<t.length)return-1;for(var e=0,r=this.length-1;r>=0;r--){var n=this.words[r],i=t.words[r];if(n!==i){i>n?e=-1:n>i&&(e=1);break}}return e},i.red=function(t){return new f(t)},i.prototype.toRed=function(t){return r(!this.red,"Already a number in reduction context"),r(!this.sign,"red works only with positives"),t.convertTo(this)._forceRed(t)},i.prototype.fromRed=function(){return r(this.red,"fromRed works only with numbers in reduction context"),this.red.convertFrom(this)},i.prototype._forceRed=function(t){return this.red=t,this},i.prototype.forceRed=function(t){return r(!this.red,"Already a number in reduction context"),this._forceRed(t)},i.prototype.redAdd=function(t){return r(this.red,"redAdd works only with red numbers"),this.red.add(this,t)},i.prototype.redIAdd=function(t){return r(this.red,"redIAdd works only with red numbers"),this.red.iadd(this,t)},i.prototype.redSub=function(t){return r(this.red,"redSub works only with red numbers"),this.red.sub(this,t)},i.prototype.redISub=function(t){return r(this.red,"redISub works only with red numbers"),this.red.isub(this,t)},i.prototype.redShl=function(t){return r(this.red,"redShl works only with red numbers"),this.red.shl(this,t)},i.prototype.redMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.mul(this,t)},i.prototype.redIMul=function(t){return r(this.red,"redMul works only with red numbers"),this.red._verify2(this,t),this.red.imul(this,t)},i.prototype.redSqr=function(){return r(this.red,"redSqr works only with red numbers"),this.red._verify1(this),this.red.sqr(this)},i.prototype.redISqr=function(){return r(this.red,"redISqr works only with red numbers"),this.red._verify1(this),this.red.isqr(this)},i.prototype.redSqrt=function(){return r(this.red,"redSqrt works only with red numbers"),this.red._verify1(this),this.red.sqrt(this)},i.prototype.redInvm=function(){return r(this.red,"redInvm works only with red numbers"),this.red._verify1(this),this.red.invm(this)},i.prototype.redNeg=function(){return r(this.red,"redNeg works only with red numbers"),this.red._verify1(this),this.red.neg(this)},i.prototype.redPow=function(t){return r(this.red&&!t.red,"redPow(normalNum)"),this.red._verify1(this),this.red.pow(this,t)};var m={k256:null,p224:null,p192:null,p25519:null};s.prototype._tmp=function(){var t=new i(null);return t.words=new Array(Math.ceil(this.n/13)),t},s.prototype.ireduce=function(t){var e,r=t;do this.split(r,this.tmp),r=this.imulK(r),r=r.iadd(this.tmp),e=r.bitLength();while(e>this.n);var n=e<this.n?-1:r.ucmp(this.p);return 0===n?(r.words[0]=0,r.length=1):n>0?r.isub(this.p):r.strip(),r},s.prototype.split=function(t,e){t.ishrn(this.n,0,e)},s.prototype.imulK=function(t){return t.imul(this.k)},n(l,s),l.prototype.split=function(t,e){for(var r=4194303,n=Math.min(t.length,9),i=0;n>i;i++)e.words[i]=t.words[i];if(e.length=n,t.length<=9)return t.words[0]=0,void(t.length=1);var a=t.words[9];e.words[e.length++]=a&r;for(var i=10;i<t.length;i++){var o=t.words[i];t.words[i-10]=(o&r)<<4|a>>>22,a=o}t.words[i-10]=a>>>22,t.length-=9},l.prototype.imulK=function(t){t.words[t.length]=0,t.words[t.length+1]=0,t.length+=2;for(var e,r=0,n=0;n<t.length;n++){var i=t.words[n];e=64*i,r+=977*i,e+=r/67108864|0,r&=67108863,t.words[n]=r,r=e}return 0===t.words[t.length-1]&&(t.length--,0===t.words[t.length-1]&&t.length--),t},n(u,s),n(c,s),n(h,s),h.prototype.imulK=function(t){for(var e=0,r=0;r<t.length;r++){var n=19*t.words[r]+e,i=67108863&n;n>>>=26,t.words[r]=i,e=n}return 0!==e&&(t.words[t.length++]=e),t},i._prime=function y(t){if(m[t])return m[t];var y;if("k256"===t)y=new l;else if("p224"===t)y=new u;else if("p192"===t)y=new c;else{if("p25519"!==t)throw new Error("Unknown prime "+t);y=new h}return m[t]=y,y},f.prototype._verify1=function(t){r(!t.sign,"red works only with positives"),r(t.red,"red works only with red numbers")},f.prototype._verify2=function(t,e){r(!t.sign&&!e.sign,"red works only with positives"),r(t.red&&t.red===e.red,"red works only with red numbers")},f.prototype.imod=function(t){return this.prime?this.prime.ireduce(t)._forceRed(this):t.mod(this.m)._forceRed(this)},f.prototype.neg=function(t){var e=t.clone();return e.sign=!e.sign,e.iadd(this.m)._forceRed(this)},f.prototype.add=function(t,e){this._verify2(t,e);var r=t.add(e);return r.cmp(this.m)>=0&&r.isub(this.m),r._forceRed(this)},f.prototype.iadd=function(t,e){this._verify2(t,e);var r=t.iadd(e);return r.cmp(this.m)>=0&&r.isub(this.m),r},f.prototype.sub=function(t,e){this._verify2(t,e);var r=t.sub(e);return r.cmpn(0)<0&&r.iadd(this.m),r._forceRed(this)},f.prototype.isub=function(t,e){this._verify2(t,e);var r=t.isub(e);return r.cmpn(0)<0&&r.iadd(this.m),r},f.prototype.shl=function(t,e){return this._verify1(t),this.imod(t.shln(e))},f.prototype.imul=function(t,e){return this._verify2(t,e),this.imod(t.imul(e))},f.prototype.mul=function(t,e){return this._verify2(t,e),this.imod(t.mul(e))},f.prototype.isqr=function(t){return this.imul(t,t)},f.prototype.sqr=function(t){return this.mul(t,t)},f.prototype.sqrt=function(t){if(0===t.cmpn(0))return t.clone();var e=this.m.andln(3);if(r(e%2===1),3===e){var n=this.m.add(new i(1)).ishrn(2),a=this.pow(t,n);return a}for(var o=this.m.subn(1),s=0;0!==o.cmpn(0)&&0===o.andln(1);)s++,o.ishrn(1);r(0!==o.cmpn(0));var l=new i(1).toRed(this),u=l.redNeg(),c=this.m.subn(1).ishrn(1),h=this.m.bitLength();for(h=new i(2*h*h).toRed(this);0!==this.pow(h,c).cmp(u);)h.redIAdd(u);for(var f=this.pow(h,o),a=this.pow(t,o.addn(1).ishrn(1)),d=this.pow(t,o),p=s;0!==d.cmp(l);){for(var g=d,v=0;0!==g.cmp(l);v++)g=g.redSqr();r(p>v);var m=this.pow(f,new i(1).ishln(p-v-1));a=a.redMul(m),f=m.redSqr(),d=d.redMul(f),p=v}return a},f.prototype.invm=function(t){var e=t._invmp(this.m);return e.sign?(e.sign=!1,this.imod(e).redNeg()):this.imod(e)},f.prototype.pow=function(t,e){var r=[];if(0===e.cmpn(0))return new i(1);for(var n=e.clone();0!==n.cmpn(0);)r.push(n.andln(1)),n.ishrn(1);for(var a=t,o=0;o<r.length&&0===r[o];o++,a=this.sqr(a));if(++o<r.length)for(var n=this.sqr(a);o<r.length;o++,n=this.sqr(n))0!==r[o]&&(a=this.mul(a,n));return a},f.prototype.convertTo=function(t){var e=t.mod(this.m);return e===t?e.clone():e},f.prototype.convertFrom=function(t){var e=t.clone();return e.red=null,e},i.mont=function(t){return new d(t)},n(d,f),d.prototype.convertTo=function(t){return this.imod(t.shln(this.shift))},d.prototype.convertFrom=function(t){var e=this.imod(t.mul(this.rinv));return e.red=null,e},d.prototype.imul=function(t,e){if(0===t.cmpn(0)||0===e.cmpn(0))return t.words[0]=0,t.length=1,t;var r=t.imul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),i=r.isub(n).ishrn(this.shift),a=i;return i.cmp(this.m)>=0?a=i.isub(this.m):i.cmpn(0)<0&&(a=i.iadd(this.m)),a._forceRed(this)},d.prototype.mul=function(t,e){if(0===t.cmpn(0)||0===e.cmpn(0))return new i(0)._forceRed(this);var r=t.mul(e),n=r.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m),a=r.isub(n).ishrn(this.shift),o=a;return a.cmp(this.m)>=0?o=a.isub(this.m):a.cmpn(0)<0&&(o=a.iadd(this.m)),o._forceRed(this)},d.prototype.invm=function(t){var e=this.imod(t._invmp(this.m).mul(this.r2));return e._forceRed(this)}}("undefined"==typeof e||e,this)},{}],260:[function(t,e,r){"use strict";function n(t){return i(t[0])*i(t[1])}var i=t("./lib/bn-sign");e.exports=n},{"./lib/bn-sign":251}],261:[function(t,e,r){"use strict";function n(t,e){return i(t[0].mul(e[1]).sub(t[1].mul(e[0])),t[1].mul(e[1]))}var i=t("./lib/rationalize");e.exports=n},{"./lib/rationalize":256}],262:[function(t,e,r){"use strict";function n(t){var e=t[0],r=t[1];if(0===e.cmpn(0))return 0;var n=e.divmod(r),o=n.div,s=i(o),l=n.mod;if(0===l.cmpn(0))return s;if(s){var u=a(s)+4,c=i(l.shln(u).divRound(r));return 0>s&&(c=-c),s+c*Math.pow(2,-u)}var h=r.bitLength()-l.bitLength()+53,c=i(l.shln(h).divRound(r));return 1023>h?c*Math.pow(2,-h):(c*=Math.pow(2,-1023),c*Math.pow(2,1023-h))}var i=t("./lib/bn-to-num"),a=t("./lib/ctz");e.exports=n},{"./lib/bn-to-num":252,"./lib/ctz":253}],263:[function(t,e,r){"use strict";function n(t,e){for(var r=0;t>r;++r)if(!(e[r]<=e[r+t]))return!0;return!1}function i(t,e,r,i){for(var a=0,o=0,s=0,l=t.length;l>s;++s){var u=t[s];if(!n(e,u)){for(var c=0;2*e>c;++c)r[a++]=u[c];i[o++]=s}}return o}function a(t,e,r,n){var a=t.length,o=e.length;if(!(0>=a||0>=o)){var s=t[0].length>>>1;if(!(0>=s)){var l,u=h.mallocDouble(2*s*a),c=h.mallocInt32(a);if(a=i(t,s,u,c),a>0){if(1===s&&n)f.init(a),l=f.sweepComplete(s,r,0,a,u,c,0,a,u,c);else{var p=h.mallocDouble(2*s*o),g=h.mallocInt32(o);o=i(e,s,p,g),o>0&&(f.init(a+o),l=1===s?f.sweepBipartite(s,r,0,a,u,c,0,o,p,g):d(s,r,n,a,u,c,o,p,g),h.free(p),h.free(g))}h.free(u),h.free(c)}return l}}}function o(t,e){c.push([t,e])}function s(t){return c=[],a(t,t,o,!0),c}function l(t,e){return c=[],a(t,e,o,!1),c}function u(t,e,r){switch(arguments.length){case 1:return s(t);case 2:return"function"==typeof e?a(t,t,e,!0):l(t,e);case 3:return a(t,e,r,!1);default:throw new Error("box-intersect: Invalid arguments")}}e.exports=u;var c,h=t("typedarray-pool"),f=t("./lib/sweep"),d=t("./lib/intersect")},{"./lib/intersect":265,"./lib/sweep":269,"typedarray-pool":233}],264:[function(t,e,r){"use strict";function n(t,e,r){var n="bruteForce"+(t?"Red":"Blue")+(e?"Flip":"")+(r?"Full":""),i=["function ",n,"(",w.join(),"){","var ",u,"=2*",a,";"],l="for(var i="+c+","+p+"="+u+"*"+c+";i<"+h+";++i,"+p+"+="+u+"){var x0="+f+"["+o+"+"+p+"],x1="+f+"["+o+"+"+p+"+"+a+"],xi="+d+"[i];",A="for(var j="+g+","+b+"="+u+"*"+g+";j<"+v+";++j,"+b+"+="+u+"){var y0="+m+"["+o+"+"+b+"],"+(r?"y1="+m+"["+o+"+"+b+"+"+a+"],":"")+"yi="+y+"[j];";return t?i.push(l,_,":",A):i.push(A,_,":",l),r?i.push("if(y1<x0||x1<y0)continue;"):e?i.push("if(y0<=x0||x1<y0)continue;"):i.push("if(y0<x0||x1<y0)continue;"),i.push("for(var k="+o+"+1;k<"+a+";++k){var r0="+f+"[k+"+p+"],r1="+f+"[k+"+a+"+"+p+"],b0="+m+"[k+"+b+"],b1="+m+"[k+"+a+"+"+b+"];if(r1<b0||b1<r0)continue "+_+";}var "+x+"="+s+"("),e?i.push("yi,xi"):i.push("xi,yi"),i.push(");if("+x+"!==void 0)return "+x+";}}}"),{name:n,code:i.join("")}}function i(t){function e(e,r){var a=n(e,r,t);i.push(a.code),o.push("return "+a.name+"("+w.join()+");")}var r="bruteForce"+(t?"Full":"Partial"),i=[],a=w.slice();t||a.splice(3,0,l);var o=["function "+r+"("+a.join()+"){"];o.push("if("+h+"-"+c+">"+v+"-"+g+"){"),t?(e(!0,!1),o.push("}else{"),e(!1,!1)):(o.push("if("+l+"){"),e(!0,!0),o.push("}else{"),e(!0,!1),o.push("}}else{if("+l+"){"),e(!1,!0),o.push("}else{"),e(!1,!1),o.push("}")),o.push("}}return "+r);var s=i.join("")+o.join(""),u=new Function(s);return u()}var a="d",o="ax",s="vv",l="fp",u="es",c="rs",h="re",f="rb",d="ri",p="rp",g="bs",v="be",m="bb",y="bi",b="bp",x="rv",_="Q",w=[a,o,s,c,h,f,d,g,v,m,y];r.partial=i(!1),r.full=i(!0)},{}],265:[function(t,e,r){"use strict";function n(t,e){var r=8*u.log2(e+1)*(t+1)|0,n=u.nextPow2(M*r);L.length<n&&(l.free(L),L=l.mallocInt32(n));var i=u.nextPow2(T*r);i>S&&(l.free(S),S=l.mallocDouble(i))}function i(t,e,r,n,i,a,o,s,l){var u=M*t;L[u]=e,L[u+1]=r,L[u+2]=n,L[u+3]=i,L[u+4]=a,L[u+5]=o;var c=T*t;S[c]=s,S[c+1]=l}function a(t,e,r,n,i,a,o,s,l,u,c){var h=2*t,f=l*h,d=u[f+e];t:for(var p=i,g=i*h;a>p;++p,g+=h){var v=o[g+e],m=o[g+e+t];if(!(v>d||d>m||n&&d===v)){for(var y=s[p],b=e+1;t>b;++b){var v=o[g+b],m=o[g+b+t],x=u[f+b],_=u[f+b+t];if(x>m||v>_)continue t}var w;if(w=n?r(c,y):r(y,c),void 0!==w)return w}}}function o(t,e,r,n,i,a,o,s,l,u){var c=2*t,h=s*c,f=l[h+e];t:for(var d=n,p=n*c;i>d;++d,p+=c){var g=o[d];if(g!==u){var v=a[p+e],m=a[p+e+t];if(!(v>f||f>m)){for(var y=e+1;t>y;++y){var v=a[p+y],m=a[p+y+t],b=l[h+y],x=l[h+y+t];if(b>m||v>x)continue t}var _=r(g,u);if(void 0!==_)return _}}}}function s(t,e,r,s,l,u,c,g,E){n(t,s+c);var C,P=0,z=2*t;for(i(P++,0,0,s,0,c,r?16:0,-(1/0),1/0),r||i(P++,0,0,c,0,s,1,-(1/0),1/0);P>0;){P-=1;var R=P*M,O=L[R],I=L[R+1],j=L[R+2],N=L[R+3],F=L[R+4],B=L[R+5],D=P*T,U=S[D],V=S[D+1],q=1&B,H=!!(16&B),G=l,Y=u,X=g,W=E;if(q&&(G=g,Y=E,X=l,W=u),!(2&B&&(j=_(t,O,I,j,G,Y,V),I>=j)||4&B&&(I=w(t,O,I,j,G,Y,U),I>=j))){var Z=j-I,$=F-N;if(H){if(y>t*Z*(Z+$)){if(C=d.scanComplete(t,O,e,I,j,G,Y,N,F,X,W),void 0!==C)return C;continue}}else{if(t*Math.min(Z,$)<v){if(C=h(t,O,e,q,I,j,G,Y,N,F,X,W),void 0!==C)return C;continue}if(m>t*Z*$){if(C=d.scanBipartite(t,O,e,q,I,j,G,Y,N,F,X,W),void 0!==C)return C;continue}}var K=b(t,O,I,j,G,Y,U,V);if(K>I)if(v>t*(K-I)){if(C=f(t,O+1,e,I,K,G,Y,N,F,X,W),void 0!==C)return C}else if(O===t-2){if(C=q?d.sweepBipartite(t,e,N,F,X,W,I,K,G,Y):d.sweepBipartite(t,e,I,K,G,Y,N,F,X,W),void 0!==C)return C}else i(P++,O+1,I,K,N,F,q,-(1/0),1/0),i(P++,O+1,N,F,I,K,1^q,-(1/0),1/0);if(j>K){var Q=p(t,O,N,F,X,W),J=X[z*Q+O],tt=x(t,O,Q,F,X,W,J);if(F>tt&&i(P++,O,K,j,tt,F,(4|q)+(H?16:0),J,V),Q>N&&i(P++,O,K,j,N,Q,(2|q)+(H?16:0),U,J),Q+1===tt){if(C=H?o(t,O,e,K,j,G,Y,Q,X,W[Q]):a(t,O,e,q,K,j,G,Y,Q,X,W[Q]),void 0!==C)return C}else if(tt>Q){var et;if(H){if(et=A(t,O,K,j,G,Y,J),et>K){var rt=x(t,O,K,et,G,Y,J);if(O===t-2){if(rt>K&&(C=d.sweepComplete(t,e,K,rt,G,Y,Q,tt,X,W),void 0!==C))return C;if(et>rt&&(C=d.sweepBipartite(t,e,rt,et,G,Y,Q,tt,X,W),void 0!==C))return C}else rt>K&&i(P++,O+1,K,rt,Q,tt,16,-(1/0),1/0),et>rt&&(i(P++,O+1,rt,et,Q,tt,0,-(1/0),1/0),i(P++,O+1,Q,tt,rt,et,1,-(1/0),1/0))}}else et=q?k(t,O,K,j,G,Y,J):A(t,O,K,j,G,Y,J),et>K&&(O===t-2?C=q?d.sweepBipartite(t,e,Q,tt,X,W,K,et,G,Y):d.sweepBipartite(t,e,K,et,G,Y,Q,tt,X,W):(i(P++,O+1,K,et,Q,tt,q,-(1/0),1/0),i(P++,O+1,Q,tt,K,et,1^q,-(1/0),1/0)))}}}}}e.exports=s;var l=t("typedarray-pool"),u=t("bit-twiddle"),c=t("./brute"),h=c.partial,f=c.full,d=t("./sweep"),p=t("./median"),g=t("./partition"),v=128,m=1<<22,y=1<<22,b=g("!(lo>=p0)&&!(p1>=hi)",["p0","p1"]),x=g("lo===p0",["p0"]),_=g("lo<p0",["p0"]),w=g("hi<=p0",["p0"]),A=g("lo<=p0&&p0<=hi",["p0"]),k=g("lo<p0&&p0<=hi",["p0"]),M=6,T=2,E=1024,L=l.mallocInt32(E),S=l.mallocDouble(E)},{"./brute":264,"./median":266,"./partition":267,"./sweep":269,"bit-twiddle":49,"typedarray-pool":233}],266:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){for(var o=2*t,s=o*(r+1)+e,l=r+1;n>l;++l,s+=o)for(var u=i[s],c=l,h=o*(l-1);c>r&&i[h+e]>u;--c,h-=o){for(var f=h,d=h+o,p=0;o>p;++p,++f,++d){var g=i[f];i[f]=i[d],i[d]=g}var v=a[c];a[c]=a[c-1],a[c-1]=v}}function i(t,e,r,i,a,l){if(r+1>=i)return r;for(var u=r,c=i,h=i+r>>>1,f=2*t,d=h,p=a[f*h+e];c>u;){if(s>c-u){n(t,e,u,c,a,l),p=a[f*h+e];break}var g=c-u,v=Math.random()*g+u|0,m=a[f*v+e],y=Math.random()*g+u|0,b=a[f*y+e],x=Math.random()*g+u|0,_=a[f*x+e];b>=m?_>=b?(d=y,p=b):m>=_?(d=v,p=m):(d=x,p=_):b>=_?(d=y,p=b):_>=m?(d=v,p=m):(d=x,p=_);for(var w=f*(c-1),A=f*d,k=0;f>k;++k,++w,++A){var M=a[w];a[w]=a[A],a[A]=M}var T=l[c-1];l[c-1]=l[d],l[d]=T,d=o(t,e,u,c-1,a,l,p);for(var w=f*(c-1),A=f*d,k=0;f>k;++k,++w,++A){var M=a[w];a[w]=a[A],a[A]=M}var T=l[c-1];if(l[c-1]=l[d],l[d]=T,d>h){for(c=d-1;c>u&&a[f*(c-1)+e]===p;)c-=1;c+=1}else{if(!(h>d))break;for(u=d+1;c>u&&a[f*u+e]===p;)u+=1}}return o(t,e,r,h,a,l,a[f*h+e])}e.exports=i;var a=t("./partition"),o=a("lo<p0",["p0"]),s=8},{"./partition":267}],267:[function(t,e,r){"use strict";function n(t,e){var r="abcdef".split("").concat(e),n=[];return t.indexOf("lo")>=0&&n.push("lo=e[k+n]"),t.indexOf("hi")>=0&&n.push("hi=e[k+o]"),r.push(i.replace("_",n.join()).replace("$",t)),Function.apply(void 0,r)}e.exports=n;var i="for(var j=2*a,k=j*c,l=k,m=c,n=b,o=a+b,p=c;d>p;++p,k+=j){var _;if($)if(m===p)m+=1,l+=j;else{for(var s=0;j>s;++s){var t=e[k+s];e[k+s]=e[l],e[l++]=t}var u=f[p];f[p]=f[m],f[m++]=u}}return m"},{}],268:[function(t,e,r){"use strict";function n(t,e){4*f>=e?i(0,e-1,t):h(0,e-1,t)}function i(t,e,r){for(var n=2*(t+1),i=t+1;e>=i;++i){for(var a=r[n++],o=r[n++],s=i,l=n-2;s-- >t;){var u=r[l-2],c=r[l-1];if(a>u)break;if(u===a&&o>c)break;r[l]=u,r[l+1]=c,l-=2}r[l]=a,r[l+1]=o}}function a(t,e,r){t*=2,e*=2;var n=r[t],i=r[t+1];r[t]=r[e],r[t+1]=r[e+1],r[e]=n,r[e+1]=i}function o(t,e,r){t*=2,e*=2,r[t]=r[e],r[t+1]=r[e+1]}function s(t,e,r,n){t*=2,e*=2,r*=2;var i=n[t],a=n[t+1];n[t]=n[e],n[t+1]=n[e+1],n[e]=n[r],n[e+1]=n[r+1],n[r]=i,n[r+1]=a}function l(t,e,r,n,i){t*=2,e*=2,i[t]=i[e],i[e]=r,i[t+1]=i[e+1],i[e+1]=n}function u(t,e,r){t*=2,e*=2;var n=r[t],i=r[e];return i>n?!1:n===i?r[t+1]>r[e+1]:!0}function c(t,e,r,n){t*=2;var i=n[t];return e>i?!0:i===e?n[t+1]<r:!1}function h(t,e,r){var n=(e-t+1)/6|0,d=t+n,p=e-n,g=t+e>>1,v=g-n,m=g+n,y=d,b=v,x=g,_=m,w=p,A=t+1,k=e-1,M=0;u(y,b,r)&&(M=y,y=b,b=M),u(_,w,r)&&(M=_,_=w,w=M),u(y,x,r)&&(M=y,y=x,x=M),u(b,x,r)&&(M=b,b=x,x=M),u(y,_,r)&&(M=y,y=_,_=M),u(x,_,r)&&(M=x,x=_,_=M),u(b,w,r)&&(M=b,b=w,w=M),u(b,x,r)&&(M=b,b=x,x=M),u(_,w,r)&&(M=_,_=w,w=M);for(var T=r[2*b],E=r[2*b+1],L=r[2*_],S=r[2*_+1],C=2*y,P=2*x,z=2*w,R=2*d,O=2*g,I=2*p,j=0;2>j;++j){var N=r[C+j],F=r[P+j],B=r[z+j];r[R+j]=N,r[O+j]=F,r[I+j]=B}o(v,t,r),o(m,e,r);for(var D=A;k>=D;++D)if(c(D,T,E,r))D!==A&&a(D,A,r),++A;else if(!c(D,L,S,r))for(;;){if(c(k,L,S,r)){c(k,T,E,r)?(s(D,A,k,r),++A,--k):(a(D,k,r),--k);break}if(--k<D)break}l(t,A-1,T,E,r),l(e,k+1,L,S,r),f>=A-2-t?i(t,A-2,r):h(t,A-2,r),f>=e-(k+2)?i(k+2,e,r):h(k+2,e,r),f>=k-A?i(A,k,r):h(A,k,r)}e.exports=n;var f=32},{}],269:[function(t,e,r){"use strict";function n(t){var e=h.nextPow2(t);g.length<e&&(c.free(g),g=c.mallocInt32(e)),v.length<e&&(c.free(v),v=c.mallocInt32(e)),m.length<e&&(c.free(m),m=c.mallocInt32(e)),y.length<e&&(c.free(y),y=c.mallocInt32(e)),b.length<e&&(c.free(b),b=c.mallocInt32(e)),x.length<e&&(c.free(x),x=c.mallocInt32(e));var r=8*e;_.length<r&&(c.free(_),_=c.mallocDouble(r))}function i(t,e,r,n){var i=e[n],a=t[r-1];t[i]=a,e[a]=i}function a(t,e,r,n){t[r]=n,e[n]=r}function o(t,e,r,n,o,s,l,u,c,h){for(var p=0,b=2*t,x=t-1,w=b-1,A=r;n>A;++A){var k=s[A],M=b*A;_[p++]=o[M+x],_[p++]=-(k+1),_[p++]=o[M+w],_[p++]=k}for(var A=l;u>A;++A){var k=h[A]+d,T=b*A;_[p++]=c[T+x],_[p++]=-k,_[p++]=c[T+w],_[p++]=k}var E=p>>>1;f(_,E);for(var L=0,S=0,A=0;E>A;++A){var C=0|_[2*A+1];if(C>=d)C=C-d|0,i(m,y,S--,C);else if(C>=0)i(g,v,L--,C);else if(-d>=C){C=-C-d|0;for(var P=0;L>P;++P){var z=e(g[P],C);if(void 0!==z)return z}a(m,y,S++,C)}else{C=-C-1|0;for(var P=0;S>P;++P){var z=e(C,m[P]);if(void 0!==z)return z}a(g,v,L++,C)}}}function s(t,e,r,n,o,s,l,u,c,h){for(var d=0,p=2*t,w=t-1,A=p-1,k=r;n>k;++k){var M=s[k]+1<<1,T=p*k;_[d++]=o[T+w],_[d++]=-M,_[d++]=o[T+A],_[d++]=M}for(var k=l;u>k;++k){var M=h[k]+1<<1,E=p*k;_[d++]=c[E+w],_[d++]=1|-M,_[d++]=c[E+A],_[d++]=1|M}var L=d>>>1;f(_,L);for(var S=0,C=0,P=0,k=0;L>k;++k){var z=0|_[2*k+1],R=1&z;if(L-1>k&&z>>1===_[2*k+3]>>1&&(R=2,k+=1),0>z){for(var O=-(z>>1)-1,I=0;P>I;++I){var j=e(b[I],O);if(void 0!==j)return j}if(0!==R)for(var I=0;S>I;++I){var j=e(g[I],O);if(void 0!==j)return j}if(1!==R)for(var I=0;C>I;++I){var j=e(m[I],O);if(void 0!==j)return j}0===R?a(g,v,S++,O):1===R?a(m,y,C++,O):2===R&&a(b,x,P++,O)}else{var O=(z>>1)-1;0===R?i(g,v,S--,O):1===R?i(m,y,C--,O):2===R&&i(b,x,P--,O)}}}function l(t,e,r,n,o,s,l,u,c,h,p,m){var y=0,b=2*t,x=e,w=e+t,A=1,k=1;n?k=d:A=d;for(var M=o;s>M;++M){var T=M+A,E=b*M;_[y++]=l[E+x],_[y++]=-T,_[y++]=l[E+w],_[y++]=T}for(var M=c;h>M;++M){var T=M+k,L=b*M;_[y++]=p[L+x],_[y++]=-T}var S=y>>>1;f(_,S);for(var C=0,M=0;S>M;++M){var P=0|_[2*M+1];if(0>P){var T=-P,z=!1;if(T>=d?(z=!n,T-=d):(z=!!n,T-=1),z)a(g,v,C++,T);else{var R=m[T],O=b*T,I=p[O+e+1],j=p[O+e+1+t];t:for(var N=0;C>N;++N){var F=g[N],B=b*F;if(!(j<l[B+e+1]||l[B+e+1+t]<I)){for(var D=e+2;t>D;++D)if(p[O+D+t]<l[B+D]||l[B+D+t]<p[O+D])continue t;var U,V=u[F];if(U=n?r(R,V):r(V,R),void 0!==U)return U}}}}else i(g,v,C--,P-A)}}function u(t,e,r,n,i,a,o,s,l,u,c){for(var h=0,p=2*t,v=e,m=e+t,y=n;i>y;++y){var b=y+d,x=p*y;_[h++]=a[x+v],_[h++]=-b,_[h++]=a[x+m],_[h++]=b}for(var y=s;l>y;++y){var b=y+1,w=p*y;_[h++]=u[w+v],_[h++]=-b}var A=h>>>1;f(_,A);for(var k=0,y=0;A>y;++y){var M=0|_[2*y+1];if(0>M){var b=-M;if(b>=d)g[k++]=b-d;else{b-=1;var T=c[b],E=p*b,L=u[E+e+1],S=u[E+e+1+t];t:for(var C=0;k>C;++C){var P=g[C],z=o[P];if(z===T)break;var R=p*P;if(!(S<a[R+e+1]||a[R+e+1+t]<L)){for(var O=e+2;t>O;++O)if(u[E+O+t]<a[R+O]||a[R+O+t]<u[E+O])continue t;var I=r(z,T);if(void 0!==I)return I}}}}else{for(var b=M-d,C=k-1;C>=0;--C)if(g[C]===b){for(var O=C+1;k>O;++O)g[O-1]=g[O];break}--k}}}e.exports={init:n,sweepBipartite:o,sweepComplete:s,scanBipartite:l,scanComplete:u};var c=t("typedarray-pool"),h=t("bit-twiddle"),f=t("./sort"),d=1<<28,p=1024,g=c.mallocInt32(p),v=c.mallocInt32(p),m=c.mallocInt32(p),y=c.mallocInt32(p),b=c.mallocInt32(p),x=c.mallocInt32(p),_=c.mallocDouble(8*p)},{"./sort":268,"bit-twiddle":49,"typedarray-pool":233}],270:[function(t,e,r){(function(t){function r(t,e){return d[0]=t,d[1]=e,f[0]}function n(t){return f[0]=t,d[0]}function i(t){return f[0]=t,d[1]}function a(t,e){return d[1]=t,d[0]=e,f[0]}function o(t){return f[0]=t,d[1]}function s(t){return f[0]=t,d[0]}function l(t,e){return p.writeUInt32LE(t,0,!0),p.writeUInt32LE(e,4,!0),p.readDoubleLE(0,!0)}function u(t){return p.writeDoubleLE(t,0,!0),p.readUInt32LE(0,!0)}function c(t){return p.writeDoubleLE(t,0,!0),p.readUInt32LE(4,!0)}var h=!1;if("undefined"!=typeof Float64Array){var f=new Float64Array(1),d=new Uint32Array(f.buffer);f[0]=1,h=!0,1072693248===d[1]?(e.exports=function(t){return f[0]=t,[d[0],d[1]]},e.exports.pack=r,e.exports.lo=n,e.exports.hi=i):1072693248===d[0]?(e.exports=function(t){return f[0]=t,[d[1],d[0]]},e.exports.pack=a,e.exports.lo=o,e.exports.hi=s):h=!1}if(!h){var p=new t(8);e.exports=function(t){return p.writeDoubleLE(t,0,!0),[p.readUInt32LE(0,!0),p.readUInt32LE(4,!0)]},e.exports.pack=l,e.exports.lo=u,e.exports.hi=c}e.exports.sign=function(t){return e.exports.hi(t)>>>31},e.exports.exponent=function(t){var r=e.exports.hi(t);return(r<<1>>>21)-1023},e.exports.fraction=function(t){var r=e.exports.lo(t),n=e.exports.hi(t),i=1048575&n;return 2146435072&n&&(i+=1<<20),[r,i]},e.exports.denormalized=function(t){var r=e.exports.hi(t);return!(2146435072&r)}}).call(this,t("buffer").Buffer)},{buffer:50}],271:[function(t,e,r){"use strict";function n(t,e){if(isNaN(t)||isNaN(e))return NaN;if(t===e)return t;if(0===t)return 0>e?-a:a;var r=i.hi(t),n=i.lo(t);return e>t==t>0?n===o?(r+=1,n=0):n+=1:0===n?(n=o,r-=1):n-=1,i.pack(n,r)}var i=t("double-bits"),a=Math.pow(2,-1074),o=-1>>>0;e.exports=n},{"double-bits":270}],272:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),a=0;r>a;++a)n[a]=i(t[a],e[a]);return n}var i=t("big-rat/add");e.exports=n},{"big-rat/add":246}],273:[function(t,e,r){"use strict";function n(t){for(var e=new Array(t.length),r=0;r<t.length;++r)e[r]=i(t[r]);return e}e.exports=n;var i=t("big-rat")},{"big-rat":249}],274:[function(t,e,r){"use strict";function n(t,e){for(var r=i(e),n=t.length,o=new Array(n),s=0;n>s;++s)o[s]=a(t[s],r);return o}var i=t("big-rat"),a=t("big-rat/mul");e.exports=n},{"big-rat":249,"big-rat/mul":258}],275:[function(t,e,r){"use strict";function n(t,e){for(var r=t.length,n=new Array(r),a=0;r>a;++a)n[a]=i(t[a],e[a]);return n}var i=t("big-rat/sub");e.exports=n},{"big-rat/sub":261}],276:[function(t,e,r){"use strict";function n(t,e,r,n){for(var i=0;2>i;++i){var a=t[i],o=e[i],s=Math.min(a,o),l=Math.max(a,o),u=r[i],c=n[i],h=Math.min(u,c),f=Math.max(u,c);if(s>f||h>l)return!1}return!0}function i(t,e,r,i){var o=a(t,r,i),s=a(e,r,i);if(o>0&&s>0||0>o&&0>s)return!1;var l=a(r,t,e),u=a(i,t,e);return l>0&&u>0||0>l&&0>u?!1:0===o&&0===s&&0===l&&0===u?n(t,e,r,i):!0}e.exports=i;var a=t("robust-orientation")[3]},{"robust-orientation":214}],277:[function(t,e,r){arguments[4][193][0].apply(r,arguments)},{dup:193}],278:[function(t,e,r){"use strict";function n(t,e){for(var r=i(t,e.length),n=new Array(e.length),a=new Array(e.length),o=[],s=0;s<e.length;++s){var l=r[s].length;a[s]=l,n[s]=!0,1>=l&&o.push(s)}for(;o.length>0;){var u=o.pop();n[u]=!1;for(var c=r[u],s=0;s<c.length;++s){var h=c[s];0===--a[h]&&o.push(h)}}for(var f=new Array(e.length),d=[],s=0;s<e.length;++s)if(n[s]){var u=d.length;f[s]=u,d.push(e[s])}else f[s]=-1;for(var p=[],s=0;s<t.length;++s){
+var g=t[s];n[g[0]]&&n[g[1]]&&p.push([f[g[0]],f[g[1]]])}return[p,d]}e.exports=n;var i=t("edges-to-adjacency-list")},{"edges-to-adjacency-list":279}],279:[function(t,e,r){"use strict";function n(t,e){var r=t.length;if("number"!=typeof e){e=0;for(var n=0;r>n;++n){var a=t[n];e=Math.max(e,a[0],a[1])}e=(0|e)+1}e=0|e;for(var o=new Array(e),n=0;e>n;++n)o[n]=[];for(var n=0;r>n;++n){var a=t[n];o[a[0]].push(a[1]),o[a[1]].push(a[0])}for(var s=0;e>s;++s)i(o[s],function(t,e){return t-e});return o}e.exports=n;var i=t("uniq")},{uniq:234}],280:[function(t,e,r){"use strict";function n(t,e){function r(t,e){var r=u[e][t[e]];r.splice(r.indexOf(t),1)}function n(t,n,a){for(var o,s,l,c=0;2>c;++c)if(u[c][n].length>0){o=u[c][n][0],l=c;break}s=o[1^l];for(var h=0;2>h;++h)for(var f=u[h][n],d=0;d<f.length;++d){var p=f[d],g=p[1^h],v=i(e[t],e[n],e[s],e[g]);v>0&&(o=p,s=g,l=h)}return a?s:(o&&r(o,l),s)}function a(t,a){var o=u[a][t][0],s=[t];r(o,a);for(var l=o[1^a];;){for(;l!==t;)s.push(l),l=n(s[s.length-2],l,!1);if(u[0][t].length+u[1][t].length===0)break;var c=s[s.length-1],h=t,f=s[1],d=n(c,h,!0);if(i(e[c],e[h],e[f],e[d])<0)break;s.push(t),l=n(c,h)}return s}function o(t,e){return e[1]===e[e.length-1]}for(var s=0|e.length,l=t.length,u=[new Array(s),new Array(s)],c=0;s>c;++c)u[0][c]=[],u[1][c]=[];for(var c=0;l>c;++c){var h=t[c];u[0][h[0]].push(h),u[1][h[1]].push(h)}for(var f=[],c=0;s>c;++c)u[0][c].length+u[1][c].length===0&&f.push([c]);for(var c=0;s>c;++c)for(var d=0;2>d;++d){for(var p=[];u[d][c].length>0;){var g=(u[0][c].length,a(c,d));o(p,g)?p.push.apply(p,g):(p.length>0&&f.push(p),p=g)}p.length>0&&f.push(p)}return f}e.exports=n;var i=t("compare-angle")},{"compare-angle":281}],281:[function(t,e,r){"use strict";function n(t,e,r){var n=s(t[0],-e[0]),i=s(t[1],-e[1]),a=s(r[0],-e[0]),o=s(r[1],-e[1]),c=u(l(n,a),l(i,o));return c[c.length-1]>=0}function i(t,e,r,i){var s=a(e,r,i);if(0===s){var l=o(a(t,e,r)),u=o(a(t,e,i));if(l===u){if(0===l){var c=n(t,e,r),h=n(t,e,i);return c===h?0:c?1:-1}return 0}return 0===u?l>0?-1:n(t,e,i)?-1:1:0===l?u>0?1:n(t,e,r)?1:-1:o(u-l)}var f=a(t,e,r);if(f>0)return s>0&&a(t,e,i)>0?1:-1;if(0>f)return s>0||a(t,e,i)>0?1:-1;var d=a(t,e,i);return d>0?1:n(t,e,r)?1:-1}e.exports=i;var a=t("robust-orientation"),o=t("signum"),s=t("two-sum"),l=t("robust-product"),u=t("robust-sum")},{"robust-orientation":214,"robust-product":282,"robust-sum":217,signum:283,"two-sum":232}],282:[function(t,e,r){"use strict";function n(t,e){if(1===t.length)return a(e,t[0]);if(1===e.length)return a(t,e[0]);if(0===t.length||0===e.length)return[0];var r=[0];if(t.length<e.length)for(var n=0;n<t.length;++n)r=i(r,a(e,t[n]));else for(var n=0;n<e.length;++n)r=i(r,a(t,e[n]));return r}var i=t("robust-sum"),a=t("robust-scale");e.exports=n},{"robust-scale":215,"robust-sum":217}],283:[function(t,e,r){"use strict";e.exports=function(t){return 0>t?-1:t>0?1:0}},{}],284:[function(t,e,r){arguments[4][20][0].apply(r,arguments)},{dup:20}],285:[function(t,e,r){"use strict";function n(t,e,r,n,i){this.mid=t,this.left=e,this.right=r,this.leftPoints=n,this.rightPoints=i,this.count=(e?e.count:0)+(r?r.count:0)+n.length}function i(t,e){t.mid=e.mid,t.left=e.left,t.right=e.right,t.leftPoints=e.leftPoints,t.rightPoints=e.rightPoints,t.count=e.count}function a(t,e){var r=p(e);t.mid=r.mid,t.left=r.left,t.right=r.right,t.leftPoints=r.leftPoints,t.rightPoints=r.rightPoints,t.count=r.count}function o(t,e){var r=t.intervals([]);r.push(e),a(t,r)}function s(t,e){var r=t.intervals([]),n=r.indexOf(e);return 0>n?y:(r.splice(n,1),a(t,r),b)}function l(t,e,r){for(var n=0;n<t.length&&t[n][0]<=e;++n){var i=r(t[n]);if(i)return i}}function u(t,e,r){for(var n=t.length-1;n>=0&&t[n][1]>=e;--n){var i=r(t[n]);if(i)return i}}function c(t,e){for(var r=0;r<t.length;++r){var n=e(t[r]);if(n)return n}}function h(t,e){return t-e}function f(t,e){var r=t[0]-e[0];return r?r:t[1]-e[1]}function d(t,e){var r=t[1]-e[1];return r?r:t[0]-e[0]}function p(t){if(0===t.length)return null;for(var e=[],r=0;r<t.length;++r)e.push(t[r][0],t[r][1]);e.sort(h);for(var i=e[e.length>>1],a=[],o=[],s=[],r=0;r<t.length;++r){var l=t[r];l[1]<i?a.push(l):i<l[0]?o.push(l):s.push(l)}var u=s,c=s.slice();return u.sort(f),c.sort(d),new n(i,p(a),p(o),u,c)}function g(t){this.root=t}function v(t){return new g(t&&0!==t.length?p(t):null)}var m=t("binary-search-bounds"),y=0,b=1,x=2;e.exports=v;var _=n.prototype;_.intervals=function(t){return t.push.apply(t,this.leftPoints),this.left&&this.left.intervals(t),this.right&&this.right.intervals(t),t},_.insert=function(t){var e=this.count-this.leftPoints.length;if(this.count+=1,t[1]<this.mid)this.left?4*(this.left.count+1)>3*(e+1)?o(this,t):this.left.insert(t):this.left=p([t]);else if(t[0]>this.mid)this.right?4*(this.right.count+1)>3*(e+1)?o(this,t):this.right.insert(t):this.right=p([t]);else{var r=m.ge(this.leftPoints,t,f),n=m.ge(this.rightPoints,t,d);this.leftPoints.splice(r,0,t),this.rightPoints.splice(n,0,t)}},_.remove=function(t){var e=this.count-this.leftPoints;if(t[1]<this.mid){if(!this.left)return y;var r=this.right?this.right.count:0;if(4*r>3*(e-1))return s(this,t);var n=this.left.remove(t);return n===x?(this.left=null,this.count-=1,b):(n===b&&(this.count-=1),n)}if(t[0]>this.mid){if(!this.right)return y;var a=this.left?this.left.count:0;if(4*a>3*(e-1))return s(this,t);var n=this.right.remove(t);return n===x?(this.right=null,this.count-=1,b):(n===b&&(this.count-=1),n)}if(1===this.count)return this.leftPoints[0]===t?x:y;if(1===this.leftPoints.length&&this.leftPoints[0]===t){if(this.left&&this.right){for(var o=this,l=this.left;l.right;)o=l,l=l.right;if(o===this)l.right=this.right;else{var u=this.left,n=this.right;o.count-=l.count,o.right=l.left,l.left=u,l.right=n}i(this,l),this.count=(this.left?this.left.count:0)+(this.right?this.right.count:0)+this.leftPoints.length}else this.left?i(this,this.left):i(this,this.right);return b}for(var u=m.ge(this.leftPoints,t,f);u<this.leftPoints.length&&this.leftPoints[u][0]===t[0];++u)if(this.leftPoints[u]===t){this.count-=1,this.leftPoints.splice(u,1);for(var n=m.ge(this.rightPoints,t,d);n<this.rightPoints.length&&this.rightPoints[n][1]===t[1];++n)if(this.rightPoints[n]===t)return this.rightPoints.splice(n,1),b}return y},_.queryPoint=function(t,e){if(t<this.mid){if(this.left){var r=this.left.queryPoint(t,e);if(r)return r}return l(this.leftPoints,t,e)}if(t>this.mid){if(this.right){var r=this.right.queryPoint(t,e);if(r)return r}return u(this.rightPoints,t,e)}return c(this.leftPoints,e)},_.queryInterval=function(t,e,r){if(t<this.mid&&this.left){var n=this.left.queryInterval(t,e,r);if(n)return n}if(e>this.mid&&this.right){var n=this.right.queryInterval(t,e,r);if(n)return n}return e<this.mid?l(this.leftPoints,e,r):t>this.mid?u(this.rightPoints,t,r):c(this.leftPoints,r)};var w=g.prototype;w.insert=function(t){this.root?this.root.insert(t):this.root=new n(t[0],null,null,[t],[t])},w.remove=function(t){if(this.root){var e=this.root.remove(t);return e===x&&(this.root=null),e!==y}return!1},w.queryPoint=function(t,e){return this.root?this.root.queryPoint(t,e):void 0},w.queryInterval=function(t,e,r){return e>=t&&this.root?this.root.queryInterval(t,e,r):void 0},Object.defineProperty(w,"count",{get:function(){return this.root?this.root.count:0}}),Object.defineProperty(w,"intervals",{get:function(){return this.root?this.root.intervals([]):[]}})},{"binary-search-bounds":284}],286:[function(t,e,r){"use strict";function n(t,e){var r,n;if(e[0][0]<e[1][0])r=e[0],n=e[1];else{if(!(e[0][0]>e[1][0])){var i=Math.min(t[0][1],t[1][1]),o=Math.max(t[0][1],t[1][1]),s=Math.min(e[0][1],e[1][1]),l=Math.max(e[0][1],e[1][1]);return s>o?o-s:i>l?i-l:o-l}r=e[1],n=e[0]}var u,c;t[0][1]<t[1][1]?(u=t[0],c=t[1]):(u=t[1],c=t[0]);var h=a(n,r,u);return h?h:(h=a(n,r,c),h?h:c-n)}function i(t,e){var r,i;if(e[0][0]<e[1][0])r=e[0],i=e[1];else{if(!(e[0][0]>e[1][0]))return n(e,t);r=e[1],i=e[0]}var o,s;if(t[0][0]<t[1][0])o=t[0],s=t[1];else{if(!(t[0][0]>t[1][0]))return-n(t,e);o=t[1],s=t[0]}var l=a(r,i,s),u=a(r,i,o);if(0>l){if(0>=u)return l}else if(l>0){if(u>=0)return l}else if(u)return u;if(l=a(s,o,i),u=a(s,o,r),0>l){if(0>=u)return l}else if(l>0){if(u>=0)return l}else if(u)return u;return i[0]-s[0]}e.exports=i;var a=t("robust-orientation")},{"robust-orientation":214}],287:[function(t,e,r){"use strict";function n(t,e,r,n,i,a){this._color=t,this.key=e,this.value=r,this.left=n,this.right=i,this._count=a}function i(t){return new n(t._color,t.key,t.value,t.left,t.right,t._count)}function a(t,e){return new n(t,e.key,e.value,e.left,e.right,e._count)}function o(t){t._count=1+(t.left?t.left._count:0)+(t.right?t.right._count:0)}function s(t,e){this._compare=t,this.root=e}function l(t,e){if(e.left){var r=l(t,e.left);if(r)return r}var r=t(e.key,e.value);return r?r:e.right?l(t,e.right):void 0}function u(t,e,r,n){var i=e(t,n.key);if(0>=i){if(n.left){var a=u(t,e,r,n.left);if(a)return a}var a=r(n.key,n.value);if(a)return a}return n.right?u(t,e,r,n.right):void 0}function c(t,e,r,n,i){var a,o=r(t,i.key),s=r(e,i.key);if(0>=o){if(i.left&&(a=c(t,e,r,n,i.left)))return a;if(s>0&&(a=n(i.key,i.value)))return a}return s>0&&i.right?c(t,e,r,n,i.right):void 0}function h(t,e){this.tree=t,this._stack=e}function f(t,e){t.key=e.key,t.value=e.value,t.left=e.left,t.right=e.right,t._color=e._color,t._count=e._count}function d(t){for(var e,r,n,s,l=t.length-1;l>=0;--l){if(e=t[l],0===l)return void(e._color=m);if(r=t[l-1],r.left===e){if(n=r.right,n.right&&n.right._color===v){if(n=r.right=i(n),s=n.right=i(n.right),r.right=n.left,n.left=r,n.right=s,n._color=r._color,e._color=m,r._color=m,s._color=m,o(r),o(n),l>1){var u=t[l-2];u.left===r?u.left=n:u.right=n}return void(t[l-1]=n)}if(n.left&&n.left._color===v){if(n=r.right=i(n),s=n.left=i(n.left),r.right=s.left,n.left=s.right,s.left=r,s.right=n,s._color=r._color,r._color=m,n._color=m,e._color=m,o(r),o(n),o(s),l>1){var u=t[l-2];u.left===r?u.left=s:u.right=s}return void(t[l-1]=s)}if(n._color===m){if(r._color===v)return r._color=m,void(r.right=a(v,n));r.right=a(v,n);continue}if(n=i(n),r.right=n.left,n.left=r,n._color=r._color,r._color=v,o(r),o(n),l>1){var u=t[l-2];u.left===r?u.left=n:u.right=n}t[l-1]=n,t[l]=r,l+1<t.length?t[l+1]=e:t.push(e),l+=2}else{if(n=r.left,n.left&&n.left._color===v){if(n=r.left=i(n),s=n.left=i(n.left),r.left=n.right,n.right=r,n.left=s,n._color=r._color,e._color=m,r._color=m,s._color=m,o(r),o(n),l>1){var u=t[l-2];u.right===r?u.right=n:u.left=n}return void(t[l-1]=n)}if(n.right&&n.right._color===v){if(n=r.left=i(n),s=n.right=i(n.right),r.left=s.right,n.right=s.left,s.right=r,s.left=n,s._color=r._color,r._color=m,n._color=m,e._color=m,o(r),o(n),o(s),l>1){var u=t[l-2];u.right===r?u.right=s:u.left=s}return void(t[l-1]=s)}if(n._color===m){if(r._color===v)return r._color=m,void(r.left=a(v,n));r.left=a(v,n);continue}if(n=i(n),r.left=n.right,n.right=r,n._color=r._color,r._color=v,o(r),o(n),l>1){var u=t[l-2];u.right===r?u.right=n:u.left=n}t[l-1]=n,t[l]=r,l+1<t.length?t[l+1]=e:t.push(e),l+=2}}}function p(t,e){return e>t?-1:t>e?1:0}function g(t){return new s(t||p,null)}e.exports=g;var v=0,m=1,y=s.prototype;Object.defineProperty(y,"keys",{get:function(){var t=[];return this.forEach(function(e,r){t.push(e)}),t}}),Object.defineProperty(y,"values",{get:function(){var t=[];return this.forEach(function(e,r){t.push(r)}),t}}),Object.defineProperty(y,"length",{get:function(){return this.root?this.root._count:0}}),y.insert=function(t,e){for(var r=this._compare,i=this.root,l=[],u=[];i;){var c=r(t,i.key);l.push(i),u.push(c),i=0>=c?i.left:i.right}l.push(new n(v,t,e,null,null,1));for(var h=l.length-2;h>=0;--h){var i=l[h];u[h]<=0?l[h]=new n(i._color,i.key,i.value,l[h+1],i.right,i._count+1):l[h]=new n(i._color,i.key,i.value,i.left,l[h+1],i._count+1)}for(var h=l.length-1;h>1;--h){var f=l[h-1],i=l[h];if(f._color===m||i._color===m)break;var d=l[h-2];if(d.left===f)if(f.left===i){var p=d.right;if(!p||p._color!==v){if(d._color=v,d.left=f.right,f._color=m,f.right=d,l[h-2]=f,l[h-1]=i,o(d),o(f),h>=3){var g=l[h-3];g.left===d?g.left=f:g.right=f}break}f._color=m,d.right=a(m,p),d._color=v,h-=1}else{var p=d.right;if(!p||p._color!==v){if(f.right=i.left,d._color=v,d.left=i.right,i._color=m,i.left=f,i.right=d,l[h-2]=i,l[h-1]=f,o(d),o(f),o(i),h>=3){var g=l[h-3];g.left===d?g.left=i:g.right=i}break}f._color=m,d.right=a(m,p),d._color=v,h-=1}else if(f.right===i){var p=d.left;if(!p||p._color!==v){if(d._color=v,d.right=f.left,f._color=m,f.left=d,l[h-2]=f,l[h-1]=i,o(d),o(f),h>=3){var g=l[h-3];g.right===d?g.right=f:g.left=f}break}f._color=m,d.left=a(m,p),d._color=v,h-=1}else{var p=d.left;if(!p||p._color!==v){if(f.left=i.right,d._color=v,d.right=i.left,i._color=m,i.right=f,i.left=d,l[h-2]=i,l[h-1]=f,o(d),o(f),o(i),h>=3){var g=l[h-3];g.right===d?g.right=i:g.left=i}break}f._color=m,d.left=a(m,p),d._color=v,h-=1}}return l[0]._color=m,new s(r,l[0])},y.forEach=function(t,e,r){if(this.root)switch(arguments.length){case 1:return l(t,this.root);case 2:return u(e,this._compare,t,this.root);case 3:if(this._compare(e,r)>=0)return;return c(e,r,this._compare,t,this.root)}},Object.defineProperty(y,"begin",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.left;return new h(this,t)}}),Object.defineProperty(y,"end",{get:function(){for(var t=[],e=this.root;e;)t.push(e),e=e.right;return new h(this,t)}}),y.at=function(t){if(0>t)return new h(this,[]);for(var e=this.root,r=[];;){if(r.push(e),e.left){if(t<e.left._count){e=e.left;continue}t-=e.left._count}if(!t)return new h(this,r);if(t-=1,!e.right)break;if(t>=e.right._count)break;e=e.right}return new h(this,[])},y.ge=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),0>=a&&(i=n.length),r=0>=a?r.left:r.right}return n.length=i,new h(this,n)},y.gt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),0>a&&(i=n.length),r=0>a?r.left:r.right}return n.length=i,new h(this,n)},y.lt=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>0&&(i=n.length),r=0>=a?r.left:r.right}return n.length=i,new h(this,n)},y.le=function(t){for(var e=this._compare,r=this.root,n=[],i=0;r;){var a=e(t,r.key);n.push(r),a>=0&&(i=n.length),r=0>a?r.left:r.right}return n.length=i,new h(this,n)},y.find=function(t){for(var e=this._compare,r=this.root,n=[];r;){var i=e(t,r.key);if(n.push(r),0===i)return new h(this,n);r=0>=i?r.left:r.right}return new h(this,[])},y.remove=function(t){var e=this.find(t);return e?e.remove():this},y.get=function(t){for(var e=this._compare,r=this.root;r;){var n=e(t,r.key);if(0===n)return r.value;r=0>=n?r.left:r.right}};var b=h.prototype;Object.defineProperty(b,"valid",{get:function(){return this._stack.length>0}}),Object.defineProperty(b,"node",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1]:null},enumerable:!0}),b.clone=function(){return new h(this.tree,this._stack.slice())},b.remove=function(){var t=this._stack;if(0===t.length)return this.tree;var e=new Array(t.length),r=t[t.length-1];e[e.length-1]=new n(r._color,r.key,r.value,r.left,r.right,r._count);for(var i=t.length-2;i>=0;--i){var r=t[i];r.left===t[i+1]?e[i]=new n(r._color,r.key,r.value,e[i+1],r.right,r._count):e[i]=new n(r._color,r.key,r.value,r.left,e[i+1],r._count)}if(r=e[e.length-1],r.left&&r.right){var a=e.length;for(r=r.left;r.right;)e.push(r),r=r.right;var o=e[a-1];e.push(new n(r._color,o.key,o.value,r.left,r.right,r._count)),e[a-1].key=r.key,e[a-1].value=r.value;for(var i=e.length-2;i>=a;--i)r=e[i],e[i]=new n(r._color,r.key,r.value,r.left,e[i+1],r._count);e[a-1].left=e[a]}if(r=e[e.length-1],r._color===v){var l=e[e.length-2];l.left===r?l.left=null:l.right===r&&(l.right=null),e.pop();for(var i=0;i<e.length;++i)e[i]._count--;return new s(this.tree._compare,e[0])}if(r.left||r.right){r.left?f(r,r.left):r.right&&f(r,r.right),r._color=m;for(var i=0;i<e.length-1;++i)e[i]._count--;return new s(this.tree._compare,e[0])}if(1===e.length)return new s(this.tree._compare,null);for(var i=0;i<e.length;++i)e[i]._count--;var u=e[e.length-2];return d(e),u.left===r?u.left=null:u.right=null,new s(this.tree._compare,e[0])},Object.defineProperty(b,"key",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1].key:void 0},enumerable:!0}),Object.defineProperty(b,"value",{get:function(){return this._stack.length>0?this._stack[this._stack.length-1].value:void 0},enumerable:!0}),Object.defineProperty(b,"index",{get:function(){var t=0,e=this._stack;if(0===e.length){var r=this.tree.root;return r?r._count:0}e[e.length-1].left&&(t=e[e.length-1].left._count);for(var n=e.length-2;n>=0;--n)e[n+1]===e[n].right&&(++t,e[n].left&&(t+=e[n].left._count));return t},enumerable:!0}),b.next=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.right)for(e=e.right;e;)t.push(e),e=e.left;else for(t.pop();t.length>0&&t[t.length-1].right===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(b,"hasNext",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].right)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].left===t[e])return!0;return!1}}),b.update=function(t){var e=this._stack;if(0===e.length)throw new Error("Can't update empty node!");var r=new Array(e.length),i=e[e.length-1];r[r.length-1]=new n(i._color,i.key,t,i.left,i.right,i._count);for(var a=e.length-2;a>=0;--a)i=e[a],i.left===e[a+1]?r[a]=new n(i._color,i.key,i.value,r[a+1],i.right,i._count):r[a]=new n(i._color,i.key,i.value,i.left,r[a+1],i._count);return new s(this.tree._compare,r[0])},b.prev=function(){var t=this._stack;if(0!==t.length){var e=t[t.length-1];if(e.left)for(e=e.left;e;)t.push(e),e=e.right;else for(t.pop();t.length>0&&t[t.length-1].left===e;)e=t[t.length-1],t.pop()}},Object.defineProperty(b,"hasPrev",{get:function(){var t=this._stack;if(0===t.length)return!1;if(t[t.length-1].left)return!0;for(var e=t.length-1;e>0;--e)if(t[e-1].right===t[e])return!0;return!1}})},{}],288:[function(t,e,r){"use strict";function n(t,e,r){this.slabs=t,this.coordinates=e,this.horizontal=r}function i(t,e){return t.y-e}function a(t,e){for(var r=null;t;){var n,i,o=t.key;o[0][0]<o[1][0]?(n=o[0],i=o[1]):(n=o[1],i=o[0]);var s=h(n,i,e);if(0>s)t=t.left;else if(s>0)if(e[0]!==o[1][0])r=t,t=t.right;else{var l=a(t.right,e);if(l)return l;t=t.left}else{if(e[0]!==o[1][0])return t;var l=a(t.right,e);if(l)return l;t=t.left}}return r}function o(t,e,r,n){this.y=t,this.index=e,this.start=r,this.closed=n}function s(t,e,r,n){this.x=t,this.segment=e,this.create=r,this.index=n}function l(t){for(var e=t.length,r=2*e,i=new Array(r),a=0;e>a;++a){var l=t[a],u=l[0][0]<l[1][0];i[2*a]=new s(l[0][0],l,u,a),i[2*a+1]=new s(l[1][0],l,!u,a)}i.sort(function(t,e){var r=t.x-e.x;return r?r:(r=t.create-e.create,r?r:Math.min(t.segment[0][1],t.segment[1][1])-Math.min(e.segment[0][1],e.segment[1][1]))});for(var h=c(f),d=[],p=[],g=[],a=0;r>a;){for(var v=i[a].x,m=[];r>a;){var y=i[a];if(y.x!==v)break;a+=1,y.segment[0][0]===y.x&&y.segment[1][0]===y.x?y.create&&(y.segment[0][1]<y.segment[1][1]?(m.push(new o(y.segment[0][1],y.index,!0,!0)),m.push(new o(y.segment[1][1],y.index,!1,!1))):(m.push(new o(y.segment[1][1],y.index,!0,!1)),m.push(new o(y.segment[0][1],y.index,!1,!0)))):h=y.create?h.insert(y.segment,y.index):h.remove(y.segment)}d.push(h.root),p.push(v),g.push(m)}return new n(d,p,g)}e.exports=l;var u=t("binary-search-bounds"),c=t("functional-red-black-tree"),h=t("robust-orientation"),f=t("./lib/order-segments"),d=n.prototype;d.castUp=function(t){var e=u.le(this.coordinates,t[0]);if(0>e)return-1;var r=(this.slabs[e],a(this.slabs[e],t)),n=-1;if(r&&(n=r.value),this.coordinates[e]===t[0]){var o=null;if(r&&(o=r.key),e>0){var s=a(this.slabs[e-1],t);s&&(o?f(s.key,o)>0&&(o=s.key,n=s.value):(n=s.value,o=s.key))}var l=this.horizontal[e];if(l.length>0){var c=u.ge(l,t[1],i);if(c<l.length){var d=l[c];if(t[1]===d.y){if(d.closed)return d.index;for(;c<l.length-1&&l[c+1].y===t[1];)if(c+=1,d=l[c],d.closed)return d.index;if(d.y===t[1]&&!d.start){if(c+=1,c>=l.length)return n;d=l[c]}}if(d.start)if(o){var p=h(o[0],o[1],[t[0],d.y]);o[0][0]>o[1][0]&&(p=-p),p>0&&(n=d.index)}else n=d.index;else d.y!==t[1]&&(n=d.index)}}}return n}},{"./lib/order-segments":286,"binary-search-bounds":284,"functional-red-black-tree":287,"robust-orientation":214}],289:[function(t,e,r){function n(){return!0}function i(t){return function(e,r){var i=t[e];return i?!!i.queryPoint(r,n):!1}}function a(t){for(var e={},r=0;r<t.length;++r){var n=t[r],a=n[0][0],o=n[0][1],s=n[1][1],l=[Math.min(o,s),Math.max(o,s)];a in e?e[a].push(l):e[a]=[l]}for(var u={},c=Object.keys(e),r=0;r<c.length;++r){var h=e[c[r]];u[c[r]]=d(h)}return i(u)}function o(t,e){return function(r){var n=p.le(e,r[0]);if(0>n)return 1;var i=t[n];if(!i){if(!(n>0&&e[n]===r[0]))return 1;i=t[n-1]}for(var a=1;i;){var o=i.key,s=h(r,o[0],o[1]);if(o[0][0]<o[1][0])if(0>s)i=i.left;else{if(!(s>0))return 0;a=-1,i=i.right}else if(s>0)i=i.left;else{if(!(0>s))return 0;a=1,i=i.right}}return a}}function s(t){return 1}function l(t){return function(e){return t(e[0],e[1])?0:1}}function u(t,e){return function(r){return t(r[0],r[1])?0:e(r)}}function c(t){for(var e=t.length,r=[],n=[],i=0;e>i;++i)for(var c=t[i],h=c.length,d=h-1,p=0;h>p;d=p++){var g=c[d],v=c[p];g[0]===v[0]?n.push([g,v]):r.push([g,v])}if(0===r.length)return 0===n.length?s:l(a(n));var m=f(r),y=o(m.slabs,m.coordinates);return 0===n.length?y:u(a(n),y)}e.exports=c;var h=t("robust-orientation")[3],f=t("slab-decomposition"),d=t("interval-tree-1d"),p=t("binary-search-bounds")},{"binary-search-bounds":284,"interval-tree-1d":285,"robust-orientation":214,"slab-decomposition":288}],290:[function(t,e,r){"use strict";function n(t,e){for(var r=new Array(t),n=0;t>n;++n)r[n]=e;return r}function i(t){for(var e=new Array(t),r=0;t>r;++r)e[r]=[];return e}function a(t,e){function r(t){for(var r=t.length,n=[0],i=0;r>i;++i){var a=e[t[i]],o=e[t[(i+1)%r]],s=u(-a[0],a[1]),l=u(-a[0],o[1]),h=u(o[0],a[1]),f=u(o[0],o[1]);n=c(n,c(c(s,l),c(h,f)))}return n[n.length-1]>0}function a(t){for(var e=t.length,r=0;e>r;++r)if(!O[t[r]])return!1;return!0}var d=f(t,e);t=d[0],e=d[1];for(var p=e.length,g=(t.length,o(t,e.length)),v=0;p>v;++v)if(g[v].length%2===1)throw new Error("planar-graph-to-polyline: graph must be manifold");var m=s(t,e);m=m.filter(r);for(var y=m.length,b=new Array(y),x=new Array(y),v=0;y>v;++v){b[v]=v;var _=new Array(y),w=m[v].map(function(t){return e[t]}),A=l([w]),k=0;t:for(var M=0;y>M;++M)if(_[M]=0,v!==M){for(var T=m[M],E=T.length,L=0;E>L;++L){var S=A(e[T[L]]);if(0!==S){0>S&&(_[M]=1,k+=1);continue t}}_[M]=1,k+=1}x[v]=[k,v,_]}x.sort(function(t,e){return e[0]-t[0]});for(var v=0;y>v;++v)for(var _=x[v],C=_[1],P=_[2],M=0;y>M;++M)P[M]&&(b[M]=C);for(var z=i(y),v=0;y>v;++v)z[v].push(b[v]),z[b[v]].push(v);for(var R={},O=n(p,!1),v=0;y>v;++v)for(var T=m[v],E=T.length,M=0;E>M;++M){var I=T[M],j=T[(M+1)%E],N=Math.min(I,j)+":"+Math.max(I,j);if(N in R){var F=R[N];z[F].push(v),z[v].push(F),O[I]=O[j]=!0}else R[N]=v}for(var B=[],D=n(y,-1),v=0;y>v;++v)b[v]!==v||a(m[v])?D[v]=-1:(B.push(v),D[v]=0);for(var d=[];B.length>0;){var U=B.pop(),V=z[U];h(V,function(t,e){return t-e});var q,H=V.length,G=D[U];if(0===G){var T=m[U];q=[T]}for(var v=0;H>v;++v){var Y=V[v];if(!(D[Y]>=0)&&(D[Y]=1^G,B.push(Y),0===G)){var T=m[Y];a(T)||(T.reverse(),q.push(T))}}0===G&&d.push(q)}return d}e.exports=a;var o=t("edges-to-adjacency-list"),s=t("planar-dual"),l=t("point-in-big-polygon"),u=t("two-product"),c=t("robust-sum"),h=t("uniq"),f=t("./lib/trim-leaves")},{"./lib/trim-leaves":278,"edges-to-adjacency-list":279,"planar-dual":280,"point-in-big-polygon":289,"robust-sum":217,"two-product":231,uniq:234}],291:[function(t,e,r){arguments[4][49][0].apply(r,arguments)},{dup:49}],292:[function(t,e,r){"use strict";"use restrict";function n(t){this.roots=new Array(t),this.ranks=new Array(t);for(var e=0;t>e;++e)this.roots[e]=e,this.ranks[e]=0}e.exports=n,n.prototype.length=function(){return this.roots.length},n.prototype.makeSet=function(){var t=this.roots.length;return this.roots.push(t),this.ranks.push(0),t},n.prototype.find=function(t){for(var e=this.roots;e[t]!==t;){var r=e[t];e[t]=e[r],t=r}return t},n.prototype.link=function(t,e){var r=this.find(t),n=this.find(e);if(r!==n){var i=this.ranks,a=this.roots,o=i[r],s=i[n];s>o?a[r]=n:o>s?a[n]=r:(a[n]=r,++i[r])}}},{}],293:[function(t,e,r){arguments[4][194][0].apply(r,arguments)},{"bit-twiddle":291,dup:194,"union-find":292}],294:[function(t,e,r){"use strict";function n(t,e,r){var n=Math.abs(a(t,e,r)),i=Math.sqrt(Math.pow(e[0]-r[0],2)+Math.pow(e[1]-r[1],2));return n/i}function i(t,e,r){function i(t){if(x[t])return 1/0;var r=m[t],i=y[t];return 0>r||0>i?1/0:n(e[t],e[r],e[i])}function a(t,e){var r=M[t],n=M[e];M[t]=n,M[e]=r,T[r]=e,T[n]=t}function s(t){return b[M[t]]}function l(t){return 1&t?t-1>>1:(t>>1)-1}function u(t){for(var e=s(t);;){var r=e,n=2*t+1,i=2*(t+1),o=t;if(L>n){var l=s(n);r>l&&(o=n,r=l)}if(L>i){var u=s(i);r>u&&(o=i)}if(o===t)return t;a(t,o),t=o}}function c(t){for(var e=s(t);t>0;){var r=l(t);if(r>=0){var n=s(r);if(n>e){a(t,r),t=r;continue}}return t}}function h(){if(L>0){var t=M[0];return a(0,L-1),L-=1,u(0),t}return-1}function f(t,e){var r=M[t];return b[r]===e?t:(b[r]=-(1/0),c(t),h(),b[r]=e,L+=1,c(L-1))}function d(t){if(!x[t]){x[t]=!0;var e=m[t],r=y[t];m[r]>=0&&(m[r]=e),y[e]>=0&&(y[e]=r),T[e]>=0&&f(T[e],i(e)),T[r]>=0&&f(T[r],i(r))}}function p(t,e){if(t[e]<0)return e;var r=e,n=e;do{var i=t[n];if(!x[n]||0>i||i===n)break;if(n=i,i=t[n],!x[n]||0>i||i===n)break;n=i,r=t[r]}while(r!==n);for(var a=e;a!==n;a=t[a])t[a]=n;return n}for(var g=e.length,v=t.length,m=new Array(g),y=new Array(g),b=new Array(g),x=new Array(g),_=0;g>_;++_)m[_]=y[_]=-1,b[_]=1/0,x[_]=!1;for(var _=0;v>_;++_){var w=t[_];if(2!==w.length)throw new Error("Input must be a graph");var A=w[1],k=w[0];-1!==y[k]?y[k]=-2:y[k]=A,-1!==m[A]?m[A]=-2:m[A]=k}for(var M=[],T=new Array(g),_=0;g>_;++_){var E=b[_]=i(_);1/0>E?(T[_]=M.length,M.push(_)):T[_]=-1}for(var L=M.length,_=L>>1;_>=0;--_)u(_);for(;;){var S=h();if(0>S||b[S]>r)break;d(S)}for(var C=[],_=0;g>_;++_)x[_]||(T[_]=C.length,C.push(e[_].slice()));var P=(C.length,[]);return t.forEach(function(t){var e=p(m,t[0]),r=p(y,t[1]);if(e>=0&&r>=0&&e!==r){var n=T[e],i=T[r];n!==i&&P.push([n,i])}}),o.unique(o.normalize(P)),{positions:C,edges:P}}e.exports=i;var a=t("robust-orientation"),o=t("simplicial-complex")},{"robust-orientation":214,"simplicial-complex":293}],295:[function(t,e,r){"use strict";e.exports=["",{path:"M-2.4,-3V3L0.6,0Z",backoff:.6},{path:"M-3.7,-2.5V2.5L1.3,0Z",backoff:1.3},{path:"M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z",backoff:1.55},{path:"M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z",backoff:1.6},{path:"M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z",backoff:2},{path:"M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z",backoff:0},{path:"M2,2V-2H-2V2Z",backoff:0}]},{}],296:[function(t,e,r){"use strict";var n=t("./arrow_paths"),i=t("../../plots/cartesian"),a=t("../../plots/font_attributes"),o=t("../../lib/extend").extendFlat;e.exports={_isLinkedToArray:!0,text:{valType:"string"},textangle:{valType:"angle",dflt:0},font:o({},a,{}),opacity:{valType:"number",min:0,max:1,dflt:1},align:{valType:"enumerated",values:["left","center","right"],dflt:"center"},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)"},bordercolor:{valType:"color",dflt:"rgba(0,0,0,0)"},borderpad:{valType:"number",min:0,dflt:1},borderwidth:{valType:"number",min:0,dflt:1},showarrow:{valType:"boolean",dflt:!0},arrowcolor:{valType:"color"},arrowhead:{valType:"integer",min:0,max:n.length,dflt:1},arrowsize:{valType:"number",min:.3,dflt:1},arrowwidth:{valType:"number",min:.1},ax:{valType:"number",dflt:-10},ay:{valType:"number",dflt:-30},xref:{valType:"enumerated",values:["paper",i.idRegex.x.toString()]},x:{valType:"number"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"auto"},yref:{valType:"enumerated",values:["paper",i.idRegex.y.toString()]},y:{valType:"number"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto"},_deprecated:{ref:{valType:"string"}}}},{"../../lib/extend":345,"../../plots/cartesian":375,"../../plots/font_attributes":383,"./arrow_paths":295}],297:[function(t,e,r){"use strict";function n(t,e){function r(e,r){return o.Lib.coerce(t,n,u.layoutAttributes,e,r)}var n={};r("opacity"),r("align"),r("bgcolor");var i=r("bordercolor"),a=o.Color.opacity(i);r("borderpad");var s=r("borderwidth"),l=r("showarrow");l&&(r("arrowcolor",a?n.bordercolor:o.Color.defaultLine),r("arrowhead"),r("arrowsize"),r("arrowwidth",2*(a&&s||1)),r("ax"),r("ay"),o.Lib.noneOrAll(t,n,["ax","ay"])),r("text",l?"&nbsp;":"new text"),r("textangle"),o.Lib.coerceFont(r,"font",e.font);for(var c=["x","y"],h=0;2>h;h++){var f=c[h],d={_fullLayout:e},p=o.Axes.coerceRef(t,n,d,f),g=.5;if("paper"!==p){var v=o.Axes.getFromId(d,p);if(g=v.range[0]+g*(v.range[1]-v.range[0]),-1!==["date","category"].indexOf(v.type)&&"string"==typeof t[f]){var m;"date"===v.type?(m=o.Lib.dateTime2ms(t[f]),m!==!1&&(t[f]=m)):(v._categories||[]).length&&(m=v._categories.indexOf(t[f]),-1!==m&&(t[f]=m))}}r(f,g),l||r(f+"anchor")}return o.Lib.noneOrAll(t,n,["x","y"]),n}function i(t){var e=t._fullLayout;e.annotations.forEach(function(e){var r=o.Axes.getFromId(t,e.xref),n=o.Axes.getFromId(t,e.yref);if(r||n){var i=(e._xsize||0)/2,a=e._xshift||0,s=(e._ysize||0)/2,l=e._yshift||0,u=i-a,c=i+a,h=s-l,f=s+l;if(e.showarrow){var d=3*e.arrowsize*e.arrowwidth;u=Math.max(u,d),c=Math.max(c,d),h=Math.max(h,d),f=Math.max(f,d)}r&&r.autorange&&o.Axes.expand(r,[r.l2c(e.x)],{ppadplus:c,ppadminus:u}),n&&n.autorange&&o.Axes.expand(n,[n.l2c(e.y)],{ppadplus:f,ppadminus:h})}})}function a(t,e,r,n,i,a,o,s){var l=r-t,u=i-t,c=o-i,h=n-e,f=a-e,d=s-a,p=l*d-c*h;if(0===p)return null;var g=(u*d-c*f)/p,v=(u*h-l*f)/p;return 0>v||v>1||0>g||g>1?null:{x:t+l*g,y:e+h*g}}var o=t("../../plotly"),s=t("d3"),l=t("fast-isnumeric"),u=e.exports={};u.ARROWPATHS=t("./arrow_paths"),u.layoutAttributes=t("./attributes"),u.supplyLayoutDefaults=function(t,e){for(var r=t.annotations||[],i=e.annotations=[],a=0;a<r.length;a++)i.push(n(r[a]||{},e))},u.drawAll=function(t){var e=t._fullLayout;e._infolayer.selectAll(".annotation").remove();for(var r=0;r<e.annotations.length;r++)u.draw(t,r);return o.Plots.previousPromises(t)},u.add=function(t){var e=t._fullLayout.annotations.length;o.relayout(t,"annotations["+e+"]","add")},u.draw=function(t,e,r,i){function c(t){return t.call(o.Drawing.font,Y).attr({"text-anchor":{left:"start",right:"end"}[O.align]||"middle"}),o.util.convertToTspans(t,h),t}function h(){function r(t,e){return"auto"===e&&(e=1/3>t?"left":t>2/3?"right":"center"),{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[e]}X.selectAll("tspan.line").attr({y:0,x:0});var n=U.select(".annotation-math-group"),i=!n.empty(),l=o.Drawing.bBox((i?n:X).node()),c=l.width,h=l.height,f=Math.round(c+2*H),d=Math.round(h+2*H);O._w=c,O._h=h;var g=!1;if(["x","y"].forEach(function(e){var n,i=o.Axes.getFromId(t,O[e+"ref"]||e),a=(F+("x"===e?0:90))*Math.PI/180,s=f*Math.abs(Math.cos(a))+d*Math.abs(Math.sin(a)),l=O[e+"anchor"];if(i){if(!i.autorange&&(O[e]-i.range[0])*(O[e]-i.range[1])>0)return void(g=!0);N[e]=i._offset+i.l2p(O[e]),n=.5}else n=O[e],"y"===e&&(n=1-n),N[e]="x"===e?w.l+w.w*n:w.t+w.h*n;var u=0;u=O.showarrow?O["a"+e]:s*r(n,l),N[e]+=u,O["_"+e+"type"]=i&&i.type,O["_"+e+"size"]=s,O["_"+e+"shift"]=u}),g)return void U.remove();var v,m;O.showarrow&&(v=o.Lib.constrain(N.x-O.ax,1,p.width-1),m=o.Lib.constrain(N.y-O.ay,1,p.height-1)),N.x=o.Lib.constrain(N.x,1,p.width-1),N.y=o.Lib.constrain(N.y,1,p.height-1);var y=H-l.top,b=H-l.left;i?n.select("svg").attr({x:H-1,y:H}):(X.attr({x:b,y:y}),X.selectAll("tspan.line").attr({y:y,x:b})),G.call(o.Drawing.setRect,V/2,V/2,f-V,d-V),U.call(o.Drawing.setRect,Math.round(N.x-f/2),Math.round(N.y-d/2),f,d);var x="annotations["+e+"]",_=function(r,n){s.select(t).selectAll('.annotation-arrow-g[data-index="'+e+'"]').remove();var i=N.x+r,l=N.y+n,c=o.Lib.rotationXYMatrix(F,i,l),h=o.Lib.apply2DTransform(c),f=o.Lib.apply2DTransform2(c),d=G.attr("width")/2,p=G.attr("height")/2,g=[[i-d,l-p,i-d,l+p],[i-d,l+p,i+d,l+p],[i+d,l+p,i+d,l-p],[i+d,l-p,i-d,l-p]].map(f);if(!g.reduce(function(t,e){return t^!!a(v,m,v+1e6,m+1e6,e[0],e[1],e[2],e[3])},!1)){g.forEach(function(t){var e=a(i,l,v,m,t[0],t[1],t[2],t[3]);
+e&&(i=e.x,l=e.y)});var y=O.arrowwidth,b=O.arrowcolor,_=B.append("g").style({opacity:o.Color.opacity(b)}).classed("annotation-arrow-g",!0).attr("data-index",String(e)),A=_.append("path").attr("d","M"+i+","+l+"L"+v+","+m).style("stroke-width",y+"px").call(o.Color.stroke,o.Color.rgb(b));u.arrowhead(A,O.arrowhead,"end",O.arrowsize);var k=_.append("path").classed("annotation",!0).classed("anndrag",!0).attr({"data-index":String(e),d:"M3,3H-3V-3H3ZM0,0L"+(i-v)+","+(l-m),transform:"translate("+v+","+m+")"}).style("stroke-width",y+6+"px").call(o.Color.stroke,"rgba(0,0,0,0)").call(o.Color.fill,"rgba(0,0,0,0)");if(t._context.editable){var M,T,E;o.Fx.dragElement({element:k.node(),prepFn:function(){T=Number(U.attr("x")),E=Number(U.attr("y")),M={},I&&I.autorange&&(M[I._name+".autorange"]=!0),j&&j.autorange&&(M[j._name+".autorange"]=!0)},moveFn:function(t,e){_.attr("transform","translate("+t+","+e+")");var r=h(T,E),n=r[0]+t,i=r[1]+e;U.call(o.Drawing.setPosition,n,i),M[x+".x"]=I?O.x+t/I._m:(v+t-w.l)/w.w,M[x+".y"]=j?O.y+e/j._m:1-(m+e-w.t)/w.h,D.attr({transform:"rotate("+F+","+n+","+i+")"})},doneFn:function(e){if(e){o.relayout(t,M);var r=document.querySelector(".js-notes-box-panel");r&&r.redraw(r.selectedObj)}}})}}};O.showarrow&&_(0,0);var A=o.Lib.rotationXYMatrix(F,N.x,N.y),k=o.Lib.apply2DTransform(A);if(t._context.editable){var M,T,E;o.Fx.dragElement({element:U.node(),prepFn:function(){M=Number(U.attr("x")),T=Number(U.attr("y")),E={}},moveFn:function(t,e){U.call(o.Drawing.setPosition,M+t,T+e);var r="pointer";if(O.showarrow)E[x+".ax"]=O.ax+t,E[x+".ay"]=O.ay+e,_(t,e);else{if(I)E[x+".x"]=O.x+t/I._m;else{var n=O._xsize/w.w,i=O.x+O._xshift/w.w-n/2;E[x+".x"]=o.Fx.dragAlign(i+t/w.w,n,0,1,O.xanchor)}if(j)E[x+".y"]=O.y+e/j._m;else{var a=O._ysize/w.h,s=O.y-O._yshift/w.h-a/2;E[x+".y"]=o.Fx.dragAlign(s-e/w.h,a,0,1,O.yanchor)}I&&j||(r=o.Fx.dragCursors(I?.5:E[x+".x"],j?.5:E[x+".y"],O.xanchor,O.yanchor))}var l=k(M,T),u=l[0]+t,c=l[1]+e;U.call(o.Drawing.setPosition,u,c),D.attr({transform:"rotate("+F+","+u+","+c+")"}),o.Fx.setCursor(U,r)},doneFn:function(e){if(o.Fx.setCursor(U),e){o.relayout(t,E);var r=document.querySelector(".js-notes-box-panel");r&&r.redraw(r.selectedObj)}}})}}var f,d=t.layout,p=t._fullLayout;if(!l(e)||-1===e){if(!e&&Array.isArray(i))return d.annotations=i,u.supplyLayoutDefaults(d,p),void u.drawAll(t);if("remove"===i)return delete d.annotations,p.annotations=[],void u.drawAll(t);if(r&&"add"!==i){for(f=0;f<p.annotations.length;f++)u.draw(t,f,r,i);return}e=p.annotations.length,p.annotations.push({})}if(!r&&i){if("remove"===i){for(p._infolayer.selectAll('.annotation[data-index="'+e+'"]').remove(),p.annotations.splice(e,1),d.annotations.splice(e,1),f=e;f<p.annotations.length;f++)p._infolayer.selectAll('.annotation[data-index="'+(f+1)+'"]').attr("data-index",String(f)),u.draw(t,f);return}if("add"===i||o.Lib.isPlainObject(i)){p.annotations.splice(e,0,{});var g=o.Lib.isPlainObject(i)?o.Lib.extendFlat({},i):{text:"New text"};for(d.annotations?d.annotations.splice(e,0,g):d.annotations=[g],f=p.annotations.length-1;f>e;f--)p._infolayer.selectAll('.annotation[data-index="'+(f-1)+'"]').attr("data-index",String(f)),u.draw(t,f)}}p._infolayer.selectAll('.annotation[data-index="'+e+'"]').remove();var v=d.annotations[e],m=p.annotations[e];if(v){var y={xref:v.xref,yref:v.yref},b={};"string"==typeof r&&r?b[r]=i:o.Lib.isPlainObject(r)&&(b=r);var x=Object.keys(b);for(f=0;f<x.length;f++){var _=x[f];o.Lib.nestedProperty(v,_).set(b[_])}var w=p._size,A=["x","y"];for(f=0;2>f;f++){var k=A[f];if(void 0===b[k]&&void 0!==v[k]){var M=o.Axes.getFromId(t,o.Axes.coerceRef(y,{},t,k)),T=o.Axes.getFromId(t,o.Axes.coerceRef(v,{},t,k)),E=v[k],L=m["_"+k+"type"];if(void 0!==b[k+"ref"]){var S="auto"===v[k+"anchor"],C="x"===k?w.w:w.h,P=(m["_"+k+"size"]||0)/(2*C);if(M&&T)E=(E-M.range[0])/(M.range[1]-M.range[0]),E=T.range[0]+E*(T.range[1]-T.range[0]);else if(M){if(E=(E-M.range[0])/(M.range[1]-M.range[0]),E=M.domain[0]+E*(M.domain[1]-M.domain[0]),S){var z=E+P,R=E-P;2/3>E+R?E=R:E+z>4/3&&(E=z)}}else T&&(S&&(1/3>E?E+=P:E>2/3&&(E-=P)),E=(E-T.domain[0])/(T.domain[1]-T.domain[0]),E=T.range[0]+E*(T.range[1]-T.range[0]))}T&&T===M&&L&&("log"===L&&"log"!==T.type?E=Math.pow(10,E):"log"!==L&&"log"===T.type&&(E=E>0?Math.log(E)/Math.LN10:void 0)),v[k]=E}}var O=n(v,p);p.annotations[e]=O;var I=o.Axes.getFromId(t,O.xref),j=o.Axes.getFromId(t,O.yref),N={x:0,y:0},F=+O.textangle||0,B=p._infolayer.append("g").classed("annotation",!0).attr("data-index",String(e)).style("opacity",O.opacity).on("click",function(){t._dragging=!1,t.emit("plotly_clickannotation",{index:e,annotation:v,fullAnnotation:O})}),D=B.append("g").classed("annotation-text-g",!0).attr("data-index",String(e)),U=D.append("svg").call(o.Drawing.setPosition,0,0),V=O.borderwidth,q=O.borderpad,H=V+q,G=U.append("rect").attr("class","bg").style("stroke-width",V+"px").call(o.Color.stroke,O.bordercolor).call(o.Color.fill,O.bgcolor),Y=O.font,X=U.append("text").classed("annotation",!0).attr("data-unformatted",O.text).text(O.text);t._context.editable?X.call(o.util.makeEditable,U).call(c).on("edit",function(r){O.text=r,this.attr({"data-unformatted":O.text}),this.call(c);var n={};n["annotations["+e+"].text"]=O.text,I&&I.autorange&&(n[I._name+".autorange"]=!0),j&&j.autorange&&(n[j._name+".autorange"]=!0),o.relayout(t,n)}):X.call(c),D.attr({transform:"rotate("+F+","+N.x+","+N.y+")"}).call(o.Drawing.setPosition,N.x,N.y)}},u.arrowhead=function(t,e,r,n){l(n)||(n=1);var i=t.node(),a=u.ARROWPATHS[e||0];if(a){"string"==typeof r&&r||(r="end");var c,h,f,d,p=(o.Drawing.getPx(t,"stroke-width")||1)*n,g=t.style("stroke")||o.Color.defaultLine,v=t.style("stroke-opacity")||1,m=r.indexOf("start")>=0,y=r.indexOf("end")>=0,b=a.backoff*p;if("line"===i.nodeName){if(c={x:+t.attr("x1"),y:+t.attr("y1")},h={x:+t.attr("x2"),y:+t.attr("y2")},f=Math.atan2(c.y-h.y,c.x-h.x),d=f+Math.PI,b){var x=b*Math.cos(f),_=b*Math.sin(f);m&&(c.x-=x,c.y-=_,t.attr({x1:c.x,y1:c.y})),y&&(h.x+=x,h.y+=_,t.attr({x2:h.x,y2:h.y}))}}else if("path"===i.nodeName){var w=i.getTotalLength(),A="";if(m){var k=i.getPointAtLength(0),M=i.getPointAtLength(.1);f=Math.atan2(k.y-M.y,k.x-M.x),c=i.getPointAtLength(Math.min(b,w)),b&&(A="0px,"+b+"px,")}if(y){var T=i.getPointAtLength(w),E=i.getPointAtLength(w-.1);if(d=Math.atan2(T.y-E.y,T.x-E.x),h=i.getPointAtLength(Math.max(0,w-b)),b){var L=A?2*b:b;A+=w-L+"px,"+w+"px"}}else A&&(A+=w+"px");A&&t.style("stroke-dasharray",A)}var S=function(r,n){e>5&&(n=0),s.select(i.parentElement).append("path").attr({"class":t.attr("class"),d:a.path,transform:"translate("+r.x+","+r.y+")rotate("+180*n/Math.PI+")scale("+p+")"}).style({fill:g,opacity:v,"stroke-width":0})};m&&S(c,f),y&&S(h,d)}},u.calcAutorange=function(t){var e=t._fullLayout,r=e.annotations;if(r.length&&t._fullData.length){var n={};r.forEach(function(t){n[t.xref]=!0,n[t.yref]=!0});var a=o.Axes.list(t).filter(function(t){return t.autorange&&n[t._id]});if(a.length)return o.Lib.syncOrAsync([u.drawAll,i],t)}}},{"../../plotly":366,"./arrow_paths":295,"./attributes":296,d3:70,"fast-isnumeric":74}],298:[function(t,e,r){"use strict";r.defaults=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],r.defaultLine="#444",r.lightLine="#eee",r.background="#fff"},{}],299:[function(t,e,r){"use strict";function n(t){if(a(t)||"string"!=typeof t)return t;var e=t.trim();if("rgb"!==e.substr(0,3))return t;var r=e.match(/^rgba?\s*\(([^()]*)\)$/);if(!r)return t;var n=r[1].trim().split(/\s*[\s,]\s*/),i="a"===e.charAt(3)&&4===n.length;if(!i&&3!==n.length)return t;for(var o=0;o<n.length;o++){if(!n[o].length)return t;if(n[o]=Number(n[o]),!(n[o]>=0))return t;if(3===o)n[o]>1&&(n[o]=1);else if(n[o]>=1)return t}var s=Math.round(255*n[0])+", "+Math.round(255*n[1])+", "+Math.round(255*n[2]);return i?"rgba("+s+", "+n[3]+")":"rgb("+s+")"}var i=t("tinycolor2"),a=t("fast-isnumeric"),o=e.exports={},s=t("./attributes");o.defaults=s.defaults,o.defaultLine=s.defaultLine,o.lightLine=s.lightLine,o.background=s.background,o.tinyRGB=function(t){var e=t.toRgb();return"rgb("+Math.round(e.r)+", "+Math.round(e.g)+", "+Math.round(e.b)+")"},o.rgb=function(t){return o.tinyRGB(i(t))},o.opacity=function(t){return t?i(t).getAlpha():0},o.addOpacity=function(t,e){var r=i(t).toRgb();return"rgba("+Math.round(r.r)+", "+Math.round(r.g)+", "+Math.round(r.b)+", "+e+")"},o.combine=function(t,e){var r=i(t).toRgb();if(1===r.a)return i(t).toRgbString();var n=i(e||o.background).toRgb(),a=1===n.a?n:{r:255*(1-n.a)+n.r*n.a,g:255*(1-n.a)+n.g*n.a,b:255*(1-n.a)+n.b*n.a},s={r:a.r*(1-r.a)+r.r*r.a,g:a.g*(1-r.a)+r.g*r.a,b:a.b*(1-r.a)+r.b*r.a};return i(s).toRgbString()},o.stroke=function(t,e){var r=i(e);t.style({stroke:o.tinyRGB(r),"stroke-opacity":r.getAlpha()})},o.fill=function(t,e){var r=i(e);t.style({fill:o.tinyRGB(r),"fill-opacity":r.getAlpha()})},o.clean=function(t){if(t&&"object"==typeof t){var e,r,i,a,s=Object.keys(t);for(e=0;e<s.length;e++)if(i=s[e],a=t[i],"color"===i.substr(i.length-5))if(Array.isArray(a))for(r=0;r<a.length;r++)a[r]=n(a[r]);else t[i]=n(a);else if("colorscale"===i.substr(i.length-10)&&Array.isArray(a))for(r=0;r<a.length;r++)Array.isArray(a[r])&&(a[r][1]=n(a[r][1]));else if(Array.isArray(a)){var l=a[0];if(!Array.isArray(l)&&l&&"object"==typeof l)for(r=0;r<a.length;r++)o.clean(a[r])}else a&&"object"==typeof a&&o.clean(a)}}},{"./attributes":298,"fast-isnumeric":74,tinycolor2:229}],300:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/layout_attributes"),i=t("../../plots/font_attributes"),a=t("../../lib/extend").extendFlat;e.exports={thicknessmode:{valType:"enumerated",values:["fraction","pixels"],dflt:"pixels"},thickness:{valType:"number",min:0,dflt:30},lenmode:{valType:"enumerated",values:["fraction","pixels"],dflt:"fraction"},len:{valType:"number",min:0,dflt:1},x:{valType:"number",dflt:1.02,min:-2,max:3},xanchor:{valType:"enumerated",values:["left","center","right"],dflt:"left"},xpad:{valType:"number",min:0,dflt:10},y:{valType:"number",dflt:.5,min:-2,max:3},yanchor:{valType:"enumerated",values:["top","middle","bottom"],dflt:"middle"},ypad:{valType:"number",min:0,dflt:10},outlinecolor:n.linecolor,outlinewidth:n.linewidth,bordercolor:n.linecolor,borderwidth:{valType:"number",min:0,dflt:0},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)"},tickmode:n.tickmode,nticks:n.nticks,tick0:n.tick0,dtick:n.dtick,tickvals:n.tickvals,ticktext:n.ticktext,ticks:a({},n.ticks,{dflt:""}),ticklen:n.ticklen,tickwidth:n.tickwidth,tickcolor:n.tickcolor,showticklabels:n.showticklabels,tickfont:n.tickfont,tickangle:n.tickangle,tickformat:n.tickformat,tickprefix:n.tickprefix,showtickprefix:n.showtickprefix,ticksuffix:n.ticksuffix,showticksuffix:n.showticksuffix,exponentformat:n.exponentformat,showexponent:n.showexponent,title:{valType:"string",dflt:"Click to enter colorscale title"},titlefont:a({},i,{}),titleside:{valType:"enumerated",values:["right","top","bottom"],dflt:"top"}}},{"../../lib/extend":345,"../../plots/cartesian/layout_attributes":376,"../../plots/font_attributes":383}],301:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/tick_value_defaults"),a=t("../../plots/cartesian/tick_defaults"),o=t("./attributes");e.exports=function(t,e,r){function s(t,e){return n.coerce(u,l,o,t,e)}var l=e.colorbar={},u=t.colorbar||{},c=s("thicknessmode");s("thickness","fraction"===c?30/(r.width-r.margin.l-r.margin.r):30);var h=s("lenmode");s("len","fraction"===h?1:r.height-r.margin.t-r.margin.b),s("x"),s("xanchor"),s("xpad"),s("y"),s("yanchor"),s("ypad"),n.noneOrAll(u,l,["x","y"]),s("outlinecolor"),s("outlinewidth"),s("bordercolor"),s("borderwidth"),s("bgcolor"),i(u,l,s,"linear"),a(u,l,s,"linear",{outerTicks:!1,font:r.font,noHover:!0}),s("title"),n.coerceFont(s,"titlefont",r.font),s("titleside")}},{"../../lib":349,"../../plots/cartesian/tick_defaults":381,"../../plots/cartesian/tick_value_defaults":382,"./attributes":300}],302:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../plotly"),a=t("../../plots/plots"),o=t("../../plots/cartesian/axes"),s=t("../../plots/cartesian/graph_interact"),l=t("../../lib"),u=t("../drawing"),c=t("../color"),h=t("../titles"),f=t("../../plots/cartesian/axis_defaults"),d=t("../../plots/cartesian/position_defaults"),p=t("../../plots/cartesian/layout_attributes"),g=t("./attributes");e.exports=function(t,e){function r(){function g(t,e){return l.coerce(G,Y,p,t,e)}function m(){if(-1!==["top","bottom"].indexOf(v.titleside)){var e=Q.select(".cbtitle"),r=e.select("text"),i=[-v.outlinewidth/2,v.outlinewidth/2],a=e.select(".h"+Y._id+"title-math-group").node(),s=15.6;if(r.node()&&(s=1.3*parseInt(r.style("font-size"),10)),a?(tt=u.bBox(a).height,tt>s&&(i[1]-=(tt-s)/2)):r.node()&&!r.classed("js-placeholder")&&(tt=u.bBox(e.node()).height),tt){if(tt+=5,"top"===v.titleside)Y.domain[1]-=tt/b._size.h,i[1]*=-1;else{Y.domain[0]+=tt/b._size.h;var l=Math.max(1,r.selectAll("tspan.line").size());i[1]+=(1-l)*s}e.attr("transform","translate("+i+")"),Y.setScale()}}Q.selectAll(".cbfills,.cblines,.cbaxis").attr("transform","translate(0,"+Math.round(b._size.h*(1-Y.domain[1]))+")");var c=Q.select(".cbfills").selectAll("rect.cbfill").data(A);c.enter().append("rect").classed("cbfill",!0).style("stroke","none"),c.exit().remove(),c.each(function(t,e){var r=[0===e?_[0]:(A[e]+A[e-1])/2,e===A.length-1?_[1]:(A[e]+A[e+1])/2].map(Y.c2p).map(Math.round);e!==A.length-1&&(r[1]+=r[1]>r[0]?1:-1),n.select(this).attr({x:D,width:Math.max(R,2),y:n.min(r),height:Math.max(n.max(r)-n.min(r),2)}).style("fill",M(t))});var h=Q.select(".cblines").selectAll("path.cbline").data(v.line.color&&v.line.width?w:[]);return h.enter().append("path").classed("cbline",!0),h.exit().remove(),h.each(function(t){n.select(this).attr("d","M"+D+","+(Math.round(Y.c2p(t))+v.line.width/2%1)+"h"+R).call(u.lineGroupStyle,v.line.width,k(t),v.line.dash)}),Y._axislayer.selectAll("g."+Y._id+"tick,path").remove(),Y._pos=D+R+(v.outlinewidth||0)/2-("outside"===v.ticks?1:0),Y.side="right",o.doTicks(t,Y)}function y(){var r=R+v.outlinewidth/2+u.bBox(Y._axislayer.node()).width;if(C=J.select("text"),C.node()&&!C.classed("js-placeholder")){var n,i=J.select(".h"+Y._id+"title-math-group").node();n=i&&-1!==["top","bottom"].indexOf(v.titleside)?u.bBox(i).width:u.bBox(J.node()).right-D-b._size.l,r=Math.max(r,n)}var o=2*v.xpad+r+v.borderwidth+v.outlinewidth/2,s=q-H;Q.select(".cbbg").attr({x:D-v.xpad-(v.borderwidth+v.outlinewidth)/2,y:H-F,width:Math.max(o,2),height:Math.max(s+2*F,2)}).call(c.fill,v.bgcolor).call(c.stroke,v.bordercolor).style({"stroke-width":v.borderwidth}),Q.selectAll(".cboutline").attr({x:D,y:H+v.ypad+("top"===v.titleside?tt:0),width:Math.max(R,2),height:Math.max(s-2*v.ypad-tt,2)}).call(c.stroke,v.outlinecolor).style({fill:"None","stroke-width":v.outlinewidth});var l=({center:.5,right:1}[v.xanchor]||0)*o;Q.attr("transform","translate("+(b._size.l-l)+","+b._size.t+")"),a.autoMargin(t,e,{x:v.x,y:v.y,l:o*({right:1,center:.5}[v.xanchor]||0),r:o*({left:1,center:.5}[v.xanchor]||0),t:s*({bottom:1,middle:.5}[v.yanchor]||0),b:s*({top:1,middle:.5}[v.yanchor]||0)})}var b=t._fullLayout;if("function"!=typeof v.fillcolor&&"function"!=typeof v.line.color)return void b._infolayer.selectAll("g."+e).remove();var x,_=n.extent(("function"==typeof v.fillcolor?v.fillcolor:v.line.color).domain()),w=[],A=[],k="function"==typeof v.line.color?v.line.color:function(){return v.line.color},M="function"==typeof v.fillcolor?v.fillcolor:function(){return v.fillcolor},T=v.levels.end+v.levels.size/100,E=v.levels.size,L=1.001*_[0]-.001*_[1],S=1.001*_[1]-.001*_[0];for(x=v.levels.start;0>(x-T)*E;x+=E)x>L&&S>x&&w.push(x);if("function"==typeof v.fillcolor)if(v.filllevels)for(T=v.filllevels.end+v.filllevels.size/100,E=v.filllevels.size,x=v.filllevels.start;0>(x-T)*E;x+=E)x>_[0]&&x<_[1]&&A.push(x);else A=w.map(function(t){return t-v.levels.size/2}),A.push(A[A.length-1]+v.levels.size);else v.fillcolor&&"string"==typeof v.fillcolor&&(A=[0]);v.levels.size<0&&(w.reverse(),A.reverse());var C,P=b.height-b.margin.t-b.margin.b,z=b.width-b.margin.l-b.margin.r,R=Math.round(v.thickness*("fraction"===v.thicknessmode?z:1)),O=R/b._size.w,I=Math.round(v.len*("fraction"===v.lenmode?P:1)),j=I/b._size.h,N=v.xpad/b._size.w,F=(v.borderwidth+v.outlinewidth)/2,B=v.ypad/b._size.h,D=Math.round(v.x*b._size.w+v.xpad),U=v.x-O*({middle:.5,right:1}[v.xanchor]||0),V=v.y+j*(({top:-.5,bottom:.5}[v.yanchor]||0)-.5),q=Math.round(b._size.h*(1-V)),H=q-I,G={type:"linear",range:_,tickmode:v.tickmode,nticks:v.nticks,tick0:v.tick0,dtick:v.dtick,tickvals:v.tickvals,ticktext:v.ticktext,ticks:v.ticks,ticklen:v.ticklen,tickwidth:v.tickwidth,tickcolor:v.tickcolor,showticklabels:v.showticklabels,tickfont:v.tickfont,tickangle:v.tickangle,tickformat:v.tickformat,exponentformat:v.exponentformat,showexponent:v.showexponent,showtickprefix:v.showtickprefix,tickprefix:v.tickprefix,showticksuffix:v.showticksuffix,ticksuffix:v.ticksuffix,title:v.title,titlefont:v.titlefont,anchor:"free",position:1},Y={},X={letter:"y",font:b.font,noHover:!0};if(f(G,Y,g,X),d(G,Y,g,X),Y._id="y"+e,Y._td=t,Y.position=v.x+N+O,r.axis=Y,-1!==["top","bottom"].indexOf(v.titleside)&&(Y.titleside=v.titleside,Y.titlex=v.x+N,Y.titley=V+("top"===v.titleside?j-B:B)),v.line.color&&"auto"===v.tickmode){Y.tickmode="linear",Y.tick0=v.levels.start;var W=v.levels.size,Z=l.constrain((q-H)/50,4,15)+1,$=(_[1]-_[0])/((v.nticks||Z)*W);if($>1){var K=Math.pow(10,Math.floor(Math.log($)/Math.LN10));W*=K*l.roundUp($/K,[2,5,10]),(Math.abs(v.levels.start)/v.levels.size+1e-6)%1<2e-6&&(Y.tick0=0)}Y.dtick=W}Y.domain=[V+B,V+j-B],Y.setScale();var Q=b._infolayer.selectAll("g."+e).data([0]);Q.enter().append("g").classed(e,!0).each(function(){var t=n.select(this);t.append("rect").classed("cbbg",!0),t.append("g").classed("cbfills",!0),t.append("g").classed("cblines",!0),t.append("g").classed("cbaxis",!0).classed("crisp",!0),t.append("g").classed("cbtitleunshift",!0).append("g").classed("cbtitle",!0),t.append("rect").classed("cboutline",!0)}),Q.attr("transform","translate("+Math.round(b._size.l)+","+Math.round(b._size.t)+")");var J=Q.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(b._size.l)+",-"+Math.round(b._size.t)+")");Y._axislayer=Q.select(".cbaxis");var tt=0;-1!==["top","bottom"].indexOf(v.titleside)&&h.draw(t,Y._id+"title");var et=l.syncOrAsync([a.previousPromises,m,a.previousPromises,y],t);if(et&&et.then&&(t._promises||[]).push(et),t._context.editable){var rt,nt,it;s.dragElement({element:Q.node(),prepFn:function(){rt=Q.attr("transform"),s.setCursor(Q)},moveFn:function(e,r){var n=t._fullLayout._size;Q.attr("transform",rt+" translate("+e+","+r+")"),nt=s.dragAlign(U+e/n.w,O,0,1,v.xanchor),it=s.dragAlign(V-r/n.h,j,0,1,v.yanchor);var i=s.dragCursors(nt,it,v.xanchor,v.yanchor);s.setCursor(Q,i)},doneFn:function(r){if(s.setCursor(Q),r&&void 0!==nt&&void 0!==it){var n,a=e.substr(2);t._fullData.some(function(t){return t.uid===a?(n=t.index,!0):void 0}),i.restyle(t,{"colorbar.x":nt,"colorbar.y":it},n)}}})}return et}var v={};return Object.keys(g).forEach(function(t){v[t]=null}),v.fillcolor=null,v.line={color:null,width:null,dash:null},v.levels={start:null,end:null,size:null},v.filllevels=null,Object.keys(v).forEach(function(t){r[t]=function(e){return arguments.length?(v[t]=l.isPlainObject(v[t])?l.extendFlat(v[t],e):e,r):v[t]}}),r.options=function(t){return Object.keys(t).forEach(function(e){"function"==typeof r[e]&&r[e](t[e])}),r},r._opts=v,r}},{"../../lib":349,"../../plotly":366,"../../plots/cartesian/axes":369,"../../plots/cartesian/axis_defaults":370,"../../plots/cartesian/graph_interact":374,"../../plots/cartesian/layout_attributes":376,"../../plots/cartesian/position_defaults":378,"../../plots/plots":413,"../color":299,"../drawing":317,"../titles":332,"./attributes":300,d3:70}],303:[function(t,e,r){"use strict";e.exports=function(t){return"object"==typeof t.colorbar&&null!==t.colorbar}},{}],304:[function(t,e,r){"use strict";r.attributes=t("./attributes"),r.supplyDefaults=t("./defaults"),r.draw=t("./draw"),r.hasColorbar=t("./has_colorbar")},{"./attributes":300,"./defaults":301,"./draw":302,"./has_colorbar":303}],305:[function(t,e,r){"use strict";e.exports={zauto:{valType:"boolean",dflt:!0},zmin:{valType:"number",dflt:null},zmax:{valType:"number",dflt:null},colorscale:{valType:"colorscale"},autocolorscale:{valType:"boolean",dflt:!0},reversescale:{valType:"boolean",dflt:!1},showscale:{valType:"boolean",dflt:!0},_deprecated:{scl:{valType:"colorscale"},reversescl:{valType:"boolean"}}}},{}],306:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./scales"),a=t("./flip_scale");e.exports=function(t,e,r,o){var s,l;r?(s=n.nestedProperty(t,r).get(),l=n.nestedProperty(t._input,r).get()):(s=t,l=t._input);var u=s[o+"auto"],c=s[o+"min"],h=s[o+"max"],f=s.colorscale;(u!==!1||void 0===c)&&(c=n.aggNums(Math.min,null,e)),(u!==!1||void 0===h)&&(h=n.aggNums(Math.max,null,e)),c===h&&(c-=.5,h+=.5),s[o+"min"]=c,s[o+"max"]=h,l[o+"min"]=c,l[o+"max"]=h,s.autocolorscale&&(f=0>c*h?i.RdBu:c>=0?i.Reds:i.Blues,l.colorscale=f,s.reversescale&&(f=a(f)),s.colorscale=f)}},{"../../lib":349,"./flip_scale":309,"./scales":316}],307:[function(t,e,r){"use strict";var n=t("./scales");e.exports=n.RdBu},{"./scales":316}],308:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../colorbar/has_colorbar"),o=t("../colorbar/defaults"),s=t("./is_valid_scale"),l=t("./flip_scale");e.exports=function(t,e,r,u,c){var h=c.prefix,f=c.cLetter,d=h.slice(0,h.length-1),p=h?i.nestedProperty(t,d).get()||{}:t,g=h?i.nestedProperty(e,d).get()||{}:e,v=p[f+"min"],m=p[f+"max"],y=p.colorscale,b=n(v)&&n(m)&&m>v;u(h+f+"auto",!b),u(h+f+"min"),u(h+f+"max");var x;void 0!==y&&(x=!s(y)),u(h+"autocolorscale",x);var _=u(h+"colorscale"),w=u(h+"reversescale");if(w&&(g.colorscale=l(_)),"marker.line."!==h){var A;h&&(A=a(p));var k=u(h+"showscale",A);k&&o(p,g,r)}}},{"../../lib":349,"../colorbar/defaults":301,"../colorbar/has_colorbar":303,"./flip_scale":309,"./is_valid_scale":313,"fast-isnumeric":74}],309:[function(t,e,r){"use strict";e.exports=function(t){for(var e,r=t.length,n=new Array(r),i=r-1,a=0;i>=0;i--,a++)e=t[i],n[a]=[1-e[0],e[1]];return n}},{}],310:[function(t,e,r){"use strict";var n=t("./scales"),i=t("./default_scale"),a=t("./is_valid_scale_array");e.exports=function(t,e){function r(){try{t=n[t]||JSON.parse(t)}catch(r){t=e}}return e||(e=i),t?("string"==typeof t&&(r(),"string"==typeof t&&r()),a(t)?t:e):e}},{"./default_scale":307,"./is_valid_scale_array":314,"./scales":316}],311:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("./is_valid_scale");e.exports=function(t,e){var r=e?i.nestedProperty(t,e).get()||{}:t,o=r.color,s=!1;if(Array.isArray(o))for(var l=0;l<o.length;l++)if(n(o[l])){s=!0;break}return"object"==typeof r&&null!==r&&(s||r.showscale===!0||n(r.cmin)&&n(r.cmax)||a(r.colorscale)||"object"==typeof r.colorbar&&null!==r.colorbar)}},{"../../lib":349,"./is_valid_scale":313,"fast-isnumeric":74}],312:[function(t,e,r){"use strict";r.scales=t("./scales"),r.defaultScale=t("./default_scale"),r.attributes=t("./attributes"),r.handleDefaults=t("./defaults"),r.calc=t("./calc"),r.hasColorscale=t("./has_colorscale"),r.isValidScale=t("./is_valid_scale"),r.getScale=t("./get_scale"),r.flipScale=t("./flip_scale"),r.makeScaleFunction=t("./make_scale_function")},{"./attributes":305,"./calc":306,"./default_scale":307,"./defaults":308,"./flip_scale":309,"./get_scale":310,"./has_colorscale":311,"./is_valid_scale":313,"./make_scale_function":315,"./scales":316}],313:[function(t,e,r){"use strict";var n=t("./scales"),i=t("./is_valid_scale_array");e.exports=function(t){return void 0!==n[t]?!0:i(t)}},{"./is_valid_scale_array":314,"./scales":316}],314:[function(t,e,r){"use strict";var n=t("tinycolor2");e.exports=function(t){var e,r=!0,i=0;if(Array.isArray(t)){if(0!==+t[0][0]||1!==+t[t.length-1][0])return!1;for(var a=0;a<t.length;a++){if(e=t[a],2!==e.length||+e[0]<i||!n(e[1]).isValid()){r=!1;break}i=+e[0]}return r}return!1}},{tinycolor2:229}],315:[function(t,e,r){"use strict";var n=t("d3"),i=t("tinycolor2"),a=t("fast-isnumeric"),o=t("../color");e.exports=function(t,e,r){for(var s,l=t.length,u=new Array(l),c=new Array(l),h=0;l>h;h++)s=t[h],u[h]=e+s[0]*(r-e),c[h]=s[1];var f=n.scale.linear().domain(u).interpolate(n.interpolateRgb).range(c);return function(t){return a(t)?f(t):i(t).isValid()?t:o.defaultLine}}},{"../color":299,d3:70,"fast-isnumeric":74,tinycolor2:229}],316:[function(t,e,r){"use strict";e.exports={Greys:[[0,"rgb(0,0,0)"],[1,"rgb(255,255,255)"]],YlGnBu:[[0,"rgb(8,29,88)"],[.125,"rgb(37,52,148)"],[.25,"rgb(34,94,168)"],[.375,"rgb(29,145,192)"],[.5,"rgb(65,182,196)"],[.625,"rgb(127,205,187)"],[.75,"rgb(199,233,180)"],[.875,"rgb(237,248,217)"],[1,"rgb(255,255,217)"]],Greens:[[0,"rgb(0,68,27)"],[.125,"rgb(0,109,44)"],[.25,"rgb(35,139,69)"],[.375,"rgb(65,171,93)"],[.5,"rgb(116,196,118)"],[.625,"rgb(161,217,155)"],[.75,"rgb(199,233,192)"],[.875,"rgb(229,245,224)"],[1,"rgb(247,252,245)"]],YlOrRd:[[0,"rgb(128,0,38)"],[.125,"rgb(189,0,38)"],[.25,"rgb(227,26,28)"],[.375,"rgb(252,78,42)"],[.5,"rgb(253,141,60)"],[.625,"rgb(254,178,76)"],[.75,"rgb(254,217,118)"],[.875,"rgb(255,237,160)"],[1,"rgb(255,255,204)"]],Bluered:[[0,"rgb(0,0,255)"],[1,"rgb(255,0,0)"]],RdBu:[[0,"rgb(5,10,172)"],[.35,"rgb(106,137,247)"],[.5,"rgb(190,190,190)"],[.6,"rgb(220,170,132)"],[.7,"rgb(230,145,90)"],[1,"rgb(178,10,28)"]],Reds:[[0,"rgb(220,220,220)"],[.2,"rgb(245,195,157)"],[.4,"rgb(245,160,105)"],[1,"rgb(178,10,28)"]],Blues:[[0,"rgb(5,10,172)"],[.35,"rgb(40,60,190)"],[.5,"rgb(70,100,245)"],[.6,"rgb(90,120,245)"],[.7,"rgb(106,137,247)"],[1,"rgb(220,220,220)"]],Picnic:[[0,"rgb(0,0,255)"],[.1,"rgb(51,153,255)"],[.2,"rgb(102,204,255)"],[.3,"rgb(153,204,255)"],[.4,"rgb(204,204,255)"],[.5,"rgb(255,255,255)"],[.6,"rgb(255,204,255)"],[.7,"rgb(255,153,255)"],[.8,"rgb(255,102,204)"],[.9,"rgb(255,102,102)"],[1,"rgb(255,0,0)"]],Rainbow:[[0,"rgb(150,0,90)"],[.125,"rgb(0,0,200)"],[.25,"rgb(0,25,255)"],[.375,"rgb(0,152,255)"],[.5,"rgb(44,255,150)"],[.625,"rgb(151,255,0)"],[.75,"rgb(255,234,0)"],[.875,"rgb(255,111,0)"],[1,"rgb(255,0,0)"]],Portland:[[0,"rgb(12,51,131)"],[.25,"rgb(10,136,186)"],[.5,"rgb(242,211,56)"],[.75,"rgb(242,143,56)"],[1,"rgb(217,30,30)"]],Jet:[[0,"rgb(0,0,131)"],[.125,"rgb(0,60,170)"],[.375,"rgb(5,255,255)"],[.625,"rgb(255,255,0)"],[.875,"rgb(250,0,0)"],[1,"rgb(128,0,0)"]],Hot:[[0,"rgb(0,0,0)"],[.3,"rgb(230,0,0)"],[.6,"rgb(255,210,0)"],[1,"rgb(255,255,255)"]],Blackbody:[[0,"rgb(0,0,0)"],[.2,"rgb(230,0,0)"],[.4,"rgb(230,210,0)"],[.7,"rgb(255,255,255)"],[1,"rgb(160,200,255)"]],Earth:[[0,"rgb(0,0,130)"],[.1,"rgb(0,180,180)"],[.2,"rgb(40,210,40)"],[.4,"rgb(230,230,50)"],[.6,"rgb(120,70,20)"],[1,"rgb(255,255,255)"]],Electric:[[0,"rgb(0,0,0)"],[.15,"rgb(30,0,100)"],[.4,"rgb(120,0,100)"],[.6,"rgb(160,90,0)"],[.8,"rgb(230,200,0)"],[1,"rgb(255,250,220)"]],Viridis:[[0,"#440154"],[.06274509803921569,"#48186a"],[.12549019607843137,"#472d7b"],[.18823529411764706,"#424086"],[.25098039215686274,"#3b528b"],[.3137254901960784,"#33638d"],[.3764705882352941,"#2c728e"],[.4392156862745098,"#26828e"],[.5019607843137255,"#21918c"],[.5647058823529412,"#1fa088"],[.6274509803921569,"#28ae80"],[.6901960784313725,"#3fbc73"],[.7529411764705882,"#5ec962"],[.8156862745098039,"#84d44b"],[.8784313725490196,"#addc30"],[.9411764705882353,"#d8e219"],[1,"#fde725"]]}},{}],317:[function(t,e,r){"use strict";function n(t,e,r,n){var i=t[0]-e[0],o=t[1]-e[1],s=r[0]-e[0],l=r[1]-e[1],u=Math.pow(i*i+o*o,v/2),c=Math.pow(s*s+l*l,v/2),h=(c*c*i-u*u*s)*n,f=(c*c*o-u*u*l)*n,d=3*c*(u+c),p=3*u*(u+c);return[[a.round(e[0]+(d&&h/d),2),a.round(e[1]+(d&&f/d),2)],[a.round(e[0]-(p&&h/p),2),a.round(e[1]-(p&&f/p),2)]]}var i=t("../../plotly"),a=t("d3"),o=t("fast-isnumeric"),s=t("../../constants/xmlns_namespaces"),l=t("../../traces/scatter/subtypes"),u=t("../../traces/scatter/make_bubble_size_func"),c=e.exports={};c.font=function(t,e,r,n){e&&e.family&&(n=e.color,r=e.size,e=e.family),e&&t.style("font-family",e),r+1&&t.style("font-size",r+"px"),n&&t.call(i.Color.fill,n)},c.setPosition=function(t,e,r){t.attr("x",e).attr("y",r)},c.setSize=function(t,e,r){t.attr("width",e).attr("height",r)},c.setRect=function(t,e,r,n,i){t.call(c.setPosition,e,r).call(c.setSize,n,i)},c.translatePoints=function(t,e,r){t.each(function(t){var n=t.xp||e.c2p(t.x),i=t.yp||r.c2p(t.y),s=a.select(this);o(n)&&o(i)?"text"===this.nodeName?s.attr("x",n).attr("y",i):s.attr("transform","translate("+n+","+i+")"):s.remove()})},c.getPx=function(t,e){return Number(t.style(e).replace(/px$/,""))},c.crispRound=function(t,e,r){return e&&o(e)?t._context.staticPlot?e:1>e?1:Math.round(e):r||0},c.lineGroupStyle=function(t,e,r,n){t.style("fill","none").each(function(t){var o=(((t||[])[0]||{}).trace||{}).line||{},s=e||o.width||0,l=n||o.dash||"";a.select(this).call(i.Color.stroke,r||o.color).call(c.dashLine,l,s)})},c.dashLine=function(t,e,r){var n=Math.max(r,3);"solid"===e?e="":"dot"===e?e=n+"px,"+n+"px":"dash"===e?e=3*n+"px,"+3*n+"px":"longdash"===e?e=5*n+"px,"+5*n+"px":"dashdot"===e?e=3*n+"px,"+n+"px,"+n+"px,"+n+"px":"longdashdot"===e&&(e=5*n+"px,"+2*n+"px,"+n+"px,"+2*n+"px"),t.style({"stroke-dasharray":e,"stroke-width":r+"px"})},c.fillGroupStyle=function(t){t.style("stroke-width",0).each(function(e){var r=a.select(this);try{r.call(i.Color.fill,e[0].trace.fillcolor)}catch(n){console.log(n,t),r.remove()}})};var h=t("./symbol_defs");c.symbolNames=[],c.symbolFuncs=[],c.symbolNeedLines={},c.symbolNoDot={},c.symbolList=[],Object.keys(h).forEach(function(t){var e=h[t];c.symbolList=c.symbolList.concat([e.n,t,e.n+100,t+"-open"]),c.symbolNames[e.n]=t,c.symbolFuncs[e.n]=e.f,e.needLine&&(c.symbolNeedLines[e.n]=!0),e.noDot?c.symbolNoDot[e.n]=!0:c.symbolList=c.symbolList.concat([e.n+200,t+"-dot",e.n+300,t+"-open-dot"])});var f=c.symbolNames.length,d="M0,0.5L0.5,0L0,-0.5L-0.5,0Z";c.symbolNumber=function(t){if("string"==typeof t){var e=0;t.indexOf("-open")>0&&(e=100,t=t.replace("-open","")),t.indexOf("-dot")>0&&(e+=200,t=t.replace("-dot","")),t=c.symbolNames.indexOf(t),t>=0&&(t+=e)}return t%100>=f||t>=400?0:Math.floor(Math.max(t,0))},c.pointStyle=function(t,e){if(t.size()){var r=e.marker,n=r.line;if(i.Plots.traceIs(e,"symbols")){var o=u(e);t.attr("d",function(t){var n;n="various"===t.ms||"various"===r.size?3:l.isBubble(e)?o(t.ms):(r.size||6)/2,t.mrc=n;var i=c.symbolNumber(t.mx||r.symbol)||0,a=i%100;return t.om=i%200>=100,c.symbolFuncs[a](n)+(i>=200?d:"")}).style("opacity",function(t){return(t.mo+1||r.opacity+1)-1})}var s=(e._input||{}).marker||{},h=c.tryColorscale(r,s,""),f=c.tryColorscale(r,s,"line.");t.each(function(t){var e,o,s;t.so?(s=n.outlierwidth,o=n.outliercolor,e=r.outliercolor):(s=(t.mlw+1||n.width+1||(t.trace?t.trace.marker.line.width:0)+1)-1,o="mlc"in t?t.mlcc=f(t.mlc):Array.isArray(n.color)?i.Color.defaultLine:n.color,e="mc"in t?t.mcc=h(t.mc):Array.isArray(r.color)?i.Color.defaultLine:r.color||"rgba(0,0,0,0)");var l=a.select(this);t.om?l.call(i.Color.stroke,e).style({"stroke-width":(s||1)+"px",fill:"none"}):(l.style("stroke-width",s+"px").call(i.Color.fill,e),s&&l.call(i.Color.stroke,o))})}},c.tryColorscale=function(t,e,r){var n=i.Lib.nestedProperty(t,r+"color").get(),a=i.Lib.nestedProperty(t,r+"colorscale").get(),s=i.Lib.nestedProperty(t,r+"cauto").get(),l=i.Lib.nestedProperty(t,r+"cmin"),u=i.Lib.nestedProperty(t,r+"cmax"),c=l.get(),h=u.get();return a&&Array.isArray(n)?(!s&&o(c)&&o(h)||(c=1/0,h=-(1/0),n.forEach(function(t){o(t)&&(c>t&&(c=+t),t>h&&(h=+t))}),c>h&&(c=0,h=1),l.set(c),u.set(h),i.Lib.nestedProperty(e,r+"cmin").set(c),i.Lib.nestedProperty(e,r+"cmax").set(h)),i.Colorscale.makeScaleFunction(a,c,h)):i.Lib.identity};var p={start:1,end:-1,middle:0,bottom:1,top:-1},g=1.3;c.textPointStyle=function(t,e){t.each(function(t){var r=a.select(this),n=t.tx||e.text;if(!n||Array.isArray(n))return void r.remove();var s=t.tp||e.textposition,l=-1!==s.indexOf("top")?"top":-1!==s.indexOf("bottom")?"bottom":"middle",u=-1!==s.indexOf("left")?"end":-1!==s.indexOf("right")?"start":"middle",h=t.ts||e.textfont.size,f=t.mrc?t.mrc/.8+1:0;h=o(h)&&h>0?h:0,r.call(c.font,t.tf||e.textfont.family,h,t.tc||e.textfont.color).attr("text-anchor",u).text(n).call(i.util.convertToTspans);var d=a.select(this.parentNode),v=r.selectAll("tspan.line"),m=((v[0].length||1)-1)*g+1,y=p[u]*f,b=.75*h+p[l]*f+(p[l]-1)*m*h/2;
+d.attr("transform","translate("+y+","+b+")"),m>1&&v.attr({x:r.attr("x"),y:r.attr("y")})})};var v=.5;c.smoothopen=function(t,e){if(t.length<3)return"M"+t.join("L");var r,i="M"+t[0],a=[];for(r=1;r<t.length-1;r++)a.push(n(t[r-1],t[r],t[r+1],e));for(i+="Q"+a[0][0]+" "+t[1],r=2;r<t.length-1;r++)i+="C"+a[r-2][1]+" "+a[r-1][0]+" "+t[r];return i+="Q"+a[t.length-3][1]+" "+t[t.length-1]},c.smoothclosed=function(t,e){if(t.length<3)return"M"+t.join("L")+"Z";var r,i="M"+t[0],a=t.length-1,o=[n(t[a],t[0],t[1],e)];for(r=1;a>r;r++)o.push(n(t[r-1],t[r],t[r+1],e));for(o.push(n(t[a-1],t[a],t[0],e)),r=1;a>=r;r++)i+="C"+o[r-1][1]+" "+o[r][0]+" "+t[r];return i+="C"+o[a][1]+" "+o[0][0]+" "+t[0]+"Z"};var m={hv:function(t,e){return"H"+a.round(e[0],2)+"V"+a.round(e[1],2)},vh:function(t,e){return"V"+a.round(e[1],2)+"H"+a.round(e[0],2)},hvh:function(t,e){return"H"+a.round((t[0]+e[0])/2,2)+"V"+a.round(e[1],2)+"H"+a.round(e[0],2)},vhv:function(t,e){return"V"+a.round((t[1]+e[1])/2,2)+"H"+a.round(e[0],2)+"V"+a.round(e[1],2)}},y=function(t,e){return"L"+a.round(e[0],2)+","+a.round(e[1],2)};c.steps=function(t){var e=m[t]||y;return function(t){for(var r="M"+a.round(t[0][0],2)+","+a.round(t[0][1],2),n=1;n<t.length;n++)r+=e(t[n-1],t[n]);return r}},c.makeTester=function(t){var e=a.select("body").selectAll("#js-plotly-tester").data([0]);e.enter().append("svg").attr("id","js-plotly-tester").attr(s.svgAttrs).style({position:"absolute",left:"-10000px",top:"-10000px",width:"9000px",height:"9000px"});var r=e.selectAll(".js-reference-point").data([0]);r.enter().append("path").classed("js-reference-point",!0).attr("d","M0,0H1V1H0Z").style({"stroke-width":0,fill:"black"}),e.node()._cache||(e.node()._cache={}),t._tester=e,t._testref=r};var b=[],x=1e4;c.bBox=function(t){var e=t.attributes["data-bb"];if(e&&e.value)return i.Lib.extendFlat({},b[e.value]);var r=a.select("#js-plotly-tester"),n=r.node(),o=t.cloneNode(!0);n.appendChild(o),a.select(o).attr({x:0,y:0,transform:""});var s=o.getBoundingClientRect(),l=r.select(".js-reference-point").node().getBoundingClientRect();n.removeChild(o);var u={height:s.height,width:s.width,left:s.left-l.left,top:s.top-l.top,right:s.right-l.left,bottom:s.bottom-l.top};return b.length>=x&&(a.selectAll("[data-bb]").attr("data-bb",null),b=[]),t.setAttribute("data-bb",b.length),b.push(u),i.Lib.extendFlat({},u)},c.setClipUrl=function(t,e){if(!e)return void t.attr("clip-path",null);var r="#"+e,n=a.select("base");n.size()&&n.attr("href")&&(r=window.location.href+r),t.attr("clip-path","url("+r+")")}},{"../../constants/xmlns_namespaces":338,"../../plotly":366,"../../traces/scatter/make_bubble_size_func":514,"../../traces/scatter/subtypes":520,"./symbol_defs":318,d3:70,"fast-isnumeric":74}],318:[function(t,e,r){"use strict";var n=t("d3");e.exports={circle:{n:0,f:function(t){var e=n.round(t,2);return"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"}},square:{n:1,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"}},diamond:{n:2,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"Z"}},cross:{n:3,f:function(t){var e=n.round(.4*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H"+e+"V"+r+"H-"+e+"V"+e+"H-"+r+"V-"+e+"H-"+e+"V-"+r+"H"+e+"V-"+e+"H"+r+"Z"}},x:{n:4,f:function(t){var e=n.round(.8*t/Math.sqrt(2),2),r="l"+e+","+e,i="l"+e+",-"+e,a="l-"+e+",-"+e,o="l-"+e+","+e;return"M0,"+e+r+i+a+i+a+o+a+o+r+o+r+"Z"}},"triangle-up":{n:5,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+e+","+r+"H"+e+"L0,-"+i+"Z"}},"triangle-down":{n:6,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+e+",-"+r+"H"+e+"L0,"+i+"Z"}},"triangle-left":{n:7,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M"+r+",-"+e+"V"+e+"L-"+i+",0Z"}},"triangle-right":{n:8,f:function(t){var e=n.round(2*t/Math.sqrt(3),2),r=n.round(t/2,2),i=n.round(t,2);return"M-"+r+",-"+e+"V"+e+"L"+i+",0Z"}},"triangle-ne":{n:9,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+r+",-"+e+"H"+e+"V"+r+"Z"}},"triangle-se":{n:10,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+e+",-"+r+"V"+e+"H-"+r+"Z"}},"triangle-sw":{n:11,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M"+r+","+e+"H-"+e+"V-"+r+"Z"}},"triangle-nw":{n:12,f:function(t){var e=n.round(.6*t,2),r=n.round(1.2*t,2);return"M-"+e+","+r+"V-"+e+"H"+r+"Z"}},pentagon:{n:13,f:function(t){var e=n.round(.951*t,2),r=n.round(.588*t,2),i=n.round(-t,2),a=n.round(t*-.309,2),o=n.round(.809*t,2);return"M"+e+","+a+"L"+r+","+o+"H-"+r+"L-"+e+","+a+"L0,"+i+"Z"}},hexagon:{n:14,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M"+i+",-"+r+"V"+r+"L0,"+e+"L-"+i+","+r+"V-"+r+"L0,-"+e+"Z"}},hexagon2:{n:15,f:function(t){var e=n.round(t,2),r=n.round(t/2,2),i=n.round(t*Math.sqrt(3)/2,2);return"M-"+r+","+i+"H"+r+"L"+e+",0L"+r+",-"+i+"H-"+r+"L-"+e+",0Z"}},octagon:{n:16,f:function(t){var e=n.round(.924*t,2),r=n.round(.383*t,2);return"M-"+r+",-"+e+"H"+r+"L"+e+",-"+r+"V"+r+"L"+r+","+e+"H-"+r+"L-"+e+","+r+"V-"+r+"Z"}},star:{n:17,f:function(t){var e=1.4*t,r=n.round(.225*e,2),i=n.round(.951*e,2),a=n.round(.363*e,2),o=n.round(.588*e,2),s=n.round(-e,2),l=n.round(e*-.309,2),u=n.round(.118*e,2),c=n.round(.809*e,2),h=n.round(.382*e,2);return"M"+r+","+l+"H"+i+"L"+a+","+u+"L"+o+","+c+"L0,"+h+"L-"+o+","+c+"L-"+a+","+u+"L-"+i+","+l+"H-"+r+"L0,"+s+"Z"}},hexagram:{n:18,f:function(t){var e=n.round(.66*t,2),r=n.round(.38*t,2),i=n.round(.76*t,2);return"M-"+i+",0l-"+r+",-"+e+"h"+i+"l"+r+",-"+e+"l"+r+","+e+"h"+i+"l-"+r+","+e+"l"+r+","+e+"h-"+i+"l-"+r+","+e+"l-"+r+",-"+e+"h-"+i+"Z"}},"star-triangle-up":{n:19,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M-"+e+","+r+o+e+","+r+o+"0,-"+i+o+"-"+e+","+r+"Z"}},"star-triangle-down":{n:20,f:function(t){var e=n.round(t*Math.sqrt(3)*.8,2),r=n.round(.8*t,2),i=n.round(1.6*t,2),a=n.round(4*t,2),o="A "+a+","+a+" 0 0 1 ";return"M"+e+",-"+r+o+"-"+e+",-"+r+o+"0,"+i+o+e+",-"+r+"Z"}},"star-square":{n:21,f:function(t){var e=n.round(1.1*t,2),r=n.round(2*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",-"+e+i+"-"+e+","+e+i+e+","+e+i+e+",-"+e+i+"-"+e+",-"+e+"Z"}},"star-diamond":{n:22,f:function(t){var e=n.round(1.4*t,2),r=n.round(1.9*t,2),i="A "+r+","+r+" 0 0 1 ";return"M-"+e+",0"+i+"0,"+e+i+e+",0"+i+"0,-"+e+i+"-"+e+",0Z"}},"diamond-tall":{n:23,f:function(t){var e=n.round(.7*t,2),r=n.round(1.4*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},"diamond-wide":{n:24,f:function(t){var e=n.round(1.4*t,2),r=n.round(.7*t,2);return"M0,"+r+"L"+e+",0L0,-"+r+"L-"+e+",0Z"}},hourglass:{n:25,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"H-"+e+"L"+e+",-"+e+"H-"+e+"Z"},noDot:!0},bowtie:{n:26,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"V-"+e+"L-"+e+","+e+"V-"+e+"Z"},noDot:!0},"circle-cross":{n:27,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"circle-x":{n:28,f:function(t){var e=n.round(t,2),r=n.round(t/Math.sqrt(2),2);return"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r+"M"+e+",0A"+e+","+e+" 0 1,1 0,-"+e+"A"+e+","+e+" 0 0,1 "+e+",0Z"},needLine:!0,noDot:!0},"square-cross":{n:29,f:function(t){var e=n.round(t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"square-x":{n:30,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e+"M"+e+","+e+"H-"+e+"V-"+e+"H"+e+"Z"},needLine:!0,noDot:!0},"diamond-cross":{n:31,f:function(t){var e=n.round(1.3*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM0,-"+e+"V"+e+"M-"+e+",0H"+e},needLine:!0,noDot:!0},"diamond-x":{n:32,f:function(t){var e=n.round(1.3*t,2),r=n.round(.65*t,2);return"M"+e+",0L0,"+e+"L-"+e+",0L0,-"+e+"ZM-"+r+",-"+r+"L"+r+","+r+"M-"+r+","+r+"L"+r+",-"+r},needLine:!0,noDot:!0},"cross-thin":{n:33,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e},needLine:!0,noDot:!0},"x-thin":{n:34,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e+"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0},asterisk:{n:35,f:function(t){var e=n.round(1.2*t,2),r=n.round(.85*t,2);return"M0,"+e+"V-"+e+"M"+e+",0H-"+e+"M"+r+","+r+"L-"+r+",-"+r+"M"+r+",-"+r+"L-"+r+","+r},needLine:!0,noDot:!0},hash:{n:36,f:function(t){var e=n.round(t/2,2),r=n.round(t,2);return"M"+e+","+r+"V-"+r+"m-"+r+",0V"+r+"M"+r+","+e+"H-"+r+"m0,-"+r+"H"+r},needLine:!0},"y-up":{n:37,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+","+i+"L0,0M"+e+","+i+"L0,0M0,-"+r+"L0,0"},needLine:!0,noDot:!0},"y-down":{n:38,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+e+",-"+i+"L0,0M"+e+",-"+i+"L0,0M0,"+r+"L0,0"},needLine:!0,noDot:!0},"y-left":{n:39,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M"+i+","+e+"L0,0M"+i+",-"+e+"L0,0M-"+r+",0L0,0"},needLine:!0,noDot:!0},"y-right":{n:40,f:function(t){var e=n.round(1.2*t,2),r=n.round(1.6*t,2),i=n.round(.8*t,2);return"M-"+i+","+e+"L0,0M-"+i+",-"+e+"L0,0M"+r+",0L0,0"},needLine:!0,noDot:!0},"line-ew":{n:41,f:function(t){var e=n.round(1.4*t,2);return"M"+e+",0H-"+e},needLine:!0,noDot:!0},"line-ns":{n:42,f:function(t){var e=n.round(1.4*t,2);return"M0,"+e+"V-"+e},needLine:!0,noDot:!0},"line-ne":{n:43,f:function(t){var e=n.round(t,2);return"M"+e+",-"+e+"L-"+e+","+e},needLine:!0,noDot:!0},"line-nw":{n:44,f:function(t){var e=n.round(t,2);return"M"+e+","+e+"L-"+e+",-"+e},needLine:!0,noDot:!0}}},{d3:70}],319:[function(t,e,r){"use strict";e.exports={visible:{valType:"boolean"},type:{valType:"enumerated",values:["percent","constant","sqrt","data"]},symmetric:{valType:"boolean"},array:{valType:"data_array"},arrayminus:{valType:"data_array"},value:{valType:"number",min:0,dflt:10},valueminus:{valType:"number",min:0,dflt:10},traceref:{valType:"integer",min:0,dflt:0},tracerefminus:{valType:"integer",min:0,dflt:0},copy_ystyle:{valType:"boolean"},copy_zstyle:{valType:"boolean"},color:{valType:"color"},thickness:{valType:"number",min:0,dflt:2},width:{valType:"number",min:0},_deprecated:{opacity:{valType:"number"}}}},{}],320:[function(t,e,r){"use strict";function n(t,e,r,n){var a=e["error_"+n]||{},l=a.visible&&-1!==["linear","log"].indexOf(r.type),u=[];if(l){for(var c=s(a),h=0;h<t.length;h++){var f=t[h],d=f[n];if(i(r.c2l(d))){var p=c(d,h);if(i(p[0])&&i(p[1])){var g=f[n+"s"]=d-p[0],v=f[n+"h"]=d+p[1];u.push(g,v)}}}o.expand(r,u,{padded:!0})}}var i=t("fast-isnumeric"),a=t("../../plots/plots"),o=t("../../plots/cartesian/axes"),s=t("./compute_error");e.exports=function(t){for(var e=t.calcdata,r=0;r<e.length;r++){var i=e[r],s=i[0].trace;if(a.traceIs(s,"errorBarsOK")){var l=o.getFromId(t,s.xaxis),u=o.getFromId(t,s.yaxis);n(i,s,l,"x"),n(i,s,u,"y")}}}},{"../../plots/cartesian/axes":369,"../../plots/plots":413,"./compute_error":321,"fast-isnumeric":74}],321:[function(t,e,r){"use strict";function n(t,e){return"percent"===t?function(t){return Math.abs(t*e/100)}:"constant"===t?function(){return Math.abs(e)}:"sqrt"===t?function(t){return Math.sqrt(Math.abs(t))}:void 0}e.exports=function(t){var e=t.type,r=t.symmetric;if("data"===e){var i=t.array,a=t.arrayminus;return r||void 0===a?function(t,e){var r=+i[e];return[r,r]}:function(t,e){return[+a[e],+i[e]]}}var o=n(e,t.value),s=n(e,t.valueminus);return r||void 0===t.valueminus?function(t){var e=o(t);return[e,e]}:function(t){return[s(t),o(t)]}}},{}],322:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../plots/plots"),a=t("../../lib"),o=t("./attributes");e.exports=function(t,e,r,s){function l(t,e){return a.coerce(h,c,o,t,e)}var u="error_"+s.axis,c=e[u]={},h=t[u]||{},f=void 0!==h.array||void 0!==h.value||"sqrt"===h.type,d=l("visible",f);if(d!==!1){var p=l("type","array"in h?"data":"percent"),g=!0;if("sqrt"!==p&&(g=l("symmetric",!(("data"===p?"arrayminus":"valueminus")in h))),"data"===p){var v=l("array");if(v||(c.array=[]),l("traceref"),!g){var m=l("arrayminus");m||(c.arrayminus=[]),l("tracerefminus")}}else("percent"===p||"constant"===p)&&(l("value"),g||l("valueminus"));var y="copy_"+s.inherit+"style";if(s.inherit){var b=e["error_"+s.inherit];(b||{}).visible&&l(y,!(h.color||n(h.thickness)||n(h.width)))}s.inherit&&c[y]||(l("color",r),l("thickness"),l("width",i.traceIs(e,"gl3d")?0:4))}}},{"../../lib":349,"../../plots/plots":413,"./attributes":319,"fast-isnumeric":74}],323:[function(t,e,r){"use strict";function n(t,e,r){var n={x:e.c2p(t.x),y:r.c2p(t.y)};return void 0!==t.yh&&(n.yh=r.c2p(t.yh),n.ys=r.c2p(t.ys),a(n.ys)||(n.noYS=!0,n.ys=r.c2p(t.ys,!0))),void 0!==t.xh&&(n.xh=e.c2p(t.xh),n.xs=e.c2p(t.xs),a(n.xs)||(n.noXS=!0,n.xs=e.c2p(t.xs,!0))),n}var i=t("d3"),a=t("fast-isnumeric"),o=t("../../lib"),s=t("../color"),l=t("../../traces/scatter/subtypes"),u=e.exports={};u.attributes=t("./attributes"),u.supplyDefaults=t("./defaults"),u.calc=t("./calc"),u.calcFromTrace=function(t,e){for(var r=t.x||[],n=t.y,i=r.length||n.length,a=new Array(i),o=0;i>o;o++)a[o]={x:r[o],y:n[o]};return a[0].trace=t,u.calc({calcdata:[a],_fullLayout:e}),a},u.plot=function(t,e,r){var s=e.x(),u=e.y();e.plot.select(".errorlayer").selectAll("g.errorbars").remove();var c;e.plot.select(".errorlayer").selectAll("g.errorbars").data(r).enter().append("g").attr("class","errorbars").each(function(t){var e=t[0].trace,r=e.error_x,h=e.error_y,f=l.hasMarkers(e)&&e.marker.maxdisplayed>0;(h.visible||r.visible)&&i.select(this).selectAll("g").data(o.identity).enter().append("g").each(function(t){c=n(t,s,u);var e,o=i.select(this);if(!f||t.vis){if(h.visible&&a(c.x)&&a(c.yh)&&a(c.ys)){var l=h.width;e="M"+(c.x-l)+","+c.yh+"h"+2*l+"m-"+l+",0V"+c.ys,c.noYS||(e+="m-"+l+",0h"+2*l),o.append("path").classed("yerror",!0).attr("d",e)}if(r.visible&&a(c.y)&&a(c.xh)&&a(c.xs)){var d=(r.copy_ystyle?h:r).width;e="M"+c.xh+","+(c.y-d)+"v"+2*d+"m0,-"+d+"H"+c.xs,c.noXS||(e+="m0,-"+d+"v"+2*d),o.append("path").classed("xerror",!0).attr("d",e)}}})})},u.style=function(t){i.select(t).selectAll("g.errorbars").each(function(t){var e=i.select(this),r=t[0].trace,n=r.error_y||{},a=r.error_x||{};e.selectAll("g path.yerror").style("stroke-width",n.thickness+"px").call(s.stroke,n.color),a.copy_ystyle&&(a=n),e.selectAll("g path.xerror").style("stroke-width",a.thickness+"px").call(s.stroke,a.color)})},u.hoverInfo=function(t,e,r){e.error_y.visible&&(r.yerr=t.yh-t.y,e.error_y.symmetric||(r.yerrneg=t.y-t.ys)),e.error_x.visible&&(r.xerr=t.xh-t.x,e.error_x.symmetric||(r.xerrneg=t.x-t.xs))}},{"../../lib":349,"../../traces/scatter/subtypes":520,"../color":299,"./attributes":319,"./calc":320,"./defaults":322,d3:70,"fast-isnumeric":74}],324:[function(t,e,r){"use strict";var n=t("../../plots/font_attributes"),i=t("../color/attributes"),a=t("../../lib/extend").extendFlat;e.exports={bgcolor:{valType:"color"},bordercolor:{valType:"color",dflt:i.defaultLine},borderwidth:{valType:"number",min:0,dflt:0},font:a({},n,{}),traceorder:{valType:"flaglist",flags:["reversed","grouped"],extras:["normal"]},tracegroupgap:{valType:"number",min:0,dflt:10},x:{valType:"number",min:-2,max:3,dflt:1.02},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"left"},y:{valType:"number",min:-2,max:3,dflt:1},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto"}}},{"../../lib/extend":345,"../../plots/font_attributes":383,"../color/attributes":298}],325:[function(t,e,r){"use strict";e.exports={scrollBarWidth:4,scrollBarHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4}},{}],326:[function(t,e,r){"use strict";function n(t){return t.visible&&u.traceIs(t,"showLegend")}function i(t){return-1!==(t.traceorder||"").indexOf("grouped")}function a(t){return-1!==(t.traceorder||"").indexOf("reversed")}var o=t("../../plotly"),s=t("d3"),l=t("../../lib"),u=t("../../plots/plots"),c=t("../../plots/cartesian/graph_interact"),h=t("../color"),f=t("../drawing"),d=t("../../traces/scatter/subtypes"),p=t("../../traces/pie/style_one"),g=e.exports={},v=t("./constants");g.layoutAttributes=t("./attributes"),g.supplyLayoutDefaults=function(t,e,r){function o(t,e){return l.coerce(c,h,g.layoutAttributes,t,e)}for(var s,c=t.legend||{},h=e.legend={},f=0,d="normal",p=0;p<r.length;p++)s=r[p],n(s)&&(f++,u.traceIs(s,"pie")&&f++),(u.traceIs(s,"bar")&&"stack"===e.barmode||-1!==["tonextx","tonexty"].indexOf(s.fill))&&(d=i({traceorder:d})?"grouped+reversed":"reversed"),void 0!==s.legendgroup&&""!==s.legendgroup&&(d=a({traceorder:d})?"reversed+grouped":"grouped");var v=l.coerce(t,e,u.layoutAttributes,"showlegend",f>1);v!==!1&&(o("bgcolor",e.paper_bgcolor),o("bordercolor"),o("borderwidth"),l.coerceFont(o,"font",e.font),o("traceorder",d),i(e.legend)&&o("tracegroupgap"),o("x"),o("xanchor"),o("y"),o("yanchor"),l.noneOrAll(c,h,["x","y"]))},g.lines=function(t){var e=t[0].trace,r=e.visible&&e.fill&&"none"!==e.fill,n=d.hasLines(e),i=s.select(this).select(".legendfill").selectAll("path").data(r?[t]:[]);i.enter().append("path").classed("js-fill",!0),i.exit().remove(),i.attr("d","M5,0h30v6h-30z").call(f.fillGroupStyle);var a=s.select(this).select(".legendlines").selectAll("path").data(n?[t]:[]);a.enter().append("path").classed("js-line",!0).attr("d","M5,0h30"),a.exit().remove(),a.call(f.lineGroupStyle)},g.points=function(t){function e(t,e,r){var n=l.nestedProperty(o,t).get(),i=Array.isArray(n)&&e?e(n):n;if(r){if(i<r[0])return r[0];if(i>r[1])return r[1]}return i}function r(t){return t[0]}var n,i,a=t[0],o=a.trace,u=d.hasMarkers(o),c=d.hasText(o),h=d.hasLines(o);if(u||c||h){var p={},g={};u&&(p.mc=e("marker.color",r),p.mo=e("marker.opacity",l.mean,[.2,1]),p.ms=e("marker.size",l.mean,[2,16]),p.mlc=e("marker.line.color",r),p.mlw=e("marker.line.width",l.mean,[0,5]),g.marker={sizeref:1,sizemin:1,sizemode:"diameter"}),h&&(g.line={width:e("line.width",r,[0,10])}),c&&(p.tx="Aa",p.tp=e("textposition",r),p.ts=10,p.tc=e("textfont.color",r),p.tf=e("textfont.family",r)),n=[l.minExtend(a,p)],i=l.minExtend(o,g)}var v=s.select(this).select("g.legendpoints"),m=v.selectAll("path.scatterpts").data(u?n:[]);m.enter().append("path").classed("scatterpts",!0).attr("transform","translate(20,0)"),m.exit().remove(),m.call(f.pointStyle,i),u&&(n[0].mrc=3);var y=v.selectAll("g.pointtext").data(c?n:[]);y.enter().append("g").classed("pointtext",!0).append("text").attr("transform","translate(20,0)"),y.exit().remove(),y.selectAll("text").call(f.textPointStyle,i)},g.bars=function(t){var e=t[0].trace,r=e.marker||{},n=r.line||{},i=s.select(this).select("g.legendpoints").selectAll("path.legendbar").data(u.traceIs(e,"bar")?[t]:[]);i.enter().append("path").classed("legendbar",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),i.exit().remove(),i.each(function(t){var e=(t.mlw+1||n.width+1)-1,i=s.select(this);i.style("stroke-width",e+"px").call(h.fill,t.mc||r.color),e&&i.call(h.stroke,t.mlc||n.color)})},g.boxes=function(t){var e=t[0].trace,r=s.select(this).select("g.legendpoints").selectAll("path.legendbox").data(u.traceIs(e,"box")&&e.visible?[t]:[]);r.enter().append("path").classed("legendbox",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.each(function(t){var r=(t.lw+1||e.line.width+1)-1,n=s.select(this);n.style("stroke-width",r+"px").call(h.fill,t.fc||e.fillcolor),r&&n.call(h.stroke,t.lc||e.line.color)})},g.pie=function(t){var e=t[0].trace,r=s.select(this).select("g.legendpoints").selectAll("path.legendpie").data(u.traceIs(e,"pie")&&e.visible?[t]:[]);r.enter().append("path").classed("legendpie",!0).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)"),r.exit().remove(),r.size()&&r.call(p,t[0],e)},g.style=function(t){t.each(function(t){var e=s.select(this),r=e.selectAll("g.legendfill").data([t]);r.enter().append("g").classed("legendfill",!0);var n=e.selectAll("g.legendlines").data([t]);n.enter().append("g").classed("legendlines",!0);var i=e.selectAll("g.legendsymbols").data([t]);i.enter().append("g").classed("legendsymbols",!0),i.style("opacity",t[0].trace.opacity),i.selectAll("g.legendpoints").data([t]).enter().append("g").classed("legendpoints",!0)}).each(g.bars).each(g.boxes).each(g.pie).each(g.lines).each(g.points)},g.texts=function(t,e,r,n,i){function a(t){o.util.convertToTspans(t,function(){e.firstRender&&g.repositionLegend(e,i)}),t.selectAll("tspan.line").attr({x:t.attr("x")})}var l=e._fullLayout,c=r[0].trace,h=u.traceIs(c,"pie"),d=c.index,p=h?r[0].label:c.name,v=s.select(t).selectAll("text.legendtext").data([0]);v.enter().append("text").classed("legendtext",!0),v.attr({x:40,y:0,"data-unformatted":p}).style({"text-anchor":"start","-webkit-user-select":"none","-moz-user-select":"none","-ms-user-select":"none","user-select":"none"}).call(f.font,l.legend.font).text(p),e._context.editable&&!h?v.call(o.util.makeEditable).call(a).on("edit",function(t){this.attr({"data-unformatted":t}),this.text(t).call(a),this.text()||(t="    "),o.restyle(e,"name",t,d)}):v.call(a)},g.getLegendData=function(t,e){function r(t,r){if(""!==t&&i(e))-1===g.indexOf(t)?(g.push(t),v=!0,p[t]=[[r]]):p[t].push([r]);else{var n="~~i"+y;g.push(n),p[n]=[[r]],y++}}var o,s,l,c,h,f,d,p={},g=[],v=!1,m={},y=0;for(h=0;h<t.length;h++)if(o=t[h],s=o[0],l=s.trace,c=l.legendgroup,n(l)&&l.showlegend)if(u.traceIs(l,"pie"))for(m[c]||(m[c]={}),f=0;f<o.length;f++)d=o[f].label,m[c][d]||(r(c,{label:d,color:o[f].color,i:o[f].i,trace:l}),m[c][d]=!0);else r(c,s);if(!g.length)return[];var b,x,_=g.length;if(v&&i(e))for(x=new Array(_),h=0;_>h;h++)b=p[g[h]],x[h]=a(e)?b.reverse():b;else{for(x=[new Array(_)],h=0;_>h;h++)b=p[g[h]][0],x[0][a(e)?_-h-1:h]=b;_=1}return e._lgroupsLength=_,x},g.draw=function(t){function e(t){var e=T-v.scrollBarHeight-2*v.scrollBarMargin,r=y.attr("data-scroll"),i=l.constrain(r-t,Math.min(T-n.height,0),0),a=-i/(n.height-T)*e+v.scrollBarMargin;y.attr("data-scroll",i),y.attr("transform","translate(0, "+i+")"),b.call(f.setRect,n.width-(v.scrollBarWidth+v.scrollBarMargin),a,v.scrollBarWidth,v.scrollBarHeight)}var r=t._fullLayout;if(r._infolayer&&t.calcdata){var n=r.legend,a=r.showlegend&&g.getLegendData(t.calcdata,n),d=r.hiddenlabels||[];if(!r.showlegend||!a.length)return r._infolayer.selectAll(".legend").remove(),void u.autoMargin(t,"legend");"undefined"==typeof t.firstRender?t.firstRender=!0:t.firstRender&&(t.firstRender=!1);var p=r._infolayer.selectAll("svg.legend").data([0]);p.enter().append("svg").attr({"class":"legend","pointer-events":"all"});var m=p.selectAll("rect.bg").data([0]);m.enter().append("rect").attr({"class":"bg","shape-rendering":"crispEdges"}).call(h.stroke,n.bordercolor).call(h.fill,n.bgcolor).style("stroke-width",n.borderwidth+"px");var y=p.selectAll("g.scrollbox").data([0]);y.enter().append("g").attr("class","scrollbox"),y.exit().remove();var b=p.selectAll("rect.scrollbar").data([0]);b.enter().append("rect").attr({"class":"scrollbar",rx:20,ry:2,width:0,height:0}).call(h.fill,"#808BA4");var x=y.selectAll("g.groups").data(a);x.enter().append("g").attr("class","groups"),x.exit().remove(),i(n)&&x.attr("transform",function(t,e){return"translate(0,"+e*n.tracegroupgap+")"});var _=x.selectAll("g.traces").data(l.identity);_.enter().append("g").attr("class","traces"),_.exit().remove(),_.call(g.style).style("opacity",function(t){var e=t[0].trace;return u.traceIs(e,"pie")?-1!==d.indexOf(t[0].label)?.5:1:"legendonly"===e.visible?.5:1}).each(function(e,r){g.texts(this,t,e,r,_);var n=s.select(this).selectAll("rect").data([0]);n.enter().append("rect").classed("legendtoggle",!0).style("cursor","pointer").attr("pointer-events","all").call(h.fill,"rgba(0,0,0,0)"),n.on("click",function(){if(!t._dragged){var r,n,i=t._fullData,a=e[0].trace,s=a.legendgroup,l=[];if(u.traceIs(a,"pie")){var c=e[0].label,h=d.slice(),f=h.indexOf(c);-1===f?h.push(c):h.splice(f,1),o.relayout(t,"hiddenlabels",h)}else{if(""===s)l=[a.index];else for(var p=0;p<i.length;p++)r=i[p],r.legendgroup===s&&l.push(r.index);n=a.visible===!0?"legendonly":!0,o.restyle(t,"visible",n,l)}}})}),g.repositionLegend(t,_);var w=r._size,A=w.l+w.w*n.x,k=w.t+w.h*(1-n.y);"right"===n.xanchor||"auto"===n.xanchor&&n.x>=2/3?A-=n.width:("center"===n.xanchor||"auto"===n.xanchor&&n.x>1/3)&&(A-=n.width/2),"bottom"===n.yanchor||"auto"===n.yanchor&&n.y<=1/3?k-=n.height:("middle"===n.yanchor||"auto"===n.yanchor&&n.y<2/3)&&(k-=n.height/2);var M=r.height-r.margin.b,T=Math.min(M-k,n.height),E=y.attr("data-scroll")?y.attr("data-scroll"):0;if(y.attr("transform","translate(0, "+E+")"),m.attr({width:n.width-2*n.borderwidth,height:T-2*n.borderwidth,x:n.borderwidth,y:n.borderwidth}),p.call(f.setRect,A,k,n.width,T),t.firstRender&&n.height-T>0&&!t._context.staticPlot&&(m.attr({width:n.width-2*n.borderwidth+v.scrollBarWidth}),p.node().addEventListener("wheel",function(t){t.preventDefault(),e(t.deltaY/20)}),b.node().addEventListener("mousedown",function(t){function r(t){1===t.buttons&&e(t.movementY)}function n(){b.node().removeEventListener("mousemove",r),window.removeEventListener("mouseup",n)}t.preventDefault(),window.addEventListener("mousemove",r),window.addEventListener("mouseup",n)}),b.call(f.setRect,n.width-(v.scrollBarWidth+v.scrollBarMargin),v.scrollBarMargin,v.scrollBarWidth,v.scrollBarHeight)),t._context.editable){var L,S,C,P,z,R;c.dragElement({element:p.node(),prepFn:function(){C=Number(p.attr("x")),P=Number(p.attr("y")),z=Number(p.attr("width")),R=Number(p.attr("height")),c.setCursor(p)},moveFn:function(e,r){var i=t._fullLayout._size;p.call(f.setPosition,C+e,P+r),L=c.dragAlign(C+e,z,i.l,i.l+i.w,n.xanchor),S=c.dragAlign(P+r+R,-R,i.t+i.h,i.t,n.yanchor);var a=c.dragCursors(L,S,n.xanchor,n.yanchor);c.setCursor(p,a)},doneFn:function(e){c.setCursor(p),e&&void 0!==L&&void 0!==S&&o.relayout(t,{"legend.x":L,"legend.y":S})}})}}},g.repositionLegend=function(t,e){var r=t._fullLayout,n=r._size,a=r.legend,o=a.borderwidth;a.width=0,a.height=0,e.each(function(t){var e,r,n=t[0].trace,i=s.select(this),l=i.selectAll(".legendtoggle"),u=i.selectAll(".legendtext"),c=i.selectAll(".legendtext>tspan"),h=1.3*a.font.size,d=c[0].length||1,p=u.node()&&f.bBox(u.node()).width,g=i.select("g[class*=math-group]");if(!n.showlegend)return void i.remove();if(g.node()){var v=f.bBox(g.node());h=v.height,p=v.width,g.attr("transform","translate(0,"+h/4+")")}else e=h*(.3+(1-d)/2),u.attr("y",e),c.attr("y",e);r=Math.max(h*d,16)+3,i.attr("transform","translate("+o+","+(5+o+a.height+r/2)+")"),l.attr({x:0,y:-r/2,height:r}),a.height+=r,a.width=Math.max(a.width,p||0)}),a.width+=45+2*o,a.height+=10+2*o,i(a)&&(a.height+=(a._lgroupsLength-1)*a.tracegroupgap),e.selectAll(".legendtoggle").attr("width",(t._context.editable?0:a.width)+40);var l=n.l+n.w*a.x,c=n.t+n.h*(1-a.y),h="left";"right"===a.xanchor||"auto"===a.xanchor&&a.x>=2/3?(l-=a.width,h="right"):("center"===a.xanchor||"auto"===a.xanchor&&a.x>1/3)&&(l-=a.width/2,h="center");var d="top";"bottom"===a.yanchor||"auto"===a.yanchor&&a.y<=1/3?(c-=a.height,d="bottom"):("middle"===a.yanchor||"auto"===a.yanchor&&a.y<2/3)&&(c-=a.height/2,d="middle"),a.width=Math.ceil(a.width),a.height=Math.ceil(a.height),l=Math.round(l),c=Math.round(c),u.autoMargin(t,"legend",{x:a.x,y:a.y,l:a.width*({right:1,center:.5}[h]||0),r:a.width*({left:1,center:.5}[h]||0),b:a.height*({top:1,middle:.5}[d]||0),t:a.height*({bottom:1,middle:.5}[d]||0)})}},{"../../lib":349,"../../plotly":366,"../../plots/cartesian/graph_interact":374,"../../plots/plots":413,"../../traces/pie/style_one":500,"../../traces/scatter/subtypes":520,"../color":299,"../drawing":317,"./attributes":324,"./constants":325,d3:70}],327:[function(t,e,r){"use strict";function n(t,e){var r=e.currentTarget,n=r.getAttribute("data-attr"),i=r.getAttribute("data-val")||!0,a=t._fullLayout,o={};if("zoom"===n)for(var s,l,c,h="in"===i?.5:2,f=(1+h)/2,d=(1-h)/2,g=u.Axes.list(t,null,!0),v=0;v<g.length;v++)s=g[v],s.fixedrange||(l=s._name,"auto"===i?o[l+".autorange"]=!0:"reset"===i?void 0===s._rangeInitial?o[l+".autorange"]=!0:o[l+".range"]=s._rangeInitial.slice():(c=s.range,o[l+".range"]=[f*c[0]+d*c[1],f*c[1]+d*c[0]]));else"hovermode"!==n||"x"!==i&&"y"!==i||(i=a._isHoriz?"y":"x",r.setAttribute("data-val",i)),o[n]=i;u.relayout(t,o).then(function(){"dragmode"===n&&(a._hasCartesian&&u.Fx.setCursor(a._paper.select(".nsewdrag"),p[i]),u.Fx.supplyLayoutDefaults(t.layout,a,t._fullData),u.Fx.init(t))})}function i(t,e){for(var r=e.currentTarget,n=r.getAttribute("data-attr"),i=r.getAttribute("data-val")||!0,a=t._fullLayout,o=u.Plots.getSubplotIds(a,"gl3d"),s={},l=n.split("."),c=0;c<o.length;c++)s[o[c]+"."+l[1]]=i;u.relayout(t,s)}function a(t,e){for(var r=e.currentTarget,n=r.getAttribute("data-attr"),i=t._fullLayout,a=u.Plots.getSubplotIds(i,"gl3d"),o=0;o<a.length;o++){var s=a[o],l=i[s],c=l._scene;"resetDefault"===n?c.setCameraToDefault():"resetLastSave"===n&&c.setCamera(l.camera)}}function o(t,e){var r=e.currentTarget,n=r._previousVal||!1,i=t.layout,a=t._fullLayout,o=u.Plots.getSubplotIds(a,"gl3d"),s=["xaxis","yaxis","zaxis"],l=["showspikes","spikesides","spikethickness","spikecolor"],h={},f={},d={};if(n)d=c.extendDeep(i,n),r._previousVal=null;else{d={"allaxes.showspikes":!1};for(var p=0;p<o.length;p++){var g=o[p],v=a[g],m=h[g]={};m.hovermode=v.hovermode,d[g+".hovermode"]=!1;for(var y=0;3>y;y++){var b=s[y];f=m[b]={};for(var x=0;x<l.length;x++){var _=l[x];f[_]=v[b][_]}}}r._previousVal=c.extendDeep({},h)}u.relayout(t,d)}function s(t,e){for(var r=e.currentTarget,n=r.getAttribute("data-attr"),i=r.getAttribute("data-val")||!0,a=t._fullLayout,o=u.Plots.getSubplotIds(a,"geo"),s=0;s<o.length;s++){var l=a[o[s]]._geo;if("zoom"===n){var c=l.projection.scale(),h="in"===i?2*c:.5*c;l.projection.scale(h),l.zoom.scale(h),l.render()}else"reset"===n&&l.zoomReset()}}function l(t){var e,r=t._fullLayout;e=r._hasCartesian?r._isHoriz?"y":"x":"closest";var n=t._fullLayout.hovermode?!1:e;u.relayout(t,"hovermode",n)}var u=t("../../plotly"),c=t("../../lib"),h=t("../../snapshot"),f=t("../../../build/ploticon"),d=e.exports={};d.toImage={name:"toImage",title:"Download plot as a png",icon:f.camera,click:function(t){var e="png";if(c.isIE())return void c.notifier("Snapshotting is unavailable in Internet Explorer. Consider exporting your images using the Plotly Cloud","long");if(t._snapshotInProgress)return void c.notifier("Snapshotting is still in progress - please hold","long");t._snapshotInProgress=!0,c.notifier("Taking snapshot - this may take a few seconds","long");var r=h.toImage(t,{format:e}),n=t.fn||"newplot";n+="."+e,r.once("success",function(e){t._snapshotInProgress=!1;var i=document.createElement("a");i.href=e,i.download=n,document.body.appendChild(i),i.click(),document.body.removeChild(i),r.clean()}),r.once("error",function(n){t._snapshotInProgress=!1,c.notifier("Sorry there was a problem downloading your "+e,"long"),console.error(n),r.clean()})}},d.sendDataToCloud={name:"sendDataToCloud",title:"Save and edit plot in cloud",icon:f.disk,click:function(t){u.Plots.sendDataToCloud(t)}},d.zoom2d={name:"zoom2d",title:"Zoom",attr:"dragmode",val:"zoom",icon:f.zoombox,click:n},d.pan2d={name:"pan2d",title:"Pan",attr:"dragmode",val:"pan",icon:f.pan,click:n},d.select2d={name:"select2d",title:"Box Select",attr:"dragmode",val:"select",icon:f.selectbox,click:n},d.lasso2d={name:"lasso2d",title:"Lasso Select",attr:"dragmode",val:"lasso",icon:f.lasso,click:n},d.zoomIn2d={name:"zoomIn2d",title:"Zoom in",attr:"zoom",val:"in",icon:f.zoom_plus,click:n},d.zoomOut2d={name:"zoomOut2d",title:"Zoom out",attr:"zoom",val:"out",icon:f.zoom_minus,click:n},d.autoScale2d={name:"autoScale2d",title:"Autoscale",attr:"zoom",val:"auto",icon:f.autoscale,click:n},d.resetScale2d={name:"resetScale2d",title:"Reset axes",attr:"zoom",val:"reset",icon:f.home,click:n},d.hoverClosestCartesian={name:"hoverClosestCartesian",title:"Show closest data on hover",attr:"hovermode",val:"closest",icon:f.tooltip_basic,gravity:"ne",click:n},d.hoverCompareCartesian={name:"hoverCompareCartesian",title:"Compare data on hover",attr:"hovermode",val:function(t){return t._fullLayout._isHoriz?"y":"x"},icon:f.tooltip_compare,gravity:"ne",click:n};var p={pan:"move",zoom:"crosshair",select:"crosshair",lasso:"crosshair"};d.zoom3d={name:"zoom3d",title:"Zoom",
+attr:"scene.dragmode",val:"zoom",icon:f.zoombox,click:i},d.pan3d={name:"pan3d",title:"Pan",attr:"scene.dragmode",val:"pan",icon:f.pan,click:i},d.orbitRotation={name:"orbitRotation",title:"orbital rotation",attr:"scene.dragmode",val:"orbit",icon:f["3d_rotate"],click:i},d.tableRotation={name:"tableRotation",title:"turntable rotation",attr:"scene.dragmode",val:"turntable",icon:f["z-axis"],click:i},d.resetCameraDefault3d={name:"resetCameraDefault3d",title:"Reset camera to default",attr:"resetDefault",icon:f.home,click:a},d.resetCameraLastSave3d={name:"resetCameraLastSave3d",title:"Reset camera to last save",attr:"resetLastSave",icon:f.movie,click:a},d.hoverClosest3d={name:"hoverClosest3d",title:"Toggle show closest data on hover",attr:"hovermode",val:null,toggle:!0,icon:f.tooltip_basic,gravity:"ne",click:o},d.zoomInGeo={name:"zoomInGeo",title:"Zoom in",attr:"zoom",val:"in",icon:f.zoom_plus,click:s},d.zoomOutGeo={name:"zoomOutGeo",title:"Zoom out",attr:"zoom",val:"out",icon:f.zoom_minus,click:s},d.resetGeo={name:"resetGeo",title:"Reset",attr:"reset",val:null,icon:f.autoscale,click:s},d.hoverClosestGeo={name:"hoverClosestGeo",title:"Toggle show closest data on hover",attr:"hovermode",val:null,toggle:!0,icon:f.tooltip_basic,gravity:"ne",click:l},d.hoverClosestGl2d={name:"hoverClosestGl2d",title:"Toggle show closest data on hover",attr:"hovermode",val:null,toggle:!0,icon:f.tooltip_basic,gravity:"ne",click:l},d.hoverClosestPie={name:"hoverClosestPie",title:"Toggle show closest data on hover",attr:"hovermode",val:"closest",icon:f.tooltip_basic,gravity:"ne",click:l},d.toggleHover={name:"toggleHover",title:"Toggle show closest data on hover",attr:"hovermode",val:null,toggle:!0,icon:f.tooltip_basic,gravity:"ne",click:function(t,e){l(t),o(t,e)}},d.resetViews={name:"resetViews",title:"Reset views",icon:f.home,click:function(t,e){var r=e.currentTarget;r.setAttribute("data-attr","zoom"),r.setAttribute("data-val","reset"),n(t,e),r.setAttribute("data-attr","resetLastSave"),a(t,e)}}},{"../../../build/ploticon":2,"../../lib":349,"../../plotly":366,"../../snapshot":420}],328:[function(t,e,r){"use strict";function n(t){this.container=t.container,this.element=document.createElement("div"),this.update(t.graphInfo,t.buttons),this.container.appendChild(this.element)}function i(t,e){var r=t._fullLayout,i=new n({graphInfo:t,container:r._paperdiv.node(),buttons:e});return r._privateplot&&a.select(i.element).append("span").classed("badge-private float--left",!0).text("PRIVATE"),i}var a=t("d3"),o=t("../../lib"),s=t("../../../build/ploticon"),l=n.prototype;l.update=function(t,e){this.graphInfo=t;var r=this.graphInfo._context;"hover"===r.displayModeBar?this.element.className="modebar modebar--hover":this.element.className="modebar";var n=!this.hasButtons(e),i=this.hasLogo!==r.displaylogo;(n||i)&&(this.removeAllButtons(),this.updateButtons(e),r.displaylogo&&(this.element.appendChild(this.getLogo()),this.hasLogo=!0)),this.updateActiveButton()},l.updateButtons=function(t){var e=this;this.buttons=t,this.buttonElements=[],this.buttonsNames=[],this.buttons.forEach(function(t){var r=e.createGroup();t.forEach(function(t){var n=t.name;if(!n)throw new Error("must provide button 'name' in button config");if(-1!==e.buttonsNames.indexOf(n))throw new Error("button name '"+n+"' is taken");e.buttonsNames.push(n);var i=e.createButton(t);e.buttonElements.push(i),r.appendChild(i)}),e.element.appendChild(r)})},l.createGroup=function(){var t=document.createElement("div");return t.className="modebar-group",t},l.createButton=function(t){var e=this,r=document.createElement("a");r.setAttribute("rel","tooltip"),r.className="modebar-btn";var n=t.title;void 0===n&&(n=t.name),(n||0===n)&&r.setAttribute("data-title",n),void 0!==t.attr&&r.setAttribute("data-attr",t.attr);var i=t.val;void 0!==i&&("function"==typeof i&&(i=i(this.graphInfo)),r.setAttribute("data-val",i));var a=t.click;if("function"!=typeof a)throw new Error("must provide button 'click' function in button config");return r.addEventListener("click",function(r){t.click(e.graphInfo,r),e.updateActiveButton(r.currentTarget)}),r.setAttribute("data-toggle",t.toggle||!1),t.toggle&&r.classList.add("active"),r.appendChild(this.createIcon(t.icon||s.question)),r.setAttribute("data-gravity",t.gravity||"n"),r},l.createIcon=function(t){var e=t.ascent-t.descent,r="http://www.w3.org/2000/svg",n=document.createElementNS(r,"svg"),i=document.createElementNS(r,"path");return n.setAttribute("height","1em"),n.setAttribute("width",t.width/e+"em"),n.setAttribute("viewBox",[0,0,t.width,e].join(" ")),i.setAttribute("d",t.path),i.setAttribute("transform","matrix(1 0 0 -1 0 "+t.ascent+")"),n.appendChild(i),n},l.updateActiveButton=function(t){var e=this.graphInfo._fullLayout,r=void 0!==t?t.getAttribute("data-attr"):null;this.buttonElements.forEach(function(t){var n=t.getAttribute("data-val")||!0,i=t.getAttribute("data-attr"),s="true"===t.getAttribute("data-toggle"),l=a.select(t);if(s)i===r&&l.classed("active",!l.classed("active"));else{var u=null===i?i:o.nestedProperty(e,i).get();l.classed("active",u===n)}})},l.hasButtons=function(t){var e=this.buttons;if(!e)return!1;if(t.length!==e.length)return!1;for(var r=0;r<t.length;++r){if(t[r].length!==e[r].length)return!1;for(var n=0;n<t[r].length;n++)if(t[r][n].name!==e[r][n].name)return!1}return!0},l.getLogo=function(){var t=this.createGroup(),e=document.createElement("a");return e.href="https://plot.ly/",e.target="_blank",e.setAttribute("data-title","Produced with Plotly"),e.className="modebar-btn plotlyjsicon modebar-btn--logo",e.appendChild(this.createIcon(s.plotlylogo)),t.appendChild(e),t},l.removeAllButtons=function(){for(;this.element.firstChild;)this.element.removeChild(this.element.firstChild);this.hasLogo=!1},l.destroy=function(){o.removeElement(this.container.querySelector(".modebar"))},e.exports=i},{"../../../build/ploticon":2,"../../lib":349,d3:70}],329:[function(t,e,r){"use strict";function n(t,e,r){function n(t){for(var r=[],n=0;n<t.length;n++){var i=t[n];-1===e.indexOf(i)&&r.push(h[i])}g.push(r)}var s=t._fullLayout,l=t._fullData,u=s._hasCartesian,c=s._hasGL3D,f=s._hasGeo,d=s._hasPie,p=s._hasGL2D,g=[];if(n(["toImage","sendDataToCloud"]),(u||p||d)+f+c>1)return n(["resetViews","toggleHover"]),o(g,r);c&&(n(["zoom3d","pan3d","orbitRotation","tableRotation"]),n(["resetCameraDefault3d","resetCameraLastSave3d"]),n(["hoverClosest3d"])),f&&(n(["zoomInGeo","zoomOutGeo","resetGeo"]),n(["hoverClosestGeo"]));var v=i(s),m=[];return!u&&!p||v||(m=["zoom2d","pan2d"]),u&&a(l)&&(m.push("select2d"),m.push("lasso2d")),m.length&&n(m),!u&&!p||v||n(["zoomIn2d","zoomOut2d","autoScale2d","resetScale2d"]),u&&d?n(["toggleHover"]):p?n(["hoverClosestGl2d"]):u?n(["hoverClosestCartesian","hoverCompareCartesian"]):d&&n(["hoverClosestPie"]),o(g,r)}function i(t){for(var e=l.Axes.list({_fullLayout:t},null,!0),r=!0,n=0;n<e.length;n++)if(!e[n].fixedrange){r=!1;break}return r}function a(t){for(var e=!1,r=0;r<t.length&&!e;r++){var n=t[r];n._module&&n._module.selectPoints&&("scatter"===n.type?(u.hasMarkers(n)||u.hasText(n))&&(e=!0):e=!0)}return e}function o(t,e){if(e.length)if(Array.isArray(e[0]))for(var r=0;r<e.length;r++)t.push(e[r]);else t.push(e);return t}function s(t){for(var e=0;e<t.length;e++)for(var r=t[e],n=0;n<r.length;n++){var i=r[n];if("string"==typeof i){if(void 0===h[i])throw new Error(["*modeBarButtons* configuration options","invalid button name"].join(" "));t[e][n]=h[i]}}return t}var l=t("../../plotly"),u=t("../../traces/scatter/subtypes"),c=t("./"),h=t("./buttons");e.exports=function(t){var e=t._fullLayout,r=t._context,i=e._modeBar;if(!r.displayModeBar)return void(i&&(i.destroy(),delete e._modeBar));if(!Array.isArray(r.modeBarButtonsToRemove))throw new Error(["*modeBarButtonsToRemove* configuration options","must be an array."].join(" "));if(!Array.isArray(r.modeBarButtonsToAdd))throw new Error(["*modeBarButtonsToAdd* configuration options","must be an array."].join(" "));var a,o=r.modeBarButtons;a=Array.isArray(o)&&o.length?s(o):n(t,r.modeBarButtonsToRemove,r.modeBarButtonsToAdd),i?i.update(t,a):e._modeBar=c(t,a)}},{"../../plotly":366,"../../traces/scatter/subtypes":520,"./":328,"./buttons":327}],330:[function(t,e,r){"use strict";var n=t("../annotations/attributes"),i=t("../../traces/scatter/attributes"),a=t("../../lib/extend").extendFlat,o=i.line;e.exports={_isLinkedToArray:!0,type:{valType:"enumerated",values:["circle","rect","path","line"]},xref:a({},n.xref,{}),x0:{valType:"any"},x1:{valType:"any"},yref:a({},n.yref,{}),y0:{valType:"any"},y1:{valType:"any"},path:{valType:"string"},opacity:{valType:"number",min:0,max:1,dflt:1},line:{color:o.color,width:o.width,dash:o.dash},fillcolor:{valType:"color",dflt:"rgba(0,0,0,0)"}}},{"../../lib/extend":345,"../../traces/scatter/attributes":502,"../annotations/attributes":296}],331:[function(t,e,r){"use strict";function n(t,e){function r(e,r){return u.Lib.coerce(t,n,h.layoutAttributes,e,r)}var n={};r("opacity"),r("fillcolor"),r("line.color"),r("line.width"),r("line.dash");for(var i=t.path?"path":"rect",o=r("type",i),s=["x","y"],l=0;2>l;l++){var c=s[l],f={_fullLayout:e},d=u.Axes.coerceRef(t,n,f,c);if("path"!==o){var p=.25,g=.75;if("paper"!==d){var v=u.Axes.getFromId(f,d),m=a(v);p=m(v.range[0]+p*(v.range[1]-v.range[0])),g=m(v.range[0]+g*(v.range[1]-v.range[0]))}r(c+"0",p),r(c+"1",g)}}return"path"===o?r("path"):u.Lib.noneOrAll(t,n,["x0","x1","y0","y1"]),n}function i(t){return"category"===t.type?t.c2l:t.d2l}function a(t){return"category"===t.type?t.l2c:t.l2d}function o(t){return function(e){return t(e.replace("_"," "))}}function s(t,e){var r,n,a,s,l=e.type,c=u.Axes.getFromId(t,e.xref),f=u.Axes.getFromId(t,e.yref),d=t._fullLayout._size;if(c?(r=i(c),n=function(t){return c._offset+c.l2p(r(t,!0))}):n=function(t){return d.l+d.w*t},f?(a=i(f),s=function(t){return f._offset+f.l2p(a(t,!0))}):s=function(t){return d.t+d.h*(1-t)},"path"===l)return c&&"date"===c.type&&(n=o(n)),f&&"date"===f.type&&(s=o(s)),h.convertPath(e.path,n,s);var p=n(e.x0),g=n(e.x1),v=s(e.y0),m=s(e.y1);if("line"===l)return"M"+p+","+v+"L"+g+","+m;if("rect"===l)return"M"+p+","+v+"H"+g+"V"+m+"H"+p+"Z";var y=(p+g)/2,b=(v+m)/2,x=Math.abs(y-p),_=Math.abs(b-v),w="A"+x+","+_,A=y+x+","+b,k=y+","+(b-_);return"M"+A+w+" 0 1,1 "+k+w+" 0 0,1 "+A+"Z"}function l(t,e,r,n,i){var a="category"===t.type?Number:t.d2c;if(void 0!==e)return[a(e),a(r)];if(n){var s,l,u,c,h,p=1/0,g=-(1/0),v=n.match(f);for("date"===t.type&&(a=o(a)),s=0;s<v.length;s++)l=v[s],u=i[l.charAt(0)].drawn,void 0!==u&&(c=v[s].substr(1).match(d),!c||c.length<u||(h=a(c[u]),p>h&&(p=h),h>g&&(g=h)));return g>=p?[p,g]:void 0}}var u=t("../../plotly"),c=t("fast-isnumeric"),h=e.exports={};h.layoutAttributes=t("./attributes"),h.supplyLayoutDefaults=function(t,e){for(var r=t.shapes||[],i=e.shapes=[],a=0;a<r.length;a++)i.push(n(r[a]||{},e))},h.drawAll=function(t){var e=t._fullLayout;e._shapelayer.selectAll("path").remove();for(var r=0;r<e.shapes.length;r++)h.draw(t,r)},h.add=function(t){var e=t._fullLayout.shapes.length;u.relayout(t,"shapes["+e+"]","add")},h.draw=function(t,e,r,o){var l,f=t.layout,d=t._fullLayout;if(!c(e)||-1===e){if(!e&&Array.isArray(o))return f.shapes=o,h.supplyLayoutDefaults(f,d),void h.drawAll(t);if("remove"===o)return delete f.shapes,d.shapes=[],void h.drawAll(t);if(r&&"add"!==o){for(l=0;l<d.shapes.length;l++)h.draw(t,l,r,o);return}e=d.shapes.length,d.shapes.push({})}if(!r&&o){if("remove"===o){for(d._shapelayer.selectAll('[data-index="'+e+'"]').remove(),d.shapes.splice(e,1),f.shapes.splice(e,1),l=e;l<d.shapes.length;l++)d._shapelayer.selectAll('[data-index="'+(l+1)+'"]').attr("data-index",String(l)),h.draw(t,l);return}if("add"===o||u.Lib.isPlainObject(o)){d.shapes.splice(e,0,{});var p=u.Lib.isPlainObject(o)?u.Lib.extendFlat({},o):{text:"New text"};for(f.shapes?f.shapes.splice(e,0,p):f.shapes=[p],l=d.shapes.length-1;l>e;l--)d._shapelayer.selectAll('[data-index="'+(l-1)+'"]').attr("data-index",String(l)),h.draw(t,l)}}d._shapelayer.selectAll('[data-index="'+e+'"]').remove();var g=f.shapes[e];if(g){var v={xref:g.xref,yref:g.yref},m={};"string"==typeof r&&r?m[r]=o:u.Lib.isPlainObject(r)&&(m=r);var y=Object.keys(m);for(l=0;l<m.length;l++){var b=y[l];u.Lib.nestedProperty(g,b).set(m[b])}var x=["x0","x1","y0","y1"];for(l=0;4>l;l++){var _=x[l];if(void 0===m[_]&&void 0!==g[_]){var w,A=_.charAt(0),k=u.Axes.getFromId(t,u.Axes.coerceRef(v,{},t,A)),M=u.Axes.getFromId(t,u.Axes.coerceRef(g,{},t,A)),T=g[_];void 0!==m[A+"ref"]&&(k?(w=i(k)(T),T=(w-k.range[0])/(k.range[1]-k.range[0])):T=(T-M.domain[0])/(M.domain[1]-M.domain[0]),M?(w=M.range[0]+T*(M.range[1]-M.range[0]),T=a(M)(w)):T=k.domain[0]+T*(k.domain[1]-k.domain[0])),g[_]=T}}var E=n(g,d);d.shapes[e]=E;var L={"data-index":String(e),"fill-rule":"evenodd",d:s(t,E)},S=(E.xref+E.yref).replace(/paper/g,""),C=E.line.width?E.line.color:"rgba(0,0,0,0)",P=d._shapelayer.append("path").attr(L).style("opacity",E.opacity).call(u.Color.stroke,C).call(u.Color.fill,E.fillcolor).call(u.Drawing.dashLine,E.line.dash,E.line.width);S&&P.call(u.Drawing.setClipUrl,"clip"+d._uid+S)}};var f=/[MLHVQCTSZ][^MLHVQCTSZ]*/g,d=/[^\s,]+/g,p={M:{0:!0,drawn:0},L:{0:!0,drawn:0},H:{0:!0,drawn:0},V:{},Q:{0:!0,2:!0,drawn:2},C:{0:!0,2:!0,4:!0,drawn:4},T:{0:!0,drawn:0},S:{0:!0,2:!0,drawn:2},Z:{}},g={M:{1:!0,drawn:1},L:{1:!0,drawn:1},H:{},V:{0:!0,drawn:0},Q:{1:!0,3:!0,drawn:3},C:{1:!0,3:!0,5:!0,drawn:5},T:{1:!0,drawn:1},S:{1:!0,3:!0,drawn:5},Z:{}},v={M:2,L:2,H:1,V:1,Q:4,C:6,T:2,S:4,Z:0};h.convertPath=function(t,e,r){return t.replace(f,function(t){var n=0,i=t.charAt(0),a=p[i],o=g[i],s=v[i],l=t.substr(1).replace(d,function(t){return a[n]?t=e(t):o[n]&&(t=r(t)),n++,n>s&&(t="X"),t});return n>s&&(l=l.replace(/[\s,]*X.*/,""),console.log("ignoring extra params in segment "+t)),i+l})},h.calcAutorange=function(t){var e,r,n,i,a,o=t._fullLayout,s=o.shapes;if(s.length&&t._fullData.length)for(e=0;e<s.length;e++)r=s[e],n=r.line.width/2,"paper"!==r.xref&&(i=u.Axes.getFromId(t,r.xref),a=l(i,r.x0,r.x1,r.path,p),a&&u.Axes.expand(i,a,{ppad:n})),"paper"!==r.yref&&(i=u.Axes.getFromId(t,r.yref),a=l(i,r.y0,r.y1,r.path,g),a&&u.Axes.expand(i,a,{ppad:n}))}},{"../../plotly":366,"./attributes":330,"fast-isnumeric":74}],332:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../plotly"),o=t("../../plots/plots"),s=t("../../lib"),l=t("../drawing"),u=t("../color"),c=t("../../lib/svg_text_utils"),h=t("../../plots/cartesian/axis_ids"),f=e.exports={};f.draw=function(t,e){function r(t){s.syncOrAsync([f,d],t)}function f(e){return e.attr("transform",R?"rotate("+[R.rotate,m.x,m.y]+") translate(0, "+R.offset+")":null),e.style({"font-family":C,"font-size":n.round(P,2)+"px",fill:u.rgb(z),opacity:j*u.opacity(z),"font-weight":o.fontWeight}).attr(m).call(c.convertToTspans).attr(m),e.selectAll("tspan.line").attr(m),o.previousPromises(t)}function d(t){var e=n.select(t.node().parentNode);if(O&&O.selection&&O.side&&F){e.attr("transform",null);var r=0,a={left:"right",right:"left",top:"bottom",bottom:"top"}[O.side],o=-1!==["left","top"].indexOf(O.side)?-1:1,u=i(O.pad)?O.pad:2,c=l.bBox(e.node()),h={left:0,top:0,right:y.width,bottom:y.height},f=_?y.width:(h[O.side]-c[O.side])*("left"===O.side||"top"===O.side?-1:1);if(0>f?r=f:(c.left-=O.offsetLeft,c.right-=O.offsetLeft,c.top-=O.offsetTop,c.bottom-=O.offsetTop,O.selection.each(function(){var t=l.bBox(this);s.bBoxIntersect(c,t,u)&&(r=Math.max(r,o*(t[O.side]-c[a])+u))}),r=Math.min(f,r)),r>0||0>f){var d={left:[-r,0],right:[r,0],top:[0,-r],bottom:[0,r]}[O.side];e.attr("transform","translate("+d+")")}}}function p(){j=0,N=!0,F=V,y._infolayer.select("."+e).attr({"data-unformatted":F}).text(F).on("mouseover.opacity",function(){n.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){n.select(this).transition().duration(1e3).style("opacity",0)})}var g,v,m,y=t._fullLayout,b=y._size,x=e.charAt(0),_="cb"===e.substr(1,2);if(_){var w=e.substr(3).replace("title","");t._fullData.some(function(e,r){return e.uid===w?(g=r,v=t.calcdata[r][0].t.cb.axis,!0):void 0})}else v=y[h.id2name(e.replace("title",""))]||y;var A,k,M,T,E,L=v===y?"title":v._name+".title",S=_?"colorscale":(v._id||x).toUpperCase()+" axis",C=v.titlefont.family,P=v.titlefont.size,z=v.titlefont.color,R="",O={selection:n.select(t).selectAll("g."+v._id+"tick"),side:v.side},I=_?0:1.5;_?(O.offsetLeft=b.l,O.offsetTop=b.t):O.selection.size()&&(E=n.select(O.selection.node().parentNode).attr("transform").match(/translate\(([-\.\d]+),([-\.\d]+)\)/),E&&(O.offsetLeft=+E[1],O.offsetTop=+E[2])),_&&v.titleside?(A=b.l+v.titlex*b.w,k=b.t+(1-v.titley)*b.h+("top"===v.titleside?3+.75*P:-3-.25*P),m={x:A,y:k,"text-anchor":"start"},O={},e="h"+e):"x"===x?(M=v,T="free"===M.anchor?{_offset:b.t+(1-(M.position||0))*b.h,_length:0}:h.getFromId(t,M.anchor),A=M._offset+M._length/2,k=T._offset+("top"===M.side?-10-P*(I+(M.showticklabels?1:0)):T._length+10+P*(I+(M.showticklabels?1.5:.5))),m={x:A,y:k,"text-anchor":"middle"},O.side||(O.side="bottom")):"y"===x?(T=v,M="free"===T.anchor?{_offset:b.l+(T.position||0)*b.w,_length:0}:h.getFromId(t,T.anchor),k=T._offset+T._length/2,A=M._offset+("right"===T.side?M._length+10+P*(I+(T.showticklabels?1:.5)):-10-P*(I+(T.showticklabels?.5:0))),m={x:A,y:k,"text-anchor":"middle"},R={rotate:"-90",offset:0},O.side||(O.side="left")):(S="Plot",P=y.titlefont.size,A=y.width/2,k=y._size.t/2,m={x:A,y:k,"text-anchor":"middle"},O={});var j=1,N=!1,F=v.title.trim();""===F&&(j=0),F.match(/Click to enter .+ title/)&&(j=.2,N=!0);var B;if(_){B=n.select(t).selectAll("."+v._id.substr(1)+" .cbtitle");var D="h"===e.charAt(0)?e.substr(1):"h"+e;B.selectAll("."+D+",."+D+"-math-group").remove()}else B=y._infolayer.selectAll(".g-"+e).data([0]),B.enter().append("g").classed("g-"+e,!0);var U=B.selectAll("text").data([0]);U.enter().append("text"),U.text(F).attr("class",e),U.attr({"data-unformatted":F}).call(r);var V="Click to enter "+S.replace(/\d+/,"")+" title";t._context.editable?(F||p(),U.call(c.makeEditable).on("edit",function(e){if(_){var r=t._fullData[g];o.traceIs(r,"markerColorscale")?a.restyle(t,"marker.colorbar.title",e,g):a.restyle(t,"colorbar.title",e,g)}else a.relayout(t,L,e)}).on("cancel",function(){this.text(this.attr("data-unformatted")).call(r)}).on("input",function(t){this.text(t||" ").attr(m).selectAll("tspan.line").attr(m)})):(!F||F.match(/Click to enter .+ title/))&&U.remove(),U.classed("js-placeholder",N)}},{"../../lib":349,"../../lib/svg_text_utils":360,"../../plotly":366,"../../plots/cartesian/axis_ids":371,"../../plots/plots":413,"../color":299,"../drawing":317,d3:70,"fast-isnumeric":74}],333:[function(t,e,r){"use strict";e.exports={DZA:"algeria",AGO:"angola",EGY:"egypt",BGD:"bangladesh|^(?=.*east).*paki?stan",NER:"\\bniger(?!ia)",LIE:"liechtenstein",NAM:"namibia",BGR:"bulgaria",BOL:"bolivia",GHA:"ghana|gold.?coast",CCK:"\\bcocos|keeling",PAK:"^(?!.*east).*paki?stan",CPV:"verde",JOR:"jordan",LBR:"liberia",LBY:"libya",MYS:"malaysia",IOT:"british.?indian.?ocean",PRI:"puerto.?rico",MYT:"mayotte",PRK:"^(?=.*democrat).*\\bkorea|^(?=.*people).*\\bkorea|^(?=.*north).*\\bkorea|\\bd\\.?p\\.?r\\.?k",PSE:"palestin|\\bgaza|west.?bank",TZA:"tanzania",BWA:"botswana|bechuana",KHM:"cambodia|kampuchea|khmer|^p\\.?r\\.?k\\.?$",UMI:"minor.?outlying.?is",TTO:"trinidad|tobago",PRY:"paraguay",HKG:"hong.?kong",SAU:"\\bsa\\w*.?arabia",LBN:"lebanon",SVN:"slovenia",BFA:"burkina|\\bfaso|upper.?volta",SVK:"^(?!.*cze).*slovak",MRT:"mauritania",HRV:"croatia",CHL:"\\bchile",CHN:"^(?!.*\\bmac)(?!.*\\bhong)(?!.*\\btai).*china|^p\\.?r\\.?c\\.?$",KNA:"kitts|\\bnevis",JAM:"jamaica",SMR:"san.?marino",GIB:"gibraltar",DJI:"djibouti",GIN:"^(?!.*eq)(?!.*span)(?!.*bissau)(?!.*portu)(?!.*new).*guinea",FIN:"finland",URY:"uruguay",VAT:"holy.?see|vatican|papal.?st",STP:"\\bs(a|\xe3)o.?tom(e|\xe9)",SYC:"seychell",NPL:"nepal",CXR:"christmas",LAO:"\\blaos?\\b",YEM:"^(?!.*arab)(?!.*north)(?!.*sana)(?!.*peo)(?!.*dem)(?!.*south)(?!.*aden)(?!.*\\bp\\.?d\\.?r).*yemen",BVT:"bouvet",ZAF:"\\bs\\w*.?africa",KIR:"kiribati",PHL:"philippines",SXM:"^(?!.*martin)(?!.*saba).*maarten",ROU:"r(o|u|ou)mania",VIR:"^(?=.*\\bu\\.?\\s?s).*virgin|^(?=.*states).*virgin",SYR:"syria",MAC:"maca(o|u)",NFK:"norfolk",NIC:"nicaragua",MLT:"\\bmalta",KAZ:"kazak",TCA:"turks",PYF:"french.?polynesia|tahiti",NIU:"niue",DMA:"dominica(?!n)",GBR:"united.?kingdom|britain|^u\\.?k\\.?$",BEN:"benin|dahome",GUF:"^(?=.*french).*guiana",BEL:"^(?!.*luxem).*belgium",MSR:"montserrat",TGO:"togo",DEU:"^(?!.*east).*germany|^(?=.*\\bfed.*\\brep).*german",GUM:"\\bguam",LKA:"sri.?lanka|ceylon",SSD:"\\bs\\w*.?sudan",FLK:"falkland|malvinas",PCN:"pitcairn",BES:"^(?=.*bonaire).*eustatius|^(?=.*carib).*netherlands|\\bbes.?islands",GUY:"guyana|british.?guiana",CRI:"costa.?rica",COK:"\\bcook",MAR:"morocco|\\bmaroc",MNP:"mariana",LSO:"lesotho|basuto",HUN:"^(?!.*austr).*hungary",TKM:"turkmen",SUR:"surinam|dutch.?guiana",NLD:"^(?!.*\\bant)(?!.*\\bcarib).*netherlands",BMU:"bermuda",HMD:"heard.*mcdonald",TCD:"\\bchad",GEO:"^(?!.*south).*georgia",MNE:"^(?!.*serbia).*montenegro",MNG:"mongolia",MHL:"marshall",MTQ:"martinique",CSK:"czechoslovakia",BLZ:"belize|^(?=.*british).*honduras",DDR:"german.?democratic.?republic|^(d|g)\\.?d\\.?r\\.?$|^(?=.*east).*germany",MMR:"myanmar|burma",AFG:"afghan",BDI:"burundi",VGB:"^(?=.*\\bu\\.?\\s?k).*virgin|^(?=.*brit).*virgin|^(?=.*kingdom).*virgin",BLR:"belarus|byelo",BLM:"barth(e|\xe9)lemy",GRD:"grenada",TKL:"tokelau",GRC:"greece|hellenic|hellas",GRL:"greenland",SHN:"helena",AND:"andorra",MOZ:"mozambique",TJK:"tajik",THA:"thailand|\\bsiam",HTI:"haiti",MEX:"\\bmexic",ANT:"^(?=.*\\bant).*(nether|dutch)",ZWE:"zimbabwe|^(?!.*northern).*rhodesia",LCA:"\\blucia",IND:"india(?!.*ocea)",LVA:"latvia",BTN:"bhutan",VCT:"vincent",VNM:"^(?!.*republic).*viet.?nam|^(?=.*socialist).*viet.?nam",NOR:"norway",CZE:"^(?=.*rep).*czech|czechia|bohemia",ATF:"french.?southern|\\bfr.*\\bso.*\\ban.*\\b\\bt",ATG:"antigua",FJI:"fiji",HND:"^(?!.*brit).*honduras",MUS:"mauritius",DOM:"dominican",LUX:"^(?!.*belg).*luxem",ISR:"israel",YUG:"yugoslavia",FSM:"micronesia",PER:"peru",REU:"r(e|\xe9)union",IDN:"indonesia",VUT:"vanuatu|new.?hebrides",MKD:"macedonia|^f\\.?y\\.?r\\.?o\\.?m\\.?$",COD:"\\bdem.*congo|congo.*\\bdem|congo.*\\bdr|\\bdr.*congo|\\bd\\.?r\\.?c|\\bd\\.?r\\.?o\\.?c|\\br\\.?d\\.?c|belgian.?congo|congo.?free.?state|kinshasa|zaire|l\\w{1,2}opoldville",COG:"^(?!.*\\bdem)(?!.*\\bdr)(?!.*kinshasa)(?!.*zaire)(?!.*belg)(?!.*l\\w{1,2}opoldville)(?!.*free).*\\bcongo",ISL:"iceland",GLP:"guadeloupe",ETH:"ethiopia|abyssinia",COM:"comoro",COL:"colombia",NGA:"nigeria",TLS:"^(?=.*leste).*timor|^(?=.*east).*timor",TWN:"taiwan|taipei|formosa",PRT:"portugal",MDA:"moldov|b(a|e)ssarabia",GGY:"guernsey",MDG:"madagascar|malagasy",ATA:"antarctica",ECU:"ecuador",SEN:"senegal",ESH:"sahara",MDV:"maldive",ASM:"^(?=.*americ).*samoa",SPM:"miquelon",CUW:"^(?!.*bonaire).*\\bcura(c|\xe7)ao",FRA:"^(?!.*\\bdep)(?!.*martinique).*france|french.?republic|\\bgaul",LTU:"lithuania",RWA:"rwanda",ZMB:"zambia|northern.?rhodesia",GMB:"gambia",WLF:"futuna|wallis",JEY:"jersey",FRO:"faroe|faeroe",GTM:"guatemala",DNK:"denmark",IMN:"^(?=.*isle).*\\bman",MAF:"^(?=.*collectivity).*martin|^(?=.*france).*martin(?!ique)|^(?=.*french).*martin(?!ique)",AUS:"australia",AUT:"^(?!.*hungary).*austria|\\baust.*\\bemp",SJM:"svalbard",VEN:"venezuela",PLW:"palau",KEN:"kenya|british.?east.?africa|east.?africa.?prot",TUR:"turkey",ALB:"albania",OMN:"\\boman|trucial",TUV:"tuvalu",ALA:"\\b(a|\xe5)land",BRN:"brunei",TUN:"tunisia",RUS:"\\brussia|soviet.?union|u\\.?s\\.?s\\.?r|socialist.?republics",BRB:"barbados",BRA:"brazil",CIV:"ivoire|ivory",SRB:"^(?!.*monte).*serbia",GNQ:"guine.*eq|eq.*guine|^(?=.*span).*guinea",USA:"^(?!.*islands).*united.?states|^u\\.?s\\.?a\\.?$|^u\\.?s\\.?$",QAT:"qatar",WSM:"^(?!.*amer).*samoa",AZE:"azerbaijan",GNB:"bissau|^(?=.*portu).*guinea",SWZ:"swaziland",TON:"tonga",CAN:"canada",UKR:"ukrain",KOR:"^(?!.*democrat)(?!.*people)(?!.*north).*\\bkorea|\\br\\.?o\\.?k\\b",AIA:"anguill?a",CAF:"\\bcen.*\\baf|^c\\.?a\\.?r\\.?$",CHE:"switz|swiss",CYP:"cyprus",BIH:"herzegovina|bosnia",SGP:"singapore",SGS:"south.?georgia|sandwich",SOM:"somali",UZB:"uzbek",CMR:"cameroon",POL:"poland",EAZ:"zanz",KWT:"kuwait",ERI:"eritrea",GAB:"gabon",CYM:"cayman",ARE:"emirates|^u\\.?a\\.?e\\.?$|united.?arab.?em",EST:"estonia",MWI:"malawi|nyasa",ESP:"spain",IRQ:"\\biraq|mesopotamia",SLV:"el.?salvador",MLI:"\\bmali\\b",YMD:"^(?=.*peo).*yemen|^(?!.*rep)(?=.*dem).*yemen|^(?=.*south).*yemen|^(?=.*aden).*yemen|^(?=.*\\bp\\.?d\\.?r).*yemen",IRL:"ireland",IRN:"\\biran|persia",ABW:"^(?!.*bonaire).*\\baruba",SLE:"sierra",PAN:"panama",SDN:"^(?!.*\\bs(?!u)).*sudan",SLB:"solomon",NZL:"new.?zealand",MCO:"monaco",ITA:"italy",JPN:"japan",KGZ:"kyrgyz|kirghiz",UGA:"uganda",NCL:"new.?caledonia",PNG:"papua|\\bp.*\\bn.*\\bguin.*|^p\\.?n\\.?g\\.?$|new.?guinea",ARG:"argentin",SWE:"sweden",BHS:"bahamas",BHR:"bahrain",ARM:"armenia",NRU:"nauru",CUB:"\\bcuba"}},{}],334:[function(t,e,r){"use strict";var n=e.exports={};n.projNames={equirectangular:"equirectangular",mercator:"mercator",orthographic:"orthographic","natural earth":"naturalEarth",kavrayskiy7:"kavrayskiy7",miller:"miller",robinson:"robinson",eckert4:"eckert4","azimuthal equal area":"azimuthalEqualArea","azimuthal equidistant":"azimuthalEquidistant","conic equal area":"conicEqualArea","conic conformal":"conicConformal","conic equidistant":"conicEquidistant",gnomonic:"gnomonic",stereographic:"stereographic",mollweide:"mollweide",hammer:"hammer","transverse mercator":"transverseMercator","albers usa":"albersUsa"},n.axesNames=["lonaxis","lataxis"],n.lonaxisSpan={orthographic:180,"azimuthal equal area":360,"azimuthal equidistant":360,"conic conformal":180,gnomonic:160,stereographic:180,"transverse mercator":180,"*":360},n.lataxisSpan={"conic conformal":150,stereographic:179.5,"*":180},n.scopeDefaults={world:{lonaxisRange:[-180,180],lataxisRange:[-90,90],projType:"equirectangular",projRotate:[0,0,0]},usa:{lonaxisRange:[-180,-50],lataxisRange:[15,80],projType:"albers usa"},europe:{lonaxisRange:[-30,60],lataxisRange:[30,80],projType:"conic conformal",projRotate:[15,0,0],projParallels:[0,60]},asia:{lonaxisRange:[22,160],lataxisRange:[-15,55],projType:"mercator",projRotate:[0,0,0]},africa:{lonaxisRange:[-30,60],lataxisRange:[-40,40],projType:"mercator",projRotate:[0,0,0]},"north america":{lonaxisRange:[-180,-45],lataxisRange:[5,85],projType:"conic conformal",projRotate:[-100,0,0],projParallels:[29.5,45.5]},"south america":{lonaxisRange:[-100,-30],lataxisRange:[-60,15],projType:"mercator",projRotate:[0,0,0]}},n.clipPad=.001,n.precision=.1,n.landColor="#F0DC82",n.waterColor="#3399FF",n.locationmodeToLayer={"ISO-3":"countries","USA-states":"subunits","country names":"countries"},n.sphereSVG={type:"Sphere"},n.fillLayers=["ocean","land","lakes"],n.lineLayers=["subunits","countries","coastlines","rivers","frame"],n.baseLayers=["ocean","land","lakes","subunits","countries","coastlines","rivers","lataxis","lonaxis","frame"],n.layerNameToAdjective={ocean:"ocean",land:"land",lakes:"lake",subunits:"subunit",countries:"country",coastlines:"coastline",rivers:"river",frame:"frame"},n.baseLayersOverChoropleth=["rivers","lakes"]},{}],335:[function(t,e,r){"use strict";e.exports={solid:[1],dot:[1,1],dash:[4,1],longdash:[8,1],dashdot:[4,1,1,1],longdashdot:[8,1,1,1]}},{}],336:[function(t,e,r){"use strict";e.exports={solid:[[],0],dot:[[.5,1],200],dash:[[.5,1],50],longdash:[[.5,1],10],dashdot:[[.5,.625,.875,1],50],longdashdot:[[.5,.7,.8,1],10]}},{}],337:[function(t,e,r){"use strict";e.exports={circle:"\u25cf","circle-open":"\u25cb",square:"\u25a0","square-open":"\u25a1",diamond:"\u25c6","diamond-open":"\u25c7",cross:"+",x:"\u274c"}},{}],338:[function(t,e,r){"use strict";r.xmlns="http://www.w3.org/2000/xmlns/",r.svg="http://www.w3.org/2000/svg",r.xlink="http://www.w3.org/1999/xlink",r.svgAttrs={xmlns:r.svg,"xmlns:xlink":r.xlink}},{}],339:[function(t,e,r){"use strict";var n=t("./plotly");r.version="1.6.3",r.plot=n.plot,r.newPlot=n.newPlot,r.restyle=n.restyle,r.relayout=n.relayout,r.redraw=n.redraw,r.extendTraces=n.extendTraces,r.prependTraces=n.prependTraces,r.addTraces=n.addTraces,r.deleteTraces=n.deleteTraces,r.moveTraces=n.moveTraces,r.setPlotConfig=t("./plot_api/set_plot_config"),r.register=n.register,r.Icons=t("../build/ploticon"),r.Plots=n.Plots,r.Fx=n.Fx,r.Snapshot=n.Snapshot,r.PlotSchema=n.PlotSchema,r.Queue=n.Queue,r.d3=t("d3")},{"../build/ploticon":2,"./plot_api/set_plot_config":365,"./plotly":366,d3:70}],340:[function(t,e,r){"use strict";"undefined"!=typeof MathJax?(r.MathJax=!0,MathJax.Hub.Config({messageStyle:"none",skipStartupTypeset:!0,displayAlign:"left",tex2jax:{inlineMath:[["$","$"],["\\(","\\)"]]}}),MathJax.Hub.Configured()):r.MathJax=!1},{}],341:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){Array.isArray(t)&&(e[r]=t[n])}},{}],342:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("tinycolor2"),a=t("./nested_property"),o=t("../components/colorscale/get_scale");Object.keys(t("../components/colorscale/scales"));r.valObjects={data_array:{coerceFunction:function(t,e,r){Array.isArray(t)?e.set(t):void 0!==r&&e.set(r)}},enumerated:{coerceFunction:function(t,e,r,n){n.coerceNumber&&(t=+t),-1===n.values.indexOf(t)?e.set(r):e.set(t)}},"boolean":{coerceFunction:function(t,e,r){t===!0||t===!1?e.set(t):e.set(r)}},number:{coerceFunction:function(t,e,r,i){!n(t)||void 0!==i.min&&t<i.min||void 0!==i.max&&t>i.max?e.set(r):e.set(+t)}},integer:{coerceFunction:function(t,e,r,i){t%1||!n(t)||void 0!==i.min&&t<i.min||void 0!==i.max&&t>i.max?e.set(r):e.set(+t)}},string:{coerceFunction:function(t,e,r,n){if(n.strict===!0&&"string"!=typeof t)return void e.set(r);var i=String(t);void 0===t||n.noBlank===!0&&!i?e.set(r):e.set(i)}},color:{coerceFunction:function(t,e,r){i(t).isValid()?e.set(t):e.set(r)}},colorscale:{coerceFunction:function(t,e,r){e.set(o(t,r))}},angle:{coerceFunction:function(t,e,r){"auto"===t?e.set("auto"):n(t)?(Math.abs(t)>180&&(t-=360*Math.round(t/360)),e.set(+t)):e.set(r)}},axisid:{coerceFunction:function(t,e,r){if("string"==typeof t&&t.charAt(0)===r){var n=Number(t.substr(1));if(n%1===0&&n>1)return void e.set(t)}e.set(r)}},sceneid:{coerceFunction:function(t,e,r){if("string"==typeof t&&t.substr(0,5)===r){var n=Number(t.substr(5));if(n%1===0&&n>1)return void e.set(t)}e.set(r)}},geoid:{coerceFunction:function(t,e,r){if("string"==typeof t&&t.substr(0,3)===r){var n=Number(t.substr(3));if(n%1===0&&n>1)return void e.set(t)}e.set(r)}},flaglist:{coerceFunction:function(t,e,r,n){if("string"!=typeof t)return void e.set(r);if(-1!==n.extras.indexOf(t))return void e.set(t);for(var i=t.split("+"),a=0;a<i.length;){var o=i[a];-1===n.flags.indexOf(o)||i.indexOf(o)<a?i.splice(a,1):a++}i.length?e.set(i.join("+")):e.set(r)}},any:{coerceFunction:function(t,e,r){void 0===t?e.set(r):e.set(t)}},info_array:{coerceFunction:function(t,e,n,i){if(!Array.isArray(t))return void e.set(n);var a=i.items,o=[];n=Array.isArray(n)?n:[];for(var s=0;s<a.length;s++)r.coerce(t,o,a,"["+s+"]",n[s]);e.set(o)}}},r.coerce=function(t,e,n,i,o){var s=a(n,i).get(),l=a(t,i),u=a(e,i),c=l.get();return void 0===o&&(o=s.dflt),s.arrayOk&&Array.isArray(c)?(u.set(c),c):(r.valObjects[s.valType].coerceFunction(c,u,o,s),u.get())},r.coerce2=function(t,e,n,i,o){var s=a(t,i),l=r.coerce(t,e,n,i,o);return s.get()?l:!1},r.coerceFont=function(t,e,r){var n={};return r=r||{},n.family=t(e+".family",r.family),n.size=t(e+".size",r.size),n.color=t(e+".color",r.color),n}},{"../components/colorscale/get_scale":310,"../components/colorscale/scales":316,"./nested_property":352,"fast-isnumeric":74,tinycolor2:229}],343:[function(t,e,r){"use strict";function n(t,e){return String(t+Math.pow(10,e)).substr(1)}function i(t){var e;return e=y.test(t)?"Y":"y",e+=b.test(t)?"b":""}function a(t){var e;return e=_.test(t)?x.test(t)?"I":"H":"D"}var o=t("d3"),s=t("fast-isnumeric");r.dateTime2ms=function(t){try{if(t.getTime)return+t}catch(e){return!1}var r,n,i,a,o=String(t).split(" ");if(o.length>2)return!1;var l=o[0].split("-");if(l.length>3||3!==l.length&&o[1])return!1;if(4===l[0].length)r=Number(l[0]);else{if(2!==l[0].length)return!1;var u=(new Date).getFullYear();r=((Number(l[0])-u+70)%100+200)%100+u-70;
+}return s(r)?1===l.length?new Date(r,0,1).getTime():(n=Number(l[1])-1,l[1].length>2||!(n>=0&&11>=n)?!1:2===l.length?new Date(r,n,1).getTime():(i=Number(l[2]),l[2].length>2||!(i>=1&&31>=i)?!1:(i=new Date(r,n,i).getTime(),o[1]?(l=o[1].split(":"),l.length>3?!1:(a=Number(l[0]),l[0].length>2||!(a>=0&&23>=a)?!1:(i+=36e5*a,1===l.length?i:(n=Number(l[1]),l[1].length>2||!(n>=0&&59>=n)?!1:(i+=6e4*n,2===l.length?i:(t=Number(l[2]),t>=0&&60>t?i+1e3*t:!1)))))):i))):!1},r.isDateTime=function(t){return r.dateTime2ms(t)!==!1},r.ms2DateTime=function(t,e){if("undefined"==typeof o)return void console.log("d3 is not defined");e||(e=0);var r=new Date(t),i=o.time.format("%Y-%m-%d")(r);return 7776e6>e?(i+=" "+n(r.getHours(),2),432e6>e&&(i+=":"+n(r.getMinutes(),2),108e5>e&&(i+=":"+n(r.getSeconds(),2),3e5>e&&(i+="."+n(r.getMilliseconds(),3)))),i.replace(/([:\s]00)*\.?[0]*$/,"")):i};var l={H:["%H:%M:%S~%L","%H:%M:%S","%H:%M"],I:["%I:%M:%S~%L%p","%I:%M:%S%p","%I:%M%p"],D:["%H","%I%p","%Hh"]},u={Y:["%Y~%m~%d","%Y%m%d","%y%m%d","%m~%d~%Y","%d~%m~%Y"],Yb:["%b~%d~%Y","%d~%b~%Y","%Y~%d~%b","%Y~%b~%d"],y:["%m~%d~%y","%d~%m~%y","%y~%m~%d"],yb:["%b~%d~%y","%d~%b~%y","%y~%d~%b","%y~%b~%d"]},c=o.time.format.utc,h={Y:{H:["%Y~%m~%dT%H:%M:%S","%Y~%m~%dT%H:%M:%S~%L"].map(c),I:[],D:["%Y%m%d%H%M%S","%Y~%m","%m~%Y"].map(c)},Yb:{H:[],I:[],D:["%Y~%b","%b~%Y"].map(c)},y:{H:[],I:[],D:[]},yb:{H:[],I:[],D:[]}};["Y","Yb","y","yb"].forEach(function(t){u[t].forEach(function(e){h[t].D.push(c(e)),["H","I","D"].forEach(function(r){l[r].forEach(function(n){var i=h[t][r];i.push(c(e+"~"+n)),i.push(c(n+"~"+e))})})})});var f=/[a-z]*/g,d=function(t){return t.substr(0,3)},p=/(mon|tue|wed|thu|fri|sat|sun|the|of|st|nd|rd|th)/g,g=/[\s,\/\-\.\(\)]+/g,v=/~?([ap])~?m(~|$)/,m=function(t,e){return e+"m "},y=/\d\d\d\d/,b=/(^|~)[a-z]{3}/,x=/[ap]m/,_=/:/,w=/q([1-4])/,A=["31~mar","30~jun","30~sep","31~dec"],k=function(t,e){return A[e-1]},M=/ ?([+\-]\d\d:?\d\d|Z)$/;r.parseDate=function(t){if(t.getTime)return t;if("string"!=typeof t)return!1;t=t.toLowerCase().replace(f,d).replace(p,"").replace(g,"~").replace(v,m).replace(w,k).trim().replace(M,"");var e,r,n=null,o=i(t),s=a(t);e=h[o][s],r=e.length;for(var l=0;r>l&&!(n=e[l].parse(t));l++);if(!(n instanceof Date))return!1;var u=n.getTimezoneOffset();return n.setTime(n.getTime()+60*u*1e3),n}},{d3:70,"fast-isnumeric":74}],344:[function(t,e,r){"use strict";var n=t("events").EventEmitter,i={init:function(t){if(t._ev instanceof n)return t;var e=new n;return t._ev=e,t.on=e.on.bind(e),t.once=e.once.bind(e),t.removeListener=e.removeListener.bind(e),t.removeAllListeners=e.removeAllListeners.bind(e),t.emit=function(r,n){"undefined"!=typeof $&&$(t).trigger(r,n),e.emit(r,n)},t},triggerHandler:function(t,e,r){var n,i;"undefined"!=typeof $&&(n=$(t).triggerHandler(e,r));var a=t._ev;if(!a)return n;var o=a._events[e];if(!o)return n;"function"==typeof o&&(o=[o]);for(var s=o.pop(),l=0;l<o.length;l++)o[l](r);return i=s(r),void 0!==n?n:i}};e.exports=i},{events:54}],345:[function(t,e,r){"use strict";function n(t,e,r){for(var o,s,l,u,c,h,f=t[0],d=t.length,p=1;d>p;p++){o=t[p];for(s in o)l=f[s],u=o[s],e&&u&&(i(u)||(c=a(u)))?(c?(c=!1,h=l&&a(l)?l:[]):h=l&&i(l)?l:{},f[s]=n([h,u],e,r)):("undefined"!=typeof u||r)&&(f[s]=u)}return f}var i=t("./is_plain_object.js"),a=Array.isArray;r.extendFlat=function(){return n(arguments,!1,!1)},r.extendDeep=function(){return n(arguments,!0,!1)},r.extendDeepAll=function(){return n(arguments,!0,!0)}},{"./is_plain_object.js":350}],346:[function(t,e,r){"use strict";function n(t,e){var r=u[t];return r(e)}function i(t){for(var e,r,n=0;n<l.length;n++)if(e=l[n],r=new RegExp(s[e]),r.test(t.toLowerCase()))return e;console.warn("unrecognized country name: "+t+".")}var a=e.exports={},o=t("../plotly"),s=t("../constants/country-name_to_iso3"),l=Object.keys(s),u={"ISO-3":o.Lib.identity,"USA-states":o.Lib.identity,"country names":i};a.locationToFeature=function(t,e,r){for(var i,a=n(t,e),o=0;o<r.length;o++)if(i=r[o],i.id===a)return i;console.warn(["location with id",a,"does not have a matching topojson feature at this resolution."].join(" "))}},{"../constants/country-name_to_iso3":333,"../plotly":366}],347:[function(t,e,r){"use strict";function n(t,e){var r=c(t);return r[3]*=e,r}function i(t){return l(t).isValid()?t:h}function a(t){return u(t)?t:f}function o(t,e,r){var o,l,u,c,d,p=t.color,g=Array.isArray(p),v=Array.isArray(e),m=[];if(o=void 0!==t.colorscale?s.Colorscale.makeScaleFunction(t.colorscale,t.cmin,t.cmax):i,l=g?function(t,e){return void 0===t[e]?h:o(t[e])}:i,u=v?function(t,e){return void 0===t[e]?f:a(t[e])}:a,g||v)for(var y=0;r>y;y++)c=l(p,y),d=u(e,y),m[y]=n(c,d);else m=n(p,e);return m}var s=t("../plotly"),l=t("tinycolor2"),u=t("fast-isnumeric"),c=t("./str2rgbarray"),h=t("../components/color/attributes").defaultLine,f=1;e.exports=o},{"../components/color/attributes":298,"../plotly":366,"./str2rgbarray":359,"fast-isnumeric":74,tinycolor2:229}],348:[function(t,e,r){"use strict";function n(t){for(var e=0;(e=t.indexOf("<sup>",e))>=0;){var r=t.indexOf("</sup>",e);if(e>r)break;t=t.slice(0,e)+l(t.slice(e+5,r))+t.slice(r+6)}return t}function i(t){return t.replace(/\<br\>/g,"\n")}function a(t){return t.replace(/\<.*\>/g,"")}function o(t){for(var e=0;(e=t.indexOf("&",e))>=0;){var r=t.indexOf(";",e);if(e>r)e+=1;else{var n=u[t.slice(e+1,r)];t=n?t.slice(0,e)+n+t.slice(r+1):t.slice(0,e)+t.slice(r+1)}}return t}function s(t){return""+o(a(n(i(t))))}var l=t("superscript-text"),u={mu:"\u03bc",amp:"&",lt:"<",gt:">"};e.exports=s},{"superscript-text":218}],349:[function(t,e,r){"use strict";var n=t("d3"),i=e.exports={};i.nestedProperty=t("./nested_property"),i.isPlainObject=t("./is_plain_object");var a=t("./coerce");i.valObjects=a.valObjects,i.coerce=a.coerce,i.coerce2=a.coerce2,i.coerceFont=a.coerceFont;var o=t("./dates");i.dateTime2ms=o.dateTime2ms,i.isDateTime=o.isDateTime,i.ms2DateTime=o.ms2DateTime,i.parseDate=o.parseDate;var s=t("./search");i.findBin=s.findBin,i.sorterAsc=s.sorterAsc,i.sorterDes=s.sorterDes,i.distinctVals=s.distinctVals,i.roundUp=s.roundUp;var l=t("./stats");i.aggNums=l.aggNums,i.len=l.len,i.mean=l.mean,i.variance=l.variance,i.stdev=l.stdev,i.interp=l.interp;var u=t("./matrix");i.init2dArray=u.init2dArray,i.transposeRagged=u.transposeRagged,i.dot=u.dot,i.translationMatrix=u.translationMatrix,i.rotationMatrix=u.rotationMatrix,i.rotationXYMatrix=u.rotationXYMatrix,i.apply2DTransform=u.apply2DTransform,i.apply2DTransform2=u.apply2DTransform2;var c=t("./extend");i.extendFlat=c.extendFlat,i.extendDeep=c.extendDeep,i.extendDeepAll=c.extendDeepAll,i.notifier=t("./notifier"),i.swapAttrs=function(t,e,r,n){r||(r="x"),n||(n="y");for(var a=0;a<e.length;a++){var o=e[a],s=i.nestedProperty(t,o.replace("?",r)),l=i.nestedProperty(t,o.replace("?",n)),u=s.get();s.set(l.get()),l.set(u)}},i.pauseEvent=function(t){return t.stopPropagation&&t.stopPropagation(),t.preventDefault&&t.preventDefault(),t.cancelBubble=!0,!1},i.VERBOSE=!1,i.TIMER=(new Date).getTime(),i.log=function(){i.VERBOSE&&console.log.apply(console,arguments)},i.markTime=function(t){if(i.VERBOSE){var e=(new Date).getTime();console.log(t,e-i.TIMER,"(msec)"),"trace"===i.VERBOSE&&console.trace(),i.TIMER=e}},i.constrain=function(t,e,r){return e>r?Math.max(r,Math.min(e,t)):Math.max(e,Math.min(r,t))},i.bBoxIntersect=function(t,e,r){return r=r||0,t.left<=e.right+r&&e.left<=t.right+r&&t.top<=e.bottom+r&&e.top<=t.bottom+r},i.identity=function(t){return t},i.randstr=function h(t,e,r){if(r||(r=16),void 0===e&&(e=24),0>=e)return"0";var n,i,a,o=Math.log(Math.pow(2,e))/Math.log(r),s="";for(n=2;o===1/0;n*=2)o=Math.log(Math.pow(2,e/n))/Math.log(r)*n;var l=o-Math.floor(o);for(n=0;n<Math.floor(o);n++)a=Math.floor(Math.random()*r).toString(r),s=a+s;l&&(i=Math.pow(r,l),a=Math.floor(Math.random()*i).toString(r),s=a+s);var u=parseInt(s,r);return t&&t.indexOf(s)>-1||u!==1/0&&u>=Math.pow(2,e)?h(t,e,r):s},i.OptionControl=function(t,e){t||(t={}),e||(e="opt");var r={};return r.optionList=[],r._newoption=function(n){n[e]=t,r[n.name]=n,r.optionList.push(n)},r["_"+e]=t,r},i.smooth=function(t,e){if(e=Math.round(e)||0,2>e)return t;var r,n,i,a,o=t.length,s=2*o,l=2*e-1,u=new Array(l),c=new Array(o);for(r=0;l>r;r++)u[r]=(1-Math.cos(Math.PI*(r+1)/e))/(2*e);for(r=0;o>r;r++){for(a=0,n=0;l>n;n++)i=r+n+1-e,-o>i?i-=s*Math.round(i/s):i>=s&&(i-=s*Math.floor(i/s)),0>i?i=-1-i:i>=o&&(i=s-1-i),a+=t[i]*u[n];c[r]=a}return c},i.promiseError=function(t){console.log(t,t.stack)},i.syncOrAsync=function(t,e,r){function n(){return i.markTime("async done "+o.name),i.syncOrAsync(t,e,r)}for(var a,o;t.length;){if(o=t.splice(0,1)[0],a=o(e),a&&a.then)return a.then(n).then(void 0,i.promiseError);i.markTime("sync done "+o.name)}return r&&r(e)},i.stripTrailingSlash=function(t){return"/"===t.substr(-1)?t.substr(0,t.length-1):t},i.noneOrAll=function(t,e,r){if(t){var n,i,a=!1,o=!0;for(n=0;n<r.length;n++)i=t[r[n]],void 0!==i&&null!==i?a=!0:o=!1;if(a&&!o)for(n=0;n<r.length;n++)t[r[n]]=e[r[n]]}},i.mergeArray=function(t,e,r){if(Array.isArray(t))for(var n=Math.min(t.length,e.length),i=0;n>i;i++)e[i][r]=t[i]},i.minExtend=function(t,e){var r={};"object"!=typeof e&&(e={});var n,a,o,s=3,l=Object.keys(t);for(n=0;n<l.length;n++)a=l[n],o=t[a],"_"!==a.charAt(0)&&"function"!=typeof o&&("module"===a?r[a]=o:Array.isArray(o)?r[a]=o.slice(0,s):o&&"object"==typeof o?r[a]=i.minExtend(t[a],e[a]):r[a]=o);for(l=Object.keys(e),n=0;n<l.length;n++)a=l[n],o=e[a],"object"==typeof o&&a in r&&"object"==typeof r[a]||(r[a]=o);return r},i.titleCase=function(t){return t.charAt(0).toUpperCase()+t.substr(1)},i.containsAny=function(t,e){for(var r=0;r<e.length;r++)if(-1!==t.indexOf(e[r]))return!0;return!1},i.getPlotDiv=function(t){for(;t&&t.removeAttribute;t=t.parentNode)if(i.isPlotDiv(t))return t},i.isPlotDiv=function(t){var e=n.select(t);return e.size()&&e.classed("js-plotly-plot")},i.removeElement=function(t){var e=t&&t.parentNode;e&&e.removeChild(t)},i.addStyleRule=function(t,e){if(!i.styleSheet){var r=document.createElement("style");r.appendChild(document.createTextNode("")),document.head.appendChild(r),i.styleSheet=r.sheet}var n=i.styleSheet;n.insertRule?n.insertRule(t+"{"+e+"}",0):n.addRule?n.addRule(t,e,0):console.warn("addStyleRule failed")},i.isIE=function(){return"undefined"!=typeof window.navigator.msSaveBlob}},{"./coerce":342,"./dates":343,"./extend":345,"./is_plain_object":350,"./matrix":351,"./nested_property":352,"./notifier":353,"./search":356,"./stats":358,d3:70}],350:[function(t,e,r){"use strict";e.exports=function(t){return"[object Object]"===Object.prototype.toString.call(t)&&Object.getPrototypeOf(t)===Object.prototype}},{}],351:[function(t,e,r){"use strict";r.init2dArray=function(t,e){for(var r=new Array(t),n=0;t>n;n++)r[n]=new Array(e);return r},r.transposeRagged=function(t){var e,r,n=0,i=t.length;for(e=0;i>e;e++)n=Math.max(n,t[e].length);var a=new Array(n);for(e=0;n>e;e++)for(a[e]=new Array(i),r=0;i>r;r++)a[e][r]=t[r][e];return a},r.dot=function(t,e){if(!t.length||!e.length||t.length!==e.length)return null;var n,i,a=t.length;if(t[0].length)for(n=new Array(a),i=0;a>i;i++)n[i]=r.dot(t[i],e);else if(e[0].length){var o=r.transposeRagged(e);for(n=new Array(o.length),i=0;i<o.length;i++)n[i]=r.dot(t,o[i])}else for(n=0,i=0;a>i;i++)n+=t[i]*e[i];return n},r.translationMatrix=function(t,e){return[[1,0,t],[0,1,e],[0,0,1]]},r.rotationMatrix=function(t){var e=t*Math.PI/180;return[[Math.cos(e),-Math.sin(e),0],[Math.sin(e),Math.cos(e),0],[0,0,1]]},r.rotationXYMatrix=function(t,e,n){return r.dot(r.dot(r.translationMatrix(e,n),r.rotationMatrix(t)),r.translationMatrix(-e,-n))},r.apply2DTransform=function(t){return function(){var e=arguments;3===e.length&&(e=e[0]);var n=1===arguments.length?e[0]:[e[0],e[1]];return r.dot(t,[n[0],n[1],1]).slice(0,2)}},r.apply2DTransform2=function(t){var e=r.apply2DTransform(t);return function(t){return e(t.slice(0,2)).concat(e(t.slice(2,4)))}}},{}],352:[function(t,e,r){"use strict";function n(t,e){return function(){var r,i,a,o,s,l=t;for(o=0;o<e.length-1;o++){if(r=e[o],-1===r){for(i=!0,a=[],s=0;s<l.length;s++)a[s]=n(l[s],e.slice(o+1))(),a[s]!==a[0]&&(i=!1);return i?a[0]:a}if("number"==typeof r&&!Array.isArray(l))return;if(l=l[r],"object"!=typeof l||null===l)return}if("object"==typeof l&&null!==l&&(a=l[e[o]],null!==a))return a}}function i(t,e){var r=["annotations","shapes","range","domain"],n=-1===r.indexOf(e);return Array.isArray(t)&&n}function a(t,e){return function(r){var n,a,c=t,h=[t],f=u(r)&&!i(r,e[e.length-1]);for(a=0;a<e.length-1;a++){if(n=e[a],"number"==typeof n&&!Array.isArray(c))throw"array index but container is not an array";if(-1===n){if(f=!o(c,e.slice(a+1),r))break;return}if(!s(c,n,e[a+1],f))break;if(c=c[n],"object"!=typeof c||null===c)throw"container is not an object";h.push(c)}f?(a===e.length-1&&delete c[e[a]],l(h)):c[e[a]]=r}}function o(t,e,r){var n,i=Array.isArray(r),o=!0,l=r,c=i?!1:u(r),h=e[0];for(n=0;n<t.length;n++)i&&(l=r[n%r.length],c=u(l)),c&&(o=!1),s(t,n,h,c)&&a(t[n],e)(l);return o}function s(t,e,r,n){if(void 0===t[e]){if(n)return!1;"number"==typeof r?t[e]=[]:t[e]={}}return!0}function l(t){var e,r,n,a,o;for(e=t.length-1;e>=0;e--){if(n=t[e],o=!1,Array.isArray(n))for(r=n.length-1;r>=0;r--)u(n[r])?o?n[r]=void 0:n.pop():o=!0;else if("object"==typeof n&&null!==n)for(a=Object.keys(n),o=!1,r=a.length-1;r>=0;r--)u(n[a[r]])&&!i(n[a[r]],a[r])?delete n[a[r]]:o=!0;if(o)return}}function u(t){return void 0===t||null===t?!0:"object"!=typeof t?!1:Array.isArray(t)?!t.length:!Object.keys(t).length}function c(t,e,r){return{set:function(){throw"bad container"},get:function(){},astr:e,parts:r,obj:t}}var h=t("fast-isnumeric");e.exports=function(t,e){if(h(e))e=String(e);else if("string"!=typeof e||"[-1]"===e.substr(e.length-4))throw"bad property string";for(var r,i,o,s=0,l=e.split(".");s<l.length;){if(r=String(l[s]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/)){if(r[1])l[s]=r[1];else{if(0!==s)throw"bad property string";l.splice(0,1)}for(i=r[2].substr(1,r[2].length-2).split("]["),o=0;o<i.length;o++)s++,l.splice(s,0,Number(i[o]))}s++}return"object"!=typeof t?c(t,e,l):{set:a(t,l),get:n(t,l),astr:e,parts:l,obj:t}}},{"fast-isnumeric":74}],353:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=[];e.exports=function(t,e){function r(t){t.duration(700).style("opacity",0).each("end",function(t){var e=a.indexOf(t);-1!==e&&a.splice(e,1),n.select(this).remove()})}if(-1===a.indexOf(t)){a.push(t);var o=1e3;i(e)?o=e:"long"===e&&(o=3e3);var s=n.select("body").selectAll(".plotly-notifier").data([0]);s.enter().append("div").classed("plotly-notifier",!0);var l=s.selectAll(".notifier-note").data(a);l.enter().append("div").classed("notifier-note",!0).style("opacity",0).each(function(t){var e=n.select(this);e.append("button").classed("notifier-close",!0).html("&times;").on("click",function(){e.transition().call(r)}),e.append("p").html(t),e.transition().duration(700).style("opacity",1).transition().delay(o).call(r)})}}},{d3:70,"fast-isnumeric":74}],354:[function(t,e,r){"use strict";var n=t("./matrix").dot,i=e.exports={};i.tester=function(t){function e(t,e){var r=t[0],n=t[1];return i>r||r>a||o>n||n>s?!1:e&&u(t)?!1:!0}function r(t,e){var r=t[0],l=t[1];if(i>r||r>a||o>l||l>s)return!1;var u,c,h,f,d,p=n.length,g=n[0][0],v=n[0][1],m=0;for(u=1;p>u;u++)if(c=g,h=v,g=n[u][0],v=n[u][1],f=Math.min(c,g),!(f>r||r>Math.max(c,g)||l>Math.max(h,v)))if(l<Math.min(h,v))r!==f&&m++;else{if(d=g===c?l:h+(r-c)*(v-h)/(g-c),l===d)return 1===u&&e?!1:!0;d>=l&&r!==f&&m++}return m%2===1}var n=t.slice(),i=n[0][0],a=i,o=n[0][1],s=o;n.push(n[0]);for(var l=1;l<n.length;l++)i=Math.min(i,n[l][0]),a=Math.max(a,n[l][0]),o=Math.min(o,n[l][1]),s=Math.max(s,n[l][1]);var u,c=!1;return 5===n.length&&(n[0][0]===n[1][0]?n[2][0]===n[3][0]&&n[0][1]===n[3][1]&&n[1][1]===n[2][1]&&(c=!0,u=function(t){return t[0]===n[0][0]}):n[0][1]===n[1][1]&&n[2][1]===n[3][1]&&n[0][0]===n[3][0]&&n[1][0]===n[2][0]&&(c=!0,u=function(t){return t[1]===n[0][1]})),{xmin:i,xmax:a,ymin:o,ymax:s,pts:n,contains:c?e:r,isRect:c}};var a=i.isSegmentBent=function(t,e,r,i){var a,o,s,l=t[e],u=[t[r][0]-l[0],t[r][1]-l[1]],c=n(u,u),h=Math.sqrt(c),f=[-u[1]/h,u[0]/h];for(a=e+1;r>a;a++)if(o=[t[a][0]-l[0],t[a][1]-l[1]],s=n(o,u),0>s||s>c||Math.abs(n(o,f))>i)return!0;return!1};i.filter=function(t,e){function r(r){t.push(r);var s=n.length,l=i;n.splice(o+1);for(var u=l+1;u<t.length;u++)(u===t.length-1||a(t,l,u+1,e))&&(n.push(t[u]),n.length<s-2&&(i=u,o=n.length-1),l=u)}var n=[t[0]],i=0,o=0;if(t.length>1){var s=t.pop();r(s)}return{addPt:r,raw:t,filtered:n}}},{"./matrix":351}],355:[function(t,e,r){"use strict";function n(t,e){for(var r,n=[],a=0;a<e.length;a++)r=e[a],r===t?n[a]=r:"object"==typeof r?n[a]=Array.isArray(r)?i.Lib.extendDeep([],r):i.Lib.extendDeepAll({},r):n[a]=r;return n}var i=t("../plotly"),a={};a.add=function(t,e,r,n,i){var a,o;return t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},o=t.undoQueue.index,t.autoplay?void(t.undoQueue.inSequence||(t.autoplay=!1)):(!t.undoQueue.sequence||t.undoQueue.beginSequence?(a={undo:{calls:[],args:[]},redo:{calls:[],args:[]}},t.undoQueue.queue.splice(o,t.undoQueue.queue.length-o,a),t.undoQueue.index+=1):a=t.undoQueue.queue[o-1],t.undoQueue.beginSequence=!1,a.undo.calls.unshift(e),a.undo.args.unshift(r),a.redo.calls.push(n),void a.redo.args.push(i))},a.startSequence=function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!0,t.undoQueue.beginSequence=!0},a.stopSequence=function(t){t.undoQueue=t.undoQueue||{index:0,queue:[],sequence:!1},t.undoQueue.sequence=!1,t.undoQueue.beginSequence=!1},a.undo=function(t){var e,r;if(t.framework&&t.framework.isPolar)return void t.framework.undo();if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index<=0)){for(t.undoQueue.index--,e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r<e.undo.calls.length;r++)a.plotDo(t,e.undo.calls[r],e.undo.args[r]);t.undoQueue.inSequence=!1,t.autoplay=!1}},a.redo=function(t){var e,r;if(t.framework&&t.framework.isPolar)return void t.framework.redo();if(!(void 0===t.undoQueue||isNaN(t.undoQueue.index)||t.undoQueue.index>=t.undoQueue.queue.length)){for(e=t.undoQueue.queue[t.undoQueue.index],t.undoQueue.inSequence=!0,r=0;r<e.redo.calls.length;r++)a.plotDo(t,e.redo.calls[r],e.redo.args[r]);t.undoQueue.inSequence=!1,t.autoplay=!1,t.undoQueue.index++}},a.plotDo=function(t,e,r){t.autoplay=!0,r=n(t,r),e.apply(null,r)},e.exports=a},{"../plotly":366}],356:[function(t,e,r){"use strict";function n(t,e){return e>t}function i(t,e){return e>=t}function a(t,e){return t>e}function o(t,e){return t>=e}var s=t("fast-isnumeric");r.findBin=function(t,e,r){if(s(e.start))return r?Math.ceil((t-e.start)/e.size)-1:Math.floor((t-e.start)/e.size);var l,u,c=0,h=e.length,f=0;for(u=e[e.length-1]>=e[0]?r?n:i:r?o:a;h>c&&f++<100;)l=Math.floor((c+h)/2),u(e[l],t)?c=l+1:h=l;return f>90&&console.log("Long binary search..."),c-1},r.sorterAsc=function(t,e){return t-e},r.sorterDes=function(t,e){return e-t},r.distinctVals=function(t){var e=t.slice();e.sort(r.sorterAsc);for(var n=e.length-1,i=e[n]-e[0]||1,a=i/(n||1)/1e4,o=[e[0]],s=0;n>s;s++)e[s+1]>e[s]+a&&(i=Math.min(i,e[s+1]-e[s]),o.push(e[s+1]));return{vals:o,minDiff:i}},r.roundUp=function(t,e,r){for(var n,i=0,a=e.length-1,o=0,s=r?0:1,l=r?1:0,u=r?Math.ceil:Math.floor;a>i&&o++<100;)n=u((i+a)/2),e[n]<=t?i=n+s:a=n-l;return e[i]}},{"fast-isnumeric":74}],357:[function(t,e,r){"use strict";var n=t("../plotly"),i=function(){};e.exports=function(t){for(var e in t)"function"==typeof t[e]&&(t[e]=i);t.destroy=function(){t.container.parentNode.removeChild(t.container)};var r=document.createElement("div");return r.textContent="Webgl is not supported by your browser - visit http://get.webgl.org for more info",r.style.cursor="pointer",r.style.fontSize="24px",r.style.color=n.Color.defaults[0],t.container.appendChild(r),t.container.style.background="#FFFFFF",t.container.onclick=function(){window.open("http://get.webgl.org")},!1}},{"../plotly":366}],358:[function(t,e,r){"use strict";var n=t("fast-isnumeric");r.aggNums=function(t,e,i,a){var o,s;if(a||(a=i.length),n(e)||(e=!1),Array.isArray(i[0])){for(s=new Array(a),o=0;a>o;o++)s[o]=r.aggNums(t,e,i[o]);i=s}for(o=0;a>o;o++)n(e)?n(i[o])&&(e=t(+e,+i[o])):e=i[o];return e},r.len=function(t){return r.aggNums(function(t){return t+1},0,t)},r.mean=function(t,e){return e||(e=r.len(t)),r.aggNums(function(t,e){return t+e},0,t)/e},r.variance=function(t,e,i){return e||(e=r.len(t)),n(i)||(i=r.mean(t,e)),r.aggNums(function(t,e){return t+Math.pow(e-i,2)},0,t)/e},r.stdev=function(t,e,n){return Math.sqrt(r.variance(t,e,n))},r.interp=function(t,e){if(!n(e))throw"n should be a finite number";if(e=e*t.length-.5,0>e)return t[0];if(e>t.length-1)return t[t.length-1];var r=e%1;return r*t[Math.ceil(e)]+(1-r)*t[Math.floor(e)]}},{"fast-isnumeric":74}],359:[function(t,e,r){"use strict";function n(t){return t=i(t),a.str2RgbaArray(t.toRgbString())}var i=t("tinycolor2"),a=t("arraytools");e.exports=n},{arraytools:48,tinycolor2:229}],360:[function(t,e,r){"use strict";function n(t,e){return t.node().getBoundingClientRect()[e]}function i(t){return t.replace(/(<|&lt;|&#60;)/g,"\\lt ").replace(/(>|&gt;|&#62;)/g,"\\gt ")}function a(t,e,r){var n="math-output-"+l.Lib.randstr([],64),a=u.select("body").append("div").attr({id:n}).style({visibility:"hidden",position:"absolute"}).style({"font-size":e.fontSize+"px"}).text(i(t));MathJax.Hub.Queue(["Typeset",MathJax.Hub,a.node()],function(){var e=u.select("body").select("#MathJax_SVG_glyphs");if(a.select(".MathJax_SVG").empty()||!a.select("svg").node())console.log("There was an error in the tex syntax.",t),r();else{var n=a.select("svg").node().getBoundingClientRect();r(a.select(".MathJax_SVG"),e,n)}a.remove()})}function o(t){for(var e=l.util.html_entity_decode(t),r=e.split(/(<[^<>]*>)/).map(function(t){var e=t.match(/<(\/?)([^ >]*)\s*(.*)>/i),r=e&&e[2].toLowerCase(),n=f[r];if(void 0!==n){var i=e[1],a=e[3],o=a.match(/^style\s*=\s*"([^"]+)"\s*/i);if("a"===r){if(i)return"</a>";if("href"!==a.substr(0,4).toLowerCase())return"<a>";var s=document.createElement("a");return s.href=a.substr(4).replace(/["'=]/g,""),-1===d.indexOf(s.protocol)?"<a>":'<a xlink:show="new" xlink:href'+a.substr(4)+">"}if("br"===r)return"<br>";if(i)return"sup"===r?'</tspan><tspan dy="0.42em">&#x200b;</tspan>':"sub"===r?'</tspan><tspan dy="-0.21em">&#x200b;</tspan>':"</tspan>";var u="<tspan";return("sup"===r||"sub"===r)&&(u="&#x200b;"+u),o&&(o=o[1].replace(/(^|;)\s*color:/,"$1 fill:"),n=(n?n+";":"")+o),u+(n?' style="'+n+'"':"")+">"}return l.util.xml_entity_encode(t).replace(/</g,"&lt;")}),n=[],i=r.indexOf("<br>");i>0;i=r.indexOf("<br>",i+1))n.push(i);var a=0;n.forEach(function(t){for(var e=t+a,n=r.slice(0,e),i="",o=n.length-1;o>=0;o--){var s=n[o].match(/<(\/?).*>/i);if(s&&"<br>"!==n[o]){s[1]||(i=n[o]);break}}i&&(r.splice(e+1,0,i),r.splice(e,0,"</tspan>"),a+=2)});var o=r.join(""),s=o.split(/<br>/gi);return s.length>1&&(r=s.map(function(t,e){return'<tspan class="line" dy="'+1.3*e+'em">'+t+"</tspan>"})),r.join("")}function s(t,e,r){var n,i,a,o=r.horizontalAlign,s=r.verticalAlign||"top",l=t.node().getBoundingClientRect(),u=e.node().getBoundingClientRect();return i="bottom"===s?function(){return l.bottom-n.height}:"middle"===s?function(){return l.top+(l.height-n.height)/2}:function(){return l.top},a="right"===o?function(){return l.right-n.width}:"center"===o?function(){return l.left+(l.width-n.width)/2}:function(){return l.left},function(){return n=this.node().getBoundingClientRect(),this.style({top:i()-u.top+"px",left:a()-u.left+"px","z-index":1e3}),this}}var l=t("../plotly"),u=t("d3"),c=t("../constants/xmlns_namespaces"),h=e.exports={};u.selection.prototype.appendSVG=function(t){for(var e=['<svg xmlns="',c.svg,'" ','xmlns:xlink="',c.xlink,'">',t,"</svg>"].join(""),r=(new DOMParser).parseFromString(e,"application/xml"),n=r.documentElement.firstChild;n;)this.node().appendChild(this.node().ownerDocument.importNode(n,!0)),n=n.nextSibling;return r.querySelector("parsererror")?(console.log(r.querySelector("parsererror div").textContent),null):u.select(this.node().lastChild)},h.html_entity_decode=function(t){var e=u.select("body").append("div").style({display:"none"}).html(""),r=t.replace(/(&[^;]*;)/gi,function(t){return"&lt;"===t?"&#60;":"&rt;"===t?"&#62;":e.html(t).text()});return e.remove(),r},h.xml_entity_encode=function(t){return t.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&amp;")},h.convertToTspans=function(t,e){function r(){d.empty()||(p=c.attr("class")+"-math",d.select("svg."+p).remove()),t.text("").style({visibility:"visible","white-space":"pre"}),f=t.appendSVG(s),f||t.text(i),t.select("a").size()&&t.style("pointer-events","all"),e&&e.call(c)}var i=t.text(),s=o(i),c=t,h=!c.attr("data-notex")&&s.match(/([^$]*)([$]+[^$]*[$]+)([^$]*)/),f=i,d=u.select(c.node().parentNode);if(!d.empty()){var p=c.attr("class")?c.attr("class").split(" ")[0]:"text";p+="-math",d.selectAll("svg."+p).remove(),d.selectAll("g."+p+"-group").remove(),t.style({visibility:null});for(var g=t.node();g&&g.removeAttribute;g=g.parentNode)g.removeAttribute("data-bb");if(h){var v=l.Lib.getPlotDiv(c.node());(v&&v._promises||[]).push(new Promise(function(t){c.style({visibility:"hidden"});var i={fontSize:parseInt(c.style("font-size"),10)};a(h[2],i,function(i,a,o){d.selectAll("svg."+p).remove(),d.selectAll("g."+p+"-group").remove();var s=i&&i.select("svg");if(!s||!s.node())return r(),void t();var l=d.append("g").classed(p+"-group",!0).attr({"pointer-events":"none"});l.node().appendChild(s.node()),a&&a.node()&&s.node().insertBefore(a.node().cloneNode(!0),s.node().firstChild),s.attr({"class":p,height:o.height,preserveAspectRatio:"xMinYMin meet"}).style({overflow:"visible","pointer-events":"none"});var u=c.style("fill")||"black";s.select("g").attr({fill:u,stroke:u});var h=n(s,"width"),f=n(s,"height"),g=+c.attr("x")-h*{start:0,middle:.5,end:1}[c.attr("text-anchor")||"start"],v=parseInt(c.style("font-size"),10)||n(c,"height"),m=-v/4;"y"===p[0]?(l.attr({transform:"rotate("+[-90,+c.attr("x"),+c.attr("y")]+") translate("+[-h/2,m-f/2]+")"}),s.attr({x:+c.attr("x"),y:+c.attr("y")})):"l"===p[0]?s.attr({x:c.attr("x"),y:m-f/2}):"a"===p[0]?s.attr({x:0,y:m}):s.attr({x:g,y:+c.attr("y")+m-f/2}),e&&e.call(c,l),t(l)})}))}else r();return t}};var f={sup:'font-size:70%" dy="-0.6em',sub:'font-size:70%" dy="0.3em',b:"font-weight:bold",i:"font-style:italic",a:"",span:"",br:"",em:"font-style:italic;font-weight:bold"},d=["http:","https:","mailto:"],p=new RegExp("</?("+Object.keys(f).join("|")+")( [^>]*)?/?>","g");h.plainText=function(t){return(t||"").replace(p," ")},h.makeEditable=function(t,e,r){function n(){a(),o.style({opacity:0});var t,e=f.attr("class");t=e?"."+e.split(" ")[0]+"-math-group":"[class*=-math-group]",t&&u.select(o.node().parentNode).select(t).style({opacity:0})}function i(t){var e=t.node(),r=document.createRange();r.selectNodeContents(e);var n=window.getSelection();n.removeAllRanges(),n.addRange(r),e.focus()}function a(){var t=u.select(l.Lib.getPlotDiv(o.node())),e=t.select(".svg-container"),n=e.append("div");n.classed("plugin-editable editable",!0).style({position:"absolute","font-family":o.style("font-family")||"Arial","font-size":o.style("font-size")||12,color:r.fill||o.style("fill")||"black",opacity:1,"background-color":r.background||"transparent",outline:"#ffffff33 1px solid",margin:[-parseFloat(o.style("font-size"))/8+1,0,0,-1].join("px ")+"px",padding:"0","box-sizing":"border-box"}).attr({contenteditable:!0}).text(r.text||o.attr("data-unformatted")).call(s(o,e,r)).on("blur",function(){o.text(this.textContent).style({opacity:1});var t,e=u.select(this).attr("class");t=e?"."+e.split(" ")[0]+"-math-group":"[class*=-math-group]",t&&u.select(o.node().parentNode).select(t).style({opacity:0});var r=this.textContent;u.select(this).transition().duration(0).remove(),u.select(document).on("mouseup",null),c.edit.call(o,r)}).on("focus",function(){var t=this;u.select(document).on("mouseup",function(){return u.event.target===t?!1:void(document.activeElement===n.node()&&n.node().blur())})}).on("keyup",function(){27===u.event.which?(o.style({opacity:1}),u.select(this).style({opacity:0}).on("blur",function(){return!1}).transition().remove(),c.cancel.call(o,this.textContent)):(c.input.call(o,this.textContent),u.select(this).call(s(o,e,r)))}).on("keydown",function(){13===u.event.which&&this.blur()}).call(i)}r||(r={});var o=this,c=u.dispatch("edit","input","cancel"),h=u.select(this.node()).style({"pointer-events":"all"}),f=e||h;return e&&h.style({"pointer-events":"none"}),r.immediate?n():f.on("click",n),u.rebind(this,c,"on")}},{"../constants/xmlns_namespaces":338,"../plotly":366,d3:70}],361:[function(t,e,r){"use strict";var n=e.exports={},i=t("../constants/geo_constants").locationmodeToLayer,a=t("topojson").feature;n.getTopojsonName=function(t){return[t.scope.replace(/ /g,"-"),"_",t.resolution.toString(),"m"].join("")},n.getTopojsonPath=function(t,e){return t+e+".json"},n.getTopojsonFeatures=function(t,e){var r=i[t.locationmode],n=e.objects[r];return a(e,n).features}},{"../constants/geo_constants":334,topojson:230}],362:[function(t,e,r){"use strict";function n(t){var e;if("string"==typeof t){if(e=document.getElementById(t),null===e)throw new Error("No DOM element with id '"+t+"' exists on the page.");return e}if(null===t||void 0===t)throw new Error("DOM element provided is null or undefined");return t}function i(t,e){t._fullLayout._paperdiv.style("background","white"),P.defaultConfig.setBackground(t,e)}function a(t,e){t._context||(t._context=z.extendFlat({},P.defaultConfig));var r=t._context;e&&(Object.keys(e).forEach(function(t){t in r&&("setBackground"===t&&"opaque"===e[t]?r[t]=i:r[t]=e[t])}),e.plot3dPixelRatio&&!r.plotGlPixelRatio&&(r.plotGlPixelRatio=r.plot3dPixelRatio)),r.staticPlot&&(r.editable=!1,r.autosizable=!1,r.scrollZoom=!1,r.doubleClick=!1,r.showTips=!1,r.showLink=!1,r.displayModeBar=!1)}function o(t,e,r){var n=L.select(t).selectAll(".plot-container").data([0]);n.enter().insert("div",":first-child").classed("plot-container plotly",!0);var i=n.selectAll(".svg-container").data([0]);i.enter().append("div").classed("svg-container",!0).style("position","relative"),i.html(""),e&&(t.data=e),r&&(t.layout=r),P.micropolar.manager.fillLayout(t),"initial"===t._fullLayout.autosize&&t._context.autosizable&&(w(t,{}),t._fullLayout.autosize=r.autosize=!0),i.style({width:t._fullLayout.width+"px",height:t._fullLayout.height+"px"}),t.framework=P.micropolar.manager.framework(t),t.framework({data:t.data,layout:t.layout},i.node()),t.framework.setUndoPoint();var a=t.framework.svg(),o=1,s=t._fullLayout.title;""!==s&&s||(o=0);var l="Click to enter title",u=function(){this.call(P.util.convertToTspans)},c=a.select(".title-group text").call(u);if(t._context.editable){c.attr({"data-unformatted":s}),s&&s!==l||(o=.2,c.attr({"data-unformatted":l}).text(l).style({opacity:o}).on("mouseover.opacity",function(){L.select(this).transition().duration(100).style("opacity",1)}).on("mouseout.opacity",function(){L.select(this).transition().duration(1e3).style("opacity",0)}));var h=function(){this.call(P.util.makeEditable).on("edit",function(e){t.framework({layout:{title:e}}),this.attr({"data-unformatted":e}).text(e).call(u),this.call(h)}).on("cancel",function(){var t=this.attr("data-unformatted");this.text(t).call(u)})};c.call(h)}return t._context.setBackground(t,t._fullLayout.paper_bgcolor),I.addLinks(t),Promise.resolve()}function s(t){var e,r;t||(t={}),t.xaxis1&&(t.xaxis||(t.xaxis=t.xaxis1),delete t.xaxis1),t.yaxis1&&(t.yaxis||(t.yaxis=t.yaxis1),delete t.yaxis1);var n=P.Axes.list({_fullLayout:t});for(e=0;e<n.length;e++){var i=n[e];i.anchor&&"free"!==i.anchor&&(i.anchor=P.Axes.cleanId(i.anchor)),i.overlaying&&(i.overlaying=P.Axes.cleanId(i.overlaying)),i.type||(i.isdate?i.type="date":i.islog?i.type="log":i.isdate===!1&&i.islog===!1&&(i.type="linear")),("withzero"===i.autorange||"tozero"===i.autorange)&&(i.autorange=!0,i.rangemode="tozero"),delete i.islog,delete i.isdate,delete i.categories,h(i,"domain")&&delete i.domain,void 0!==i.autotick&&(void 0===i.tickmode&&(i.tickmode=i.autotick?"auto":"linear"),delete i.autotick)}void 0===t.annotations||Array.isArray(t.annotations)||(console.log("annotations must be an array"),
+delete t.annotations);var a=(t.annotations||[]).length;for(e=0;a>e;e++){var o=t.annotations[e];o.ref&&("paper"===o.ref?(o.xref="paper",o.yref="paper"):"data"===o.ref&&(o.xref="x",o.yref="y"),delete o.ref),l(o,"xref"),l(o,"yref")}void 0===t.shapes||Array.isArray(t.shapes)||(console.log("shapes must be an array"),delete t.shapes);var s=(t.shapes||[]).length;for(e=0;s>e;e++){var u=t.shapes[e];l(u,"xref"),l(u,"yref")}var c=t.legend;c&&(c.x>3?(c.x=1.02,c.xanchor="left"):c.x<-2&&(c.x=-.02,c.xanchor="right"),c.y>3?(c.y=1.02,c.yanchor="bottom"):c.y<-2&&(c.y=-.02,c.yanchor="top")),"rotate"===t.dragmode&&(t.dragmode="orbit"),t.scene1&&(t.scene||(t.scene=t.scene1),delete t.scene1);var f=I.getSubplotIds(t,"gl3d");for(e=0;e<f.length;e++){var d=t[f[e]],p=d.cameraposition;if(Array.isArray(p)&&4===p[0].length){var g=p[0],v=p[1],m=p[2],y=S([],g),b=[];for(r=0;3>r;++r)b[r]=v[e]+m*y[2+4*r];d.camera={eye:{x:b[0],y:b[1],z:b[2]},center:{x:v[0],y:v[1],z:v[2]},up:{x:y[1],y:y[5],z:y[9]}},delete d.cameraposition}}return z.markTime("finished rest of cleanLayout, starting color"),N.clean(t),z.markTime("finished cleanLayout color.clean"),t}function l(t,e){var r=t[e],n=e.charAt(0);r&&"paper"!==r&&(t[e]=P.Axes.cleanId(r,n))}function u(t,e){for(var r=[],n=(t.concat(Array.isArray(e)?e:[]).filter(function(t){return"uid"in t}).map(function(t){return t.uid})),i=0;i<t.length;i++){var a=t[i];if(!("uid"in a)||-1!==r.indexOf(a.uid)){var o,s;for(s=0;100>s&&(o=z.randstr(n),-1!==r.indexOf(o));s++);a.uid=z.randstr(n),n.push(a.uid)}if(r.push(a.uid),"histogramy"===a.type&&"xbins"in a&&!("ybins"in a)&&(a.ybins=a.xbins,delete a.xbins),a.error_y&&"opacity"in a.error_y){var l=N.defaults,u=a.error_y.color||(I.traceIs(a,"bar")?N.defaultLine:l[i%l.length]);a.error_y.color=N.addOpacity(N.rgb(u),N.opacity(u)*a.error_y.opacity),delete a.error_y.opacity}if("bardir"in a&&("h"!==a.bardir||!I.traceIs(a,"bar")&&"histogram"!==a.type.substr(0,9)||(a.orientation="h",x(a)),delete a.bardir),"histogramy"===a.type&&x(a),("histogramx"===a.type||"histogramy"===a.type)&&(a.type="histogram"),"scl"in a&&(a.colorscale=a.scl,delete a.scl),"reversescl"in a&&(a.reversescale=a.reversescl,delete a.reversescl),a.xaxis&&(a.xaxis=P.Axes.cleanId(a.xaxis,"x")),a.yaxis&&(a.yaxis=P.Axes.cleanId(a.yaxis,"y")),I.traceIs(a,"gl3d")&&a.scene&&(a.scene=I.subplotsRegistry.gl3d.cleanId(a.scene)),I.traceIs(a,"pie")||(Array.isArray(a.textposition)?a.textposition=a.textposition.map(c):a.textposition&&(a.textposition=c(a.textposition))),I.traceIs(a,"2dMap")&&("YIGnBu"===a.colorscale&&(a.colorscale="YlGnBu"),"YIOrRd"===a.colorscale&&(a.colorscale="YlOrRd")),I.traceIs(a,"markerColorscale")&&a.marker){var f=a.marker;"YIGnBu"===f.colorscale&&(f.colorscale="YlGnBu"),"YIOrRd"===f.colorscale&&(f.colorscale="YlOrRd")}h(a,"line")&&delete a.line,"marker"in a&&(h(a.marker,"line")&&delete a.marker.line,h(a,"marker")&&delete a.marker),z.markTime("finished rest of cleanData, starting color"),N.clean(a),z.markTime("finished cleanData color.clean")}}function c(t){var e="middle",r="center";return-1!==t.indexOf("top")?e="top":-1!==t.indexOf("bottom")&&(e="bottom"),-1!==t.indexOf("left")?r="left":-1!==t.indexOf("right")&&(r="right"),e+" "+r}function h(t,e){return e in t&&"object"==typeof t[e]&&0===Object.keys(t[e]).length}function f(t){var e,r,n,i,a=P.Axes.list(t),o=t._fullData,s=t._fullLayout,l=t.calcdata=new Array(o.length);for(t.firstscatter=!0,t.numboxes=0,t._hmpixcount=0,t._hmlumcount=0,s._piecolormap={},s._piedefaultcolorcount=0,e=0;e<a.length;e++)a[e]._categories=[];for(e=0;e<o.length;e++)r=o[e],n=r._module,i=[],n&&r.visible===!0&&n.calc&&(i=n.calc(t,r)),Array.isArray(i)&&i[0]||(i=[{x:!1,y:!1}]),i[0].t||(i[0].t={}),i[0].trace=r,z.markTime("done with calcdata for "+e),l[e]=i}function d(t,e){var r,n,i=e+1,a=[];for(r=0;r<t.length;r++)n=t[r],0>n?a.push(i+n):a.push(n);return a}function p(t,e,r){var n,i;for(n=0;n<e.length;n++){if(i=e[n],i!==parseInt(i,10))throw new Error("all values in "+r+" must be integers");if(i>=t.data.length||i<-t.data.length)throw new Error(r+" must be valid indices for gd.data.");if(e.indexOf(i,n+1)>-1||i>=0&&e.indexOf(-t.data.length+i)>-1||0>i&&e.indexOf(t.data.length+i)>-1)throw new Error("each index in "+r+" must be unique.")}}function g(t,e,r){if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("currentIndices is a required argument.");if(Array.isArray(e)||(e=[e]),p(t,e,"currentIndices"),"undefined"==typeof r||Array.isArray(r)||(r=[r]),"undefined"!=typeof r&&p(t,r,"newIndices"),"undefined"!=typeof r&&e.length!==r.length)throw new Error("current and new indices must be of equal length.")}function v(t,e,r){var n,i;if(!Array.isArray(t.data))throw new Error("gd.data must be an array.");if("undefined"==typeof e)throw new Error("traces must be defined.");for(Array.isArray(e)||(e=[e]),n=0;n<e.length;n++)if(i=e[n],"object"!=typeof i||Array.isArray(i)||null===i)throw new Error("all values in traces array must be non-array objects");if("undefined"==typeof r||Array.isArray(r)||(r=[r]),"undefined"!=typeof r&&r.length!==e.length)throw new Error("if indices is specified, traces.length must equal indices.length")}function m(t,e,r,n){var i=z.isPlainObject(n);if(!Array.isArray(t.data))throw new Error("gd.data must be an array");if(!z.isPlainObject(e))throw new Error("update must be a key:value object");if("undefined"==typeof r)throw new Error("indices must be an integer or array of integers");p(t,r,"indices");for(var a in e){if(!Array.isArray(e[a])||e[a].length!==r.length)throw new Error("attribute "+a+" must be an array of length equal to indices array length");if(i&&(!(a in n)||!Array.isArray(n[a])||n[a].length!==e[a].length))throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object")}}function y(t,e,r,n){var i,a,o,s,l,u=z.isPlainObject(n),c=[];Array.isArray(r)||(r=[r]),r=d(r,t.data.length-1);for(var h in e)for(var f=0;f<r.length;f++){if(i=t.data[r[f]],o=z.nestedProperty(i,h),a=o.get(),s=e[h][f],!Array.isArray(s))throw new Error("attribute: "+h+" index: "+f+" must be an array");if(!Array.isArray(a))throw new Error("cannot extend missing or non-array attribute: "+h);l=u?n[h][f]:n,C(l)||(l=-1),c.push({prop:o,target:a,insert:s,maxp:Math.floor(l)})}return c}function b(t,e,r,n,i,a){m(t,e,r,n);for(var o,s,l,u=y(t,e,r,n),c=[],h={},f={},d=0;d<u.length;d++)s=u[d].prop,l=u[d].maxp,o=i(u[d].target,u[d].insert),l>=0&&l<o.length&&(c=a(o,l)),l=u[d].target.length,s.set(o),Array.isArray(h[s.astr])||(h[s.astr]=[]),Array.isArray(f[s.astr])||(f[s.astr]=[]),h[s.astr].push(c),f[s.astr].push(l);return{update:h,maxPoints:f}}function x(t){var e;if(z.swapAttrs(t,["?","?0","d?","?bins","nbins?","autobin?","?src","error_?"]),Array.isArray(t.z)&&Array.isArray(t.z[0])&&(t.transpose?delete t.transpose:t.transpose=!0),t.error_x&&t.error_y){var r=t.error_y,n="copy_ystyle"in r?r.copy_ystyle:!(r.color||r.thickness||r.width);z.swapAttrs(t,["error_?.copy_ystyle"]),n&&z.swapAttrs(t,["error_?.color","error_?.thickness","error_?.width"])}if(t.hoverinfo){var i=t.hoverinfo.split("+");for(e=0;e<i.length;e++)"x"===i[e]?i[e]="y":"y"===i[e]&&(i[e]="x");t.hoverinfo=i.join("+")}}function _(t){var e,r={left:0,right:0,bottom:0,top:0};if(t)for(e in t)t.hasOwnProperty(e)&&(r.left+=t[e].left||0,r.right+=t[e].right||0,r.bottom+=t[e].bottom||0,r.top+=t[e].top||0);return r}function w(t,e){var r,n,i,a=t._fullLayout,o=t._context;if(t.emit("plotly_autosize"),t._context.fillFrame)i=window.innerWidth,n=window.innerHeight,document.body.style.overflow="hidden";else if(C(o.frameMargins)&&o.frameMargins>0){var s=_(t._boundingBoxMargins),l=s.left+s.right,u=s.bottom+s.top,c=a._container.node().getBoundingClientRect(),h=1-2*o.frameMargins;i=Math.round(h*(c.width-l)),n=Math.round(h*(c.height-u))}else r=window.getComputedStyle(t),n=parseFloat(r.height)||a.height,i=parseFloat(r.width)||a.width;return Math.abs(a.width-i)>1||Math.abs(a.height-n)>1?(a.height=t.layout.height=n,a.width=t.layout.width=i):"initial"!==a.autosize&&(delete e.autosize,a.autosize=t.layout.autosize=!0),I.sanitizeMargins(a),e}function A(t){var e=L.select(t),r=t._fullLayout;if(r._hasGL3D&&I.subplotsRegistry.gl3d.initAxes(t),r._container=e.selectAll(".plot-container").data([0]),r._container.enter().insert("div",":first-child").classed("plot-container",!0).classed("plotly",!0),r._paperdiv=r._container.selectAll(".svg-container").data([0]),r._paperdiv.enter().append("div").classed("svg-container",!0).style("position","relative"),"initial"===r.autosize&&(w(t,{}),r.autosize=!0,t.layout.autosize=!0),r._glcontainer=r._paperdiv.selectAll(".gl-container").data([0]),r._glcontainer.enter().append("div").classed("gl-container",!0),r._geocontainer=r._paperdiv.selectAll(".geo-container").data([0]),r._geocontainer.enter().append("div").classed("geo-container",!0),r._paperdiv.selectAll(".main-svg").remove(),r._paper=r._paperdiv.insert("svg",":first-child").classed("main-svg",!0),r._toppaper=r._paperdiv.append("svg").classed("main-svg",!0),!r._uid){var n=[];L.selectAll("defs").each(function(){this.id&&n.push(this.id.split("-")[1])}),r._uid=z.randstr(n)}r._paperdiv.selectAll(".main-svg").attr(H.svgAttrs),r._defs=r._paper.append("defs").attr("id","defs-"+r._uid),r._draggers=r._paper.append("g").classed("draglayer",!0);var i=P.Axes.getSubplots(t);i.join("")!==Object.keys(t._fullLayout._plots||{}).join("")&&k(t,i),r._hasCartesian&&M(t,i),r._shapelayer=r._paper.append("g").classed("shapelayer",!0),r._pielayer=r._paper.append("g").classed("pielayer",!0),r._glimages=r._paper.append("g").classed("glimages",!0),r._geoimages=r._paper.append("g").classed("geoimages",!0),r._infolayer=r._toppaper.append("g").classed("infolayer",!0),r._hoverlayer=r._toppaper.append("g").classed("hoverlayer",!0),t.emit("plotly_framework");var a=z.syncOrAsync([T,function(){return P.Axes.doTicks(t,"redraw")},j.init],t);return a&&a.then&&t._promises.push(a),a}function k(t,e){function r(e,r){return function(){return P.Axes.getFromId(t,e,r)}}for(var n,i,a=t._fullLayout._plots={},o=0;o<e.length;o++)n=e[o],i=a[n]={},i.id=n,i.x=r(n,"x"),i.y=r(n,"y"),i.xaxis=i.x(),i.yaxis=i.y()}function M(t,e){function r(t){t.append("g").classed("imagelayer",!0),t.append("g").classed("maplayer",!0),t.append("g").classed("barlayer",!0),t.append("g").classed("errorlayer",!0),t.append("g").classed("boxlayer",!0),t.append("g").classed("scatterlayer",!0)}var n=t._fullLayout,i=[];n._paper.selectAll("g.subplot").data(e).enter().append("g").classed("subplot",!0).each(function(a){var o=n._plots[a],s=o.plotgroup=L.select(this).classed(a,!0),l=o.xaxis,u=o.yaxis;o.overlays=[];var c=P.Axes.getFromId(t,l.overlaying)||l;c!==l&&c.overlaying&&(c=l,l.overlaying=!1);var h=P.Axes.getFromId(t,u.overlaying)||u;h!==u&&h.overlaying&&(h=u,u.overlaying=!1);var f=c._id+h._id;f!==a&&-1!==e.indexOf(f)?(o.mainplot=f,i.push(o),l.domain=c.domain.slice(),u.domain=h.domain.slice()):(o.bg=s.append("rect").style("stroke-width",0),o.gridlayer=s.append("g"),o.overgrid=s.append("g"),o.zerolinelayer=s.append("g"),o.overzero=s.append("g"),o.plot=s.append("svg").call(r),o.overplot=s.append("g"),o.xlines=s.append("path"),o.ylines=s.append("path"),o.overlines=s.append("g"),o.xaxislayer=s.append("g"),o.yaxislayer=s.append("g"),o.overaxes=s.append("g")),o.draglayer=n._draggers.append("g")}),i.forEach(function(t){var e=n._plots[t.mainplot];e.overlays.push(t),t.gridlayer=e.overgrid.append("g"),t.zerolinelayer=e.overzero.append("g"),t.plot=e.overplot.append("svg").call(r),t.xlines=e.overlines.append("path"),t.ylines=e.overlines.append("path"),t.xaxislayer=e.overaxes.append("g"),t.yaxislayer=e.overaxes.append("g")}),e.forEach(function(t){var e=n._plots[t];e.plot.attr("preserveAspectRatio","none").style("fill","none"),e.xlines.style("fill","none").classed("crisp",!0),e.ylines.style("fill","none").classed("crisp",!0)})}function T(t){return z.syncOrAsync([I.doAutoMargin,E],t)}function E(t){var e,r=t._fullLayout,n=r._size,i=P.Axes.list(t);for(e=0;e<i.length;e++)i[e]._linepositions={};r._paperdiv.style({width:r.width+"px",height:r.height+"px"}).selectAll(".main-svg").call(F.setSize,r.width,r.height),t._context.setBackground(t,r.paper_bgcolor);var a=[];return r._paper.selectAll("g.subplot").each(function(e){var i=r._plots[e],o=P.Axes.getFromId(t,e,"x"),s=P.Axes.getFromId(t,e,"y");o.setScale(),s.setScale(),i.bg&&i.bg.call(F.setRect,o._offset-n.p,s._offset-n.p,o._length+2*n.p,s._length+2*n.p).call(N.fill,r.plot_bgcolor),i.plot.call(F.setRect,o._offset,s._offset,o._length,s._length);var l=F.crispRound(t,o.linewidth,1),u=F.crispRound(t,s.linewidth,1),c=n.p+u,h="M"+-c+",",f="h"+(o._length+2*c),d="free"===o.anchor&&-1===a.indexOf(o._id),p=n.h*(1-(o.position||0))+l/2%1,g=o.anchor===s._id&&(o.mirror||"top"!==o.side)||"all"===o.mirror||"allticks"===o.mirror||o.mirrors&&o.mirrors[s._id+"bottom"],v=s._length+n.p+l/2,m=o.anchor===s._id&&(o.mirror||"top"===o.side)||"all"===o.mirror||"allticks"===o.mirror||o.mirrors&&o.mirrors[s._id+"top"],y=-n.p-l/2,b=n.p,x=g?0:l,_=m?0:l,w=","+(-b-_)+"v"+(s._length+2*b+_+x),A="free"===s.anchor&&-1===a.indexOf(s._id),k=n.w*(s.position||0)+u/2%1,M=s.anchor===o._id&&(s.mirror||"right"!==s.side)||"all"===s.mirror||"allticks"===s.mirror||s.mirrors&&s.mirrors[o._id+"left"],T=-n.p-u/2,E=s.anchor===o._id&&(s.mirror||"right"===s.side)||"all"===s.mirror||"allticks"===s.mirror||s.mirrors&&s.mirrors[o._id+"right"],L=o._length+n.p+u/2;o._linepositions[e]=[g?v:void 0,m?y:void 0,d?p:void 0],o.anchor===s._id?o._linepositions[e][3]="top"===o.side?y:v:d&&(o._linepositions[e][3]=p),s._linepositions[e]=[M?T:void 0,E?L:void 0,A?k:void 0],s.anchor===o._id?s._linepositions[e][3]="right"===s.side?L:T:A&&(s._linepositions[e][3]=k);var S="translate("+o._offset+","+s._offset+")",C=S,z=S;d&&(C="translate("+o._offset+","+n.t+")",y+=s._offset-n.t,v+=s._offset-n.t),A&&(z="translate("+n.l+","+s._offset+")",T+=o._offset-n.l,L+=o._offset-n.l),i.xlines.attr("transform",C).attr("d",(g?h+v+f:"")+(m?h+y+f:"")+(d?h+p+f:"")||"M0,0").style("stroke-width",l+"px").call(N.stroke,o.showline?o.linecolor:"rgba(0,0,0,0)"),i.ylines.attr("transform",z).attr("d",(M?"M"+T+w:"")+(E?"M"+L+w:"")+(A?"M"+k+w:"")||"M0,0").attr("stroke-width",u+"px").call(N.stroke,s.showline?s.linecolor:"rgba(0,0,0,0)"),i.xaxislayer.attr("transform",C),i.yaxislayer.attr("transform",z),i.gridlayer.attr("transform",S),i.zerolinelayer.attr("transform",S),i.draglayer.attr("transform",S),d&&a.push(o._id),A&&a.push(s._id)}),P.Axes.makeClipPaths(t),V.draw(t,"gtitle"),q(t),t._promises.length&&Promise.all(t._promises)}var L=t("d3"),S=t("gl-mat4/fromQuat"),C=t("fast-isnumeric"),P=t("../plotly"),z=t("../lib"),R=t("../lib/events"),O=t("../lib/queue"),I=t("../plots/plots"),j=t("../plots/cartesian/graph_interact"),N=t("../components/color"),F=t("../components/drawing"),B=t("../components/errorbars"),D=t("../components/legend"),U=t("../components/shapes"),V=t("../components/titles"),q=t("../components/modebar/manage"),H=t("../constants/xmlns_namespaces");P.plot=function(t,e,r,i){function l(){var e,r,n,i=t.calcdata;for(D.draw(t),e=0;e<i.length;e++)r=i[e],n=r[0].trace,n.visible===!0&&n._module.colorbar?n._module.colorbar(t,r):I.autoMargin(t,"cb"+n.uid);return I.doAutoMargin(t),I.previousPromises(t)}function c(){var e=JSON.stringify(M._size)===C?[]:[l,T];return z.syncOrAsync(e.concat(j.init),t)}function h(){if(E){for(var e,r,n=I.getSubplotIds(M,"cartesian"),i=t._modules,a=0;a<n.length;a++){e=M._plots[n[a]];for(var o=0;o<i.length;o++)r=i[o],r.setPositions&&r.setPositions(t,e)}return z.markTime("done with bar/box adjustments"),B.calc(t),z.markTime("done ErrorBars.calc"),z.syncOrAsync([U.calcAutorange,P.Annotations.calcAutorange,d],t)}}function d(){for(var e=P.Axes.list(t,"",!0),r=0;r<e.length;r++)P.Axes.doAutoRange(e[r])}function p(){return P.Axes.doTicks(t,"redraw")}function g(){for(var e=t.calcdata,r=0;r<e.length;r++){var n=e[r][0].trace,i=n.visible===!0,a=n.uid;i&&I.traceIs(n,"2dMap")||M._paper.selectAll(".hm"+a+",.contour"+a+",#clip"+a).remove(),i&&n._module.colorbar||M._infolayer.selectAll(".cb"+a).remove()}var o=I.subplotsRegistry;return M._hasGL3D&&o.gl3d.plot(t),M._hasGeo&&o.geo.plot(t),M._hasGL2D&&o.gl2d.plot(t),(M._hasCartesian||M._hasPie)&&o.cartesian.plot(t),I.style(t),z.markTime("done Plots.style"),U.drawAll(t),P.Annotations.drawAll(t),I.addLinks(t),t._replotting=!1,I.previousPromises(t)}function v(){U.drawAll(t),P.Annotations.drawAll(t),D.draw(t)}function m(){z.markTime("done plot"),t.emit("plotly_afterplot")}z.markTime("in plot"),t=n(t),R.init(t);var y=R.triggerHandler(t,"plotly_beforeplot",[e,r,i]);if(y===!1)return Promise.reject();e||r||z.isPlotDiv(t)||console.log("Warning: calling Plotly.plot as if redrawing but this container doesn't yet have a plot.",t),a(t,i),r||(r={}),L.select(t).classed("js-plotly-plot",!0),F.makeTester(t),t._promises=[];var b=0===(t.data||[]).length&&Array.isArray(e);if(Array.isArray(e)&&(u(e,t.data),b?t.data=e:t.data.push.apply(t.data,e),t.empty=!1),(!t.layout||b)&&(t.layout=s(r)),t._dragging)return t._replotPending=!0,Promise.reject();if(t._replotPending=!1,I.supplyDefaults(t),e&&e[0]&&e[0].r)return o(t,e,r);t._replotting=!0;var x=t._fullData.length>0,_=P.Axes.getSubplots(t).join(""),w=Object.keys(t._fullLayout._plots||{}).join(""),k=w===_;x?(t.framework!==A||b||!k)&&(t.framework=A,A(t)):k?b&&A(t):(t.framework=A,A(t));var M=t._fullLayout,E=!t.calcdata||t.calcdata.length!==(t.data||[]).length;E&&(f(t),(t._context.doubleClick!==!1||t._context.displayModeBar!==!1)&&P.Axes.saveRangeInitial(t));for(var S=0;S<t.calcdata.length;S++)t.calcdata[S][0].trace=t._fullData[S];var C=JSON.stringify(M._size),O=z.syncOrAsync([I.previousPromises,l,T,c,h,p,g,v],t,m);return O&&O.then?O:Promise.resolve(t)},P.redraw=function(t){return t=n(t),z.isPlotDiv(t)?(t.calcdata=void 0,P.plot(t).then(function(){return t.emit("plotly_redraw"),t})):void console.log("This element is not a Plotly Plot",t)},P.newPlot=function(t,e,r,i){return t=n(t),I.purge(t),P.plot(t,e,r,i)},P.extendTraces=function G(t,e,r,i){t=n(t);var a=b(t,e,r,i,function(t,e){return t.concat(e)},function(t,e){return t.splice(0,t.length-e)}),o=P.redraw(t),s=[t,a.update,r,a.maxPoints];return O&&O.add(t,P.prependTraces,s,G,arguments),o},P.prependTraces=function Y(t,e,r,i){t=n(t);var a=b(t,e,r,i,function(t,e){return e.concat(t)},function(t,e){return t.splice(e,t.length)}),o=P.redraw(t),s=[t,a.update,r,a.maxPoints];return O&&O.add(t,P.extendTraces,s,Y,arguments),o},P.addTraces=function X(t,e,r){t=n(t);var i,a,o=[],s=P.deleteTraces,l=X,c=[t,o],h=[t,e];for(v(t,e,r),Array.isArray(e)||(e=[e]),u(e,t.data),i=0;i<e.length;i+=1)t.data.push(e[i]);for(i=0;i<e.length;i++)o.push(-e.length+i);if("undefined"==typeof r)return a=P.redraw(t),O&&O.add(t,s,c,l,h),a;Array.isArray(r)||(r=[r]);try{g(t,o,r)}catch(f){throw t.data.splice(t.data.length-e.length,e.length),f}return O&&O.startSequence(t),O&&O.add(t,s,c,l,h),a=P.moveTraces(t,o,r),O&&O.stopSequence(t),a},P.deleteTraces=function W(t,e){t=n(t);var r,i,a=[],o=P.addTraces,s=W,l=[t,a,e],u=[t,e];if("undefined"==typeof e)throw new Error("indices must be an integer or array of integers.");for(Array.isArray(e)||(e=[e]),p(t,e,"indices"),e=d(e,t.data.length-1),e.sort(z.sorterDes),r=0;r<e.length;r+=1)i=t.data.splice(e[r],1)[0],a.push(i);var c=P.redraw(t);return O&&O.add(t,o,l,s,u),c},P.moveTraces=function Z(t,e,r){t=n(t);var i,a=[],o=[],s=Z,l=Z,u=[t,r,e],c=[t,e,r];if(g(t,e,r),e=Array.isArray(e)?e:[e],"undefined"==typeof r)for(r=[],i=0;i<e.length;i++)r.push(-e.length+i);for(r=Array.isArray(r)?r:[r],e=d(e,t.data.length-1),r=d(r,t.data.length-1),i=0;i<t.data.length;i++)-1===e.indexOf(i)&&a.push(t.data[i]);for(i=0;i<e.length;i++)o.push({newIndex:r[i],trace:t.data[e[i]]});for(o.sort(function(t,e){return t.newIndex-e.newIndex}),i=0;i<o.length;i+=1)a.splice(o[i].newIndex,0,o[i].trace);t.data=a;var h=P.redraw(t);return O&&O.add(t,s,u,l,c),h},P.restyle=function $(t,e,r,i){function a(){return i.map(function(){})}function o(t){var e=P.Axes.id2name(t);-1===p.indexOf(e)&&p.push(e)}function s(t){return"LAYOUT"+t+".autorange"}function l(t){return"LAYOUT"+t+".range"}function u(e,r,n){if(Array.isArray(e))return void e.forEach(function(t){u(t,r,n)});if(!(e in f)){var o;o="LAYOUT"===e.substr(0,6)?z.nestedProperty(t.layout,e.replace("LAYOUT","")):z.nestedProperty(t.data[i[n]],e),e in T||(T[e]=a()),void 0===T[e][n]&&(T[e][n]=o.get()),void 0!==r&&o.set(r)}}t=n(t);var c,h=t._fullLayout,f={};if("string"==typeof e)f[e]=r;else{if(!z.isPlainObject(e))return console.log("restyle fail",e,r,i),Promise.reject();f=e,void 0===i&&(i=r)}Object.keys(f).length&&(t.changed=!0),C(i)?i=[i]:Array.isArray(i)&&i.length||(i=t._fullData.map(function(t,e){return e}));var d=["mode","visible","type","orientation","fill","histfunc","histnorm","text","x","y","z","xtype","x0","dx","ytype","y0","dy","xaxis","yaxis","line.width","connectgaps","transpose","zsmooth","showscale","marker.showscale","zauto","marker.cauto","autocolorscale","marker.autocolorscale","colorscale","marker.colorscale","reversescale","marker.reversescale","autobinx","nbinsx","xbins","xbins.start","xbins.end","xbins.size","autobiny","nbinsy","ybins","ybins.start","ybins.end","ybins.size","autocontour","ncontours","contours","contours.coloring","error_y","error_y.visible","error_y.value","error_y.type","error_y.traceref","error_y.array","error_y.symmetric","error_y.arrayminus","error_y.valueminus","error_y.tracerefminus","error_x","error_x.visible","error_x.value","error_x.type","error_x.traceref","error_x.array","error_x.symmetric","error_x.arrayminus","error_x.valueminus","error_x.tracerefminus","swapxy","swapxyaxes","orientationaxes","marker.colors","values","labels","label0","dlabel","sort","textinfo","textposition","textfont.size","textfont.family","textfont.color","insidetextfont.size","insidetextfont.family","insidetextfont.color","outsidetextfont.size","outsidetextfont.family","outsidetextfont.color","hole","scalegroup","domain","domain.x","domain.y","domain.x[0]","domain.x[1]","domain.y[0]","domain.y[1]","tilt","tiltaxis","depth","direction","rotation","pull"];for(c=0;c<i.length;c++)if(I.traceIs(t._fullData[i[c]],"box")){d.push("name");break}var p,g=["marker","marker.size","textfont","boxpoints","jitter","pointpos","whiskerwidth","boxmean"],v=["zmin","zmax","zauto","marker.cmin","marker.cmax","marker.cauto","contours.start","contours.end","contours.size","contours.showlines","line","line.smoothing","line.shape","error_y.width","error_x.width","error_x.copy_ystyle","marker.maxdisplayed"],m=["type","x","y","x0","y0","orientation","xaxis","yaxis"],y=!1,b=!1,_=!1,w=!1,A=!1,k=!1,M={},T={},E={};(h._hasGL3D||h._hasGeo||h._hasGL2D)&&(_=!0);var L=["zmin","zmax"],S=["xbins.start","xbins.end","xbins.size"],R=["ybins.start","ybins.end","ybins.size"],j=["contours.start","contours.end","contours.size"];for(var N in f){var F,B,U,V,q,H=f[N];if(M[N]=H,"LAYOUT"!==N.substr(0,6)){for(T[N]=a(),c=0;c<i.length;c++){if(F=t.data[i[c]],B=t._fullData[i[c]],U=z.nestedProperty(F,N),V=U.get(),q=Array.isArray(H)?H[c%H.length]:H,-1!==L.indexOf(N))u("zauto",!1,c);else if("colorscale"===N)u("autocolorscale",!1,c);else if("autocolorscale"===N)u("colorscale",void 0,c);else if("marker.colorscale"===N)u("marker.autocolorscale",!1,c);else if("marker.autocolorscale"===N)u("marker.colorscale",void 0,c);else if("zauto"===N)u(L,void 0,c);else if(-1!==S.indexOf(N))u("autobinx",!1,c);else if("autobinx"===N)u(S,void 0,c);else if(-1!==R.indexOf(N))u("autobiny",!1,c);else if("autobiny"===N)u(R,void 0,c);else if(-1!==j.indexOf(N))u("autocontour",!1,c);else if("autocontour"===N)u(j,void 0,c);else if(-1!==["x0","dx"].indexOf(N)&&B.x&&"scaled"!==B.xtype)u("xtype","scaled",c);else if(-1!==["y0","dy"].indexOf(N)&&B.y&&"scaled"!==B.ytype)u("ytype","scaled",c);else if("colorbar.thicknessmode"===N&&U.get()!==q&&-1!==["fraction","pixels"].indexOf(q)&&B.colorbar){var G=-1!==["top","bottom"].indexOf(B.colorbar.orient)?h.height-h.margin.t-h.margin.b:h.width-h.margin.l-h.margin.r;u("colorbar.thickness",B.colorbar.thickness*("fraction"===q?1/G:G),c)}else if("colorbar.lenmode"===N&&U.get()!==q&&-1!==["fraction","pixels"].indexOf(q)&&B.colorbar){var Y=-1!==["top","bottom"].indexOf(B.colorbar.orient)?h.width-h.margin.l-h.margin.r:h.height-h.margin.t-h.margin.b;u("colorbar.len",B.colorbar.len*("fraction"===q?1/Y:Y),c)}else"colorbar.tick0"===N||"colorbar.dtick"===N?u("colorbar.tickmode","linear",c):"colorbar.tickmode"===N&&u(["colorbar.tick0","colorbar.dtick"],void 0,c);if("type"===N&&"pie"===q!=("pie"===V)){var X="x",W="y";"bar"!==q&&"bar"!==V||"h"!==F.orientation||(X="y",W="x"),z.swapAttrs(F,["?","?src"],"labels",X),z.swapAttrs(F,["d?","?0"],"label",X),z.swapAttrs(F,["?","?src"],"values",W),"pie"===V?(z.nestedProperty(F,"marker.color").set(z.nestedProperty(F,"marker.colors").get()),h._pielayer.selectAll("g.trace").remove()):I.traceIs(F,"cartesian")&&(z.nestedProperty(F,"marker.colors").set(z.nestedProperty(F,"marker.color").get()),E[F.xaxis||"x"]=!0,E[F.yaxis||"y"]=!0)}T[N][c]=V;var Z=["swapxy","swapxyaxes","orientation","orientationaxes"];if(-1!==Z.indexOf(N)){if("orientation"===N){if(U.set(q),U.get()===T[N][c])continue}else"orientationaxes"===N&&(F.orientation={v:"h",h:"v"}[B.orientation]);x(F)}else U.set(q)}if(-1!==["swapxyaxes","orientationaxes"].indexOf(N)&&P.Axes.swap(t,i),"orientationaxes"===N){var K=z.nestedProperty(t.layout,"hovermode");"x"===K.get()?K.set("y"):"y"===K.get()&&K.set("x")}if(-1!==i.indexOf(0)&&-1!==m.indexOf(N)&&(P.Axes.clearTypes(t,i),y=!0),(-1===["autobinx","autobiny","zauto"].indexOf(N)||q!==!1)&&(A=!0),(-1!==["colorbar","line"].indexOf(U.parts[0])||"marker"===U.parts[0]&&"colorbar"===U.parts[1])&&(k=!0),-1!==d.indexOf(N)){if(-1!==["orientation","type"].indexOf(N)){for(p=[],c=0;c<i.length;c++){var Q=t.data[i[c]];I.traceIs(Q,"cartesian")&&(o(Q.xaxis||"x"),o(Q.yaxis||"y"),"type"===e&&u(["autobinx","autobiny"],!0,c))}u(p.map(s),!0,0),u(p.map(l),[0,1],0)}y=!0}else-1!==v.indexOf(N)?_=!0:-1!==g.indexOf(N)&&(b=!0)}else U=z.nestedProperty(t.layout,N.replace("LAYOUT","")),T[N]=[U.get()],U.set(Array.isArray(H)?H[0]:H),y=!0}var J=Object.keys(E);t:for(c=0;c<J.length;c++){for(var tt=J[c],et=tt.charAt(0),rt=et+"axis",nt=0;nt<t.data.length;nt++)if(I.traceIs(t.data[nt],"cartesian")&&(t.data[nt][rt]||et)===tt)continue t;u("LAYOUT"+P.Axes.id2name(tt),null,0)}O&&O.add(t,$,[t,T,i],$,[t,M,i]);var it=!1;P.Axes.list(t).forEach(function(t){t.autorange&&(it=!0)}),(y||w||b&&it)&&(t.calcdata=void 0);var at;w?at=[function(){var e=t.layout;return t.layout=void 0,P.plot(t,"",e)}]:y||_||b?at=[P.plot]:(I.supplyDefaults(t),at=[I.previousPromises],A&&at.push(function(){var e,r,n;for(e=0;e<t.calcdata.length;e++)r=t.calcdata[e],n=(((r[0]||{}).trace||{})._module||{}).arraysToCalcdata,n&&n(r);return I.style(t),D.draw(t),I.previousPromises(t)}),k&&at.push(function(){return t.calcdata.forEach(function(t){if((t[0].t||{}).cb){var e=t[0].trace,r=t[0].t.cb;I.traceIs(e,"contour")&&r.line({width:e.contours.showlines!==!1?e.line.width:0,dash:e.line.dash,color:"line"===e.contours.coloring?r._opts.line.color:e.line.color}),I.traceIs(e,"markerColorscale")?r.options(e.marker.colorbar)():r.options(e.colorbar)()}}),I.previousPromises(t)}));var ot=z.syncOrAsync(at,t);return ot&&ot.then||(ot=Promise.resolve()),ot.then(function(){return t.emit("plotly_restyle",z.extendDeep([],[M,i])),t})},P.relayout=function K(t,e,r){function i(t,e){if(Array.isArray(t))return void t.forEach(function(t){i(t,e)});if(!(t in g)){var r=z.nestedProperty(d,t);t in M||(M[t]=r.get()),void 0!==e&&r.set(e)}}function a(t,e){var r=P.Axes.id2name(t[e+"ref"]||e);return(p[r]||{}).autorange}if(t=n(t),t.framework&&t.framework.isPolar)return Promise.resolve(t);var o,s,l,u,c,h,f,d=t.layout,p=t._fullLayout,g={},v=!1,m=!1,y=!1,b=!1,x=!1,_=!1;if("string"==typeof e)g[e]=r;else{if(!z.isPlainObject(e))return console.log("relayout fail",e,r),Promise.reject();g=e}for(Object.keys(g).length&&(t.changed=!0),l=Object.keys(g),s=P.Axes.list(t),f=0;f<l.length;f++){if(0===l[f].indexOf("allaxes")){for(var A=0;A<s.length;A++)c=s[A]._id.substr(1),h=-1!==c.indexOf("scene")?c+".":"",o=l[f].replace("allaxes",h+s[A]._name),g[o]||(g[o]=g[l[f]]);delete g[l[f]]}l[f].match(/^annotations\[[0-9-]+\].ref$/)&&(u=g[l[f]].split("y"),g[l[f].replace("ref","xref")]=u[0],g[l[f].replace("ref","yref")]=2===u.length?"y"+u[1]:"paper",delete g[l[f]])}var k={},M={},E=["height","width"];for(var L in g){var S=z.nestedProperty(d,L),C=g[L],R=S.parts.length,j="string"==typeof S.parts[R-1]?R-1:R-2,N=S.parts[j],F=S.parts[j-1]+"."+N,B=S.parts.slice(0,j).join("."),U=z.nestedProperty(t.layout,B).get(),H=z.nestedProperty(p,B).get();if(k[L]=C,M[L]="reverse"===N?C:S.get(),-1!==E.indexOf(L)?i("autosize",!1):"autosize"===L?i(E,void 0):F.match(/^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/)?i(B+".autorange",!1):F.match(/^[xyz]axis[0-9]*\.autorange$/)?i([B+".range[0]",B+".range[1]"],void 0):F.match(/^aspectratio\.[xyz]$/)?i(S.parts[0]+".aspectmode","manual"):F.match(/^aspectmode$/)?i([B+".x",B+".y",B+".z"],void 0):"tick0"===N||"dtick"===N?i(B+".tickmode","linear"):"tickmode"===N?i([B+".tick0",B+".dtick"],void 0):/[xy]axis[0-9]*?$/.test(N)&&!Object.keys(C||{}).length&&(x=!0),"type"===N&&"log"===H.type!=("log"===C)){var G=U;if(G&&G.range)if(H.autorange)"log"===C&&(G.range=G.range[1]>G.range[0]?[1,2]:[2,1]);else{var Y=G.range[0],X=G.range[1];"log"===C?(0>=Y&&0>=X&&i(B+".autorange",!0),0>=Y?Y=X/1e6:0>=X&&(X=Y/1e6),i(B+".range[0]",Math.log(Y)/Math.LN10),i(B+".range[1]",Math.log(X)/Math.LN10)):(i(B+".range[0]",Math.pow(10,Y)),i(B+".range[1]",Math.pow(10,X)))}else i(B+".autorange",!0)}if("reverse"===N)U.range?U.range.reverse():(i(B+".autorange",!0),U.range=[1,0]),H.autorange?x=!0:b=!0;else if("annotations"===S.parts[0]||"shapes"===S.parts[0]){var W=S.parts[1],Z=S.parts[0],$=d[Z]||[],Q=P[z.titleCase(Z)],J=$[W]||{};2===S.parts.length&&("add"===g[L]||z.isPlainObject(g[L])?M[L]="remove":"remove"===g[L]?-1===W?(M[Z]=$,delete M[L]):M[L]=J:console.log("???",g)),!a(J,"x")&&!a(J,"y")||z.containsAny(L,["color","opacity","align","dash"])||(x=!0),Q.draw(t,W,S.parts.slice(2).join("."),g[L]),delete g[L]}else 0===S.parts[0].indexOf("scene")?b=!0:0===S.parts[0].indexOf("geo")?b=!0:!p._hasGL2D||-1===L.indexOf("axis")&&"plot_bgcolor"!==S.parts[0]?"hiddenlabels"===L?x=!0:-1!==S.parts[0].indexOf("legend")?v=!0:-1!==L.indexOf("title")?m=!0:-1!==S.parts[0].indexOf("bgcolor")?y=!0:S.parts.length>1&&z.containsAny(S.parts[1],["tick","exponent","grid","zeroline"])?m=!0:-1!==L.indexOf(".linewidth")&&-1!==L.indexOf("axis")?m=y=!0:S.parts.length>1&&-1!==S.parts[1].indexOf("line")?y=!0:S.parts.length>1&&"mirror"===S.parts[1]?m=y=!0:"margin.pad"===L?m=y=!0:"margin"===S.parts[0]||"autorange"===S.parts[1]||"rangemode"===S.parts[1]||"type"===S.parts[1]||"domain"===S.parts[1]||L.match(/^(bar|box|font)/)?x=!0:-1!==["hovermode","dragmode"].indexOf(L)?_=!0:-1===["hovermode","dragmode","height","width","autosize"].indexOf(L)&&(b=!0):b=!0,S.set(C)}O&&O.add(t,K,[t,M],K,[t,k]),g.autosize&&(g=w(t,g)),(g.height||g.width||g.autosize)&&(x=!0);var tt=Object.keys(g),et=[I.previousPromises];if(b||x)et.push(function(){return t.layout=void 0,x&&(t.calcdata=void 0),P.plot(t,"",d)});else if(tt.length&&(I.supplyDefaults(t),p=t._fullLayout,v&&et.push(function(){return D.draw(t),I.previousPromises(t)}),y&&et.push(T),m&&et.push(function(){return P.Axes.doTicks(t,"redraw"),V.draw(t,"gtitle"),I.previousPromises(t)}),_)){var rt;for(q(t),rt=I.getSubplotIds(p,"gl3d"),f=0;f<rt.length;f++)c=p[rt[f]]._scene,c.updateFx(p.dragmode,p.hovermode);for(rt=I.getSubplotIds(p,"gl2d"),f=0;f<rt.length;f++)c=p._plots[rt[f]]._scene2d,c.updateFx(p);for(rt=I.getSubplotIds(p,"geo"),f=0;f<rt.length;f++){var nt=p[rt[f]]._geo;nt.updateFx(p.hovermode)}}var it=z.syncOrAsync(et,t);return it&&it.then||(it=Promise.resolve(t)),it.then(function(){return t.emit("plotly_relayout",z.extendDeep({},k)),t})}},{"../components/color":299,"../components/drawing":317,"../components/errorbars":323,"../components/legend":326,"../components/modebar/manage":329,"../components/shapes":331,"../components/titles":332,"../constants/xmlns_namespaces":338,
+"../lib":349,"../lib/events":344,"../lib/queue":355,"../plotly":366,"../plots/cartesian/graph_interact":374,"../plots/plots":413,d3:70,"fast-isnumeric":74,"gl-mat4/fromQuat":91}],363:[function(t,e,r){"use strict";function n(t,e){try{t._fullLayout._paper.style("background",e)}catch(r){console.log(r)}}e.exports={staticPlot:!1,editable:!1,autosizable:!1,fillFrame:!1,frameMargins:0,scrollZoom:!1,doubleClick:"reset+autosize",showTips:!0,showLink:!1,sendData:!0,linkText:"Edit chart",showSources:!1,displayModeBar:"hover",modeBarButtonsToRemove:[],modeBarButtonsToAdd:[],modeBarButtons:!1,displaylogo:!0,plotGlPixelRatio:2,setBackground:n,topojsonURL:"https://cdn.plot.ly/"}},{}],364:[function(t,e,r){"use strict";function n(t){var e=v.attributes,r=l({type:t}),n=c(t),i=f(t),a={},h={};a.type=null,b(a,e),a=o(r.attributes,a,"attributes",t),void 0!==i.attributes&&b(a,i.attributes),a.type=t,a=u(a),s(a),E.traces[t]=y({},n,{attributes:a}),void 0!==r.layoutAttributes&&(h=o(r.layoutAttributes,h,"layoutAttributes",t),s(h),E.traces[t].layoutAttributes=h)}function i(){var t=v.layoutAttributes,e={};e=o(t,e,"layoutAttributes","*"),e=h(e),e=d(e),e=u(e),s(e),e=p(e),E.layout={layoutAttributes:e}}function a(){E.defs={valObjects:m.valObjects,metaKeys:T.concat(["description","role"])}}function o(t,e,r,n){var i,a,s,u,c;return Object.keys(t).forEach(function(h){return h===_?void Object.keys(t[h]).forEach(function(u){i=l({module:t[h][u]}),void 0!==i&&(a=i[r],s=o(a,{},r,n),m.nestedProperty(e,u).set(b({},s)))}):h===w?void Object.keys(t[h]).forEach(function(i){i===n&&(u=l({module:t[h][i]}),void 0!==u&&(c=u[r],c=o(c,{},r,n),x(e,c)))}):void(e[h]=m.isPlainObject(t[h])?x({},t[h]):t[h])}),e}function s(t){function e(t){return{valType:"string"}}function r(t,r,n){C.isValObject(t)?"data_array"===t.valType?(t.role="data",n[r+"src"]=e(r)):t.arrayOk===!0&&(n[r+"src"]=e(r)):m.isPlainObject(t)&&(t.role="object")}C.crawl(t,r)}function l(t){if("type"in t)return"area"===t.type?{attributes:L}:v.getModule({type:t.type});var e=v.subplotsRegistry,r=t.module;return e[r]?e[r]:"module"in t?g[r]:void 0}function u(t){return Object.keys(t).forEach(function(e){"_"===e.charAt(0)&&-1===T.indexOf(e)&&delete t[e]}),t}function c(t){return"area"===t?{}:v.modules[t].meta||{}}function h(t){return y(t,{radialaxis:S.radialaxis,angularaxis:S.angularaxis}),y(t,S.layout),t}function f(t){if("area"===t)return{};var e=v.subplotsRegistry,r=Object.keys(e).filter(function(e){return v.traceIs({type:t},e)})[0];return void 0===r?{}:e[r]}function d(t){var e=v.subplotsRegistry;return Object.keys(t).forEach(function(r){Object.keys(e).forEach(function(n){var i,a=e[n];i="cartesian"===n||"gl2d"===n?a.attrRegex.x.test(r)||a.attrRegex.y.test(r):a.attrRegex.test(r),i&&(t[r][A]=!0)})}),t}function p(t){return Object.keys(t).forEach(function(e){var r=b({},t[e]);if(r[k]===!0){var n=e.substr(0,e.length-1);delete r[k],t[e]={items:{}},t[e].items[n]=r,t[e].role="object"}}),t}var g=t("../plotly"),v=t("../plots/plots"),m=t("../lib"),y=m.extendFlat,b=m.extendDeep,x=m.extendDeepAll,_="_nestedModules",w="_composedModules",A="_isSubplotObj",k="_isLinkedToArray",M="_deprecated",T=[A,k,M],E={traces:{},layout:{},defs:{}},L=t("../plots/polar/area_attributes"),S=t("../plots/polar/axis_attributes"),C=e.exports={};C.get=function(){return v.allTypes.concat("area").forEach(n),i(),a(),E},C.crawl=function(t,e){Object.keys(t).forEach(function(r){var n=t[r];-1===T.indexOf(r)&&(e(n,r,t),C.isValObject(n)||m.isPlainObject(n)&&C.crawl(n,e))})},C.isValObject=function(t){return t&&void 0!==t.valType}},{"../lib":349,"../plotly":366,"../plots/plots":413,"../plots/polar/area_attributes":414,"../plots/polar/axis_attributes":415}],365:[function(t,e,r){"use strict";var n=t("../plotly");e.exports=function(t){return n.Lib.extendFlat(n.defaultConfig,t)}},{"../plotly":366}],366:[function(t,e,r){"use strict";t("es6-promise").polyfill(),r.Lib=t("./lib"),r.util=t("./lib/svg_text_utils"),r.Queue=t("./lib/queue"),t("../build/plotcss"),r.MathJaxConfig=t("./fonts/mathjax_config"),r.defaultConfig=t("./plot_api/plot_config");var n=r.Plots=t("./plots/plots");r.Axes=t("./plots/cartesian/axes"),r.Fx=t("./plots/cartesian/graph_interact"),r.micropolar=t("./plots/polar/micropolar"),r.Color=t("./components/color"),r.Drawing=t("./components/drawing"),r.Colorscale=t("./components/colorscale"),r.Colorbar=t("./components/colorbar"),r.ErrorBars=t("./components/errorbars"),r.Annotations=t("./components/annotations"),r.Shapes=t("./components/shapes"),r.Legend=t("./components/legend"),r.ModeBar=t("./components/modebar"),r.register=function(t){if(!t)throw new Error("No argument passed to Plotly.register.");t&&!Array.isArray(t)&&(t=[t]);for(var e=0;e<t.length;e++){var r=t[e];if(r&&"trace"!==r.moduleType)throw new Error("Invalid module was attempted to be registered!");n.register(r,r.name,r.categories,r.meta),n.subplotsRegistry[r.basePlotModule.name]||n.registerSubplot(r.basePlotModule)}},r.register(t("./traces/scatter")),t("./plot_api/plot_api"),r.PlotSchema=t("./plot_api/plot_schema"),r.Snapshot=t("./snapshot")},{"../build/plotcss":1,"./components/annotations":297,"./components/color":299,"./components/colorbar":304,"./components/colorscale":312,"./components/drawing":317,"./components/errorbars":323,"./components/legend":326,"./components/modebar":328,"./components/shapes":331,"./fonts/mathjax_config":340,"./lib":349,"./lib/queue":355,"./lib/svg_text_utils":360,"./plot_api/plot_api":362,"./plot_api/plot_config":363,"./plot_api/plot_schema":364,"./plots/cartesian/axes":369,"./plots/cartesian/graph_interact":374,"./plots/plots":413,"./plots/polar/micropolar":416,"./snapshot":420,"./traces/scatter":511,"es6-promise":73}],367:[function(t,e,r){"use strict";e.exports={type:{valType:"enumerated",values:[],dflt:"scatter"},visible:{valType:"enumerated",values:[!0,!1,"legendonly"],dflt:!0},showlegend:{valType:"boolean",dflt:!0},legendgroup:{valType:"string",dflt:""},opacity:{valType:"number",min:0,max:1,dflt:1},name:{valType:"string"},uid:{valType:"string",dflt:""},hoverinfo:{valType:"flaglist",flags:["x","y","z","text","name"],extras:["all","none"],dflt:"all"},stream:{token:{valType:"string",noBlank:!0,strict:!0},maxpoints:{valType:"number",min:0}}}},{}],368:[function(t,e,r){"use strict";e.exports={xaxis:{valType:"axisid",dflt:"x"},yaxis:{valType:"axisid",dflt:"y"}}},{}],369:[function(t,e,r){"use strict";function n(t){var e,r,n=t.tickvals,i=t.ticktext,a=new Array(n.length),o=1.0001*t.range[0]-1e-4*t.range[1],l=1.0001*t.range[1]-1e-4*t.range[0],u=Math.min(o,l),c=Math.max(o,l),h=0;for(Array.isArray(i)||(i=[]),r=0;r<n.length;r++)e=t.d2l(n[r]),e>u&&c>e&&(void 0===i[r]?a[h]=A.tickText(t,e):a[h]=s(t,e,String(i[r])),h++);return h<n.length&&a.splice(h,n.length-h),a}function i(t,e,r){return e*_.Lib.roundUp(t/e,r)}function a(t){var e,r=t.dtick;if(t._tickexponent=0,x(r)||"string"==typeof r||(r=1),"category"===t.type)t._tickround=null;else if(x(r)||"L"===r.charAt(0))if("date"===t.type)r>=864e5?t._tickround="d":r>=36e5?t._tickround="H":r>=6e4?t._tickround="M":r>=1e3?t._tickround="S":t._tickround=3-Math.round(Math.log(r/2)/Math.LN10);else{x(r)||(r=Number(r.substr(1))),t._tickround=2-Math.floor(Math.log(r)/Math.LN10+.01),e="log"===t.type?Math.pow(10,Math.max(t.range[0],t.range[1])):Math.max(Math.abs(t.range[0]),Math.abs(t.range[1]));var n=Math.floor(Math.log(e)/Math.LN10+.01);Math.abs(n)>3&&("SI"===t.exponentformat||"B"===t.exponentformat?t._tickexponent=3*Math.round((n-1)/3):t._tickexponent=n)}else"M"===r.charAt(0)?t._tickround=2===r.length?"m":"y":t._tickround=null}function o(t,e){var r=t.match(F),n=new Date(e);if(r){var i=Math.min(+r[1]||6,6),a=String(e/1e3%1+2.0000005).substr(2,i).replace(/0+$/,"")||"0";return b.time.format(t.replace(F,a))(n)}return b.time.format(t)(n)}function s(t,e,r){var n=t.tickfont||t._td._fullLayout.font;return{x:e,dx:0,dy:0,text:r||"",fontSize:n.size,font:n.family,fontColor:n.color}}function l(t,e,r,n){var i,a=e.x,s=t._tickround,l=new Date(a),u="";r&&t.hoverformat?i=o(t.hoverformat,a):t.tickformat?i=o(t.tickformat,a):(n&&(x(s)?s+=2:s={y:"m",m:"d",d:"H",H:"M",M:"S",S:2}[s]),"y"===s?i=z(l):"m"===s?i=R(l):(a!==t._tmin||r||(u="<br>"+z(l)),"d"===s?i=O(l):"H"===s?i=I(l):(a!==t._tmin||r||(u="<br>"+O(l)+", "+z(l)),i=j(l),"M"!==s&&(i+=N(l),"S"!==s&&(i+=f(y(a/1e3,1),t,"none",r).substr(1)))))),e.text=i+u}function u(t,e,r,n,i){var a=t.dtick,o=e.x;if(!n||"string"==typeof a&&"L"===a.charAt(0)||(a="L3"),t.tickformat||"string"==typeof a&&"L"===a.charAt(0))e.text=f(Math.pow(10,o),t,i,n);else if(x(a)||"D"===a.charAt(0)&&y(o+.01,1)<.1)if(-1!==["e","E","power"].indexOf(t.exponentformat)){var s=Math.round(o);0===s?e.text=1:1===s?e.text="10":s>1?e.text="10<sup>"+s+"</sup>":e.text="10<sup>\u2212"+-s+"</sup>",e.fontSize*=1.25}else e.text=f(Math.pow(10,o),t,"","fakehover"),"D1"===a&&"y"===t._id.charAt(0)&&(e.dy-=e.fontSize/6);else{if("D"!==a.charAt(0))throw"unrecognized dtick "+String(a);e.text=String(Math.round(Math.pow(10,y(o,1)))),e.fontSize*=.75}if("D1"===t.dtick){var l=String(e.text).charAt(0);("0"===l||"1"===l)&&("y"===t._id.charAt(0)?e.dx-=e.fontSize/4:(e.dy+=e.fontSize/2,e.dx+=(t.range[1]>t.range[0]?1:-1)*e.fontSize*(0>o?.5:.25)))}}function c(t,e){var r=t._categories[Math.round(e.x)];void 0===r&&(r=""),e.text=String(r)}function h(t,e,r,n,i){"all"===t.showexponent&&Math.abs(e.x/t.dtick)<1e-6&&(i="hide"),e.text=f(e.x,t,i,n)}function f(t,e,r,n){var i=0>t,o=e._tickround,s=r||e.exponentformat||"B",l=e._tickexponent,u=e.tickformat;if(n){var c={exponentformat:e.exponentformat,dtick:"none"===e.showexponent?e.dtick:x(t)?Math.abs(t)||1:1,range:"none"===e.showexponent?e.range:[0,t||1]};a(c),o=(Number(c._tickround)||0)+4,l=c._tickexponent,e.hoverformat&&(u=e.hoverformat)}if(u)return b.format(u)(t).replace(/-/g,"\u2212");var h=Math.pow(10,-o)/2;if("none"===s&&(l=0),t=Math.abs(t),h>t)t="0",i=!1;else{if(t+=h,l&&(t*=Math.pow(10,-l),o+=l),0===o)t=String(Math.floor(t));else if(0>o){t=String(Math.round(t)),t=t.substr(0,t.length+o);for(var f=o;0>f;f++)t+="0"}else{t=String(t);var p=t.indexOf(".")+1;p&&(t=t.substr(0,p+o).replace(/\.?0+$/,""))}t=d(t,e._td._fullLayout.separators)}if(l&&"hide"!==s){var g;g=0>l?"\u2212"+-l:"power"!==s?"+"+l:String(l),"e"===s||("SI"===s||"B"===s)&&(l>12||-15>l)?t+="e"+g:"E"===s?t+="E"+g:"power"===s?t+="&times;10<sup>"+g+"</sup>":"B"===s&&9===l?t+="B":("SI"===s||"B"===s)&&(t+=B[l/3+5])}return i?"\u2212"+t:t}function d(t,e){var r=e.charAt(0),n=e.charAt(1),i=t.split("."),a=i[0],o=i.length>1?r+i[1]:"";if(n&&(i.length>1||a.length>4))for(;D.test(a);)a=a.replace(D,"$1"+n+"$2");return a+o}function p(t,e){var r,n,i=[];for(r=0;r<e.length;r++){var a=[],o=t._fullData[e[r]].xaxis,s=t._fullData[e[r]].yaxis;if(o&&s){for(n=0;n<i.length;n++)(-1!==i[n].x.indexOf(o)||-1!==i[n].y.indexOf(s))&&a.push(n);if(a.length){var l,u=i[a[0]];if(a.length>1)for(n=1;n<a.length;n++)l=i[a[n]],g(u.x,l.x),g(u.y,l.y);g(u.x,[o]),g(u.y,[s])}else i.push({x:[o],y:[s]})}}return i}function g(t,e){for(var r=0;r<e.length;r++)-1===t.indexOf(e[r])&&t.push(e[r])}function v(t,e,r){var n,i,a=[],o=[],s=t.layout;for(n=0;n<e.length;n++)a.push(A.getFromId(t,e[n]));for(n=0;n<r.length;n++)o.push(A.getFromId(t,r[n]));var l=Object.keys(a[0]),u=["anchor","domain","overlaying","position","side","tickangle"],c=["linear","log"];for(n=0;n<l.length;n++){var h=l[n],f=a[0][h],d=o[0][h],p=!0,g=!1,v=!1;if("_"!==h.charAt(0)&&"function"!=typeof f&&-1===u.indexOf(h)){for(i=1;i<a.length&&p;i++){var y=a[i][h];"type"===h&&-1!==c.indexOf(f)&&-1!==c.indexOf(y)&&f!==y?g=!0:y!==f&&(p=!1)}for(i=1;i<o.length&&p;i++){var b=o[i][h];"type"===h&&-1!==c.indexOf(d)&&-1!==c.indexOf(b)&&d!==b?v=!0:o[i][h]!==d&&(p=!1)}p&&(g&&(s[a[0]._name].type="linear"),v&&(s[o[0]._name].type="linear"),m(s,h,a,o))}}for(n=0;n<t._fullLayout.annotations.length;n++){var x=t._fullLayout.annotations[n];-1!==e.indexOf(x.xref)&&-1!==r.indexOf(x.yref)&&_.Lib.swapAttrs(s.annotations[n],["?"])}}function m(t,e,r,n){var i,a=_.Lib.nestedProperty,o=a(t[r[0]._name],e).get(),s=a(t[n[0]._name],e).get();for("title"===e&&("Click to enter X axis title"===o&&(o="Click to enter Y axis title"),"Click to enter Y axis title"===s&&(s="Click to enter X axis title")),i=0;i<r.length;i++)a(t,r[i]._name+"."+e).set(s);for(i=0;i<n.length;i++)a(t,n[i]._name+"."+e).set(o)}function y(t,e){return(t%e+e)%e}var b=t("d3"),x=t("fast-isnumeric"),_=t("../../plotly"),w=t("../../components/titles"),A=e.exports={};A.layoutAttributes=t("./layout_attributes"),A.supplyLayoutDefaults=t("./layout_defaults"),A.setConvert=t("./set_convert");var k=t("./axis_ids");A.id2name=k.id2name,A.cleanId=k.cleanId,A.list=k.list,A.listIds=k.listIds,A.getFromId=k.getFromId,A.getFromTrace=k.getFromTrace,A.coerceRef=function(t,e,r,n){var i=r._fullLayout._hasGL2D?[]:A.listIds(r,n),a=n+"ref",o={};return o[a]={valType:"enumerated",values:i.concat(["paper"]),dflt:i[0]||"paper"},_.Lib.coerce(t,e,o,a)},A.clearTypes=function(t,e){Array.isArray(e)&&e.length||(e=t._fullData.map(function(t,e){return e})),e.forEach(function(e){var r=t.data[e];delete(A.getFromId(t,r.xaxis)||{}).type,delete(A.getFromId(t,r.yaxis)||{}).type})},A.counterLetter=function(t){var e=t.charAt(0);return"x"===e?"y":"y"===e?"x":void 0},A.minDtick=function(t,e,r,n){-1===["log","category"].indexOf(t.type)&&n?null===t._minDtick?(t._minDtick=e,t._forceTick0=r):t._minDtick&&((t._minDtick/e+1e-6)%1<2e-6&&((r-t._forceTick0)/e%1+1.000001)%1<2e-6?(t._minDtick=e,t._forceTick0=r):((e/t._minDtick+1e-6)%1>2e-6||((r-t._forceTick0)/t._minDtick%1+1.000001)%1>2e-6)&&(t._minDtick=0)):t._minDtick=0},A.doAutoRange=function(t){if(t._length||t.setScale(),t.autorange&&t._min&&t._max&&t._min.length&&t._max.length){var e,r=t._min[0].val,n=t._max[0].val;for(e=1;e<t._min.length&&r===n;e++)r=Math.min(r,t._min[e].val);for(e=1;e<t._max.length&&r===n;e++)n=Math.max(n,t._max[e].val);var i,a,o,s,l,u,c,h=0,f=t.range&&t.range[1]<t.range[0];for("reversed"===t.autorange&&(f=!0,t.autorange=!0),e=0;e<t._min.length;e++)for(a=t._min[e],i=0;i<t._max.length;i++)o=t._max[i],c=o.val-a.val,u=t._length-a.pad-o.pad,c>0&&u>0&&c/u>h&&(s=a,l=o,h=c/u);r===n?t.range=f?[r+1,"normal"!==t.rangemode?0:r-1]:["normal"!==t.rangemode?0:r-1,r+1]:h&&(("linear"===t.type||"-"===t.type)&&("tozero"===t.rangemode&&s.val>=0?s={val:0,pad:0}:"nonnegative"===t.rangemode&&(s.val-h*s.pad<0&&(s={val:0,pad:0}),l.val<0&&(l={val:1,pad:0})),h=(l.val-s.val)/(t._length-s.pad-l.pad)),t.range=[s.val-h*s.pad,l.val+h*l.pad],t.range[0]===t.range[1]&&(t.range=[t.range[0]-1,t.range[0]+1]),f&&t.range.reverse());var d=t._td.layout[t._name];d||(t._td.layout[t._name]=d={}),d!==t&&(d.range=t.range.slice(),d.autorange=t.autorange)}},A.saveRangeInitial=function(t,e){for(var r=A.list(t,"",!0),n=!1,i=0;i<r.length;i++){var a=r[i],o=void 0===a._rangeInitial,s=o||!(a.range[0]===a._rangeInitial[0]&&a.range[1]===a._rangeInitial[1]);(o&&a.autorange===!1||e&&s)&&(a._rangeInitial=a.range.slice(),n=!0)}return n};var M=Number.MAX_VALUE/2;A.expand=function(t,e,r){function n(t){if(Array.isArray(t))return function(e){return Math.max(Number(t[e]||0),0)};var e=Math.max(Number(t||0),0);return function(){return e}}function i(r){function n(t){return x(t)&&Math.abs(t)<M}if(l=e[r],x(l)){if(h=b(r)+m,f=_(r)+m,p=l-A(r),g=l+w(r),"log"===t.type&&g/10>p&&(p=g/10),u=t.c2l(p),c=t.c2l(g),y&&(u=Math.min(0,u),c=Math.max(0,c)),n(u)){for(d=!0,o=0;o<t._min.length&&d;o++)s=t._min[o],s.val<=u&&s.pad>=f?d=!1:s.val>=u&&s.pad<=f&&(t._min.splice(o,1),o--);d&&t._min.push({val:u,pad:y&&0===u?0:f})}if(n(c)){for(d=!0,o=0;o<t._max.length&&d;o++)s=t._max[o],s.val>=c&&s.pad>=h?d=!1:s.val<=c&&s.pad<=h&&(t._max.splice(o,1),o--);d&&t._max.push({val:c,pad:y&&0===c?0:h})}}}if(t.autorange&&e){t._min||(t._min=[]),t._max||(t._max=[]),r||(r={}),t._m||t.setScale();var a,o,s,l,u,c,h,f,d,p,g,v=e.length,m=r.padded?.05*t._length:0,y=r.tozero&&("linear"===t.type||"-"===t.type),b=n((t._m>0?r.ppadplus:r.ppadminus)||r.ppad||0),_=n((t._m>0?r.ppadminus:r.ppadplus)||r.ppad||0),w=n(r.vpadplus||r.vpad),A=n(r.vpadminus||r.vpad);for(a=0;6>a;a++)i(a);for(a=v-1;a>5;a--)i(a)}},A.autoBin=function(t,e,r,n){function i(t){return(1+100*(t-d)/h.dtick)%100<2}var a=_.Lib.aggNums(Math.min,null,t),o=_.Lib.aggNums(Math.max,null,t);if("category"===e.type)return{start:a-.5,end:o+.5,size:1};var s;if(r)s=(o-a)/r;else{var l=_.Lib.distinctVals(t),u=Math.pow(10,Math.floor(Math.log(l.minDiff)/Math.LN10)),c=u*_.Lib.roundUp(l.minDiff/u,[.9,1.9,4.9,9.9],!0);s=Math.max(c,2*_.Lib.stdev(t)/Math.pow(t.length,n?.25:.4))}var h={type:"log"===e.type?"linear":e.type,range:[a,o]};A.autoTicks(h,s);var f,d=A.tickIncrement(A.tickFirst(h),h.dtick,"reverse");if("number"==typeof h.dtick){for(var p=0,g=0,v=0,m=0,y=0;y<t.length;y++)t[y]%1===0?v++:x(t[y])||m++,i(t[y])&&p++,i(t[y]+h.dtick/2)&&g++;var b=t.length-m;if(v===b&&"date"!==e.type)h.dtick<1?d=a-.5*h.dtick:d-=.5;else if(.1*b>g&&(p>.3*b||i(a)||i(o))){var w=h.dtick/2;d+=a>d+w?w:-w}var k=1+Math.floor((o-d)/h.dtick);f=d+k*h.dtick}else for(f=d;o>=f;)f=A.tickIncrement(f,h.dtick);return{start:d,end:f,size:h.dtick}},A.calcTicks=function(t){if("array"===t.tickmode)return n(t);if("auto"===t.tickmode||!t.dtick){var e,r=t.nticks;r||("category"===t.type?(e=t.tickfont?1.2*(t.tickfont.size||12):15,r=t._length/e):(e="y"===t._id.charAt(0)?40:80,r=_.Lib.constrain(t._length/e,4,9)+1)),A.autoTicks(t,Math.abs(t.range[1]-t.range[0])/r),t._minDtick>0&&t.dtick<2*t._minDtick&&(t.dtick=t._minDtick,t.tick0=t._forceTick0)}t.tick0||(t.tick0="date"===t.type?new Date(2e3,0,1).getTime():0),a(t),t._tmin=A.tickFirst(t);var i=t.range[1]<t.range[0],o=[],s=1.0001*t.range[1]-1e-4*t.range[0];"category"===t.type&&(s=i?Math.max(-.5,s):Math.min(t._categories.length-.5,s));for(var l=t._tmin;(i?l>=s:s>=l)&&(o.push(l),!(o.length>1e3));l=A.tickIncrement(l,t.dtick,i));t._tmax=o[o.length-1];for(var u=new Array(o.length),c=0;c<o.length;c++)u[c]=A.tickText(t,o[c]);return u};var T=[2,5,10],E=[1,2,3,6,12],L=[1,2,5,10,15,30],S=[1,2,3,7,14],C=[-.046,0,.301,.477,.602,.699,.778,.845,.903,.954,1],P=[-.301,0,.301,.699,1];A.autoTicks=function(t,e){var r;if("date"===t.type)t.tick0=new Date(2e3,0,1).getTime(),e>157788e5?(e/=315576e5,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick="M"+12*i(e,r,T)):e>12096e5?(e/=26298e5,t.dtick="M"+i(e,1,E)):e>432e5?(t.dtick=i(e,864e5,S),t.tick0=new Date(2e3,0,2).getTime()):e>18e5?t.dtick=i(e,36e5,E):e>3e4?t.dtick=i(e,6e4,L):e>500?t.dtick=i(e,1e3,L):(r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick=i(e,r,T));else if("log"===t.type)if(t.tick0=0,e>.7)t.dtick=Math.ceil(e);else if(Math.abs(t.range[1]-t.range[0])<1){var n=1.5*Math.abs((t.range[1]-t.range[0])/e);e=Math.abs(Math.pow(10,t.range[1])-Math.pow(10,t.range[0]))/n,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick="L"+i(e,r,T)}else t.dtick=e>.3?"D2":"D1";else"category"===t.type?(t.tick0=0,t.dtick=Math.ceil(Math.max(e,1))):(t.tick0=0,r=Math.pow(10,Math.floor(Math.log(e)/Math.LN10)),t.dtick=i(e,r,T));if(0===t.dtick&&(t.dtick=1),!x(t.dtick)&&"string"!=typeof t.dtick){var a=t.dtick;throw t.dtick=1,"ax.dtick error: "+String(a)}},A.tickIncrement=function(t,e,r){var n=r?-1:1;if(x(e))return t+n*e;var i=e.charAt(0),a=n*Number(e.substr(1));if("M"===i){var o=new Date(t);return o.setMonth(o.getMonth()+a)}if("L"===i)return Math.log(Math.pow(10,t)+a)/Math.LN10;if("D"===i){var s="D2"===e?P:C,l=t+.01*n,u=_.Lib.roundUp(y(l,1),s,r);return Math.floor(l)+Math.log(b.round(Math.pow(10,u),1))/Math.LN10}throw"unrecognized dtick "+String(e)},A.tickFirst=function(t){var e=t.range[1]<t.range[0],r=e?Math.floor:Math.ceil,n=1.0001*t.range[0]-1e-4*t.range[1],i=t.dtick,a=t.tick0;if(x(i)){var o=r((n-a)/i)*i+a;return"category"===t.type&&(o=_.Lib.constrain(o,0,t._categories.length-1)),o}var s,l,u,c=i.charAt(0),h=Number(i.substr(1));if("M"===c){for(s=new Date(a),n=new Date(n),l=12*(n.getFullYear()-s.getFullYear())+n.getMonth()-s.getMonth(),u=s.setMonth(s.getMonth()+(Math.round(l/h)+(e?1:-1))*h);e?u>n:n>u;)u=A.tickIncrement(u,i,e);return u}if("L"===c)return Math.log(r((Math.pow(10,n)-a)/h)*h+a)/Math.LN10;if("D"===c){var f="D2"===i?P:C,d=_.Lib.roundUp(y(n,1),f,e);return Math.floor(n)+Math.log(b.round(Math.pow(10,d),1))/Math.LN10}throw"unrecognized dtick "+String(i)};var z=b.time.format("%Y"),R=b.time.format("%b %Y"),O=b.time.format("%b %-d"),I=b.time.format("%b %-d %Hh"),j=b.time.format("%H:%M"),N=b.time.format(":%S"),F=/%(\d?)f/g;A.tickText=function(t,e,r){function n(n){var i;return void 0===n?!0:r?"none"===n:(i={first:t._tmin,last:t._tmax}[n],"all"!==n&&e!==i)}var i,a,o=s(t,e),f="array"===t.tickmode,d=r||f;if(f&&Array.isArray(t.ticktext)){var p=Math.abs(t.range[1]-t.range[0])/1e4;for(a=0;a<t.ticktext.length&&!(Math.abs(e-t.d2l(t.tickvals[a]))<p);a++);if(a<t.ticktext.length)return o.text=String(t.ticktext[a]),o}return i="none"!==t.exponentformat&&n(t.showexponent)?"hide":"","date"===t.type?l(t,o,r,d):"log"===t.type?u(t,o,r,d,i):"category"===t.type?c(t,o):h(t,o,r,d,i),t.tickprefix&&!n(t.showtickprefix)&&(o.text=t.tickprefix+o.text),t.ticksuffix&&!n(t.showticksuffix)&&(o.text+=t.ticksuffix),o};var B=["f","p","n","&mu;","m","","k","M","G","T"],D=/(\d+)(\d{3})/;A.subplotMatch=/^x([0-9]*)y([0-9]*)$/,A.getSubplots=function(t,e){function r(t,e){return-1!==t.indexOf(e._id)}var n,i,a,o=[],s=t.data||[];for(n=0;n<s.length;n++){var l=s[n];if(l.visible!==!1&&"legendonly"!==l.visible&&(_.Plots.traceIs(l,"cartesian")||_.Plots.traceIs(l,"gl2d"))){var u=l.xaxis||"x",c=l.yaxis||"y";a=u+c,-1===o.indexOf(a)&&o.push(a)}}var h=A.list(t,"",!0);for(n=0;n<h.length;n++){var f=h[n],d=f._id.charAt(0),p="free"===f.anchor?"x"===d?"y":"x":f.anchor,g=A.getFromId(t,p),v=!1;for(i=0;i<o.length;i++)if(r(o[i],f)){v=!0;break}"free"===f.anchor&&v||g&&(a="x"===d?f._id+g._id:g._id+f._id,-1===o.indexOf(a)&&o.push(a))}var m=A.subplotMatch,y=[];for(n=0;n<o.length;n++)a=o[n],m.test(a)&&y.push(a);return y.sort(function(t,e){var r=t.match(m),n=e.match(m);return r[1]===n[1]?+(r[2]||1)-(n[2]||1):+(r[1]||0)-(n[1]||0)}),e?A.findSubplotsWithAxis(y,e):y},A.findSubplotsWithAxis=function(t,e){for(var r=new RegExp("x"===e._id.charAt(0)?"^"+e._id+"y":e._id+"$"),n=[],i=0;i<t.length;i++){var a=t[i];r.test(a)&&n.push(a)}return n},A.makeClipPaths=function(t){var e,r,n=t._fullLayout,i=n._defs,a={_offset:0,_length:n.width,_id:""},o={_offset:0,_length:n.height,_id:""},s=A.list(t,"x",!0),l=A.list(t,"y",!0),u=[];for(e=0;e<s.length;e++)for(u.push({x:s[e],y:o}),r=0;r<l.length;r++)0===e&&u.push({x:a,y:l[r]}),u.push({x:s[e],y:l[r]});var c=i.selectAll("g.clips").data([0]);c.enter().append("g").classed("clips",!0);var h=c.selectAll(".axesclip").data(u,function(t){return t.x._id+t.y._id});h.enter().append("clipPath").classed("axesclip",!0).attr("id",function(t){return"clip"+n._uid+t.x._id+t.y._id}).append("rect"),h.exit().remove(),h.each(function(t){b.select(this).select("rect").attr({x:t.x._offset||0,y:t.y._offset||0,width:t.x._length||1,height:t.y._length||1})})},A.doTicks=function(t,e,r){function n(t){var e=l.l2p(t.x);return e>1&&e<l._length-1}function i(t,e){var r=t.selectAll("path."+M).data("inside"===l.ticks?I:y,k);e&&l.ticks?(r.enter().append("path").classed(M,1).classed("ticks",1).classed("crisp",1).call(_.Color.stroke,l.tickcolor).style("stroke-width",z+"px").attr("d",e),r.attr("transform",f),r.exit().remove()):r.remove()}function a(n,i){function a(t,e){t.each(function(t){var r=d(e),n=b.select(this),i=n.select(".text-math-group"),a=f(t)+(x(e)&&0!==+e?" rotate("+e+","+c(t)+","+(h(t)-t.fontSize/2)+")":"");if(i.empty()){var o=n.select("text").attr({transform:a,"text-anchor":r});o.empty()||o.selectAll("tspan.line").attr({x:o.attr("x"),y:o.attr("y")})}else{var s=_.Drawing.bBox(i.node()).width*{end:-.5,start:.5}[r];i.attr("transform",a+(s?"translate("+s+",0)":""))}})}function o(){return E.length&&Promise.all(E)}function s(){if(a(u,l.tickangle),"x"===v&&!x(l.tickangle)&&("log"!==l.type||"D"!==String(l.dtick).charAt(0))){var n=[];for(u.each(function(t){var e=b.select(this),r=e.select(".text-math-group"),i=l.l2p(t.x);r.empty()&&(r=e.select("text"));var a=_.Drawing.bBox(r.node());n.push({top:0,bottom:10,height:10,left:i-a.width/2,right:i+a.width/2+2,width:a.width+2})}),g=0;g<n.length-1;g++)if(_.Lib.bBoxIntersect(n[g],n[g+1])){T=30;break}if(T){var i=Math.abs((y[y.length-1].x-y[0].x)*l._m)/(y.length-1);2.5*A>i&&(T=90),a(u,T)}l._lastangle=T}return r||w.draw(t,e+"title"),e+" done"}var u=n.selectAll("g."+M).data(y,k);if(!l.showticklabels||!x(i))return u.remove(),void w.draw(t,e+"title");var c,h,d,p;if("x"===v){var m="bottom"===R?1:-1;c=function(t){return t.dx},p=i+(S+L)*m,h=function(t){return t.dy+p+t.fontSize*("bottom"===R?1:-.5)},d=function(t){return x(t)&&0!==t&&180!==t?0>t*m?"end":"start":"middle"}}else h=function(t){return t.dy+t.fontSize/2},c=function(t){return t.dx+i+(S+L+(90===Math.abs(l.tickangle)?t.fontSize/2:0))*("right"===R?1:-1)},d=function(t){return x(t)&&90===Math.abs(t)?"middle":"right"===R?"start":"end"};var A=0,T=0,E=[];u.enter().append("g").classed(M,1).append("text").attr("text-anchor","middle").each(function(e){var r=b.select(this),n=t._promises.length;r.call(_.Drawing.setPosition,c(e),h(e)).call(_.Drawing.font,e.font,e.fontSize,e.fontColor).text(e.text).call(_.util.convertToTspans),n=t._promises[n],n?E.push(t._promises.pop().then(function(){a(r,l.tickangle)})):a(r,l.tickangle)}),u.exit().remove(),u.each(function(t){A=Math.max(A,t.fontSize)}),a(u,l._lastangle||l.tickangle);var C=_.Lib.syncOrAsync([o,s]);return C&&C.then&&t._promises.push(C),C}function o(t,e){return t.visible!==!0||t.xaxis+t.yaxis!==e?!1:_.Plots.traceIs(t,"bar")&&t.orientation==={x:"h",y:"v"}[v]?!0:t.fill&&t.fill.charAt(t.fill.length-1)===v}function s(e,r,i){var a=e.gridlayer,s=e.zerolinelayer,u=e["hidegrid"+v]?[]:I,c="M0,0"+("x"===v?"v":"h")+r._length,h=a.selectAll("path."+T).data(l.showgrid===!1?[]:u,k);h.enter().append("path").classed(T,1).classed("crisp",1).attr("d",c).each(function(t){l.zeroline&&("linear"===l.type||"-"===l.type)&&Math.abs(t.x)<l.dtick/100&&b.select(this).remove()}),h.attr("transform",f).call(_.Color.stroke,l.gridcolor||"#ddd").style("stroke-width",C+"px"),h.exit().remove();for(var d=!1,p=0;p<t._fullData.length;p++)if(o(t._fullData[p],i)){d=!0;break}var g=l.range[0]*l.range[1]<=0&&l.zeroline&&("linear"===l.type||"-"===l.type)&&u.length&&(d||n({x:0})||!l.showline),m=s.selectAll("path."+E).data(g?[{x:0}]:[]);m.enter().append("path").classed(E,1).classed("zl",1).classed("crisp",1).attr("d",c),m.attr("transform",f).call(_.Color.stroke,l.zerolinecolor||_.Color.defaultLine).style("stroke-width",P+"px"),m.exit().remove()}var l,u=t._fullLayout,c=!1;if("object"==typeof e)l=e,e=l._id,c=!0;else if(l=A.getFromId(t,e),"redraw"===e&&u._paper.selectAll("g.subplot").each(function(t){var e=u._plots[t],r=e.x(),n=e.y();e.plot.attr("viewBox","0 0 "+r._length+" "+n._length),e.xaxislayer.selectAll("."+r._id+"tick").remove(),e.yaxislayer.selectAll("."+n._id+"tick").remove(),e.gridlayer.selectAll("path").remove(),e.zerolinelayer.selectAll("path").remove()}),!e||"redraw"===e)return _.Lib.syncOrAsync(A.list(t,"",!0).map(function(r){return function(){if(r._id){var n=A.doTicks(t,r._id);return"redraw"===e&&(r._r=r.range.slice()),n}}}));l.tickformat||(-1===["none","e","E","power","SI","B"].indexOf(l.exponentformat)&&(l.exponentformat="e"),-1===["all","first","last","none"].indexOf(l.showexponent)&&(l.showexponent="all")),l.range=[+l.range[0],+l.range[1]],l.setScale();var h,f,d,p,g,v=e.charAt(0),m=A.counterLetter(e),y=A.calcTicks(l),k=function(t){return t.text+t.x+l.mirror},M=e+"tick",T=e+"grid",E=e+"zl",L=(l.linewidth||1)/2,S=("outside"===l.ticks?l.ticklen:1)+(l.linewidth||0),C=_.Drawing.crispRound(t,l.gridwidth,1),P=_.Drawing.crispRound(t,l.zerolinewidth,C),z=_.Drawing.crispRound(t,l.tickwidth,1);if("x"===v)h=["bottom","top"],f=function(t){return"translate("+l.l2p(t.x)+",0)"},d="M0,",p="v";else{if("y"!==v)return void console.log("unrecognized doTicks axis",e);h=["left","right"],f=function(t){return"translate(0,"+l.l2p(t.x)+")"},d="M",p=",0h"}var R=l.side||h[0],O=[-1,1,R===h[1]?1:-1];"inside"!==l.ticks==("x"===v)&&(O=O.map(function(t){return-t}));var I=y.filter(n);if(c)return i(l._axislayer,d+(l._pos+L*O[2])+p+O[2]*l.ticklen),a(l._axislayer,l._pos);var j=A.getSubplots(t,l).map(function(t){var e=u._plots[t];if(u._hasCartesian){var r=e[v+"axislayer"],n=l._linepositions[t]||[],o=e[m](),c=o._id===l.anchor,f=[!1,!1,!1],y="";if("allticks"===l.mirror?f=[!0,!0,!1]:c&&("ticks"===l.mirror?f=[!0,!0,!1]:f[h.indexOf(R)]=!0),l.mirrors)for(g=0;2>g;g++){var b=l.mirrors[o._id+h[g]];("ticks"===b||"labels"===b)&&(f[g]=!0)}return void 0!==n[2]&&(f[2]=!0),f.forEach(function(t,e){var r=n[e],i=O[e];t&&x(r)&&(y+=d+(r+L*i)+p+i*l.ticklen)}),i(r,y),s(e,o,t),a(r,n[3])}}).filter(function(t){return t&&t.then});return j.length?Promise.all(j):0},A.swap=function(t,e){for(var r=p(t,e),n=0;n<r.length;n++)v(t,r[n].x,r[n].y)}},{"../../components/titles":332,"../../plotly":366,"./axis_ids":371,"./layout_attributes":376,"./layout_defaults":377,"./set_convert":380,d3:70,"fast-isnumeric":74}],370:[function(t,e,r){"use strict";function n(t,e){if("-"===t.type){var r=t._id,n=r.charAt(0);-1!==r.indexOf("scene")&&(r=n);var l=s(e,r,n);if(l){if("histogram"===l.type&&n==={v:"y",h:"x"}[l.orientation||"v"])return void(t.type="linear");if(a(l,n)){for(var u,c=i(l),h=[],f=0;f<e.length;f++)u=e[f],d.traceIs(u,"box")&&(u[n+"axis"]||n)===r&&(void 0!==u[c]?h.push(u[c][0]):void 0!==u.name?h.push(u.name):h.push("text"));t.type=o(h)}else t.type=o(l[n]||[l[n+"0"]])}}}function i(t){return{v:"x",h:"y"}[t.orientation||"v"]}function a(t,e){var r=i(t);return d.traceIs(t,"box")&&e===r&&void 0===t[r]&&void 0===t[r+"0"]}function o(t){return u(t)?"date":c(t)?"category":l(t)?"linear":"-"}function s(t,e,r){for(var n=0;n<t.length;n++){var i=t[n];if((i[r+"axis"]||r)===e){if(a(i,r))return i;if((i[r]||[]).length||i[r+"0"])return i}}}function l(t){if(!t)return!1;for(var e=0;e<t.length;e++)if(h(t[e]))return!0;return!1}function u(t){for(var e,r=0,n=0,i=Math.max(1,(t.length-1)/1e3),a=0;a<t.length;a+=i)e=t[Math.round(a)],f.isDateTime(e)&&(r+=1),h(e)&&(n+=1);return r>2*n}function c(t){for(var e,r=Math.max(1,(t.length-1)/1e3),n=0,i=0,a=0;a<t.length;a+=r)e=y(t[Math.round(a)]),h(e)?n++:"string"==typeof e&&""!==e&&"None"!==e&&i++;return i>2*n}var h=t("fast-isnumeric"),f=t("../../lib"),d=t("../plots"),p=t("./layout_attributes"),g=t("./tick_value_defaults"),v=t("./tick_defaults"),m=t("./set_convert"),y=t("./clean_datum"),b=t("./axis_ids");e.exports=function(t,e,r,i){var a=i.letter,o=i.font||{},s="Click to enter "+(i.title||a.toUpperCase()+" axis")+" title";i.name&&(e._name=i.name,e._id=b.name2id(i.name));var l=r("type");"-"===l&&(n(e,i.data),"-"===e.type?e.type="linear":l=t.type=e.type),m(e),r("title",s),f.coerceFont(r,"titlefont",{family:o.family,size:Math.round(1.2*o.size),color:o.color});var u=2===(t.range||[]).length&&h(t.range[0])&&h(t.range[1]),c=r("autorange",!u);c&&r("rangemode");var d=r("range",[-1,"x"===a?6:4]);d[0]===d[1]&&(e.range=[d[0]-1,d[0]+1]),f.noneOrAll(t.range,e.range,[0,1]),r("fixedrange"),g(t,e,r,l),v(t,e,r,l,i);var y=f.coerce2(t,e,p,"linecolor"),x=f.coerce2(t,e,p,"linewidth"),_=r("showline",!!y||!!x);_||(delete e.linecolor,delete e.linewidth),(_||e.ticks)&&r("mirror");var w=f.coerce2(t,e,p,"gridcolor"),A=f.coerce2(t,e,p,"gridwidth"),k=r("showgrid",i.showGrid||!!w||!!A);k||(delete e.gridcolor,delete e.gridwidth);var M=f.coerce2(t,e,p,"zerolinecolor"),T=f.coerce2(t,e,p,"zerolinewidth"),E=r("zeroline",i.showGrid||!!M||!!T);return E||(delete e.zerolinecolor,delete e.zerolinewidth),e}},{"../../lib":349,"../plots":413,"./axis_ids":371,"./clean_datum":372,"./layout_attributes":376,"./set_convert":380,"./tick_defaults":381,"./tick_value_defaults":382,"fast-isnumeric":74}],371:[function(t,e,r){"use strict";function n(t,e,r){function n(t,r){for(var n=Object.keys(t),i=/^[xyz]axis[0-9]*/,a=[],o=0;o<n.length;o++){var s=n[o];e&&s.charAt(0)!==e||i.test(s)&&a.push(r+s)}return a.sort()}var a=t._fullLayout;if(!a)return[];var o=n(a,"");if(r)return o;for(var s=i.getSubplotIds(a,"gl3d")||[],l=0;l<s.length;l++){var u=s[l];o=o.concat(n(a[u],u+"."))}return o}var i=t("../plots"),a=t("../../lib"),o=t("./constants");r.id2name=function(t){if("string"==typeof t&&t.match(o.AX_ID_PATTERN)){var e=t.substr(1);
+return"1"===e&&(e=""),t.charAt(0)+"axis"+e}},r.name2id=function(t){if(t.match(o.AX_NAME_PATTERN)){var e=t.substr(5);return"1"===e&&(e=""),t.charAt(0)+e}},r.cleanId=function(t,e){if(t.match(o.AX_ID_PATTERN)&&(!e||t.charAt(0)===e)){var r=t.substr(1).replace(/^0+/,"");return"1"===r&&(r=""),t.charAt(0)+r}},r.list=function(t,e,r){return n(t,e,r).map(function(e){return a.nestedProperty(t._fullLayout,e).get()})},r.listIds=function(t,e){return n(t,e,!0).map(r.name2id)},r.getFromId=function(t,e,n){var i=t._fullLayout;return"x"===n?e=e.replace(/y[0-9]*/,""):"y"===n&&(e=e.replace(/x[0-9]*/,"")),i[r.id2name(e)]},r.getFromTrace=function(t,e,n){var a=t._fullLayout,o=null;if(i.traceIs(e,"gl3d")){var s=e.scene;"scene"===s.substr(0,5)&&(o=a[s][n+"axis"])}else o=r.getFromId(t,e[n+"axis"]||n);return o}},{"../../lib":349,"../plots":413,"./constants":373}],372:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib");e.exports=function(t){try{if("object"==typeof t&&null!==t&&t.getTime)return i.ms2DateTime(t);if("string"!=typeof t&&!n(t))return"";t=t.toString().replace(/['"%,$# ]/g,"")}catch(e){console.log(e,t)}return t}},{"../../lib":349,"fast-isnumeric":74}],373:[function(t,e,r){"use strict";e.exports={BADNUM:void 0,xAxisMatch:/^xaxis[0-9]*$/,yAxisMatch:/^yaxis[0-9]*$/,AX_ID_PATTERN:/^[xyz][0-9]*$/,AX_NAME_PATTERN:/^[xyz]axis[0-9]*$/,DBLCLICKDELAY:600,MINDRAG:8,MINSELECT:12,MINZOOM:20,DRAGGERSIZE:20,MAXDIST:20,YANGLE:60,HOVERARROWSIZE:6,HOVERTEXTPAD:3,HOVERFONTSIZE:13,HOVERFONT:"Arial, sans-serif",HOVERMINTIME:100,BENDPX:1.5}},{}],374:[function(t,e,r){"use strict";function n(t,e){for(var r=[],n=t.length;n>0;n--)r.push(e);return r}function i(t,e){for(var r=[],n=0;n<t.length;n++)r.push(t[n].p2c(e));return r}function a(t,e){return function(r){var n=t(r),i=e(r);return Math.sqrt(n*n+i*i)}}function o(t,e,r){if("pie"===r)return void t.emit("plotly_hover",{points:[e]});r||(r="xy");var a=t._fullLayout,o=a._plots[r],d=[r].concat(o.overlays.map(function(t){return t.id})),p=d.map(function(e){return A.Axes.getFromId(t,e,"x")}),g=d.map(function(e){return A.Axes.getFromId(t,e,"y")}),v=e.hovermode||a.hovermode;if(-1===["x","y","closest"].indexOf(v)||!t.calcdata||t.querySelector(".zoombox")||t._dragging)return f(t,e);var m,y,b,x,_,k,T,L,S,C,P,z,R=[],O=[];if(Array.isArray(e))for(v="array",b=0;b<e.length;b++)_=t.calcdata[e[b].curveNumber||0],"none"!==_[0].trace.hoverinfo&&O.push(_);else{for(x=0;x<t.calcdata.length;x++)_=t.calcdata[x],k=_[0].trace,"none"!==k.hoverinfo&&-1!==d.indexOf(k.xaxis+k.yaxis)&&O.push(_);var I,j;if(e.target&&"clientX"in e&&"clientY"in e){if(M.triggerHandler(t,"plotly_beforehover",e)===!1)return;var N=e.target.getBoundingClientRect();if(I=e.clientX-N.left,j=e.clientY-N.top,0>I||I>N.width||0>j||j>N.height)return f(t,e)}else I="xpx"in e?e.xpx:p[0]._length/2,j="ypx"in e?e.ypx:g[0]._length/2;if(m="xval"in e?n(d,e.xval):i(p,I),y="yval"in e?n(d,e.yval):i(g,j),!w(m[0])||!w(y[0]))return console.log("Plotly.Fx.hover failed",e,t),f(t,e)}var F=1/0;for(x=0;x<O.length;x++)if(_=O[x],_&&_[0]&&_[0].trace&&_[0].trace.visible===!0){if(k=_[0].trace,T=d.indexOf(k.xaxis+k.yaxis),L=v,P={cd:_,trace:k,xa:p[T],ya:g[T],name:t.data.length>1||-1!==k.hoverinfo.indexOf("name")?k.name:void 0,index:!1,distance:Math.min(F,E.MAXDIST),color:A.Color.defaultLine,x0:void 0,x1:void 0,y0:void 0,y1:void 0,xLabelVal:void 0,yLabelVal:void 0,zLabelVal:void 0,text:void 0},z=R.length,"array"===L){var B=e[x];"pointNumber"in B?(P.index=B.pointNumber,L="closest"):(L="","xval"in B&&(S=B.xval,L="x"),"yval"in B&&(C=B.yval,L=L?"closest":"y"))}else S=m[T],C=y[T];if(k._module&&k._module.hoverPoints){var D=k._module.hoverPoints(P,S,C,L);if(D)for(var U,V=0;V<D.length;V++)U=D[V],w(U.x0)&&w(U.y0)&&R.push(s(U,v))}else console.log("unrecognized trace type in hover",k);"closest"===v&&R.length>z&&(R.splice(0,z),F=R[0].distance)}if(0===R.length)return f(t,e);var q="y"===v&&O.length>1;R.sort(function(t,e){return t.distance-e.distance});var H={hovermode:v,rotateLabels:q,bgColor:A.Color.combine(a.plot_bgcolor,a.paper_bgcolor),container:a._hoverlayer,outerContainer:a._paperdiv},G=l(R,H);u(R,q?p[0]:g[0]),c(G,q);var Y=t._hoverdata,X=[];for(b=0;b<R.length;b++){var W=R[b],Z={data:W.trace._input,fullData:W.trace,curveNumber:W.trace.index,pointNumber:W.index,x:W.xVal,y:W.yVal,xaxis:W.xa,yaxis:W.ya};void 0!==W.zLabelVal&&(Z.z=W.zLabelVal),X.push(Z)}t._hoverdata=X,h(t,e,Y)&&(Y&&t.emit("plotly_unhover",{points:Y}),t.emit("plotly_hover",{points:t._hoverdata,xaxes:p,yaxes:g,xvals:m,yvals:y}))}function s(t,e){t.posref="y"===e?(t.x0+t.x1)/2:(t.y0+t.y1)/2,t.x0=A.Lib.constrain(t.x0,0,t.xa._length),t.x1=A.Lib.constrain(t.x1,0,t.xa._length),t.y0=A.Lib.constrain(t.y0,0,t.ya._length),t.y1=A.Lib.constrain(t.y1,0,t.ya._length);var r;if(void 0!==t.xLabelVal){r="log"===t.xa.type&&t.xLabelVal<=0;var n=A.Axes.tickText(t.xa,t.xa.c2l(r?-t.xLabelVal:t.xLabelVal),"hover");r?0===t.xLabelVal?t.xLabel="0":t.xLabel="-"+n.text:t.xLabel=n.text,t.xVal=t.xa.c2d(t.xLabelVal)}if(void 0!==t.yLabelVal){r="log"===t.ya.type&&t.yLabelVal<=0;var i=A.Axes.tickText(t.ya,t.ya.c2l(r?-t.yLabelVal:t.yLabelVal),"hover");r?0===t.yLabelVal?t.yLabel="0":t.yLabel="-"+i.text:t.yLabel=i.text,t.yVal=t.ya.c2d(t.yLabelVal)}if(void 0!==t.zLabelVal&&(t.zLabel=String(t.zLabelVal)),void 0!==t.xerr){var a=A.Axes.tickText(t.xa,t.xa.c2l(t.xerr),"hover").text;void 0!==t.xerrneg?t.xLabel+=" +"+a+" / -"+A.Axes.tickText(t.xa,t.xa.c2l(t.xerrneg),"hover").text:t.xLabel+=" &plusmn; "+a,"x"===e&&(t.distance+=1)}if(void 0!==t.yerr){var o=A.Axes.tickText(t.ya,t.ya.c2l(t.yerr),"hover").text;void 0!==t.yerrneg?t.yLabel+=" +"+o+" / -"+A.Axes.tickText(t.ya,t.ya.c2l(t.yerrneg),"hover").text:t.yLabel+=" &plusmn; "+o,"y"===e&&(t.distance+=1)}var s=t.trace.hoverinfo;return"all"!==s&&(s=s.split("+"),-1===s.indexOf("x")&&(t.xLabel=void 0),-1===s.indexOf("y")&&(t.yLabel=void 0),-1===s.indexOf("z")&&(t.zLabel=void 0),-1===s.indexOf("text")&&(t.text=void 0),-1===s.indexOf("name")&&(t.name=void 0)),t}function l(t,e){var r,n,i=e.hovermode,a=e.rotateLabels,o=e.bgColor,s=e.container,l=e.outerContainer,u=t[0],c=u.xa,h=u.ya,f="y"===i?"yLabel":"xLabel",d=u[f],p=(String(d)||"").split(" ")[0],g=l.node().getBoundingClientRect(),v=g.top,m=g.width,y=g.height,b=u.distance<=E.MAXDIST&&("x"===i||"y"===i);for(r=0;r<t.length;r++){n=t[r].trace.hoverinfo;var w=n.split("+");if(-1===w.indexOf("all")&&-1===w.indexOf(i)){b=!1;break}}var k=s.selectAll("g.axistext").data(b?[0]:[]);k.enter().append("g").classed("axistext",!0),k.exit().remove(),k.each(function(){var e=x.select(this),r=e.selectAll("path").data([0]),n=e.selectAll("text").data([0]);r.enter().append("path").style({fill:A.Color.defaultLine,"stroke-width":"1px",stroke:A.Color.background}),n.enter().append("text").call(A.Drawing.font,N,j,A.Color.background).attr("data-notex",1),n.text(d).call(A.util.convertToTspans).call(A.Drawing.setPosition,0,0).selectAll("tspan.line").call(A.Drawing.setPosition,0,0),e.attr("transform","");var a=n.node().getBoundingClientRect();if("x"===i){n.attr("text-anchor","middle").call(A.Drawing.setPosition,0,"top"===c.side?v-a.bottom-O-I:v-a.top+O+I).selectAll("tspan.line").attr({x:n.attr("x"),y:n.attr("y")});var o="top"===c.side?"-":"";r.attr("d","M0,0L"+O+","+o+O+"H"+(I+a.width/2)+"v"+o+(2*I+a.height)+"H-"+(I+a.width/2)+"V"+o+O+"H-"+O+"Z"),e.attr("transform","translate("+(c._offset+(u.x0+u.x1)/2)+","+(h._offset+("top"===c.side?0:h._length))+")")}else{n.attr("text-anchor","right"===h.side?"start":"end").call(A.Drawing.setPosition,("right"===h.side?1:-1)*(I+O),v-a.top-a.height/2).selectAll("tspan.line").attr({x:n.attr("x"),y:n.attr("y")});var s="right"===h.side?"":"-";r.attr("d","M0,0L"+s+O+","+O+"V"+(I+a.height/2)+"h"+s+(2*I+a.width)+"V-"+(I+a.height/2)+"H"+s+O+"V-"+O+"Z"),e.attr("transform","translate("+(c._offset+("right"===h.side?c._length:0))+","+(h._offset+(u.y0+u.y1)/2)+")")}t=t.filter(function(t){return void 0!==t.zLabelVal||(t[f]||"").split(" ")[0]===p})});var M=s.selectAll("g.hovertext").data(t,function(t){return[t.trace.index,t.index,t.x0,t.y0,t.name,t.attr||""].join(",")});return M.enter().append("g").classed("hovertext",!0).each(function(){var t=x.select(this);t.append("rect").call(A.Color.fill,A.Color.addOpacity(o,.8)),t.append("text").classed("name",!0).call(A.Drawing.font,N,j),t.append("path").style("stroke-width","1px"),t.append("text").classed("nums",!0).call(A.Drawing.font,N,j)}),M.exit().remove(),M.each(function(t){var e=x.select(this).attr("transform",""),r="",n="",s=A.Color.opacity(t.color)?t.color:A.Color.defaultLine,l=A.Color.combine(s,o),u=_(l).getBrightness()>128?"#000":A.Color.background;if(t.name&&void 0===t.zLabelVal){var f=document.createElement("p");f.innerHTML=t.name,r=f.textContent||"",r.length>15&&(r=r.substr(0,12)+"...")}void 0!==t.zLabel?(void 0!==t.xLabel&&(n+="x: "+t.xLabel+"<br>"),void 0!==t.yLabel&&(n+="y: "+t.yLabel+"<br>"),n+=(n?"z: ":"")+t.zLabel):b&&t[i+"Label"]===d?n=t[("x"===i?"y":"x")+"Label"]||"":void 0===t.xLabel?void 0!==t.yLabel&&(n=t.yLabel):n=void 0===t.yLabel?t.xLabel:"("+t.xLabel+", "+t.yLabel+")",t.text&&!Array.isArray(t.text)&&(n+=(n?"<br>":"")+t.text),""===n&&(""===r&&e.remove(),n=r);var p=e.select("text.nums").style("fill",u).call(A.Drawing.setPosition,0,0).text(n).attr("data-notex",1).call(A.util.convertToTspans);p.selectAll("tspan.line").call(A.Drawing.setPosition,0,0);var g=e.select("text.name"),w=0;r&&r!==n?(g.style("fill",l).text(r).call(A.Drawing.setPosition,0,0).attr("data-notex",1).call(A.util.convertToTspans),g.selectAll("tspan.line").call(A.Drawing.setPosition,0,0),w=g.node().getBoundingClientRect().width+2*I):(g.remove(),e.select("rect").remove()),e.select("path").style({fill:l,stroke:u});var k,M,T=p.node().getBoundingClientRect(),E=c._offset+(t.x0+t.x1)/2,L=h._offset+(t.y0+t.y1)/2,C=Math.abs(t.x1-t.x0),P=Math.abs(t.y1-t.y0),z=T.width+O+I+w;t.ty0=v-T.top,t.bx=T.width+2*I,t.by=T.height+2*I,t.anchor="start",t.txwidth=T.width,t.tx2width=w,t.offset=0,a?(t.pos=E,k=y>=L+P/2+z,M=L-P/2-z>=0,"top"!==t.idealAlign&&k||!M?k?(L+=P/2,t.anchor="start"):t.anchor="middle":(L-=P/2,t.anchor="end")):(t.pos=L,k=m>=E+C/2+z,M=E-C/2-z>=0,"left"!==t.idealAlign&&k||!M?k?(E+=C/2,t.anchor="start"):t.anchor="middle":(E-=C/2,t.anchor="end")),p.attr("text-anchor",t.anchor),w&&g.attr("text-anchor",t.anchor),e.attr("transform","translate("+E+","+L+")"+(a?"rotate("+S+")":""))}),M}function u(t,e){function r(t){var e=t[0],r=t[t.length-1];if(i=h-e.pos-e.dp+e.size,a=r.pos+r.dp+r.size-f,i>.01){for(s=t.length-1;s>=0;s--)t[s].dp+=i;n=!1}if(!(.01>a)){if(-.01>i){for(s=t.length-1;s>=0;s--)t[s].dp-=a;n=!1}if(n){var u=0;for(o=0;o<t.length;o++)l=t[o],l.pos+l.dp+l.size>f&&u++;for(o=t.length-1;o>=0&&!(0>=u);o--)l=t[o],l.pos>f-1&&(l.del=!0,u--);for(o=0;o<t.length&&!(0>=u);o++)if(l=t[o],l.pos<h+1)for(l.del=!0,u--,a=2*l.size,s=t.length-1;s>=0;s--)t[s].dp-=a;for(o=t.length-1;o>=0&&!(0>=u);o--)l=t[o],l.pos+l.dp+l.size>f&&(l.del=!0,u--)}}}for(var n,i,a,o,s,l,u,c=0,h=e._offset,f=e._offset+e._length,d=t.map(function(t,r){return[{i:r,dp:0,pos:t.pos,posref:t.posref,size:t.by*("x"===e._id.charAt(0)?P:1)/2}]}).sort(function(t,e){return t[0].posref-e[0].posref});!n&&c<=t.length;){for(c++,n=!0,o=0;o<d.length-1;){var p=d[o],g=d[o+1],v=p[p.length-1],m=g[0];if(i=v.pos+v.dp+v.size-m.pos-m.dp+m.size,i>.01){for(s=g.length-1;s>=0;s--)g[s].dp+=i;for(p.push.apply(p,g),d.splice(o+1,1),u=0,s=p.length-1;s>=0;s--)u+=p[s].dp;for(a=u/p.length,s=p.length-1;s>=0;s--)p[s].dp-=a;n=!1}else o++}d.forEach(r)}for(o=d.length-1;o>=0;o--){var y=d[o];for(s=y.length-1;s>=0;s--){var b=y[s],x=t[b.i];x.offset=b.dp,x.del=b.del}}}function c(t,e){t.each(function(t){var r=x.select(this);if(t.del)return void r.remove();var n="end"===t.anchor?-1:1,i=r.select("text.nums"),a={start:1,end:-1,middle:0}[t.anchor],o=a*(O+I),s=o+a*(t.txwidth+I),l=0,u=t.offset;"middle"===t.anchor&&(o-=t.tx2width/2,s-=t.tx2width/2),e&&(u*=-R,l=t.offset*z),r.select("path").attr("d","middle"===t.anchor?"M-"+t.bx/2+",-"+t.by/2+"h"+t.bx+"v"+t.by+"h-"+t.bx+"Z":"M0,0L"+(n*O+l)+","+(O+u)+"v"+(t.by/2-O)+"h"+n*t.bx+"v-"+t.by+"H"+(n*O+l)+"V"+(u-O)+"Z"),i.call(A.Drawing.setPosition,o+l,u+t.ty0-t.by/2+I).selectAll("tspan.line").attr({x:i.attr("x"),y:i.attr("y")}),t.tx2width&&(r.select("text.name, text.name tspan.line").call(A.Drawing.setPosition,s+a*I+l,u+t.ty0-t.by/2+I),r.select("rect").call(A.Drawing.setRect,s+(a-1)*t.tx2width/2+l,u-t.by/2-1,t.tx2width,t.by+2))})}function h(t,e,r){if(!e.target)return!1;if(!r||r.length!==t._hoverdata.length)return!0;for(var n=r.length-1;n>=0;n--){var i=r[n],a=t._hoverdata[n];if(i.curveNumber!==a.curveNumber||String(i.pointNumber)!==String(a.pointNumber))return!0}return!1}function f(t,e){var r=t._fullLayout;e||(e={}),e.target&&M.triggerHandler(t,"plotly_beforehover",e)===!1||(r._hoverlayer.selectAll("g").remove(),e.target&&t._hoverdata&&t.emit("plotly_unhover",{points:t._hoverdata}),t._hoverdata=void 0)}function d(t,e){return t?"nsew"===t?"pan"===e?"move":"crosshair":t.toLowerCase()+"-resize":"pointer"}function p(t,e,r,n,i,a,o,s){function l(t,e){for(P=0;P<t.length;P++)if(!t[P].fixedrange)return e;return""}function u(t){t[0]=Number(t[0]),t[1]=Number(t[1])}function c(r,n,i){var a=Z.getBoundingClientRect();for(K=n-a.left,Q=i-a.top,J={l:K,r:K,w:0,t:Q,b:Q,h:0},tt=t._hmpixcount?t._hmlumcount/t._hmpixcount:_(t._fullLayout.plot_bgcolor).getLuminance(),et=et="M0,0H"+B+"V"+D+"H0V0",rt=!1,nt="xy",it=e.plot.append("path").attr("class","zoombox").style({fill:tt>.2?"rgba(0,0,0,0)":"rgba(255,255,255,0)","stroke-width":0}).attr("d",et+"Z"),at=e.plot.append("path").attr("class","zoombox-corners").style({fill:A.Color.background,stroke:A.Color.defaultLine,"stroke-width":1,opacity:0}).attr("d","M0,0Z"),h(),P=0;P<q.length;P++)u(q[P].range)}function h(){e.plot.selectAll(".select-outline").remove()}function f(t,e){var r=Math.max(0,Math.min(B,t+K)),n=Math.max(0,Math.min(D,e+Q)),i=Math.abs(r-K),a=Math.abs(n-Q),o=Math.floor(Math.min(a,i,V)/2);J.l=Math.min(K,r),J.r=Math.max(K,r),J.t=Math.min(Q,n),J.b=Math.max(Q,n),!G||a<Math.min(Math.max(.6*i,U),V)?U>i?(nt="",J.r=J.l,J.t=J.b,at.attr("d","M0,0Z")):(J.t=0,J.b=D,nt="x",at.attr("d","M"+(J.l-.5)+","+(Q-V-.5)+"h-3v"+(2*V+1)+"h3ZM"+(J.r+.5)+","+(Q-V-.5)+"h3v"+(2*V+1)+"h-3Z")):!H||i<Math.min(.6*a,V)?(J.l=0,J.r=B,nt="y",at.attr("d","M"+(K-V-.5)+","+(J.t-.5)+"v-3h"+(2*V+1)+"v3ZM"+(K-V-.5)+","+(J.b+.5)+"v3h"+(2*V+1)+"v-3Z")):(nt="xy",at.attr("d","M"+(J.l-3.5)+","+(J.t-.5+o)+"h3v"+-o+"h"+o+"v-3h-"+(o+3)+"ZM"+(J.r+3.5)+","+(J.t-.5+o)+"h-3v"+-o+"h"+-o+"v-3h"+(o+3)+"ZM"+(J.r+3.5)+","+(J.b+.5-o)+"h-3v"+o+"h"+-o+"v3h"+(o+3)+"ZM"+(J.l-3.5)+","+(J.b+.5-o)+"h3v"+o+"h"+o+"v3h-"+(o+3)+"Z")),J.w=J.r-J.l,J.h=J.b-J.t,it.attr("d",et+"M"+J.l+","+J.t+"v"+J.h+"h"+J.w+"v-"+J.h+"h-"+J.w+"Z"),rt||(it.transition().style("fill",tt>.2?"rgba(0,0,0,0.4)":"rgba(255,255,255,0.3)").duration(200),at.transition().style("opacity",1).duration(200),rt=!0)}function p(t,e,r){var n,i,a;for(n=0;n<t.length;n++)i=t[n],i.fixedrange||(a=i.range,i.range=[a[0]+(a[1]-a[0])*e,a[0]+(a[1]-a[0])*r])}function m(e,r){return Math.min(J.h,J.w)<2*U?(2===r?M():v(t),y(t)):(("xy"===nt||"x"===nt)&&p(j,J.l/B,J.r/B),("xy"===nt||"y"===nt)&&p(N,(D-J.b)/D,(D-J.t)/D),y(t),S(nt),void(F&&t.data&&t._context.showTips&&(A.Lib.notifier("Double-click to<br>zoom back out","long"),F=!1)))}function b(e,r){var n=1===(o+s).length;if(e)S();else if(2!==r||n)if(1===r&&n){var i=o?N[0]:j[0],a="s"===o||"w"===s?0:1,l=i._name+".range["+a+"]",u=g(i,a),c="left",h="middle";if(i.fixedrange)return;o?(h="n"===o?"top":"bottom","right"===i.side&&(c="right")):"e"===s&&(c="right"),W.call(A.util.makeEditable,null,{immediate:!0,background:O.paper_bgcolor,text:String(u),fill:i.tickfont?i.tickfont.color:"#444",horizontalAlign:c,verticalAlign:h}).on("edit",function(e){var r="category"===i.type?i.c2l(e):i.d2l(e);void 0!==r&&A.relayout(t,l,r)})}else v(t);else M()}function x(e){function r(t,e,r){if(!t.fixedrange){u(t.range);var n=t.range,i=n[0]+(n[1]-n[0])*e;t.range=[i+(n[0]-i)*r,i+(n[1]-i)*r]}}if(t._context.scrollZoom||O._enablescrollzoom){var n=t.querySelector(".plotly");if(!(n.scrollHeight-n.clientHeight>10||n.scrollWidth-n.clientWidth>10)){clearTimeout(st);var i=-e.deltaY;if(isFinite(i)||(i=e.wheelDelta/10),!isFinite(i))return void console.log("did not find wheel motion attributes",e);var a,l=Math.exp(-Math.min(Math.max(i,-20),20)/100),c=ut.draglayer.select(".nsewdrag").node().getBoundingClientRect(),h=(e.clientX-c.left)/c.width,f=ot[0]+ot[2]*h,d=(c.bottom-e.clientY)/c.height,p=ot[1]+ot[3]*(1-d);if(s){for(a=0;a<j.length;a++)r(j[a],h,l);ot[2]*=l,ot[0]=f-ot[2]*h}if(o){for(a=0;a<N.length;a++)r(N[a],d,l);ot[3]*=l,ot[1]=p-ot[3]*(1-d)}return C(ot),k(o,s),st=setTimeout(function(){ot=[0,0,B,D],S()},lt),A.Lib.pauseEvent(e)}}}function w(t,e){function r(t,e){for(var r=0;r<t.length;r++){var n=t[r];n.fixedrange||(n.range=[n._r[0]-e/n._m,n._r[1]-e/n._m])}}function n(t){return 1-(t>=0?Math.min(t,.9):1/(1/Math.max(t,-.3)+3.222))}function i(t,e,r){for(var i=1-e,a=0,o=0;o<t.length;o++){var s=t[o];s.fixedrange||(a=o,s.range[e]=s._r[i]+(s._r[e]-s._r[i])/n(r/s._length))}return t[a]._length*(t[a]._r[e]-t[a].range[e])/(t[a]._r[e]-t[a]._r[i])}return"ew"===H||"ns"===G?(H&&r(j,t),G&&r(N,e),C([H?-t:0,G?-e:0,B,D]),void k(G,H)):("w"===H?t=i(j,0,t):"e"===H?t=i(j,1,-t):H||(t=0),"n"===G?e=i(N,1,e):"s"===G?e=i(N,0,-e):G||(e=0),C(["w"===H?t:0,"n"===G?e:0,B-t,D-e]),void k(G,H))}function k(e,r){function n(t){for(a=0;a<t.length;a++)t[a].fixedrange||o.push(t[a]._id)}function i(n,i){var s;for(a=0;a<n.length;a++)s=n[a],(r&&-1!==o.indexOf(s.xref)||e&&-1!==o.indexOf(s.yref))&&i.draw(t,a)}var a,o=[];for(r&&n(j),e&&n(N),a=0;a<o.length;a++)A.Axes.doTicks(t,o[a],!0);i(O.annotations||[],A.Annotations),i(O.shapes||[],A.Shapes)}function M(){var e,r,n=t._context.doubleClick,i=(H?j:[]).concat(G?N:[]),a={};if("autosize"===n)for(r=0;r<i.length;r++)e=i[r],e.fixedrange||(a[e._name+".autorange"]=!0);else if("reset"===n)for(r=0;r<i.length;r++)e=i[r],e._rangeInitial?a[e._name+".range"]=e._rangeInitial.slice():a[e._name+".autorange"]=!0;else if("reset+autosize"===n)for(r=0;r<i.length;r++)e=i[r],e.fixedrange||(void 0===e._rangeInitial||e.range[0]===e._rangeInitial[0]&&e.range[1]===e._rangeInitial[1]?a[e._name+".autorange"]=!0:a[e._name+".range"]=e._rangeInitial.slice());t.emit("plotly_doubleclick",null),A.relayout(t,a)}function S(e){for(var r={},n=0;n<q.length;n++){var i=q[n];e&&-1===e.indexOf(i._id.charAt(0))||(i._r[0]!==i.range[0]&&(r[i._name+".range[0]"]=i.range[0]),i._r[1]!==i.range[1]&&(r[i._name+".range[1]"]=i.range[1]),i.range=i._r.slice())}C([0,0,B,D]),A.relayout(t,r)}function C(t){var e,r,n,i,a,l,u=O._plots,c=Object.keys(u);for(e=0;e<c.length;e++)if(r=u[c[e]],n=r.x(),i=r.y(),a=s&&-1!==j.indexOf(n)&&!n.fixedrange,l=o&&-1!==N.indexOf(i)&&!i.fixedrange,a||l){var h=[0,0,n._length,i._length];a&&(h[0]=t[0],h[2]=t[2]),l&&(h[1]=t[1],h[3]=t[3]),r.plot.attr("viewBox",h.join(" "))}}var P,z,R,O=t._fullLayout,I=[e].concat(o&&s?e.overlays:[]),j=[e.x()],N=[e.y()],B=j[0]._length,D=N[0]._length,U=E.MINDRAG,V=E.MINZOOM;for(P=1;P<I.length;P++)z=I[P].x(),R=I[P].y(),-1===j.indexOf(z)&&j.push(z),-1===N.indexOf(R)&&N.push(R);var q=j.concat(N),H=l(j,s),G=l(N,o),Y=d(G+H,O.dragmode),X=o+s+"drag",W=e.draglayer.selectAll("."+X).data([0]);W.enter().append("rect").classed("drag",!0).classed(X,!0).style({fill:"transparent","stroke-width":0}).attr("data-subplot",e.id),W.call(A.Drawing.setRect,r,n,i,a).call(L.setCursor,Y);var Z=W.node();if(!G&&!H)return Z.onmousedown=null,Z.style.pointerEvents=o+s==="nsew"?"all":"none",Z;var $={element:Z,gd:t,plotinfo:e,xaxes:j,yaxes:N,doubleclick:M,prepFn:function(e,r,n){var i=t._fullLayout.dragmode;o+s==="nsew"?e.shiftKey&&(i="pan"===i?"zoom":"pan"):i="pan","lasso"===i?$.minDrag=1:$.minDrag=void 0,"zoom"===i?($.moveFn=f,$.doneFn=m,c(e,r,n)):"pan"===i?($.moveFn=w,$.doneFn=b,h()):("select"===i||"lasso"===i)&&T(e,r,n,$,i)}};L.dragElement($);var K,Q,J,tt,et,rt,nt,it,at,ot=[0,0,B,D],st=null,lt=300,ut=e.mainplot?O._plots[e.mainplot]:e;return o.length*s.length!==1&&(void 0!==Z.onwheel?Z.onwheel=x:void 0!==Z.onmousewheel&&(Z.onmousewheel=x)),Z}function g(t,e){var r,n=t.range[e],i=Math.abs(n-t.range[1-e]);return"date"===t.type?A.Lib.ms2DateTime(n,i):"log"===t.type?(r=Math.ceil(Math.max(0,-Math.log(i)/Math.LN10))+3,x.format("."+r+"g")(Math.pow(10,n))):(r=Math.floor(Math.log(Math.abs(n))/Math.LN10)-Math.floor(Math.log(i)/Math.LN10)+4,x.format("."+String(r)+"g")(n))}function v(t){t._dragging=!0;var e=t._replotPending;t._replotPending=!1,setTimeout(function(){t._replotPending=e,m(t)},E.DBLCLICKDELAY)}function m(t){t._dragging=!1,t._replotPending&&A.plot(t)}function y(t){x.select(t).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove()}function b(){var t=document.createElement("div");t.className="dragcover";var e=t.style;return e.position="fixed",e.left=0,e.right=0,e.top=0,e.bottom=0,e.zIndex=999999999,e.background="none",document.body.appendChild(t),t}var x=t("d3"),_=t("tinycolor2"),w=t("fast-isnumeric"),A=t("../../plotly"),k=t("../../lib"),M=t("../../lib/events"),T=t("./select"),E=t("./constants"),L=e.exports={};L.layoutAttributes={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],dflt:"zoom"},hovermode:{valType:"enumerated",values:["x","y","closest",!1]}},L.supplyLayoutDefaults=function(t,e,r){function n(r,n){return k.coerce(t,e,L.layoutAttributes,r,n)}n("dragmode");var i;if(e._hasCartesian){var a=e._isHoriz=L.isHoriz(r);i=a?"y":"x"}else i="closest";n("hovermode",i)},L.isHoriz=function(t){for(var e=!0,r=0;r<t.length;r++){var n=t[r];if("h"!==n.orientation){e=!1;break}}return e},L.init=function(t){var e=t._fullLayout;if(e._hasCartesian&&!t._context.staticPlot){var r=Object.keys(e._plots||{}).sort(function(t,r){if((e._plots[t].mainplot&&!0)===(e._plots[r].mainplot&&!0)){var n=t.split("y"),i=r.split("y");return n[0]===i[0]?Number(n[1]||1)-Number(i[1]||1):Number(n[0]||1)-Number(i[0]||1)}return e._plots[t].mainplot?1:-1});r.forEach(function(r){var n=e._plots[r];if(e._hasCartesian){var i=n.x(),a=n.y(),o=(i._linepositions[r]||[])[3],s=(a._linepositions[r]||[])[3],l=E.DRAGGERSIZE;if(w(o)&&"top"===i.side&&(o-=l),w(s)&&"right"!==a.side&&(s-=l),!n.mainplot){var u=p(t,n,0,0,i._length,a._length,"ns","ew");u.onmousemove=function(n){L.hover(t,n,r),e._lasthover=u,e._hoversubplot=r},u.onmouseout=function(e){t._dragging||L.unhover(t,e)},u.onclick=function(e){L.click(t,e)},p(t,n,-l,-l,l,l,"n","w"),p(t,n,i._length,-l,l,l,"n","e"),p(t,n,-l,a._length,l,l,"s","w"),p(t,n,i._length,a._length,l,l,"s","e")}w(o)&&("free"===i.anchor&&(o-=e._size.h*(1-a.domain[1])),p(t,n,.1*i._length,o,.8*i._length,l,"","ew"),p(t,n,0,o,.1*i._length,l,"","w"),p(t,n,.9*i._length,o,.1*i._length,l,"","e")),w(s)&&("free"===a.anchor&&(s-=e._size.w*i.domain[0]),p(t,n,s,.1*a._length,l,.8*a._length,"ns",""),p(t,n,s,.9*a._length,l,.1*a._length,"s",""),p(t,n,s,0,l,.1*a._length,"n",""))}});var n=e._hoverlayer.node();n.onmousemove=function(r){r.target=e._lasthover,L.hover(t,r,e._hoversubplot)},n.onclick=function(r){r.target=e._lasthover,L.click(t,r)},n.onmousedown=function(t){e._lasthover.onmousedown(t)}}};var S=E.YANGLE,C=Math.PI*S/180,P=1/Math.sin(C),z=Math.cos(C),R=Math.sin(C),O=E.HOVERARROWSIZE,I=E.HOVERTEXTPAD,j=E.HOVERFONTSIZE,N=E.HOVERFONT;L.hover=function(t,e,r){return"string"==typeof t&&(t=document.getElementById(t)),void 0===t._lastHoverTime&&(t._lastHoverTime=0),void 0!==t._hoverTimer&&(clearTimeout(t._hoverTimer),t._hoverTimer=void 0),Date.now()>t._lastHoverTime+E.HOVERMINTIME?(o(t,e,r),void(t._lastHoverTime=Date.now())):void(t._hoverTimer=setTimeout(function(){o(t,e,r),t._lastHoverTime=Date.now(),t._hoverTimer=void 0},E.HOVERMINTIME))},L.unhover=function(t,e,r){"string"==typeof t&&(t=document.getElementById(t)),t._hoverTimer&&(clearTimeout(t._hoverTimer),t._hoverTimer=void 0),f(t,e,r)},L.getDistanceFunction=function(t,e,r,n){return"closest"===t?n||a(e,r):"x"===t?e:r},L.getClosest=function(t,e,r){if(r.index!==!1)r.index>=0&&r.index<t.length?r.distance=0:r.index=!1;else for(var n=0;n<t.length;n++){var i=e(t[n]);i<r.distance&&(r.index=n,r.distance=i)}return r},L.loneHover=function(t,e){var r={color:t.color||A.Color.defaultLine,x0:t.x0||t.x||0,x1:t.x1||t.x||0,y0:t.y0||t.y||0,y1:t.y1||t.y||0,xLabel:t.xLabel,yLabel:t.yLabel,zLabel:t.zLabel,text:t.text,name:t.name,idealAlign:t.idealAlign,trace:{index:0,hoverinfo:""},xa:{_offset:0},ya:{_offset:0},index:0},n=x.select(e.container),i=e.outerContainer?x.select(e.outerContainer):n,a={hovermode:"closest",rotateLabels:!1,bgColor:e.bgColor||A.Color.background,container:n,outerContainer:i},o=l([r],a);return c(o,a.rotateLabels),o.node()},L.loneUnhover=function(t){var e=t instanceof x.selection?t:x.select(t);e.selectAll("g.hovertext").remove()},L.click=function(t,e){t._hoverdata&&e&&e.target&&(t.emit("plotly_click",{points:t._hoverdata}),e.stopImmediatePropagation&&e.stopImmediatePropagation())};var F=!0;L.dragAlign=function(t,e,r,n,i){var a=(t-r)/(n-r),o=a+e/(n-r),s=(a+o)/2;return"left"===i||"bottom"===i?a:"center"===i||"middle"===i?s:"right"===i||"top"===i?o:2/3-s>a?a:o>4/3-s?o:s};var B=[["sw-resize","s-resize","se-resize"],["w-resize","move","e-resize"],["nw-resize","n-resize","ne-resize"]];L.dragCursors=function(t,e,r,n){return t="left"===r?0:"center"===r?1:"right"===r?2:A.Lib.constrain(Math.floor(3*t),0,2),e="bottom"===n?0:"middle"===n?1:"top"===n?2:A.Lib.constrain(Math.floor(3*e),0,2),B[e][t]},L.dragElement=function(t){function e(e){var f=document.querySelector(".plugin-editable");return f&&x.select(f).on("blur").call(f),u._dragged=!1,u._dragging=!0,i=e.clientX,a=e.clientY,l=e.target,o=(new Date).getTime(),o-u._mouseDownTime<h?c+=1:(c=1,u._mouseDownTime=o),t.prepFn&&t.prepFn(e,i,a),s=b(),s.onmousemove=r,s.onmouseup=n,s.onmouseout=n,s.style.cursor=window.getComputedStyle(t.element).cursor,A.Lib.pauseEvent(e)}function r(e){var r=e.clientX-i,n=e.clientY-a,o=t.minDrag||E.MINDRAG;return Math.abs(r)<o&&(r=0),Math.abs(n)<o&&(n=0),(r||n)&&(u._dragged=!0,L.unhover(u)),t.moveFn&&t.moveFn(r,n,u._dragged),A.Lib.pauseEvent(e)}function n(e){if(s.onmousemove=null,s.onmouseup=null,s.onmouseout=null,A.Lib.removeElement(s),!u._dragging)return void(u._dragged=!1);if(u._dragging=!1,(new Date).getTime()-u._mouseDownTime>h&&(c=Math.max(c-1,1)),t.doneFn&&t.doneFn(u._dragged,c),!u._dragged){var r=document.createEvent("MouseEvents");r.initEvent("click",!0,!0),l.dispatchEvent(r)}return m(u),u._dragged=!1,A.Lib.pauseEvent(e)}var i,a,o,s,l,u=A.Lib.getPlotDiv(t.element)||{},c=1,h=E.DBLCLICKDELAY;u._mouseDownTime||(u._mouseDownTime=0),t.element.onmousedown=e,t.element.style.pointerEvents="all"},L.setCursor=function(t,e){(t.attr("class")||"").split(" ").forEach(function(e){0===e.indexOf("cursor-")&&t.classed(e,!1)}),e&&t.classed("cursor-"+e,!0)},L.inbox=function(t,e){return 0>t*e||0===t?E.MAXDIST*(.6-.3/Math.max(3,Math.abs(t-e))):1/0}},{"../../lib":349,"../../lib/events":344,"../../plotly":366,"./constants":373,"./select":379,d3:70,"fast-isnumeric":74,tinycolor2:229}],375:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../plots"),a=t("../../components/errorbars");r.name="cartesian",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.attributes=t("./attributes"),r.idRegex={x:/^x([2-9]|[1-9][0-9]+)?$/,y:/^y([2-9]|[1-9][0-9]+)?$/},r.attrRegex={x:/^xaxis([2-9]|[1-9][0-9]+)?$/,y:/^yaxis([2-9]|[1-9][0-9]+)?$/},r.plot=function(t){function e(t,e){for(var r=[],n=0;n<t.length;n++){var i=t[n],a=i[0].trace;a.xaxis+a.yaxis===e&&r.push(i)}return r}function r(t,e){for(var r=[],n=0;n<t.length;n++){var i=t[n],a=i[0].trace;a._module===e&&a.visible===!0&&r.push(i)}return r}for(var o=t._fullLayout,s=i.getSubplotIds(o,"cartesian"),l=t.calcdata,u=t._modules,c=0;c<s.length;c++){var h=s[c],f=o._plots[h],d=e(l,h),p=[];f.plot&&f.plot.selectAll("g.trace").remove();for(var g=0;g<u.length;g++){var v=u[g];if("cartesian"===v.basePlotModule.name&&"pie"!==v.name){var m=r(d,v);v.plot(t,f,m),n.markTime("done "+(m[0]&&m[0][0].trace.type)),m[0]&&m[0][0].trace&&i.traceIs(m[0][0].trace,"errorBarsOK")&&(p=p.concat(m))}}a.plot(t,f,p),n.markTime("done ErrorBars")}if(o._hasPie){var y=i.getModule("pie"),b=r(l,y);b.length&&y.plot(t,b)}},r.clean=function(t,e,r,n){n._hasPie&&!e._hasPie&&n._pielayer.selectAll("g.trace").remove()}},{"../../components/errorbars":323,"../../lib":349,"../plots":413,"./attributes":368}],376:[function(t,e,r){"use strict";var n=t("./index"),i=t("../font_attributes"),a=t("../../components/color/attributes"),o=t("../../lib/extend").extendFlat;e.exports={title:{valType:"string"},titlefont:o({},i,{}),type:{valType:"enumerated",values:["-","linear","log","date","category"],dflt:"-"},autorange:{valType:"enumerated",values:[!0,!1,"reversed"],dflt:!0},rangemode:{valType:"enumerated",values:["normal","tozero","nonnegative"],dflt:"normal"},range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},fixedrange:{valType:"boolean",dflt:!1},tickmode:{valType:"enumerated",values:["auto","linear","array"]},nticks:{valType:"integer",min:0,dflt:0},tick0:{valType:"number",dflt:0},dtick:{valType:"any",dflt:1},tickvals:{valType:"data_array"},ticktext:{valType:"data_array"},ticks:{valType:"enumerated",values:["outside","inside",""]},mirror:{valType:"enumerated",values:[!0,"ticks",!1,"all","allticks"],dflt:!1},ticklen:{valType:"number",min:0,dflt:5},tickwidth:{valType:"number",min:0,dflt:1},tickcolor:{valType:"color",dflt:a.defaultLine},showticklabels:{valType:"boolean",dflt:!0},tickfont:o({},i,{}),tickangle:{valType:"angle",dflt:"auto"},tickprefix:{valType:"string",dflt:""},showtickprefix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all"},ticksuffix:{valType:"string",dflt:""},showticksuffix:{valType:"enumerated",values:["all","first","last","none"],dflt:"all"},showexponent:{valType:"enumerated",values:["all","first","last","none"],dflt:"all"},exponentformat:{valType:"enumerated",values:["none","e","E","power","SI","B"],dflt:"B"},tickformat:{valType:"string",dflt:""},hoverformat:{valType:"string",dflt:""},showline:{valType:"boolean",dflt:!1},linecolor:{valType:"color",dflt:a.defaultLine},linewidth:{valType:"number",min:0,dflt:1},showgrid:{valType:"boolean"},gridcolor:{valType:"color",dflt:a.lightLine},gridwidth:{valType:"number",min:0,dflt:1},zeroline:{valType:"boolean"},zerolinecolor:{valType:"color",dflt:a.defaultLine},zerolinewidth:{valType:"number",dflt:1},anchor:{valType:"enumerated",values:["free",n.idRegex.x.toString(),n.idRegex.y.toString()]},side:{valType:"enumerated",values:["top","bottom","left","right"]},overlaying:{valType:"enumerated",values:["free",n.idRegex.x.toString(),n.idRegex.y.toString()]},domain:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]},position:{valType:"number",min:0,max:1,dflt:0},_deprecated:{autotick:{valType:"boolean"}}}},{"../../components/color/attributes":298,"../../lib/extend":345,"../font_attributes":383,"./index":375}],377:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../plots"),a=t("./constants"),o=t("./layout_attributes"),s=t("./axis_defaults"),l=t("./position_defaults"),u=t("./axis_ids");e.exports=function(t,e,r){function c(t,e){var r=Number(t.substr(5)||1),n=Number(e.substr(5)||1);return r-n}var h,f=Object.keys(t),d=[],p=[],g=[],v=[],m={},y={};for(h=0;h<r.length;h++){var b,x,_=r[h];if(i.traceIs(_,"cartesian"))b=d,x=p;else{if(!i.traceIs(_,"gl2d"))continue;b=g,x=v}var w=u.id2name(_.xaxis),A=u.id2name(_.yaxis);if(w&&-1===b.indexOf(w)&&b.push(w),A&&-1===x.indexOf(A)&&x.push(A),i.traceIs(_,"2dMap")&&(m[w]=!0,m[A]=!0),i.traceIs(_,"oriented")){var k="h"===_.orientation?A:w;y[k]=!0}}var M=e._hasGL3D||e._hasGeo;if(!M)for(h=0;h<f.length;h++){var T=f[h];-1===g.indexOf(T)&&-1===d.indexOf(T)&&a.xAxisMatch.test(T)?d.push(T):-1===v.indexOf(T)&&-1===p.indexOf(T)&&a.yAxisMatch.test(T)&&p.push(T)}d.length&&p.length&&(e._hasCartesian=!0);var E=d.concat(g).sort(c),L=p.concat(v).sort(c);E.concat(L).forEach(function(i){function a(t,e){return n.coerce(h,f,o,t,e)}var c=i.charAt(0),h=t[i]||{},f={},d={letter:c,font:e.font,outerTicks:m[i],showGrid:!y[i],name:i,data:r},p={letter:c,counterAxes:{x:L,y:E}[c].map(u.name2id),overlayableAxes:{x:E,y:L}[c].filter(function(e){
+return e!==i&&!(t[e]||{}).overlaying}).map(u.name2id)};s(h,f,a,d),l(h,f,a,p),e[i]=f,t[i]||"-"===h.type||(t[i]={type:h.type})}),E.length&&L.length&&n.coerce(t,e,i.layoutAttributes,"plot_bgcolor")}},{"../../lib":349,"../plots":413,"./axis_defaults":370,"./axis_ids":371,"./constants":373,"./layout_attributes":376,"./position_defaults":378}],378:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib");e.exports=function(t,e,r,a){var o=a.counterAxes||[],s=a.overlayableAxes||[],l=a.letter,u=i.coerce(t,e,{anchor:{valType:"enumerated",values:["free"].concat(o),dflt:n(t.position)?"free":o[0]||"free"}},"anchor");"free"===u&&r("position"),i.coerce(t,e,{side:{valType:"enumerated",values:"x"===l?["bottom","top"]:["left","right"],dflt:"x"===l?"bottom":"left"}},"side");var c=!1;if(s.length&&(c=i.coerce(t,e,{overlaying:{valType:"enumerated",values:[!1].concat(s),dflt:!1}},"overlaying")),!c){var h=r("domain");h[0]>h[1]-.01&&(e.domain=[0,1]),i.noneOrAll(t.domain,e.domain,[0,1])}return e}},{"../../lib":349,"fast-isnumeric":74}],379:[function(t,e,r){"use strict";function n(t){return t._id}var i=t("../../lib/polygon"),a=t("../../components/color"),o=t("./axes"),s=t("./constants"),l=i.filter,u=i.tester,c=s.MINSELECT;e.exports=function(t,e,r,i,h){function f(t){var e="y"===t._id.charAt(0)?1:0;return function(r){return t.p2d(r[e])}}function d(t,e){return t-e}var p,g=i.plotinfo.plot,v=i.element.getBoundingClientRect(),m=e-v.left,y=r-v.top,b=m,x=y,_="M"+m+","+y,w=i.xaxes[0]._length,A=i.yaxes[0]._length,k=i.xaxes.map(n),M=i.yaxes.map(n),T=i.xaxes.concat(i.yaxes);"lasso"===h&&(p=l([[m,y]],s.BENDPX));var E=g.selectAll("path.select-outline").data([1,2]);E.enter().append("path").attr("class",function(t){return"select-outline select-outline-"+t}).attr("d",_+"Z");var L,S,C,P,z,R=g.append("path").attr("class","zoombox-corners").style({fill:a.background,stroke:a.defaultLine,"stroke-width":1}).attr("d","M0,0Z"),O=[],I=i.gd,j=[];for(L=0;L<I.calcdata.length;L++)S=I.calcdata[L],C=S[0].trace,C._module&&C._module.selectPoints&&-1!==k.indexOf(C.xaxis)&&-1!==M.indexOf(C.yaxis)&&O.push({selectPoints:C._module.selectPoints,cd:S,xaxis:o.getFromId(I,C.xaxis),yaxis:o.getFromId(I,C.yaxis)});i.moveFn=function(t,e){var r,n;b=Math.max(0,Math.min(w,t+m)),x=Math.max(0,Math.min(A,e+y));var a=Math.abs(b-m),o=Math.abs(x-y);for("select"===h?(o<Math.min(.6*a,c)?(r=u([[m,0],[m,A],[b,A],[b,0]]),R.attr("d","M"+r.xmin+","+(y-c)+"h-4v"+2*c+"h4ZM"+(r.xmax-1)+","+(y-c)+"h4v"+2*c+"h-4Z")):a<Math.min(.6*o,c)?(r=u([[0,y],[0,x],[w,x],[w,y]]),R.attr("d","M"+(m-c)+","+r.ymin+"v-4h"+2*c+"v4ZM"+(m-c)+","+(r.ymax-1)+"v4h"+2*c+"v-4Z")):(r=u([[m,y],[m,x],[b,x],[b,y]]),R.attr("d","M0,0Z")),E.attr("d","M"+r.xmin+","+r.ymin+"H"+(r.xmax-1)+"V"+(r.ymax-1)+"H"+r.xmin+"Z")):"lasso"===h&&(p.addPt([b,x]),r=u(p.filtered),E.attr("d","M"+p.filtered.join("L")+"Z")),j=[],L=0;L<O.length;L++)P=O[L],[].push.apply(j,P.selectPoints(P,r));if(z={points:j},"select"===h){var s,l=z.range={};for(L=0;L<T.length;L++)n=T[L],s=n._id.charAt(0),l[n._id]=[n.p2d(r[s+"min"]),n.p2d(r[s+"max"])].sort(d)}else{var g=z.lassoPoints={};for(L=0;L<T.length;L++)n=T[L],g[n._id]=p.filtered.map(f(n))}i.gd.emit("plotly_selecting",z)},i.doneFn=function(t,e){if(t||2!==e)i.gd.emit("plotly_selected",z);else{for(E.remove(),L=0;L<O.length;L++)P=O[L],P.selectPoints(P,!1);I.emit("plotly_deselect",null)}R.remove()}}},{"../../components/color":299,"../../lib/polygon":354,"./axes":369,"./constants":373}],380:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("./constants"),s=t("./clean_datum"),l=t("./axis_ids");e.exports=function(t){function e(e,r){if(e>0)return Math.log(e)/Math.LN10;if(0>=e&&r&&t.range&&2===t.range.length){var n=t.range[0],i=t.range[1];return.5*(n+i-3*c*Math.abs(n-i))}return o.BADNUM}function r(t){return Math.pow(10,t)}function u(t){return i(t)?Number(t):o.BADNUM}var c=10;if(t.c2l="log"===t.type?e:u,t.l2c="log"===t.type?r:u,t.l2d=function(e){return t.c2d(t.l2c(e))},t.p2d=function(e){return t.l2d(t.p2l(e))},t.setScale=function(){var e,r=t._td._fullLayout._size;if(t._categories||(t._categories=[]),t.overlaying){var n=l.getFromId(t._td,t.overlaying);t.domain=n.domain}for(t.range&&2===t.range.length&&t.range[0]!==t.range[1]||(t.range=[-1,1]),e=0;2>e;e++)i(t.range[e])||(t.range[e]=i(t.range[1-e])?t.range[1-e]*(e?10:.1):e?1:-1),t.range[e]<-(Number.MAX_VALUE/2)?t.range[e]=-(Number.MAX_VALUE/2):t.range[e]>Number.MAX_VALUE/2&&(t.range[e]=Number.MAX_VALUE/2);if("y"===t._id.charAt(0)?(t._offset=r.t+(1-t.domain[1])*r.h,t._length=r.h*(t.domain[1]-t.domain[0]),t._m=t._length/(t.range[0]-t.range[1]),t._b=-t._m*t.range[1]):(t._offset=r.l+t.domain[0]*r.w,t._length=r.w*(t.domain[1]-t.domain[0]),t._m=t._length/(t.range[1]-t.range[0]),t._b=-t._m*t.range[0]),!isFinite(t._m)||!isFinite(t._b))throw a.notifier("Something went wrong with axis scaling","long"),t._td._replotting=!1,new Error("axis scaling")},t.l2p=function(e){return i(e)?n.round(a.constrain(t._b+t._m*e,-c*t._length,(1+c)*t._length),2):o.BADNUM},t.p2l=function(e){return(e-t._b)/t._m},t.c2p=function(e,r){return t.l2p(t.c2l(e,r))},t.p2c=function(e){return t.l2c(t.p2l(e))},-1!==["linear","log","-"].indexOf(t.type))t.c2d=u,t.d2c=function(t){return t=s(t),i(t)?Number(t):o.BADNUM},t.d2l=function(e,r){return"log"===t.type?t.c2l(t.d2c(e),r):t.d2c(e)};else if("date"===t.type){if(t.c2d=function(t){return i(t)?a.ms2DateTime(t):o.BADNUM},t.d2c=function(t){return i(t)?Number(t):a.dateTime2ms(t)},t.d2l=t.d2c,t.range&&t.range.length>1)try{var h=t.range.map(a.dateTime2ms);!i(t.range[0])&&i(h[0])&&(t.range[0]=h[0]),!i(t.range[1])&&i(h[1])&&(t.range[1]=h[1])}catch(f){console.log(f,t.range)}}else"category"===t.type&&(t.c2d=function(e){return t._categories[Math.round(e)]},t.d2c=function(e){null!==e&&void 0!==e&&-1===t._categories.indexOf(e)&&t._categories.push(e);var r=t._categories.indexOf(e);return-1===r?o.BADNUM:r},t.d2l=t.d2c);t.makeCalcdata=function(e,r){var n,i,a;if(r in e)for(n=e[r],i=new Array(n.length),a=0;a<n.length;a++)i[a]=t.d2c(n[a]);else{var o=r+"0"in e?t.d2c(e[r+"0"]):0,s=e["d"+r]?Number(e["d"+r]):1;for(n=e[{x:"y",y:"x"}[r]],i=new Array(n.length),a=0;a<n.length;a++)i[a]=o+a*s}return i},t._min=[],t._max=[],t._minDtick=null,t._forceTick0=null}},{"../../lib":349,"./axis_ids":371,"./clean_datum":372,"./constants":373,d3:70,"fast-isnumeric":74}],381:[function(t,e,r){"use strict";function n(t){var e=["showexponent","showtickprefix","showticksuffix"],r=e.filter(function(e){return void 0!==t[e]}),n=function(e){return t[e]===t[r[0]]};return r.every(n)||1===r.length?t[r[0]]:void 0}var i=t("../../lib"),a=t("./layout_attributes");e.exports=function(t,e,r,o,s){var l=i.coerce2(t,e,a,"ticklen"),u=i.coerce2(t,e,a,"tickwidth"),c=i.coerce2(t,e,a,"tickcolor"),h=r("ticks",s.outerTicks||l||u||c?"outside":"");h||(delete e.ticklen,delete e.tickwidth,delete e.tickcolor);var f=n(t),d=r("tickprefix");d&&r("showtickprefix",f);var p=r("ticksuffix");p&&r("showticksuffix",f);var g=r("showticklabels");if(g&&(i.coerceFont(r,"tickfont",s.font||{}),r("tickangle"),"category"!==o)){var v=r("tickformat");v||"date"===o||(r("showexponent",f),r("exponentformat"))}"category"===o||s.noHover||r("hoverformat")}},{"../../lib":349,"./layout_attributes":376}],382:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t,e,r,i){var a="auto";"array"!==t.tickmode||"log"!==i&&"date"!==i||(t.tickmode="auto"),Array.isArray(t.tickvals)?a="array":t.dtick&&n(t.dtick)&&(a="linear");var o=r("tickmode",a);if("auto"===o)r("nticks");else if("linear"===o)r("tick0"),r("dtick");else{var s=r("tickvals");void 0===s?e.tickmode="auto":r("ticktext")}}},{"fast-isnumeric":74}],383:[function(t,e,r){"use strict";e.exports={family:{valType:"string",noBlank:!0,strict:!0},size:{valType:"number",min:1},color:{valType:"color"}}},{}],384:[function(t,e,r){"use strict";function n(t,e){this.id=t.id,this.graphDiv=t.graphDiv,this.container=t.container,this.topojsonURL=t.topojsonURL,p(),this.hoverContainer=null,this.topojsonName=null,this.topojson=null,this.projectionType=null,this.projection=null,this.clipAngle=null,this.setScale=null,this.path=null,this.zoom=null,this.zoomReset=null,this.makeFramework(),this.updateFx(e.hovermode),this.traceHash={}}function i(t){for(var e=[],r=0;r<t.length;r++){var n=t[r];n.visible===!0&&e.push(n)}return e}function a(t,e,r){return c.geo.graticule().extent([[t[0],e[0]],[t[1],e[1]]]).step(r)}function o(t,e,r){var n=b.layerNameToAdjective[e];t.select("."+e).selectAll("path").attr("stroke","none").call(h.fill,r[n+"color"])}function s(t,e,r){var n=b.layerNameToAdjective[e];t.select("."+e).selectAll("path").attr("fill","none").call(h.stroke,r[n+"color"]).call(f.dashLine,"",r[n+"width"])}function l(t,e,r){t.select("."+e+"graticule").selectAll("path").attr("fill","none").call(h.stroke,r[e].gridcolor).call(f.dashLine,"",r[e].gridwidth)}function u(t){var e={type:"linear",showexponent:"all",exponentformat:d.layoutAttributes.exponentformat.dflt,_td:{_fullLayout:t}};return d.setConvert(e),e}var c=t("d3"),h=t("../../components/color"),f=t("../../components/drawing"),d=t("../../plots/cartesian/axes"),p=t("./projections"),g=t("./set_scale"),v=t("./zoom"),m=t("./zoom_reset"),y=t("../../constants/xmlns_namespaces"),b=t("../../constants/geo_constants"),x=t("../../lib/topojson_utils"),_=t("topojson").feature;e.exports=n;var w=n.prototype;w.plot=function(t,e,r){var n,i,a=this,o=e[a.id],s=e._size;a.projection=null,a.setScale=g(o,s),a.makeProjection(o),a.makePath(),a.adjustLayout(o,s),a.zoom=v(a,o),a.zoomReset=m(a,o),a.mockAxis=u(e),a.framework.call(a.zoom).on("dblclick.zoom",a.zoomReset),n=x.getTopojsonName(o),null===a.topojson||n!==a.topojsonName?(a.topojsonName=n,void 0!==PlotlyGeoAssets.topojson[a.topojsonName]?(a.topojson=PlotlyGeoAssets.topojson[a.topojsonName],a.onceTopojsonIsLoaded(t,o)):(i=x.getTopojsonPath(a.topojsonURL,a.topojsonName),r.push(new Promise(function(e,r){c.json(i,function(n,s){return n?void r(404===n.status?new Error(["plotly.js could not find topojson file at",i,".","Make sure the *topojsonURL* plot config option","is set properly."].join(" ")):new Error(["unexpected error while fetching topojson file at",i].join(" "))):(a.topojson=s,PlotlyGeoAssets.topojson[a.topojsonName]=s,a.onceTopojsonIsLoaded(t,o),void e())})})))):a.onceTopojsonIsLoaded(t,o)},w.onceTopojsonIsLoaded=function(t,e){var r;this.drawLayout(e);var n=this.traceHash,a={};for(r=0;r<t.length;r++){var o=t[r];a[o.type]=a[o.type]||[],a[o.type].push(o)}var s=Object.keys(n),l=Object.keys(a);for(r=0;r<s.length;r++){var u=s[r];if(-1===l.indexOf(u)){var c=n[u][0];c.visible=!1,a[u]=[c]}}for(l=Object.keys(a),r=0;r<l.length;r++){var h=a[l[r]],f=h[0]._module;f.plot(this,i(h),e)}this.traceHash=a,this.render()},w.updateFx=function(t){this.showHover=t!==!1},w.makeProjection=function(t){var e,r=t.projection,n=r.type,i=null===this.projection||n!==this.projectionType;i?(this.projectionType=n,e=this.projection=c.geo[b.projNames[n]]()):e=this.projection,e.translate(r._translate0).precision(b.precision),t._isAlbersUsa||e.rotate(r._rotate).center(r._center),t._clipAngle?(this.clipAngle=t._clipAngle,e.clipAngle(t._clipAngle-b.clipPad)):this.clipAngle=null,r.parallels&&e.parallels(r.parallels),i&&this.setScale(e),e.translate(r._translate).scale(r._scale)},w.makePath=function(){this.path=c.geo.path().projection(this.projection)},w.makeFramework=function(){var t=this.geoDiv=c.select(this.container).append("div");t.attr("id",this.id).style("position","absolute");var e=this.hoverContainer=t.append("svg");e.attr(y.svgAttrs).style({position:"absolute","z-index":20,"pointer-events":"none"});var r=this.framework=t.append("svg");r.attr(y.svgAttrs).attr({position:"absolute",preserveAspectRatio:"none"}),r.append("g").attr("class","bglayer").append("rect"),r.append("g").attr("class","baselayer"),r.append("g").attr("class","choroplethlayer"),r.append("g").attr("class","baselayeroverchoropleth"),r.append("g").attr("class","scattergeolayer"),r.on("dblclick.zoom",null)},w.adjustLayout=function(t,e){var r=t.domain;this.geoDiv.style({left:e.l+e.w*r.x[0]+t._marginX+"px",top:e.t+e.h*(1-r.y[1])+t._marginY+"px",width:t._width+"px",height:t._height+"px"}),this.hoverContainer.attr({width:t._width,height:t._height}),this.framework.attr({width:t._width,height:t._height}),this.framework.select(".bglayer").select("rect").attr({width:t._width,height:t._height}).style({fill:t.bgcolor,"stroke-width":0})},w.drawTopo=function(t,e,r){if(r["show"+e]===!0){var n=this.topojson,i="frame"===e?b.sphereSVG:_(n,n.objects[e]);t.append("g").datum(i).attr("class",e).append("path").attr("class","basepath")}},w.drawGraticule=function(t,e,r){var n=r[e];if(n.showgrid===!0){var i=b.scopeDefaults[r.scope],o=i.lonaxisRange,s=i.lataxisRange,l="lonaxis"===e?[n.dtick]:[0,n.dtick],u=a(o,s,l);t.append("g").datum(u).attr("class",e+"graticule").append("path").attr("class","graticulepath")}},w.drawLayout=function(t){var e,r=this.framework.select("g.baselayer"),n=b.baseLayers,i=b.axesNames;r.selectAll("*").remove();for(var a=0;a<n.length;a++)e=n[a],-1!==i.indexOf(e)?this.drawGraticule(r,e,t):this.drawTopo(r,e,t);this.styleLayout(t)},w.styleLayer=function(t,e,r){var n=b.fillLayers,i=b.lineLayers;-1!==n.indexOf(e)?o(t,e,r):-1!==i.indexOf(e)&&s(t,e,r)},w.styleLayout=function(t){for(var e,r=this.framework.select("g.baselayer"),n=b.baseLayers,i=b.axesNames,a=0;a<n.length;a++)e=n[a],-1!==i.indexOf(e)?l(r,e,t):this.styleLayer(r,e,t)},w.render=function(){function t(t){var e=a([t.lon,t.lat]);return e?"translate("+e[0]+","+e[1]+")":null}function e(t){var e=a.rotate(),r=c.geo.distance([t.lon,t.lat],[-e[0],-e[1]]),n=s*Math.PI/180;return r>n?"0":"1.0"}var r=this.framework,n=r.select("g.choroplethlayer"),i=r.select("g.scattergeolayer"),a=this.projection,o=this.path,s=this.clipAngle;r.selectAll("path.basepath").attr("d",o),r.selectAll("path.graticulepath").attr("d",o),n.selectAll("path.choroplethlocation").attr("d",o),n.selectAll("path.basepath").attr("d",o),i.selectAll("path.js-line").attr("d",o),null!==s?(i.selectAll("path.point").style("opacity",e).attr("transform",t),i.selectAll("text").style("opacity",e).attr("transform",t)):(i.selectAll("path.point").attr("transform",t),i.selectAll("text").attr("transform",t))}},{"../../components/color":299,"../../components/drawing":317,"../../constants/geo_constants":334,"../../constants/xmlns_namespaces":338,"../../lib/topojson_utils":361,"../../plots/cartesian/axes":369,"./projections":391,"./set_scale":392,"./zoom":393,"./zoom_reset":394,d3:70,topojson:230}],385:[function(t,e,r){"use strict";var n=t("./geo"),i=t("../../plots/plots");r.name="geo",r.attr="geo",r.idRoot="geo",r.idRegex=/^geo([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^geo([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"geo");void 0===window.PlotlyGeoAssets&&(window.PlotlyGeoAssets={topojson:{}});for(var o=0;o<a.length;o++){var s=a[o],l=i.getSubplotData(r,"geo",s),u=e[s]._geo;void 0===u&&(u=new n({id:s,graphDiv:t,container:e._geocontainer.node(),topojsonURL:t._context.topojsonURL},e),e[s]._geo=u),u.plot(l,e,t._promises)}},r.clean=function(t,e,r,n){for(var a=i.getSubplotIds(n,"geo"),o=0;o<a.length;o++){var s=a[o],l=n[s]._geo;!e[s]&&l&&l.geoDiv.remove()}}},{"../../plots/plots":413,"./geo":384,"./layout/attributes":386,"./layout/defaults":389,"./layout/layout_attributes":390}],386:[function(t,e,r){"use strict";e.exports={geo:{valType:"geoid",dflt:"geo"}}},{}],387:[function(t,e,r){"use strict";var n=t("../../../components/color/attributes");e.exports={range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},showgrid:{valType:"boolean",dflt:!1},tick0:{valType:"number"},dtick:{valType:"number"},gridcolor:{valType:"color",dflt:n.lightLine},gridwidth:{valType:"number",min:0,dflt:1}}},{"../../../components/color/attributes":298}],388:[function(t,e,r){"use strict";var n=t("../../../lib"),i=t("../../../constants/geo_constants"),a=t("./axis_attributes");e.exports=function(t,e){function r(t,e){return n.coerce(s,l,a,t,e)}function o(t){var r,n,a,o,s,l,u=e.scope;return"world"===u?(r=e.projection,n=r.type,a=r.rotation,s=i[t+"Span"],l=void 0!==s[n]?s[n]/2:s["*"]/2,o="lonaxis"===t?a.lon:a.lat,[o-l,o+l]):i.scopeDefaults[u][t+"Range"]}for(var s,l,u=i.axesNames,c=0;c<u.length;c++){var h=u[c];s=t[h]||{},l={};var f=o(h),d=r("range",f);n.noneOrAll(s.range,l.range,[0,1]),r("tick0",d[0]),r("dtick","lonaxis"===h?30:10);var p=r("showgrid");p&&(r("gridcolor"),r("gridwidth")),e[h]=l,e[h]._fullRange=f}}},{"../../../constants/geo_constants":334,"../../../lib":349,"./axis_attributes":387}],389:[function(t,e,r){"use strict";function n(t,e,r){var n,i=r("scope"),a="world"!==i,s=o.scopeDefaults[i],u=r("resolution"),c=r("projection.type",s.projType),h="albers usa"===c,f=-1!==c.indexOf("conic");if(f){var d=s.projParallels||[0,60];r("projection.parallels",d)}if(h)e.scope="usa";else{var p=s.projRotate||[0,0,0];r("projection.rotation.lon",p[0]),r("projection.rotation.lat",p[1]),r("projection.rotation.roll",p[2]),n=r("showcoastlines",!a),n&&(r("coastlinecolor"),r("coastlinewidth")),n=r("showocean"),n&&r("oceancolor")}r("projection.scale"),n=r("showland"),n&&r("landcolor"),n=r("showlakes"),n&&r("lakecolor"),n=r("showrivers"),n&&(r("rivercolor"),r("riverwidth")),n=r("showcountries",a),n&&(r("countrycolor"),r("countrywidth")),("usa"===i||"north america"===i&&50===u)&&(r("showsubunits",!0),r("subunitcolor"),r("subunitwidth")),a||(n=r("showframe",!0),n&&(r("framecolor"),r("framewidth"))),r("bgcolor"),l(t,e),e._isHighRes=50===u,e._clipAngle=o.lonaxisSpan[c]/2,e._isAlbersUsa=h,e._isConic=f,e._isScoped=a;var g=e.projection.rotation||{};e.projection._rotate=[-g.lon||0,-g.lat||0,g.roll||0]}var i=t("../../../lib"),a=t("../../plots"),o=t("../../../constants/geo_constants"),s=t("./layout_attributes"),l=t("./axis_defaults");e.exports=function(t,e,r){function o(t,e){return i.coerce(l,u,s,t,e)}if(e._hasGeo)for(var l,u,c=a.findSubplotIds(r,"geo"),h=c.length,f=0;h>f;f++){var d=c[f];l=t[d]?t[d]:t[d]={},l=t[d],u={},o("domain.x"),o("domain.y",[f/h,(f+1)/h]),n(l,u,o),e[d]=u}}},{"../../../constants/geo_constants":334,"../../../lib":349,"../../plots":413,"./axis_defaults":388,"./layout_attributes":390}],390:[function(t,e,r){"use strict";var n=t("../../../components/color/attributes"),i=t("../../../constants/geo_constants"),a=t("./axis_attributes");e.exports={domain:{x:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]},y:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]}},resolution:{valType:"enumerated",values:[110,50],dflt:110,coerceNumber:!0},scope:{valType:"enumerated",values:Object.keys(i.scopeDefaults),dflt:"world"},projection:{type:{valType:"enumerated",values:Object.keys(i.projNames)},rotation:{lon:{valType:"number"},lat:{valType:"number"},roll:{valType:"number"}},parallels:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},scale:{valType:"number",min:0,max:10,dflt:1}},showcoastlines:{valType:"boolean"},coastlinecolor:{valType:"color",dflt:n.defaultLine},coastlinewidth:{valType:"number",min:0,dflt:1},showland:{valType:"boolean",dflt:!1},landcolor:{valType:"color",dflt:i.landColor},showocean:{valType:"boolean",dflt:!1},oceancolor:{valType:"color",dflt:i.waterColor},showlakes:{valType:"boolean",dflt:!1},lakecolor:{valType:"color",dflt:i.waterColor},showrivers:{valType:"boolean",dflt:!1},rivercolor:{valType:"color",dflt:i.waterColor},riverwidth:{valType:"number",min:0,dflt:1},showcountries:{valType:"boolean"},countrycolor:{valType:"color",dflt:n.defaultLine},countrywidth:{valType:"number",min:0,dflt:1},showsubunits:{valType:"boolean"},subunitcolor:{valType:"color",dflt:n.defaultLine},subunitwidth:{valType:"number",min:0,dflt:1},showframe:{valType:"boolean"},framecolor:{valType:"color",dflt:n.defaultLine},framewidth:{valType:"number",min:0,dflt:1},bgcolor:{valType:"color",dflt:n.background},lonaxis:a,lataxis:a}},{"../../../components/color/attributes":298,"../../../constants/geo_constants":334,"./axis_attributes":387}],391:[function(t,e,r){function n(){function t(t,r){return{type:"Feature",id:t.id,properties:t.properties,geometry:e(t.geometry,r)}}function e(t,r){if(!t)return null;if("GeometryCollection"===t.type)return{type:"GeometryCollection",geometries:object.geometries.map(function(t){return e(t,r)})};if(!k.hasOwnProperty(t.type))return null;var n=k[t.type];return i.geo.stream(t,r(n)),n.result()}function r(){}function n(t){if((e=t.length)<4)return!1;for(var e,r=0,n=t[e-1][1]*t[0][0]-t[e-1][0]*t[0][1];++r<e;)n+=t[r-1][1]*t[r][0]-t[r-1][0]*t[r][1];return 0>=n}function a(t,e){for(var r=e[0],n=e[1],i=!1,a=0,o=t.length,s=o-1;o>a;s=a++){var l=t[a],u=l[0],c=l[1],h=t[s],f=h[0],d=h[1];c>n^d>n&&(f-u)*(n-c)/(d-c)+u>r&&(i=!i)}return i}function o(t){return t>1?L:-1>t?-L:Math.asin(t)}function s(t,e){var r=(2+L)*Math.sin(e);e/=2;for(var n=0,i=1/0;10>n&&Math.abs(i)>M;n++){var a=Math.cos(e);e-=i=(e+Math.sin(e)*(a+2)-r)/(2*a*(1+a))}return[2/Math.sqrt(E*(4+E))*t*(1+Math.cos(e)),2*Math.sqrt(E/(4+E))*Math.sin(e)]}function l(t,e){function r(r,n){var i=R(r/e,n);return i[0]*=t,i}return arguments.length<2&&(e=t),1===e?R:e===1/0?c:(r.invert=function(r,n){var i=R.invert(r/t,n);return i[0]*=e,i},r)}function u(){var t=2,e=z(l),r=e(t);return r.coefficient=function(r){return arguments.length?e(t=+r):t},r}function c(t,e){return[t*Math.cos(e)/Math.cos(e/=2),2*Math.sin(e)]}function h(t,e){return[3*t/(2*E)*Math.sqrt(E*E/3-e*e),e]}function f(t,e){return[t,1.25*Math.log(Math.tan(E/4+.4*e))]}function d(t){return function(e){var r,n=t*Math.sin(e),i=30;do e-=r=(e+Math.sin(e)-n)/(1+Math.cos(e));while(Math.abs(r)>M&&--i>0);return e/2}}function p(t,e,r){function n(r,n){return[t*r*Math.cos(n=i(n)),e*Math.sin(n)]}var i=d(r);return n.invert=function(n,i){var a=o(i/e);return[n/(t*Math.cos(a)),o((2*a+Math.sin(2*a))/r)]},n}function g(t,e){var r=e*e,n=r*r;return[t*(.8707-.131979*r+n*(-.013791+n*(.003971*r-.001529*n))),e*(1.007226+r*(.015085+n*(-.044475+.028874*r-.005916*n)))]}function v(t,e){var r,n=Math.min(18,36*Math.abs(e)/E),i=Math.floor(n),a=n-i,o=(r=I[i])[0],s=r[1],l=(r=I[++i])[0],u=r[1],c=(r=I[Math.min(19,++i)])[0],h=r[1];return[t*(l+a*(c-o)/2+a*a*(c-2*l+o)/2),(e>0?L:-L)*(u+a*(h-s)/2+a*a*(h-2*u+s)/2)]}function m(t,e){return[t*Math.cos(e),e]}i.geo.project=function(t,r){var n=r.stream;if(!n)throw new Error("not yet supported");return(t&&y.hasOwnProperty(t.type)?y[t.type]:e)(t,n)};var y={Feature:t,FeatureCollection:function(e,r){return{type:"FeatureCollection",features:e.features.map(function(e){return t(e,r)})}}},b=[],x=[],_={point:function(t,e){b.push([t,e])},result:function(){var t=b.length?b.length<2?{type:"Point",coordinates:b[0]}:{type:"MultiPoint",coordinates:b}:null;return b=[],t}},w={lineStart:r,point:function(t,e){b.push([t,e])},lineEnd:function(){b.length&&(x.push(b),b=[])},result:function(){var t=x.length?x.length<2?{type:"LineString",coordinates:x[0]}:{type:"MultiLineString",coordinates:x}:null;return x=[],t}},A={polygonStart:r,lineStart:r,point:function(t,e){b.push([t,e])},lineEnd:function(){var t=b.length;if(t){do b.push(b[0].slice());while(++t<4);x.push(b),b=[]}},polygonEnd:r,result:function(){if(!x.length)return null;var t=[],e=[];return x.forEach(function(r){n(r)?t.push([r]):e.push(r)}),e.forEach(function(e){var r=e[0];t.some(function(t){return a(t[0],r)?(t.push(e),!0):void 0})||t.push([e])}),x=[],t.length?t.length>1?{type:"MultiPolygon",coordinates:t}:{type:"Polygon",coordinates:t[0]}:null}},k={Point:_,MultiPoint:_,LineString:w,MultiLineString:w,Polygon:A,MultiPolygon:A,Sphere:A},M=1e-6,T=M*M,E=Math.PI,L=E/2,S=(Math.sqrt(E),E/180),C=180/E,P=i.geo.projection,z=i.geo.projectionMutator;i.geo.interrupt=function(t){function e(e,r){for(var n=0>r?-1:1,i=l[+(0>r)],a=0,o=i.length-1;o>a&&e>i[a][2][0];++a);var s=t(e-i[a][1][0],r);return s[0]+=t(i[a][1][0],n*r>n*i[a][0][1]?i[a][0][1]:r)[0],s}function r(){s=l.map(function(e){return e.map(function(e){var r,n=t(e[0][0],e[0][1])[0],i=t(e[2][0],e[2][1])[0],a=t(e[1][0],e[0][1])[1],o=t(e[1][0],e[1][1])[1];return a>o&&(r=a,a=o,o=r),[[n,a],[i,o]]})})}function n(){for(var t=1e-6,e=[],r=0,n=l[0].length;n>r;++r){var o=l[0][r],s=180*o[0][0]/E,u=180*o[0][1]/E,c=180*o[1][1]/E,h=180*o[2][0]/E,f=180*o[2][1]/E;e.push(a([[s+t,u+t],[s+t,c-t],[h-t,c-t],[h-t,f+t]],30))}for(var r=l[1].length-1;r>=0;--r){var o=l[1][r],s=180*o[0][0]/E,u=180*o[0][1]/E,c=180*o[1][1]/E,h=180*o[2][0]/E,f=180*o[2][1]/E;e.push(a([[h-t,f-t],[h-t,c+t],[s+t,c+t],[s+t,u-t]],30))}return{type:"Polygon",coordinates:[i.merge(e)]}}function a(t,e){for(var r,n,i,a=-1,o=t.length,s=t[0],l=[];++a<o;){r=t[a],n=(r[0]-s[0])/e,i=(r[1]-s[1])/e;for(var u=0;e>u;++u)l.push([s[0]+u*n,s[1]+u*i]);s=r}return l.push(r),l}function o(t,e){return Math.abs(t[0]-e[0])<M&&Math.abs(t[1]-e[1])<M}var s,l=[[[[-E,0],[0,L],[E,0]]],[[[-E,0],[0,-L],[E,0]]]];t.invert&&(e.invert=function(r,n){for(var i=s[+(0>n)],a=l[+(0>n)],u=0,c=i.length;c>u;++u){var h=i[u];if(h[0][0]<=r&&r<h[1][0]&&h[0][1]<=n&&n<h[1][1]){var f=t.invert(r-t(a[u][1][0],0)[0],n);return f[0]+=a[u][1][0],o(e(f[0],f[1]),[r,n])?f:null}}});var u=i.geo.projection(e),c=u.stream;return u.stream=function(t){var e=u.rotate(),r=c(t),a=(u.rotate([0,0]),c(t));return u.rotate(e),r.sphere=function(){i.geo.stream(n(),a)},r},u.lobes=function(t){return arguments.length?(l=t.map(function(t){return t.map(function(t){return[[t[0][0]*E/180,t[0][1]*E/180],[t[1][0]*E/180,t[1][1]*E/180],[t[2][0]*E/180,t[2][1]*E/180]]})}),r(),u):l.map(function(t){return t.map(function(t){return[[180*t[0][0]/E,180*t[0][1]/E],[180*t[1][0]/E,180*t[1][1]/E],[180*t[2][0]/E,180*t[2][1]/E]]})})},u},s.invert=function(t,e){var r=.5*e*Math.sqrt((4+E)/E),n=o(r),i=Math.cos(n);return[t/(2/Math.sqrt(E*(4+E))*(1+i)),o((n+r*(i+2))/(2+L))]},(i.geo.eckert4=function(){return P(s)}).raw=s;var R=i.geo.azimuthalEqualArea.raw;c.invert=function(t,e){var r=2*o(e/2);return[t*Math.cos(r/2)/Math.cos(r),r]},(i.geo.hammer=u).raw=l,h.invert=function(t,e){return[2/3*E*t/Math.sqrt(E*E/3-e*e),e]},(i.geo.kavrayskiy7=function(){return P(h)}).raw=h,f.invert=function(t,e){return[t,2.5*Math.atan(Math.exp(.8*e))-.625*E]},(i.geo.miller=function(){return P(f)}).raw=f;var O=(d(E),p(Math.SQRT2/L,Math.SQRT2,E));(i.geo.mollweide=function(){return P(O)}).raw=O,g.invert=function(t,e){var r,n=e,i=25;do{var a=n*n,o=a*a;n-=r=(n*(1.007226+a*(.015085+o*(-.044475+.028874*a-.005916*o)))-e)/(1.007226+a*(.045255+o*(-0.311325+.259866*a-.005916*11*o)))}while(Math.abs(r)>M&&--i>0);return[t/(.8707+(a=n*n)*(-.131979+a*(-.013791+a*a*a*(.003971-.001529*a)))),n]},(i.geo.naturalEarth=function(){return P(g)}).raw=g;var I=[[.9986,-.062],[1,0],[.9986,.062],[.9954,.124],[.99,.186],[.9822,.248],[.973,.31],[.96,.372],[.9427,.434],[.9216,.4958],[.8962,.5571],[.8679,.6176],[.835,.6769],[.7986,.7346],[.7597,.7903],[.7186,.8435],[.6732,.8936],[.6213,.9394],[.5722,.9761],[.5322,1]];I.forEach(function(t){t[1]*=1.0144}),v.invert=function(t,e){var r=e/L,n=90*r,i=Math.min(18,Math.abs(n/5)),a=Math.max(0,Math.floor(i));do{var o=I[a][1],s=I[a+1][1],l=I[Math.min(19,a+2)][1],u=l-o,c=l-2*s+o,h=2*(Math.abs(r)-s)/u,f=c/u,d=h*(1-f*h*(1-2*f*h));if(d>=0||1===a){n=(e>=0?5:-5)*(d+i);var p,g=50;do i=Math.min(18,Math.abs(n)/5),a=Math.floor(i),d=i-a,o=I[a][1],s=I[a+1][1],l=I[Math.min(19,a+2)][1],n-=(p=(e>=0?L:-L)*(s+d*(l-o)/2+d*d*(l-2*s+o)/2)-e)*C;while(Math.abs(p)>T&&--g>0);break}}while(--a>=0);var v=I[a][0],m=I[a+1][0],y=I[Math.min(19,a+2)][0];return[t/(m+d*(y-v)/2+d*d*(y-2*m+v)/2),n*S]},(i.geo.robinson=function(){return P(v)}).raw=v,m.invert=function(t,e){return[t/Math.cos(e),e]},(i.geo.sinusoidal=function(){return P(m)}).raw=m}var i=t("d3");e.exports=n},{d3:70}],392:[function(t,e,r){"use strict";function n(t,e){var r=t.projection,n=t.lonaxis,o=t.lataxis,l=t.domain,u=t.framewidth||0,c=e.w*(l.x[1]-l.x[0]),h=e.h*(l.y[1]-l.y[0]),f=n.range[0]+s,d=n.range[1]-s,p=o.range[0]+s,g=o.range[1]-s,v=n._fullRange[0]+s,m=n._fullRange[1]-s,y=o._fullRange[0]+s,b=o._fullRange[1]-s;r._translate0=[e.l+c/2,e.t+h/2];var x=d-f,_=g-p,w=[f+x/2,p+_/2],A=r._rotate;r._center=[w[0]+A[0],w[1]+A[1]];var k=function(e){function n(t){return Math.min(_*c/(t[1][0]-t[0][0]),_*h/(t[1][1]-t[0][1]))}var o,s,l,x,_=e.scale(),w=r._translate0,A=i(f,p,d,g),k=i(v,y,m,b);l=a(e,A),o=n(l),x=a(e,k),r._fullScale=n(x),e.scale(o),l=a(e,A),s=[w[0]-l[0][0]+u,w[1]-l[0][1]+u],r._translate=s,e.translate(s),l=a(e,A),t._isAlbersUsa||e.clipExtent(l),o=r.scale*o,r._scale=o,t._width=Math.round(l[1][0])+u,t._height=Math.round(l[1][1])+u,t._marginX=(c-Math.round(l[1][0]))/2,t._marginY=(h-Math.round(l[1][1]))/2};return k}function i(t,e,r,n){var i=(r-t)/4;return{type:"Polygon",coordinates:[[[t,e],[t,n],[t+i,n],[t+2*i,n],[t+3*i,n],[r,n],[r,e],[r-i,e],[r-2*i,e],[r-3*i,e],[t,e]]]}}function a(t,e){return o.geo.path().projection(t).bounds(e)}var o=t("d3"),s=t("../../constants/geo_constants").clipPad;e.exports=n},{"../../constants/geo_constants":334,d3:70}],393:[function(t,e,r){"use strict";function n(t,e){var r;return(r=e._isScoped?a:e._clipAngle?s:o)(t,e.projection)}function i(t,e){var r=e._fullScale;return _.behavior.zoom().translate(t.translate()).scale(t.scale()).scaleExtent([.5*r,100*r])}function a(t,e){function r(){_.select(this).style(k)}function n(){o.scale(_.event.scale).translate(_.event.translate),t.render()}function a(){_.select(this).style(M)}var o=t.projection,s=i(o,e);return s.on("zoomstart",r).on("zoom",n).on("zoomend",a),s}function o(t,e){function r(t){return v.invert(t)}function n(t){var e=v(r(t));return Math.abs(e[0]-t[0])>y||Math.abs(e[1]-t[1])>y}function a(){_.select(this).style(k),l=_.mouse(this),u=v.rotate(),c=v.translate(),h=u,f=r(l)}function o(){return d=_.mouse(this),n(l)?(m.scale(v.scale()),void m.translate(v.translate())):(v.scale(_.event.scale),v.translate([c[0],_.event.translate[1]]),f?r(d)&&(g=r(d),p=[h[0]+(g[0]-f[0]),u[1],u[2]],v.rotate(p),h=p):(l=d,f=r(l)),void t.render())}function s(){_.select(this).style(M)}var l,u,c,h,f,d,p,g,v=t.projection,m=i(v,e),y=2;return m.on("zoomstart",a).on("zoom",o).on("zoomend",s),m}function s(t,e){function r(t){m++||t({type:"zoomstart"})}function n(t){t({type:"zoom"})}function a(t){--m||t({type:"zoomend"})}var o,s=t.projection,d={r:s.rotate(),k:s.scale()},p=i(s,e),g=x(p,"zoomstart","zoom","zoomend"),m=0,y=p.on;return p.on("zoomstart",function(){_.select(this).style(k);var t=_.mouse(this),e=s.rotate(),i=e,a=s.translate(),m=u(e);o=l(s,t),y.call(p,"zoom",function(){var r=_.mouse(this);if(s.scale(d.k=_.event.scale),o){if(l(s,r)){s.rotate(e).translate(a);var u=l(s,r),p=h(o,u),y=v(c(m,p)),b=d.r=f(y,o,i);isFinite(b[0])&&isFinite(b[1])&&isFinite(b[2])||(b=i),s.rotate(b),i=b}}else t=r,o=l(s,t);n(g.of(this,arguments))}),r(g.of(this,arguments))}).on("zoomend",function(){_.select(this).style(M),y.call(p,"zoom",null),a(g.of(this,arguments))}).on("zoom.redraw",function(){t.render()}),_.rebind(p,g,"on")}function l(t,e){var r=t.invert(e);return r&&isFinite(r[0])&&isFinite(r[1])&&m(r)}function u(t){var e=.5*t[0]*w,r=.5*t[1]*w,n=.5*t[2]*w,i=Math.sin(e),a=Math.cos(e),o=Math.sin(r),s=Math.cos(r),l=Math.sin(n),u=Math.cos(n);return[a*s*u+i*o*l,i*s*u-a*o*l,a*o*u+i*s*l,a*s*l-i*o*u]}function c(t,e){var r=t[0],n=t[1],i=t[2],a=t[3],o=e[0],s=e[1],l=e[2],u=e[3];return[r*o-n*s-i*l-a*u,r*s+n*o+i*u-a*l,r*l-n*u+i*o+a*s,r*u+n*l-i*s+a*o]}function h(t,e){if(t&&e){var r=b(t,e),n=Math.sqrt(y(r,r)),i=.5*Math.acos(Math.max(-1,Math.min(1,y(t,e)))),a=Math.sin(i)/n;return n&&[Math.cos(i),r[2]*a,-r[1]*a,r[0]*a]}}function f(t,e,r){var n=g(e,2,t[0]);n=g(n,1,t[1]),n=g(n,0,t[2]-r[2]);var i,a,o=e[0],s=e[1],l=e[2],u=n[0],c=n[1],h=n[2],f=Math.atan2(s,o)*A,p=Math.sqrt(o*o+s*s);Math.abs(c)>p?(a=(c>0?90:-90)-f,i=0):(a=Math.asin(c/p)*A-f,i=Math.sqrt(p*p-c*c));var v=180-a-2*f,m=(Math.atan2(h,u)-Math.atan2(l,i))*A,y=(Math.atan2(h,u)-Math.atan2(l,-i))*A,b=d(r[0],r[1],a,m),x=d(r[0],r[1],v,y);return x>=b?[a,m,r[2]]:[v,y,r[2]]}function d(t,e,r,n){var i=p(r-t),a=p(n-e);return Math.sqrt(i*i+a*a)}function p(t){return(t%360+540)%360-180;
+}function g(t,e,r){var n=r*w,i=t.slice(),a=0===e?1:0,o=2===e?1:2,s=Math.cos(n),l=Math.sin(n);return i[a]=t[a]*s-t[o]*l,i[o]=t[o]*s+t[a]*l,i}function v(t){return[Math.atan2(2*(t[0]*t[1]+t[2]*t[3]),1-2*(t[1]*t[1]+t[2]*t[2]))*A,Math.asin(Math.max(-1,Math.min(1,2*(t[0]*t[2]-t[3]*t[1]))))*A,Math.atan2(2*(t[0]*t[3]+t[1]*t[2]),1-2*(t[2]*t[2]+t[3]*t[3]))*A]}function m(t){var e=t[0]*w,r=t[1]*w,n=Math.cos(r);return[n*Math.cos(e),n*Math.sin(e),Math.sin(r)]}function y(t,e){for(var r=0,n=0,i=t.length;i>n;++n)r+=t[n]*e[n];return r}function b(t,e){return[t[1]*e[2]-t[2]*e[1],t[2]*e[0]-t[0]*e[2],t[0]*e[1]-t[1]*e[0]]}function x(t){for(var e=0,r=arguments.length,n=[];++e<r;)n.push(arguments[e]);var i=_.dispatch.apply(null,n);return i.of=function(e,r){return function(n){var a;try{a=n.sourceEvent=_.event,n.target=t,_.event=n,i[n.type].apply(e,r)}finally{_.event=a}}},i}var _=t("d3"),w=Math.PI/180,A=180/Math.PI,k={cursor:"pointer"},M={cursor:"auto"};e.exports=n},{d3:70}],394:[function(t,e,r){"use strict";function n(t,e){var r=t.projection,n=t.zoom,a=function(){t.makeProjection(e),t.makePath(),n.scale(r.scale()),n.translate(r.translate()),i.loneUnhover(t.hoverContainer),t.render()};return a}var i=t("../cartesian/graph_interact");e.exports=n},{"../cartesian/graph_interact":374}],395:[function(t,e,r){"use strict";function n(t,e){this.element=t,this.plot=e,this.mouseListener=null,this.wheelListener=null,this.lastInputTime=Date.now(),this.lastPos=[0,0],this.boxEnabled=!1,this.boxStart=[0,0],this.boxEnd=[0,0]}function i(t){var e=t.mouseContainer,r=t.glplot,i=new n(e,r);return i.mouseListener=a(e,function(e,n,a){function o(e,r,n){var a=Math.min(r,n),o=Math.max(r,n);a!==o?(e[0]=a,e[1]=o,i.dataBox=e):(t.selectBox.selectBox=[0,0,1,1],t.glplot.setDirty())}var s=t.xaxis.range,l=t.yaxis.range,u=r.viewBox,c=i.lastPos[0],h=i.lastPos[1];switch(n*=r.pixelRatio,a*=r.pixelRatio,a=u[3]-u[1]-a,t.fullLayout.dragmode){case"zoom":if(e){var f=n/(u[2]-u[0])*(s[1]-s[0])+s[0],d=a/(u[3]-u[1])*(l[1]-l[0])+l[0];i.boxEnabled||(i.boxStart[0]=f,i.boxStart[1]=d),i.boxEnd[0]=f,i.boxEnd[1]=d,i.boxEnabled=!0}else i.boxEnabled&&(o(s,i.boxStart[0],i.boxEnd[0]),o(l,i.boxStart[1],i.boxEnd[1]),i.boxEnabled=!1);break;case"pan":if(i.boxEnabled=!1,e){var p=(c-n)*(s[1]-s[0])/(r.viewBox[2]-r.viewBox[0]),g=(h-a)*(l[1]-l[0])/(r.viewBox[3]-r.viewBox[1]);s[0]+=p,s[1]+=p,l[0]+=g,l[1]+=g,i.lastInputTime=Date.now(),t.cameraChanged()}}i.lastPos[0]=n,i.lastPos[1]=a}),i.wheelListener=o(e,function(e,n){var a=t.xaxis.range,o=t.yaxis.range,s=r.viewBox,l=i.lastPos[0],u=i.lastPos[1];switch(t.fullLayout.dragmode){case"zoom":break;case"pan":var c=Math.exp(.1*n/(s[3]-s[1])),h=l/(s[2]-s[0])*(a[1]-a[0])+a[0],f=u/(s[3]-s[1])*(o[1]-o[0])+o[0];a[0]=(a[0]-h)*c+h,a[1]=(a[1]-h)*c+h,o[0]=(o[0]-f)*c+f,o[1]=(o[1]-f)*c+f,i.lastInputTime=Date.now(),t.cameraChanged()}return!0}),i}var a=t("mouse-change"),o=t("mouse-wheel");e.exports=i},{"mouse-change":196,"mouse-wheel":200}],396:[function(t,e,r){"use strict";function n(t){this.scene=t,this.gl=t.gl,this.pixelRatio=t.pixelRatio,this.screenBox=[0,0,1,1],this.viewBox=[0,0,1,1],this.dataBox=[-1,-1,1,1],this.borderLineEnable=[!1,!1,!1,!1],this.borderLineWidth=[1,1,1,1],this.borderLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.ticks=[[],[]],this.tickEnable=[!0,!0,!1,!1],this.tickPad=[15,15,15,15],this.tickAngle=[0,0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickMarkLength=[0,0,0,0],this.tickMarkWidth=[0,0,0,0],this.tickMarkColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labels=["x","y"],this.labelEnable=[!0,!0,!1,!1],this.labelAngle=[0,Math.PI/2,0,3*Math.PI/2],this.labelPad=[15,15,15,15],this.labelSize=[12,12],this.labelFont=["sans-serif","sans-serif"],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.title="",this.titleEnable=!0,this.titleCenter=[0,0,0,0],this.titleAngle=0,this.titleColor=[0,0,0,1],this.titleFont="sans-serif",this.titleSize=18,this.gridLineEnable=[!0,!0],this.gridLineColor=[[0,0,0,.5],[0,0,0,.5]],this.gridLineWidth=[1,1],this.zeroLineEnable=[!0,!0],this.zeroLineWidth=[1,1],this.zeroLineColor=[[0,0,0,1],[0,0,0,1]],this.borderColor=[0,0,0,0],this.backgroundColor=[0,0,0,0]}function i(t){return new n(t)}var a=t("../../plotly"),o=t("../../lib/html2unicode"),s=t("../../lib/str2rgbarray"),l=n.prototype,u=["xaxis","yaxis"];l.merge=function(t){this.titleEnable=!1,this.backgroundColor=s(t.plot_bgcolor);var e,r,n,i,a,l,c,h,f,d,p;for(d=0;2>d;++d){for(e=u[d],r=t[this.scene[e]._name],n=/Click to enter .+ title/.test(r.title)?"":r.title,p=0;2>=p;p+=2)this.labelEnable[d+p]=!1,this.labels[d+p]=o(n),this.labelColor[d+p]=s(r.titlefont.color),this.labelFont[d+p]=r.titlefont.family,this.labelSize[d+p]=r.titlefont.size,this.labelPad[d+p]=this.getLabelPad(e,r),this.tickEnable[d+p]=!1,this.tickColor[d+p]=s((r.tickfont||{}).color),this.tickAngle[d+p]="auto"===r.tickangle?0:Math.PI*-r.tickangle/180,this.tickPad[d+p]=this.getTickPad(r),this.tickMarkLength[d+p]=0,this.tickMarkWidth[d+p]=r.tickwidth||0,this.tickMarkColor[d+p]=s(r.tickcolor),this.borderLineEnable[d+p]=!1,this.borderLineColor[d+p]=s(r.linecolor),this.borderLineWidth[d+p]=r.linewidth||0;c=this.hasSharedAxis(r),a=this.hasAxisInDfltPos(e,r)&&!c,l=this.hasAxisInAltrPos(e,r)&&!c,i=r.mirror||!1,h=c?-1!==String(i).indexOf("all"):!!i,f=c?"allticks"===i:-1!==String(i).indexOf("ticks"),a?this.labelEnable[d]=!0:l&&(this.labelEnable[d+2]=!0),a?this.tickEnable[d]=r.showticklabels:l&&(this.tickEnable[d+2]=r.showticklabels),(a||h)&&(this.borderLineEnable[d]=r.showline),(l||h)&&(this.borderLineEnable[d+2]=r.showline),(a||f)&&(this.tickMarkLength[d]=this.getTickMarkLength(r)),(l||f)&&(this.tickMarkLength[d+2]=this.getTickMarkLength(r)),this.gridLineEnable[d]=r.showgrid,this.gridLineColor[d]=s(r.gridcolor),this.gridLineWidth[d]=r.gridwidth,this.zeroLineEnable[d]=r.zeroline,this.zeroLineColor[d]=s(r.zerolinecolor),this.zeroLineWidth[d]=r.zerolinewidth}},l.hasSharedAxis=function(t){var e=this.scene,r=a.Plots.getSubplotIds(e.fullLayout,"gl2d"),n=a.Axes.findSubplotsWithAxis(r,t);return 0!==n.indexOf(e.id)},l.hasAxisInDfltPos=function(t,e){var r=e.side;return"xaxis"===t?"bottom"===r:"yaxis"===t?"left"===r:void 0},l.hasAxisInAltrPos=function(t,e){var r=e.side;return"xaxis"===t?"top"===r:"yaxis"===t?"right"===r:void 0},l.getLabelPad=function(t,e){var r=1.5,n=e.titlefont.size,i=e.showticklabels;return"xaxis"===t?"top"===e.side?-10+n*(r+(i?1:0)):-10+n*(r+(i?.5:0)):"yaxis"===t?"right"===e.side?10+n*(r+(i?1:.5)):10+n*(r+(i?.5:0)):void 0},l.getTickPad=function(t){return"outside"===t.ticks?10+t.ticklen:15},l.getTickMarkLength=function(t){if(!t.ticks)return 0;var e=t.ticklen;return"inside"===t.ticks?-e:e},e.exports=i},{"../../lib/html2unicode":348,"../../lib/str2rgbarray":359,"../../plotly":366}],397:[function(t,e,r){"use strict";var n=t("../../plotly"),i=t("./scene2d"),a=n.Plots;r.name="gl2d",r.attr=["xaxis","yaxis"],r.idRoot=["x","y"],r.idRegex={x:/^x([2-9]|[1-9][0-9]+)?$/,y:/^y([2-9]|[1-9][0-9]+)?$/},r.attrRegex={x:/^xaxis([2-9]|[1-9][0-9]+)?$/,y:/^yaxis([2-9]|[1-9][0-9]+)?$/},r.attributes=t("../cartesian/attributes"),r.plot=function(t){for(var e=t._fullLayout,r=t._fullData,n=a.getSubplotIds(e,"gl2d"),o=0;o<n.length;o++){var s=n[o],l=e._plots[s],u=a.getSubplotData(r,"gl2d",s),c=l._scene2d;void 0===c&&(c=new i({container:t.querySelector(".gl-container"),id:s,staticPlot:t._context.staticPlot,plotGlPixelRatio:t._context.plotGlPixelRatio},e),l._scene2d=c),c.plot(u,e,t.layout)}}},{"../../plotly":366,"../cartesian/attributes":368,"./scene2d":398}],398:[function(t,e,r){"use strict";function n(t,e){this.container=t.container,this.pixelRatio=t.plotGlPixelRatio||window.devicePixelRatio,this.id=t.id,this.staticPlot=!!t.staticPlot,this.fullLayout=e,this.updateAxes(e),this.makeFramework(),this.glplotOptions=d(this),this.glplotOptions.merge(e),this.glplot=c(this.glplotOptions),this.camera=p(this),this.traces={},this.spikes=h(this.glplot),this.selectBox=f(this.glplot,{innerFill:!1,outerFill:!0}),this.pickResult=null,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.stopped=!1,this.redraw=this.draw.bind(this),this.redraw()}function i(t,e){for(var r=0;2>r;++r){var n=t[r],i=e[r];if(n.length!==i.length)return!0;for(var a=0;a<n.length;++a)if(n[a].x!==i[a].x)return!0}return!1}var a,o,s=t("../../plots/plots"),l=t("../../plots/cartesian/axes"),u=t("../../plots/cartesian/graph_interact"),c=t("gl-plot2d"),h=t("gl-spikes2d"),f=t("gl-select-box"),d=t("./convert"),p=t("./camera"),g=t("../../lib/html2unicode"),v=t("../../lib/show_no_webgl_msg"),m=["xaxis","yaxis"];e.exports=n;var y=n.prototype;y.makeFramework=function(){if(this.staticPlot){if(!o){a=document.createElement("canvas");try{o=a.getContext("webgl",{preserveDrawingBuffer:!0,premultipliedAlpha:!0,antialias:!0})}catch(t){throw new Error(["Error creating static canvas/context for image server"].join(" "))}}this.canvas=a,this.gl=o}else{var e,r=document.createElement("canvas"),n={premultipliedAlpha:!0};try{e=r.getContext("webgl",n)}catch(t){}if(!e)try{e=r.getContext("experimental-webgl",n)}catch(t){}e||v(this),this.canvas=r,this.gl=e}var i=this.canvas,s=this.pixelRatio,l=this.fullLayout;i.width=0|Math.ceil(s*l.width),i.height=0|Math.ceil(s*l.height),i.style.width="100%",i.style.height="100%",i.style.position="absolute",i.style.top="0px",i.style.left="0px",i.style["pointer-events"]="none";var u=this.svgContainer=document.createElementNS("http://www.w3.org/2000/svg","svg");u.style.position="absolute",u.style.top=u.style.left="0px",u.style.width=u.style.height="100%",u.style["z-index"]=20,u.style["pointer-events"]="none";var c=this.mouseContainer=document.createElement("div");c.style.position="absolute";var h=this.container;h.appendChild(i),h.appendChild(u),h.appendChild(c)},y.toImage=function(t){t||(t="png"),this.stopped=!0,this.staticPlot&&this.container.appendChild(a),this.glplot.setDirty(!0),this.glplot.draw();var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.bindFramebuffer(e.FRAMEBUFFER,null);var i=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,i);for(var o=0,s=n-1;s>o;++o,--s)for(var l=0;r>l;++l)for(var u=0;4>u;++u){var c=i[4*(r*o+l)+u];i[4*(r*o+l)+u]=i[4*(r*s+l)+u],i[4*(r*s+l)+u]=c}var h=document.createElement("canvas");h.width=r,h.height=n;var f=h.getContext("2d"),d=f.createImageData(r,n);d.data.set(i),f.putImageData(d,0,0);var p;switch(t){case"jpeg":p=h.toDataURL("image/jpeg");break;case"webp":p=h.toDataURL("image/webp");break;default:p=h.toDataURL("image/png")}return this.staticPlot&&this.container.removeChild(a),p},y.computeTickMarks=function(){this.xaxis._length=this.glplot.viewBox[2]-this.glplot.viewBox[0],this.yaxis._length=this.glplot.viewBox[3]-this.glplot.viewBox[1];for(var t=[l.calcTicks(this.xaxis),l.calcTicks(this.yaxis)],e=0;2>e;++e)for(var r=0;r<t[e].length;++r)t[e][r].text=g(t[e][r].text+"").replace(/\n/g," ");return t},y.updateAxes=function(t){var e=l.subplotMatch,r="xaxis"+this.id.match(e)[1],n="yaxis"+this.id.match(e)[2];this.xaxis=t[r],this.yaxis=t[n]},y.updateFx=function(t){var e=this.fullLayout;e.dragmode=t.dragmode,e.hovermode=t.hovermode},y.cameraChanged=function(){var t=this.camera,e=this.xaxis.range,r=this.yaxis.range;this.glplot.setDataBox([e[0],r[0],e[1],r[1]]);var n=this.computeTickMarks(),a=this.glplotOptions.ticks;i(n,a)&&(this.glplotOptions.ticks=n,this.glplotOptions.dataBox=t.dataBox,this.glplot.update(this.glplotOptions))},y.destroy=function(){this.glplot.dispose()},y.plot=function(t,e){var r,n,i=this.glplot,a=this.pixelRatio;this.fullLayout=e,this.updateAxes(e);var o=e.width,u=e.height,c=0|Math.ceil(a*o),h=0|Math.ceil(a*u),f=this.canvas;(f.width!==c||f.height!==h)&&(f.width=c,f.height=h),t?Array.isArray(t)||(t=[t]):t=[];var d,p;for(r=0;r<t.length;++r){if(d=t[r],p=this.traces[d.uid])p.update(d);else{var g=s.getModule(d.type);p=g.plot(this,d)}this.traces[d.uid]=p}var v=Object.keys(this.traces);t:for(r=0;r<v.length;++r){for(n=0;n<t.length;++n)if(t[n].uid===v[r])continue t;p=this.traces[v[r]],p.dispose(),delete this.traces[v[r]]}var y=this.glplotOptions;y.merge(e),y.screenBox=[0,0,o,u];var b=e._size,x=this.xaxis.domain,_=this.yaxis.domain;y.viewBox=[b.l+x[0]*b.w,b.b+_[0]*b.h,o-b.r-(1-x[1])*b.w,u-b.t-(1-_[1])*b.h],this.mouseContainer.style.width=b.w*(x[1]-x[0])+"px",this.mouseContainer.style.height=b.h*(_[1]-_[0])+"px",this.mouseContainer.height=b.h*(_[1]-_[0]),this.mouseContainer.style.left=b.l+x[0]*b.w+"px",this.mouseContainer.style.top=b.t+(1-_[1])*b.h+"px";var w=this.bounds;for(w[0]=w[1]=1/0,w[2]=w[3]=-(1/0),v=Object.keys(this.traces),r=0;r<v.length;++r){p=this.traces[v[r]];for(var A=0;2>A;++A)w[A]=Math.min(w[A],p.bounds[A]),w[A+2]=Math.max(w[A+2],p.bounds[A+2])}var k;for(r=0;2>r;++r)w[r]>w[r+2]&&(w[r]=-1,w[r+2]=1),k=this[m[r]],k._length=y.viewBox[r+2]-y.viewBox[r],l.doAutoRange(k);y.ticks=this.computeTickMarks();var M=this.xaxis.range,T=this.yaxis.range;y.dataBox=[M[0],T[0],M[1],T[1]],y.merge(e),i.update(y)},y.draw=function(){if(!this.stopped){requestAnimationFrame(this.redraw);var t=this.glplot,e=this.camera,r=e.mouseListener,n=this.fullLayout;this.cameraChanged();var i=r.x*t.pixelRatio,a=this.canvas.height-t.pixelRatio*r.y;if(e.boxEnabled&&"zoom"===n.dragmode)this.selectBox.enabled=!0,this.selectBox.selectBox=[Math.min(e.boxStart[0],e.boxEnd[0]),Math.min(e.boxStart[1],e.boxEnd[1]),Math.max(e.boxStart[0],e.boxEnd[0]),Math.max(e.boxStart[1],e.boxEnd[1])],t.setDirty();else{this.selectBox.enabled=!1;var o=n._size,s=this.xaxis.domain,l=this.yaxis.domain,c=t.pick(i/t.pixelRatio+o.l+s[0]*o.w,a/t.pixelRatio-(o.t+(1-l[1])*o.h));if(c&&n.hovermode){var h=c.object._trace.handlePick(c);if(h&&(!this.lastPickResult||this.lastPickResult.trace!==h.trace||this.lastPickResult.dataCoord[0]!==h.dataCoord[0]||this.lastPickResult.dataCoord[1]!==h.dataCoord[1])){var f=this.lastPickResult=h;this.spikes.update({center:c.dataCoord}),f.screenCoord=[((t.viewBox[2]-t.viewBox[0])*(c.dataCoord[0]-t.dataBox[0])/(t.dataBox[2]-t.dataBox[0])+t.viewBox[0])/t.pixelRatio,(this.canvas.height-(t.viewBox[3]-t.viewBox[1])*(c.dataCoord[1]-t.dataBox[1])/(t.dataBox[3]-t.dataBox[1])-t.viewBox[1])/t.pixelRatio];var d=f.hoverinfo;if("all"!==d){var p=d.split("+");-1===p.indexOf("x")&&(f.traceCoord[0]=void 0),-1===p.indexOf("y")&&(f.traceCoord[1]=void 0),-1===p.indexOf("text")&&(f.textLabel=void 0),-1===p.indexOf("name")&&(f.name=void 0)}u.loneHover({x:f.screenCoord[0],y:f.screenCoord[1],xLabel:this.hoverFormatter("xaxis",f.traceCoord[0]),yLabel:this.hoverFormatter("yaxis",f.traceCoord[1]),text:f.textLabel,name:f.name,color:f.color},{container:this.svgContainer}),this.lastPickResult={dataCoord:c.dataCoord}}}else!c&&this.lastPickResult&&(this.spikes.update({}),this.lastPickResult=null,u.loneUnhover(this.svgContainer))}t.draw()}},y.hoverFormatter=function(t,e){if(void 0!==e){var r=this[t];return l.tickText(r,r.c2l(e),"hover").text}}},{"../../lib/html2unicode":348,"../../lib/show_no_webgl_msg":357,"../../plots/cartesian/axes":369,"../../plots/cartesian/graph_interact":374,"../../plots/plots":413,"./camera":395,"./convert":396,"gl-plot2d":122,"gl-select-box":152,"gl-spikes2d":178}],399:[function(t,e,r){"use strict";function n(t,e){t=t||document.body,e=e||{};var r=[.01,1/0];"distanceLimits"in e&&(r[0]=e.distanceLimits[0],r[1]=e.distanceLimits[1]),"zoomMin"in e&&(r[0]=e.zoomMin),"zoomMax"in e&&(r[1]=e.zoomMax);var n=a({center:e.center||[0,0,0],up:e.up||[0,1,0],eye:e.eye||[0,0,10],mode:e.mode||"orbit",distanceLimits:r}),l=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],u=0,c=t.clientWidth,h=t.clientHeight,f={keyBindingMode:"rotate",view:n,element:t,delay:e.delay||16,rotateSpeed:e.rotateSpeed||1,zoomSpeed:e.zoomSpeed||1,translateSpeed:e.translateSpeed||1,flipX:!!e.flipX,flipY:!!e.flipY,modes:n.modes,tick:function(){var e=i(),r=this.delay,a=e-2*r;n.idle(e-r),n.recalcMatrix(a),n.flush(e-(100+2*r));for(var o=!0,s=n.computedMatrix,f=0;16>f;++f)o=o&&l[f]===s[f],l[f]=s[f];var d=t.clientWidth===c&&t.clientHeight===h;return c=t.clientWidth,h=t.clientHeight,o?!d:(u=Math.exp(n.computedRadius[0]),!0)},lookAt:function(t,e,r){n.lookAt(n.lastT(),t,e,r)},rotate:function(t,e,r){n.rotate(n.lastT(),t,e,r)},pan:function(t,e,r){n.pan(n.lastT(),t,e,r)},translate:function(t,e,r){n.translate(n.lastT(),t,e,r)}};Object.defineProperties(f,{matrix:{get:function(){return n.computedMatrix},set:function(t){return n.setMatrix(n.lastT(),t),n.computedMatrix},enumerable:!0},mode:{get:function(){return n.getMode()},set:function(t){var e=n.computedUp.slice(),r=n.computedEye.slice(),a=n.computedCenter.slice();if(n.setMode(t),"turntable"===t){var o=i();n._active.lookAt(o,r,a,e),n._active.lookAt(o+500,r,a,[0,0,1]),n._active.flush(o)}return n.getMode()},enumerable:!0},center:{get:function(){return n.computedCenter},set:function(t){return n.lookAt(n.lastT(),null,t),n.computedCenter},enumerable:!0},eye:{get:function(){return n.computedEye},set:function(t){return n.lookAt(n.lastT(),t),n.computedEye},enumerable:!0},up:{get:function(){return n.computedUp},set:function(t){return n.lookAt(n.lastT(),null,null,t),n.computedUp},enumerable:!0},distance:{get:function(){return u},set:function(t){return n.setDistance(n.lastT(),t),t},enumerable:!0},distanceLimits:{get:function(){return n.getDistanceLimits(r)},set:function(t){return n.setDistanceLimits(t),t},enumerable:!0}}),t.addEventListener("contextmenu",function(t){return t.preventDefault(),!1});var d=0,p=0;return o(t,function(e,r,a,o){var s="rotate"===f.keyBindingMode,l="pan"===f.keyBindingMode,c="zoom"===f.keyBindingMode,h=!!o.control,g=!!o.alt,v=!!o.shift,m=!!(1&e),y=!!(2&e),b=!!(4&e),x=1/t.clientHeight,_=x*(r-d),w=x*(a-p),A=f.flipX?1:-1,k=f.flipY?1:-1,M=i(),T=Math.PI*f.rotateSpeed;if((s&&m&&!h&&!g&&!v||m&&!h&&!g&&v)&&n.rotate(M,A*T*_,-k*T*w,0),(l&&m&&!h&&!g&&!v||y||m&&h&&!g&&!v)&&n.pan(M,-f.translateSpeed*_*u,f.translateSpeed*w*u,0),c&&m&&!h&&!g&&!v||b||m&&!h&&g&&!v){var E=-f.zoomSpeed*w/window.innerHeight*(M-n.lastT())*100;n.pan(M,0,0,u*(Math.exp(E)-1))}return d=r,p=a,!0}),s(t,function(t,e){var r=f.flipX?1:-1,a=f.flipY?1:-1,o=i();if(Math.abs(t)>Math.abs(e))n.rotate(o,0,0,-t*r*Math.PI*f.rotateSpeed/window.innerWidth);else{var s=-f.zoomSpeed*a*e/window.innerHeight*(o-n.lastT())/100;n.pan(o,0,0,u*(Math.exp(s)-1))}},!0),f}e.exports=n;var i=t("right-now"),a=t("3d-view"),o=t("mouse-change"),s=t("mouse-wheel")},{"3d-view":38,"mouse-change":196,"mouse-wheel":200,"right-now":210}],400:[function(t,e,r){"use strict";var n=t("./scene"),i=t("../plots"),a=["xaxis","yaxis","zaxis"];r.name="gl3d",r.attr="scene",r.idRoot="scene",r.idRegex=/^scene([2-9]|[1-9][0-9]+)?$/,r.attrRegex=/^scene([2-9]|[1-9][0-9]+)?$/,r.attributes=t("./layout/attributes"),r.layoutAttributes=t("./layout/layout_attributes"),r.supplyLayoutDefaults=t("./layout/defaults"),r.plot=function(t){var e=t._fullLayout,r=t._fullData,a=i.getSubplotIds(e,"gl3d");e._paperdiv.style({width:e.width+"px",height:e.height+"px"}),t._context.setBackground(t,e.paper_bgcolor);for(var o=0;o<a.length;o++){var s=a[o],l=i.getSubplotData(r,"gl3d",s),u=e[s]._scene;void 0===u&&(u=new n({id:s,graphDiv:t,container:t.querySelector(".gl-container"),staticPlot:t._context.staticPlot,plotGlPixelRatio:t._context.plotGlPixelRatio},e),e[s]._scene=u),u.plot(l,e,t.layout)}},r.clean=function(t,e,r,n){for(var a=i.getSubplotIds(n,"gl3d"),o=0;o<a.length;o++){var s=a[o];!e[s]&&n[s]._scene&&n[s]._scene.destroy()}},r.cleanId=function(t){if(t.match(/^scene[0-9]*$/)){var e=t.substr(5);return"1"===e&&(e=""),"scene"+e}},r.setConvert=t("./set_convert"),r.initAxes=function(t){for(var e=t._fullLayout,r=i.getSubplotIds(e,"gl3d"),n=0;n<r.length;++n)for(var o=r[n],s=e[o],l=0;3>l;++l){var u=a[l],c=s[u];c._td=t}}},{"../plots":413,"./layout/attributes":401,"./layout/defaults":405,"./layout/layout_attributes":406,"./scene":410,"./set_convert":411}],401:[function(t,e,r){"use strict";e.exports={scene:{valType:"sceneid",dflt:"scene"}}},{}],402:[function(t,e,r){"use strict";var n=t("../../cartesian/layout_attributes"),i=t("../../../lib/extend").extendFlat;e.exports={showspikes:{valType:"boolean",dflt:!0},spikesides:{valType:"boolean",dflt:!0},spikethickness:{valType:"number",min:0,dflt:2},spikecolor:{valType:"color",dflt:"rgb(0,0,0)"},showbackground:{valType:"boolean",dflt:!1},backgroundcolor:{valType:"color",dflt:"rgba(204, 204, 204, 0.5)"},showaxeslabels:{valType:"boolean",dflt:!0},title:n.title,titlefont:n.titlefont,type:n.type,autorange:n.autorange,rangemode:n.rangemode,range:n.range,fixedrange:n.fixedrange,tickmode:n.tickmode,nticks:n.nticks,tick0:n.tick0,dtick:n.dtick,tickvals:n.tickvals,ticktext:n.ticktext,ticks:n.ticks,mirror:n.mirror,ticklen:n.ticklen,tickwidth:n.tickwidth,tickcolor:n.tickcolor,showticklabels:n.showticklabels,tickfont:n.tickfont,tickangle:n.tickangle,tickprefix:n.tickprefix,showtickprefix:n.showtickprefix,ticksuffix:n.ticksuffix,showticksuffix:n.showticksuffix,showexponent:n.showexponent,exponentformat:n.exponentformat,tickformat:n.tickformat,hoverformat:n.hoverformat,showline:n.showline,linecolor:n.linecolor,linewidth:n.linewidth,showgrid:n.showgrid,gridcolor:i({},n.gridcolor,{dflt:"rgb(204, 204, 204)"}),gridwidth:n.gridwidth,zeroline:n.zeroline,zerolinecolor:n.zerolinecolor,zerolinewidth:n.zerolinewidth}},{"../../../lib/extend":345,"../../cartesian/layout_attributes":376}],403:[function(t,e,r){"use strict";var n=t("../../../lib"),i=t("./axis_attributes"),a=t("../../cartesian/axis_defaults"),o=["xaxis","yaxis","zaxis"],s=function(){};e.exports=function(t,e,r){function l(t,e){return n.coerce(u,c,i,t,e)}for(var u,c,h=0;h<o.length;h++){var f=o[h];u=t[f]||{},c={_id:f[0]+r.scene,_name:f},e[f]=c=a(u,c,l,{font:r.font,letter:f[0],data:r.data,showGrid:!0}),l("gridcolor"),l("title",f[0]),c.setScale=s,l("showspikes")&&(l("spikesides"),l("spikethickness"),l("spikecolor")),l("showbackground")&&l("backgroundcolor"),l("showaxeslabels")}}},{"../../../lib":349,"../../cartesian/axis_defaults":370,"./axis_attributes":402}],404:[function(t,e,r){"use strict";function n(){this.bounds=[[-10,-10,-10],[10,10,10]],this.ticks=[[],[],[]],this.tickEnable=[!0,!0,!0],this.tickFont=["sans-serif","sans-serif","sans-serif"],this.tickSize=[12,12,12],this.tickAngle=[0,0,0],this.tickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.tickPad=[18,18,18],this.labels=["x","y","z"],this.labelEnable=[!0,!0,!0],this.labelFont=["Open Sans","Open Sans","Open Sans"],this.labelSize=[20,20,20],this.labelAngle=[0,0,0],this.labelColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.labelPad=[30,30,30],this.lineEnable=[!0,!0,!0],this.lineMirror=[!1,!1,!1],this.lineWidth=[1,1,1],this.lineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.lineTickEnable=[!0,!0,!0],this.lineTickMirror=[!1,!1,!1],this.lineTickLength=[10,10,10],this.lineTickWidth=[1,1,1],this.lineTickColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.gridEnable=[!0,!0,!0],this.gridWidth=[1,1,1],this.gridColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroEnable=[!0,!0,!0],this.zeroLineColor=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.zeroLineWidth=[2,2,2],this.backgroundEnable=[!0,!0,!0],this.backgroundColor=[[.8,.8,.8,.5],[.8,.8,.8,.5],[.8,.8,.8,.5]],this._defaultTickPad=l(this.tickPad),this._defaultLabelPad=l(this.labelPad),this._defaultLineTickLength=l(this.lineTickLength)}function i(t){var e=new n;return e.merge(t),e}var a=t("arraytools"),o=t("../../../lib/html2unicode"),s=t("../../../lib/str2rgbarray"),l=a.copy1D,u=["xaxis","yaxis","zaxis"],c=n.prototype;c.merge=function(t){for(var e=this,r=0;3>r;++r){var n=t[u[r]];e.labels[r]=o(n.title),"titlefont"in n&&(n.titlefont.color&&(e.labelColor[r]=s(n.titlefont.color)),n.titlefont.family&&(e.labelFont[r]=n.titlefont.family),n.titlefont.size&&(e.labelSize[r]=n.titlefont.size)),"showline"in n&&(e.lineEnable[r]=n.showline),"linecolor"in n&&(e.lineColor[r]=s(n.linecolor)),"linewidth"in n&&(e.lineWidth[r]=n.linewidth),"showgrid"in n&&(e.gridEnable[r]=n.showgrid),"gridcolor"in n&&(e.gridColor[r]=s(n.gridcolor)),"gridwidth"in n&&(e.gridWidth[r]=n.gridwidth),"log"===n.type?e.zeroEnable[r]=!1:"zeroline"in n&&(e.zeroEnable[r]=n.zeroline),"zerolinecolor"in n&&(e.zeroLineColor[r]=s(n.zerolinecolor)),"zerolinewidth"in n&&(e.zeroLineWidth[r]=n.zerolinewidth),"ticks"in n&&n.ticks?e.lineTickEnable[r]=!0:e.lineTickEnable[r]=!1,"ticklen"in n&&(e.lineTickLength[r]=e._defaultLineTickLength[r]=n.ticklen),"tickcolor"in n&&(e.lineTickColor[r]=s(n.tickcolor)),"tickwidth"in n&&(e.lineTickWidth[r]=n.tickwidth),"tickangle"in n&&(e.tickAngle[r]="auto"===n.tickangle?0:Math.PI*-n.tickangle/180),"showticklabels"in n&&(e.tickEnable[r]=n.showticklabels),"tickfont"in n&&(n.tickfont.color&&(e.tickColor[r]=s(n.tickfont.color)),n.tickfont.family&&(e.tickFont[r]=n.tickfont.family),n.tickfont.size&&(e.tickSize[r]=n.tickfont.size)),"mirror"in n?-1!==["ticks","all","allticks"].indexOf(n.mirror)?(e.lineTickMirror[r]=!0,e.lineMirror[r]=!0):n.mirror===!0?(e.lineTickMirror[r]=!1,e.lineMirror[r]=!0):(e.lineTickMirror[r]=!1,e.lineMirror[r]=!1):e.lineMirror[r]=!1,"showbackground"in n&&n.showbackground!==!1?(e.backgroundEnable[r]=!0,e.backgroundColor[r]=s(n.backgroundcolor)):e.backgroundEnable[r]=!1}},e.exports=i},{"../../../lib/html2unicode":348,"../../../lib/str2rgbarray":359,arraytools:48}],405:[function(t,e,r){"use strict";var n=t("../../../lib"),i=t("../../plots"),a=t("./layout_attributes"),o=t("./axis_defaults");e.exports=function(t,e,r){function s(t,e){return n.coerce(u,c,a,t,e)}function l(r){var n=!(e._hasCartesian||e._hasGeo||e._hasGL2D||e._hasPie),i=-1!==a[r].values.indexOf(t[r]);return n&&i?t[r]:void 0}if(e._hasGL3D)for(var u,c,h=i.findSubplotIds(r,"gl3d"),f=h.length,d=0;f>d;d++){var p=h[d];t[p]?u=t[p]:t[p]=u={},c=e[p]||{},s("bgcolor");for(var g=Object.keys(a.camera),v=0;v<g.length;v++)s("camera."+g[v]+".x"),s("camera."+g[v]+".y"),s("camera."+g[v]+".z");s("domain.x",[d/f,(d+1)/f]),s("domain.y");var m=!!s("aspectratio.x")&&!!s("aspectratio.y")&&!!s("aspectratio.z"),y=m?"manual":"auto",b=s("aspectmode",y);m||(u.aspectratio=c.aspectratio={x:1,y:1,z:1},"manual"===b&&(c.aspectmode="auto")),o(u,c,{font:e.font,scene:p,data:r}),s("dragmode",l("dragmode")),s("hovermode",l("hovermode")),e[p]=c}}},{"../../../lib":349,"../../plots":413,"./axis_defaults":403,"./layout_attributes":406}],406:[function(t,e,r){"use strict";function n(t,e,r){return{x:{valType:"number",dflt:t},y:{valType:"number",dflt:e},z:{valType:"number",dflt:r}}}var i=t("./axis_attributes"),a=t("../../../lib/extend").extendFlat;e.exports={bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)"},camera:{up:a(n(0,0,1),{}),center:a(n(0,0,0),{}),eye:a(n(1.25,1.25,1.25),{})},domain:{x:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]},y:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]}},aspectmode:{valType:"enumerated",values:["auto","cube","data","manual"],dflt:"auto"},aspectratio:{x:{valType:"number",min:0},y:{valType:"number",min:0},z:{valType:"number",min:0}},xaxis:i,yaxis:i,zaxis:i,dragmode:{valType:"enumerated",values:["orbit","turntable","zoom","pan"],dflt:"turntable"},hovermode:{valType:"enumerated",values:["closest",!1],dflt:"closest"},_deprecated:{cameraposition:{valType:"info_array"}}}},{"../../../lib/extend":345,"./axis_attributes":402}],407:[function(t,e,r){"use strict";function n(){this.enabled=[!0,!0,!0],this.colors=[[0,0,0,1],[0,0,0,1],[0,0,0,1]],this.drawSides=[!0,!0,!0],this.lineWidth=[1,1,1]}function i(t){var e=new n;return e.merge(t),e}var a=t("../../../lib/str2rgbarray"),o=["xaxis","yaxis","zaxis"],s=n.prototype;s.merge=function(t){for(var e=0;3>e;++e){var r=t[o[e]];this.enabled[e]=r.showspikes,this.colors[e]=a(r.spikecolor),this.drawSides[e]=r.spikesides,this.lineWidth[e]=r.spikethickness}},e.exports=i},{"../../../lib/str2rgbarray":359}],408:[function(t,e,r){"use strict";function n(t){for(var e=new Array(3),r=0;3>r;++r){for(var n=t[r],i=new Array(n.length),a=0;a<n.length;++a)i[a]=n[a].x;e[r]=i}return e}function i(t){for(var e=t.axesOptions,r=t.glplot.axesPixels,i=t.fullSceneLayout,u=[[],[],[]],c=0;3>c;++c){var h=i[s[c]];if(h._length=(r[c].hi-r[c].lo)*r[c].pixelsPerDataUnit/t.dataScale[c],Math.abs(h._length)===1/0)u[c]=[];else{h.range[0]=r[c].lo/t.dataScale[c],h.range[1]=r[c].hi/t.dataScale[c],h._m=1/(t.dataScale[c]*r[c].pixelsPerDataUnit),h.range[0]===h.range[1]&&(h.range[0]-=1,h.range[1]+=1);var f=h.tickmode;if("auto"===h.tickmode){h.tickmode="linear";var d=h.nticks||a.Lib.constrain(h._length/40,4,9);a.Axes.autoTicks(h,Math.abs(h.range[1]-h.range[0])/d)}for(var p=a.Axes.calcTicks(h),g=0;g<p.length;++g)p[g].x=p[g].x*t.dataScale[c],p[g].text=o(p[g].text);u[c]=p,h.tickmode=f}}e.ticks=u;for(var c=0;3>c;++c){l[c]=.5*(t.glplot.bounds[0][c]+t.glplot.bounds[1][c]);for(var g=0;2>g;++g)e.bounds[g][c]=t.glplot.bounds[g][c]}t.contourLevels=n(u)}e.exports=i;var a=t("../../../plotly"),o=t("../../../lib/html2unicode"),s=["xaxis","yaxis","zaxis"],l=[0,0,0]},{"../../../lib/html2unicode":348,"../../../plotly":366}],409:[function(t,e,r){"use strict";function n(t,e){var r,n,i=[0,0,0,0];for(r=0;4>r;++r)for(n=0;4>n;++n)i[n]+=t[4*r+n]*e[r];return i}function i(t,e){var r=n(t.projection,n(t.view,n(t.model,[e[0],e[1],e[2],1])));return r}e.exports=i},{}],410:[function(t,e,r){"use strict";function n(t){function e(e,r){if("string"==typeof r)return r;var n=t.fullSceneLayout[e];return d.tickText(n,n.c2l(r),"hover").text}var r=t.svgContainer,n=t.container.getBoundingClientRect(),i=n.width,a=n.height;r.setAttributeNS(null,"viewBox","0 0 "+i+" "+a),r.setAttributeNS(null,"width",i),r.setAttributeNS(null,"height",a),w(t),t.glplot.axes.update(t.axesOptions);for(var o=Object.keys(t.traces),s=null,l=t.glplot.selection,u=0;u<o.length;++u){var c=t.traces[o[u]];c.handlePick(l)&&(s=c),c.setContourLevels&&c.setContourLevels()}var h;if(null!==s){var f=y(t.glplot.cameraParams,l.dataCoordinate),c=s.data,g=c.hoverinfo,v=e("xaxis",l.traceCoordinate[0]),m=e("yaxis",l.traceCoordinate[1]),b=e("zaxis",l.traceCoordinate[2]);if("all"!==g){var x=g.split("+");-1===x.indexOf("x")&&(v=void 0),-1===x.indexOf("y")&&(m=void 0),-1===x.indexOf("z")&&(b=void 0),-1===x.indexOf("text")&&(l.textLabel=void 0),-1===x.indexOf("name")&&(s.name=void 0)}t.fullSceneLayout.hovermode&&p.loneHover({x:(.5+.5*f[0]/f[3])*i,y:(.5-.5*f[1]/f[3])*a,xLabel:v,yLabel:m,zLabel:b,text:l.textLabel,name:s.name,color:s.color},{container:r});var _={points:[{x:v,y:m,z:b,data:c._input,fullData:c,curveNumber:c.index,pointNumber:l.data.index}]};l.buttons&&l.distance<5?t.graphDiv.emit("plotly_click",_):t.graphDiv.emit("plotly_hover",_),h=_}else p.loneUnhover(r),t.graphDiv.emit("plotly_unhover",h)}function i(t,e,r,i){var a={canvas:r,gl:i,container:t.container,axes:t.axesOptions,spikes:t.spikeOptions,pickRadius:10,snapToData:!0,autoScale:!0,autoBounds:!1};if(t.staticMode){if(!u){l=document.createElement("canvas");try{u=l.getContext("webgl",{preserveDrawingBuffer:!0,premultipliedAlpha:!0})}catch(o){throw new Error("error creating static canvas/context for image server")}}a.pixelRatio=t.pixelRatio,a.gl=u,a.canvas=l}try{t.glplot=c(a)}catch(o){v(t)}if(t.staticMode||t.glplot.canvas.addEventListener("webglcontextlost",function(t){console.log("lost context"),t.preventDefault()}),!t.camera){var s=t.fullSceneLayout.camera;t.camera=m(t.container,{center:[s.center.x,s.center.y,s.center.z],eye:[s.eye.x,s.eye.y,s.eye.z],up:[s.up.x,s.up.y,s.up.z],zoomMin:.1,zoomMax:100,mode:"orbit"})}return t.glplot.mouseListener.enabled=!1,t.glplot.camera=t.camera,t.glplot.oncontextloss=function(){t.recoverContext()},t.glplot.onrender=n.bind(null,t),t.traces={},!0}function a(t,e){var r=document.createElement("div"),n=t.container;this.graphDiv=t.graphDiv;var a=document.createElementNS("http://www.w3.org/2000/svg","svg");a.style.position="absolute",a.style.top=a.style.left="0px",a.style.width=a.style.height="100%",a.style["z-index"]=20,a.style["pointer-events"]="none",r.appendChild(a),this.svgContainer=a,r.id=t.id,r.style.position="absolute",r.style.top=r.style.left="0px",r.style.width=r.style.height="100%",n.appendChild(r),this.fullLayout=e,this.id=t.id||"scene",this.fullSceneLayout=e[this.id],this.plotArgs=[[],{},{}],this.axesOptions=x(e[this.id]),this.spikeOptions=_(e[this.id]),this.container=r,this.staticMode=!!t.staticPlot,
+this.pixelRatio=t.plotGlPixelRatio||2,this.dataScale=[1,1,1],this.contourLevels=[[],[],[]],!i(this,e)}function o(t,e,r,n){for(var i=0;i<e.length;++i)if(Array.isArray(e[i]))for(var a=0;a<e[i].length;++a){var o=t.d2l(e[i][a]);!isNaN(o)&&isFinite(o)&&(n[0][r]=Math.min(n[0][r],o),n[1][r]=Math.max(n[1][r],o))}else{var o=t.d2l(e[i]);!isNaN(o)&&isFinite(o)&&(n[0][r]=Math.min(n[0][r],o),n[1][r]=Math.max(n[1][r],o))}}function s(t,e,r){var n=t.fullSceneLayout;o(n.xaxis,e.x,0,r),o(n.yaxis,e.y,1,r),o(n.zaxis,e.z,2,r)}var l,u,c=t("gl-plot3d"),h=t("../../lib"),f=t("../../plots/plots"),d=t("../../plots/cartesian/axes"),p=t("../../plots/cartesian/graph_interact"),g=t("../../lib/str2rgbarray"),v=t("../../lib/show_no_webgl_msg"),m=t("./camera"),y=t("./project"),b=t("./set_convert"),x=t("./layout/convert"),_=t("./layout/spikes"),w=t("./layout/tick_marks"),A=a.prototype;A.recoverContext=function(){function t(){return r.isContextLost()?void requestAnimationFrame(t):i(e,e.fullLayout,n,r)?void e.plot.apply(e,e.plotArgs):void console.error("catastrophic/unrecoverable webgl error.  context lost.")}var e=this,r=this.glplot.gl,n=this.glplot.canvas;this.glplot.dispose(),requestAnimationFrame(t)};var k=["xaxis","yaxis","zaxis"];A.plot=function(t,e,r){if(this.plotArgs=[t,e,r],!this.glplot.contextLost){var n,i,a,o,l=e[this.id],u=r[this.id];for(l.bgcolor?this.glplot.clearColor=g(l.bgcolor):this.glplot.clearColor=[0,0,0,0],this.glplot.snapToData=!0,this.fullSceneLayout=l,this.glplotLayout=l,this.axesOptions.merge(l),this.spikeOptions.merge(l),this.updateFx(l.dragmode,l.hovermode),this.glplot.update({}),a=0;3>a;++a){var c=l[k[a]];b(c)}t?Array.isArray(t)||(t=[t]):t=[];for(var h=[[1/0,1/0,1/0],[-(1/0),-(1/0),-(1/0)]],a=0;a<t.length;++a){var n=t[a];n.visible===!0&&s(this,n,h)}for(var d=[1,1,1],o=0;3>o;++o)h[0][o]>h[1][o]?d[o]=1:h[1][o]===h[0][o]?d[o]=1:d[o]=1/(h[1][o]-h[0][o]);this.dataScale=d;for(var a=0;a<t.length;++a)if(n=t[a],n.visible===!0){if(i=this.traces[n.uid])i.update(n);else{var p=f.getModule(n.type);i=p.plot(this,n),this.traces[n.uid]=i}i.name=n.name}var v=Object.keys(this.traces);t:for(a=0;a<v.length;++a){for(o=0;o<t.length;++o)if(t[o].uid===v[a]&&t[o].visible===!0)continue t;i=this.traces[v[a]],i.dispose(),delete this.traces[v[a]]}var m=[[0,0,0],[0,0,0]],y=[],x={};for(a=0;3>a;++a){var c=l[k[a]],_=c.type;if(_ in x?(x[_].acc*=d[a],x[_].count+=1):x[_]={acc:d[a],count:1},c.autorange){for(m[0][a]=1/0,m[1][a]=-(1/0),o=0;o<this.glplot.objects.length;++o){var w=this.glplot.objects[o].bounds;m[0][a]=Math.min(m[0][a],w[0][a]/d[a]),m[1][a]=Math.max(m[1][a],w[1][a]/d[a])}if("rangemode"in c&&"tozero"===c.rangemode&&(m[0][a]=Math.min(m[0][a],0),m[1][a]=Math.max(m[1][a],0)),m[0][a]>m[1][a])m[0][a]=-1,m[1][a]=1;else{var A=m[1][a]-m[0][a];m[0][a]-=A/32,m[1][a]+=A/32}}else{var M=l[k[a]].range;m[0][a]=M[0],m[1][a]=M[1]}m[0][a]===m[1][a]&&(m[0][a]-=1,m[1][a]+=1),y[a]=m[1][a]-m[0][a],this.glplot.bounds[0][a]=m[0][a]*d[a],this.glplot.bounds[1][a]=m[1][a]*d[a]}for(var T=[1,1,1],a=0;3>a;++a){var c=l[k[a]],_=c.type,E=x[_];T[a]=Math.pow(E.acc,1/E.count)/d[a]}var L,S=4;if("auto"===l.aspectmode)L=Math.max.apply(null,T)/Math.min.apply(null,T)<=S?T:[1,1,1];else if("cube"===l.aspectmode)L=[1,1,1];else if("data"===l.aspectmode)L=T;else{if("manual"!==l.aspectmode)throw new Error("scene.js aspectRatio was not one of the enumerated types");var C=l.aspectratio;L=[C.x,C.y,C.z]}l.aspectratio.x=u.aspectratio.x=L[0],l.aspectratio.y=u.aspectratio.y=L[1],l.aspectratio.z=u.aspectratio.z=L[2],this.glplot.aspect=L;var P=l.domain||null,z=e._size||null;if(P&&z){var R=this.container.style;R.position="absolute",R.left=z.l+P.x[0]*z.w+"px",R.top=z.t+(1-P.y[1])*z.h+"px",R.width=z.w*(P.x[1]-P.x[0])+"px",R.height=z.h*(P.y[1]-P.y[0])+"px"}}},A.destroy=function(){this.glplot.dispose(),this.container.parentNode.removeChild(this.container),this.glplot=null},A.setCameraToDefault=function(){this.glplot.camera.lookAt([1.25,1.25,1.25],[0,0,0],[0,0,1])},A.getCamera=function(){this.glplot.camera.view.recalcMatrix(this.camera.view.lastT());var t=this.glplot.camera.up,e=this.glplot.camera.center,r=this.glplot.camera.eye;return{up:{x:t[0],y:t[1],z:t[2]},center:{x:e[0],y:e[1],z:e[2]},eye:{x:r[0],y:r[1],z:r[2]}}},A.setCamera=function(t){var e=t.up,r=t.center,n=t.eye;this.glplot.camera.lookAt([n.x,n.y,n.z],[r.x,r.y,r.z],[e.x,e.y,e.z])},A.saveCamera=function(t){function e(t,e,r,n){var i=["up","center","eye"],a=["x","y","z"];return t[i[r]][a[n]]===e[i[r]][a[n]]}var r=this.getCamera(),n=h.nestedProperty(t,this.id+".camera"),i=n.get(),a=!1;if(void 0===i)a=!0;else for(var o=0;3>o;o++)for(var s=0;3>s;s++)if(!e(r,i,o,s)){a=!0;break}return a&&n.set(r),a},A.updateFx=function(t,e){var r=this.camera;r&&("orbit"===t?(r.mode="orbit",r.keyBindingMode="rotate"):"turntable"===t?(r.up=[0,0,1],r.mode="turntable",r.keyBindingMode="rotate"):r.keyBindingMode=t),this.fullSceneLayout.hovermode=e},A.toImage=function(t){t||(t="png"),this.staticMode&&this.container.appendChild(l),this.glplot.redraw();var e=this.glplot.gl,r=e.drawingBufferWidth,n=e.drawingBufferHeight;e.bindFramebuffer(e.FRAMEBUFFER,null);var i=new Uint8Array(r*n*4);e.readPixels(0,0,r,n,e.RGBA,e.UNSIGNED_BYTE,i);for(var a=0,o=n-1;o>a;++a,--o)for(var s=0;r>s;++s)for(var u=0;4>u;++u){var c=i[4*(r*a+s)+u];i[4*(r*a+s)+u]=i[4*(r*o+s)+u],i[4*(r*o+s)+u]=c}var h=document.createElement("canvas");h.width=r,h.height=n;var f=h.getContext("2d"),d=f.createImageData(r,n);d.data.set(i),f.putImageData(d,0,0);var p;switch(t){case"jpeg":p=h.toDataURL("image/jpeg");break;case"webp":p=h.toDataURL("image/webp");break;default:p=h.toDataURL("image/png")}return this.staticMode&&this.container.removeChild(l),p},e.exports=a},{"../../lib":349,"../../lib/show_no_webgl_msg":357,"../../lib/str2rgbarray":359,"../../plots/cartesian/axes":369,"../../plots/cartesian/graph_interact":374,"../../plots/plots":413,"./camera":399,"./layout/convert":404,"./layout/spikes":407,"./layout/tick_marks":408,"./project":409,"./set_convert":411,"gl-plot3d":140}],411:[function(t,e,r){"use strict";var n=t("../cartesian/axes"),i=function(){};e.exports=function(t){n.setConvert(t),t.setScale=i}},{"../cartesian/axes":369}],412:[function(t,e,r){"use strict";var n=t("../plotly"),i=t("./font_attributes"),a=t("../components/color/attributes"),o=n.Lib.extendFlat;e.exports={font:{family:o({},i.family,{dflt:'"Open Sans", verdana, arial, sans-serif'}),size:o({},i.size,{dflt:12}),color:o({},i.color,{dflt:a.defaultLine})},title:{valType:"string",dflt:"Click to enter Plot title"},titlefont:o({},i,{}),autosize:{valType:"enumerated",values:[!0,!1,"initial"]},width:{valType:"number",min:10,dflt:700},height:{valType:"number",min:10,dflt:450},margin:{l:{valType:"number",min:0,dflt:80},r:{valType:"number",min:0,dflt:80},t:{valType:"number",min:0,dflt:100},b:{valType:"number",min:0,dflt:80},pad:{valType:"number",min:0,dflt:0},autoexpand:{valType:"boolean",dflt:!0}},paper_bgcolor:{valType:"color",dflt:a.background},plot_bgcolor:{valType:"color",dflt:a.background},separators:{valType:"string",dflt:".,"},hidesources:{valType:"boolean",dflt:!1},smith:{valType:"enumerated",values:[!1],dflt:!1},showlegend:{valType:"boolean"},_hasCartesian:{valType:"boolean",dflt:!1},_hasGL3D:{valType:"boolean",dflt:!1},_hasGeo:{valType:"boolean",dflt:!1},_hasPie:{valType:"boolean",dflt:!1},_hasGL2D:{valType:"boolean",dflt:!1},_composedModules:{"*":"Fx"},_nestedModules:{xaxis:"Axes",yaxis:"Axes",scene:"gl3d",geo:"geo",legend:"Legend",annotations:"Annotations",shapes:"Shapes"}}},{"../components/color/attributes":298,"../plotly":366,"./font_attributes":383}],413:[function(t,e,r){"use strict";function n(t){return"object"==typeof t&&(t=t.type),t}function i(t,e){e.text("");var r=e.append("a").attr({"xlink:xlink:href":"#","class":"link--impt link--embedview","font-weight":"bold"}).text(t._context.linkText+" "+String.fromCharCode(187));if(t._context.sendData)r.on("click",function(){h.sendDataToCloud(t)});else{var n=window.location.pathname.split("/"),i=window.location.search;r.attr({"xlink:xlink:show":"new","xlink:xlink:href":"/"+n[2].split(".")[0]+"/"+n[1]+i})}}function a(t,e,r,n){var i,a,o=Object.keys(g);for(i=0;i<o.length;i++){var s=g[o[i]];s.clean&&s.clean(t,e,r,n)}var l=!!n._paper,u=!!n._infolayer;t:for(i=0;i<r.length;i++){var c=r[i],h=c.uid;for(a=0;a<t.length;a++){var f=t[a];if(h===f.uid)continue t}l&&n._paper.selectAll(".hm"+h+",.contour"+h+",#clip"+h).remove(),u&&n._infolayer.selectAll(".cb"+h).remove()}}function o(t,e){for(var r,n=Object.keys(e),i=0;i<n.length;++i){var a=n[i];if("_"===a.charAt(0)||"function"==typeof e[a]){if(a in t)continue;t[a]=e[a]}else if(Array.isArray(e[a])&&Array.isArray(t[a])&&e[a].length&&c.isPlainObject(e[a][0])){if(e[a].length!==t[a].length)throw new Error("relinkPrivateKeys needs equal length arrays");for(r=0;r<e[a].length;r++)o(t[a][r],e[a][r])}else c.isPlainObject(e[a])&&c.isPlainObject(t[a])&&(o(t[a],e[a]),Object.keys(t[a]).length||delete t[a])}}var s=t("../plotly"),l=t("d3"),u=t("fast-isnumeric"),c=t("../lib"),h=e.exports={},f=h.modules={},d=h.allTypes=[],p=h.allCategories={},g=h.subplotsRegistry={};h.attributes=t("./attributes"),h.attributes.type.values=d,h.fontAttrs=t("./font_attributes"),h.layoutAttributes=t("./layout_attributes"),h.fontWeight="normal",h.register=function(t,e,r,n){if(f[e])return void console.log("type "+e+" already registered");for(var i={},a=0;a<r.length;a++)i[r[a]]=!0,p[r[a]]=!0;f[e]={_module:t,categories:i},n&&Object.keys(n).length&&(f[e].meta=n),d.push(e)},h.getModule=function(t){if(void 0!==t.r)return console.log("Oops, tried to put a polar trace on an incompatible graph of cartesian data. Ignoring this dataset.",t),!1;var e=f[n(t)];return e?e._module:!1},h.traceIs=function(t,e){if(t=n(t),"various"===t)return!1;var r=f[t];return r||(void 0!==t&&console.warn("unrecognized trace type "+t),r=f[h.attributes.type.dflt]),!!r.categories[e]},h.registerSubplot=function(t){var e=t.name;return g[e]?void console.log("plot type "+e+" already registered"):void(g[e]=t)},h.findSubplotIds=function(t,e){var r=[];if(void 0===h.subplotsRegistry[e])return r;for(var n=h.subplotsRegistry[e].attr,i=0;i<t.length;i++){var a=t[i];h.traceIs(a,e)&&-1===r.indexOf(a[n])&&r.push(a[n])}return r},h.getSubplotIds=function(t,e){var r=h.subplotsRegistry[e];if(void 0===r)return[];if("cartesian"===e&&!t._hasCartesian)return[];if("gl2d"===e&&!t._hasGL2D)return[];if("cartesian"===e||"gl2d"===e)return Object.keys(t._plots);for(var n=r.idRegex,i=Object.keys(t),a=[],o=0;o<i.length;o++){var s=i[o];n.test(s)&&a.push(s)}var l=r.idRoot.length;return a.sort(function(t,e){var r=+(t.substr(l)||1),n=+(e.substr(l)||1);return r-n}),a},h.getSubplotData=function(t,e,r){if(void 0===h.subplotsRegistry[e])return[];for(var n,i=h.subplotsRegistry[e].attr,a=[],o=0;o<t.length;o++)if(n=t[o],"gl2d"===e&&h.traceIs(n,"gl2d")){var l=s.Axes.subplotMatch,u="x"+r.match(l)[1],c="y"+r.match(l)[2];n[i[0]]===u&&n[i[1]]===c&&a.push(n)}else n[i]===r&&a.push(n);return a},h.redrawText=function(t){return t._fullLayout._hasGL3D||t.data&&t.data[0]&&t.data[0].r?void 0:new Promise(function(e){setTimeout(function(){s.Annotations.drawAll(t),s.Legend.draw(t),(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()}),e(h.previousPromises(t))},300)})},h.resize=function(t){return new Promise(function(e,r){t&&"none"!==l.select(t).style("display")||r(new Error("Resize must be passed a plot div element.")),t._redrawTimer&&clearTimeout(t._redrawTimer),t._redrawTimer=setTimeout(function(){if((t._fullLayout||{}).autosize){var r=t.changed;t.autoplay=!0,s.relayout(t,{autosize:!0}),t.changed=r,e(t)}},100)})},h.previousPromises=function(t){return(t._promises||[]).length?Promise.all(t._promises).then(function(){t._promises=[]}):void 0},h.addLinks=function(t){var e=t._fullLayout,r=e._paper.selectAll("text.js-plot-link-container").data([0]);r.enter().append("text").classed("js-plot-link-container",!0).style({"font-family":'"Open Sans", Arial, sans-serif',"font-size":"12px",fill:s.Color.defaultLine,"pointer-events":"all"}).each(function(){var t=l.select(this);t.append("tspan").classed("js-link-to-tool",!0),t.append("tspan").classed("js-link-spacer",!0),t.append("tspan").classed("js-sourcelinks",!0)});var n=r.node(),a={y:e._paper.attr("height")-9};n&&n.getComputedTextLength()>=e.width-20?(a["text-anchor"]="start",a.x=5):(a["text-anchor"]="end",a.x=e._paper.attr("width")-7),r.attr(a);var o=r.select(".js-link-to-tool"),u=r.select(".js-link-spacer"),c=r.select(".js-sourcelinks");t._context.showSources&&t._context.showSources(t),t._context.showLink&&i(t,o),u.text(o.text()&&c.text()?" - ":"")},h.sendDataToCloud=function(t){t.emit("plotly_beforeexport");var e=window.PLOTLYENV&&window.PLOTLYENV.BASE_URL||"https://plot.ly",r=l.select(t).append("div").attr("id","hiddenform").style("display","none"),n=r.append("form").attr({action:e+"/external",method:"post",target:"_blank"}),i=n.append("input").attr({type:"text",name:"data"});return i.node().value=h.graphJson(t,!1,"keepdata"),n.node().submit(),r.remove(),t.emit("plotly_afterexport"),!1},h.supplyDefaults=function(t){var e,r,n,i,l,u,c=t._fullLayout||{},f=t._fullLayout={},d=t.layout||{},p=t._fullData||[],g=t._fullData=[],v=t.data||[],m=t._modules=[];for(h.supplyLayoutGlobalDefaults(d,f),f._dataLength=v.length,e=0;e<v.length;e++)r=v[e],n=h.supplyDataDefaults(r,e,f),g.push(n),h.traceIs(n,"cartesian")?f._hasCartesian=!0:h.traceIs(n,"gl3d")?f._hasGL3D=!0:h.traceIs(n,"geo")?f._hasGeo=!0:h.traceIs(n,"pie")?f._hasPie=!0:h.traceIs(n,"gl2d")?f._hasGL2D=!0:"r"in n&&(f._hasPolar=!0),i=n._module,i&&-1===m.indexOf(i)&&m.push(i);for(e=0;e<m.length;e++)i=m[e],i.cleanData&&i.cleanData(g);if(p.length===v.length)for(e=0;e<g.length;e++)o(g[e],p[e]);for(h.supplyLayoutModuleDefaults(d,f,g),a(g,f,p,c),o(f,c),h.doAutoMargin(t),l=s.Axes.list(t),e=0;e<l.length;e++)u=l[e],u._td=t,u.setScale();if((t.calcdata||[]).length===g.length)for(e=0;e<g.length;e++)r=g[e],(t.calcdata[e][0]||{}).trace=r},h.supplyDataDefaults=function(t,e,r){function n(e,r){return c.coerce(t,a,h.attributes,e,r)}function i(e,r){return h.traceIs(a,e)?c.coerce(t,a,h.subplotsRegistry[e].attributes,r):void 0}var a={},o=s.Color.defaults[e%s.Color.defaults.length];a.index=e;var l,u,f=n("visible");return n("type"),n("uid"),i("gl3d","scene"),i("geo","geo"),(f||l)&&(u=h.getModule(a),a._module=u),f&&n("hoverinfo",1===r._dataLength?"x+y+z+text":void 0),u&&f&&u.supplyDefaults(t,a,o,r),f&&(n("name","trace "+e),h.traceIs(a,"noOpacity")||n("opacity"),i("cartesian","xaxis"),i("cartesian","yaxis"),i("gl2d","xaxis"),i("gl2d","yaxis"),h.traceIs(a,"showLegend")&&(n("showlegend"),n("legendgroup"))),a._input=t,a},h.supplyLayoutGlobalDefaults=function(t,e){function r(r,n){return c.coerce(t,e,h.layoutAttributes,r,n)}var n=c.coerceFont(r,"font");r("title"),c.coerceFont(r,"titlefont",{family:n.family,size:Math.round(1.4*n.size),color:n.color});var i=r("autosize",t.width&&t.height?!1:"initial");r("width"),r("height"),r("margin.l"),r("margin.r"),r("margin.t"),r("margin.b"),r("margin.pad"),r("margin.autoexpand"),"initial"!==i&&h.sanitizeMargins(e),r("paper_bgcolor"),r("separators"),r("hidesources"),r("smith"),r("_hasCartesian"),r("_hasGL3D"),r("_hasGeo"),r("_hasPie"),r("_hasGL2D")},h.supplyLayoutModuleDefaults=function(t,e,r){var n,i;s.Axes.supplyLayoutDefaults(t,e,r);var a=Object.keys(g);for(n=0;n<a.length;n++)i=g[a[n]],i.supplyLayoutDefaults&&i.supplyLayoutDefaults(t,e,r);var o=Object.keys(f);for(n=0;n<o.length;n++)i=f[d[n]]._module,i.supplyLayoutDefaults&&i.supplyLayoutDefaults(t,e,r);var l=["Fx","Annotations","Shapes","Legend"];for(n=0;n<l.length;n++)i=l[n],s[i]&&s[i].supplyLayoutDefaults(t,e,r)},h.purge=function(t){var e=t._fullLayout||{};void 0!==e._glcontainer&&e._glcontainer.remove(),void 0!==e._geocontainer&&e._geocontainer.remove(),e._modeBar&&e._modeBar.destroy(),delete t.data,delete t.layout,delete t._fullData,delete t._fullLayout,delete t.calcdata,delete t.framework,delete t.empty,delete t.fid,delete t.undoqueue,delete t.undonum,delete t.autoplay,delete t.changed,delete t._modules,delete t._tester,delete t._testref,delete t._promises,delete t._redrawTimer,delete t._replotting,delete t.firstscatter,delete t.hmlumcount,delete t.hmpixcount,delete t.numboxes,delete t._hoverTimer,delete t._lastHoverTime,t.removeAllListeners&&t.removeAllListeners()},h.style=function(t){for(var e=t._modules.concat(s.ErrorBars),r=0;r<e.length;r++){var n=e[r];n.style&&n.style(t)}},h.sanitizeMargins=function(t){if(t&&t.margin){var e,r=t.width,n=t.height,i=t.margin,a=r-(i.l+i.r),o=n-(i.t+i.b);0>a&&(e=(r-1)/(i.l+i.r),i.l=Math.floor(e*i.l),i.r=Math.floor(e*i.r)),0>o&&(e=(n-1)/(i.t+i.b),i.t=Math.floor(e*i.t),i.b=Math.floor(e*i.b))}},h.autoMargin=function(t,e,r){var n=t._fullLayout;if(n._pushmargin||(n._pushmargin={}),n.margin.autoexpand!==!1){if(r){var i=r.pad||12;r.l+r.r>.5*n.width&&(r.l=r.r=0),r.b+r.t>.5*n.height&&(r.b=r.t=0),n._pushmargin[e]={l:{val:r.x,size:r.l+i},r:{val:r.x,size:r.r+i},b:{val:r.y,size:r.b+i},t:{val:r.y,size:r.t+i}}}else delete n._pushmargin[e];t._replotting||h.doAutoMargin(t)}},h.doAutoMargin=function(t){var e=t._fullLayout;e._size||(e._size={}),e._pushmargin||(e._pushmargin={});var r=e._size,n=JSON.stringify(r),i=Math.max(e.margin.l||0,0),a=Math.max(e.margin.r||0,0),o=Math.max(e.margin.t||0,0),l=Math.max(e.margin.b||0,0),c=e._pushmargin;return e.margin.autoexpand!==!1&&(c.base={l:{val:0,size:i},r:{val:1,size:a},t:{val:1,size:o},b:{val:0,size:l}},Object.keys(c).forEach(function(t){var r=c[t].l||{},n=c[t].b||{},s=r.val,h=r.size,f=n.val,d=n.size;Object.keys(c).forEach(function(t){if(u(h)&&c[t].r){var r=c[t].r.val,n=c[t].r.size;if(r>s){var p=(h*r+(n-e.width)*s)/(r-s),g=(n*(1-s)+(h-e.width)*(1-r))/(r-s);p>=0&&g>=0&&p+g>i+a&&(i=p,a=g)}}if(u(d)&&c[t].t){var v=c[t].t.val,m=c[t].t.size;if(v>f){var y=(d*v+(m-e.height)*f)/(v-f),b=(m*(1-f)+(d-e.height)*(1-v))/(v-f);y>=0&&b>=0&&y+b>l+o&&(l=y,o=b)}}})})),r.l=Math.round(i),r.r=Math.round(a),r.t=Math.round(o),r.b=Math.round(l),r.p=Math.round(e.margin.pad),r.w=Math.round(e.width)-r.l-r.r,r.h=Math.round(e.height)-r.t-r.b,t._replotting||"{}"===n||n===JSON.stringify(e._size)?void 0:s.plot(t)},h.graphJson=function(t,e,r,n,i){function a(t){if("function"==typeof t)return null;if(c.isPlainObject(t)){var e,n,i={};for(e in t)if("function"!=typeof t[e]&&-1===["_","["].indexOf(e.charAt(0))){if("keepdata"===r){if("src"===e.substr(e.length-3))continue}else if("keepstream"===r){if(n=t[e+"src"],"string"==typeof n&&n.indexOf(":")>0&&!c.isPlainObject(t.stream))continue}else if("keepall"!==r&&(n=t[e+"src"],"string"==typeof n&&n.indexOf(":")>0))continue;i[e]=a(t[e])}return i}return Array.isArray(t)?t.map(a):t&&t.getTime?c.ms2DateTime(t):t}(i&&e&&!t._fullData||i&&!e&&!t._fullLayout)&&h.supplyDefaults(t);var o=i?t._fullData:t.data,s=i?t._fullLayout:t.layout,l={data:(o||[]).map(function(t){var r=a(t);return e&&delete r.fit,r})};return e||(l.layout=a(s)),t.framework&&t.framework.isPolar&&(l=t.framework.getConfig()),"object"===n?l:JSON.stringify(l)}},{"../lib":349,"../plotly":366,"./attributes":367,"./font_attributes":383,"./layout_attributes":412,d3:70,"fast-isnumeric":74}],414:[function(t,e,r){"use strict";var n=t("../../traces/scatter/attributes"),i=n.marker;e.exports={r:n.r,t:n.t,marker:{color:i.color,size:i.size,symbol:i.symbol,opacity:i.opacity}}},{"../../traces/scatter/attributes":502}],415:[function(t,e,r){"use strict";function n(t,e){var r={showline:{valType:"boolean"},showticklabels:{valType:"boolean"},tickorientation:{valType:"enumerated",values:["horizontal","vertical"]},ticklen:{valType:"number",min:0},tickcolor:{valType:"color"},ticksuffix:{valType:"string"},endpadding:{valType:"number"},visible:{valType:"boolean"}};return a({},e,r)}var i=t("../cartesian/layout_attributes"),a=t("../../lib/extend").extendFlat,o=a({},i.domain,{});e.exports={radialaxis:n("radial",{range:{valType:"info_array",items:[{valType:"number"},{valType:"number"}]},domain:o,orientation:{valType:"number"}}),angularaxis:n("angular",{range:{valType:"info_array",items:[{valType:"number",dflt:0},{valType:"number",dflt:360}]},domain:o}),layout:{direction:{valType:"enumerated",values:["clockwise","counterclockwise"]},orientation:{valType:"angle"}}}},{"../../lib/extend":345,"../cartesian/layout_attributes":376}],416:[function(t,e,r){var n=t("../../plotly"),i=t("d3"),a=e.exports={version:"0.2.2",manager:t("./micropolar_manager")},o=n.Lib.extendDeepAll;a.Axis=function(){function t(t){r=t||r;var u=l.data,h=l.layout;return("string"==typeof r||r.nodeName)&&(r=i.select(r)),r.datum(u).each(function(t,r){function l(t,e){return s(t)%360+h.orientation}var u=t.slice();c={data:a.util.cloneJson(u),layout:a.util.cloneJson(h)};var f=0;u.forEach(function(t,e){t.color||(t.color=h.defaultColorRange[f],f=(f+1)%h.defaultColorRange.length),t.strokeColor||(t.strokeColor="LinePlot"===t.geometry?t.color:i.rgb(t.color).darker().toString()),c.data[e].color=t.color,c.data[e].strokeColor=t.strokeColor,c.data[e].strokeDash=t.strokeDash,c.data[e].strokeSize=t.strokeSize});var d=u.filter(function(t,e){var r=t.visible;return"undefined"==typeof r||r===!0}),p=!1,g=d.map(function(t,e){return p=p||"undefined"!=typeof t.groupId,t});if(p){var v=i.nest().key(function(t,e){return"undefined"!=typeof t.groupId?t.groupId:"unstacked"}).entries(g),m=[],y=v.map(function(t,e){if("unstacked"===t.key)return t.values;var r=t.values[0].r.map(function(t,e){return 0});return t.values.forEach(function(t,e,n){t.yStack=[r],m.push(r),r=a.util.sumArrays(t.r,r)}),t.values});d=i.merge(y)}d.forEach(function(t,e){t.t=Array.isArray(t.t[0])?t.t:[t.t],t.r=Array.isArray(t.r[0])?t.r:[t.r]});var b=Math.min(h.width-h.margin.left-h.margin.right,h.height-h.margin.top-h.margin.bottom)/2;b=Math.max(10,b);var x,_=[h.margin.left+b,h.margin.top+b];if(p){var w=i.max(a.util.sumArrays(a.util.arrayLast(d).r[0],a.util.arrayLast(m)));x=[0,w]}else x=i.extent(a.util.flattenArray(d.map(function(t,e){return t.r})));h.radialAxis.domain!=a.DATAEXTENT&&(x[0]=0),n=i.scale.linear().domain(h.radialAxis.domain!=a.DATAEXTENT&&h.radialAxis.domain?h.radialAxis.domain:x).range([0,b]),c.layout.radialAxis.domain=n.domain();var A,k=a.util.flattenArray(d.map(function(t,e){return t.t})),M="string"==typeof k[0];M&&(k=a.util.deduplicate(k),A=k.slice(),k=i.range(k.length),d=d.map(function(t,e){var r=t;return t.t=[k],p&&(r.yStack=t.yStack),r}));var T=d.filter(function(t,e){return"LinePlot"===t.geometry||"DotPlot"===t.geometry}).length===d.length,E=null===h.needsEndSpacing?M||!T:h.needsEndSpacing,L=h.angularAxis.domain&&h.angularAxis.domain!=a.DATAEXTENT&&!M&&h.angularAxis.domain[0]>=0,S=L?h.angularAxis.domain:i.extent(k),C=Math.abs(k[1]-k[0]);T&&!M&&(C=0);var P=S.slice();E&&M&&(P[1]+=C);var z=h.angularAxis.ticksCount||4;z>8&&(z=z/(z/8)+z%8),h.angularAxis.ticksStep&&(z=(P[1]-P[0])/z);var R=h.angularAxis.ticksStep||(P[1]-P[0])/(z*(h.minorTicks+1));A&&(R=Math.max(Math.round(R),1)),P[2]||(P[2]=R);var O=i.range.apply(this,P);if(O=O.map(function(t,e){return parseFloat(t.toPrecision(12))}),s=i.scale.linear().domain(P.slice(0,2)).range("clockwise"===h.direction?[0,360]:[360,0]),c.layout.angularAxis.domain=s.domain(),c.layout.angularAxis.endPadding=E?C:0,e=i.select(this).select("svg.chart-root"),"undefined"==typeof e||e.empty()){var I="<svg xmlns='http://www.w3.org/2000/svg' class='chart-root'>' + '<g class='outer-group'>' + '<g class='chart-group'>' + '<circle class='background-circle'></circle>' + '<g class='geometry-group'></g>' + '<g class='radial axis-group'>' + '<circle class='outside-circle'></circle>' + '</g>' + '<g class='angular axis-group'></g>' + '<g class='guides-group'><line></line><circle r='0'></circle></g>' + '</g>' + '<g class='legend-group'></g>' + '<g class='tooltips-group'></g>' + '<g class='title-group'><text></text></g>' + '</g>' + '</svg>",j=(new DOMParser).parseFromString(I,"application/xml"),N=this.appendChild(this.ownerDocument.importNode(j.documentElement,!0));e=i.select(N)}e.select(".guides-group").style({"pointer-events":"none"}),e.select(".angular.axis-group").style({"pointer-events":"none"}),e.select(".radial.axis-group").style({"pointer-events":"none"});var F,B=e.select(".chart-group"),D={fill:"none",stroke:h.tickColor},U={"font-size":h.font.size,"font-family":h.font.family,fill:h.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+h.font.outlineColor}).join(",")};if(h.showLegend){F=e.select(".legend-group").attr({transform:"translate("+[b,h.margin.top]+")"}).style({display:"block"});var V=d.map(function(t,e){var r=a.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend="undefined"==typeof t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});a.Legend().config({data:d.map(function(t,e){return t.name||"Element"+e}),legendConfig:o({},a.Legend.defaultConfig().legendConfig,{container:F,elements:V,reverseOrder:h.legend.reverseOrder})})();var q=F.node().getBBox();b=Math.min(h.width-q.width-h.margin.left-h.margin.right,h.height-h.margin.top-h.margin.bottom)/2,b=Math.max(10,b),_=[h.margin.left+b,h.margin.top+b],n.range([0,b]),c.layout.radialAxis.domain=n.domain(),F.attr("transform","translate("+[_[0]+b,_[1]-b]+")")}else F=e.select(".legend-group").style({display:"none"});e.attr({width:h.width,height:h.height}).style({opacity:h.opacity}),B.attr("transform","translate("+_+")").style({cursor:"crosshair"});var H=[(h.width-(h.margin.left+h.margin.right+2*b+(q?q.width:0)))/2,(h.height-(h.margin.top+h.margin.bottom+2*b))/2];if(H[0]=Math.max(0,H[0]),H[1]=Math.max(0,H[1]),e.select(".outer-group").attr("transform","translate("+H+")"),h.title){var G=e.select("g.title-group text").style(U).text(h.title),Y=G.node().getBBox();G.attr({x:_[0]-Y.width/2,y:_[1]-b-20})}var X=e.select(".radial.axis-group");if(h.radialAxis.gridLinesVisible){var W=X.selectAll("circle.grid-circle").data(n.ticks(5));W.enter().append("circle").attr({"class":"grid-circle"}).style(D),W.attr("r",n),W.exit().remove()}X.select("circle.outside-circle").attr({r:b}).style(D);var Z=e.select("circle.background-circle").attr({r:b}).style({fill:h.backgroundColor,stroke:h.stroke});if(h.radialAxis.visible){var $=i.svg.axis().scale(n).ticks(5).tickSize(5);X.call($).attr({transform:"rotate("+h.radialAxis.orientation+")"}),X.selectAll(".domain").style(D),X.selectAll("g>text").text(function(t,e){return this.textContent+h.radialAxis.ticksSuffix}).style(U).style({"text-anchor":"start"}).attr({x:0,y:0,dx:0,dy:0,transform:function(t,e){return"horizontal"===h.radialAxis.tickOrientation?"rotate("+-h.radialAxis.orientation+") translate("+[0,U["font-size"]]+")":"translate("+[0,U["font-size"]]+")"}}),X.selectAll("g>line").style({stroke:"black"})}var K=e.select(".angular.axis-group").selectAll("g.angular-tick").data(O),Q=K.enter().append("g").classed("angular-tick",!0);K.attr({transform:function(t,e){return"rotate("+l(t,e)+")"}}).style({display:h.angularAxis.visible?"block":"none"}),K.exit().remove(),Q.append("line").classed("grid-line",!0).classed("major",function(t,e){return e%(h.minorTicks+1)==0}).classed("minor",function(t,e){return!(e%(h.minorTicks+1)==0)}).style(D),Q.selectAll(".minor").style({stroke:h.minorTickColor}),K.select("line.grid-line").attr({x1:h.tickLength?b-h.tickLength:0,x2:b}).style({display:h.angularAxis.gridLinesVisible?"block":"none"}),Q.append("text").classed("axis-text",!0).style(U);var J=K.select("text.axis-text").attr({x:b+h.labelOffset,dy:".35em",transform:function(t,e){var r=l(t,e),n=b+h.labelOffset,i=h.angularAxis.tickOrientation;return"horizontal"==i?"rotate("+-r+" "+n+" 0)":"radial"==i?270>r&&r>90?"rotate(180 "+n+" 0)":null:"rotate("+(180>=r&&r>0?-90:90)+" "+n+" 0)"}}).style({"text-anchor":"middle",display:h.angularAxis.labelsVisible?"block":"none"}).text(function(t,e){return e%(h.minorTicks+1)!=0?"":A?A[t]+h.angularAxis.ticksSuffix:t+h.angularAxis.ticksSuffix}).style(U);h.angularAxis.rewriteTicks&&J.text(function(t,e){return e%(h.minorTicks+1)!=0?"":h.angularAxis.rewriteTicks(this.textContent,e)});var tt=i.max(B.selectAll(".angular-tick text")[0].map(function(t,e){return t.getCTM().e+t.getBBox().width}));F.attr({transform:"translate("+[b+tt,h.margin.top]+")"});var et=e.select("g.geometry-group").selectAll("g").size()>0,rt=e.select("g.geometry-group").selectAll("g.geometry").data(d);if(rt.enter().append("g").attr({"class":function(t,e){return"geometry geometry"+e}}),rt.exit().remove(),d[0]||et){var nt=[];d.forEach(function(t,e){var r={};r.radialScale=n,r.angularScale=s,r.container=rt.filter(function(t,r){return r==e}),r.geometry=t.geometry,r.orientation=h.orientation,r.direction=h.direction,r.index=e,nt.push({data:t,geometryConfig:r})});var it=i.nest().key(function(t,e){return"undefined"!=typeof t.data.groupId||"unstacked"}).entries(nt),at=[];it.forEach(function(t,e){"unstacked"===t.key?at=at.concat(t.values.map(function(t,e){return[t]})):at.push(t.values)}),at.forEach(function(t,e){var r;r=Array.isArray(t)?t[0].geometryConfig.geometry:t.geometryConfig.geometry;var n=t.map(function(t,e){return o(a[r].defaultConfig(),t)});a[r]().config(n)()})}var ot,st,lt=e.select(".guides-group"),ut=e.select(".tooltips-group"),ct=a.tooltipPanel().config({container:ut,fontSize:8})(),ht=a.tooltipPanel().config({container:ut,fontSize:8})(),ft=a.tooltipPanel().config({container:ut,hasTick:!0})();if(!M){var dt=lt.select("line").attr({x1:0,y1:0,y2:0}).style({stroke:"grey","pointer-events":"none"});B.on("mousemove.angular-guide",function(t,e){var r=a.util.getMousePos(Z).angle;dt.attr({x2:-b,transform:"rotate("+r+")"}).style({opacity:.5});var n=(r+180+360-h.orientation)%360;ot=s.invert(n);var i=a.util.convertToCartesian(b+12,r+180);ct.text(a.util.round(ot)).move([i[0]+_[0],i[1]+_[1]])}).on("mouseout.angular-guide",function(t,e){lt.select("line").style({opacity:0})})}var pt=lt.select("circle").style({stroke:"grey",fill:"none"});B.on("mousemove.radial-guide",function(t,e){var r=a.util.getMousePos(Z).radius;pt.attr({r:r}).style({opacity:.5}),st=n.invert(a.util.getMousePos(Z).radius);var i=a.util.convertToCartesian(r,h.radialAxis.orientation);ht.text(a.util.round(st)).move([i[0]+_[0],i[1]+_[1]])}).on("mouseout.radial-guide",function(t,e){pt.style({opacity:0}),ft.hide(),ct.hide(),ht.hide()}),e.selectAll(".geometry-group .mark").on("mouseover.tooltip",function(t,r){var n=i.select(this),o=n.style("fill"),s="black",l=n.style("opacity")||1;if(n.attr({"data-opacity":l}),"none"!=o){n.attr({"data-fill":o}),s=i.hsl(o).darker().toString(),n.style({fill:s,opacity:1});var u={t:a.util.round(t[0]),r:a.util.round(t[1])};M&&(u.t=A[t[0]]);var c="t: "+u.t+", r: "+u.r,h=this.getBoundingClientRect(),f=e.node().getBoundingClientRect(),d=[h.left+h.width/2-H[0]-f.left,h.top+h.height/2-H[1]-f.top];ft.config({color:s}).text(c),ft.move(d)}else o=n.style("stroke"),n.attr({"data-stroke":o}),s=i.hsl(o).darker().toString(),n.style({stroke:s,opacity:1})}).on("mousemove.tooltip",function(t,e){return 0!=i.event.which?!1:void(i.select(this).attr("data-fill")&&ft.show())}).on("mouseout.tooltip",function(t,e){ft.hide();var r=i.select(this),n=r.attr("data-fill");n?r.style({fill:n,opacity:r.attr("data-opacity")}):r.style({stroke:r.attr("data-stroke"),opacity:r.attr("data-opacity")})})}),f}var e,r,n,s,l={data:[],layout:{}},u={},c={},h=i.dispatch("hover"),f={};return f.render=function(e){return t(e),this},f.config=function(t){if(!arguments.length)return l;var e=a.util.cloneJson(t);return e.data.forEach(function(t,e){l.data[e]||(l.data[e]={}),o(l.data[e],a.Axis.defaultConfig().data[0]),o(l.data[e],t)}),o(l.layout,a.Axis.defaultConfig().layout),o(l.layout,e.layout),this},f.getLiveConfig=function(){return c},f.getinputConfig=function(){return u},f.radialScale=function(t){return n},f.angularScale=function(t){return s},f.svg=function(){return e},i.rebind(f,h,"on"),f},a.Axis.defaultConfig=function(t,e){var r={data:[{t:[1,2,3,4],r:[10,11,12,13],name:"Line1",geometry:"LinePlot",color:null,strokeDash:"solid",strokeColor:null,strokeSize:"1",visibleInLegend:!0,opacity:1}],layout:{defaultColorRange:i.scale.category10().range(),title:null,height:450,
+width:500,margin:{top:40,right:40,bottom:40,left:40},font:{size:12,color:"gray",outlineColor:"white",family:"Tahoma, sans-serif"},direction:"clockwise",orientation:0,labelOffset:10,radialAxis:{domain:null,orientation:-45,ticksSuffix:"",visible:!0,gridLinesVisible:!0,tickOrientation:"horizontal",rewriteTicks:null},angularAxis:{domain:[0,360],ticksSuffix:"",visible:!0,gridLinesVisible:!0,labelsVisible:!0,tickOrientation:"horizontal",rewriteTicks:null,ticksCount:null,ticksStep:null},minorTicks:0,tickLength:null,tickColor:"silver",minorTickColor:"#eee",backgroundColor:"none",needsEndSpacing:null,showLegend:!0,legend:{reverseOrder:!1},opacity:1}};return r},a.util={},a.DATAEXTENT="dataExtent",a.AREA="AreaChart",a.LINE="LinePlot",a.DOT="DotPlot",a.BAR="BarChart",a.util._override=function(t,e){for(var r in t)r in e&&(e[r]=t[r])},a.util._extend=function(t,e){for(var r in t)e[r]=t[r]},a.util._rndSnd=function(){return 2*Math.random()-1+(2*Math.random()-1)+(2*Math.random()-1)},a.util.dataFromEquation2=function(t,e){var r=e||6,n=i.range(0,360+r,r).map(function(e,r){var n=e*Math.PI/180,i=t(n);return[e,i]});return n},a.util.dataFromEquation=function(t,e,r){var n=e||6,a=[],o=[];i.range(0,360+n,n).forEach(function(e,r){var n=e*Math.PI/180,i=t(n);a.push(e),o.push(i)});var s={t:a,r:o};return r&&(s.name=r),s},a.util.ensureArray=function(t,e){if("undefined"==typeof t)return null;var r=[].concat(t);return i.range(e).map(function(t,e){return r[e]||r[0]})},a.util.fillArrays=function(t,e,r){return e.forEach(function(e,n){t[e]=a.util.ensureArray(t[e],r)}),t},a.util.cloneJson=function(t){return JSON.parse(JSON.stringify(t))},a.util.validateKeys=function(t,e){"string"==typeof e&&(e=e.split("."));var r=e.shift();return t[r]&&(!e.length||objHasKeys(t[r],e))},a.util.sumArrays=function(t,e){return i.zip(t,e).map(function(t,e){return i.sum(t)})},a.util.arrayLast=function(t){return t[t.length-1]},a.util.arrayEqual=function(t,e){for(var r=Math.max(t.length,e.length,1);r-- >=0&&t[r]===e[r];);return-2===r},a.util.flattenArray=function(t){for(var e=[];!a.util.arrayEqual(e,t);)e=t,t=[].concat.apply([],t);return t},a.util.deduplicate=function(t){return t.filter(function(t,e,r){return r.indexOf(t)==e})},a.util.convertToCartesian=function(t,e){var r=e*Math.PI/180,n=t*Math.cos(r),i=t*Math.sin(r);return[n,i]},a.util.round=function(t,e){var r=e||2,n=Math.pow(10,r);return Math.round(t*n)/n},a.util.getMousePos=function(t){var e=i.mouse(t.node()),r=e[0],n=e[1],a={};return a.x=r,a.y=n,a.pos=e,a.angle=180*(Math.atan2(n,r)+Math.PI)/Math.PI,a.radius=Math.sqrt(r*r+n*n),a},a.util.duplicatesCount=function(t){for(var e,r={},n={},i=0,a=t.length;a>i;i++)e=t[i],e in r?(r[e]++,n[e]=r[e]):r[e]=1;return n},a.util.duplicates=function(t){return Object.keys(a.util.duplicatesCount(t))},a.util.translator=function(t,e,r,n){if(n){var i=r.slice();r=e,e=i}var a=e.reduce(function(t,e){return"undefined"!=typeof t?t[e]:void 0},t);"undefined"!=typeof a&&(e.reduce(function(t,r,n){return"undefined"!=typeof t?(n===e.length-1&&delete t[r],t[r]):void 0},t),r.reduce(function(t,e,n){return"undefined"==typeof t[e]&&(t[e]={}),n===r.length-1&&(t[e]=a),t[e]},t))},a.PolyChart=function(){function t(){var t=r[0].geometryConfig,e=t.container;"string"==typeof e&&(e=i.select(e)),e.datum(r).each(function(e,r){function n(e,r){var n=t.radialScale(e[1]),i=(t.angularScale(e[0])+t.orientation)*Math.PI/180;return{r:n,t:i}}function a(t){var e=t.r*Math.cos(t.t),r=t.r*Math.sin(t.t);return{x:e,y:r}}var o=!!e[0].data.yStack,l=e.map(function(t,e){return o?i.zip(t.data.t[0],t.data.r[0],t.data.yStack[0]):i.zip(t.data.t[0],t.data.r[0])}),u=t.angularScale,c=t.radialScale.domain()[0],h={};h.bar=function(r,n,a){var o=e[a].data,s=t.radialScale(r[1])-t.radialScale(0),l=t.radialScale(r[2]||0),c=o.barWidth;i.select(this).attr({"class":"mark bar",d:"M"+[[s+l,-c/2],[s+l,c/2],[l,c/2],[l,-c/2]].join("L")+"Z",transform:function(e,r){return"rotate("+(t.orientation+u(e[0]))+")"}})},h.dot=function(t,r,o){var s=t[2]?[t[0],t[1]+t[2]]:t,l=i.svg.symbol().size(e[o].data.dotSize).type(e[o].data.dotType)(t,r);i.select(this).attr({"class":"mark dot",d:l,transform:function(t,e){var r=a(n(s));return"translate("+[r.x,r.y]+")"}})};var f=i.svg.line.radial().interpolate(e[0].data.lineInterpolation).radius(function(e){return t.radialScale(e[1])}).angle(function(e){return t.angularScale(e[0])*Math.PI/180});h.line=function(r,n,a){var o=r[2]?l[a].map(function(t,e){return[t[0],t[1]+t[2]]}):l[a];if(i.select(this).each(h.dot).style({opacity:function(t,r){return+e[a].data.dotVisible},fill:v.stroke(r,n,a)}).attr({"class":"mark dot"}),!(n>0)){var s=i.select(this.parentNode).selectAll("path.line").data([0]);s.enter().insert("path"),s.attr({"class":"line",d:f(o),transform:function(e,r){return"rotate("+(t.orientation+90)+")"},"pointer-events":"none"}).style({fill:function(t,e){return v.fill(r,n,a)},"fill-opacity":0,stroke:function(t,e){return v.stroke(r,n,a)},"stroke-width":function(t,e){return v["stroke-width"](r,n,a)},"stroke-dasharray":function(t,e){return v["stroke-dasharray"](r,n,a)},opacity:function(t,e){return v.opacity(r,n,a)},display:function(t,e){return v.display(r,n,a)}})}};var d=t.angularScale.range(),p=Math.abs(d[1]-d[0])/l[0].length*Math.PI/180,g=i.svg.arc().startAngle(function(t){return-p/2}).endAngle(function(t){return p/2}).innerRadius(function(e){return t.radialScale(c+(e[2]||0))}).outerRadius(function(e){return t.radialScale(c+(e[2]||0))+t.radialScale(e[1])});h.arc=function(e,r,n){i.select(this).attr({"class":"mark arc",d:g,transform:function(e,r){return"rotate("+(t.orientation+u(e[0])+90)+")"}})};var v={fill:function(t,r,n){return e[n].data.color},stroke:function(t,r,n){return e[n].data.strokeColor},"stroke-width":function(t,r,n){return e[n].data.strokeSize+"px"},"stroke-dasharray":function(t,r,n){return s[e[n].data.strokeDash]},opacity:function(t,r,n){return e[n].data.opacity},display:function(t,r,n){return"undefined"==typeof e[n].data.visible||e[n].data.visible?"block":"none"}},m=i.select(this).selectAll("g.layer").data(l);m.enter().append("g").attr({"class":"layer"});var y=m.selectAll("path.mark").data(function(t,e){return t});y.enter().append("path").attr({"class":"mark"}),y.style(v).each(h[t.geometryType]),y.exit().remove(),m.exit().remove()})}var e,r=[a.PolyChart.defaultConfig()],n=i.dispatch("hover"),s={solid:"none",dash:[5,2],dot:[2,5]};return t.config=function(t){return arguments.length?(t.forEach(function(t,e){r[e]||(r[e]={}),o(r[e],a.PolyChart.defaultConfig()),o(r[e],t)}),this):r},t.getColorScale=function(){return e},i.rebind(t,n,"on"),t},a.PolyChart.defaultConfig=function(){var t={data:{name:"geom1",t:[[1,2,3,4]],r:[[1,2,3,4]],dotType:"circle",dotSize:64,dotVisible:!1,barWidth:20,color:"#ffa500",strokeSize:1,strokeColor:"silver",strokeDash:"solid",opacity:1,index:0,visible:!0,visibleInLegend:!0},geometryConfig:{geometry:"LinePlot",geometryType:"arc",direction:"clockwise",orientation:0,container:"body",radialScale:null,angularScale:null,colorScale:i.scale.category20()}};return t},a.BarChart=function(){return a.PolyChart()},a.BarChart.defaultConfig=function(){var t={geometryConfig:{geometryType:"bar"}};return t},a.AreaChart=function(){return a.PolyChart()},a.AreaChart.defaultConfig=function(){var t={geometryConfig:{geometryType:"arc"}};return t},a.DotPlot=function(){return a.PolyChart()},a.DotPlot.defaultConfig=function(){var t={geometryConfig:{geometryType:"dot",dotType:"circle"}};return t},a.LinePlot=function(){return a.PolyChart()},a.LinePlot.defaultConfig=function(){var t={geometryConfig:{geometryType:"line"}};return t},a.Legend=function(){function t(){var r=e.legendConfig,n=e.data.map(function(t,e){return[].concat(t).map(function(t,n){var i=o({},r.elements[e]);return i.name=t,i.color=[].concat(r.elements[e].color)[n],i})}),a=i.merge(n);a=a.filter(function(t,e){return r.elements[e]&&(r.elements[e].visibleInLegend||"undefined"==typeof r.elements[e].visibleInLegend)}),r.reverseOrder&&(a=a.reverse());var s=r.container;("string"==typeof s||s.nodeName)&&(s=i.select(s));var l=a.map(function(t,e){return t.color}),u=r.fontSize,c=null==r.isContinuous?"number"==typeof a[0]:r.isContinuous,h=c?r.height:u*a.length,f=s.classed("legend-group",!0),d=f.selectAll("svg").data([0]),p=d.enter().append("svg").attr({width:300,height:h+u,xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink",version:"1.1"});p.append("g").classed("legend-axis",!0),p.append("g").classed("legend-marks",!0);var g=i.range(a.length),v=i.scale[c?"linear":"ordinal"]().domain(g).range(l),m=i.scale[c?"linear":"ordinal"]().domain(g)[c?"range":"rangePoints"]([0,h]),y=function(t,e){var r=3*e;return"line"===t?"M"+[[-e/2,-e/12],[e/2,-e/12],[e/2,e/12],[-e/2,e/12]]+"Z":-1!=i.svg.symbolTypes.indexOf(t)?i.svg.symbol().type(t).size(r)():i.svg.symbol().type("square").size(r)()};if(c){var b=d.select(".legend-marks").append("defs").append("linearGradient").attr({id:"grad1",x1:"0%",y1:"0%",x2:"0%",y2:"100%"}).selectAll("stop").data(l);b.enter().append("stop"),b.attr({offset:function(t,e){return e/(l.length-1)*100+"%"}}).style({"stop-color":function(t,e){return t}}),d.append("rect").classed("legend-mark",!0).attr({height:r.height,width:r.colorBandWidth,fill:"url(#grad1)"})}else{var x=d.select(".legend-marks").selectAll("path.legend-mark").data(a);x.enter().append("path").classed("legend-mark",!0),x.attr({transform:function(t,e){return"translate("+[u/2,m(e)+u/2]+")"},d:function(t,e){var r=t.symbol;return y(r,u)},fill:function(t,e){return v(e)}}),x.exit().remove()}var _=i.svg.axis().scale(m).orient("right"),w=d.select("g.legend-axis").attr({transform:"translate("+[c?r.colorBandWidth:u,u/2]+")"}).call(_);return w.selectAll(".domain").style({fill:"none",stroke:"none"}),w.selectAll("line").style({fill:"none",stroke:c?r.textColor:"none"}),w.selectAll("text").style({fill:r.textColor,"font-size":r.fontSize}).text(function(t,e){return a[e].name}),t}var e=a.Legend.defaultConfig(),r=i.dispatch("hover");return t.config=function(t){return arguments.length?(o(e,t),this):e},i.rebind(t,r,"on"),t},a.Legend.defaultConfig=function(t,e){var r={data:["a","b","c"],legendConfig:{elements:[{symbol:"line",color:"red"},{symbol:"square",color:"yellow"},{symbol:"diamond",color:"limegreen"}],height:150,colorBandWidth:30,fontSize:12,container:"body",isContinuous:null,textColor:"grey",reverseOrder:!1}};return r},a.tooltipPanel=function(){var t,e,r,n={container:null,hasTick:!1,fontSize:12,color:"white",padding:5},s="tooltip-"+a.tooltipPanel.uid++,l=10,u=function(){t=n.container.selectAll("g."+s).data([0]);var i=t.enter().append("g").classed(s,!0).style({"pointer-events":"none",display:"none"});return r=i.append("path").style({fill:"white","fill-opacity":.9}).attr({d:"M0 0"}),e=i.append("text").attr({dx:n.padding+l,dy:.3*+n.fontSize}),u};return u.text=function(a){var o=i.hsl(n.color).l,s=o>=.5?"#aaa":"white",c=o>=.5?"black":"white",h=a||"";e.style({fill:c,"font-size":n.fontSize+"px"}).text(h);var f=n.padding,d=e.node().getBBox(),p={fill:n.color,stroke:s,"stroke-width":"2px"},g=d.width+2*f+l,v=d.height+2*f;return r.attr({d:"M"+[[l,-v/2],[l,-v/4],[n.hasTick?0:l,0],[l,v/4],[l,v/2],[g,v/2],[g,-v/2]].join("L")+"Z"}).style(p),t.attr({transform:"translate("+[l,-v/2+2*f]+")"}),t.style({display:"block"}),u},u.move=function(e){return t?(t.attr({transform:"translate("+[e[0],e[1]]+")"}).style({display:"block"}),u):void 0},u.hide=function(){return t?(t.style({display:"none"}),u):void 0},u.show=function(){return t?(t.style({display:"block"}),u):void 0},u.config=function(t){return o(n,t),u},u},a.tooltipPanel.uid=1,a.adapter={},a.adapter.plotly=function(){var t={};return t.convert=function(t,e){var r={};if(t.data&&(r.data=t.data.map(function(t,r){var n=o({},t),i=[[n,["marker","color"],["color"]],[n,["marker","opacity"],["opacity"]],[n,["marker","line","color"],["strokeColor"]],[n,["marker","line","dash"],["strokeDash"]],[n,["marker","line","width"],["strokeSize"]],[n,["marker","symbol"],["dotType"]],[n,["marker","size"],["dotSize"]],[n,["marker","barWidth"],["barWidth"]],[n,["line","interpolation"],["lineInterpolation"]],[n,["showlegend"],["visibleInLegend"]]];return i.forEach(function(t,r){a.util.translator.apply(null,t.concat(e))}),e||delete n.marker,e&&delete n.groupId,e?("LinePlot"===n.geometry?(n.type="scatter",n.dotVisible===!0?(delete n.dotVisible,n.mode="lines+markers"):n.mode="lines"):"DotPlot"===n.geometry?(n.type="scatter",n.mode="markers"):"AreaChart"===n.geometry?n.type="area":"BarChart"===n.geometry&&(n.type="bar"),delete n.geometry):("scatter"===n.type?"lines"===n.mode?n.geometry="LinePlot":"markers"===n.mode?n.geometry="DotPlot":"lines+markers"===n.mode&&(n.geometry="LinePlot",n.dotVisible=!0):"area"===n.type?n.geometry="AreaChart":"bar"===n.type&&(n.geometry="BarChart"),delete n.mode,delete n.type),n}),!e&&t.layout&&"stack"===t.layout.barmode)){var n=a.util.duplicates(r.data.map(function(t,e){return t.geometry}));r.data.forEach(function(t,e){var i=n.indexOf(t.geometry);-1!=i&&(r.data[e].groupId=i)})}if(t.layout){var s=o({},t.layout),l=[[s,["plot_bgcolor"],["backgroundColor"]],[s,["showlegend"],["showLegend"]],[s,["radialaxis"],["radialAxis"]],[s,["angularaxis"],["angularAxis"]],[s.angularaxis,["showline"],["gridLinesVisible"]],[s.angularaxis,["showticklabels"],["labelsVisible"]],[s.angularaxis,["nticks"],["ticksCount"]],[s.angularaxis,["tickorientation"],["tickOrientation"]],[s.angularaxis,["ticksuffix"],["ticksSuffix"]],[s.angularaxis,["range"],["domain"]],[s.angularaxis,["endpadding"],["endPadding"]],[s.radialaxis,["showline"],["gridLinesVisible"]],[s.radialaxis,["tickorientation"],["tickOrientation"]],[s.radialaxis,["ticksuffix"],["ticksSuffix"]],[s.radialaxis,["range"],["domain"]],[s.angularAxis,["showline"],["gridLinesVisible"]],[s.angularAxis,["showticklabels"],["labelsVisible"]],[s.angularAxis,["nticks"],["ticksCount"]],[s.angularAxis,["tickorientation"],["tickOrientation"]],[s.angularAxis,["ticksuffix"],["ticksSuffix"]],[s.angularAxis,["range"],["domain"]],[s.angularAxis,["endpadding"],["endPadding"]],[s.radialAxis,["showline"],["gridLinesVisible"]],[s.radialAxis,["tickorientation"],["tickOrientation"]],[s.radialAxis,["ticksuffix"],["ticksSuffix"]],[s.radialAxis,["range"],["domain"]],[s.font,["outlinecolor"],["outlineColor"]],[s.legend,["traceorder"],["reverseOrder"]],[s,["labeloffset"],["labelOffset"]],[s,["defaultcolorrange"],["defaultColorRange"]]];if(l.forEach(function(t,r){a.util.translator.apply(null,t.concat(e))}),e?("undefined"!=typeof s.tickLength&&(s.angularaxis.ticklen=s.tickLength,delete s.tickLength),s.tickColor&&(s.angularaxis.tickcolor=s.tickColor,delete s.tickColor)):(s.angularAxis&&"undefined"!=typeof s.angularAxis.ticklen&&(s.tickLength=s.angularAxis.ticklen),s.angularAxis&&"undefined"!=typeof s.angularAxis.tickcolor&&(s.tickColor=s.angularAxis.tickcolor)),s.legend&&"boolean"!=typeof s.legend.reverseOrder&&(s.legend.reverseOrder="normal"!=s.legend.reverseOrder),s.legend&&"boolean"==typeof s.legend.traceorder&&(s.legend.traceorder=s.legend.traceorder?"reversed":"normal",delete s.legend.reverseOrder),s.margin&&"undefined"!=typeof s.margin.t){var u=["t","r","b","l","pad"],c=["top","right","bottom","left","pad"],h={};i.entries(s.margin).forEach(function(t,e){h[c[u.indexOf(t.key)]]=t.value}),s.margin=h}e&&(delete s.needsEndSpacing,delete s.minorTickColor,delete s.minorTicks,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksCount,delete s.angularaxis.ticksStep,delete s.angularaxis.rewriteTicks,delete s.angularaxis.nticks,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksCount,delete s.radialaxis.ticksStep,delete s.radialaxis.rewriteTicks,delete s.radialaxis.nticks),r.layout=s}return r},t}},{"../../plotly":366,"./micropolar_manager":417,d3:70}],417:[function(t,e,r){"use strict";var n=t("../../plotly"),i=t("d3"),a=t("./undo_manager"),o=e.exports={},s=n.Lib.extendDeepAll;o.framework=function(t){function e(e,a){return a&&(h=a),i.select(i.select(h).node().parentNode).selectAll(".svg-container>*:not(.chart-root)").remove(),r=r?s(r,e):e,u||(u=n.micropolar.Axis()),c=n.micropolar.adapter.plotly().convert(r),u.config(c).render(h),t.data=r.data,t.layout=r.layout,o.fillLayout(t),r}var r,l,u,c,h,f=new a;return e.isPolar=!0,e.svg=function(){return u.svg()},e.getConfig=function(){return r},e.getLiveConfig=function(){return n.micropolar.adapter.plotly().convert(u.getLiveConfig(),!0)},e.getLiveScales=function(){return{t:u.angularScale(),r:u.radialScale()}},e.setUndoPoint=function(){var t=this,e=n.micropolar.util.cloneJson(r);!function(e,r){f.add({undo:function(){r&&t(r)},redo:function(){t(e)}})}(e,l),l=n.micropolar.util.cloneJson(e)},e.undo=function(){f.undo()},e.redo=function(){f.redo()},e},o.fillLayout=function(t){var e=i.select(t).selectAll(".plot-container"),r=e.selectAll(".svg-container"),a=t.framework&&t.framework.svg&&t.framework.svg(),o={width:800,height:600,paper_bgcolor:n.Color.background,_container:e,_paperdiv:r,_paper:a};t._fullLayout=s(o,t.layout)}},{"../../plotly":366,"./undo_manager":418,d3:70}],418:[function(t,e,r){"use strict";e.exports=function(){function t(t,e){return t?(i=!0,t[e](),i=!1,this):this}var e,r=[],n=-1,i=!1;return{add:function(t){return i?this:(r.splice(n+1,r.length-n),r.push(t),n=r.length-1,this)},setCallback:function(t){e=t},undo:function(){var i=r[n];return i?(t(i,"undo"),n-=1,e&&e(i.undo),this):this},redo:function(){var i=r[n+1];return i?(t(i,"redo"),n+=1,e&&e(i.redo),this):this},clear:function(){r=[],n=-1},hasUndo:function(){return-1!==n},hasRedo:function(){return n<r.length-1},getCommands:function(){return r},getPreviousCommand:function(){return r[n-1]},getIndex:function(){return n}}}},{}],419:[function(t,e,r){"use strict";function n(t){var e;switch(t){case"themes__thumb":e={autosize:!0,width:150,height:150,title:"",showlegend:!1,margin:{l:5,r:5,t:5,b:5,pad:0},annotations:[]};break;case"thumbnail":e={title:"",hidesources:!0,showlegend:!1,borderwidth:0,bordercolor:"",margin:{l:1,r:1,t:1,b:1,pad:0},annotations:[]};break;default:e={}}return e}function i(t){var e=["xaxis","yaxis","zaxis"];return e.indexOf(t.slice(0,5))>-1}var a=t("../plotly"),o=a.Lib.extendFlat,s=a.Lib.extendDeep;e.exports=function(t,e){t.framework&&t.framework.isPolar&&(t=t.framework.getConfig());var r,l=t.data,u=t.layout,c=s([],l),h=s({},u,n(e.tileClass));if(e.width&&(h.width=e.width),e.height&&(h.height=e.height),"thumbnail"===e.tileClass||"themes__thumb"===e.tileClass){h.annotations=[];var f=Object.keys(h);for(r=0;r<f.length;r++)i(f[r])&&(h[f[r]].title="");for(r=0;r<c.length;r++){var d=c[r];d.showscale=!1,d.marker&&(d.marker.showscale=!1),"pie"===d.type&&(d.textposition="none")}}if(Array.isArray(e.annotations))for(r=0;r<e.annotations.length;r++)h.annotations.push(e.annotations[r]);var p=a.Plots.getSubplotIds(h,"gl3d");if(p.length){var g={};for("thumbnail"===e.tileClass&&(g={title:"",showaxeslabels:!1,showticklabels:!1,linetickenable:!1}),r=0;r<p.length;r++){var v=p[r];o(h[v].xaxis,g),o(h[v].yaxis,g),o(h[v].zaxis,g),h[v]._scene=null}}var m=document.createElement("div");e.tileClass&&(m.className=e.tileClass);var y={td:m,layout:h,data:c,config:{staticPlot:void 0===e.staticPlot?!0:e.staticPlot,plotGlPixelRatio:void 0===e.plotGlPixelRatio?2:e.plotGlPixelRatio,displaylogo:e.displaylogo||!1,showLink:e.showLink||!1,showTips:e.showTips||!1}};return"transparent"!==e.setBackground&&(y.config.setBackground=e.setBackground||"opaque"),y.td.defaultLayout=n(e.tileClass),y}},{"../plotly":366}],420:[function(t,e,r){"use strict";function n(t){return t._hasGL3D||t._hasGL2D?500:0}function i(t){return function(){var e=t._fullLayout;e._hasGL3D||e._hasGL2D||t.data&&t.data[0]&&t.data[0].r||(t.calcdata||[]).forEach(function(t){t[0]&&t[0].t&&t[0].t.cb&&t[0].t.cb()})}}var a={getDelay:n,getRedrawFunc:i,clone:t("./cloneplot"),toSVG:t("./tosvg"),svgToImg:t("./svgtoimg"),toImage:t("./toimage")};e.exports=a},{"./cloneplot":419,"./svgtoimg":421,"./toimage":422,"./tosvg":423}],421:[function(t,e,r){"use strict";function n(t){var e=t.emitter?t.emitter:new i,r=window.Image,n=window.Blob,a=t.svg,o=t.format||"png",s=t.canvas,l=s.getContext("2d"),u=new r,c=window.URL||window.webkitURL,h=new n([a],{type:"image/svg+xml;charset=utf-8"}),f=c.createObjectURL(h);return s.height=t.height||150,s.width=t.width||300,u.onload=function(){var t;switch(c.revokeObjectURL(f),l.drawImage(u,0,0),o){case"jpeg":t=s.toDataURL("image/jpeg");break;case"png":t=s.toDataURL("image/png");break;case"webp":t=s.toDataURL("image/webp");break;case"svg":t=a;break;default:return e.emit("error","Image format is not jpeg, png or svg")}e.emit("success",t)},u.onerror=function(t){return c.revokeObjectURL(f),e.emit("error",t)},u.src=f,e}var i=t("events").EventEmitter;e.exports=n},{events:54}],422:[function(t,e,r){"use strict";function n(t,e){function r(){var t=n.getDelay(l._fullLayout);setTimeout(function(){var t=a.Snapshot.toSVG(l),r=window.document.createElement("div"),n=window.document.createElement("canvas");r.appendChild(n),r.id=a.Lib.randstr(),n.id=a.Lib.randstr(),o=a.Snapshot.svgToImg({format:e.format,width:l._fullLayout.width,height:l._fullLayout.height,canvas:n,emitter:o,svg:t}),o.clean=function(){l&&l.remove()}},t)}var n=a.Snapshot,o=new i,s=n.clone(t,{format:"png"}),l=s.td;l.style.position="absolute",l.style.left="-5000px",document.body.appendChild(l);var u=n.getRedrawFunc(l);return a.plot(l,s.data,s.layout,s.config).then(u).then(r).catch(function(t){o.emit("error",t)}),o}var i=t("events").EventEmitter,a=t("../plotly");e.exports=n},{"../plotly":366,events:54}],423:[function(t,e,r){"use strict";function n(t,e,r){var n=e.toImage("png");t._glimages.append("svg:image").attr({xmlns:o.svg,"xlink:href":n,x:r.x,y:r.y,width:r.width,height:r.height,preserveAspectRatio:"none"}),e.destroy()}var i=t("../plotly"),a=t("d3"),o=t("../constants/xmlns_namespaces");e.exports=function(t,e){var r,s,l=t._fullLayout,u=l._paper,c=l._size;u.insert("rect",":first-child").call(i.Drawing.setRect,0,0,l.width,l.height).call(i.Color.fill,l.paper_bgcolor);var h,f=i.Plots.getSubplotIds(l,"gl3d");for(s=0;s<f.length;s++)h=l[f[s]],r=h.domain,n(l,h._scene,{x:c.l+c.w*r.x[0],y:c.t+c.h*(1-r.y[1]),width:c.w*(r.x[1]-r.x[0]),height:c.h*(r.y[1]-r.y[0])});var d,p=i.Plots.getSubplotIds(l,"gl2d");for(s=0;s<p.length;s++)d=l._plots[p[s]],n(l,d._scene2d,{x:c.l,y:c.t,width:c.w,height:c.h});var g,v,m=i.Plots.getSubplotIds(l,"geo");for(s=0;s<m.length;s++)g=l[m[s]],r=g.domain,v=g._geo.framework,v.attr("style",null),v.attr({x:c.l+c.w*r.x[0]+g._marginX,y:c.t+c.h*(1-r.y[1])+g._marginY,width:g._width,height:g._height}),l._geoimages.node().appendChild(v.node());if(l._toppaper){var y,b=l._toppaper.node().childNodes;for(s=0;s<b.length;s++)y=b[s],y.childNodes.length&&u.node().appendChild(y)}u.node().style.background="",u.selectAll("text").attr({"data-unformatted":null}).style({"-webkit-user-select":null,"-moz-user-select":null,"-ms-user-select":null}).each(function(){var t=a.select(this);if("hidden"===t.style("visibility"))return void t.remove();var e=t.style("font-family");e&&-1!==e.indexOf('"')&&t.style("font-family",e.replace(/"/g,"\\'"))}),("pdf"===e||"eps"===e)&&u.selectAll("#MathJax_SVG_glyphs path").attr("stroke-width",0),u.node().setAttributeNS(o.xmlns,"xmlns",o.svg),u.node().setAttributeNS(o.xmlns,"xmlns:xlink",o.xlink);var x=(new window.XMLSerializer).serializeToString(u.node());return x=i.util.html_entity_decode(x),x=i.util.xml_entity_encode(x)}},{"../constants/xmlns_namespaces":338,"../plotly":366,d3:70}],424:[function(t,e,r){"use strict";var n=t("../../lib").mergeArray;e.exports=function(t){var e=t[0].trace,r=e.marker,i=r.line;n(e.text,t,"tx"),n(r.opacity,t,"mo"),n(r.color,t,"mc"),n(i.color,t,"mlc"),n(i.width,t,"mlw")}},{"../../lib":349}],425:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=n.marker,a=i.line;e.exports={x:n.x,x0:n.x0,dx:n.dx,y:n.y,y0:n.y0,dy:n.dy,text:n.text,orientation:{valType:"enumerated",values:["v","h"]},marker:{color:i.color,colorscale:i.colorscale,cauto:i.cauto,cmax:i.cmax,cmin:i.cmin,autocolorscale:i.autocolorscale,reversescale:i.reversescale,showscale:i.showscale,line:{color:a.color,colorscale:a.colorscale,cauto:a.cauto,cmax:a.cmax,cmin:a.cmin,width:a.width,autocolorscale:a.autocolorscale,reversescale:a.reversescale}},r:n.r,t:n.t,_nestedModules:{error_y:"ErrorBars",error_x:"ErrorBars","marker.colorbar":"Colorbar"},_deprecated:{bardir:{valType:"enumerated",values:["v","h"]}}}},{"../scatter/attributes":502}],426:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../plots/cartesian/axes"),a=t("../../components/colorscale/has_colorscale"),o=t("../../components/colorscale/calc");e.exports=function(t,e){var r,s,l,u=i.getFromId(t,e.xaxis||"x"),c=i.getFromId(t,e.yaxis||"y"),h=e.orientation||(e.x&&!e.y?"h":"v");"h"===h?(s=u.makeCalcdata(e,"x"),r=c.makeCalcdata(e,"y")):(s=c.makeCalcdata(e,"y"),r=u.makeCalcdata(e,"x"));var f=Math.min(r.length,s.length),d=[];for(l=0;f>l;l++)n(r[l])&&n(s[l])&&d.push({p:r[l],s:s[l],b:0});return a(e,"marker")&&o(e,e.marker.color,"marker","c"),a(e,"marker.line")&&o(e,e.marker.line.color,"marker.line","c"),d}},{"../../components/colorscale/calc":306,"../../components/colorscale/has_colorscale":311,"../../plots/cartesian/axes":369,"fast-isnumeric":74}],427:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("../scatter/xy_defaults"),o=t("../bar/style_defaults"),s=t("../../components/errorbars/defaults"),l=t("./attributes");e.exports=function(t,e,r,u){function c(r,i){return n.coerce(t,e,l,r,i)}var h=a(t,e,c);return h?(c("orientation",e.x&&!e.y?"h":"v"),c("text"),o(t,e,c,r,u),s(t,e,i.defaultLine,{axis:"y"}),void s(t,e,i.defaultLine,{axis:"x",inherit:"y"})):void(e.visible=!1)}},{"../../components/color":299,"../../components/errorbars/defaults":322,"../../lib":349,"../bar/style_defaults":435,"../scatter/xy_defaults":522,"./attributes":425}],428:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/graph_interact"),i=t("../../components/errorbars"),a=t("../../components/color");e.exports=function(t,e,r,o){var s,l=t.cd,u=l[0].trace,c=l[0].t,h=t.xa,f=t.ya,d="closest"===o?c.barwidth/2:c.dbar*(1-h._td._fullLayout.bargap)/2;s="closest"!==o?function(t){return t.p}:"h"===u.orientation?function(t){return t.y}:function(t){return t.x};var p,g;"h"===u.orientation?(p=function(t){return n.inbox(t.b-e,t.x-e)+(t.x-e)/(t.x-t.b)},g=function(t){var e=s(t)-r;return n.inbox(e-d,e+d)}):(g=function(t){return n.inbox(t.b-r,t.y-r)+(t.y-r)/(t.y-t.b)},p=function(t){var r=s(t)-e;return n.inbox(r-d,r+d)});var v=n.getDistanceFunction(o,p,g);if(n.getClosest(l,v,t),t.index!==!1){var m=l[t.index],y=m.mcc||u.marker.color,b=m.mlcc||u.marker.line.color,x=m.mlw||u.marker.line.width;return a.opacity(y)?t.color=y:a.opacity(b)&&x&&(t.color=b),"h"===u.orientation?(t.x0=t.x1=h.c2p(m.x,!0),t.xLabelVal=m.s,t.y0=f.c2p(s(m)-d,!0),t.y1=f.c2p(s(m)+d,!0),t.yLabelVal=m.p):(t.y0=t.y1=f.c2p(m.y,!0),t.yLabelVal=m.s,t.x0=h.c2p(s(m)-d,!0),t.x1=h.c2p(s(m)+d,!0),t.xLabelVal=m.p),m.tx&&(t.text=m.tx),i.hoverInfo(m,u,t),[t]}}},{"../../components/color":299,"../../components/errorbars":323,"../../plots/cartesian/graph_interact":374}],429:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("./layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.calc=t("./calc"),n.setPositions=t("./set_positions"),n.colorbar=t("../scatter/colorbar"),n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.moduleType="trace",n.name="bar",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","bar","oriented","markerColorscale","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":375,"../scatter/colorbar":505,"./arrays_to_calcdata":424,"./attributes":425,"./calc":426,"./defaults":427,"./hover":428,"./layout_attributes":430,"./layout_defaults":431,"./plot":432,"./set_positions":433,"./style":434}],430:[function(t,e,r){"use strict";e.exports={barmode:{valType:"enumerated",values:["stack","group","overlay"],dflt:"group"},barnorm:{valType:"enumerated",values:["","fraction","percent"],dflt:""},bargap:{valType:"number",min:0,max:1},bargroupgap:{valType:"number",min:0,max:1,dflt:0}}},{}],431:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./layout_attributes");e.exports=function(t,e,r){function s(r,n){return a.coerce(t,e,o,r,n)}for(var l=!1,u=!1,c=!1,h={},f=0;f<r.length;f++){var d=r[f];if(n.traceIs(d,"bar")){if(l=!0,"overlay"!==t.barmode&&"stack"!==t.barmode){var p=d.xaxis+d.yaxis;h[p]&&(c=!0),h[p]=!0}if(d.visible&&"histogram"===d.type){var g=i.getFromId({_fullLayout:e},d["v"===d.orientation?"xaxis":"yaxis"]);"category"!==g.type&&(u=!0)}}}if(l){var v=s("barmode");"overlay"!==v&&s("barnorm"),s("bargap",u&&!c?0:.2),s("bargroupgap")}}},{"../../lib":349,"../../plots/cartesian/axes":369,"../../plots/plots":413,"./layout_attributes":430}],432:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../components/color"),s=t("./arrays_to_calcdata");e.exports=function(t,e,r){var l=e.x(),u=e.y(),c=t._fullLayout,h=e.plot.select(".barlayer").selectAll("g.trace.bars").data(r).enter().append("g").attr("class","trace bars");h.append("g").attr("class","points").each(function(e){var r=e[0].t,h=e[0].trace;s(e),n.select(this).selectAll("path").data(a.identity).enter().append("path").each(function(e){function a(t){return 0===c.bargap&&0===c.bargroupgap?n.round(Math.round(t)-m,2):t}function s(t,e){return Math.abs(t-e)>=2?a(t):t>e?Math.ceil(t):Math.floor(t)}var f,d,p,g;if("h"===h.orientation?(p=u.c2p(r.poffset+e.p,!0),g=u.c2p(r.poffset+e.p+r.barwidth,!0),f=l.c2p(e.b,!0),d=l.c2p(e.s+e.b,!0)):(f=l.c2p(r.poffset+e.p,!0),d=l.c2p(r.poffset+e.p+r.barwidth,!0),g=u.c2p(e.s+e.b,!0),p=u.c2p(e.b,!0)),!(i(f)&&i(d)&&i(p)&&i(g)&&f!==d&&p!==g))return void n.select(this).remove();var v=(e.mlw+1||h.marker.line.width+1||(e.trace?e.trace.marker.line.width:0)+1)-1,m=n.round(v/2%1,2);if(!t._context.staticPlot){var y=o.opacity(e.mc||h.marker.color),b=1>y||v>.01?a:s;f=b(f,d),d=b(d,f),p=b(p,g),g=b(g,p)}n.select(this).attr("d","M"+f+","+p+"V"+g+"H"+d+"V"+p+"Z")})})}},{"../../components/color":299,"../../lib":349,"./arrays_to_calcdata":424,d3:70,"fast-isnumeric":74}],433:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../plots/plots"),a=t("../../plots/cartesian/axes"),o=t("../../lib");e.exports=function(t,e){var r,s,l=t._fullLayout,u=e.x(),c=e.y();["v","h"].forEach(function(h){function f(e){function r(t){t[p]=t.p+f}var n=[];e.forEach(function(e){t.calcdata[e].forEach(function(t){n.push(t.p)})});var i=o.distinctVals(n),s=i.vals,u=i.minDiff,c=!1,h=[];"group"===l.barmode&&e.forEach(function(e){c||(t.calcdata[e].forEach(function(t){c||h.forEach(function(e){Math.abs(t.p-e)<u&&(c=!0)})}),c||t.calcdata[e].forEach(function(t){h.push(t.p)}))}),a.minDtick(v,u,s[0],c),a.expand(v,s,{vpad:u/2}),u*=1-l.bargap,c&&(u/=d.length);for(var f,g=0;g<e.length;g++){var m=t.calcdata[e[g]][0].t;m.barwidth=u*(1-l.bargroupgap),m.poffset=((c?(2*g+1-e.length)*u:0)-m.barwidth)/2,m.dbar=i.minDiff,f=m.poffset+m.barwidth/2,t.calcdata[e[g]].forEach(r)}}var d=[],p={v:"x",h:"y"}[h],g={v:"y",h:"x"}[h],v=e[p](),m=e[g]();if(t._fullData.forEach(function(t,e){t.visible===!0&&i.traceIs(t,"bar")&&t.orientation===h&&t.xaxis===u._id&&t.yaxis===c._id&&d.push(e)}),d.length){"overlay"===l.barmode?d.forEach(function(t){f([t])}):f(d);var y="stack"===l.barmode,b=l.barnorm;if(y||b){var x,_,w,A=m.l2c(m.c2l(0)),k=A,M={},T=t.calcdata[d[0]][0].t.barwidth/100,E=0,L=!0;for(r=0;r<d.length;r++)for(_=t.calcdata[d[r]],s=0;s<_.length;s++){E=Math.round(_[s].p/T);var S=M[E]||0;y&&(_[s].b=S),x=_[s].b+_[s].s,M[E]=S+_[s].s,y&&(_[s][g]=x,!b&&n(m.c2l(x))&&(A=Math.max(A,x),k=Math.min(k,x)))}if(b){L=!1;var C="fraction"===b?1:100,P=C/1e9;for(k=0,A=y?C:0,r=0;r<d.length;r++)for(_=t.calcdata[d[r]],s=0;s<_.length;s++)w=C/M[Math.round(_[s].p/T)],_[s].b*=w,_[s].s*=w,x=_[s].b+_[s].s,_[s][g]=x,n(m.c2l(x))&&(k-P>x&&(L=!0,k=x),x>A+P&&(L=!0,A=x))}a.expand(m,[k,A],{tozero:!0,padded:L
+})}else{var z=function(t){return t[g]=t.s,t.s};for(r=0;r<d.length;r++)a.expand(m,t.calcdata[d[r]].map(z),{tozero:!0,padded:!0})}}})}},{"../../lib":349,"../../plots/cartesian/axes":369,"../../plots/plots":413,"fast-isnumeric":74}],434:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/color"),a=t("../../components/drawing");e.exports=function(t){var e=n.select(t).selectAll("g.trace.bars"),r=e.size(),o=t._fullLayout;e.style("opacity",function(t){return t[0].trace.opacity}).each(function(t){("stack"===o.barmode&&r>1||0===o.bargap&&0===o.bargroupgap&&!t[0].trace.marker.line.width)&&n.select(this).attr("shape-rendering","crispEdges")}),e.selectAll("g.points").each(function(t){var e=t[0].trace,r=e.marker,o=r.line,s=(e._input||{}).marker||{},l=a.tryColorscale(r,s,""),u=a.tryColorscale(r,s,"line.");n.select(this).selectAll("path").each(function(t){var e,a,s=(t.mlw+1||o.width+1)-1,c=n.select(this);e="mc"in t?t.mcc=l(t.mc):Array.isArray(r.color)?i.defaultLine:r.color,c.style("stroke-width",s+"px").call(i.fill,e),s&&(a="mlc"in t?t.mlcc=u(t.mlc):Array.isArray(o.color)?i.defaultLine:o.color,c.call(i.stroke,a))})})}},{"../../components/color":299,"../../components/drawing":317,d3:70}],435:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/defaults");e.exports=function(t,e,r,o,s){r("marker.color",o),i(t,"marker")&&a(t,e,s,r,{prefix:"marker.",cLetter:"c"}),r("marker.line.color",n.defaultLine),i(t,"marker.line")&&a(t,e,s,r,{prefix:"marker.line.",cLetter:"c"}),r("marker.line.width")}},{"../../components/color":299,"../../components/colorscale/defaults":308,"../../components/colorscale/has_colorscale":311}],436:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/color/attributes"),a=t("../../lib/extend").extendFlat,o=n.marker,s=o.line;e.exports={y:{valType:"data_array"},x:{valType:"data_array"},x0:{valType:"any"},y0:{valType:"any"},whiskerwidth:{valType:"number",min:0,max:1,dflt:.5},boxpoints:{valType:"enumerated",values:["all","outliers","suspectedoutliers",!1],dflt:"outliers"},boxmean:{valType:"enumerated",values:[!0,"sd",!1],dflt:!1},jitter:{valType:"number",min:0,max:1},pointpos:{valType:"number",min:-2,max:2},orientation:{valType:"enumerated",values:["v","h"]},marker:{outliercolor:{valType:"color",dflt:"rgba(0, 0, 0, 0)"},symbol:a({},o.symbol,{arrayOk:!1}),opacity:a({},o.opacity,{arrayOk:!1,dflt:1}),size:a({},o.size,{arrayOk:!1}),color:a({},o.color,{arrayOk:!1}),line:{color:a({},s.color,{arrayOk:!1,dflt:i.defaultLine}),width:a({},s.width,{arrayOk:!1,dflt:0}),outliercolor:{valType:"color"},outlierwidth:{valType:"number",min:0,dflt:1}}},line:{color:{valType:"color"},width:{valType:"number",min:0,dflt:2}},fillcolor:n.fillcolor}},{"../../components/color/attributes":298,"../../lib/extend":345,"../scatter/attributes":502}],437:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../plots/cartesian/axes");e.exports=function(t,e){function r(t,e,r,a,o){var s;return r in e?p=a.makeCalcdata(e,r):(s=r+"0"in e?e[r+"0"]:"name"in e&&("category"===a.type||n(e.name)&&-1!==["linear","log"].indexOf(a.type)||i.isDateTime(e.name)&&"date"===a.type)?e.name:t.numboxes,s=a.d2c(s),p=o.map(function(){return s})),p}function o(t,e,r,a,o){var s,l,u,c,h=a.length,f=e.length,d=[],p=[];for(s=0;h>s;++s)l=a[s],t[s]={pos:l},p[s]=l-o,d[s]=[];for(p.push(a[h-1]+o),s=0;f>s;++s)c=e[s],n(c)&&(u=i.findBin(r[s],p),u>=0&&f>u&&d[u].push(c));return d}function s(t,e){var r,n,a,o;for(o=0;o<e.length;++o)r=e[o].sort(i.sorterAsc),n=r.length,a=t[o],a.val=r,a.min=r[0],a.max=r[n-1],a.mean=i.mean(r,n),a.sd=i.stdev(r,n,a.mean),a.q1=i.interp(r,.25),a.med=i.interp(r,.5),a.q3=i.interp(r,.75),a.lf=Math.min(a.q1,r[Math.min(i.findBin(2.5*a.q1-1.5*a.q3,r,!0)+1,n-1)]),a.uf=Math.max(a.q3,r[Math.max(i.findBin(2.5*a.q3-1.5*a.q1,r),0)]),a.lo=4*a.q1-3*a.q3,a.uo=4*a.q3-3*a.q1}var l,u,c,h,f,d,p,g,v,m=a.getFromId(t,e.xaxis||"x"),y=a.getFromId(t,e.yaxis||"y"),b=e.orientation,x=[];"h"===b?(l=m,u="x",f=y,d="y"):(l=y,u="y",f=m,d="x"),c=l.makeCalcdata(e,u),a.expand(l,c,{padded:!0}),p=r(t,e,d,f,c);var _=i.distinctVals(p);return g=_.vals,v=_.minDiff/2,h=o(x,c,p,g,v),s(x,h),x=x.filter(function(t){return t.val&&t.val.length}),x.length?(x[0].t={boxnum:t.numboxes,dPos:v},t.numboxes++,x):[{t:{emptybox:!0}}]}},{"../../lib":349,"../../plots/cartesian/axes":369,"fast-isnumeric":74}],438:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("./attributes");e.exports=function(t,e,r){function o(r,i){return n.coerce(t,e,a,r,i)}var s,l=o("y"),u=o("x");if(l&&l.length)s="v",u||o("x0");else{if(!u||!u.length)return void(e.visible=!1);s="h",o("y0")}o("orientation",s),o("line.color",(t.marker||{}).color||r),o("line.width",2),o("fillcolor",i.addOpacity(e.line.color,.5)),o("whiskerwidth"),o("boxmean");var c=n.coerce2(t,e,a,"marker.outliercolor"),h=o("marker.line.outliercolor"),f=c||h?o("boxpoints","suspectedoutliers"):o("boxpoints");f&&(o("jitter","all"===f?.3:0),o("pointpos","all"===f?-1.5:0),o("marker.symbol"),o("marker.opacity"),o("marker.size"),o("marker.color",e.line.color),o("marker.line.color"),o("marker.line.width"),"suspectedoutliers"===f&&(o("marker.line.outliercolor",e.marker.color),o("marker.line.outlierwidth")))}},{"../../components/color":299,"../../lib":349,"./attributes":436}],439:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../../plots/cartesian/graph_interact"),a=t("../../lib"),o=t("../../components/color");e.exports=function(t,e,r,s){var l,u,c,h,f,d,p,g,v,m=t.cd,y=m[0].trace,b=m[0].t,x=t.xa,_=t.ya,w=[];if(h="closest"===s?2.5*b.bdPos:b.bdPos,"h"===y.orientation?(l=function(t){return i.inbox(t.min-e,t.max-e)},u=function(t){var e=t.pos+b.bPos-r;return i.inbox(e-h,e+h)},f="y",d=_,g="x",v=x):(l=function(t){var r=t.pos+b.bPos-e;return i.inbox(r-h,r+h)},u=function(t){return i.inbox(t.min-r,t.max-r)},f="x",d=x,g="y",v=_),c=i.getDistanceFunction(s,l,u),i.getClosest(m,c,t),t.index!==!1){var A=m[t.index],k=y.line.color,M=(y.marker||{}).color;o.opacity(k)&&y.line.width?t.color=k:o.opacity(M)&&y.boxpoints?t.color=M:t.color=y.fillcolor,t[f+"0"]=d.c2p(A.pos+b.bPos-b.bdPos,!0),t[f+"1"]=d.c2p(A.pos+b.bPos+b.bdPos,!0),n.tickText(d,d.c2l(A.pos),"hover").text,t[f+"LabelVal"]=A.pos;var T,E,L={},S=["med","min","q1","q3","max"];y.boxmean&&S.push("mean"),y.boxpoints&&[].push.apply(S,["lf","uf"]);for(var C=0;C<S.length;C++)T=S[C],T in A&&!(A[T]in L)&&(L[A[T]]=!0,p=v.c2p(A[T],!0),E=a.extendFlat({},t),E[g+"0"]=E[g+"1"]=p,E[g+"LabelVal"]=A[T],E.attr=T,"mean"===T&&"sd"in A&&"sd"===y.boxmean&&(E[g+"err"]=A.sd),t.name="",w.push(E));return w}}},{"../../components/color":299,"../../lib":349,"../../plots/cartesian/axes":369,"../../plots/cartesian/graph_interact":374}],440:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("./layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.calc=t("./calc"),n.setPositions=t("./set_positions"),n.plot=t("./plot"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.moduleType="trace",n.name="box",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","symbols","oriented","box","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":375,"./attributes":436,"./calc":437,"./defaults":438,"./hover":439,"./layout_attributes":441,"./layout_defaults":442,"./plot":443,"./set_positions":444,"./style":445}],441:[function(t,e,r){"use strict";e.exports={boxmode:{valType:"enumerated",values:["group","overlay"],dflt:"overlay"},boxgap:{valType:"number",min:0,max:1,dflt:.3},boxgroupgap:{valType:"number",min:0,max:1,dflt:.3}}},{}],442:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("../../lib"),a=t("./layout_attributes");e.exports=function(t,e,r){function o(r,n){return i.coerce(t,e,a,r,n)}for(var s,l=0;l<r.length;l++)if(n.traceIs(r[l],"box")){s=!0;break}s&&(o("boxmode"),o("boxgap"),o("boxgroupgap"))}},{"../../lib":349,"../../plots/plots":413,"./layout_attributes":441}],443:[function(t,e,r){"use strict";function n(){l=2e9}function i(){var t=l;return l=(69069*l+1)%4294967296,Math.abs(l-t)<429496729?i():l/4294967296}var a=t("d3"),o=t("../../lib"),s=t("../../components/drawing"),l=2e9,u=5,c=.01;e.exports=function(t,e,r){var l,h,f=t._fullLayout,d=e.x(),p=e.y(),g=e.plot.select(".boxlayer").selectAll("g.trace.boxes").data(r).enter().append("g").attr("class","trace boxes");g.each(function(e){var r=e[0].t,g=e[0].trace,v="group"===f.boxmode&&t.numboxes>1,m=r.dPos*(1-f.boxgap)*(1-f.boxgroupgap)/(v?t.numboxes:1),y=v?2*r.dPos*(-.5+(r.boxnum+.5)/t.numboxes)*(1-f.boxgap):0,b=m*g.whiskerwidth;return g.visible!==!0||r.emptybox?void a.select(this).remove():("h"===g.orientation?(l=p,h=d):(l=d,h=p),r.bPos=y,r.bdPos=m,n(),a.select(this).selectAll("path.box").data(o.identity).enter().append("path").attr("class","box").each(function(t){var e=l.c2p(t.pos+y,!0),r=l.c2p(t.pos+y-m,!0),n=l.c2p(t.pos+y+m,!0),i=l.c2p(t.pos+y-b,!0),s=l.c2p(t.pos+y+b,!0),u=h.c2p(t.q1,!0),c=h.c2p(t.q3,!0),f=o.constrain(h.c2p(t.med,!0),Math.min(u,c)+1,Math.max(u,c)-1),d=h.c2p(g.boxpoints===!1?t.min:t.lf,!0),p=h.c2p(g.boxpoints===!1?t.max:t.uf,!0);"h"===g.orientation?a.select(this).attr("d","M"+f+","+r+"V"+n+"M"+u+","+r+"V"+n+"H"+c+"V"+r+"ZM"+u+","+e+"H"+d+"M"+c+","+e+"H"+p+(0===g.whiskerwidth?"":"M"+d+","+i+"V"+s+"M"+p+","+i+"V"+s)):a.select(this).attr("d","M"+r+","+f+"H"+n+"M"+r+","+u+"H"+n+"V"+c+"H"+r+"ZM"+e+","+u+"V"+d+"M"+e+","+c+"V"+p+(0===g.whiskerwidth?"":"M"+i+","+d+"H"+s+"M"+i+","+p+"H"+s))}),g.boxpoints&&a.select(this).selectAll("g.points").data(function(t){return t.forEach(function(t){t.t=r,t.trace=g}),t}).enter().append("g").attr("class","points").selectAll("path").data(function(t){var e,r,n,a,s,l,h,f="all"===g.boxpoints?t.val:t.val.filter(function(e){return e<t.lf||e>t.uf}),d=(t.q3-t.q1)*c,p=[],v=0;if(g.jitter){for(e=0;e<f.length;e++)r=Math.max(0,e-u),a=f[r],n=Math.min(f.length-1,e+u),s=f[n],"all"!==g.boxpoints&&(f[e]<t.lf?s=Math.min(s,t.lf):a=Math.max(a,t.uf)),l=Math.sqrt(d*(n-r)/(s-a))||0,l=o.constrain(Math.abs(l),0,1),p.push(l),v=Math.max(l,v);h=2*g.jitter/v}return f.map(function(e,r){var n,a=g.pointpos;return g.jitter&&(a+=h*p[r]*(i()-.5)),n="h"===g.orientation?{y:t.pos+a*m+y,x:e}:{x:t.pos+a*m+y,y:e},"suspectedoutliers"===g.boxpoints&&e<t.uo&&e>t.lo&&(n.so=!0),n})}).enter().append("path").call(s.translatePoints,d,p),void(g.boxmean&&a.select(this).selectAll("path.mean").data(o.identity).enter().append("path").attr("class","mean").style("fill","none").each(function(t){var e=l.c2p(t.pos+y,!0),r=l.c2p(t.pos+y-m,!0),n=l.c2p(t.pos+y+m,!0),i=h.c2p(t.mean,!0),o=h.c2p(t.mean-t.sd,!0),s=h.c2p(t.mean+t.sd,!0);"h"===g.orientation?a.select(this).attr("d","M"+i+","+r+"V"+n+("sd"!==g.boxmean?"":"m0,0L"+o+","+e+"L"+i+","+r+"L"+s+","+e+"Z")):a.select(this).attr("d","M"+r+","+i+"H"+n+("sd"!==g.boxmean?"":"m0,0L"+e+","+o+"L"+r+","+i+"L"+e+","+s+"Z"))})))})}},{"../../components/drawing":317,"../../lib":349,d3:70}],444:[function(t,e,r){"use strict";var n=t("../../plots/plots"),i=t("../../plots/cartesian/axes"),a=t("../../lib");e.exports=function(t,e){var r,o,s,l,u=t._fullLayout,c=e.x(),h=e.y(),f=["v","h"];for(o=0;o<f.length;++o){var d,p,g,v=f[o],m=[],y=[],b=0,x=0;for(r="h"===v?h:c,s=0;s<t.calcdata.length;++s)d=t.calcdata[s],p=d[0].t,g=d[0].trace,g.visible===!0&&n.traceIs(g,"box")&&!p.emptybox&&g.orientation===v&&g.xaxis===c._id&&g.yaxis===h._id&&(m.push(s),g.boxpoints!==!1&&(b=Math.max(b,g.jitter-g.pointpos-1),x=Math.max(x,g.jitter+g.pointpos-1)));for(s=0;s<m.length;s++)for(d=t.calcdata[m[s]],l=0;l<d.length;l++)y.push(d[l].pos);if(y.length){var _=a.distinctVals(y),w=_.minDiff/2;for(y.length===_.vals.length&&(t.numboxes=1),i.minDtick(r,_.minDiff,_.vals[0],!0),o=0;o<m.length;++o)t.calcdata[o][0].t.dPos=w;var A=(1-u.boxgap)*(1-u.boxgroupgap)*w/t.numboxes;i.expand(r,_.vals,{vpadminus:w+b*A,vpadplus:w+x*A})}}}},{"../../lib":349,"../../plots/cartesian/axes":369,"../../plots/plots":413}],445:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/color"),a=t("../../components/drawing");e.exports=function(t){var e=n.select(t).selectAll("g.trace.boxes");e.style("opacity",function(t){return t[0].trace.opacity}).each(function(t){var e=t[0].trace,r=e.line.width;n.select(this).selectAll("path.box").style("stroke-width",r+"px").call(i.stroke,e.line.color).call(i.fill,e.fillcolor),n.select(this).selectAll("path.mean").style({"stroke-width":r,"stroke-dasharray":2*r+"px,"+r+"px"}).call(i.stroke,e.line.color),n.select(this).selectAll("g.points path").call(a.pointStyle,e)})}},{"../../components/color":299,"../../components/drawing":317,d3:70}],446:[function(t,e,r){"use strict";var n=t("../scattergeo/attributes"),i=t("../../components/colorscale/attributes"),a=t("../../plots/attributes"),o=t("../../lib/extend").extendFlat,s=n.marker.line;e.exports={locations:{valType:"data_array"},locationmode:n.locationmode,z:{valType:"data_array"},text:{valType:"data_array"},marker:{line:{color:s.color,width:s.width}},zauto:i.zauto,zmin:i.zmin,zmax:i.zmax,colorscale:i.colorscale,autocolorscale:i.autocolorscale,reversescale:i.reversescale,showscale:i.showscale,hoverinfo:o({},a.hoverinfo,{flags:["location","z","text","name"]}),_nestedModules:{colorbar:"Colorbar"}}},{"../../components/colorscale/attributes":305,"../../lib/extend":345,"../../plots/attributes":367,"../scattergeo/attributes":529}],447:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/colorscale/defaults"),a=t("./attributes");e.exports=function(t,e,r,o){function s(r,i){return n.coerce(t,e,a,r,i)}var l,u=s("locations");if(u&&(l=u.length),!u||!l)return void(e.visible=!1);var c=s("z");return Array.isArray(c)?(c.length>l&&(e.z=c.slice(0,l)),s("locationmode"),s("text"),s("marker.line.color"),s("marker.line.width"),i(t,e,o,s,{prefix:"",cLetter:"z"}),void s("hoverinfo",1===o._dataLength?"location+z+text":void 0)):void(e.visible=!1)}},{"../../components/colorscale/defaults":308,"../../lib":349,"./attributes":446}],448:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../heatmap/colorbar"),n.calc=t("../surface/calc"),n.plot=t("./plot").plot,n.moduleType="trace",n.name="choropleth",n.basePlotModule=t("../../plots/geo"),n.categories=["geo","noOpacity"],n.meta={},e.exports=n},{"../../plots/geo":385,"../heatmap/colorbar":461,"../surface/calc":539,"./attributes":446,"./defaults":447,"./plot":449}],449:[function(t,e,r){"use strict";function n(t,e){function r(e){var r=t.mockAxis;return o.tickText(r,r.c2l(e),"hover").text}var n=e.hoverinfo;if("none"===n)return function(t){delete t.nameLabel,delete t.textLabel};var i="all"===n?v.hoverinfo.flags:n.split("+"),a=-1!==i.indexOf("name"),s=-1!==i.indexOf("location"),l=-1!==i.indexOf("z"),u=-1!==i.indexOf("text"),c=!a&&s;return function(t){var n=[];c?t.nameLabel=t.id:(a&&(t.nameLabel=e.name),s&&n.push(t.id)),l&&n.push(r(t.z)),u&&n.push(t.tx),t.textLabel=n.join("<br>")}}function i(t){return function(e,r){return{points:[{data:t._input,fullData:t,curveNumber:t.index,pointNumber:r,location:e.id,z:e.z}]}}}var a=t("d3"),o=t("../../plots/cartesian/axes"),s=t("../../plots/cartesian/graph_interact"),l=t("../../components/color"),u=t("../../components/drawing"),c=t("../../components/colorscale/get_scale"),h=t("../../components/colorscale/make_scale_function"),f=t("../../lib/topojson_utils").getTopojsonFeatures,d=t("../../lib/geo_location_utils").locationToFeature,p=t("../../lib/array_to_calc_item"),g=t("../../constants/geo_constants"),v=t("./attributes"),m=e.exports={};m.calcGeoJSON=function(t,e){for(var r,n=[],i=t.locations,a=i.length,o=f(t,e),s=(t.marker||{}).line||{},l=0;a>l;l++)r=d(t.locationmode,i[l],o),void 0!==r&&(r.z=t.z[l],void 0!==t.text&&(r.tx=t.text[l]),p(s.color,r,"mlc",l),p(s.width,r,"mlw",l),n.push(r));return n.length>0&&(n[0].trace=t),n},m.plot=function(t,e,r){var o,l=t.framework,u=l.select("g.choroplethlayer"),c=l.select("g.baselayer"),h=l.select("g.baselayeroverchoropleth"),f=g.baseLayersOverChoropleth,d=u.selectAll("g.trace.choropleth").data(e,function(t){return t.uid});d.enter().append("g").attr("class","trace choropleth"),d.exit().remove(),d.each(function(e){function r(e,r){if(t.showHover){var n=t.projection(e.properties.ct);u(e),s.loneHover({x:n[0],y:n[1],name:e.nameLabel,text:e.textLabel},{container:t.hoverContainer.node()}),t.graphDiv.emit("plotly_hover",c(e,r))}}function o(e,r){t.graphDiv.emit("plotly_click",c(e,r))}var l=m.calcGeoJSON(e,t.topojson),u=n(t,e),c=i(e);a.select(this).selectAll("path.choroplethlocation").data(l).enter().append("path").attr("class","choroplethlocation").on("mouseover",r).on("click",o).on("mouseout",function(){s.loneUnhover(t.hoverContainer)}).on("mousedown",function(){s.loneUnhover(t.hoverContainer)}).on("mouseup",r)}),h.selectAll("*").remove();for(var p=0;p<f.length;p++)o=f[p],c.select("g."+o).remove(),t.drawTopo(h,o,r),t.styleLayer(h,o,r);m.style(t)},m.style=function(t){t.framework.selectAll("g.trace.choropleth").each(function(t){var e=a.select(this),r=t.marker||{},n=r.line||{},i=t.zmin,o=t.zmax,s=c(t.colorscale),f=h(s,i,o);e.selectAll("path.choroplethlocation").each(function(t){a.select(this).attr("fill",function(t){return f(t.z)}).call(l.stroke,t.mlc||n.color).call(u.dashLine,"",t.mlw||n.width)})})}},{"../../components/color":299,"../../components/colorscale/get_scale":310,"../../components/colorscale/make_scale_function":315,"../../components/drawing":317,"../../constants/geo_constants":334,"../../lib/array_to_calc_item":341,"../../lib/geo_location_utils":346,"../../lib/topojson_utils":361,"../../plots/cartesian/axes":369,"../../plots/cartesian/graph_interact":374,"./attributes":446,d3:70}],450:[function(t,e,r){"use strict";var n=t("../heatmap/attributes"),i=t("../scatter/attributes"),a=t("../../lib/extend").extendFlat,o=i.line;e.exports={z:n.z,x:n.x,x0:n.x0,dx:n.dx,y:n.y,y0:n.y0,dy:n.dy,text:n.text,transpose:n.transpose,xtype:n.xtype,ytype:n.ytype,zauto:n.zauto,zmin:n.zmin,zmax:n.zmax,colorscale:n.colorscale,autocolorscale:n.autocolorscale,reversescale:n.reversescale,showscale:n.showscale,connectgaps:n.connectgaps,autocontour:{valType:"boolean",dflt:!0},ncontours:{valType:"integer",dflt:0},contours:{start:{valType:"number",dflt:null},end:{valType:"number",dflt:null},size:{valType:"number",dflt:null},coloring:{valType:"enumerated",values:["fill","heatmap","lines","none"],dflt:"fill"},showlines:{valType:"boolean",dflt:!0}},line:{color:a({},o.color,{}),width:o.width,dash:o.dash,smoothing:a({},o.smoothing,{})},_nestedModules:{colorbar:"Colorbar"}}},{"../../lib/extend":345,"../heatmap/attributes":459,"../scatter/attributes":502}],451:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes"),i=t("../heatmap/calc");e.exports=function(t,e){var r=i(t,e),a=e.contours;if(e.autocontour!==!1){var o={type:"linear",range:[e.zmin,e.zmax]};n.autoTicks(o,(e.zmax-e.zmin)/(e.ncontours||15)),a.start=n.tickFirst(o),a.size=o.dtick,o.range.reverse(),a.end=n.tickFirst(o),a.start===e.zmin&&(a.start+=a.size),a.end===e.zmax&&(a.end-=a.size),a.end+=a.size/100,e._input.contours=a}return r}},{"../../plots/cartesian/axes":369,"../heatmap/calc":460}],452:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../plots/plots"),a=t("../../components/colorscale/get_scale"),o=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,s="cb"+r.uid;if(t._fullLayout._infolayer.selectAll("."+s).remove(),r.showscale===!1)return void i.autoMargin(t,s);var l=o(t,s);e[0].t.cb=l;var u=r.contours,c=r.line,h=u.size||1,f=Math.floor((u.end+h/10-u.start)/h)+1,d=a(r.colorscale),p="lines"===u.coloring?0:1,g=n.scale.linear().interpolate(n.interpolateRgb),v=d.map(function(t){return(t[0]*(f+p-1)-p/2)*h+u.start}),m=d.map(function(t){return t[1]});if("heatmap"===u.coloring){r.zauto&&r.autocontour===!1&&(r.zmin=u.start-h/2,r.zmax=r.zmin+f*h),l.filllevels({start:r.zmin,end:r.zmax,size:(r.zmax-r.zmin)/254}),v=d.map(function(t){return t[0]*(r.zmax-r.zmin)+r.zmin});var y=n.extent([r.zmin,r.zmax,u.start,u.start+h*(f-1)]),b=y[r.zmin<r.zmax?0:1],x=y[r.zmin<r.zmax?1:0];b!==r.zmin&&(v.splice(0,0,b),m.splice(0,0,m[0])),x!==r.zmax&&(v.push(x),m.push(m[m.length-1]))}g.domain(v).range(m),l.fillcolor("fill"===u.coloring||"heatmap"===u.coloring?g:"").line({color:"lines"===u.coloring?g:c.color,width:u.showlines!==!1?c.width:0,dash:c.dash}).levels({start:u.start,end:u.end,size:h}).options(r.colorbar)()}},{"../../components/colorbar/draw":302,"../../components/colorscale/get_scale":310,"../../plots/plots":413,d3:70}],453:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../heatmap/has_columns"),a=t("../heatmap/xyz_defaults"),o=t("../contour/style_defaults"),s=t("./attributes");e.exports=function(t,e,r,l){function u(r,i){return n.coerce(t,e,s,r,i)}var c=a(t,e,u);if(!c)return void(e.visible=!1);u("text"),u("connectgaps",i(e));var h=n.coerce2(t,e,s,"contours.start"),f=n.coerce2(t,e,s,"contours.end"),d=u("autocontour",!(h&&f));u(d?"ncontours":"contours.size"),o(t,e,u,l)}},{"../../lib":349,"../contour/style_defaults":458,"../heatmap/has_columns":464,"../heatmap/xyz_defaults":470,"./attributes":450}],454:[function(t,e,r){"use strict";var n=t("../heatmap/hover");e.exports=function(t,e,r,i){return n(t,e,r,i,!0)}},{"../heatmap/hover":465}],455:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.colorbar=t("./colorbar"),n.hoverPoints=t("./hover"),n.moduleType="trace",n.name="contour",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","2dMap","contour"],n.meta={},e.exports=n},{"../../plots/cartesian":375,"./attributes":450,"./calc":451,"./colorbar":452,"./defaults":453,"./hover":454,"./plot":456,"./style":457}],456:[function(t,e,r){"use strict";function n(t,e,r){_.markTime("in Contour.plot");var n=r[0].trace,a=r[0].x,s=r[0].y,u=n.contours,c=n.uid,h=e.x(),f=e.y(),v=t._fullLayout,b="contour"+c,x=i(u,e,r[0]);if(n.visible!==!0)return v._paper.selectAll("."+b+",.hm"+c).remove(),void v._infolayer.selectAll(".cb"+c).remove();"heatmap"===u.coloring?(n.zauto&&n.autocontour===!1&&(n._input.zmin=n.zmin=u.start-u.size/2,n._input.zmax=n.zmax=n.zmin+x.length*u.size),A(t,e,[r])):v._paper.selectAll(".hm"+c).remove(),o(x),l(x);var w=h.c2p(a[0],!0),k=h.c2p(a[a.length-1],!0),M=f.c2p(s[0],!0),T=f.c2p(s[s.length-1],!0),E=[[w,T],[k,T],[k,M],[w,M]],L=d(e,r,b);p(L,E,u),g(L,x,E,u),m(L,x,u),y(L,e,r[0],E),_.markTime("done Contour.plot")}function i(t,e,r){for(var n=t.size||1,i=[],a=t.start;a<t.end+n/10;a+=n)i.push({level:a,crossings:{},starts:[],edgepaths:[],paths:[],xaxis:e.x(),yaxis:e.y(),x:r.x,y:r.y,z:r.z,smoothing:r.trace.line.smoothing});return i}function a(t,e){var r=(e[0][0]>t?0:1)+(e[0][1]>t?0:2)+(e[1][1]>t?0:4)+(e[1][0]>t?0:8);if(5===r||10===r){var n=(e[0][0]+e[0][1]+e[1][0]+e[1][1])/4;return t>n?5===r?713:1114:5===r?104:208}return 15===r?0:r}function o(t){var e,r,n,i,o,s,l,u,c,h=t[0].z,f=h.length,d=h[0].length,p=2===f||2===d;for(r=0;f-1>r;r++)for(i=[],0===r&&(i=i.concat(k)),r===f-2&&(i=i.concat(M)),e=0;d-1>e;e++)for(n=i.slice(),0===e&&(n=n.concat(T)),e===d-2&&(n=n.concat(E)),o=e+","+r,s=[[h[r][e],h[r][e+1]],[h[r+1][e],h[r+1][e+1]]],c=0;c<t.length;c++)u=t[c],l=a(u.level,s),l&&(u.crossings[o]=l,-1!==n.indexOf(l)&&(u.starts.push([e,r]),p&&-1!==n.indexOf(l,n.indexOf(l)+1)&&u.starts.push([e,r])))}function s(t,e,r){function n(t){return d[t%d.length]}var i,a=e.join(","),o=a,s=t.crossings[o],l=u(s,r,e),d=[f(t,e,[-l[0],-l[1]])],p=l.join(","),g=t.z.length,v=t.z[0].length;for(i=0;1e4>i;i++){if(s>20?(s=S[s][(l[0]||l[1])<0?0:1],t.crossings[o]=C[s]):delete t.crossings[o],l=L[s],!l){console.log("found bad marching index",s,e,t.level);break}if(d.push(f(t,e,l)),e[0]+=l[0],e[1]+=l[1],c(d[d.length-1],d[d.length-2])&&d.pop(),o=e.join(","),o===a&&l.join(",")===p||r&&(l[0]&&(e[0]<0||e[0]>v-2)||l[1]&&(e[1]<0||e[1]>g-2)))break;s=t.crossings[o]}1e4===i&&console.log("Infinite loop in contour?");var m,y,b,x,_,w,A,k=c(d[0],d[d.length-1]),M=0,T=.2*t.smoothing,E=[],P=0;for(i=1;i<d.length;i++)A=h(d[i],d[i-1]),M+=A,E.push(A);var z=M/E.length*T;for(i=d.length-2;i>=P;i--)if(m=E[i],z>m){for(b=0,y=i-1;y>=P&&m+E[y]<z;y--)m+=E[y];if(k&&i===d.length-2)for(b=0;y>b&&m+E[b]<z;b++)m+=E[b];_=i-y+b+1,w=Math.floor((i+y+b+2)/2),x=k||i!==d.length-2?k||-1!==y?_%2?n(w):[(n(w)[0]+n(w+1)[0])/2,(n(w)[1]+n(w+1)[1])/2]:d[0]:d[d.length-1],d.splice(y+1,i-y+1,x),i=y+1,b&&(P=b),k&&(i===d.length-2?d[b]=d[d.length-1]:0===i&&(d[d.length-1]=d[0]))}if(d.splice(0,P),!(d.length<2))if(k)d.pop(),t.paths.push(d);else{r||console.log("unclosed interior contour?",t.level,a,d.join("L"));var R=!1;t.edgepaths.forEach(function(e,r){if(!R&&c(e[0],d[d.length-1])){d.pop(),R=!0;var n=!1;t.edgepaths.forEach(function(e,i){!n&&c(e[e.length-1],d[0])&&(n=!0,d.splice(0,1),t.edgepaths.splice(r,1),i===r?t.paths.push(d.concat(e)):t.edgepaths[i]=t.edgepaths[i].concat(d,e))}),n||(t.edgepaths[r]=d.concat(e))}}),t.edgepaths.forEach(function(e,r){!R&&c(e[e.length-1],d[0])&&(d.splice(0,1),t.edgepaths[r]=e.concat(d),R=!0)}),R||t.edgepaths.push(d)}}function l(t){var e,r,n,i,a;for(n=0;n<t.length;n++){for(i=t[n],a=0;a<i.starts.length;a++)r=i.starts[a],s(i,r,"edge");for(e=0;Object.keys(i.crossings).length&&1e4>e;)e++,r=Object.keys(i.crossings)[0].split(",").map(Number),s(i,r);1e4===e&&console.log("Infinite loop in contour?")}}function u(t,e,r){var n=0,i=0;return t>20&&e?208===t||1114===t?n=0===r[0]?1:-1:i=0===r[1]?1:-1:-1!==k.indexOf(t)?i=1:-1!==T.indexOf(t)?n=1:-1!==M.indexOf(t)?i=-1:n=-1,[n,i]}function c(t,e){return Math.abs(t[0]-e[0])<.01&&Math.abs(t[1]-e[1])<.01}function h(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}function f(t,e,r){var n=e[0]+Math.max(r[0],0),i=e[1]+Math.max(r[1],0),a=t.z[i][n],o=t.xaxis,s=t.yaxis;if(r[1]){var l=(t.level-a)/(t.z[i][n+1]-a);return[o.c2p((1-l)*t.x[n]+l*t.x[n+1],!0),s.c2p(t.y[i],!0)]}var u=(t.level-a)/(t.z[i+1][n]-a);return[o.c2p(t.x[n],!0),s.c2p((1-u)*t.y[i]+u*t.y[i+1],!0)]}function d(t,e,r){var n=t.plot.select(".maplayer").selectAll("g.contour."+r).data(e);return n.enter().append("g").classed("contour",!0).classed(r,!0),n.exit().remove(),n}function p(t,e,r){var n=t.selectAll("g.contourbg").data([0]);n.enter().append("g").classed("contourbg",!0);var i=n.selectAll("path").data("fill"===r.coloring?[0]:[]);i.enter().append("path"),i.exit().remove(),i.attr("d","M"+e.join("L")+"Z").style("stroke","none")}function g(t,e,r,n){var i=t.selectAll("g.contourfill").data([0]);i.enter().append("g").classed("contourfill",!0);var a=i.selectAll("path").data("fill"===n.coloring?e:[]);a.enter().append("path"),a.exit().remove(),a.each(function(t){var e=v(t,r);e?x.select(this).attr("d",e).style("stroke","none"):x.select(this).remove()})}function v(t,e){function r(t){return Math.abs(t[1]-e[0][1])<.01}function n(t){return Math.abs(t[1]-e[2][1])<.01}function i(t){return Math.abs(t[0]-e[0][0])<.01}function a(t){return Math.abs(t[0]-e[2][0])<.01}for(var o,s,l,u,c,h,f=t.edgepaths.length||t.z[0][0]<t.level?"":"M"+e.join("L")+"Z",d=0,p=t.edgepaths.map(function(t,e){return e}),g=!0;p.length;){for(h=w.smoothopen(t.edgepaths[d],t.smoothing),f+=g?h:h.replace(/^M/,"L"),p.splice(p.indexOf(d),1),o=t.edgepaths[d][t.edgepaths[d].length-1],u=-1,l=0;4>l;l++){if(!o){console.log("missing end?",d,t);break}for(r(o)&&!a(o)?s=e[1]:i(o)?s=e[0]:n(o)?s=e[3]:a(o)&&(s=e[2]),c=0;c<t.edgepaths.length;c++){var v=t.edgepaths[c][0];Math.abs(o[0]-s[0])<.01?Math.abs(o[0]-v[0])<.01&&(v[1]-o[1])*(s[1]-v[1])>=0&&(s=v,u=c):Math.abs(o[1]-s[1])<.01?Math.abs(o[1]-v[1])<.01&&(v[0]-o[0])*(s[0]-v[0])>=0&&(s=v,u=c):console.log("endpt to newendpt is not vert. or horz.",o,s,v)}if(o=s,u>=0)break;f+="L"+s}if(u===t.edgepaths.length){console.log("unclosed perimeter path");break}d=u,g=-1===p.indexOf(d),g&&(d=p[0],f+="Z")}for(d=0;d<t.paths.length;d++)f+=w.smoothclosed(t.paths[d],t.smoothing);return f}function m(t,e,r){var n=e[0].smoothing,i=t.selectAll("g.contourlevel").data(r.showlines===!1?[]:e);i.enter().append("g").classed("contourlevel",!0),i.exit().remove();var a=i.selectAll("path.openline").data(function(t){return t.edgepaths});a.enter().append("path").classed("openline",!0),a.exit().remove(),a.attr("d",function(t){return w.smoothopen(t,n)}).style("stroke-miterlimit",1);var o=i.selectAll("path.closedline").data(function(t){return t.paths});o.enter().append("path").classed("closedline",!0),o.exit().remove(),o.attr("d",function(t){return w.smoothclosed(t,n)}).style("stroke-miterlimit",1)}function y(t,e,r,n){var i="clip"+r.trace.uid,a=e.plot.selectAll("defs").data([0]);a.enter().append("defs");var s=a.selectAll("#"+i).data(r.trace.connectgaps?[]:[0]);if(s.enter().append("clipPath").attr("id",i),s.exit().remove(),r.trace.connectgaps===!1){var u={level:.9,crossings:{},starts:[],edgepaths:[],paths:[],xaxis:e.x(),yaxis:e.y(),x:r.x,y:r.y,z:b(r),smoothing:0};o([u]),l([u]);var c=v(u,n),h=s.selectAll("path").data([0]);h.enter().append("path"),h.attr("d",c)}else i=null;t.call(w.setClipUrl,i),e.plot.selectAll(".hm"+r.trace.uid).call(w.setClipUrl,i)}function b(t){var e,r,n=t.trace._emptypoints,i=[],a=t.z.length,o=t.z[0].length,s=[];for(e=0;o>e;e++)s.push(1);for(e=0;a>e;e++)i.push(s.slice());for(e=0;e<n.length;e++)r=n[e],i[r[0]][r[1]]=0;return t.zmask=i,i}var x=t("d3"),_=t("../../lib"),w=t("../../components/drawing"),A=t("../heatmap/plot");e.exports=function(t,e,r){for(var i=0;i<r.length;i++)n(t,e,r[i])};var k=[1,9,13,104,713],M=[4,6,7,104,713],T=[8,12,14,208,1114],E=[2,3,11,208,1114],L=[null,[-1,0],[0,-1],[-1,0],[1,0],null,[0,-1],[-1,0],[0,1],[0,1],null,[0,1],[1,0],[1,0],[0,-1]],S={104:[4,1],208:[2,8],713:[7,13],1114:[11,14]},C={1:4,2:8,4:1,7:13,8:2,11:14,13:7,14:11}},{"../../components/drawing":317,"../../lib":349,"../heatmap/plot":468,d3:70}],457:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/drawing"),a=t("../../components/colorscale/get_scale"),o=t("../heatmap/style");e.exports=function(t){n.select(t).selectAll("g.contour").style("opacity",function(t){return t.trace.opacity}).each(function(t){var e=n.select(this),r=t.trace,o=r.contours,s=r.line,l="lines"===o.coloring,u=o.size||1,c=Math.floor((o.end+u/10-o.start)/u)+1,h=a(r.colorscale),f=l?0:1,d=n.scale.linear().domain(h.map(function(t){return(t[0]*(c+f-1)-f/2)*u+o.start})).interpolate(n.interpolateRgb).range(h.map(function(t){return t[1]}));e.selectAll("g.contourlevel").each(function(t,e){n.select(this).selectAll("path").call(i.lineGroupStyle,s.width,l?d(o.start+e*u):s.color,s.dash)}),e.selectAll("g.contourbg path").style("fill",d(o.start-u/2)),e.selectAll("g.contourfill path").style("fill",function(t,e){return d(o.start+(e+.5)*u)})}),o(t)}},{"../../components/colorscale/get_scale":310,"../../components/drawing":317,"../heatmap/style":469,d3:70}],458:[function(t,e,r){"use strict";var n=t("../../components/colorscale/defaults");e.exports=function(t,e,r,i){var a,o=r("contours.coloring");"fill"===o&&(a=r("contours.showlines")),a!==!1&&("lines"!==o&&r("line.color","#000"),r("line.width",.5),r("line.dash")),r("line.smoothing"),"none"!==(e.contours||{}).coloring&&n(t,e,i,r,{prefix:"",cLetter:"z"})}},{"../../components/colorscale/defaults":308}],459:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../components/colorscale/attributes"),a=t("../../lib/extend").extendFlat;e.exports={z:{valType:"data_array"},x:n.x,x0:n.x0,dx:n.dx,y:n.y,y0:n.y0,dy:n.dy,text:{valType:"data_array"},transpose:{valType:"boolean",dflt:!1},xtype:{valType:"enumerated",values:["array","scaled"]},ytype:{valType:"enumerated",values:["array","scaled"]},zauto:i.zauto,zmin:i.zmin,zmax:i.zmax,colorscale:i.colorscale,autocolorscale:a({},i.autocolorscale,{dflt:!1}),reversescale:i.reversescale,showscale:i.showscale,zsmooth:{valType:"enumerated",values:["fast","best",!1],dflt:!1},connectgaps:{valType:"boolean",dflt:!1},_nestedModules:{colorbar:"Colorbar"}}},{"../../components/colorscale/attributes":305,"../../lib/extend":345,"../scatter/attributes":502}],460:[function(t,e,r){"use strict";function n(t){function e(t){return u(t)?+t:void 0;
+}var r,n,i,a,o,s,l=t.z;if(t.transpose){for(r=0,o=0;o<l.length;o++)r=Math.max(r,l[o].length);if(0===r)return!1;i=function(t){return t.length},a=function(t,e,r){return t[r][e]}}else r=l.length,i=function(t,e){return t[e].length},a=function(t,e,r){return t[e][r]};var c=new Array(r);for(o=0;r>o;o++)for(n=i(l,o),c[o]=new Array(n),s=0;n>s;s++)c[o][s]=e(a(l,o,s));return c}function i(t,e,r,n,i,a){var o,s,l,u=[],c=f.traceIs(t,"contour"),h=f.traceIs(t,"histogram");if(Array.isArray(e)&&!h&&"category"!==a.type){e=e.map(a.d2c);var d=e.length;if(!(i>=d))return c?e.slice(0,i):e.slice(0,i+1);if(c)u=e.slice(0,i);else if(1===i)u=[e[0]-.5,e[0]+.5];else{for(u=[1.5*e[0]-.5*e[1]],l=1;d>l;l++)u.push(.5*(e[l-1]+e[l]));u.push(1.5*e[d-1]-.5*e[d-2])}if(i>d){var p=u[u.length-1],g=p-u[u.length-2];for(l=d;i>l;l++)p+=g,u.push(p)}}else for(s=n||1,o=void 0===r?0:h||"category"===a.type?r:a.d2c(r),l=c?0:-.5;i>l;l++)u.push(o+s*l);return u}function a(t){return.5-.25*Math.min(1,.5*t)}function o(t,e,r){var n,i,o=1;if(Array.isArray(r))for(n=0;n<e.length;n++)i=e[n],t[i[0]][i[1]]=r[i[0]][i[1]];else l(t,e);for(n=0;n<e.length&&!(e[n][2]<4);n++);for(e=e.slice(n),n=0;100>n&&o>y;n++)o=l(t,e,a(o));return o>y&&console.log("interp2d didn't converge quickly",o),t}function s(t){var e,r,n,i,a,o,s,l,u=[],c={},h=[],f=t[0],d=[],p=[0,0,0],g=m(t);for(r=0;r<t.length;r++)for(e=d,d=f,f=t[r+1]||[],n=0;g>n;n++)void 0===d[n]&&(o=(void 0!==d[n-1]?1:0)+(void 0!==d[n+1]?1:0)+(void 0!==e[n]?1:0)+(void 0!==f[n]?1:0),o?(0===r&&o++,0===n&&o++,r===t.length-1&&o++,n===d.length-1&&o++,4>o&&(c[[r,n]]=[r,n,o]),u.push([r,n,o])):h.push([r,n]));for(;h.length;){for(s={},l=!1,a=h.length-1;a>=0;a--)i=h[a],r=i[0],n=i[1],o=((c[[r-1,n]]||p)[2]+(c[[r+1,n]]||p)[2]+(c[[r,n-1]]||p)[2]+(c[[r,n+1]]||p)[2])/20,o&&(s[i]=[r,n,o],h.splice(a,1),l=!0);if(!l)throw"findEmpties iterated with no new neighbors";for(i in s)c[i]=s[i],u.push(s[i])}return u.sort(function(t,e){return e[2]-t[2]})}function l(t,e,r){var n,i,a,o,s,l,u,c,h,f,d,p,g,v=0;for(o=0;o<e.length;o++){for(n=e[o],i=n[0],a=n[1],d=t[i][a],f=0,h=0,s=0;4>s;s++)l=b[s],u=t[i+l[0]],u&&(c=u[a+l[1]],void 0!==c&&(0===f?p=g=c:(p=Math.min(p,c),g=Math.max(g,c)),h++,f+=c));if(0===h)throw"iterateInterp2d order is wrong: no defined neighbors";t[i][a]=f/h,void 0===d?4>h&&(v=1):(t[i][a]=(1+r)*t[i][a]-r*d,g>p&&(v=Math.max(v,Math.abs(t[i][a]-d)/(g-p))))}return v}var u=t("fast-isnumeric"),c=t("../../lib"),h=t("../../plots/cartesian/axes"),f=t("../../plots/plots"),d=t("../histogram2d/calc"),p=t("../../components/colorscale/calc"),g=t("./has_columns"),v=t("./convert_column_xyz"),m=t("./max_row_length");e.exports=function(t,e){function r(t){E=e._input.zsmooth=e.zsmooth=!1,c.notifier("cannot fast-zsmooth: "+t)}c.markTime("start convert x&y");var a,l,u,y,b,x,_,w,A=h.getFromId(t,e.xaxis||"x"),k=h.getFromId(t,e.yaxis||"y"),M=f.traceIs(e,"contour"),T=f.traceIs(e,"histogram"),E=M?"best":e.zsmooth;if(A._minDtick=0,k._minDtick=0,c.markTime("done convert x&y"),T){var L=d(t,e);a=L.x,l=L.x0,u=L.dx,y=L.y,b=L.y0,x=L.dy,_=L.z}else g(e)&&v(e,A,k),a=e.x?A.makeCalcdata(e,"x"):[],y=e.y?k.makeCalcdata(e,"y"):[],l=e.x0||0,u=e.dx||1,b=e.y0||0,x=e.dy||1,_=n(e),(M||e.connectgaps)&&(e._emptypoints=s(_),e._interpz=o(_,e._emptypoints,e._interpz));if("fast"===E)if("log"===A.type||"log"===k.type)r("log axis found");else if(!T){if(a.length){var S=(a[a.length-1]-a[0])/(a.length-1),C=Math.abs(S/100);for(w=0;w<a.length-1;w++)if(Math.abs(a[w+1]-a[w]-S)>C){r("x scale is not linear");break}}if(y.length&&"fast"===E){var P=(y[y.length-1]-y[0])/(y.length-1),z=Math.abs(P/100);for(w=0;w<y.length-1;w++)if(Math.abs(y[w+1]-y[w]-P)>z){r("y scale is not linear");break}}}var R=m(_),O="scaled"===e.xtype?"":e.x,I=i(e,O,l,u,R,A),j="scaled"===e.ytype?"":e.y,N=i(e,j,b,x,_.length,k);h.expand(A,I),h.expand(k,N);var F={x:I,y:N,z:_};if(p(e,_,"","z"),M&&e.contours&&"heatmap"===e.contours.coloring){var B="contour"===e.type?"heatmap":"histogram2d";F.xfill=i(B,O,l,u,R,A),F.yfill=i(B,j,b,x,_.length,k)}return[F]};var y=.01,b=[[-1,0],[1,0],[0,-1],[0,1]]},{"../../components/colorscale/calc":306,"../../lib":349,"../../plots/cartesian/axes":369,"../../plots/plots":413,"../histogram2d/calc":480,"./convert_column_xyz":462,"./has_columns":464,"./max_row_length":467,"fast-isnumeric":74}],461:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../plots/plots"),s=t("../../components/colorscale/get_scale"),l=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,u="cb"+r.uid,c=s(r.colorscale),h=r.zmin,f=r.zmax;if(i(h)||(h=a.aggNums(Math.min,null,r.z)),i(f)||(f=a.aggNums(Math.max,null,r.z)),t._fullLayout._infolayer.selectAll("."+u).remove(),!r.showscale)return void o.autoMargin(t,u);var d=e[0].t.cb=l(t,u);d.fillcolor(n.scale.linear().domain(c.map(function(t){return h+t[0]*(f-h)})).range(c.map(function(t){return t[1]}))).filllevels({start:h,end:f,size:(f-h)/254}).options(r.colorbar)(),a.markTime("done colorbar")}},{"../../components/colorbar/draw":302,"../../components/colorscale/get_scale":310,"../../lib":349,"../../plots/plots":413,d3:70,"fast-isnumeric":74}],462:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r){var i,a=t.x.slice(),o=t.y.slice(),s=t.z,l=t.text,u=Math.min(a.length,o.length,s.length),c=void 0!==l&&!Array.isArray(l[0]);for(u<a.length&&(a=a.slice(0,u)),u<o.length&&(o=o.slice(0,u)),i=0;u>i;i++)a[i]=e.d2c(a[i]),o[i]=r.d2c(o[i]);var h,f,d,p=n.distinctVals(a),g=p.vals,v=n.distinctVals(o),m=v.vals,y=n.init2dArray(m.length,g.length);for(c&&(d=n.init2dArray(m.length,g.length)),i=0;u>i;i++)h=n.findBin(a[i]+p.minDiff/2,g),f=n.findBin(o[i]+v.minDiff/2,m),y[f][h]=s[i],c&&(d[f][h]=l[i]);t.x=g,t.y=m,t.z=y,c&&(t.text=d)}},{"../../lib":349}],463:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./has_columns"),a=t("./xyz_defaults"),o=t("../../components/colorscale/defaults"),s=t("./attributes");e.exports=function(t,e,r,l){function u(r,i){return n.coerce(t,e,s,r,i)}var c=a(t,e,u);return c?(u("text"),u("zsmooth"),u("connectgaps",i(e)&&e.zsmooth!==!1),void o(t,e,l,u,{prefix:"",cLetter:"z"})):void(e.visible=!1)}},{"../../components/colorscale/defaults":308,"../../lib":349,"./attributes":459,"./has_columns":464,"./xyz_defaults":470}],464:[function(t,e,r){"use strict";e.exports=function(t){return!Array.isArray(t.z[0])}},{}],465:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/graph_interact"),i=t("../../lib");e.exports=function(t,e,r,a,o){if(!(t.distance<n.MAXDIST)){var s,l,u,c,h=t.cd[0],f=h.trace,d=t.xa,p=t.ya,g=h.x,v=h.y,m=h.z,y=h.zmask,b=g,x=v;if(t.index!==!1){try{u=Math.round(t.index[1]),c=Math.round(t.index[0])}catch(_){return void console.log("Error hovering on heatmap, pointNumber must be [row,col], found:",t.index)}if(0>u||u>=m[0].length||0>c||c>m.length)return}else{if(n.inbox(e-g[0],e-g[g.length-1])>n.MAXDIST||n.inbox(r-v[0],r-v[v.length-1])>n.MAXDIST)return;if(o){var w;for(b=[2*g[0]-g[1]],w=1;w<g.length;w++)b.push((g[w]+g[w-1])/2);for(b.push([2*g[g.length-1]-g[g.length-2]]),x=[2*v[0]-v[1]],w=1;w<v.length;w++)x.push((v[w]+v[w-1])/2);x.push([2*v[v.length-1]-v[v.length-2]])}u=Math.max(0,Math.min(b.length-2,i.findBin(e,b))),c=Math.max(0,Math.min(x.length-2,i.findBin(r,x)))}var A=d.c2p(g[u]),k=d.c2p(g[u+1]),M=p.c2p(v[c]),T=p.c2p(v[c+1]);o?(k=A,s=g[u],T=M,l=v[c]):(s=(g[u]+g[u+1])/2,l=(v[c]+v[c+1])/2,f.zsmooth&&(A=k=(A+k)/2,M=T=(M+T)/2));var E=m[c][u];y&&!y[c][u]&&(E=void 0);var L;return Array.isArray(f.text)&&Array.isArray(f.text[c])&&(L=f.text[c][u]),[i.extendFlat(t,{index:[c,u],distance:n.MAXDIST+10,x0:A,x1:k,y0:M,y1:T,xLabelVal:s,yLabelVal:l,zLabelVal:E,text:L})]}}},{"../../lib":349,"../../plots/cartesian/graph_interact":374}],466:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("./calc"),n.plot=t("./plot"),n.colorbar=t("./colorbar"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.moduleType="trace",n.name="heatmap",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","2dMap"],n.meta={},e.exports=n},{"../../plots/cartesian":375,"./attributes":459,"./calc":460,"./colorbar":461,"./defaults":463,"./hover":465,"./plot":468,"./style":469}],467:[function(t,e,r){"use strict";e.exports=function(t){for(var e=0,r=0;r<t.length;r++)e=Math.max(e,t[r].length);return e}},{}],468:[function(t,e,r){"use strict";function n(t,e,r){function n(t,e){var r=e.length-2,n=o.constrain(o.findBin(t,e),0,r),i=e[n],a=e[n+1],s=o.constrain(n+(t-i)/(a-i)-.5,0,r),l=Math.round(s),u=Math.abs(s-l);return s&&s!==r&&u?{bin0:l,frac:u,bin1:Math.round(l+u/(s-l))}:{bin0:l,bin1:l,frac:0}}function h(t,e){if(void 0!==t){var r=X((t-E)/(L-E));return r[0]=Math.round(r[0]),r[1]=Math.round(r[1]),r[2]=Math.round(r[2]),it+=e,at+=r[0]*e,ot+=r[1]*e,st+=r[2]*e,r}return[0,0,0,0]}function f(t,e,r){t[e]=r[0],t[e+1]=r[1],t[e+2]=r[2],t[e+3]=Math.round(255*r[3])}function d(t,e,r,n){var i=t[r.bin0];if(void 0===i)return h(void 0,1);var a,o=t[r.bin1],s=e[r.bin0],l=e[r.bin1],u=o-i||0,c=s-i||0;return a=void 0===o?void 0===l?0:void 0===s?2*(l-i):2*(2*l-s-i)/3:void 0===l?void 0===s?0:2*(2*i-o-s)/3:void 0===s?2*(2*l-o-i)/3:l+i-o-s,h(i+r.frac*u+n.frac*(c+r.frac*a))}o.markTime("in Heatmap.plot");var p=r[0].trace,g=p.uid,v=e.x(),m=e.y(),y=t._fullLayout,b="hm"+g;if(y._paper.selectAll(".contour"+g).remove(),p.visible!==!0)return y._paper.selectAll("."+b).remove(),void y._infolayer.selectAll(".cb"+g).remove();var x,_,w,A,k,M,T=r[0].z,E=p.zmin,L=p.zmax,S=l(p.colorscale),C=r[0].x,P=r[0].y,z=s.traceIs(p,"contour"),R=z?"best":p.zsmooth,O=T.length,I=c(T),j=!1,N=!1;for(M=0;void 0===x&&M<C.length-1;)x=v.c2p(C[M]),M++;for(M=C.length-1;void 0===_&&M>0;)_=v.c2p(C[M]),M--;for(x>_&&(w=_,_=x,x=w,j=!0),M=0;void 0===A&&M<P.length-1;)A=m.c2p(P[M]),M++;for(M=P.length-1;void 0===k&&M>0;)k=m.c2p(P[M]),M--;if(A>k&&(w=A,A=k,k=w,N=!0),z&&(C=r[0].xfill,P=r[0].yfill),"fast"!==R){var F="best"===R?0:.5;x=Math.max(-F*v._length,x),_=Math.min((1+F)*v._length,_),A=Math.max(-F*m._length,A),k=Math.min((1+F)*m._length,k)}var B=Math.round(_-x),D=Math.round(k-A);if(!(0>=B||0>=D)){var U,V;"fast"===R?(U=I,V=O):(U=B,V=D);var q=document.createElement("canvas");q.width=U,q.height=V;var H,G,Y=q.getContext("2d"),X=i.scale.linear().domain(S.map(function(t){return t[0]})).range(S.map(function(t){var e=a(t[1]).toRgb();return[e.r,e.g,e.b,e.a]})).clamp(!0);"fast"===R?(H=j?function(t){return I-1-t}:o.identity,G=N?function(t){return O-1-t}:o.identity):(H=function(t){return o.constrain(Math.round(v.c2p(C[t])-x),0,B)},G=function(t){return o.constrain(Math.round(m.c2p(P[t])-A),0,D)});var W,Z,$,K,Q,J,tt=G(0),et=[tt,tt],rt=j?0:1,nt=N?0:1,it=0,at=0,ot=0,st=0;if(o.markTime("done init png"),R){var lt=0,ut=new Uint8Array(B*D*4);if("best"===R){var ct,ht,ft,dt=new Array(C.length),pt=new Array(P.length),gt=new Array(B);for(M=0;M<C.length;M++)dt[M]=Math.round(v.c2p(C[M])-x);for(M=0;M<P.length;M++)pt[M]=Math.round(m.c2p(P[M])-A);for(M=0;B>M;M++)gt[M]=n(M,dt);for(Z=0;D>Z;Z++)for(ct=n(Z,pt),ht=T[ct.bin0],ft=T[ct.bin1],M=0;B>M;M++,lt+=4)J=d(ht,ft,gt[M],ct),f(ut,lt,J)}else for(Z=0;O>Z;Z++)for(Q=T[Z],et=G(Z),M=0;I>M;M++)J=h(Q[M],1),lt=4*(et*B+H(M)),f(ut,lt,J);var vt=Y.createImageData(B,D);vt.data.set(ut),Y.putImageData(vt,0,0)}else for(Z=0;O>Z;Z++)if(Q=T[Z],et.reverse(),et[nt]=G(Z+1),et[0]!==et[1]&&void 0!==et[0]&&void 0!==et[1])for($=H(0),W=[$,$],M=0;I>M;M++)W.reverse(),W[rt]=H(M+1),W[0]!==W[1]&&void 0!==W[0]&&void 0!==W[1]&&(K=Q[M],J=h(K,(W[1]-W[0])*(et[1]-et[0])),Y.fillStyle="rgba("+J.join(",")+")",Y.fillRect(W[0],et[0],W[1]-W[0],et[1]-et[0]));o.markTime("done filling png"),at=Math.round(at/it),ot=Math.round(ot/it),st=Math.round(st/it);var mt=a("rgb("+at+","+ot+","+st+")");t._hmpixcount=(t._hmpixcount||0)+it,t._hmlumcount=(t._hmlumcount||0)+it*mt.getLuminance();var yt=e.plot.select(".imagelayer").selectAll("g.hm."+b).data([0]);yt.enter().append("g").classed("hm",!0).classed(b,!0),yt.exit().remove();var bt=yt.selectAll("image").data(r);bt.enter().append("svg:image"),bt.exit().remove(),bt.attr({xmlns:u.svg,"xlink:href":q.toDataURL("image/png"),height:D,width:B,x:x,y:A,preserveAspectRatio:"none"}),o.markTime("done showing png")}}var i=t("d3"),a=t("tinycolor2"),o=t("../../lib"),s=t("../../plots/plots"),l=t("../../components/colorscale/get_scale"),u=t("../../constants/xmlns_namespaces"),c=t("./max_row_length");e.exports=function(t,e,r){for(var i=0;i<r.length;i++)n(t,e,r[i])}},{"../../components/colorscale/get_scale":310,"../../constants/xmlns_namespaces":338,"../../lib":349,"../../plots/plots":413,"./max_row_length":467,d3:70,tinycolor2:229}],469:[function(t,e,r){"use strict";var n=t("d3");e.exports=function(t){n.select(t).selectAll("image").style("opacity",function(t){return t.trace.opacity})}},{d3:70}],470:[function(t,e,r){"use strict";function n(t,e){var r=e(t),n=r?e(t+"type","array"):"scaled";return"scaled"===n&&(e(t+"0"),e("d"+t)),r}function i(t){for(var e,r=!0,n=!1,i=!1,o=0;o<t.length;o++){if(e=t[o],!Array.isArray(e)){r=!1;break}e.length>0&&(n=!0);for(var s=0;s<e.length;s++)if(a(e[s])){i=!0;break}}return r&&n&&i}var a=t("fast-isnumeric"),o=t("./has_columns");e.exports=function(t,e,r){var a,s,l=r("z");if(void 0===l||!l.length)return 0;if(o(t)){if(a=r("x"),s=r("y"),!a||!s)return 0}else{if(a=n("x",r),s=n("y",r),!i(l))return 0;r("transpose")}return e.z.length}},{"./has_columns":464,"fast-isnumeric":74}],471:[function(t,e,r){"use strict";function n(t){return{start:{valType:"number",dflt:null},end:{valType:"number",dflt:null},size:{valType:"any",dflt:1}}}var i=t("../bar/attributes"),a=t("../../lib").extendFlat,o=i.marker,s=o.line;e.exports={x:{valType:"data_array"},y:{valType:"data_array"},text:i.text,orientation:i.orientation,histfunc:{valType:"enumerated",values:["count","sum","avg","min","max"],dflt:"count"},histnorm:{valType:"enumerated",values:["","percent","probability","density","probability density"],dflt:""},autobinx:{valType:"boolean",dflt:!0},nbinsx:{valType:"integer",min:0,dflt:0},xbins:n("x"),autobiny:{valType:"boolean",dflt:!0},nbinsy:{valType:"integer",min:0,dflt:0},ybins:n("y"),marker:{color:o.color,colorscale:o.colorscale,cauto:o.cauto,cmax:o.cmax,cmin:o.cmin,autocolorscale:o.autocolorscale,reversescale:o.reversescale,showscale:o.showscale,line:{color:s.color,colorscale:s.colorscale,cauto:s.cauto,cmax:s.cmax,cmin:s.cmin,autocolorscale:s.autocolorscale,reversescale:s.reversescale,width:a({},s.width,{dflt:0})}},_nestedModules:{error_y:"ErrorBars",error_x:"ErrorBars","marker.colorbar":"Colorbar"},_deprecated:{bardir:i._deprecated.bardir}}},{"../../lib":349,"../bar/attributes":425}],472:[function(t,e,r){"use strict";e.exports=function(t,e){for(var r=t.length,n=0,i=0;r>i;i++)e[i]?(t[i]/=e[i],n+=t[i]):t[i]=null;return n}},{}],473:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){return r("histnorm"),n.forEach(function(t){var e=r(t+"bins.start"),n=r(t+"bins.end"),i=r("autobin"+t,!(e&&n));r(i?"nbins"+t:t+"bins.size")}),e}},{}],474:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports={count:function(t,e,r){return r[t]++,1},sum:function(t,e,r,i){var a=i[e];return n(a)?(a=Number(a),r[t]+=a,a):0},avg:function(t,e,r,i,a){var o=i[e];return n(o)&&(o=Number(o),r[t]+=o,a[t]++),0},min:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]>a)return r[t]=a,a-r[t]}return 0},max:function(t,e,r,i){var a=i[e];if(n(a)){if(a=Number(a),!n(r[t]))return r[t]=a,a;if(r[t]<a)return r[t]=a,a-r[t]}return 0}}},{"fast-isnumeric":74}],475:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../lib"),a=t("../../plots/cartesian/axes"),o=t("./bin_functions"),s=t("./norm_functions"),l=t("./average");e.exports=function(t,e){if(e.visible===!0){var r,u=[],c=[],h=a.getFromId(t,"h"===e.orientation?e.yaxis||"y":e.xaxis||"x"),f="h"===e.orientation?"y":"x",d={x:"y",y:"x"}[f],p=h.makeCalcdata(e,f);e["autobin"+f]===!1&&f+"bins"in e||(e[f+"bins"]=a.autoBin(p,h,e["nbins"+f]),e._input[f+"bins"]=e[f+"bins"]);var g,v,m,y,b=e[f+"bins"],x="string"==typeof b.size,_=x?[]:b,w=[],A=[],k=0,M=e.histnorm,T=e.histfunc,E=-1!==M.indexOf("density"),L="max"===T||"min"===T,S=L?null:0,C=o.count,P=s[M],z=!1;for(Array.isArray(e[d])&&"count"!==T&&(y=e[d],z="avg"===T,C=o[T]),r=b.start,v=b.end+(b.start-a.tickIncrement(b.start,b.size))/1e6;v>r&&u.length<5e3;)g=a.tickIncrement(r,b.size),u.push((r+g)/2),c.push(S),x&&_.push(r),E&&w.push(1/(g-r)),z&&A.push(0),r=g;var R=c.length;for(r=0;r<p.length;r++)m=i.findBin(p[r],_),m>=0&&R>m&&(k+=C(m,r,c,y,A));z&&(k=l(c,A)),P&&P(c,k,w);var O=Math.min(u.length,c.length),I=[],j=0,N=O-1;for(r=0;O>r;r++)if(c[r]){j=r;break}for(r=O-1;r>j;r--)if(c[r]){N=r;break}for(r=j;N>=r;r++)n(u[r])&&n(c[r])&&I.push({p:u[r],s:c[r],b:0});return I}}},{"../../lib":349,"../../plots/cartesian/axes":369,"./average":472,"./bin_functions":474,"./norm_functions":478,"fast-isnumeric":74}],476:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/color"),a=t("./bin_defaults"),o=t("../bar/style_defaults"),s=t("../../components/errorbars/defaults"),l=t("./attributes");e.exports=function(t,e,r,u){function c(r,i){return n.coerce(t,e,l,r,i)}var h=c("x"),f=c("y");c("text");var d=c("orientation",f&&!h?"h":"v"),p=e["v"===d?"x":"y"];if(!p||!p.length)return void(e.visible=!1);var g=e["h"===d?"x":"y"];g&&c("histfunc");var v="h"===d?["y"]:["x"];a(t,e,c,v),o(t,e,c,r,u),s(t,e,i.defaultLine,{axis:"y"}),s(t,e,i.defaultLine,{axis:"x",inherit:"y"})}},{"../../components/color":299,"../../components/errorbars/defaults":322,"../../lib":349,"../bar/style_defaults":435,"./attributes":471,"./bin_defaults":473}],477:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.layoutAttributes=t("../bar/layout_attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("../bar/layout_defaults"),n.calc=t("./calc"),n.setPositions=t("../bar/set_positions"),n.plot=t("../bar/plot"),n.style=t("../bar/style"),n.colorbar=t("../scatter/colorbar"),n.hoverPoints=t("../bar/hover"),n.moduleType="trace",n.name="histogram",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","bar","histogram","oriented","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":375,"../bar/hover":428,"../bar/layout_attributes":430,"../bar/layout_defaults":431,"../bar/plot":432,"../bar/set_positions":433,"../bar/style":434,"../scatter/colorbar":505,"./attributes":471,"./calc":475,"./defaults":476}],478:[function(t,e,r){"use strict";e.exports={percent:function(t,e){for(var r=t.length,n=100/e,i=0;r>i;i++)t[i]*=n},probability:function(t,e){for(var r=t.length,n=0;r>n;n++)t[n]/=e},density:function(t,e,r,n){var i=t.length;n=n||1;for(var a=0;i>a;a++)t[a]*=r[a]*n},"probability density":function(t,e,r,n){var i=t.length;n&&(e/=n);for(var a=0;i>a;a++)t[a]*=r[a]/e}}},{}],479:[function(t,e,r){"use strict";var n=t("../histogram/attributes"),i=t("../heatmap/attributes");e.exports={x:n.x,y:n.y,z:{valType:"data_array"},marker:{color:{valType:"data_array"}},histnorm:n.histnorm,histfunc:n.histfunc,autobinx:n.autobinx,nbinsx:n.nbinsx,xbins:n.xbins,autobiny:n.autobiny,nbinsy:n.nbinsy,ybins:n.ybins,zauto:i.zauto,zmin:i.zmin,zmax:i.zmax,colorscale:i.colorscale,autocolorscale:i.autocolorscale,reversescale:i.reversescale,showscale:i.showscale,zsmooth:i.zsmooth,_nestedModules:{colorbar:"Colorbar"}}},{"../heatmap/attributes":459,"../histogram/attributes":471}],480:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../plots/cartesian/axes"),a=t("../histogram/bin_functions"),o=t("../histogram/norm_functions"),s=t("../histogram/average");e.exports=function(t,e){var r,l,u,c,h,f,d=i.getFromId(t,e.xaxis||"x"),p=e.x?d.makeCalcdata(e,"x"):[],g=i.getFromId(t,e.yaxis||"y"),v=e.y?g.makeCalcdata(e,"y"):[],m=Math.min(p.length,v.length);p.length>m&&p.splice(m,p.length-m),v.length>m&&v.splice(m,v.length-m),n.markTime("done convert data"),!e.autobinx&&"xbins"in e||(e.xbins=i.autoBin(p,d,e.nbinsx,"2d"),"histogram2dcontour"===e.type&&(e.xbins.start-=e.xbins.size,e.xbins.end+=e.xbins.size),e._input.xbins=e.xbins),!e.autobiny&&"ybins"in e||(e.ybins=i.autoBin(v,g,e.nbinsy,"2d"),"histogram2dcontour"===e.type&&(e.ybins.start-=e.ybins.size,e.ybins.end+=e.ybins.size),e._input.ybins=e.ybins),n.markTime("done autoBin"),h=[];var y,b,x=[],_=[],w="string"==typeof e.xbins.size?[]:e.xbins,A="string"==typeof e.xbins.size?[]:e.ybins,k=0,M=[],T=e.histnorm,E=e.histfunc,L=-1!==T.indexOf("density"),S="max"===E||"min"===E,C=S?null:0,P=a.count,z=o[T],R=!1,O=[],I=[],j="z"in e?e.z:"marker"in e&&Array.isArray(e.marker.color)?e.marker.color:"";j&&"count"!==E&&(R="avg"===E,P=a[E]);var N=e.xbins,F=N.end+(N.start-i.tickIncrement(N.start,N.size))/1e6;for(f=N.start;F>f;f=i.tickIncrement(f,N.size))x.push(C),Array.isArray(w)&&w.push(f),R&&_.push(0);Array.isArray(w)&&w.push(f);var B=x.length;for(r=e.xbins.start,l=(f-r)/B,r+=l/2,N=e.ybins,F=N.end+(N.start-i.tickIncrement(N.start,N.size))/1e6,f=N.start;F>f;f=i.tickIncrement(f,N.size))h.push(x.concat()),Array.isArray(A)&&A.push(f),R&&M.push(_.concat());Array.isArray(A)&&A.push(f);var D=h.length;for(u=e.ybins.start,c=(f-u)/D,u+=c/2,L&&(O=x.map(function(t,e){return Array.isArray(w)?1/(w[e+1]-w[e]):1/l}),I=h.map(function(t,e){return Array.isArray(A)?1/(A[e+1]-A[e]):1/c})),n.markTime("done making bins"),f=0;m>f;f++)y=n.findBin(p[f],w),b=n.findBin(v[f],A),y>=0&&B>y&&b>=0&&D>b&&(k+=P(y,f,h[b],j,M[b]));if(R)for(b=0;D>b;b++)k+=s(h[b],M[b]);if(z)for(b=0;D>b;b++)z(h[b],k,O,I[b]);return n.markTime("done binning"),{x:p,x0:r,dx:l,y:v,y0:u,dy:c,z:h}}},{"../../lib":349,"../../plots/cartesian/axes":369,"../histogram/average":472,"../histogram/bin_functions":474,"../histogram/norm_functions":478}],481:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./sample_defaults"),a=t("../../components/colorscale/defaults"),o=t("./attributes");e.exports=function(t,e,r){function s(r,i){return n.coerce(t,e,o,r,i)}i(t,e,s),s("zsmooth"),a(t,e,r,s,{prefix:"",cLetter:"z"})}},{"../../components/colorscale/defaults":308,"../../lib":349,"./attributes":479,"./sample_defaults":483}],482:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("../heatmap/calc"),n.plot=t("../heatmap/plot"),n.colorbar=t("../heatmap/colorbar"),n.style=t("../heatmap/style"),n.hoverPoints=t("../heatmap/hover"),n.moduleType="trace",n.name="histogram2d",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","2dMap","histogram"],n.meta={},e.exports=n},{"../../plots/cartesian":375,"../heatmap/calc":460,"../heatmap/colorbar":461,"../heatmap/hover":465,"../heatmap/plot":468,"../heatmap/style":469,"./attributes":479,"./defaults":481}],483:[function(t,e,r){"use strict";var n=t("../histogram/bin_defaults");e.exports=function(t,e,r){var i=r("x"),a=r("y");if(!(i&&i.length&&a&&a.length))return void(e.visible=!1);var o=r("z")||r("marker.color");o&&r("histfunc");var s=["x","y"];n(t,e,r,s)}},{"../histogram/bin_defaults":473}],484:[function(t,e,r){"use strict";var n=t("../histogram2d/attributes"),i=t("../contour/attributes");e.exports={x:n.x,y:n.y,z:n.z,marker:n.marker,histnorm:n.histnorm,histfunc:n.histfunc,autobinx:n.autobinx,nbinsx:n.nbinsx,xbins:n.xbins,autobiny:n.autobiny,nbinsy:n.nbinsy,ybins:n.ybins,zauto:i.zauto,zmin:i.zmin,zmax:i.zmax,colorscale:i.colorscale,autocolorscale:i.autocolorscale,reversescale:i.reversescale,showscale:i.showscale,autocontour:i.autocontour,ncontours:i.ncontours,contours:i.contours,line:i.line,_nestedModules:{colorbar:"Colorbar"}}},{"../contour/attributes":450,"../histogram2d/attributes":479}],485:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../histogram2d/sample_defaults"),a=t("../contour/style_defaults"),o=t("./attributes");e.exports=function(t,e,r,s){function l(r,i){return n.coerce(t,e,o,r,i)}i(t,e,l);var u=n.coerce2(t,e,o,"contours.start"),c=n.coerce2(t,e,o,"contours.end"),h=l("autocontour",!(u&&c));l(h?"ncontours":"contours.size"),a(t,e,l,s)}},{"../../lib":349,"../contour/style_defaults":458,"../histogram2d/sample_defaults":483,"./attributes":484}],486:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.calc=t("../contour/calc"),n.plot=t("../contour/plot"),n.style=t("../contour/style"),n.colorbar=t("../contour/colorbar"),n.hoverPoints=t("../contour/hover"),n.moduleType="trace",n.name="histogram2dcontour",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","2dMap","contour","histogram"],n.meta={},e.exports=n},{"../../plots/cartesian":375,"../contour/calc":451,"../contour/colorbar":452,"../contour/hover":454,"../contour/plot":456,"../contour/style":457,"./attributes":484,"./defaults":485}],487:[function(t,e,r){"use strict";var n=t("../../components/colorscale/attributes"),i=t("../surface/attributes"),a=t("../../lib/extend").extendFlat;e.exports={x:{valType:"data_array"},y:{valType:"data_array"},z:{valType:"data_array"},i:{valType:"data_array"},j:{valType:"data_array"},k:{valType:"data_array"},delaunayaxis:{valType:"enumerated",values:["x","y","z"],dflt:"z"},alphahull:{valType:"number",dflt:-1},intensity:{valType:"data_array"},color:{valType:"color"},vertexcolor:{valType:"data_array"},facecolor:{valType:"data_array"},opacity:a({},i.opacity),flatshading:{valType:"boolean",dflt:!1},contour:{show:a({},i.contours.x.show,{}),color:a({},i.contours.x.color),width:a({},i.contours.x.width)},colorscale:n.colorscale,reversescale:n.reversescale,showscale:n.showscale,lighting:a({},i.lighting),_nestedModules:{colorbar:"Colorbar"}}},{"../../components/colorscale/attributes":305,"../../lib/extend":345,"../surface/attributes":538}],488:[function(t,e,r){"use strict";function n(t,e,r){this.scene=t,this.uid=r,this.mesh=e,this.name="",this.color="#fff",this.data=null,this.showContour=!1}function i(t){return t.map(function(t){var e=t[0],r=u(t[1]),n=r.toRgb();return{index:e,rgb:[n.r,n.g,n.b,1]}})}function a(t){return t.map(d)}function o(t,e,r){for(var n=new Array(t.length),i=0;i<t.length;++i)n[i]=[t[i],e[i],r[i]];return n}function s(t,e){var r=t.glplot.gl,i=l({gl:r}),a=new n(t,i,e.uid);return a.update(e),t.glplot.add(i),a}var l=t("gl-mesh3d"),u=t("tinycolor2"),c=t("delaunay-triangulate"),h=t("alpha-shape"),f=t("convex-hull"),d=t("../../lib/str2rgbarray"),p=n.prototype;p.handlePick=function(t){if(t.object===this.mesh){var e=t.data.index;return t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]],!0}},p.update=function(t){function e(t,e,r){return e.map(function(e){return t.d2l(e)*r})}var r=this.scene,n=r.fullSceneLayout;this.data=t;var s,l=o(e(n.xaxis,t.x,r.dataScale[0]),e(n.yaxis,t.y,r.dataScale[1]),e(n.zaxis,t.z,r.dataScale[2]));if(t.i&&t.j&&t.k)s=o(t.i,t.j,t.k);else if(0===t.alphahull)s=f(l);else if(t.alphahull>0)s=h(t.alphahull,l);else{var u=["x","y","z"].indexOf(t.delaunayaxis);s=c(l.map(function(t){return[t[(u+1)%3],t[(u+2)%3]]}))}var p={positions:l,cells:s,ambient:t.lighting.ambient,diffuse:t.lighting.diffuse,specular:t.lighting.specular,roughness:t.lighting.roughness,fresnel:t.lighting.fresnel,opacity:t.opacity,contourEnable:t.contour.show,contourColor:d(t.contour.color).slice(0,3),contourWidth:t.contour.width,useFacetNormals:t.flatshading};t.intensity?(this.color="#fff",p.vertexIntensity=t.intensity,p.colormap=i(t.colorscale)):t.vertexcolor?(this.color=t.vertexcolors[0],p.vertexColors=a(t.vertexcolor)):t.facecolor?(this.color=t.facecolor[0],p.cellColors=a(t.facecolor)):(this.color=t.color,p.meshColor=d(t.color)),this.mesh.update(p)},p.dispose=function(){this.scene.glplot.remove(this.mesh),this.mesh.dispose()},e.exports=s},{"../../lib/str2rgbarray":359,"alpha-shape":39,"convex-hull":60,"delaunay-triangulate":71,"gl-mesh3d":107,tinycolor2:229}],489:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/colorbar/defaults"),a=t("./attributes");e.exports=function(t,e,r,o){function s(r,i){return n.coerce(t,e,a,r,i)}function l(t){var e=t.map(function(t){var e=s(t);return e&&Array.isArray(e)?e:null});return e.every(function(t){return t&&t.length===e[0].length})&&e}var u=l(["x","y","z"]),c=l(["i","j","k"]);return u?(c&&c.forEach(function(t){for(var e=0;e<t.length;++e)t[e]|=0}),["lighting.ambient","lighting.diffuse","lighting.specular","lighting.roughness","lighting.fresnel","contour.show","contour.color","contour.width","colorscale","reversescale","flatshading","alphahull","delaunayaxis","opacity"].forEach(function(t){s(t)}),"intensity"in t?(s("intensity"),s("showscale",!0)):(e.showscale=!1,"vertexcolor"in t?s("vertexcolor"):"facecolor"in t?s("facecolor"):s("color",r)),e.reversescale&&(e.colorscale=e.colorscale.map(function(t){return[1-t[0],t[1]]}).reverse()),void(e.showscale&&i(t,e,o))):void(e.visible=!1)}},{"../../components/colorbar/defaults":301,"../../lib":349,"./attributes":487}],490:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../heatmap/colorbar"),n.plot=t("./convert"),n.moduleType="trace",n.name="mesh3d",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d"],n.meta={},e.exports=n},{"../../plots/gl3d":400,"../heatmap/colorbar":461,"./attributes":487,"./convert":488,"./defaults":489}],491:[function(t,e,r){"use strict";var n=t("../../components/color/attributes"),i=t("../../plots/font_attributes"),a=t("../../plots/attributes"),o=t("../../lib/extend").extendFlat;e.exports={labels:{valType:"data_array"},label0:{valType:"number",dflt:0},dlabel:{valType:"number",dflt:1},values:{valType:"data_array"},marker:{colors:{valType:"data_array"},line:{color:{valType:"color",dflt:n.defaultLine,arrayOk:!0},width:{valType:"number",min:0,dflt:0,arrayOk:!0}}},text:{valType:"data_array"},scalegroup:{valType:"string",dflt:""},textinfo:{valType:"flaglist",flags:["label","text","value","percent"],extras:["none"]},hoverinfo:o({},a.hoverinfo,{flags:["label","text","value","percent","name"]}),textposition:{valType:"enumerated",values:["inside","outside","auto","none"],dflt:"auto",arrayOk:!0},textfont:o({},i,{}),insidetextfont:o({},i,{}),outsidetextfont:o({},i,{}),domain:{x:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]},y:{valType:"info_array",items:[{valType:"number",min:0,max:1},{valType:"number",min:0,max:1}],dflt:[0,1]}},hole:{valType:"number",min:0,max:1,dflt:0},sort:{valType:"boolean",dflt:!0},direction:{valType:"enumerated",values:["clockwise","counterclockwise"],dflt:"counterclockwise"},rotation:{valType:"number",min:-360,max:360,dflt:0},pull:{valType:"number",min:0,max:1,dflt:0,arrayOk:!0}}},{"../../components/color/attributes":298,"../../lib/extend":345,"../../plots/attributes":367,"../../plots/font_attributes":383}],492:[function(t,e,r){"use strict";function n(t){if(!l){var e=o.defaults;l=e.slice();var r;for(r=0;r<e.length;r++)l.push(a(e[r]).lighten(20).toHexString());for(r=0;r<o.defaults.length;r++)l.push(a(e[r]).darken(20).toHexString())}return l[t%l.length]}var i=t("fast-isnumeric"),a=t("tinycolor2"),o=t("../../components/color"),s=t("./helpers");e.exports=function(t,e){var r,l,u,c,h,f,d=e.values,p=e.labels,g=[],v=t._fullLayout,m=v._piecolormap,y={},b=!1,x=0,_=v.hiddenlabels||[];if(e.dlabel)for(p=new Array(d.length),r=0;r<d.length;r++)p[r]=String(e.label0+r*e.dlabel);for(r=0;r<d.length;r++)l=d[r],i(l)&&(l=+l,0>l||(u=p[r],(void 0===u||""===u)&&(u=r),u=String(u),void 0===y[u]&&(y[u]=!0,c=a(e.marker.colors[r]),c.isValid()?(c=o.addOpacity(c,c.getAlpha()),m[u]||(m[u]=c)):m[u]?c=m[u]:(c=!1,b=!0),h=-1!==_.indexOf(u),h||(x+=l),g.push({v:l,label:u,color:c,i:r,hidden:h}))));if(e.sort&&g.sort(function(t,e){return e.v-t.v}),b)for(r=0;r<g.length;r++)f=g[r],f.color===!1&&(m[f.label]=f.color=n(v._piedefaultcolorcount),v._piedefaultcolorcount++);if(g[0]&&(g[0].vTotal=x),e.textinfo&&"none"!==e.textinfo){var w,A=-1!==e.textinfo.indexOf("label"),k=-1!==e.textinfo.indexOf("text"),M=-1!==e.textinfo.indexOf("value"),T=-1!==e.textinfo.indexOf("percent");for(r=0;r<g.length;r++)f=g[r],w=A?[f.label]:[],k&&e.text[f.i]&&w.push(e.text[f.i]),M&&w.push(s.formatPieValue(f.v)),T&&w.push(s.formatPiePercent(f.v/x)),f.text=w.join("<br>")}return g};var l},{"../../components/color":299,"./helpers":494,"fast-isnumeric":74,tinycolor2:229}],493:[function(t,e,r){"use strict";
+var n=t("../../lib"),i=t("./attributes");e.exports=function(t,e,r,a){function o(r,a){return n.coerce(t,e,i,r,a)}var s=n.coerceFont,l=o("values");if(!Array.isArray(l)||!l.length)return void(e.visible=!1);var u=o("labels");Array.isArray(u)||(o("label0"),o("dlabel"));var c=o("marker.line.width");c&&o("marker.line.color");var h=o("marker.colors");Array.isArray(h)||(e.marker.colors=[]),o("scalegroup");var f=o("text"),d=o("textinfo",Array.isArray(f)?"text+percent":"percent");if(o("hoverinfo",1===a._dataLength?"label+text+value+percent":void 0),d&&"none"!==d){var p=o("textposition"),g=Array.isArray(p)||"auto"===p,v=g||"inside"===p,m=g||"outside"===p;if(v||m){var y=s(o,"textfont",a.font);v&&s(o,"insidetextfont",y),m&&s(o,"outsidetextfont",y)}}o("domain.x"),o("domain.y"),o("hole"),o("sort"),o("direction"),o("rotation"),o("pull")}},{"../../lib":349,"./attributes":491}],494:[function(t,e,r){"use strict";r.formatPiePercent=function(t){var e=(100*t).toPrecision(3);return-1!==e.indexOf(".")?e.replace(/[.]?0+$/,"")+"%":e+"%"},r.formatPieValue=function(t){var e=t.toPrecision(10);return-1!==e.indexOf(".")?e.replace(/[.]?0+$/,""):e}},{}],495:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.supplyLayoutDefaults=t("./layout_defaults"),n.layoutAttributes=t("./layout_attributes"),n.calc=t("./calc"),n.plot=t("./plot"),n.style=t("./style"),n.styleOne=t("./style_one"),n.moduleType="trace",n.name="pie",n.basePlotModule=t("../../plots/cartesian"),n.categories=["pie","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":375,"./attributes":491,"./calc":492,"./defaults":493,"./layout_attributes":496,"./layout_defaults":497,"./plot":498,"./style":499,"./style_one":500}],496:[function(t,e,r){"use strict";e.exports={hiddenlabels:{valType:"data_array"}}},{}],497:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("./layout_attributes");e.exports=function(t,e){function r(r,a){return n.coerce(t,e,i,r,a)}r("hiddenlabels")}},{"../../lib":349,"./layout_attributes":496}],498:[function(t,e,r){"use strict";function n(t,e,r){var n=Math.sqrt(t.width*t.width+t.height*t.height),a=t.width/t.height,o=Math.PI*Math.min(e.v/r.vTotal,.5),s=1-r.trace.hole,l=i(e,r),u={scale:l*r.r*2/n,rCenter:1-l,rotate:0};if(u.scale>=1)return u;var c=a+1/(2*Math.tan(o)),h=r.r*Math.min(1/(Math.sqrt(c*c+.5)+c),s/(Math.sqrt(a*a+s/2)+a)),f={scale:2*h/t.height,rCenter:Math.cos(h/r.r)-h*a/r.r,rotate:(180/Math.PI*e.midangle+720)%180-90},d=1/a,p=d+1/(2*Math.tan(o)),g=r.r*Math.min(1/(Math.sqrt(p*p+.5)+p),s/(Math.sqrt(d*d+s/2)+d)),v={scale:2*g/t.width,rCenter:Math.cos(g/r.r)-g/a/r.r,rotate:(180/Math.PI*e.midangle+810)%180-90},m=v.scale>f.scale?v:f;return u.scale<1&&m.scale>u.scale?m:u}function i(t,e){if(t.v===e.vTotal&&!e.trace.hole)return 1;var r=Math.PI*Math.min(t.v/e.vTotal,.5);return Math.min(1/(1+1/Math.sin(r)),(1-e.trace.hole)/2)}function a(t,e){var r=e.pxmid[0],n=e.pxmid[1],i=t.width/2,a=t.height/2;return 0>r&&(i*=-1),0>n&&(a*=-1),{scale:1,rCenter:1,rotate:0,x:i+Math.abs(a)*(i>0?1:-1)/2,y:a/(1+r*r/(n*n)),outside:!0}}function o(t,e){function r(t,e){return t.pxmid[1]-e.pxmid[1]}function n(t,e){return e.pxmid[1]-t.pxmid[1]}function i(t,r){r||(r={});var n,i,a,s,f,d,g=r.labelExtraY+(o?r.yLabelMax:r.yLabelMin),v=o?t.yLabelMin:t.yLabelMax,m=o?t.yLabelMax:t.yLabelMin,y=t.cyFinal+u(t.px0[1],t.px1[1]),b=g-v;if(b*h>0&&(t.labelExtraY=b),Array.isArray(e.pull))for(i=0;i<p.length;i++)a=p[i],a===t||(e.pull[t.i]||0)>=e.pull[a.i]||((t.pxmid[1]-a.pxmid[1])*h>0?(s=a.cyFinal+u(a.px0[1],a.px1[1]),b=s-v-t.labelExtraY,b*h>0&&(t.labelExtraY+=b)):(m+t.labelExtraY-y)*h>0&&(n=3*c*Math.abs(i-p.indexOf(t)),f=a.cxFinal+l(a.px0[0],a.px1[0]),d=f+n-(t.cxFinal+t.pxmid[0])-t.labelExtraX,d*c>0&&(t.labelExtraX+=d)))}var a,o,s,l,u,c,h,f,d,p,g,v,m;for(o=0;2>o;o++)for(s=o?r:n,u=o?Math.max:Math.min,h=o?1:-1,a=0;2>a;a++){for(l=a?Math.max:Math.min,c=a?1:-1,f=t[o][a],f.sort(s),d=t[1-o][a],p=d.concat(f),v=[],g=0;g<f.length;g++)void 0!==f[g].yLabelMid&&v.push(f[g]);for(m=!1,g=0;o&&g<d.length;g++)if(void 0!==d[g].yLabelMid){m=d[g];break}for(g=0;g<v.length;g++){var y=g&&v[g-1];m&&!g&&(y=m),i(v[g],y)}}}function s(t,e){var r,n,i,a,o,s,l,c,h,f,d=[];for(i=0;i<t.length;i++){if(o=t[i][0],s=o.trace,r=e.w*(s.domain.x[1]-s.domain.x[0]),n=e.h*(s.domain.y[1]-s.domain.y[0]),l=s.tiltaxis*Math.PI/180,c=s.pull,Array.isArray(c))for(c=0,a=0;a<s.pull.length;a++)s.pull[a]>c&&(c=s.pull[a]);o.r=Math.min(r/u(s.tilt,Math.sin(l),s.depth),n/u(s.tilt,Math.cos(l),s.depth))/(2+2*c),o.cx=e.l+e.w*(s.domain.x[1]+s.domain.x[0])/2,o.cy=e.t+e.h*(2-s.domain.y[1]-s.domain.y[0])/2,s.scalegroup&&-1===d.indexOf(s.scalegroup)&&d.push(s.scalegroup)}for(a=0;a<d.length;a++){for(f=1/0,h=d[a],i=0;i<t.length;i++)o=t[i][0],o.trace.scalegroup===h&&(f=Math.min(f,o.r*o.r/o.vTotal));for(i=0;i<t.length;i++)o=t[i][0],o.trace.scalegroup===h&&(o.r=Math.sqrt(f*o.vTotal))}}function l(t){function e(t){var e=h.r*Math.sin(t),r=-h.r*Math.cos(t);return d?[e*(1-s*n*n)+r*o*s,e*o*s+r*(1-s*i*i),Math.sin(a)*(r*i-e*n)]:[e,r]}var r,n,i,a,o,s,l,u,c,h=t[0],f=h.trace,d=f.tilt,p=f.rotation*Math.PI/180,g=2*Math.PI/h.vTotal,v="px0",m="px1";if("counterclockwise"===f.direction){for(l=0;l<t.length&&t[l].hidden;l++);if(l===t.length)return;p+=g*t[l].v,g*=-1,v="px1",m="px0"}for(d&&(a=d*Math.PI/180,r=f.tiltaxis*Math.PI/180,o=Math.sin(r)*Math.cos(r),s=1-Math.cos(a),n=Math.sin(r),i=Math.cos(r)),c=e(p),l=0;l<t.length;l++)u=t[l],u.hidden||(u[v]=c,p+=g*u.v/2,u.pxmid=e(p),u.midangle=p,p+=g*u.v/2,c=e(p),u[m]=c,u.largeArc=u.v>h.vTotal/2?1:0)}function u(t,e,r){if(!t)return 1;var n=Math.sin(t*Math.PI/180);return Math.max(.01,r*n*Math.abs(e)+2*Math.sqrt(1-n*n*e*e))}var c=t("d3"),h=t("../../plots/cartesian/graph_interact"),f=t("../../components/color"),d=t("../../components/drawing"),p=t("../../lib/svg_text_utils"),g=t("./helpers");e.exports=function(t,e){var r=t._fullLayout;s(e,r._size);var u=r._pielayer.selectAll("g.trace").data(e);u.enter().append("g").attr({"stroke-linejoin":"round","class":"trace"}),u.exit().remove(),u.order(),u.each(function(e){var s=c.select(this),u=e[0],v=u.trace,m=0,y=(v.depth||0)*u.r*Math.sin(m)/2,b=v.tiltaxis||0,x=b*Math.PI/180,_=[y*Math.sin(x),y*Math.cos(x)],w=u.r*Math.cos(m),A=s.selectAll("g.part").data(v.tilt?["top","sides"]:["top"]);A.enter().append("g").attr("class",function(t){return t+" part"}),A.exit().remove(),A.order(),l(e),s.selectAll(".top").each(function(){var s=c.select(this).selectAll("g.slice").data(e);s.enter().append("g").classed("slice",!0),s.exit().remove();var l=[[[],[]],[[],[]]],m=!1;s.each(function(o){function s(e){var r=t._fullLayout,n=t._fullData[v.index],a=n.hoverinfo;if("all"===a&&(a="label+text+value+percent+name"),!t._dragging&&r.hovermode!==!1&&"none"!==a&&a){var s=i(o,u),l=A+o.pxmid[0]*(1-s),c=k+o.pxmid[1]*(1-s),f=[];-1!==a.indexOf("label")&&f.push(o.label),n.text&&n.text[o.i]&&-1!==a.indexOf("text")&&f.push(n.text[o.i]),-1!==a.indexOf("value")&&f.push(g.formatPieValue(o.v)),-1!==a.indexOf("percent")&&f.push(g.formatPiePercent(o.v/u.vTotal)),h.loneHover({x0:l-s*u.r,x1:l+s*u.r,y:c,text:f.join("<br>"),name:-1!==a.indexOf("name")?n.name:void 0,color:o.color,idealAlign:o.pxmid[0]<0?"left":"right"},{container:r._hoverlayer.node(),outerContainer:r._paper.node()}),h.hover(t,e,"pie"),E=!0}}function f(){E&&(h.loneUnhover(r._hoverlayer.node()),E=!1)}function y(){t._hoverdata=[o],t._hoverdata.trace=e.trace,h.click(t,{target:!0})}function x(t,e,r,n){return"a"+n*u.r+","+n*w+" "+b+" "+o.largeArc+(r?" 1 ":" 0 ")+n*(e[0]-t[0])+","+n*(e[1]-t[1])}if(o.hidden)return void c.select(this).selectAll("path,g").remove();l[o.pxmid[1]<0?0:1][o.pxmid[0]<0?0:1].push(o);var A=u.cx+_[0],k=u.cy+_[1],M=c.select(this),T=M.selectAll("path.surface").data([o]),E=!1;if(T.enter().append("path").classed("surface",!0).style({"pointer-events":"all"}),M.select("path.textline").remove(),M.on("mouseover",s).on("mouseout",f).on("click",y),v.pull){var L=+(Array.isArray(v.pull)?v.pull[o.i]:v.pull)||0;L>0&&(A+=L*o.pxmid[0],k+=L*o.pxmid[1])}o.cxFinal=A,o.cyFinal=k;var S=v.hole;if(o.v===u.vTotal){var C="M"+(A+o.px0[0])+","+(k+o.px0[1])+x(o.px0,o.pxmid,!0,1)+x(o.pxmid,o.px0,!0,1)+"Z";S?T.attr("d","M"+(A+S*o.px0[0])+","+(k+S*o.px0[1])+x(o.px0,o.pxmid,!1,S)+x(o.pxmid,o.px0,!1,S)+"Z"+C):T.attr("d",C)}else{var P=x(o.px0,o.px1,!0,1);if(S){var z=1-S;T.attr("d","M"+(A+S*o.px1[0])+","+(k+S*o.px1[1])+x(o.px1,o.px0,!1,S)+"l"+z*o.px0[0]+","+z*o.px0[1]+P+"Z")}else T.attr("d","M"+A+","+k+"l"+o.px0[0]+","+o.px0[1]+P+"Z")}var R=Array.isArray(v.textposition)?v.textposition[o.i]:v.textposition,O=M.selectAll("g.slicetext").data(o.text&&"none"!==R?[0]:[]);O.enter().append("g").classed("slicetext",!0),O.exit().remove(),O.each(function(){var t=c.select(this).selectAll("text").data([0]);t.enter().append("text").attr("data-notex",1),t.exit().remove(),t.text(o.text).attr({"class":"slicetext",transform:"","data-bb":"","text-anchor":"middle",x:0,y:0}).call(d.font,"outside"===R?v.outsidetextfont:v.insidetextfont).call(p.convertToTspans),t.selectAll("tspan.line").attr({x:0,y:0});var e,r=d.bBox(t.node());"outside"===R?e=a(r,o):(e=n(r,o,u),"auto"===R&&e.scale<1&&(t.call(d.font,v.outsidetextfont),(v.outsidetextfont.family!==v.insidetextfont.family||v.outsidetextfont.size!==v.insidetextfont.size)&&(t.attr({"data-bb":""}),r=d.bBox(t.node())),e=a(r,o)));var i=A+o.pxmid[0]*e.rCenter+(e.x||0),s=k+o.pxmid[1]*e.rCenter+(e.y||0);e.outside&&(o.yLabelMin=s-r.height/2,o.yLabelMid=s,o.yLabelMax=s+r.height/2,o.labelExtraX=0,o.labelExtraY=0,m=!0),t.attr("transform","translate("+i+","+s+")"+(e.scale<1?"scale("+e.scale+")":"")+(e.rotate?"rotate("+e.rotate+")":"")+"translate("+-(r.left+r.right)/2+","+-(r.top+r.bottom)/2+")")})}),m&&o(l,v),s.each(function(t){if(t.labelExtraX||t.labelExtraY){var e=c.select(this),r=e.select("g.slicetext text");r.attr("transform","translate("+t.labelExtraX+","+t.labelExtraY+")"+r.attr("transform"));var n=t.cxFinal+t.pxmid[0],i=t.cyFinal+t.pxmid[1],a="M"+n+","+i,o=(t.yLabelMax-t.yLabelMin)*(t.pxmid[0]<0?-1:1)/4;if(t.labelExtraX){var s=t.labelExtraX*t.pxmid[1]/t.pxmid[0],l=t.yLabelMid+t.labelExtraY-(t.cyFinal+t.pxmid[1]);a+=Math.abs(s)>Math.abs(l)?"l"+l*t.pxmid[0]/t.pxmid[1]+","+l+"H"+(n+t.labelExtraX+o):"l"+t.labelExtraX+","+s+"v"+(l-s)+"h"+o}else a+="V"+(t.yLabelMid+t.labelExtraY)+"h"+o;e.append("path").classed("textline",!0).call(f.stroke,v.outsidetextfont.color).attr({"stroke-width":Math.min(2,v.outsidetextfont.size/8),d:a,fill:"none"})}})})}),setTimeout(function(){u.selectAll("tspan").each(function(){var t=c.select(this);t.attr("dy")&&t.attr("dy",t.attr("dy"))})},0)}},{"../../components/color":299,"../../components/drawing":317,"../../lib/svg_text_utils":360,"../../plots/cartesian/graph_interact":374,"./helpers":494,d3:70}],499:[function(t,e,r){"use strict";var n=t("d3"),i=t("./style_one");e.exports=function(t){t._fullLayout._pielayer.selectAll(".trace").each(function(t){var e=t[0],r=e.trace,a=n.select(this);a.style({opacity:r.opacity}),a.selectAll(".top path.surface").each(function(t){n.select(this).call(i,t,r)})})}},{"./style_one":500,d3:70}],500:[function(t,e,r){"use strict";var n=t("../../components/color");e.exports=function(t,e,r){var i=r.marker.line.color;Array.isArray(i)&&(i=i[e.i]||n.defaultLine);var a=r.marker.line.width||0;Array.isArray(a)&&(a=a[e.i]||0),t.style({"stroke-width":a,fill:e.color}).call(n.stroke,i)}},{"../../components/color":299}],501:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t){var e=t[0].trace,r=e.marker;if(n.mergeArray(e.text,t,"tx"),n.mergeArray(e.textposition,t,"tp"),e.textfont&&(n.mergeArray(e.textfont.size,t,"ts"),n.mergeArray(e.textfont.color,t,"tc"),n.mergeArray(e.textfont.family,t,"tf")),r&&r.line){var i=r.line;n.mergeArray(r.opacity,t,"mo"),n.mergeArray(r.symbol,t,"mx"),n.mergeArray(r.color,t,"mc"),n.mergeArray(i.color,t,"mlc"),n.mergeArray(i.width,t,"mlw")}}},{"../../lib":349}],502:[function(t,e,r){"use strict";var n=t("../../components/drawing");t("./constants");e.exports={x:{valType:"data_array"},x0:{valType:"any",dflt:0},dx:{valType:"number",dflt:1},y:{valType:"data_array"},y0:{valType:"any",dflt:0},dy:{valType:"number",dflt:1},text:{valType:"string",dflt:"",arrayOk:!0},mode:{valType:"flaglist",flags:["lines","markers","text"],extras:["none"]},line:{color:{valType:"color"},width:{valType:"number",min:0,dflt:2},shape:{valType:"enumerated",values:["linear","spline","hv","vh","hvh","vhv"],dflt:"linear"},smoothing:{valType:"number",min:0,max:1.3,dflt:1},dash:{valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid"}},connectgaps:{valType:"boolean",dflt:!1},fill:{valType:"enumerated",values:["none","tozeroy","tozerox","tonexty","tonextx"],dflt:"none"},fillcolor:{valType:"color"},marker:{symbol:{valType:"enumerated",values:n.symbolList,dflt:"circle",arrayOk:!0},opacity:{valType:"number",min:0,max:1,arrayOk:!0},size:{valType:"number",min:0,dflt:6,arrayOk:!0},color:{valType:"color",arrayOk:!0},maxdisplayed:{valType:"number",min:0,dflt:0},sizeref:{valType:"number",dflt:1},sizemin:{valType:"number",min:0,dflt:0},sizemode:{valType:"enumerated",values:["diameter","area"],dflt:"diameter"},colorscale:{valType:"colorscale"},cauto:{valType:"boolean",dflt:!0},cmax:{valType:"number",dflt:null},cmin:{valType:"number",dflt:null},autocolorscale:{valType:"boolean",dflt:!0},reversescale:{valType:"boolean",dflt:!1},showscale:{valType:"boolean",dflt:!1},line:{color:{valType:"color",arrayOk:!0},width:{valType:"number",min:0,arrayOk:!0},colorscale:{valType:"colorscale"},cauto:{valType:"boolean",dflt:!0},cmax:{valType:"number",dflt:null},cmin:{valType:"number",dflt:null},autocolorscale:{valType:"boolean",dflt:!0},reversescale:{valType:"boolean",dflt:!1}}},textposition:{valType:"enumerated",values:["top left","top center","top right","middle left","middle center","middle right","bottom left","bottom center","bottom right"],dflt:"middle center",arrayOk:!0},textfont:{family:{valType:"string",noBlank:!0,strict:!0,arrayOk:!0},size:{valType:"number",min:1,arrayOk:!0},color:{valType:"color",arrayOk:!0}},r:{valType:"data_array"},t:{valType:"data_array"},_nestedModules:{error_y:"ErrorBars",error_x:"ErrorBars","marker.colorbar":"Colorbar"}}},{"../../components/drawing":317,"./constants":506}],503:[function(t,e,r){"use strict";var n=t("fast-isnumeric"),i=t("../../plots/cartesian/axes"),a=t("../../lib"),o=t("./subtypes"),s=t("./marker_colorscale_calc");e.exports=function(t,e){var r=i.getFromId(t,e.xaxis||"x"),l=i.getFromId(t,e.yaxis||"y");a.markTime("in Scatter.calc");var u=r.makeCalcdata(e,"x");a.markTime("finished convert x");var c=l.makeCalcdata(e,"y");a.markTime("finished convert y");var h,f,d,p=Math.min(u.length,c.length);r._minDtick=0,l._minDtick=0,u.length>p&&u.splice(p,u.length-p),c.length>p&&c.splice(p,c.length-p);var g={padded:!0},v={padded:!0};if(o.hasMarkers(e)){if(h=e.marker,f=h.size,Array.isArray(f)){var m={type:"linear"};i.setConvert(m),f=m.makeCalcdata(e.marker,"size"),f.length>p&&f.splice(p,f.length-p)}var y,b=1.6*(e.marker.sizeref||1);y="area"===e.marker.sizemode?function(t){return Math.max(Math.sqrt((t||0)/b),3)}:function(t){return Math.max((t||0)/b,3)},g.ppad=v.ppad=Array.isArray(f)?f.map(y):y(f)}s(e),!("tozerox"===e.fill||"tonextx"===e.fill&&t.firstscatter)||u[0]===u[p-1]&&c[0]===c[p-1]?e.error_y.visible||-1===["tonexty","tozeroy"].indexOf(e.fill)&&(o.hasMarkers(e)||o.hasText(e))||(g.padded=!1,g.ppad=0):g.tozero=!0,!("tozeroy"===e.fill||"tonexty"===e.fill&&t.firstscatter)||u[0]===u[p-1]&&c[0]===c[p-1]?-1!==["tonextx","tozerox"].indexOf(e.fill)&&(v.padded=!1):v.tozero=!0,a.markTime("ready for Axes.expand"),i.expand(r,u,g),a.markTime("done expand x"),i.expand(l,c,v),a.markTime("done expand y");var x=new Array(p);for(d=0;p>d;d++)x[d]=n(u[d])&&n(c[d])?{x:u[d],y:c[d]}:{x:!1,y:!1};return void 0!==typeof f&&a.mergeArray(f,x,"ms"),t.firstscatter=!1,x}},{"../../lib":349,"../../plots/cartesian/axes":369,"./marker_colorscale_calc":515,"./subtypes":520,"fast-isnumeric":74}],504:[function(t,e,r){"use strict";e.exports=function(t){var e,r,n,i,a;for(e=0;e<t.length;e++)if(r=t[e],n=r.fill,"none"!==n&&"scatter"===r.type&&(r.opacity=void 0,"tonexty"===n||"tonextx"===n))for(i=e-1;i>=0;i--)if(a=t[i],"scatter"===a.type&&a.xaxis===r.xaxis&&a.yaxis===r.yaxis){a.opacity=void 0;break}}},{}],505:[function(t,e,r){"use strict";var n=t("d3"),i=t("fast-isnumeric"),a=t("../../lib"),o=t("../../plots/plots"),s=t("../../components/colorscale/get_scale"),l=t("../../components/colorbar/draw");e.exports=function(t,e){var r=e[0].trace,u=r.marker,c="cb"+r.uid;if(t._fullLayout._infolayer.selectAll("."+c).remove(),void 0===u||!u.showscale)return void o.autoMargin(t,c);var h=s(u.colorscale),f=u.color,d=u.cmin,p=u.cmax;i(d)||(d=a.aggNums(Math.min,null,f)),i(p)||(p=a.aggNums(Math.max,null,f));var g=e[0].t.cb=l(t,c);g.fillcolor(n.scale.linear().domain(h.map(function(t){return d+t[0]*(p-d)})).range(h.map(function(t){return t[1]}))).filllevels({start:d,end:p,size:(p-d)/254}).options(u.colorbar)(),a.markTime("done colorbar")}},{"../../components/colorbar/draw":302,"../../components/colorscale/get_scale":310,"../../lib":349,"../../plots/plots":413,d3:70,"fast-isnumeric":74}],506:[function(t,e,r){"use strict";e.exports={PTS_LINESONLY:20}},{}],507:[function(t,e,r){"use strict";function n(t,e,r){var n=r("line.shape");"spline"===n&&r("line.smoothing")}var i=t("../../lib"),a=t("./attributes"),o=t("./constants"),s=t("./subtypes"),l=t("./xy_defaults"),u=t("./marker_defaults"),c=t("./line_defaults"),h=t("./text_defaults"),f=t("./fillcolor_defaults"),d=t("../../components/errorbars/defaults");e.exports=function(t,e,r,p){function g(r,n){return i.coerce(t,e,a,r,n)}var v=l(t,e,g),m=v<o.PTS_LINESONLY?"lines+markers":"lines";return v?(g("text"),g("mode",m),s.hasLines(e)&&(c(t,e,r,g),n(t,e,g),g("connectgaps")),s.hasMarkers(e)&&u(t,e,r,p,g),s.hasText(e)&&h(t,e,p,g),(s.hasMarkers(e)||s.hasText(e))&&g("marker.maxdisplayed"),g("fill"),"none"!==e.fill&&(f(t,e,r,g),s.hasLines(e)||n(t,e,g)),d(t,e,r,{axis:"y"}),void d(t,e,r,{axis:"x",inherit:"y"})):void(e.visible=!1)}},{"../../components/errorbars/defaults":322,"../../lib":349,"./attributes":502,"./constants":506,"./fillcolor_defaults":508,"./line_defaults":512,"./marker_defaults":516,"./subtypes":520,"./text_defaults":521,"./xy_defaults":522}],508:[function(t,e,r){"use strict";var n=t("../../components/color");e.exports=function(t,e,r,i){var a=!1;if(e.marker){var o=e.marker.color,s=(e.marker.line||{}).color;o&&!Array.isArray(o)?a=o:s&&!Array.isArray(s)&&(a=s)}i("fillcolor",n.addOpacity((e.line||{}).color||a||r,.5))}},{"../../components/color":299}],509:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("./subtypes");e.exports=function(t,e){var r,a;if("lines"===t.mode)return r=t.line.color,r&&n.opacity(r)?r:t.fillcolor;if("none"===t.mode)return t.fill?t.fillcolor:"";var o=e.mcc||(t.marker||{}).color,s=e.mlcc||((t.marker||{}).line||{}).color;return a=o&&n.opacity(o)?o:s&&n.opacity(s)&&(e.mlw||((t.marker||{}).line||{}).width)?s:"",a?n.opacity(a)<.3?n.addOpacity(a,.3):a:(r=(t.line||{}).color,r&&n.opacity(r)&&i.hasLines(t)&&t.line.width?r:t.fillcolor)}},{"../../components/color":299,"./subtypes":520}],510:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/graph_interact"),i=t("../../components/errorbars"),a=t("./get_trace_color");e.exports=function(t,e,r,o){var s=t.cd,l=s[0].trace,u=t.xa,c=t.ya,h=function(t){var r=Math.max(3,t.mrc||0);return Math.max(Math.abs(u.c2p(t.x)-u.c2p(e))-r,1-3/r)},f=function(t){var e=Math.max(3,t.mrc||0);return Math.max(Math.abs(c.c2p(t.y)-c.c2p(r))-e,1-3/e)},d=function(t){var n=Math.max(3,t.mrc||0),i=Math.abs(u.c2p(t.x)-u.c2p(e)),a=Math.abs(c.c2p(t.y)-c.c2p(r));return Math.max(Math.sqrt(i*i+a*a)-n,1-3/n)},p=n.getDistanceFunction(o,h,f,d);if(n.getClosest(s,p,t),t.index!==!1){var g=s[t.index],v=u.c2p(g.x,!0),m=c.c2p(g.y,!0),y=g.mrc||1;return t.color=a(l,g),t.x0=v-y,t.x1=v+y,t.xLabelVal=g.x,t.y0=m-y,t.y1=m+y,t.yLabelVal=g.y,g.tx?t.text=g.tx:l.text&&(t.text=l.text),i.hoverInfo(g,l,t),[t]}}},{"../../components/errorbars":323,"../../plots/cartesian/graph_interact":374,"./get_trace_color":509}],511:[function(t,e,r){"use strict";var n={},i=t("./subtypes");n.hasLines=i.hasLines,n.hasMarkers=i.hasMarkers,n.hasText=i.hasText,n.isBubble=i.isBubble,n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.cleanData=t("./clean_data"),n.calc=t("./calc"),n.arraysToCalcdata=t("./arrays_to_calcdata"),n.plot=t("./plot"),n.colorbar=t("./colorbar"),n.style=t("./style"),n.hoverPoints=t("./hover"),n.selectPoints=t("./select"),n.moduleType="trace",n.name="scatter",n.basePlotModule=t("../../plots/cartesian"),n.categories=["cartesian","symbols","markerColorscale","errorBarsOK","showLegend"],n.meta={},e.exports=n},{"../../plots/cartesian":375,"./arrays_to_calcdata":501,"./attributes":502,"./calc":503,"./clean_data":504,"./colorbar":505,"./defaults":507,"./hover":510,"./plot":517,"./select":518,"./style":519,"./subtypes":520}],512:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){var i=(t.marker||{}).color;n("line.color",(Array.isArray(i)?!1:i)||r),n("line.width"),n("line.dash")}},{}],513:[function(t,e,r){"use strict";var n=t("../../plots/cartesian/axes");e.exports=function(t,e){function r(e){var r=w.c2p(t[e].x),n=A.c2p(t[e].y);return r===L||n===L?!1:[r,n]}function i(t){var e=t[0]/w._length,r=t[1]/A._length;return(1+10*Math.max(0,-e,e-1,-r,r-1))*M}function a(t,e){var r=t[0]-e[0],n=t[1]-e[1];return Math.sqrt(r*r+n*n)}var o,s,l,u,c,h,f,d,p,g,v,m,y,b,x,_,w=e.xaxis,A=e.yaxis,k=e.connectGaps,M=e.baseTolerance,T=e.linear,E=[],L=n.BADNUM,S=.2,C=new Array(t.length),P=0;for(o=0;o<t.length;o++)if(s=r(o)){for(P=0,C[P++]=s,o++;o<t.length;o++){if(u=r(o),!u){if(k)continue;break}if(T){if(f=a(u,s),!(f<i(u)*S)){for(p=[(u[0]-s[0])/f,(u[1]-s[1])/f],c=s,v=f,m=b=x=0,d=!1,l=u,o++;o<t.length;o++){if(h=r(o),!h){if(k)continue;break}if(g=[h[0]-s[0],h[1]-s[1]],_=g[0]*p[1]-g[1]*p[0],b=Math.min(b,_),x=Math.max(x,_),x-b>i(h))break;l=h,y=g[0]*p[0]+g[1]*p[1],y>v?(v=y,u=h,d=!1):m>y&&(m=y,c=h,d=!0)}if(d?(C[P++]=u,l!==c&&(C[P++]=c)):(c!==s&&(C[P++]=c),l!==u&&(C[P++]=u)),C[P++]=l,o>=t.length||!h)break;C[P++]=h,s=h}}else C[P++]=u}E.push(C.slice(0,P))}return E}},{"../../plots/cartesian/axes":369}],514:[function(t,e,r){"use strict";var n=t("fast-isnumeric");e.exports=function(t){var e=t.marker,r=e.sizeref||1,i=e.sizemin||0,a="area"===e.sizemode?function(t){return Math.sqrt(t/r)}:function(t){return t/r};return function(t){var e=a(t/2);return n(e)&&e>0?Math.max(e,i):0}}},{"fast-isnumeric":74}],515:[function(t,e,r){"use strict";var n=t("../../components/colorscale/has_colorscale"),i=t("../../components/colorscale/calc"),a=t("./subtypes");e.exports=function(t){if(a.hasMarkers(t)){var e=t.marker;n(t,"marker")&&i(t,e.color,"marker","c"),n(t,"marker.line")&&i(t,e.line.color,"marker.line","c")}}},{"../../components/colorscale/calc":306,"../../components/colorscale/has_colorscale":311,"./subtypes":520}],516:[function(t,e,r){"use strict";var n=t("../../components/color"),i=t("../../components/colorscale/has_colorscale"),a=t("../../components/colorscale/defaults"),o=t("./subtypes");e.exports=function(t,e,r,s,l){var u,c=o.isBubble(t),h=(t.line||{}).color;h&&(r=h),l("marker.symbol"),l("marker.opacity",c?.7:1),l("marker.size"),l("marker.color",r),i(t,"marker")&&a(t,e,s,l,{prefix:"marker.",cLetter:"c"}),u=h&&e.marker.color!==h?h:c?n.background:n.defaultLine,l("marker.line.color",u),i(t,"marker.line")&&a(t,e,s,l,{prefix:"marker.line.",cLetter:"c"}),l("marker.line.width",c?1:0),c&&(l("marker.sizeref"),l("marker.sizemin"),l("marker.sizemode"))}},{"../../components/color":299,"../../components/colorscale/defaults":308,"../../components/colorscale/has_colorscale":311,"./subtypes":520}],517:[function(t,e,r){"use strict";function n(t,e,r){var n=e.x(),a=e.y(),o=i.extent(n.range.map(n.l2c)),l=i.extent(a.range.map(a.l2c));r.forEach(function(t,e){var n=t[0].trace;if(s.hasMarkers(n)){var i=n.marker.maxdisplayed;if(0!==i){var a=t.filter(function(t){return t.x>=o[0]&&t.x<=o[1]&&t.y>=l[0]&&t.y<=l[1]}),u=Math.ceil(a.length/i),c=0;r.forEach(function(t,r){var n=t[0].trace;s.hasMarkers(n)&&n.marker.maxdisplayed>0&&e>r&&c++});var h=Math.round(c*u/3+Math.floor(c/3)*u/7.1);t.forEach(function(t){delete t.vis}),a.forEach(function(t,e){0===Math.round((e+h)%u)&&(t.vis=!0)})}}})}var i=t("d3"),a=t("../../lib"),o=t("../../components/drawing"),s=t("./subtypes"),l=t("./arrays_to_calcdata"),u=t("./line_points");e.exports=function(t,e,r){function c(t){return t.filter(function(t){return t.vis})}n(t,e,r);var h=e.x(),f=e.y(),d=e.plot.select(".scatterlayer").selectAll("g.trace.scatter").data(r);d.enter().append("g").attr("class","trace scatter").style("stroke-miterlimit",2);var p,g,v,m="";d.each(function(t){var e=t[0].trace,r=e.line,n=i.select(this);if(e.visible===!0&&(t[0].node3=n,l(t),s.hasLines(e)||"none"!==e.fill)){var a,c,d,y,b="",x="";p="tozero"===e.fill.substr(0,6)||"to"===e.fill.substr(0,2)&&!m?n.append("path").classed("js-fill",!0):null,v&&(g=v.datum(t)),v=n.append("path").classed("js-fill",!0),-1!==["hv","vh","hvh","vhv"].indexOf(r.shape)?(c=o.steps(r.shape),d=o.steps(r.shape.split("").reverse().join(""))):c=d="spline"===r.shape?function(t){return o.smoothopen(t,r.smoothing)}:function(t){return"M"+t.join("L")},y=function(t){return"L"+d(t.reverse()).substr(1)};var _=u(t,{xaxis:h,yaxis:f,connectGaps:e.connectgaps,baseTolerance:Math.max(r.width||1,3)/4,linear:"linear"===r.shape});if(_.length){for(var w=_[0][0],A=_[_.length-1],k=A[A.length-1],M=0;M<_.length;M++){var T=_[M];a=c(T),b+=b?"L"+a.substr(1):a,x=y(T)+x,s.hasLines(e)&&T.length>1&&n.append("path").classed("js-line",!0).attr("d",a)}p?w&&k&&("y"===e.fill.charAt(e.fill.length-1)?w[1]=k[1]=f.c2p(0,!0):w[0]=k[0]=h.c2p(0,!0),p.attr("d",b+"L"+k+"L"+w+"Z")):"tonext"===e.fill.substr(0,6)&&b&&m&&g.attr("d",b+m+"Z"),m=x}}}),d.selectAll("path:not([d])").remove(),d.append("g").attr("class","points").each(function(t){var e=t[0].trace,r=i.select(this),n=s.hasMarkers(e),l=s.hasText(e);!n&&!l||e.visible!==!0?r.remove():(n&&r.selectAll("path.point").data(e.marker.maxdisplayed?c:a.identity).enter().append("path").classed("point",!0).call(o.translatePoints,h,f),l&&r.selectAll("g").data(e.marker.maxdisplayed?c:a.identity).enter().append("g").append("text").call(o.translatePoints,h,f))})}},{"../../components/drawing":317,"../../lib":349,"./arrays_to_calcdata":501,"./line_points":513,"./subtypes":520,d3:70}],518:[function(t,e,r){"use strict";var n=t("./subtypes"),i=.2;e.exports=function(t,e){var r,a,o,s,l=t.cd,u=t.xaxis,c=t.yaxis,h=[],f=l[0].trace,d=f.index,p=f.marker;if(n.hasMarkers(f)||n.hasText(f)){var g=Array.isArray(p.opacity)?1:p.opacity;if(e===!1)for(r=0;r<l.length;r++)l[r].dim=0;else for(r=0;r<l.length;r++)a=l[r],o=u.c2p(a.x),s=c.c2p(a.y),e.contains([o,s])?(h.push({curveNumber:d,pointNumber:r,x:a.x,y:a.y}),a.dim=0):a.dim=1;return l[0].node3.selectAll("path.point").style("opacity",function(t){return((t.mo+1||g+1)-1)*(t.dim?i:1)}),l[0].node3.selectAll("text").style("opacity",function(t){return t.dim?i:1}),h}}},{"./subtypes":520}],519:[function(t,e,r){"use strict";var n=t("d3"),i=t("../../components/drawing");e.exports=function(t){var e=n.select(t).selectAll("g.trace.scatter");e.style("opacity",function(t){return t[0].trace.opacity}),e.selectAll("g.points").each(function(t){n.select(this).selectAll("path.point").call(i.pointStyle,t.trace||t[0].trace),n.select(this).selectAll("text").call(i.textPointStyle,t.trace||t[0].trace)}),e.selectAll("g.trace path.js-line").call(i.lineGroupStyle),e.selectAll("g.trace path.js-fill").call(i.fillGroupStyle)}},{"../../components/drawing":317,d3:70}],520:[function(t,e,r){"use strict";e.exports={hasLines:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("lines")},hasMarkers:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("markers")},hasText:function(t){return t.visible&&t.mode&&-1!==t.mode.indexOf("text")},isBubble:function(t){return"object"==typeof t.marker&&Array.isArray(t.marker.size)}}},{}],521:[function(t,e,r){"use strict";var n=t("../../lib");e.exports=function(t,e,r,i){i("textposition"),n.coerceFont(i,"textfont",r.font)}},{"../../lib":349}],522:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n,i=r("x"),a=r("y");if(i)a?(n=Math.min(i.length,a.length),n<i.length&&(e.x=i.slice(0,n)),n<a.length&&(e.y=a.slice(0,n))):(n=i.length,r("y0"),r("dy"));else{if(!a)return 0;n=e.y.length,r("x0"),r("dx")}return n}},{}],523:[function(t,e,r){"use strict";function n(t){return{show:{valType:"boolean",dflt:!1},opacity:{valType:"number",min:0,max:1,dflt:1},scale:{valType:"number",min:0,max:10,dflt:2/3}}}var i=t("../scatter/attributes"),a=t("../../constants/gl_markers"),o=t("../../lib/extend").extendFlat,s=i.line,l=i.marker,u=l.line;e.exports={x:{valType:"data_array"},y:{valType:"data_array"},z:{valType:"data_array"},text:o({},i.text,{}),mode:o({},i.mode,{dflt:"lines+markers"}),surfaceaxis:{valType:"enumerated",values:[-1,0,1,2],dflt:-1},surfacecolor:{valType:"color"},projection:{x:n("x"),y:n("y"),z:n("z")},line:{color:s.color,width:s.width,dash:s.dash},marker:{color:l.color,symbol:{valType:"enumerated",values:Object.keys(a),dflt:"circle",arrayOk:!0},size:o({},l.size,{dflt:8}),sizeref:l.sizeref,sizemin:l.sizemin,sizemode:l.sizemode,opacity:o({},l.opacity,{arrayOk:!1}),colorscale:l.colorscale,cauto:l.cauto,cmax:l.cmax,cmin:l.cmin,autocolorscale:l.autocolorscale,reversescale:l.reversescale,showscale:l.showscale,line:{color:u.color,width:o({},u.width,{arrayOk:!1}),colorscale:u.colorscale,cauto:u.cauto,cmax:u.cmax,cmin:u.cmin,autocolorscale:u.autocolorscale,reversescale:u.reversescale}},textposition:o({},i.textposition,{dflt:"top center"}),textfont:i.textfont,_nestedModules:{error_x:"ErrorBars",error_y:"ErrorBars",error_z:"ErrorBars","marker.colorbar":"Colorbar"}}},{"../../constants/gl_markers":337,"../../lib/extend":345,"../scatter/attributes":502}],524:[function(t,e,r){"use strict";var n=t("../scatter/arrays_to_calcdata"),i=t("../scatter/marker_colorscale_calc");e.exports=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return n(r),i(e),r}},{"../scatter/arrays_to_calcdata":501,"../scatter/marker_colorscale_calc":515}],525:[function(t,e,r){"use strict";function n(t,e,r){if(!e||!e.visible)return null;for(var n=o(e),i=new Array(t.length),a=0;a<t.length;a++){var s=n(+t[a],a);i[a]=[-s[0]*r,s[1]*r]}return i}function i(t){for(var e=0;e<t.length;e++)if(t[e])return t[e].length;return 0}function a(t,e){var r=[n(t.x,t.error_x,e[0]),n(t.y,t.error_y,e[1]),n(t.z,t.error_z,e[2])],a=i(r);if(0===a)return null;for(var o=new Array(a),s=0;a>s;s++){for(var l=[[0,0,0],[0,0,0]],u=0;3>u;u++)if(r[u])for(var c=0;2>c;c++)l[c][u]=r[u][s][c];o[s]=l}return o}var o=t("../../components/errorbars/compute_error");e.exports=a},{"../../components/errorbars/compute_error":321}],526:[function(t,e,r){"use strict";function n(t,e){this.scene=t,this.uid=e,this.linePlot=null,this.scatterPlot=null,this.errorBars=null,this.textMarkers=null,this.delaunayMesh=null,this.color=null,this.mode="",this.dataPoints=[],this.axesBounds=[[-(1/0),-(1/0),-(1/0)],[1/0,1/0,1/0]],this.textLabels=null,this.data=null}function i(t,e,r){var n,i=(r+1)%3,a=(r+2)%3,o=[],s=[];for(n=0;n<t.length;++n){var l=t[n];!isNaN(l[i])&&isFinite(l[i])&&!isNaN(l[a])&&isFinite(l[a])&&(o.push([l[i],l[a]]),s.push(n))}var u=m(o);for(n=0;n<u.length;++n)for(var c=u[n],h=0;h<c.length;++h)c[h]=s[c[h]];return{positions:t,cells:u,meshColor:e}}function a(t){for(var e=[0,0,0],r=[[0,0,0],[0,0,0],[0,0,0]],n=[0,0,0],i=0;3>i;i++){var a=t[i];a&&a.copy_zstyle!==!1&&(a=t[2]),a&&(e[i]=a.width/2,r[i]=b(a.color),n=a.thickness)}return{capSize:e,color:r,lineWidth:n}}function o(t){var e=[0,0];return Array.isArray(t)?[0,-1]:(t.indexOf("bottom")>=0&&(e[1]+=1),t.indexOf("top")>=0&&(e[1]-=1),t.indexOf("left")>=0&&(e[0]-=1),t.indexOf("right")>=0&&(e[0]+=1),e)}function s(t,e){return e(4*t)}function l(t){return A[t]}function u(t,e,r,n,i){var a=null;if(Array.isArray(t)){a=[];for(var o=0;e>o;o++)void 0===t[o]?a[o]=n:a[o]=r(t[o],i)}else a=r(t,y.identity);return a}function c(t,e){var r,n,i,c,h,f,d=[],p=t.fullSceneLayout,g=t.dataScale,v=p.xaxis,m=p.yaxis,w=p.zaxis,A=e.marker,M=e.line,T=e.x||[],E=e.y||[],L=e.z||[],S=T.length;
+for(n=0;S>n;n++)i=v.d2l(T[n])*g[0],c=m.d2l(E[n])*g[1],h=w.d2l(L[n])*g[2],d[n]=[i,c,h];if(Array.isArray(e.text))f=e.text;else if(void 0!==e.text)for(f=new Array(S),n=0;S>n;n++)f[n]=e.text;if(r={position:d,mode:e.mode,text:f},"line"in e&&(r.lineColor=b(M.color),r.lineWidth=M.width,r.lineDashes=M.dash),"marker"in e){var C=_(e);r.scatterColor=x(A,1,S),r.scatterSize=u(A.size,S,s,20,C),r.scatterMarker=u(A.symbol,S,l,"\u25cf"),r.scatterLineWidth=A.line.width,r.scatterLineColor=x(A.line,1,S),r.scatterAngle=0}"textposition"in e&&(r.textOffset=o(e.textposition),r.textColor=x(e.textfont,1,S),r.textSize=u(e.textfont.size,S,y.identity,12),r.textFont=e.textfont.family,r.textAngle=0);var P=["x","y","z"];for(r.project=[!1,!1,!1],r.projectScale=[1,1,1],r.projectOpacity=[1,1,1],n=0;3>n;++n){var z=e.projection[P[n]];(r.project[n]=z.show)&&(r.projectOpacity[n]=z.opacity,r.projectScale[n]=z.scale)}r.errorBounds=k(e,g);var R=a([e.error_x,e.error_y,e.error_z]);return r.errorColor=R.color,r.errorLineWidth=R.lineWidth,r.errorCapSize=R.capSize,r.delaunayAxis=e.surfaceaxis,r.delaunayColor=b(e.surfacecolor),r}function h(t){if(Array.isArray(t)){var e=t[0];return Array.isArray(e)&&(t=e),"rgb("+t.slice(0,3).map(function(t){return Math.round(255*t)})+")"}return null}function f(t,e){var r=new n(t,e.uid);return r.update(e),r}var d=t("gl-line3d"),p=t("gl-scatter3d"),g=t("gl-error3d"),v=t("gl-mesh3d"),m=t("delaunay-triangulate"),y=t("../../lib"),b=t("../../lib/str2rgbarray"),x=t("../../lib/gl_format_color"),_=t("../scatter/make_bubble_size_func"),w=t("../../constants/gl3d_dashes"),A=t("../../constants/gl_markers"),k=t("./calc_errors"),M=n.prototype;M.handlePick=function(t){if(t.object&&(t.object===this.linePlot||t.object===this.delaunayMesh||t.object===this.textMarkers||t.object===this.scatterPlot)){t.object.highlight&&t.object.highlight(null),this.scatterPlot&&(t.object=this.scatterPlot,this.scatterPlot.highlight(t.data)),this.textLabels&&void 0!==this.textLabels[t.data.index]?t.textLabel=this.textLabels[t.data.index]:t.textLabel="";var e=t.data.index;return t.traceCoordinate=[this.data.x[e],this.data.y[e],this.data.z[e]],!0}},M.update=function(t){var e,r,n,a,o=this.scene.glplot.gl,s=w.solid;this.data=t;var l=c(this.scene,t);"mode"in l&&(this.mode=l.mode),"lineDashes"in l&&l.lineDashes in w&&(s=w[l.lineDashes]),this.color=h(l.scatterColor)||h(l.lineColor),this.dataPoints=l.position,e={gl:o,position:l.position,color:l.lineColor,lineWidth:l.lineWidth||1,dashes:s[0],dashScale:s[1],opacity:t.opacity},-1!==this.mode.indexOf("lines")?this.linePlot?this.linePlot.update(e):(this.linePlot=d(e),this.scene.glplot.add(this.linePlot)):this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose(),this.linePlot=null);var u=t.opacity;if(t.marker&&t.marker.opacity&&(u*=t.marker.opacity),r={gl:o,position:l.position,color:l.scatterColor,size:l.scatterSize,glyph:l.scatterMarker,opacity:u,orthographic:!0,lineWidth:l.scatterLineWidth,lineColor:l.scatterLineColor,project:l.project,projectScale:l.projectScale,projectOpacity:l.projectOpacity},-1!==this.mode.indexOf("markers")?this.scatterPlot?this.scatterPlot.update(r):(this.scatterPlot=p(r),this.scatterPlot.highlightScale=1,this.scene.glplot.add(this.scatterPlot)):this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose(),this.scatterPlot=null),a={gl:o,position:l.position,glyph:l.text,color:l.textColor,size:l.textSize,angle:l.textAngle,alignment:l.textOffset,font:l.textFont,orthographic:!0,lineWidth:0,project:!1,opacity:t.opacity},this.textLabels=l.text,-1!==this.mode.indexOf("text")?this.textMarkers?this.textMarkers.update(a):(this.textMarkers=p(a),this.textMarkers.highlightScale=1,this.scene.glplot.add(this.textMarkers)):this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose(),this.textMarkers=null),n={gl:o,position:l.position,color:l.errorColor,error:l.errorBounds,lineWidth:l.errorLineWidth,capSize:l.errorCapSize,opacity:t.opacity},this.errorBars?l.errorBounds?this.errorBars.update(n):(this.scene.glplot.remove(this.errorBars),this.errorBars.dispose(),this.errorBars=null):l.errorBounds&&(this.errorBars=g(n),this.scene.glplot.add(this.errorBars)),l.delaunayAxis>=0){var f=i(l.position,l.delaunayColor,l.delaunayAxis);this.delaunayMesh?this.delaunayMesh.update(f):(f.gl=o,this.delaunayMesh=v(f),this.scene.glplot.add(this.delaunayMesh))}else this.delaunayMesh&&(this.scene.glplot.remove(this.delaunayMesh),this.delaunayMesh.dispose(),this.delaunayMesh=null)},M.dispose=function(){this.linePlot&&(this.scene.glplot.remove(this.linePlot),this.linePlot.dispose()),this.scatterPlot&&(this.scene.glplot.remove(this.scatterPlot),this.scatterPlot.dispose()),this.errorBars&&(this.scene.remove(this.errorBars),this.errorBars.dispose()),this.textMarkers&&(this.scene.glplot.remove(this.textMarkers),this.textMarkers.dispose()),this.delaunayMesh&&(this.scene.glplot.remove(this.textMarkers),this.delaunayMesh.dispose())},e.exports=f},{"../../constants/gl3d_dashes":336,"../../constants/gl_markers":337,"../../lib":349,"../../lib/gl_format_color":347,"../../lib/str2rgbarray":359,"../scatter/make_bubble_size_func":514,"./calc_errors":525,"delaunay-triangulate":71,"gl-error3d":78,"gl-line3d":84,"gl-mesh3d":107,"gl-scatter3d":150}],527:[function(t,e,r){"use strict";function n(t,e,r){var n=0,i=r("x"),a=r("y"),o=r("z");return i&&a&&o&&(n=Math.min(i.length,a.length,o.length),n<i.length&&(e.x=i.slice(0,n)),n<a.length&&(e.y=a.slice(0,n)),n<o.length&&(e.z=o.slice(0,n))),n}var i=t("../../lib"),a=t("../scatter/subtypes"),o=t("../scatter/marker_defaults"),s=t("../scatter/line_defaults"),l=t("../scatter/text_defaults"),u=t("../../components/errorbars/defaults"),c=t("./attributes");e.exports=function(t,e,r,h){function f(r,n){return i.coerce(t,e,c,r,n)}var d=n(t,e,f);if(!d)return void(e.visible=!1);f("text"),f("mode"),a.hasLines(e)&&s(t,e,r,f),a.hasMarkers(e)&&o(t,e,r,h,f),a.hasText(e)&&l(t,e,h,f);var p=(e.line||{}).color,g=(e.marker||{}).color;f("surfaceaxis")>=0&&f("surfacecolor",p||g);for(var v=["x","y","z"],m=0;3>m;++m){var y="projection."+v[m];f(y+".show")&&(f(y+".opacity"),f(y+".scale"))}u(t,e,r,{axis:"z"}),u(t,e,r,{axis:"y",inherit:"z"}),u(t,e,r,{axis:"x",inherit:"z"})}},{"../../components/errorbars/defaults":322,"../../lib":349,"../scatter/line_defaults":512,"../scatter/marker_defaults":516,"../scatter/subtypes":520,"../scatter/text_defaults":521,"./attributes":523}],528:[function(t,e,r){"use strict";var n={};n.plot=t("./convert"),n.attributes=t("./attributes"),n.markerSymbols=t("../../constants/gl_markers"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.moduleType="trace",n.name="scatter3d",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","symbols","markerColorscale","showLegend"],n.meta={},e.exports=n},{"../../constants/gl_markers":337,"../../plots/gl3d":400,"../scatter/colorbar":505,"./attributes":523,"./calc":524,"./convert":526,"./defaults":527}],529:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../plots/attributes"),a=t("../../lib/extend").extendFlat,o=n.marker,s=n.line,l=o.line;e.exports={lon:{valType:"data_array"},lat:{valType:"data_array"},locations:{valType:"data_array"},locationmode:{valType:"enumerated",values:["ISO-3","USA-states","country names"],dflt:"ISO-3"},mode:a({},n.mode,{dflt:"markers"}),text:a({},n.text,{}),line:{color:s.color,width:s.width,dash:s.dash},marker:{symbol:o.symbol,opacity:o.opacity,size:o.size,sizeref:o.sizeref,sizemin:o.sizemin,sizemode:o.sizemode,color:o.color,colorscale:o.colorscale,cauto:o.cauto,cmax:o.cmax,cmin:o.cmin,autocolorscale:o.autocolorscale,reversescale:o.reversescale,showscale:o.showscale,line:{color:l.color,width:l.width,colorscale:l.colorscale,cauto:l.cauto,cmax:l.cmax,cmin:l.cmin,autocolorscale:l.autocolorscale,reversescale:l.reversescale}},textfont:n.textfont,textposition:n.textposition,hoverinfo:a({},i.hoverinfo,{flags:["lon","lat","location","text","name"]}),_nestedModules:{"marker.colorbar":"Colorbar"}}},{"../../lib/extend":345,"../../plots/attributes":367,"../scatter/attributes":502}],530:[function(t,e,r){"use strict";var n=t("../scatter/marker_colorscale_calc");e.exports=function(t,e){var r=[{x:!1,y:!1,trace:e,t:{}}];return n(e),r}},{"../scatter/marker_colorscale_calc":515}],531:[function(t,e,r){"use strict";function n(t,e,r){var n,i,a=0,o=r("locations");return o?(r("locationmode"),a=o.length):(n=r("lon")||[],i=r("lat")||[],a=Math.min(n.length,i.length),a<n.length&&(e.lon=n.slice(0,a)),a<i.length&&(e.lat=i.slice(0,a)),a)}var i=t("../../lib"),a=t("../scatter/subtypes"),o=t("../scatter/marker_defaults"),s=t("../scatter/line_defaults"),l=t("../scatter/text_defaults"),u=t("./attributes");e.exports=function(t,e,r,c){function h(r,n){return i.coerce(t,e,u,r,n)}var f=n(t,e,h);return f?(h("text"),h("mode"),a.hasLines(e)&&s(t,e,r,h),a.hasMarkers(e)&&o(t,e,r,c,h),a.hasText(e)&&l(t,e,c,h),void h("hoverinfo",1===c._dataLength?"lon+lat+location+text":void 0)):void(e.visible=!1)}},{"../../lib":349,"../scatter/line_defaults":512,"../scatter/marker_defaults":516,"../scatter/subtypes":520,"../scatter/text_defaults":521,"./attributes":529}],532:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("./calc"),n.plot=t("./plot").plot,n.moduleType="trace",n.name="scattergeo",n.basePlotModule=t("../../plots/geo"),n.categories=["geo","symbols","markerColorscale","showLegend"],n.meta={},e.exports=n},{"../../plots/geo":385,"../scatter/colorbar":505,"./attributes":529,"./calc":530,"./defaults":531,"./plot":533}],533:[function(t,e,r){"use strict";function n(t,e,r){function n(t,n){f(t,e,n,r)}var i=t.marker;if(n(t.text,"tx"),n(t.textposition,"tp"),t.textfont&&(n(t.textfont.size,"ts"),n(t.textfont.color,"tc"),n(t.textfont.family,"tf")),i&&i.line){var a=i.line;n(i.opacity,"mo"),n(i.symbol,"mx"),n(i.color,"mc"),n(i.size,"ms"),n(a.color,"mlc"),n(a.width,"mlw")}}function i(t){for(var e=t.lon.length,r=new Array(e),n=0;e>n;n++)r[n]=[t.lon[n],t.lat[n]];return{type:"LineString",coordinates:r,trace:t}}function a(t,e){function r(e){var r=t.mockAxis;return u.tickText(r,r.c2l(e),"hover").text+"\xb0"}var n=e.hoverinfo;if("none"===n)return function(t){delete t.textLabel};var i="all"===n?v.hoverinfo.flags:n.split("+"),a=-1!==i.indexOf("location")&&Array.isArray(e.locations),o=-1!==i.indexOf("lon"),s=-1!==i.indexOf("lat"),l=-1!==i.indexOf("text");return function(t){var n=[];a?n.push(t.location):o&&s?n.push("("+r(t.lon)+", "+r(t.lat)+")"):o?n.push("lon: "+r(t.lon)):s&&n.push("lat: "+r(t.lat)),l&&n.push(t.tx||e.text),t.textLabel=n.join("<br>")}}function o(t){var e=Array.isArray(t.locations);return function(r,n){return{points:[{data:t._input,fullData:t,curveNumber:t.index,pointNumber:n,lon:r.lon,lat:r.lat,location:e?r.location:null}]}}}var s=t("d3"),l=t("../../plots/cartesian/graph_interact"),u=t("../../plots/cartesian/axes"),c=t("../../lib/topojson_utils").getTopojsonFeatures,h=t("../../lib/geo_location_utils").locationToFeature,f=t("../../lib/array_to_calc_item"),d=t("../../components/color"),p=t("../../components/drawing"),g=t("../scatter/subtypes"),v=t("./attributes"),m=e.exports={};m.calcGeoJSON=function(t,e){var r,i,a,o,s=[],l=Array.isArray(t.locations);l?(o=t.locations,r=o.length,i=c(t,e),a=function(t,e){var r=h(t.locationmode,o[e],i);return void 0!==r?r.properties.ct:void 0}):(r=t.lon.length,a=function(t,e){return[t.lon[e],t.lat[e]]});for(var u=0;r>u;u++){var f=a(t,u);if(f){var d={lon:f[0],lat:f[1],location:l?t.locations[u]:null};n(t,d,u),s.push(d)}}return s.length>0&&(s[0].trace=t),s},m.plot=function(t,e){var r=t.framework.select(".scattergeolayer").selectAll("g.trace.scattergeo").data(e,function(t){return t.uid});r.enter().append("g").attr("class","trace scattergeo"),r.exit().remove(),r.each(function(t){g.hasLines(t)&&s.select(this).append("path").datum(i(t)).attr("class","js-line")}),r.append("g").attr("class","points").each(function(e){function r(r,n){if(t.showHover){var i=t.projection([r.lon,r.lat]);f(r),l.loneHover({x:i[0],y:i[1],name:v?e.name:void 0,text:r.textLabel,color:r.mc||(e.marker||{}).color},{container:t.hoverContainer.node()}),t.graphDiv.emit("plotly_hover",d(r,n))}}function n(e,r){t.graphDiv.emit("plotly_click",d(e,r))}var i=s.select(this),u=g.hasMarkers(e),c=g.hasText(e);if(u||c){var h=m.calcGeoJSON(e,t.topojson),f=a(t,e),d=o(e),p=e.hoverinfo,v="all"===p||-1!==p.indexOf("name");u&&i.selectAll("path.point").data(h).enter().append("path").attr("class","point").on("mouseover",r).on("click",n).on("mouseout",function(){l.loneUnhover(t.hoverContainer)}).on("mousedown",function(){l.loneUnhover(t.hoverContainer)}).on("mouseup",r),c&&i.selectAll("g").data(h).enter().append("g").append("text")}}),m.style(t)},m.style=function(t){var e=t.framework.selectAll("g.trace.scattergeo");e.style("opacity",function(t){return t.opacity}),e.selectAll("g.points").each(function(t){s.select(this).selectAll("path.point").call(p.pointStyle,t),s.select(this).selectAll("text").call(p.textPointStyle,t)}),e.selectAll("path.js-line").style("fill","none").each(function(t){var e=t.trace,r=e.line||{};s.select(this).call(d.stroke,r.color).call(p.dashLine,r.dash||"",r.width||0)})}},{"../../components/color":299,"../../components/drawing":317,"../../lib/array_to_calc_item":341,"../../lib/geo_location_utils":346,"../../lib/topojson_utils":361,"../../plots/cartesian/axes":369,"../../plots/cartesian/graph_interact":374,"../scatter/subtypes":520,"./attributes":529,d3:70}],534:[function(t,e,r){"use strict";var n=t("../scatter/attributes"),i=t("../../constants/gl2d_dashes"),a=t("../../constants/gl_markers"),o=t("../../lib/extend").extendFlat,s=n.line,l=n.marker,u=l.line;e.exports={x:n.x,x0:n.x0,dx:n.dx,y:n.y,y0:n.y0,dy:n.dy,text:o({},n.text,{}),mode:{valType:"flaglist",flags:["lines","markers"],extras:["none"]},line:{color:s.color,width:s.width,dash:{valType:"enumerated",values:Object.keys(i),dflt:"solid"}},marker:{color:l.color,symbol:{valType:"enumerated",values:Object.keys(a),dflt:"circle",arrayOk:!0},size:l.size,sizeref:l.sizeref,sizemin:l.sizemin,sizemode:l.sizemode,opacity:l.opacity,colorscale:l.colorscale,cauto:l.cauto,cmax:l.cmax,cmin:l.cmin,autocolorscale:l.autocolorscale,reversescale:l.reversescale,showscale:l.showscale,line:{color:u.color,width:u.width,colorscale:u.colorscale,cauto:u.cauto,cmax:u.cmax,cmin:u.cmin,autocolorscale:u.autocolorscale,reversescale:u.reversescale}},fill:o({},n.fill,{values:["none","tozeroy","tozerox"]}),fillcolor:n.fillcolor,_nestedModules:{error_x:"ErrorBars",error_y:"ErrorBars","marker.colorbar":"Colorbar"}}},{"../../constants/gl2d_dashes":335,"../../constants/gl_markers":337,"../../lib/extend":345,"../scatter/attributes":502}],535:[function(t,e,r){"use strict";function n(t,e){this.scene=t,this.uid=e,this.xData=[],this.yData=[],this.textLabels=[],this.color="rgb(0, 0, 0)",this.name="",this.hoverinfo="all",this.idToIndex=[],this.bounds=[0,0,0,0],this.hasLines=!1,this.lineOptions={positions:new Float32Array,color:[0,0,0,1],width:1,fill:[!1,!1,!1,!1],fillColor:[[0,0,0,1],[0,0,0,1],[0,0,0,1],[0,0,0,1]],dashes:[1]},this.line=d(t.glplot,this.lineOptions),this.line._trace=this,this.hasErrorX=!1,this.errorXOptions={positions:new Float32Array,errors:new Float32Array,lineWidth:1,capSize:0,color:[0,0,0,1]},this.errorX=p(t.glplot,this.errorXOptions),this.errorX._trace=this,this.hasErrorY=!1,this.errorYOptions={positions:new Float32Array,errors:new Float32Array,lineWidth:1,capSize:0,color:[0,0,0,1]},this.errorY=p(t.glplot,this.errorYOptions),this.errorY._trace=this,this.hasMarkers=!1,this.scatterOptions={positions:new Float32Array,sizes:[],colors:[],glyphs:[],borderWidths:[],borderColors:[],size:12,color:[0,0,0,1],borderSize:1,borderColor:[0,0,0,1]},this.scatter=h(t.glplot,this.scatterOptions),this.scatter._trace=this,this.fancyScatter=f(t.glplot,this.scatterOptions),this.fancyScatter._trace=this}function i(t,e,r){return Array.isArray(e)||(e=[e]),a(t,e,r)}function a(t,e,r){for(var n=new Array(r),i=e[0],a=0;r>a;++a)n[a]=t(a>=e.length?i:e[a]);return n}function o(t,e,r){return l(S(t,r),L(e,r),r)}function s(t,e,r,n){var i=x(t,e,n);return i=Array.isArray(i[0])?i:a(v.identity,[i],n),l(i,L(r,n),n)}function l(t,e,r){for(var n=new Array(4*r),i=0;r>i;++i){for(var a=0;3>a;++a)n[4*i+a]=t[i][a];n[4*i+3]=t[i][3]*e[i]}return n}function u(t,e){if(void 0===Float32Array.slice){for(var r=new Float32Array(e),n=0;e>n;n++)r[n]=t[n];return r}return t.slice(0,e)}function c(t,e){var r=new n(t,e.uid);return r.update(e),r}var h=t("gl-scatter2d"),f=t("gl-scatter2d-fancy"),d=t("gl-line2d"),p=t("gl-error2d"),g=t("fast-isnumeric"),v=t("../../lib"),m=t("../../plots/cartesian/axes"),y=t("../../components/errorbars"),b=t("../../lib/str2rgbarray"),x=t("../../lib/gl_format_color"),_=t("../scatter/subtypes"),w=t("../scatter/make_bubble_size_func"),A=t("../scatter/get_trace_color"),k=t("../../constants/gl_markers"),M=t("../../constants/gl2d_dashes"),T=["xaxis","yaxis"],E=n.prototype;E.handlePick=function(t){var e=this.idToIndex[t.pointId];return{trace:this,dataCoord:t.dataCoord,traceCoord:[this.xData[e],this.yData[e]],textLabel:Array.isArray(this.textLabels)?this.textLabels[e]:this.textLabels,color:Array.isArray(this.color)?this.color[e]:this.color,name:this.name,hoverinfo:this.hoverinfo}},E.isFancy=function(t){if("linear"!==this.scene.xaxis.type)return!0;if("linear"!==this.scene.yaxis.type)return!0;if(!t.x||!t.y)return!0;var e=t.marker||{};if(Array.isArray(e.symbol)||"circle"!==e.symbol||Array.isArray(e.size)||Array.isArray(e.line.width)||Array.isArray(e.opacity))return!0;var r=e.color;if(Array.isArray(r))return!0;var n=Array.isArray(e.line.color);return Array.isArray(n)?!0:this.hasErrorX?!0:this.hasErrorY?!0:!1};var L=i.bind(null,function(t){return+t}),S=i.bind(null,b),C=i.bind(null,function(t){return k[t]||"\u25cf"});E.update=function(t){t.visible!==!0?(this.hasLines=!1,this.hasErrorX=!1,this.hasErrorY=!1,this.hasMarkers=!1):(this.hasLines=_.hasLines(t),this.hasErrorX=t.error_x.visible===!0,this.hasErrorY=t.error_y.visible===!0,this.hasMarkers=_.hasMarkers(t)),this.textLabels=t.text,this.name=t.name,this.hoverinfo=t.hoverinfo,this.bounds=[1/0,1/0,-(1/0),-(1/0)],this.isFancy(t)?this.updateFancy(t):this.updateFast(t),this.color=A(t,{})},E.updateFast=function(t){for(var e,r,n=this.xData=t.x,i=this.yData=t.y,a=n.length,o=new Array(a),s=new Float32Array(2*a),l=this.bounds,c=0,h=0,f=0;a>f;++f)e=n[f],r=i[f],g(e)&&g(r)&&(o[c++]=f,s[h++]=e,s[h++]=r,l[0]=Math.min(l[0],e),l[1]=Math.min(l[1],r),l[2]=Math.max(l[2],e),l[3]=Math.max(l[3],r));s=u(s,h),this.idToIndex=o,this.updateLines(t,s),this.updateError("X",t),this.updateError("Y",t);var d;if(this.hasMarkers){this.scatterOptions.positions=s;var p=b(t.marker.color),v=b(t.marker.line.color),m=t.opacity*t.marker.opacity;p[3]*=m,this.scatterOptions.color=p,v[3]*=m,this.scatterOptions.borderColor=v,d=t.marker.size,this.scatterOptions.size=d,this.scatterOptions.borderSize=t.marker.line.width,this.scatter.update(this.scatterOptions)}else this.scatterOptions.positions=new Float32Array,this.scatterOptions.glyphs=[],this.scatter.update(this.scatterOptions);this.scatterOptions.positions=new Float32Array,this.scatterOptions.glyphs=[],this.fancyScatter.update(this.scatterOptions),this.expandAxesFast(l,d)},E.updateFancy=function(t){var e,r,n,a,o,l,c,h,f=this.scene,d=f.xaxis,p=f.yaxis,g=this.bounds,v=this.xData=d.makeCalcdata(t,"x"),m=this.yData=p.makeCalcdata(t,"y"),b=y.calcFromTrace(t,f.fullLayout),x=v.length,_=new Array(x),A=new Float32Array(2*x),k=new Float32Array(4*x),M=new Float32Array(4*x),T=0,E=0,S=0,P=0,z="log"===d.type?function(t){return d.d2l(t)}:function(t){return t},R="log"===p.type?function(t){return p.d2l(t)}:function(t){return t};for(e=0;x>e;++e)n=z(v[e]),a=R(m[e]),isNaN(n)||isNaN(a)||(_[T++]=e,A[E++]=n,A[E++]=a,o=k[S++]=n-b[e].xs||0,l=k[S++]=b[e].xh-n||0,k[S++]=0,k[S++]=0,M[P++]=0,M[P++]=0,c=M[P++]=a-b[e].ys||0,h=M[P++]=b[e].yh-a||0,g[0]=Math.min(g[0],n-o),g[1]=Math.min(g[1],a-c),g[2]=Math.max(g[2],n+l),g[3]=Math.max(g[3],a+h));A=u(A,E),this.idToIndex=_,this.updateLines(t,A),this.updateError("X",t,A,k),this.updateError("Y",t,A,M);var O;if(this.hasMarkers){this.scatterOptions.positions=A,this.scatterOptions.sizes=new Array(T),this.scatterOptions.glyphs=new Array(T),this.scatterOptions.borderWidths=new Array(T),this.scatterOptions.colors=new Array(4*T),this.scatterOptions.borderColors=new Array(4*T);var I,j=w(t),N=t.marker,F=N.opacity,B=t.opacity,D=s(N,F,B,x),U=C(N.symbol,x),V=L(N.line.width,x),q=s(N.line,F,B,x);for(O=i(j,N.size,x),e=0;T>e;++e)for(I=_[e],this.scatterOptions.sizes[e]=4*O[I],this.scatterOptions.glyphs[e]=U[I],this.scatterOptions.borderWidths[e]=.5*V[I],r=0;4>r;++r)this.scatterOptions.colors[4*e+r]=D[4*I+r],this.scatterOptions.borderColors[4*e+r]=q[4*I+r];this.fancyScatter.update(this.scatterOptions)}else this.scatterOptions.positions=new Float32Array,this.scatterOptions.glyphs=[],this.fancyScatter.update(this.scatterOptions);this.scatterOptions.positions=new Float32Array,this.scatterOptions.glyphs=[],this.scatter.update(this.scatterOptions),this.expandAxesFancy(v,m,O)},E.updateLines=function(t,e){if(this.hasLines){this.lineOptions.positions=e;var r=b(t.line.color);this.hasMarkers&&(r[3]*=t.marker.opacity);for(var n=Math.round(.5*this.lineOptions.width),i=(M[t.line.dash]||[1]).slice(),a=0;a<i.length;++a)i[a]*=n;switch(t.fill){case"tozeroy":this.lineOptions.fill=[!1,!0,!1,!1];break;case"tozerox":this.lineOptions.fill=[!0,!1,!1,!1];break;default:this.lineOptions.fill=[!1,!1,!1,!1]}var o=b(t.fillcolor);this.lineOptions.color=r,this.lineOptions.width=2*t.line.width,this.lineOptions.dashes=i,this.lineOptions.fillColor=[o,o,o,o]}else this.lineOptions.positions=new Float32Array;this.line.update(this.lineOptions)},E.updateError=function(t,e,r,n){var i=this["error"+t],a=e["error_"+t.toLowerCase()],s=this["error"+t+"Options"];"x"===t.toLowerCase()&&a.copy_ystyle&&(a=e.error_y),this["hasError"+t]?(s.positions=r,s.errors=n,s.capSize=a.width,s.lineWidth=a.thickness/2,s.color=o(a.color,1,1)):s.positions=new Float32Array,i.update(s)},E.expandAxesFast=function(t,e){for(var r,n,i,a=e||10,o=0;2>o;o++)r=this.scene[T[o]],n=r._min,n||(n=[]),n.push({val:t[o],pad:a}),i=r._max,i||(i=[]),i.push({val:t[o+2],pad:a})},E.expandAxesFancy=function(t,e,r){var n=this.scene,i={padded:!0,ppad:r};m.expand(n.xaxis,t,i),m.expand(n.yaxis,e,i)},E.dispose=function(){this.line.dispose(),this.errorX.dispose(),this.errorY.dispose(),this.scatter.dispose(),this.fancyScatter.dispose()},e.exports=c},{"../../components/errorbars":323,"../../constants/gl2d_dashes":335,"../../constants/gl_markers":337,"../../lib":349,"../../lib/gl_format_color":347,"../../lib/str2rgbarray":359,"../../plots/cartesian/axes":369,"../scatter/get_trace_color":509,"../scatter/make_bubble_size_func":514,"../scatter/subtypes":520,"fast-isnumeric":74,"gl-error2d":76,"gl-line2d":82,"gl-scatter2d":147,"gl-scatter2d-fancy":142}],536:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../scatter/constants"),a=t("../scatter/subtypes"),o=t("../scatter/xy_defaults"),s=t("../scatter/marker_defaults"),l=t("../scatter/line_defaults"),u=t("../scatter/fillcolor_defaults"),c=t("../../components/errorbars/defaults"),h=t("./attributes");e.exports=function(t,e,r,f){function d(r,i){return n.coerce(t,e,h,r,i)}var p=o(t,e,d);return p?(d("text"),d("mode",p<i.PTS_LINESONLY?"lines+markers":"lines"),a.hasLines(e)&&l(t,e,r,d),a.hasMarkers(e)&&s(t,e,r,f,d),d("fill"),"none"!==e.fill&&u(t,e,r,d),c(t,e,r,{axis:"y"}),void c(t,e,r,{axis:"x",inherit:"y"})):void(e.visible=!1)}},{"../../components/errorbars/defaults":322,"../../lib":349,"../scatter/constants":506,"../scatter/fillcolor_defaults":508,"../scatter/line_defaults":512,"../scatter/marker_defaults":516,"../scatter/subtypes":520,"../scatter/xy_defaults":522,"./attributes":534}],537:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../scatter/colorbar"),n.calc=t("../scatter3d/calc"),n.plot=t("./convert"),n.moduleType="trace",n.name="scattergl",n.basePlotModule=t("../../plots/gl2d"),n.categories=["gl2d","symbols","errorBarsOK","markerColorscale","showLegend"],n.meta={},e.exports=n},{"../../plots/gl2d":397,"../scatter/colorbar":505,"../scatter3d/calc":524,"./attributes":534,"./convert":535,"./defaults":536}],538:[function(t,e,r){"use strict";function n(t){return{valType:"boolean",dflt:!1}}function i(t){return{show:{valType:"boolean",dflt:!1},project:{x:n("x"),y:n("y"),z:n("z")},color:{valType:"color",dflt:"#000"},usecolormap:{valType:"boolean",dflt:!1},width:{valType:"number",min:1,max:16,dflt:2},highlight:{valType:"boolean",dflt:!1},highlightColor:{valType:"color",dflt:"#000"},highlightWidth:{valType:"number",min:1,max:16,dflt:2}}}var a=t("../../components/colorscale/attributes"),o=t("../../lib/extend").extendFlat;e.exports={z:{valType:"data_array"},x:{valType:"data_array"},y:{valType:"data_array"},text:{valType:"data_array"},zauto:a.zauto,zmin:a.zmin,zmax:a.zmax,colorscale:a.colorscale,autocolorscale:o({},a.autocolorscale,{dflt:!1}),reversescale:a.reversescale,showscale:a.showscale,contours:{x:i("x"),y:i("y"),z:i("z")},hidesurface:{valType:"boolean",dflt:!1},lighting:{ambient:{valType:"number",min:0,max:1,dflt:.8},diffuse:{valType:"number",min:0,max:1,dflt:.8},specular:{valType:"number",min:0,max:2,dflt:.05},roughness:{valType:"number",min:0,max:1,dflt:.5},fresnel:{valType:"number",min:0,max:5,dflt:.2}},opacity:{valType:"number",min:0,max:1,dflt:1},_nestedModules:{colorbar:"Colorbar"}}},{"../../components/colorscale/attributes":305,"../../lib/extend":345}],539:[function(t,e,r){"use strict";var n=t("../../components/colorscale/calc");e.exports=function(t,e){n(e,e.z,"","z")}},{"../../components/colorscale/calc":306}],540:[function(t,e,r){"use strict";function n(t,e,r){this.scene=t,this.uid=r,this.surface=e,this.data=null,this.showContour=[!1,!1,!1],this.dataScale=1}function i(t,e){return void 0===e&&(e=1),t.map(function(t){var r=t[0],n=d(t[1]),i=n.toRgb();return{index:r,rgb:[i.r,i.g,i.b,e]}})}function a(t){var e=t.shape,r=[e[0]+2,e[1]+2],n=u(new Float32Array(r[0]*r[1]),r);return f.assign(n.lo(1,1).hi(e[0],e[1]),t),f.assign(n.lo(1).hi(e[0],1),t.hi(e[0],1)),f.assign(n.lo(1,r[1]-1).hi(e[0],1),t.lo(0,e[1]-1).hi(e[0],1)),f.assign(n.lo(0,1).hi(1,e[1]),t.hi(1)),f.assign(n.lo(r[0]-1,1).hi(1,e[1]),t.lo(e[0]-1)),n.set(0,0,t.get(0,0)),n.set(0,r[1]-1,t.get(0,e[1]-1)),n.set(r[0]-1,0,t.get(e[0]-1,0)),n.set(r[0]-1,r[1]-1,t.get(e[0]-1,e[1]-1)),n}function o(t){var e=Math.max(t[0].shape[0],t[0].shape[1]);if(g>e){for(var r=g/e,n=[0|Math.floor(t[0].shape[0]*r+1),0|Math.floor(t[0].shape[1]*r+1)],i=n[0]*n[1],o=0;3>o;++o){var s=a(t[o]),l=u(new Float32Array(i),n);c(l,s,[r,0,0,0,r,0,0,0,1]),t[o]=l}return r}return 1}function s(t,e){var r=t.glplot.gl,i=l({gl:r}),a=new n(t,i,e.uid);return a.update(e),t.glplot.add(i),a}var l=t("gl-surface3d"),u=t("ndarray"),c=t("ndarray-homography"),h=t("ndarray-fill"),f=t("ndarray-ops"),d=t("tinycolor2"),p=t("../../lib/str2rgbarray"),g=128,v=n.prototype;v.handlePick=function(t){if(t.object===this.surface){var e=[Math.min(0|Math.round(t.data.index[0]/this.dataScale-1),this.data.z[0].length-1),Math.min(0|Math.round(t.data.index[1]/this.dataScale-1),this.data.z.length-1)],r=[0,0,0];Array.isArray(this.data.x[0])?r[0]=this.data.x[e[1]][e[0]]:r[0]=this.data.x[e[0]],Array.isArray(this.data.y[0])?r[1]=this.data.y[e[1]][e[0]]:r[1]=this.data.y[e[1]],r[2]=this.data.z[e[1]][e[0]],t.traceCoordinate=r;var n=this.scene.fullSceneLayout;t.dataCoordinate=[n.xaxis.d2l(r[0])*this.scene.dataScale[0],n.yaxis.d2l(r[1])*this.scene.dataScale[1],n.zaxis.d2l(r[2])*this.scene.dataScale[2]];var i=this.data.text;return i&&i[e[1]]&&void 0!==i[e[1]][e[0]]?t.textLabel=i[e[1]][e[0]]:t.textLabel="",t.data.dataCoordinate=t.dataCoordinate.slice(),this.surface.highlight(t.data),this.scene.glplot.spikes.position=t.dataCoordinate,!0}},v.setContourLevels=function(){for(var t=[[],[],[]],e=!1,r=0;3>r;++r)this.showContour[r]&&(e=!0,t[r]=this.scene.contourLevels[r]);e&&this.surface.update({levels:t})},v.update=function(t){var e,r=this.scene,n=r.fullSceneLayout,a=this.surface,s=t.opacity,l=i(t.colorscale,s),c=t.z,f=t.x,d=t.y,g=n.xaxis,v=n.yaxis,m=n.zaxis,y=r.dataScale,b=c[0].length,x=c.length,_=[u(new Float32Array(b*x),[b,x]),u(new Float32Array(b*x),[b,x]),u(new Float32Array(b*x),[b,x])],w=_[0],A=_[1],k=r.contourLevels;this.data=t,h(_[2],function(t,e){return m.d2l(c[e][t])*y[2]}),Array.isArray(f[0])?h(w,function(t,e){return g.d2l(f[e][t])*y[0]}):h(w,function(t){return g.d2l(f[t])*y[0]}),Array.isArray(d[0])?h(A,function(t,e){return v.d2l(d[e][t])*y[1]}):h(A,function(t,e){return v.d2l(d[e])*y[1]}),this.dataScale=o(_);var M={colormap:l,levels:[[],[],[]],showContour:[!0,!0,!0],showSurface:!t.hidesurface,contourProject:[[!1,!1,!1],[!1,!1,!1],[!1,!1,!1]],contourWidth:[1,1,1],contourColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],contourTint:[1,1,1],dynamicColor:[[1,1,1,1],[1,1,1,1],[1,1,1,1]],dynamicWidth:[1,1,1],dynamicTint:[1,1,1],opacity:1,colorBounds:[t.zmin*y[2],t.zmax*y[2]]};"opacity"in t&&t.opacity<1&&(M.opacity=.25*t.opacity);var T=[!0,!0,!0],E=[!0,!0,!0],L=["x","y","z"];for(e=0;3>e;++e){var S=t.contours[L[e]];T[e]=S.highlight,E[e]=S.show,M.showContour[e]=S.show||S.highlight,M.showContour[e]&&(M.contourProject[e]=[S.project.x,S.project.y,S.project.z],S.show?(this.showContour[e]=!0,M.levels[e]=k[e],a.highlightColor[e]=M.contourColor[e]=p(S.color),S.usecolormap?a.highlightTint[e]=M.contourTint[e]=0:a.highlightTint[e]=M.contourTint[e]=1,M.contourWidth[e]=S.width):this.showContour[e]=!1,S.highlight&&(M.dynamicColor[e]=p(S.highlightColor),M.dynamicWidth[e]=S.highlightWidth))}M.coords=_,a.update(M),a.highlightEnable=T,a.contourEnable=E,a.visible=t.visible,a.snapToData=!0,"lighting"in t&&(a.ambientLight=t.lighting.ambient,a.diffuseLight=t.lighting.diffuse,a.specularLight=t.lighting.specular,a.roughness=t.lighting.roughness,a.fresnel=t.lighting.fresnel),s&&1>s&&(a.supportsTransparency=!0)},v.dispose=function(){this.scene.glplot.remove(this.surface),this.surface.dispose()},e.exports=s},{"../../lib/str2rgbarray":359,"gl-surface3d":184,ndarray:208,"ndarray-fill":201,"ndarray-homography":206,"ndarray-ops":207,tinycolor2:229}],541:[function(t,e,r){"use strict";var n=t("../../lib"),i=t("../../components/colorscale/defaults"),a=t("./attributes");e.exports=function(t,e,r,o){function s(r,i){return n.coerce(t,e,a,r,i)}var l,u,c=s("z");if(!c)return void(e.visible=!1);var h=c[0].length,f=c.length;if(s("x"),s("y"),!Array.isArray(e.x))for(e.x=[],l=0;h>l;++l)e.x[l]=l;if(s("text"),!Array.isArray(e.y))for(e.y=[],l=0;f>l;++l)e.y[l]=l;s("lighting.ambient"),s("lighting.diffuse"),s("lighting.specular"),s("lighting.roughness"),s("lighting.fresnel"),s("hidesurface"),s("opacity"),s("colorscale");var d=["x","y","z"];for(l=0;3>l;++l){var p="contours."+d[l],g=s(p+".show"),v=s(p+".highlight");if(g||v)for(u=0;3>u;++u)s(p+".project."+d[u]);g&&(s(p+".color"),s(p+".width"),s(p+".usecolormap")),v&&(s(p+".highlightColor"),s(p+".highlightWidth"))}i(t,e,o,s,{prefix:"",cLetter:"z"})}},{"../../components/colorscale/defaults":308,"../../lib":349,"./attributes":538}],542:[function(t,e,r){"use strict";var n={};n.attributes=t("./attributes"),n.supplyDefaults=t("./defaults"),n.colorbar=t("../heatmap/colorbar"),n.calc=t("./calc"),n.plot=t("./convert"),n.moduleType="trace",n.name="surface",n.basePlotModule=t("../../plots/gl3d"),n.categories=["gl3d","noOpacity"],n.meta={},e.exports=n},{"../../plots/gl3d":400,"../heatmap/colorbar":461,"./attributes":538,"./calc":539,"./convert":540,"./defaults":541}]},{},[12])(12)});
Index: /branches/WebJobManager/HeuristicLab.Clients.Hive/3.3/HiveTasks/OptimizerHiveTask.cs
===================================================================
--- /branches/WebJobManager/HeuristicLab.Clients.Hive/3.3/HiveTasks/OptimizerHiveTask.cs	(revision 13711)
+++ /branches/WebJobManager/HeuristicLab.Clients.Hive/3.3/HiveTasks/OptimizerHiveTask.cs	(revision 13712)
@@ -295,5 +295,5 @@
     /// Recursively updates all the child-jobs as well
     /// </summary>
-    internal void SetIndexInParentOptimizerList(OptimizerHiveTask parentHiveTask) {
+    public void SetIndexInParentOptimizerList(OptimizerHiveTask parentHiveTask) {
       if (parentHiveTask != null) {
         if (parentHiveTask.ItemTask.Item is Optimization.Experiment) {
