diff --git a/dist/Application.d.ts b/dist/Application.d.ts index fe7f5cbb..4aae02df 100644 --- a/dist/Application.d.ts +++ b/dist/Application.d.ts @@ -1,6 +1,8 @@ import 'regenerator-runtime/runtime'; +import './index.scss'; import * as React from 'react'; import { ConnectedProps } from 'react-redux'; +import Split from 'react-split'; import { Dataset } from './model/Dataset'; import { BaseConfig, FeatureConfig, ComponentConfig } from './BaseConfig'; /** @@ -18,11 +20,11 @@ declare const connector: import("react-redux").InferableComponentEnhancerWithPro allIds: string[]; }; }; + globalLabels: import(".").GlobalLabelsState; } & { setOpenTab: (openTab: any) => any; setLineByOptions: (options: any) => any; setGlobalPointBrightness: (value: any) => any; - setGenericFingerprintAttributes: (value: any) => any; setGroupVisualizationMode: (value: any) => any; setLineUpInput_visibility: (open: any) => any; loadDataset: (dataset: Dataset) => any; @@ -41,7 +43,7 @@ type Props = PropsFromRedux & { */ export declare const Application: import("react-redux").ConnectedComponent<{ new (props: any): { - splitRef: any; + splitRef: React.LegacyRef; componentDidMount(): void; /** * Main callback when the dataset changes @@ -74,5 +76,5 @@ export declare const Application: import("react-redux").ConnectedComponent<{ UNSAFE_componentWillUpdate?(nextProps: Readonly, nextState: Readonly, nextContext: any): void; }; contextType?: React.Context; -}, import("react-redux").Omit>; +}, import("react-redux").Omit>; export {}; diff --git a/dist/BaseConfig.d.ts b/dist/BaseConfig.d.ts index 6b4071eb..8b979fe4 100644 --- a/dist/BaseConfig.d.ts +++ b/dist/BaseConfig.d.ts @@ -1,6 +1,7 @@ import { ConnectedComponent } from 'react-redux'; import { EncodingChannel } from './model/EncodingChannel'; import { EmbeddingController } from './components/DrawerTabPanels/EmbeddingTabPanel/EmbeddingController'; +import { TypedObject } from './model'; export type BaseConfig = Partial<{ baseUrl: string; preselect: Partial<{ @@ -12,6 +13,7 @@ export type EmbeddingMethod = { id: string; name: string; settings: { + hideSettings?: boolean; perplexity?: boolean; learningRate?: boolean; nneighbors?: boolean; @@ -31,6 +33,14 @@ export declare const DEFAULT_EMBEDDINGS: { name: string; settings: {}; }[]; +export type CoordinatesType = { + x: number; + y: number; +}; +export type MouseInteractions = { + onmousemove?: (coordinates: CoordinatesType, event_used: boolean) => void; + onmouseclick?: (coordinates: CoordinatesType, event_used: boolean, button: number) => void; +}; export type FeatureConfig = Partial<{ embeddings: EmbeddingMethod[]; encodings: EncodingChannel[]; @@ -46,16 +56,18 @@ export type ComponentConfig = Partial<{ detailViews: Array; layers: Array; tabs: Array; - contextMenuItems: Array; + contextMenuItems: Array<(props: { + handleClose: () => void; + pos_x: number; + pos_y: number; + menuTarget: TypedObject; + }) => JSX.Element>; + mouseInteractionCallbacks: MouseInteractions; }>; -export type ContextMenuItem = { - key: string; - title: string; - function: (coords: any) => void; -}; export type DetailViewSpec = { name: string; - view: () => JSX.Element; + view: JSX.Element | (() => JSX.Element) | ConnectedComponent; + settings: JSX.Element | (() => JSX.Element) | ConnectedComponent; }; export type TabSpec = { name: string; diff --git a/dist/Theme.d.ts b/dist/Theme.d.ts new file mode 100644 index 00000000..cb0ff5c3 --- /dev/null +++ b/dist/Theme.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dist/bundle.js b/dist/bundle.js index 0e427277..3325c63c 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -838,6 +838,27 @@ var weakMemoize = function weakMemoize(func) { /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (weakMemoize); +/***/ }), + +/***/ "./node_modules/@mui/base/utils/isHostComponent.js": +/*!*********************************************************!*\ + !*** ./node_modules/@mui/base/utils/isHostComponent.js ***! + \*********************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/** + * Determines if a given element is a DOM element name (i.e. not a React component). + */ +function isHostComponent(element) { + return typeof element === 'string'; +} +/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (isHostComponent); + /***/ }), /***/ "./node_modules/@mui/icons-material/ChevronRight.js": @@ -1141,6 +1162,29 @@ exports["default"] = _default; /***/ }), +/***/ "./node_modules/@mui/icons-material/Star.js": +/*!**************************************************!*\ + !*** ./node_modules/@mui/icons-material/Star.js ***! + \**************************************************/ +/***/ ((__unused_webpack_module, exports, __webpack_require__) => { + +"use strict"; + + +var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "./node_modules/@babel/runtime/helpers/interopRequireDefault.js"); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _createSvgIcon = _interopRequireDefault(__webpack_require__(/*! ./utils/createSvgIcon */ "./node_modules/@mui/icons-material/utils/createSvgIcon.js")); +var _jsxRuntime = __webpack_require__(/*! react/jsx-runtime */ "./node_modules/react/jsx-runtime.js"); +var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { + d: "M12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z" +}), 'Star'); +exports["default"] = _default; + +/***/ }), + /***/ "./node_modules/@mui/icons-material/Stop.js": /*!**************************************************!*\ !*** ./node_modules/@mui/icons-material/Stop.js ***! @@ -1209,6 +1253,2513 @@ var _utils = __webpack_require__(/*! @mui/material/utils */ "./node_modules/@mui /***/ }), +/***/ "./node_modules/@mui/material/ButtonBase/ButtonBase.js": +/*!*************************************************************!*\ + !*** ./node_modules/@mui/material/ButtonBase/ButtonBase.js ***! + \*************************************************************/ +/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { + +"use strict"; +__webpack_require__.r(__webpack_exports__); +/* harmony export */ __webpack_require__.d(__webpack_exports__, { +/* harmony export */ "ButtonBaseRoot": () => (/* binding */ ButtonBaseRoot), +/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__) +/* harmony export */ }); +/* harmony import */ var _babel_runtime_helpers_esm_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/esm/extends */ "./node_modules/@babel/runtime/helpers/esm/extends.js"); +/* harmony import */ var _babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/helpers/esm/objectWithoutPropertiesLoose */ "./node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! react */ "react"); +/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! prop-types */ "./node_modules/prop-types/index.js"); +/* harmony import */ var prop_types__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(prop_types__WEBPACK_IMPORTED_MODULE_14__); +/* harmony import */ var clsx__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! clsx */ "./node_modules/clsx/dist/clsx.m.js"); +/* harmony import */ var _mui_utils__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! @mui/utils */ "./node_modules/@mui/utils/esm/refType.js"); +/* harmony import */ var _mui_utils__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! @mui/utils */ "./node_modules/@mui/utils/esm/elementTypeAcceptingRef.js"); +/* harmony import */ var _mui_base_composeClasses__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! @mui/base/composeClasses */ "./node_modules/@mui/utils/esm/composeClasses/composeClasses.js"); +/* harmony import */ var _styles_styled__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../styles/styled */ "./node_modules/@mui/material/styles/styled.js"); +/* harmony import */ var _styles_useThemeProps__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../styles/useThemeProps */ "./node_modules/@mui/material/styles/useThemeProps.js"); +/* harmony import */ var _utils_useForkRef__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../utils/useForkRef */ "./node_modules/@mui/material/utils/useForkRef.js"); +/* harmony import */ var _utils_useEventCallback__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../utils/useEventCallback */ "./node_modules/@mui/material/utils/useEventCallback.js"); +/* harmony import */ var _utils_useIsFocusVisible__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../utils/useIsFocusVisible */ "./node_modules/@mui/material/utils/useIsFocusVisible.js"); +/* harmony import */ var _TouchRipple__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./TouchRipple */ "./node_modules/@mui/material/ButtonBase/TouchRipple.js"); +/* harmony import */ var _buttonBaseClasses__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./buttonBaseClasses */ "./node_modules/@mui/material/ButtonBase/buttonBaseClasses.js"); +/* harmony import */ var react_jsx_runtime__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! react/jsx-runtime */ "./node_modules/react/jsx-runtime.js"); + + +const _excluded = ["action", "centerRipple", "children", "className", "component", "disabled", "disableRipple", "disableTouchRipple", "focusRipple", "focusVisibleClassName", "LinkComponent", "onBlur", "onClick", "onContextMenu", "onDragLeave", "onFocus", "onFocusVisible", "onKeyDown", "onKeyUp", "onMouseDown", "onMouseLeave", "onMouseUp", "onTouchEnd", "onTouchMove", "onTouchStart", "tabIndex", "TouchRippleProps", "touchRippleRef", "type"]; + + + + + + + + + + + + + + +const useUtilityClasses = ownerState => { + const { + disabled, + focusVisible, + focusVisibleClassName, + classes + } = ownerState; + const slots = { + root: ['root', disabled && 'disabled', focusVisible && 'focusVisible'] + }; + const composedClasses = (0,_mui_base_composeClasses__WEBPACK_IMPORTED_MODULE_5__["default"])(slots, _buttonBaseClasses__WEBPACK_IMPORTED_MODULE_6__.getButtonBaseUtilityClass, classes); + if (focusVisible && focusVisibleClassName) { + composedClasses.root += ` ${focusVisibleClassName}`; + } + return composedClasses; +}; +const ButtonBaseRoot = (0,_styles_styled__WEBPACK_IMPORTED_MODULE_7__["default"])('button', { + name: 'MuiButtonBase', + slot: 'Root', + overridesResolver: (props, styles) => styles.root +})({ + display: 'inline-flex', + alignItems: 'center', + justifyContent: 'center', + position: 'relative', + boxSizing: 'border-box', + WebkitTapHighlightColor: 'transparent', + backgroundColor: 'transparent', + // Reset default value + // We disable the focus ring for mouse, touch and keyboard users. + outline: 0, + border: 0, + margin: 0, + // Remove the margin in Safari + borderRadius: 0, + padding: 0, + // Remove the padding in Firefox + cursor: 'pointer', + userSelect: 'none', + verticalAlign: 'middle', + MozAppearance: 'none', + // Reset + WebkitAppearance: 'none', + // Reset + textDecoration: 'none', + // So we take precedent over the style of a native element. + color: 'inherit', + '&::-moz-focus-inner': { + borderStyle: 'none' // Remove Firefox dotted outline. + }, + + [`&.${_buttonBaseClasses__WEBPACK_IMPORTED_MODULE_6__["default"].disabled}`]: { + pointerEvents: 'none', + // Disable link interactions + cursor: 'default' + }, + '@media print': { + colorAdjust: 'exact' + } +}); + +/** + * `ButtonBase` contains as few styles as possible. + * It aims to be a simple building block for creating a button. + * It contains a load of style reset and some focus/ripple logic. + */ +const ButtonBase = /*#__PURE__*/react__WEBPACK_IMPORTED_MODULE_2__.forwardRef(function ButtonBase(inProps, ref) { + const props = (0,_styles_useThemeProps__WEBPACK_IMPORTED_MODULE_8__["default"])({ + props: inProps, + name: 'MuiButtonBase' + }); + const { + action, + centerRipple = false, + children, + className, + component = 'button', + disabled = false, + disableRipple = false, + disableTouchRipple = false, + focusRipple = false, + LinkComponent = 'a', + onBlur, + onClick, + onContextMenu, + onDragLeave, + onFocus, + onFocusVisible, + onKeyDown, + onKeyUp, + onMouseDown, + onMouseLeave, + onMouseUp, + onTouchEnd, + onTouchMove, + onTouchStart, + tabIndex = 0, + TouchRippleProps, + touchRippleRef, + type + } = props, + other = (0,_babel_runtime_helpers_esm_objectWithoutPropertiesLoose__WEBPACK_IMPORTED_MODULE_1__["default"])(props, _excluded); + const buttonRef = react__WEBPACK_IMPORTED_MODULE_2__.useRef(null); + const rippleRef = react__WEBPACK_IMPORTED_MODULE_2__.useRef(null); + const handleRippleRef = (0,_utils_useForkRef__WEBPACK_IMPORTED_MODULE_9__["default"])(rippleRef, touchRippleRef); + const { + isFocusVisibleRef, + onFocus: handleFocusVisible, + onBlur: handleBlurVisible, + ref: focusVisibleRef + } = (0,_utils_useIsFocusVisible__WEBPACK_IMPORTED_MODULE_10__["default"])(); + const [focusVisible, setFocusVisible] = react__WEBPACK_IMPORTED_MODULE_2__.useState(false); + if (disabled && focusVisible) { + setFocusVisible(false); + } + react__WEBPACK_IMPORTED_MODULE_2__.useImperativeHandle(action, () => ({ + focusVisible: () => { + setFocusVisible(true); + buttonRef.current.focus(); + } + }), []); + const [mountedState, setMountedState] = react__WEBPACK_IMPORTED_MODULE_2__.useState(false); + react__WEBPACK_IMPORTED_MODULE_2__.useEffect(() => { + setMountedState(true); + }, []); + const enableTouchRipple = mountedState && !disableRipple && !disabled; + react__WEBPACK_IMPORTED_MODULE_2__.useEffect(() => { + if (focusVisible && focusRipple && !disableRipple && mountedState) { + rippleRef.current.pulsate(); + } + }, [disableRipple, focusRipple, focusVisible, mountedState]); + function useRippleHandler(rippleAction, eventCallback, skipRippleAction = disableTouchRipple) { + return (0,_utils_useEventCallback__WEBPACK_IMPORTED_MODULE_11__["default"])(event => { + if (eventCallback) { + eventCallback(event); + } + const ignore = skipRippleAction; + if (!ignore && rippleRef.current) { + rippleRef.current[rippleAction](event); + } + return true; + }); + } + const handleMouseDown = useRippleHandler('start', onMouseDown); + const handleContextMenu = useRippleHandler('stop', onContextMenu); + const handleDragLeave = useRippleHandler('stop', onDragLeave); + const handleMouseUp = useRippleHandler('stop', onMouseUp); + const handleMouseLeave = useRippleHandler('stop', event => { + if (focusVisible) { + event.preventDefault(); + } + if (onMouseLeave) { + onMouseLeave(event); + } + }); + const handleTouchStart = useRippleHandler('start', onTouchStart); + const handleTouchEnd = useRippleHandler('stop', onTouchEnd); + const handleTouchMove = useRippleHandler('stop', onTouchMove); + const handleBlur = useRippleHandler('stop', event => { + handleBlurVisible(event); + if (isFocusVisibleRef.current === false) { + setFocusVisible(false); + } + if (onBlur) { + onBlur(event); + } + }, false); + const handleFocus = (0,_utils_useEventCallback__WEBPACK_IMPORTED_MODULE_11__["default"])(event => { + // Fix for https://github.com/facebook/react/issues/7769 + if (!buttonRef.current) { + buttonRef.current = event.currentTarget; + } + handleFocusVisible(event); + if (isFocusVisibleRef.current === true) { + setFocusVisible(true); + if (onFocusVisible) { + onFocusVisible(event); + } + } + if (onFocus) { + onFocus(event); + } + }); + const isNonNativeButton = () => { + const button = buttonRef.current; + return component && component !== 'button' && !(button.tagName === 'A' && button.href); + }; + + /** + * IE11 shim for https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat + */ + const keydownRef = react__WEBPACK_IMPORTED_MODULE_2__.useRef(false); + const handleKeyDown = (0,_utils_useEventCallback__WEBPACK_IMPORTED_MODULE_11__["default"])(event => { + // Check if key is already down to avoid repeats being counted as multiple activations + if (focusRipple && !keydownRef.current && focusVisible && rippleRef.current && event.key === ' ') { + keydownRef.current = true; + rippleRef.current.stop(event, () => { + rippleRef.current.start(event); + }); + } + if (event.target === event.currentTarget && isNonNativeButton() && event.key === ' ') { + event.preventDefault(); + } + if (onKeyDown) { + onKeyDown(event); + } + + // Keyboard accessibility for non interactive elements + if (event.target === event.currentTarget && isNonNativeButton() && event.key === 'Enter' && !disabled) { + event.preventDefault(); + if (onClick) { + onClick(event); + } + } + }); + const handleKeyUp = (0,_utils_useEventCallback__WEBPACK_IMPORTED_MODULE_11__["default"])(event => { + // calling preventDefault in keyUp on a \n \n setOpenClusterPanel(false)}\n anchorOrigin={{\n vertical: 'top',\n horizontal: 'right',\n }}\n transformOrigin={{\n vertical: 'top',\n horizontal: 'left',\n }}\n >\n \n \n Clustering Settings\n \n \n\n \n {\n setClusterAdvancedMode(newValue);\n }}\n name=\"advancedClustering\"\n />\n }\n label=\"Advanced\"\n />\n \n {clusterAdvancedMode ? (\n \n \n {\n setClusterSelectionOnly(newValue);\n }}\n name=\"selectionClustering\"\n />\n }\n label=\"Cluster only Selected Items\"\n />\n \n \n {\n setAddClusterToCurrentStory(newValue);\n }}\n name=\"addClusterToCurrentStory\"\n />\n }\n label=\"Add Cluster to current Story\"\n />\n \n {\n set_min_cluster_size(Math.max(parseInt(event.target.value, 10), 2));\n }}\n />\n
\n {\n set_min_cluster_samples(Math.max(parseInt(event.target.value, 10), 1));\n }}\n />\n
\n {\n set_allow_single_cluster(event.target.checked);\n }}\n />\n }\n label=\"Allow Single Cluster\"\n />\n
\n ) : (\n \n handleClusterSliderChange(newValue, clusterSelectionOnly)}\n />\n \n )}\n \n {\n calc_hdbscan(min_cluster_size, min_cluster_samples, allow_single_cluster, cancellablePromise, clusterSelectionOnly, addClusterToCurrentStory);\n setOpenClusterPanel(false);\n }}\n >\n Run Clustering{/* Projection-based Clustering */}\n \n \n \n\n \n \n Groups and Stories\n \n \n\n \n \n \n\n
\n \n
\n \n );\n },\n);\n\ntype ClusterPopoverProps = {\n anchorEl: any;\n setAnchorEl: any;\n cluster: ICluster;\n removeClusterFromStories: any;\n splitRef: any;\n dataset: Dataset;\n};\n\nfunction ClusterPopover({ anchorEl, setAnchorEl, cluster, dataset, removeClusterFromStories, splitRef }: ClusterPopoverProps) {\n if (!cluster) return null;\n\n const [name, setName] = React.useState(cluster.label);\n const dispatch = useDispatch();\n\n React.useEffect(() => {\n if (cluster && anchorEl) {\n setName(cluster.label);\n }\n }, [anchorEl, cluster]);\n\n const onSave = () => {\n dispatch(StoriesActions.changeClusterName({ cluster: cluster.id, name }));\n\n setAnchorEl(null);\n };\n\n const onDelete = () => {\n setAnchorEl(null);\n removeClusterFromStories(cluster);\n };\n\n const onLineup = () => {\n setAnchorEl(null);\n\n const curr_sizes = splitRef.current.split.getSizes();\n if (curr_sizes[1] < 2) {\n splitRef.current.split.setSizes([30, 70]);\n }\n };\n\n return (\n setAnchorEl(null)}\n anchorOrigin={{\n vertical: 'bottom',\n horizontal: 'center',\n }}\n transformOrigin={{\n vertical: 'bottom',\n horizontal: 'center',\n }}\n >\n
\n \n {/* Settings */}\n\n }\n >\n Delete Group\n \n\n \n {\n setName(event.target.value);\n }}\n margin=\"normal\"\n />\n\n
\n \n \n
\n
\n
\n
\n \n );\n}\n\ntype ClusterListProps = {\n selectedClusters: EntityId[];\n stories: IStorytelling;\n removeClusterFromStories;\n splitRef;\n setSelectedCluster;\n dataset;\n};\n\nfunction ClusterList({ selectedClusters, stories, dataset, removeClusterFromStories, splitRef, setSelectedCluster }: ClusterListProps) {\n const [anchorEl, setAnchorEl] = React.useState(null);\n const [popoverCluster, setPopoverCluster] = React.useState(null);\n\n const activeStory = AStorytelling.getActive(stories);\n\n const storyItems = new Array();\n\n if (activeStory) {\n for (const key of activeStory.clusters.ids) {\n const cluster = activeStory.clusters.entities[key];\n\n storyItems.push(\n {\n setSelectedCluster([key], event.ctrlKey);\n }}\n >\n \n \n {\n // removeClusterFromStories(cluster)\n setPopoverCluster(cluster);\n setAnchorEl(event.target);\n }}\n >\n \n \n \n ,\n );\n }\n }\n\n return (\n
\n \n\n {storyItems}\n
\n );\n}\n","import { EntityId } from '@reduxjs/toolkit';\nimport { useState } from 'react';\nimport * as React from 'react';\nimport { Button, FormControl, FormHelperText, Grid, ListItem, ListItemText, Select } from '@mui/material';\nimport { connect, ConnectedProps, useDispatch } from 'react-redux';\nimport { IBook } from '../../../model/Book';\nimport type { RootState } from '../../Store/Store';\nimport { StoriesActions, AStorytelling } from '../../Ducks/StoriesDuck';\nimport { EditBookDialog } from '../EmbeddingTabPanel/EditBookDialog';\n\nconst mapStateToProps = (state: RootState) => ({\n stories: state.stories,\n});\n\nconst mapDispatchToProps = (dispatch) => ({\n setActiveStory: (book: EntityId) => dispatch(StoriesActions.setActiveStoryBook(book)),\n deleteStory: (book: EntityId) => dispatch(StoriesActions.deleteBookAsync(book)),\n addStory: (book: IBook) => dispatch(StoriesActions.addBookAsync({ book, activate: true })),\n});\n\nconst connector = connect(mapStateToProps, mapDispatchToProps);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux;\n\nexport const StoryPreview = connector(({ stories, setActiveStory, deleteStory, addStory }: Props) => {\n const [editBook, setEditBook] = useState(null);\n\n const deleteHandler = (story) => {\n if (stories.active === story) {\n setActiveStory(null);\n }\n\n deleteStory(story);\n };\n\n const addHandler = () => {\n addStory(AStorytelling.emptyStory());\n };\n\n const dispatch = useDispatch();\n\n return (\n \n \n Active Story Book\n {\n setActiveStory(event.target.value);\n }}\n >\n \n \n \n {stories.stories &&\n stories.stories.ids\n .map((id) => stories.stories.entities[id])\n .map((story) => {\n return (\n \n \n \n );\n })}\n \n \n\n \n addHandler()}\n variant=\"outlined\"\n size=\"small\"\n >\n Add Empty\n \n\n {stories.active ? (\n {\n setEditBook(stories.stories.entities[stories.active]);\n }}\n >\n Edit Selected\n \n ) : null}\n \n\n {\n setEditBook(null);\n }}\n onSave={(id: EntityId, changes: any) => {\n dispatch(StoriesActions.changeBookName({ id: editBook.id, name: changes.name }));\n setEditBook(null);\n }}\n onDelete={() => {\n deleteHandler(editBook.id);\n setEditBook(null);\n }}\n />\n \n );\n});\n","export * from './ClusteringTabPanel';\nexport * from './StoryPreview';\n","import { Grid } from '@mui/material';\nimport * as React from 'react';\nimport * as Papa from 'papaparse';\nimport type { Dataset } from '../../..';\nimport { CSVLoader } from '../../Utility/Loaders/CSVLoader';\nimport { JSONLoader } from '../../Utility/Loaders/JSONLoader';\nimport { DragAndDrop } from './DragAndDrop';\n\nexport function DatasetDrop({ onChange }: { onChange(dataset: Dataset): void }) {\n return (\n \n {\n if (files == null || files.length <= 0) {\n return;\n }\n\n const file = files[0];\n const fileName = file.name as string;\n\n if (fileName.endsWith('.csv')) {\n const rows = [];\n let header = null;\n\n Papa.parse(file, {\n // @ts-ignore\n worker: true,\n skipEmptyLines: true,\n step(results: any) {\n if (!header) {\n header = results.data;\n\n return;\n }\n\n const dict = {};\n results.data.forEach((value, i) => {\n dict[header[i]] = value;\n });\n\n rows.push(dict);\n },\n complete() {\n new CSVLoader().resolveVectors(rows, onChange);\n },\n });\n } else {\n const reader = new FileReader();\n\n reader.onload = (event) => {\n const content = event.target.result;\n\n if (fileName.endsWith('json')) {\n new JSONLoader().resolveContent(content, onChange);\n }\n };\n\n reader.readAsText(file);\n }\n }}\n >\n
\n \n \n );\n}\n","import { Box, Typography, Button } from '@mui/material';\nimport * as React from 'react';\nimport * as d3v5 from 'd3v5';\nimport { Dataset } from '../../../model/Dataset';\nimport { AVector } from '../../../model/Vector';\nimport { CSVLoader } from '../../Utility/Loaders/CSVLoader';\nimport { JSONLoader } from '../../Utility/Loaders/JSONLoader';\nimport { DatasetDrop } from './DatasetDrop';\nimport { DownloadJob } from './DownloadJob';\nimport { DownloadProgress } from './DownloadProgress';\nimport { PredefinedDatasets } from './PredefinedDatasets';\n\nconst onClickPersist = async () => {\n const content = '';\n\n // @ts-ignore\n const handle = await window.showSaveFilePicker({\n suggestedName: 'session.pse',\n types: [\n {\n description: 'PSE Session',\n accept: {\n 'text/plain': ['.pse'],\n },\n },\n ],\n });\n\n const writable = await handle.createWritable();\n writable.write(content);\n await writable.close();\n\n return handle;\n};\n\nconst onClickHydrate = async () => {\n // @ts-ignore\n const [fileHandle] = await window.showOpenFilePicker();\n const file = await fileHandle.getFile();\n const contents = await file.text();\n\n return contents;\n};\n\nfunction convertFromCSV(vectors) {\n return vectors.map((vector) => {\n return AVector.create(vector);\n });\n}\n\nexport function DatasetTabPanel({ onDataSelected }: { onDataSelected(dataset: Dataset): void }) {\n const [job, setJob] = React.useState(null);\n\n const predefined = (\n {\n setJob(new DownloadJob(entry));\n }}\n />\n );\n\n return (\n
\n \n \n Custom Datasets (Drag and Drop)\n \n \n\n \n\n \n \n \n \n\n \n \n Predefined Datasets\n \n \n\n {predefined}\n\n {\n if (job.entry.path.endsWith('json')) {\n new JSONLoader().resolve(JSON.parse(result), onDataSelected, job.entry.type, job.entry);\n } else {\n new CSVLoader().resolve(onDataSelected, convertFromCSV(d3v5.csvParse(result)), job.entry.type, job.entry);\n }\n\n setJob(null);\n }}\n onCancel={() => {\n setJob(null);\n }}\n />\n
\n );\n}\n","import { DatasetType } from '../../../model/DatasetType';\n\n/**\n * Helper for fetching a resource asynchronous.\n */\nexport class DownloadJob {\n // The entry to fetch with this job\n entry: { path: string; type: DatasetType };\n\n // If this job terminated from outside?\n terminated: boolean;\n\n constructor(entry: { path: string; type: DatasetType }) {\n this.entry = entry;\n this.terminated = false;\n }\n\n sleep(ms) {\n // eslint-disable-next-line no-promise-executor-return\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n\n async download(response: Response, callback: (string) => void, onProgress: (number) => void) {\n const reader = response.body.getReader();\n const chunks = [];\n let receivedLength = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const { done, value } = await reader.read();\n\n if (done || this.terminated) {\n break;\n }\n\n chunks.push(value);\n\n // Update progress\n receivedLength += value.length;\n onProgress(receivedLength);\n\n // This sleep is necessary to have a fluid animated UI, else it would stutter since everything is on the same thread\n await this.sleep(0);\n }\n\n if (this.terminated) {\n return;\n }\n\n // Combine all small chunks to one big chunk\n const chunksAll = new Uint8Array(receivedLength);\n let position = 0;\n for (const chunk of chunks) {\n chunksAll.set(chunk, position);\n position += chunk.length;\n }\n\n // Encode result as string\n const result = new TextDecoder('utf-8').decode(chunksAll);\n\n // call finish\n callback(result);\n }\n\n start(callback: (string) => void, onProgress: (number) => void) {\n fetch(this.entry.path)\n .then((response) => {\n this.download(response, callback, onProgress);\n })\n .catch(() => {});\n }\n\n /**\n * Terminates this job\n */\n terminate() {\n this.terminated = true;\n }\n}\n","/* eslint-disable react-hooks/exhaustive-deps */\nimport { Box, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, Typography } from '@mui/material';\nimport * as React from 'react';\nimport { connect, ConnectedProps } from 'react-redux';\nimport { DownloadJob } from './DownloadJob';\n\nconst mapStateToProps = () => ({});\n\nconst mapDispatchToProps = () => ({});\n\nconst connector = connect(mapStateToProps, mapDispatchToProps);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {\n job: DownloadJob;\n onFinish: any;\n onCancel: any;\n};\n\nexport function DownloadProgress({ job, onFinish, onCancel }: Props) {\n const [progress, setProgress] = React.useState(0);\n const [, setFinished] = React.useState(false);\n\n React.useEffect(() => {\n if (job) {\n job.start(\n (result) => {\n setFinished(true);\n onFinish(result);\n },\n (progress) => {\n setProgress(progress);\n },\n );\n }\n }, [job]);\n\n return (\n \n Download Progress\n \n
\n \n \n \n {`${Math.round(progress / 1000)}kb`}\n \n \n
\n
\n \n {\n job.terminate();\n onCancel();\n }}\n color=\"primary\"\n >\n Cancel\n \n \n
\n );\n}\n","import { Button, Grid } from '@mui/material';\nimport * as React from 'react';\n\nexport type DragAndDropProps = {\n handleDrop: Function;\n accept: string;\n};\n\nexport type DragAndDropState = {\n drag: boolean;\n};\n\nexport class DragAndDrop extends React.Component {\n dropRef: any;\n\n fileInput: any;\n\n constructor(props) {\n super(props);\n\n this.state = {\n drag: false,\n };\n this.dropRef = React.createRef();\n this.fileInput = React.createRef();\n }\n\n componentDidMount() {\n const div = this.dropRef.current;\n div.addEventListener('dragenter', this.handleDragIn);\n div.addEventListener('dragleave', this.handleDragOut);\n div.addEventListener('dragover', this.handleDrag);\n div.addEventListener('drop', this.handleDrop);\n }\n\n componentWillUnmount() {\n const div = this.dropRef.current;\n div.removeEventListener('dragenter', this.handleDragIn);\n div.removeEventListener('dragleave', this.handleDragOut);\n div.removeEventListener('dragover', this.handleDrag);\n div.removeEventListener('drop', this.handleDrop);\n }\n\n handleDrag = (e) => {\n e.preventDefault();\n e.stopPropagation();\n };\n\n handleDragIn = (e) => {\n e.preventDefault();\n e.stopPropagation();\n\n if (e.dataTransfer.items && e.dataTransfer.items.length > 0) {\n this.setState({ drag: true });\n }\n };\n\n handleDragOut = (e) => {\n e.preventDefault();\n e.stopPropagation();\n\n const rect = this.dropRef.current.getBoundingClientRect();\n if (e.clientY < rect.top || e.clientY >= rect.bottom || e.clientX < rect.left || e.clientX >= rect.right) {\n this.setState({ drag: false });\n }\n };\n\n handleDrop = (e) => {\n e.preventDefault();\n e.stopPropagation();\n this.setState({ drag: false });\n\n if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {\n this.props.handleDrop(e.dataTransfer.files);\n // e.dataTransfer.clearData()\n }\n };\n\n render() {\n return (\n \n {this.state.drag ? (\n \n \n \n
Drop a file here
\n
\n
\n \n ) : (\n \n \n {\n this.props.handleDrop(e.target.files);\n }}\n />\n \n\n \n
Drop a file here
\n \n
\n \n )}\n {this.props.children}\n \n );\n }\n}\nexport default DragAndDrop;\n","import { Grid, List, ListItem, ListItemText, ListSubheader, ListItemIcon, SvgIcon } from '@mui/material';\nimport * as React from 'react';\nimport MenuBookIcon from '@mui/icons-material/MenuBook';\nimport ShareIcon from '@mui/icons-material/Share';\nimport WidgetsIcon from '@mui/icons-material/Widgets';\nimport HelpOutlineIcon from '@mui/icons-material/HelpOutline';\nimport { connect, ConnectedProps } from 'react-redux';\nimport { DatasetType } from '../../../model/DatasetType';\nimport type { RootState } from '../../Store';\nimport { DatasetEntriesAPI } from '../../Ducks/DatasetEntriesDuck';\n\nexport function TypeIcon({ type }) {\n switch (type) {\n case DatasetType.Neural:\n return (\n \n \n \n );\n case DatasetType.Story:\n return (\n \n \n \n );\n case DatasetType.Chess:\n return (\n \n \n \n \n \n \n \n \n \n \n \n \n );\n case DatasetType.Rubik:\n return (\n \n \n \n );\n default:\n return (\n \n \n \n );\n }\n}\n\nconst mapStateToProps = (state: RootState) => ({\n datasetEntries: state.datasetEntries,\n});\n\nconst mapDispatchToProps = () => ({});\n\nconst connector = connect(mapStateToProps, mapDispatchToProps);\n\ntype Props = ConnectedProps & {\n onChange: any;\n};\n\nexport const PredefinedDatasets = connector(({ onChange, datasetEntries }: Props) => {\n const types = DatasetEntriesAPI.getTypes(datasetEntries);\n\n const handleClick = (entry) => {\n onChange(entry);\n };\n\n return (\n \n } style={{ backgroundColor: 'white' }}>\n {types.map((type) => {\n return (\n
  • \n
      \n {Object.keys(DatasetType)[Object.values(DatasetType).indexOf(type)].replaceAll('_', ' ')}\n {Object.values(datasetEntries.values.byId)\n .filter((value) => value.type === type)\n .map((entry) => {\n return (\n {\n handleClick(entry);\n }}\n >\n \n \n \n );\n })}\n
    \n
  • \n );\n })}\n
    \n
    \n );\n});\n","export * from './DatasetDrop';\nexport * from './DatasetTabPanel';\nexport * from './DownloadJob';\nexport * from './DownloadProgress';\nexport * from './DragAndDrop';\nexport * from './PredefinedDatasets';\n","/* eslint-disable @typescript-eslint/no-use-before-define */\nimport { Box, Button, Checkbox, Divider, FormControl, FormControlLabel, FormHelperText, MenuItem, Popover, Select, Switch, Typography } from '@mui/material';\nimport * as React from 'react';\nimport { connect, ConnectedProps } from 'react-redux';\nimport { setGenericFingerprintAttributes } from '../../Ducks/GenericFingerprintAttributesDuck';\nimport { setHoverWindowMode, WindowMode } from '../../Ducks/HoverSettingsDuck';\nimport { HoverStateOrientation, setHoverStateOrientation } from '../../Ducks/HoverStateOrientationDuck';\nimport { SelectionClusters } from '../../Overlays/SelectionClusters';\nimport type { RootState } from '../../Store/Store';\nimport { VirtualColumn, VirtualTable } from '../../UI/VirtualTable';\nimport { selectVectors } from '../../Ducks/AggregationDuck';\nimport { AStorytelling } from '../../Ducks/StoriesDuck';\nimport { FeatureConfig } from '../../../BaseConfig';\n\nconst mapStateToProps = (state: RootState) => ({\n hoverSettings: state.hoverSettings,\n currentAggregation: state.currentAggregation,\n dataset: state.dataset,\n hoverStateOrientation: state.hoverStateOrientation,\n activeStorybook: AStorytelling.getActive(state.stories),\n});\n\nconst mapDispatchToProps = (dispatch) => ({\n setHoverWindowMode: (value) => dispatch(setHoverWindowMode(value)),\n setAggregation: (value) => dispatch(selectVectors(value, false)),\n setHoverStateOrientation: (value) => dispatch(setHoverStateOrientation(value)),\n});\n\nconst connector = connect(mapStateToProps, mapDispatchToProps);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {\n config: FeatureConfig;\n};\n\nconst strrenderer = (name: string, row: any) => {\n return row[name];\n};\n\nexport const DetailsTabPanel = connector(\n ({\n hoverSettings,\n setHoverWindowMode,\n setAggregation,\n currentAggregation,\n dataset,\n hoverStateOrientation,\n setHoverStateOrientation,\n activeStorybook,\n config,\n }: Props) => {\n const handleChange = (_, value) => {\n setHoverWindowMode(value ? WindowMode.Extern : WindowMode.Embedded);\n };\n\n return (\n
    \n \n {currentAggregation.selectedClusters && currentAggregation.selectedClusters.length > 0 ? (\n \n Selected {currentAggregation.selectedClusters.length} out of {activeStorybook?.clusters.ids.length} groups\n \n ) : (\n \n Selected {currentAggregation.aggregation.length} out of {dataset?.vectors.length} items\n \n )}\n \n\n \n }\n label=\"External Summary\"\n />\n \n \n {\n setAggregation([]);\n }}\n >\n Clear Selection\n \n \n\n \n \n \n\n \n
    \n \n Hover Position\n {\n setHoverStateOrientation(event.target.value);\n }}\n >\n North East\n South West\n \n \n
    \n
    \n\n \n \n \n\n \n
    \n );\n },\n);\n\nconst attributeConnector = connect(\n (state: RootState) => ({\n genericFingerprintAttributes: state.genericFingerprintAttributes,\n }),\n (dispatch) => ({\n setGenericFingerprintAttributes: (genericFingerprintAttributes) => dispatch(setGenericFingerprintAttributes(genericFingerprintAttributes)),\n }),\n null,\n { forwardRef: true },\n);\n\ntype AttributeTablePropsFromRedux = ConnectedProps;\n\ntype AttributeTableProps = AttributeTablePropsFromRedux & { config: FeatureConfig };\n\nconst AttributeTable = attributeConnector(({ config, genericFingerprintAttributes, setGenericFingerprintAttributes }: AttributeTableProps) => {\n const [anchorEl, setAnchorEl] = React.useState(null);\n\n const fingerprintAttributes = (event) => {\n setAnchorEl(event.currentTarget);\n };\n\n const handleClose = () => {\n setAnchorEl(null);\n setGenericFingerprintAttributes([...localAttributes]);\n };\n\n const [localAttributes, setLocalAttributes] = React.useState([]);\n\n React.useEffect(() => {\n setLocalAttributes(genericFingerprintAttributes);\n }, [genericFingerprintAttributes]);\n\n const booleanRenderer = (row: any) => {\n return (\n {\n row.show = event.target.checked;\n setLocalAttributes([...localAttributes]);\n }}\n />\n );\n };\n\n return (\n
    \n {config?.showSummaryAttributes !== false ? (\n \n ) : null}\n\n \n \n \n strrenderer('feature', row)} />\n booleanRenderer(row)} />\n \n \n \n
    \n );\n});\n","export * from './DetailsTabPanel';\n","import { FormControlLabel, FormGroup, Slider, Switch, Typography } from '@mui/material';\nimport * as React from 'react';\nimport { connect, ConnectedProps } from 'react-redux';\nimport { setTrailLength, setTrailVisibility } from '../../Ducks/TrailSettingsDuck';\nimport type { RootState } from '../../Store/Store';\n\nconst mapStateToProps = (state: RootState) => ({\n trailSettings: state.trailSettings,\n});\n\nconst mapDispatchToProps = (dispatch) => ({\n setTrailVisibility: (visibility) => dispatch(setTrailVisibility(visibility)),\n setTrailLength: (length) => dispatch(setTrailLength(length)),\n});\n\nconst connector = connect(mapStateToProps, mapDispatchToProps);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {};\n\nexport const ClusterTrailSettings = connector(({ trailSettings, setTrailVisibility, setTrailLength }: Props) => {\n return (\n \n setTrailVisibility(newVal)} name=\"jason\" />}\n label=\"Show Group Trail\"\n />\n \n Trail Length\n \n {\n setTrailLength(newVal);\n }}\n />\n \n );\n});\n","import * as React from 'react';\nimport DeleteIcon from '@mui/icons-material/Delete';\nimport { Box, Button, Dialog, DialogTitle, DialogContent, DialogActions, TextField, IconButton } from '@mui/material';\nimport { EntityId } from '@reduxjs/toolkit';\nimport type { IBook } from '../../../model';\n\nexport function EditBookDialog({\n book,\n onClose,\n onSave,\n onDelete,\n}: {\n book: IBook;\n onClose: () => void;\n onSave: (id: EntityId, changes: any) => void;\n onDelete: (id: EntityId) => void;\n}) {\n const [name, setName] = React.useState(book?.name);\n\n React.useEffect(() => {\n if (book) {\n setName(book.name);\n }\n }, [book]);\n\n const onSubmit = (event: React.FormEvent) => {\n event.preventDefault();\n\n onSave(book.id, { name });\n };\n\n return (\n \n \n {`Edit story book ${book?.name ? book.name : ''}`}\n\n \n setName(event.target.value)} sx={{ mt: 1 }} />\n \n\n \n onDelete(book?.id)}>\n \n \n\n \n \n \n \n );\n}\n","import DeleteIcon from '@mui/icons-material/Delete';\nimport { Box, Button, Dialog, DialogTitle, DialogContent, DialogActions, TextField, IconButton } from '@mui/material';\nimport * as React from 'react';\nimport { EntityId } from '@reduxjs/toolkit';\nimport type { IProjection } from '../../../model';\n\nfunction FeatureList({ features }: { features: any[] }) {\n return null;\n}\n\nexport function EditProjectionDialog({\n projection,\n onClose,\n onSave,\n onDelete,\n}: {\n projection: IProjection;\n onClose: () => void;\n onSave: (id: EntityId, changes: any) => void;\n onDelete: (id: EntityId) => void;\n}) {\n const [name, setName] = React.useState(projection?.name);\n\n React.useEffect(() => {\n if (projection) {\n setName(projection.name);\n }\n }, [projection]);\n\n const onSubmit = (event: React.FormEvent) => {\n event.preventDefault();\n\n onSave(projection.hash, { name });\n };\n\n return (\n \n \n {`Edit Projection ${projection?.name}`}\n\n \n setName(event.target.value)} sx={{ mt: 1 }} />\n \n\n \n\n \n onDelete(projection?.hash)}>\n \n \n\n \n \n \n \n );\n}\n","export class EmbeddingController {\n worker: Worker;\n\n stepper: any;\n\n notifier: any;\n\n terminate() {\n this.worker.terminate();\n }\n}\n","import { connect, ConnectedProps, useDispatch, useSelector } from 'react-redux';\nimport * as React from 'react';\nimport { Box, Button, Chip, Grid, IconButton, List, ListItem, ListItemSecondaryAction, ListItemText, Typography } from '@mui/material';\nimport SettingsIcon from '@mui/icons-material/Settings';\nimport { EntityId } from '@reduxjs/toolkit';\nimport { ProjectionControlCard } from './ProjectionControlCard';\nimport { setProjectionOpenAction } from '../../Ducks/ProjectionOpenDuck';\nimport { setProjectionWorkerAction } from '../../Ducks/ProjectionWorkerDuck';\nimport { ADataset, Dataset } from '../../../model/Dataset';\nimport { GenericSettings } from './GenericSettings';\nimport type { RootState } from '../../Store/Store';\nimport { TSNEEmbeddingController } from './TSNEEmbeddingController';\nimport { UMAPEmbeddingController } from './UMAPEmbeddingController';\nimport { ClusterTrailSettings } from './ClusterTrailSettings';\nimport { setTrailVisibility } from '../../Ducks/TrailSettingsDuck';\nimport { ForceAtlas2EmbeddingController } from './ForceAtlas2EmbeddingController';\nimport { IProjection, IBaseProjection, ProjectionMethod, IPosition } from '../../../model/ProjectionInterfaces';\nimport { FeatureConfig, DEFAULT_EMBEDDINGS, EmbeddingMethod } from '../../../BaseConfig';\nimport { EditProjectionDialog } from './EditProjectionDialog';\nimport { ViewActions, ViewSelector } from '../../Ducks/ViewDuck';\nimport { FeatureType } from '../../../model';\nimport { SelectFeatureComponent } from '../StatesTabPanel/SelectFeatureComponent';\nimport { setProjectionColumnsAction } from '../../Ducks';\n\nconst mapStateToProps = (state: RootState) => ({\n // currentAggregation: state.currentAggregation,\n stories: state.stories,\n projectionWorker: state.projectionWorker,\n projectionOpen: state.projectionOpen,\n dataset: state.dataset,\n // projectionParams: state.projectionParams,\n projections: state.multiples.projections,\n projectionParams: state.projectionParams,\n});\n\nconst mapDispatchToProps = (dispatch) => ({\n setProjectionOpen: (value) => dispatch(setProjectionOpenAction(value)),\n setProjectionWorker: (value) => dispatch(setProjectionWorkerAction(value)),\n // setProjectionParams: value => dispatch(setProjectionParamsAction(value)),\n setProjectionColumns: (value) => dispatch(setProjectionColumnsAction(value)),\n setTrailVisibility: (visibility) => dispatch(setTrailVisibility(visibility)),\n addProjection: (embedding) => dispatch(ViewActions.add(embedding)),\n deleteProjection: (handle: string) => dispatch(ViewActions.remove(handle)),\n updateWorkspace: (workspace: IBaseProjection, metadata?) => dispatch(ViewActions.updateActive({ positions: workspace, metadata })),\n});\n\nconst connector = connect(mapStateToProps, mapDispatchToProps);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {\n config: FeatureConfig;\n projectionWorker?: Worker;\n projectionOpen?: boolean;\n setProjectionOpen?: any;\n setProjectionWorker?: any;\n dataset?: Dataset;\n};\n\nfunction EmbeddingMethodButtons(props: { setOpen; setDomainSettings; embeddings?: EmbeddingMethod[] }) {\n const embeddings = props.embeddings ?? DEFAULT_EMBEDDINGS;\n\n return (\n \n {embeddings.map((emb) => (\n \n {\n props.setDomainSettings(emb);\n props.setOpen(true);\n }}\n >\n {emb.name}\n \n \n ))}\n \n );\n}\n\nexport const EmbeddingTabPanel = connector((props: Props) => {\n const [open, setOpen] = React.useState(false);\n const [domainSettings, setDomainSettings] = React.useState({\n id: '',\n name: '',\n embController: null,\n });\n const [controller, setController] = React.useState(null);\n const [projectionToEdit, setProjectionToEdit] = React.useState(null);\n const [step, setStep] = React.useState(0);\n const stepRef = React.useRef(0);\n\n const dispatch = useDispatch();\n\n const workspace = useSelector(ViewSelector.getWorkspace);\n const workspaceIsTemporal = useSelector(ViewSelector.workspaceIsTemporal);\n const dataset = useSelector((state: RootState) => state.dataset);\n\n let numericFeatures = null;\n if (dataset) {\n numericFeatures = Object.keys(dataset.columns).filter((key) => dataset.columns[key].featureType === FeatureType.Quantitative);\n }\n\n React.useEffect(() => {\n if (controller) {\n controller.terminate();\n }\n setController(null);\n props.setTrailVisibility(false);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [props.dataset]);\n\n const onSaveProjectionClick = () => {\n dispatch(ViewActions.copyFromWorkspace());\n };\n\n const onProjectionClick = (projection: IProjection) => {\n dispatch(ViewActions.loadById(projection.hash));\n };\n\n const onDeleteEditProjectDialog = (handle: string) => {\n props.deleteProjection(handle);\n setProjectionToEdit(null);\n };\n\n const onCloseEditProjectionDialog = () => {\n setProjectionToEdit(null);\n };\n\n const onSaveEditProjectionDialog = (key: EntityId, changes: any) => {\n dispatch(ViewActions.save({ id: key, changes }));\n setProjectionToEdit(null);\n };\n\n return (\n
    \n \n\n \n \n Projection Methods\n \n \n\n \n \n \n\n \n {\n if (controller) {\n controller.terminate();\n }\n setController(null);\n props.setTrailVisibility(false);\n }}\n onComputingChanged={() => {}}\n onStep={(step) => {\n stepRef.current += 1;\n setStep(stepRef.current);\n }}\n />\n \n\n setOpen(false)}\n onStart={(params, selection) => {\n const checked_sel = selection.filter((s) => s.checked);\n if (checked_sel.length <= 0) {\n alert('Select at least one feature.');\n return;\n }\n\n stepRef.current = 0;\n setOpen(false);\n props.setProjectionColumns(selection);\n\n const seed = ADataset.getSpatialData(dataset, workspace.xChannel, workspace.yChannel, workspace.positions);\n\n // props.setProjectionParams(params)\n\n switch (domainSettings.id) {\n case ProjectionMethod.TSNE: {\n const controller = new TSNEEmbeddingController();\n controller.init(props.dataset, selection, params, seed);\n const paramsCopy = { ...params };\n controller.stepper = (Y) => {\n const workspace = Y.map((y) => ({ x: y[0], y: y[1] }));\n props.updateWorkspace(workspace, { ...paramsCopy, iterations: stepRef.current, features: [...selection] });\n };\n\n setController(controller);\n break;\n }\n\n case ProjectionMethod.UMAP: {\n console.log(workspace);\n const controller = new UMAPEmbeddingController();\n const paramsCopy = { ...params };\n controller.init(props.dataset, selection, params, seed);\n controller.stepper = (Y) => {\n const workspace = props.dataset.vectors.map((sample, i) => {\n return {\n x: Y[i][0],\n y: Y[i][1],\n };\n });\n props.updateWorkspace(workspace, { ...paramsCopy, iterations: stepRef.current, features: [...selection] });\n };\n\n setController(controller);\n break;\n }\n case ProjectionMethod.FORCEATLAS2: {\n const controller = new ForceAtlas2EmbeddingController();\n controller.init(props.dataset, selection, params);\n const paramsCopy = { ...params };\n controller.stepper = (Y) => {\n const workspace = props.dataset.vectors.map((sample) => {\n const idx = controller.nodes[sample.__meta__.duplicateOf].__meta__.meshIndex;\n return {\n x: Y[idx].x,\n y: Y[idx].y,\n };\n });\n\n props.updateWorkspace(workspace, { ...paramsCopy, iterations: stepRef.current, features: [...selection] });\n };\n\n setController(controller);\n break;\n }\n default: {\n // custom embedding controller\n if (domainSettings.embController) {\n const controller = domainSettings.embController;\n const paramsCopy = { ...params };\n controller.init(props.dataset, selection, params, workspace);\n controller.stepper = (Y: IBaseProjection) => {\n props.updateWorkspace(Y, { ...paramsCopy, method: ProjectionMethod.CUSTOM, iterations: stepRef.current, features: [...selection] });\n };\n\n setController(controller);\n }\n break;\n }\n }\n }}\n />\n\n \n \n Projection Settings\n \n \n\n \n \n \n\n \n {dataset && numericFeatures && workspace ? (\n {\n dispatch(ViewActions.selectChannel({ dataset, channel: 'x', value: newValue }));\n }}\n />\n ) : null}\n\n {dataset && numericFeatures && workspace ? (\n {\n dispatch(ViewActions.selectChannel({ dataset, channel: 'y', value: newValue }));\n }}\n />\n ) : null}\n \n\n \n \n Visible Projection\n \n : }\n >\n {workspaceIsTemporal ? (\n {workspace?.metadata.method.toUpperCase()}} secondary={`Iteration ${step}`} />\n ) : (\n {workspace?.metadata.method.toUpperCase()}} secondary={`loaded from ${workspace?.name}`} />\n )}\n \n \n\n \n \n \n\n \n \n Stored Projections\n \n \n\n
    \n \n {props.projections.ids.map((key) => {\n const projection = props.projections.entities[key];\n return (\n onProjectionClick(projection)}\n selected={workspaceIsTemporal === false && workspace?.hash === projection.hash}\n >\n \n \n setProjectionToEdit(props.projections.entities[key])}>\n \n \n \n \n );\n })}\n \n
    \n
    \n );\n});\n","/* eslint-disable react/static-property-placement */\n/* eslint-disable react/no-unstable-nested-components */\n/* eslint-disable react/no-this-in-sfc */\n/* eslint-disable react/function-component-definition */\nimport * as React from 'react';\nimport DataGrid, { SelectColumn, SelectCellFormatter, GroupFormatterProps, Column } from 'react-data-grid';\nimport { groupBy as rowGrouper } from 'lodash';\nimport { DefaultFeatureLabel } from '../../../model/Dataset';\nimport { ProjectionColumn } from '../../Ducks';\n\nexport function FeaturePicker({\n selection,\n setSelection,\n selectedRows,\n setSelectedRows,\n}: {\n selection: ProjectionColumn[];\n setSelection;\n selectedRows;\n setSelectedRows;\n}) {\n const [expandedGroupIds, setExpandedGroupIds] = React.useState>(\n () => new Set(Object.keys(rowGrouper(selection, 'featureLabel')).includes(DefaultFeatureLabel) ? [DefaultFeatureLabel] : []),\n );\n\n const ref = React.useRef();\n ref.current = () => setSelection([...selection]);\n\n const columns = React.useMemo[]>(\n () => [\n SelectColumn,\n { key: 'featureLabel', name: 'Group', width: 250 },\n { key: 'name', name: 'Name' },\n {\n key: 'normalized',\n name: 'Normalized',\n width: 80,\n formatter({ row, onRowChange, isCellSelected }) {\n return (\n {\n onRowChange({ ...row, normalized: !row.normalized });\n }}\n isCellSelected={isCellSelected}\n />\n );\n },\n groupFormatter(props: GroupFormatterProps) {\n return (\n row.normalized).length === props.childRows.length}\n onChange={(checked) => {\n props.childRows.forEach((row) => {\n row.normalized = checked;\n });\n ref.current();\n }}\n />\n );\n },\n },\n {\n key: 'range',\n name: 'Range',\n width: 250,\n },\n ],\n [],\n );\n\n return (\n row.name}\n onRowsChange={setSelection}\n rows={selection}\n columns={columns}\n />\n );\n}\n","/* eslint-disable spaced-comment */\n/* eslint-disable @typescript-eslint/no-this-alias */\n/* eslint-disable new-cap */\nimport * as Graph from 'graphology';\n\n// @ts-ignore\nimport forceatlas2Worker from 'worker-loader?inline=no-fallback!../../workers/embeddings/forceatlas2.worker';\nimport { DataLine } from '../../../model/DataLine';\nimport { Dataset } from '../../../model/Dataset';\nimport { EmbeddingController } from './EmbeddingController';\n\nimport { IVector } from '../../../model/Vector';\n\nexport class ForceAtlas2EmbeddingController extends EmbeddingController {\n nodes: any;\n\n buildGraph(segments: DataLine[]) {\n const nodes: IVector[] = [];\n const edges = [];\n\n const dups = [];\n segments.forEach((segment) => {\n let prev: IVector = null;\n let prevWasDuplicate = false;\n\n segment.vectors.forEach((sample, i) => {\n const fIdx = nodes.findIndex((e) => e.x === sample.x && e.y === sample.y);\n const isDuplicate = fIdx >= 0;\n\n if (isDuplicate) {\n dups.push(sample);\n // If we have a duplicate, add edge only\n if (!prevWasDuplicate && i !== 0) {\n edges.push({ source: prev.__meta__.meshIndex, destination: nodes[fIdx].__meta__.meshIndex });\n }\n sample.__meta__.duplicateOf = fIdx;\n } else {\n nodes.push(sample);\n if (i !== 0) {\n edges.push({ source: prev.__meta__.meshIndex, destination: sample.__meta__.meshIndex });\n }\n sample.__meta__.duplicateOf = nodes.length - 1;\n }\n\n prevWasDuplicate = isDuplicate;\n prev = isDuplicate ? nodes[fIdx] : sample;\n });\n });\n return [nodes, edges];\n }\n\n init(dataset: Dataset, selection: any, params: any) {\n //@ts-ignore\n const graph = new Graph();\n\n const [nodes, edges] = this.buildGraph(dataset.segments);\n this.nodes = nodes;\n\n nodes.forEach((node) => {\n if (!params.seeded) {\n node.x = Math.random();\n node.y = Math.random();\n }\n graph.addNode(node.__meta__.meshIndex, {\n x: params.seeded ? node.x : Math.random(),\n y: params.seeded ? node.y : Math.random(),\n });\n });\n edges.forEach((edge) => {\n graph.addEdge(edge.source, edge.destination);\n });\n\n // this.worker = new Worker(new URL('../../workers/embeddings/forceatlas2.worker', import.meta.url));\n this.worker = new forceatlas2Worker();\n\n const self = this;\n this.worker.onmessage = function (e) {\n switch (e.data.type) {\n case 'progress':\n case 'finish': {\n const Y = e.data.positions;\n self.stepper(Y);\n self.notifier();\n break;\n }\n default:\n break;\n }\n };\n this.worker.postMessage({\n nodes: nodes.map((e) => ({ x: e.x, y: e.y, meshIndex: e.__meta__.meshIndex })),\n edges,\n params: { iterations: params.iterations },\n });\n }\n\n step() {\n // this.worker.postMessage({\n // messageType: 'step'\n // })\n }\n}\n","import {\n Button,\n Checkbox,\n Container,\n Dialog,\n DialogActions,\n DialogContent,\n FormControl,\n FormControlLabel,\n FormGroup,\n FormLabel,\n Grid,\n InputLabel,\n MenuItem,\n Select,\n TextField,\n} from '@mui/material';\nimport * as React from 'react';\nimport { connect, ConnectedProps } from 'react-redux';\nimport clone from 'fast-clone';\nimport type { RootState } from '../../Store/Store';\nimport { DistanceMetric } from '../../../model/DistanceMetric';\nimport { NormalizationMethod } from '../../../model/NormalizationMethod';\nimport { EncodingMethod } from '../../../model/EncodingMethod';\nimport { FeaturePicker } from './FeaturePicker';\nimport { setProjectionParamsAction } from '../../Ducks/ProjectionParamsDuck';\nimport { ProjectionMethod } from '../../../model';\nimport { ProjectionColumn } from '../../Ducks';\n\nconst mapState = (state: RootState) => ({\n projectionColumns: state.projectionColumns,\n projectionParams: state.projectionParams,\n});\n\nconst mapDispatch = (dispatch) => ({\n setProjectionParams: (value) => dispatch(setProjectionParamsAction(value)),\n});\n\nconst connector = connect(mapState, mapDispatch);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {\n domainSettings: any;\n open: boolean;\n onClose: any;\n onStart: any;\n};\n\nfunction CustomSettings({ tempProjectionParams, setTempProjectionParams, inputDict }) {\n return (\n \n {inputDict.perplexity && (\n {\n setTempProjectionParams({ ...tempProjectionParams, perplexity: event.target.value });\n }}\n />\n )}\n {inputDict.learningRate && (\n {\n setTempProjectionParams({ ...tempProjectionParams, learningRate: event.target.value });\n }}\n />\n )}\n {inputDict.nneighbors && (\n {\n setTempProjectionParams({ ...tempProjectionParams, nNeighbors: event.target.value });\n }}\n />\n )}\n \n );\n}\n\n// const TSNESettings = ({ tempProjectionParams, setTempProjectionParams }) => {\n\n// return \n// {\n// setTempProjectionParams({...tempProjectionParams, perplexity: event.target.value});\n// }}\n// />\n// {\n// setTempProjectionParams({...tempProjectionParams, learningRate: event.target.value});\n// }}\n// />\n// \n// }\n\n// const UMAPSettings = ({ tempProjectionParams, setTempProjectionParams }) => {\n\n// return \n// {\n// setTempProjectionParams({...tempProjectionParams, nNeighbors: event.target.value});\n// }}\n// />\n// \n// }\n\nfunction GenericSettingsComp({ domainSettings, open, onClose, onStart, projectionParams, setProjectionParams, projectionColumns }: Props) {\n const [tempProjectionParams, setTempProjectionParams] = React.useState({ ...projectionParams });\n\n const changeDistanceMetric = (value) => {\n // when we change the distance metric, we need to adapt normalization Method and encoding of categorical features --> gower's distance usually normalizes between [0,1] and does not one-hot encode because it uses dedicated distance measures for categorical data\n // TODO: maybe it would make sense to make a user input for normalization and encoding methods...\n switch (value) {\n case DistanceMetric.GOWER:\n setTempProjectionParams({ ...tempProjectionParams, normalizationMethod: NormalizationMethod.NORMALIZE01 });\n setTempProjectionParams({ ...tempProjectionParams, encodingMethod: EncodingMethod.NUMERIC });\n break;\n default:\n setTempProjectionParams({ ...tempProjectionParams, normalizationMethod: NormalizationMethod.STANDARDIZE });\n setTempProjectionParams({ ...tempProjectionParams, encodingMethod: EncodingMethod.ONEHOT });\n break;\n }\n setTempProjectionParams({ ...tempProjectionParams, distanceMetric: value });\n };\n\n const cloneColumns = (projectionColumns) => {\n return projectionColumns.map((val) => {\n return clone(val);\n });\n };\n\n const [selection, setSelection] = React.useState(cloneColumns(projectionColumns) as ProjectionColumn[]);\n const [selectedRows, setSelectedRows] = React.useState>(() => new Set(selection.filter((row) => row.checked).map((row) => row.name)));\n\n React.useEffect(() => {\n if (open) {\n setSelection(cloneColumns(projectionColumns));\n setSelectedRows(new Set(projectionColumns.filter((row) => row.checked).map((row) => row.name)));\n }\n }, [projectionColumns, open]);\n\n return (\n \n \n \n {domainSettings.id !== ProjectionMethod.FORCEATLAS2 && (\n \n )}\n\n \n \n \n Projection Parameters\n {/* TODO: add also make parameters customizable; currently only a fixed set of parameters can set to be shown or not */}\n \n {/* {domainSettings.id == 'umap' && } */}\n {/* {domainSettings.id == 'tsne' && } */}\n \n \n\n \n \n General Parameters\n \n {\n setTempProjectionParams({ ...tempProjectionParams, iterations: parseInt(event.target.value, 10) });\n }}\n />\n setTempProjectionParams({ ...tempProjectionParams, seeded: checked })}\n name=\"jason\"\n />\n }\n label=\"Seed Position\"\n />\n setTempProjectionParams({ ...tempProjectionParams, useSelection: checked })}\n />\n }\n label=\"Project Selection Only\"\n />\n {domainSettings.id !== ProjectionMethod.FORCEATLAS2 && (\n \n Distance Metric\n {\n changeDistanceMetric(event.target.value);\n }}\n >\n Euclidean\n Jaccard\n Gower\n \n \n )}\n \n \n \n \n \n \n \n \n {\n selection.forEach((row) => {\n row.checked = selectedRows.has(row.name);\n });\n\n tempProjectionParams.method = domainSettings.id;\n setProjectionParams(tempProjectionParams);\n onStart(tempProjectionParams, selection);\n }}\n >\n Start\n \n \n \n );\n}\n\nexport const GenericSettings = connector(GenericSettingsComp);\n","/* eslint-disable react-hooks/exhaustive-deps */\nimport * as React from 'react';\nimport { Card, CardHeader, IconButton } from '@mui/material';\nimport PlayArrowIcon from '@mui/icons-material/PlayArrow';\nimport StopIcon from '@mui/icons-material/Stop';\nimport CloseIcon from '@mui/icons-material/Close';\nimport { connect, ConnectedProps } from 'react-redux';\nimport { makeStyles } from '@mui/styles';\nimport type { RootState } from '../../Store/Store';\n\n/**\n * Styles for the projection card that allows to stop/resume projection steps.\n */\nconst useStylesMedia = makeStyles(() => ({\n root: {\n display: 'flex',\n margin: '8px 0',\n pointerEvents: 'auto',\n },\n details: {\n display: 'flex',\n flexDirection: 'column',\n width: '100%',\n },\n content: {\n flex: '1 0 auto',\n },\n cover: {\n width: 151,\n },\n controls: {\n display: 'flex',\n alignItems: 'center',\n flexDirection: 'column',\n // paddingLeft: theme.spacing(1),\n // paddingBottom: theme.spacing(1),\n width: '100%',\n },\n playIcon: {\n height: 38,\n width: 38,\n },\n}));\n\nconst mapStateToProps = (state: RootState) => ({\n projectionParams: state.projectionParams,\n worker: state.projectionWorker,\n});\n\nconst mapDispatch = () => ({});\n\nconst connector = connect(mapStateToProps, mapDispatch);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {\n onClose: any;\n onComputingChanged: any;\n controller: any;\n dataset_name: string;\n onStep?: any;\n};\n\n/**\n * Projection card that allows to start/stop the projection and shows the current steps.\n */\nexport const ProjectionControlCard = connector(({ onComputingChanged, projectionParams, controller, onClose, dataset_name, onStep }: Props) => {\n if (controller == null) return null;\n\n const classes = useStylesMedia();\n\n const [step, setStep] = React.useState(0);\n const [msg, setMsg] = React.useState('');\n const ref = React.useRef(step);\n\n if (step === 0) {\n console.time(`time elapsed to project the file ${dataset_name}`);\n }\n if (step / projectionParams.iterations >= 1) {\n console.timeEnd(`time elapsed to project the file ${dataset_name}`);\n }\n\n const [computing, setComputing] = React.useState(true);\n\n function updateState(newState) {\n ref.current = newState;\n setStep(newState);\n }\n\n controller.notifier = (step?: number, msg?: string) => {\n setMsg(msg);\n let new_step = ref.current + 1;\n if (step != null && !Number.isNaN(step)) {\n // checks if step is not null or undefined or nan\n new_step = step;\n }\n updateState(new_step);\n if (onStep) {\n onStep(new_step);\n }\n };\n\n React.useEffect(() => {\n if (step < projectionParams.iterations && computing) {\n controller.step();\n }\n }, [step, computing]);\n\n const genlabel = (step) => {\n if (step === 0) {\n return (\n
    \n
    Initializing Projection ...
    \n {msg &&
    Server: {msg}
    }\n
    \n );\n }\n const percent = Math.min((step / projectionParams.iterations) * 100, 100).toFixed(1);\n return (\n
    \n
    {`${Math.min(step, projectionParams.iterations)}/${projectionParams.iterations}`}
    \n
    {`${percent}%`}
    \n {msg &&
    Server: {msg}
    }\n
    \n );\n };\n\n return (\n \n
    \n }\n action={\n {\n console.timeEnd(`time elapsed to project the file ${dataset_name}`);\n onClose();\n }}\n >\n \n \n }\n title={projectionParams.method}\n subheader={genlabel(step)}\n />\n
    \n {\n const newVal = !computing;\n setComputing(newVal);\n onComputingChanged(null, newVal);\n }}\n >\n {/* TODO: don't show play/pause for back-end projection, since it does not do anything */}\n {computing ? : }\n \n
    \n
    \n
    \n );\n});\n","// @ts-ignore\nimport tsneWorker from 'worker-loader?inline=no-fallback!../../workers/embeddings/tsne.worker';\nimport { Dataset, ADataset } from '../../../model/Dataset';\nimport { EmbeddingController } from './EmbeddingController';\n\nimport { IBaseProjection } from '../../../model/ProjectionInterfaces';\n\nexport class TSNEEmbeddingController extends EmbeddingController {\n init(dataset: Dataset, selection: any, params: any, workspace: IBaseProjection) {\n // this.worker = new Worker(new URL('../../workers/embeddings/tsne.worker', import.meta.url));\n // eslint-disable-next-line new-cap\n this.worker = new tsneWorker();\n\n const tensor = ADataset.asTensor(\n dataset,\n selection.filter((e) => e.checked),\n params.encodingMethod,\n params.normalizationMethod,\n ); // for gower, we don't need one-hot-encoding\n this.worker.postMessage({\n messageType: 'init',\n input: tensor.tensor,\n seed: dataset.vectors.map((vec, i) => [workspace[i].x, workspace[i].y]),\n params,\n featureTypes: tensor.featureTypes,\n });\n\n this.worker.addEventListener(\n 'message',\n (e) => {\n const Y = e.data;\n this.stepper(Y);\n this.notifier();\n },\n false,\n );\n }\n\n step() {\n this.worker.postMessage({\n messageType: 'step',\n });\n }\n}\n","// @ts-ignore\nimport umapWorker from 'worker-loader?inline=no-fallback!../../workers/embeddings/umap.worker';\nimport { Dataset, ADataset } from '../../../model/Dataset';\nimport { EmbeddingController } from './EmbeddingController';\n\nimport { IBaseProjection } from '../../../model/ProjectionInterfaces';\n\nexport class UMAPEmbeddingController extends EmbeddingController {\n targetBounds: any;\n\n init(dataset: Dataset, selection: any, params: any, workspace: IBaseProjection) {\n // this.worker = new Worker(new URL('../../workers/embeddings/umap.worker', import.meta.url));\n // eslint-disable-next-line new-cap\n this.worker = new umapWorker();\n\n const tensor = ADataset.asTensor(\n dataset,\n selection.filter((e) => e.checked),\n params.encodingMethod,\n params.normalizationMethod,\n );\n this.worker.postMessage({\n messageType: 'init',\n input: tensor.tensor,\n seed: dataset.vectors.map((vec, i) => [workspace[i].x, workspace[i].y]),\n params,\n featureTypes: tensor.featureTypes,\n });\n\n this.worker.addEventListener(\n 'message',\n (e) => {\n const Y = e.data;\n this.stepper(Y);\n this.notifier();\n },\n false,\n );\n }\n\n step() {\n this.worker.postMessage({\n messageType: 'step',\n });\n }\n}\n","export * from './ClusterTrailSettings';\nexport * from './EmbeddingController';\nexport * from './EmbeddingTabPanel';\nexport * from './ForceAtlas2EmbeddingController';\nexport * from './GenericSettings';\nexport * from './ProjectionControlCard';\nexport * from './TSNEEmbeddingController';\nexport * from './UMAPEmbeddingController';\n","import { Box, Button, FormControlLabel, Switch, Typography } from '@mui/material';\nimport * as React from 'react';\nimport { connect, ConnectedProps } from 'react-redux';\nimport { selectVectors } from '../../Ducks/AggregationDuck';\nimport { setHoverWindowMode, WindowMode } from '../../Ducks/HoverSettingsDuck';\nimport { SelectionClusters } from '../../Overlays/SelectionClusters';\nimport type { RootState } from '../../Store/Store';\n\nconst mapStateToProps = (state: RootState) => ({\n hoverSettings: state.hoverSettings,\n currentAggregation: state.currentAggregation,\n dataset: state.dataset,\n});\n\nconst mapDispatchToProps = (dispatch) => ({\n setHoverWindowMode: (value) => dispatch(setHoverWindowMode(value)),\n setAggregation: (value) => dispatch(selectVectors(value)),\n});\n\nconst connector = connect(mapStateToProps, mapDispatchToProps);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {};\n\nexport const HoverTabPanel = connector(({ hoverSettings, setHoverWindowMode, setAggregation, currentAggregation, dataset }: Props) => {\n const handleChange = (_, value) => {\n setHoverWindowMode(value ? WindowMode.Extern : WindowMode.Embedded);\n };\n\n return (\n
    \n \n {/* TODO: Cluster count not working */}\n {/* in {currentAggregation.selectedClusters.length} Groups */}\n \n Selected {currentAggregation.aggregation.length} out of {dataset && dataset.vectors.length} items\n \n\n }\n label=\"External Selection Summary\"\n />\n\n {\n setAggregation([]);\n }}\n >\n Clear Selection\n \n \n\n \n
    \n );\n});\n","export * from './HoverTabPanel';\n","import { connect } from 'react-redux';\nimport * as React from 'react';\nimport { FormControlLabel, Checkbox, Typography, Grid } from '@mui/material';\nimport { Mapping, mapValueToColor } from '../../Utility/Colors/Mapping';\nimport { setAdvancedColoringSelectionAction } from '../../Ducks/AdvancedColoringSelectionDuck';\nimport { RootState } from '../../Store';\n\nconst mapStateToProps = (state: RootState) => ({\n advancedColoringSelection: state.advancedColoringSelection,\n});\n\nconst mapDispatchToProps = (dispatch) => ({\n setAdvancedColoringSelection: (advancedColoringSelection) => dispatch(setAdvancedColoringSelectionAction(advancedColoringSelection)),\n});\n\ntype ShowColorLegendProps = {\n pointColorMapping: Mapping;\n advancedColoringSelection: boolean[];\n setAdvancedColoringSelection: Function;\n};\n\nfunction toLabel(value: any): string {\n if (value === '') {\n return '';\n }\n if (value === null) {\n return '';\n }\n if (value === undefined) {\n return '';\n }\n\n return value;\n}\n\nexport function AdvancedColoringLegendFull({ pointColorMapping, advancedColoringSelection, setAdvancedColoringSelection }: ShowColorLegendProps) {\n if (pointColorMapping == null) {\n return
    ;\n }\n\n if (pointColorMapping.type === 'categorical') {\n return (\n \n {pointColorMapping.values.map((value, index) => {\n const color = mapValueToColor(pointColorMapping, value);\n return (\n {\n const values = advancedColoringSelection.splice(0);\n values[event.target.value] = event.target.checked;\n setAdvancedColoringSelection(values);\n }}\n value={index}\n />\n }\n label={{toLabel(value)}}\n />\n );\n })}\n \n );\n }\n\n return
    ;\n}\n\nexport const AdvancedColoringLegend = connect(mapStateToProps, mapDispatchToProps)(AdvancedColoringLegendFull);\n","import { Button, Popover } from '@mui/material';\nimport * as React from 'react';\nimport { AdvancedColoringLegend } from './AdvancedColoringLegend';\n\nexport function AdvancedColoringPopover({ pointColorMapping }) {\n const [anchorEl, setAnchorEl] = React.useState(null);\n\n const handleClick = (event) => {\n setAnchorEl(event.currentTarget);\n };\n\n const handleClose = () => {\n setAnchorEl(null);\n };\n\n const open = Boolean(anchorEl);\n const id = open ? 'simple-popover' : undefined;\n\n return (\n
    \n \n \n \n \n
    \n );\n}\n","import * as React from 'react';\nimport { Typography, Slider } from '@mui/material';\nimport { connect } from 'react-redux';\nimport { makeStyles } from '@mui/styles';\nimport type { RootState } from '../../Store/Store';\nimport { setGlobalPointBrightness } from '../../Ducks/GlobalPointBrightnessDuck';\n\nconst useStyles = makeStyles(() => ({\n root: {\n margin: '0px 16px',\n padding: '0px 8px',\n },\n}));\n\nfunction BrightnessSliderFull({ globalPointBrightness, setRange }) {\n const classes = useStyles();\n\n const marks = [\n {\n value: 0,\n label: '0',\n },\n {\n value: 0.25,\n label: `0.25`,\n },\n {\n value: 0.5,\n label: `0.5`,\n },\n {\n value: 0.75,\n label: `0.75`,\n },\n {\n value: 1,\n label: `1`,\n },\n ];\n\n return (\n
    \n \n Brightness Scale\n \n setRange(newValue)} step={0.05} marks={marks} valueLabelDisplay=\"auto\" />\n
    \n );\n}\n\nconst mapStateToProps = (state: RootState) => ({});\n\nconst mapDispatchToProps = (dispatch) => ({\n setRange: (value) => dispatch(setGlobalPointBrightness(value)),\n});\n\nexport const BrightnessSlider = connect(mapStateToProps, mapDispatchToProps)(BrightnessSliderFull);\n","import * as React from 'react';\nimport { Button, List, ListItem, Menu, MenuItem, Slider, TextField } from '@mui/material';\nimport { connect, useSelector, useDispatch } from 'react-redux';\nimport { css, styled } from '@mui/material/styles';\nimport { clone } from 'lodash';\nimport * as d3v5 from 'd3v5';\nimport { RootState } from '../../Store';\nimport { ANormalized, ContinuousMapping, DivergingMapping, isNumericMapping, Mapping, mapValueToColor, NormalizedDictionary } from '../../Utility';\nimport { BaseColorScale } from '../../../model/Palette';\nimport { APalette } from '../../../model/palettes';\nimport { PointColorScaleActions } from '../../Ducks';\nimport { CategoryOption } from '../../WebGLView/CategoryOptions';\nimport { ViewActions, ViewSelector } from '../../Ducks/ViewDuck';\nimport { Dataset } from '../../../model/Dataset';\nimport { getMinMaxOfChannel } from '../../WebGLView/UtilityFunctions';\n\nconst SVG_ID = 'mapping_svghistogram';\nconst WIDTH = 288 - 32;\n\n/**\n * Custom styled slider that is positioned over a color scale to adjust the center.\n */\nexport const ThumbSlider = styled(Slider)(({ theme }) => ({\n color: theme.palette.mode === 'dark' ? '#3880ff' : '#3880ff',\n height: 2,\n padding: '15px 0',\n position: 'absolute',\n top: 3,\n pointerEvents: 'none',\n '& .MuiSlider-thumb': {\n pointerEvents: 'auto',\n },\n '& .MuiSlider-track': {\n display: 'none',\n },\n '& .MuiSlider-rail': {\n display: 'none',\n },\n '& .MuiSlider-mark': {\n display: 'none',\n },\n '& .MuiSlider-thumb:before': {\n width: 1,\n height: 62,\n backgroundImage: 'linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 50%, rgba(0,0,0,0) 100%)',\n borderRadius: 0,\n top: -64,\n },\n}));\n\nconst BaseScale = styled('div')({\n width: '100%',\n minWidth: 200,\n height: '1rem',\n});\n\n/**\n * Renders one color scale with an optional center point.\n */\nexport function ColorScaleMenuItem({ scale, skew, deadzone }: { scale: BaseColorScale; skew?: number; deadzone?: number }) {\n if (!scale) {\n return null;\n }\n\n const center = skew ?? 50;\n const palette = typeof scale.palette === 'string' ? APalette.getByName(scale.palette) : scale.palette;\n\n switch (scale.type) {\n case 'sequential':\n return stop.hex).join(',')})` }} />;\n case 'diverging': {\n const i0 = Math.floor(palette.length / 2);\n const i1 = palette.length / 2 + 0.5;\n const t0 = center - (deadzone ?? 0) * 100;\n const t1 = center + (deadzone ?? 0) * 100;\n\n const gradient = `${palette\n .slice(0, i0)\n .map((stop, i) => `${stop.hex} ${i * (t0 / i0)}%`)\n .join(',')}, ${palette[Math.floor(palette.length / 2)].hex} ${t0}%, ${palette[Math.floor(palette.length / 2)].hex} ${t1}%, ${palette\n .slice(i1, palette.length)\n .map((stop, i) => `${stop.hex} ${t1 + (i + 1) * ((100 - t1) / i0)}%`)\n .join(',')}`;\n\n return (\n \n );\n }\n case 'categorical':\n return (\n `${stop.hex} ${(index / palette.length) * 100.0}%, ${stop.hex} ${((index + 1) / palette.length) * 100.0}%`)\n .join(',')})`,\n }}\n />\n );\n default:\n return null;\n }\n}\n\nexport default function NumberInput({ value, setValue, label }: { value: number; setValue: (_: number) => void; label: string }) {\n return (\n {\n const value = parseFloat(e.target.value);\n\n if (!Number.isNaN(value)) {\n setValue(value);\n }\n }}\n variant=\"standard\"\n size=\"small\"\n label={label}\n />\n );\n}\n\nfunction DivergingInput({ mapping, setMapping }: { mapping: [number, number, number] | [number, number]; setMapping: (value) => void }) {\n const alterMapping = (index: number, value: number) => {\n const newVal = clone(mapping);\n newVal[index] = value;\n setMapping(newVal);\n };\n\n return (\n
    \n alterMapping(0, value)} label=\"min\" />\n {mapping.length === 3 ? alterMapping(1, value)} label=\"center\" /> : null}\n alterMapping(mapping.length - 1, value)} label=\"max\" />\n
    \n );\n}\n\n/**\n * Component that lets user pick from a list of color scales.\n */\nexport function ColorScaleSelectFull({ channelColor, active }: { channelColor: CategoryOption; active }) {\n const [anchorEl, setAnchorEl] = React.useState(null);\n\n const dataset = useSelector((state) => state.dataset);\n const scales = useSelector>((state) => state.colorScales.scales);\n const mapping = useSelector(ViewSelector.defaultSelector).attributes.pointColorMapping as Mapping;\n\n const [tempMapping, setTempMapping] = React.useState<[number, number, number]>([0, 0, 0]);\n let min = 0;\n let max = 0;\n let mid = 0;\n if (tempMapping.length === 3) {\n [min, mid, max] = tempMapping;\n } else {\n [min, max] = tempMapping;\n }\n\n const height = 50;\n\n React.useEffect(() => {\n if (isNumericMapping(mapping)) {\n setTempMapping(clone(mapping.range));\n }\n }, [mapping]);\n\n React.useEffect(() => {\n const svg = d3v5.select(`#${SVG_ID}`);\n\n if (!(channelColor && active && isNumericMapping(mapping))) {\n svg.selectAll('*').remove();\n\n return;\n }\n\n const x = d3v5.scaleLinear().domain([min, max]).range([0, WIDTH]);\n\n const histogram = d3v5\n .histogram()\n .value(function (d) {\n return d[channelColor.key];\n })\n .domain(x.domain() as [number, number])\n .thresholds(x.ticks(70));\n\n // @ts-ignore\n const bins = histogram(dataset.vectors);\n\n const y = d3v5\n .scaleLinear()\n .range([height, 0])\n .domain([\n 0,\n d3v5.max(bins, function (d) {\n return d.length;\n }),\n ]);\n\n svg\n .selectAll('rect')\n .data(bins)\n .join('rect')\n .attr('x', 1)\n .attr('transform', function (d) {\n return `translate(${x(d.x0)},${y(d.length)})`;\n })\n .attr('width', function (d) {\n return Math.max(0, x(d.x1) - x(d.x0) - 1);\n })\n .attr('height', function (d) {\n return height - y(d.length);\n });\n }, [min, max, channelColor, mapping, dataset.vectors, active]);\n\n React.useEffect(() => {\n if (!(channelColor && active && isNumericMapping(mapping))) {\n return;\n }\n\n const svg = d3v5.select(`#${SVG_ID}`);\n const newMapping = clone(mapping) as DivergingMapping | ContinuousMapping;\n\n if (mapping.type === 'diverging') {\n newMapping.range = [min, mid, max];\n } else {\n newMapping.range = [min, max];\n }\n\n svg.selectAll('rect').style('fill', (d) => {\n // @ts-ignore\n return mapValueToColor(newMapping, d.x0).hex;\n });\n }, [min, mid, max, mapping, active, channelColor]);\n\n const dispatch = useDispatch();\n\n const handleClickListItem = (event) => {\n setAnchorEl(event.currentTarget);\n };\n\n const handleMenuItemClick = () => {\n setAnchorEl(null);\n };\n\n const handleClose = () => {\n setAnchorEl(null);\n };\n\n if (!channelColor || !scales) {\n return null;\n }\n\n const scaleFilter =\n channelColor.type === 'categorical'\n ? (value: BaseColorScale) => value.type === 'categorical'\n : (value: BaseColorScale) => value.type === 'diverging' || value.type === 'sequential';\n\n return (\n <>\n {isNumericMapping(mapping) ? (\n \n ) : null}\n\n
    \n \n \n \n \n \n \n {ANormalized.entries(scales)\n .filter(([, value]) => scaleFilter(value))\n .map(([key, value]) => (\n {\n dispatch(PointColorScaleActions.pickScale(key));\n handleMenuItemClick();\n }}\n >\n \n \n ))}\n \n\n {mapping?.type === 'diverging' ? (\n {\n setTempMapping([min, newValue, max]);\n }}\n />\n ) : null}\n\n {isNumericMapping(mapping) ? (\n <>\n \n\n
    \n {\n dispatch(ViewActions.changeDivergingRange(tempMapping));\n }}\n >\n Apply\n \n {\n const bounds = getMinMaxOfChannel(dataset, channelColor.key);\n\n if (mapping?.type === 'diverging') {\n dispatch(ViewActions.changeDivergingRange([bounds.min, (bounds.min + bounds.max) / 2, bounds.max]));\n } else if (mapping?.type === 'sequential') {\n dispatch(ViewActions.changeDivergingRange([bounds.min, bounds.max]));\n }\n }}\n >\n Reset\n \n
    \n \n ) : null}\n
    \n \n );\n}\n\nconst mapStateToProps = (state: RootState) => ({});\n\nconst mapDispatchToProps = () => ({});\n\nexport const ColorScaleSelect = connect(mapStateToProps, mapDispatchToProps)(ColorScaleSelectFull);\n","import * as React from 'react';\nimport { Checkbox, FormControlLabel, Typography } from '@mui/material';\nimport { makeStyles } from '@mui/styles';\n\nconst useStyles = makeStyles({\n root: {\n '&:hover': {\n backgroundColor: 'transparent',\n },\n padding: '3px 9px',\n },\n icon: {\n borderRadius: 3,\n width: 16,\n height: 16,\n boxShadow: 'inset 0 0 0 1px rgba(16,22,26,.2), inset 0 -1px 0 rgba(16,22,26,.1)',\n backgroundColor: '#f5f8fa',\n backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.8),hsla(0,0%,100%,0))',\n '$root.Mui-focusVisible &': {\n outline: '2px auto rgba(19,124,189,.6)',\n outlineOffset: 2,\n },\n 'input:hover ~ &': {\n backgroundColor: '#ebf1f5',\n },\n 'input:disabled ~ &': {\n boxShadow: 'none',\n background: 'rgba(206,217,224,.5)',\n },\n },\n checkedIcon: {\n backgroundColor: '#137cbd',\n backgroundImage: 'linear-gradient(180deg,hsla(0,0%,100%,.1),hsla(0,0%,100%,0))',\n '&:before': {\n display: 'block',\n width: 16,\n height: 16,\n backgroundImage:\n \"url(\\\"data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Cpath\" +\n \" fill-rule='evenodd' clip-rule='evenodd' d='M12 5c-.28 0-.53.11-.71.29L7 9.59l-2.29-2.3a1.003 \" +\n \"1.003 0 00-1.42 1.42l3 3c.18.18.43.29.71.29s.53-.11.71-.29l5-5A1.003 1.003 0 0012 5z' fill='%23fff'/%3E%3C/svg%3E\\\")\",\n content: '\"\"',\n },\n 'input:hover ~ &': {\n backgroundColor: '#106ba3',\n },\n },\n});\n\nexport function Checky({ checked, onChange, id, name, comp }) {\n const classes = useStyles();\n\n return (\n }\n label={{name}}\n />\n );\n}\n\ntype LegendState = {\n lineChecks: any;\n type: string;\n};\n\ntype LegendProps = {\n onLineSelect: any;\n};\n\nexport class Legend extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n lineChecks: null,\n type: null,\n };\n\n this.onCheckbox = this.onCheckbox.bind(this);\n }\n\n onCheckbox(event) {\n const newState = {\n lineChecks: this.state.lineChecks,\n };\n const col = newState.lineChecks.filter((c) => c.algo === event.target.id)[0];\n col.checked = event.target.checked;\n\n this.setState(newState);\n\n this.props.onLineSelect(col.algo, event.target.checked);\n }\n\n // eslint-disable-next-line react/no-unused-class-component-methods\n load(type, lineColorScheme, algorithms) {\n const lineChecks = algorithms.map((entry) => {\n return {\n color: lineColorScheme.map(entry.algo),\n name: entry.algo,\n checked: true,\n algo: entry.algo,\n };\n });\n\n this.setState({\n lineChecks,\n type,\n });\n }\n\n render() {\n if (this.state.lineChecks === undefined) return
    ;\n\n let colorLegend = null;\n if (this.state.type === 'neural') {\n colorLegend = this.state.lineChecks.map((line) => {\n const comp = line.color.rgb;\n return (\n
    \n \n {line.name === 'undefined' ? '-' : line.name}\n \n \n
    \n );\n });\n } else {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n colorLegend = this.state.lineChecks.map((line) => {\n const comp = line.color.rgb;\n return (\n \n );\n });\n }\n\n return (\n
    \n {this.state.lineChecks.map((line) => {\n const comp = line.color.rgb;\n\n return ;\n })}\n
    \n );\n }\n}\n","import * as React from 'react';\nimport { Typography, Slider } from '@mui/material';\nimport { connect } from 'react-redux';\nimport { setLineBrightness } from '../../Ducks/LineBrightnessDuck';\n\nfunction PathBrightnessSliderFull({ lineBrightness, setLineBrightness }) {\n const marks = [\n {\n value: 0,\n label: '0%',\n },\n {\n value: 50,\n label: '50%',\n },\n {\n value: 100,\n label: '100%',\n },\n ];\n\n return (\n
    \n \n Line Opacity\n \n {\n setLineBrightness(newValue);\n }}\n marks={marks}\n valueLabelDisplay=\"auto\"\n />\n
    \n );\n}\n\nconst mapStateToProps = (state) => ({});\n\nconst mapDispatchToProps = (dispatch) => ({\n setLineBrightness: (lineBrightness) => dispatch(setLineBrightness(lineBrightness)),\n});\n\nexport const PathBrightnessSlider = connect(mapStateToProps, mapDispatchToProps)(PathBrightnessSliderFull);\n","import * as React from 'react';\nimport { Typography, Slider } from '@mui/material';\nimport { connect } from 'react-redux';\nimport { setPathLengthRange } from '../../Ducks/PathLengthRange';\n\nexport function PathLengthFilterFull({ pathLengthRange, setPathLengthRange }) {\n if (pathLengthRange == null) {\n return
    ;\n }\n\n const marks = [\n {\n value: 0,\n label: '0',\n },\n {\n value: pathLengthRange.maximum,\n label: `${pathLengthRange.maximum}`,\n },\n ];\n\n return (\n
    \n \n Path Length Filter\n \n {\n setPathLengthRange(newValue);\n }}\n marks={marks}\n valueLabelDisplay=\"auto\"\n />\n
    \n );\n}\n\nconst mapStateToProps = (state) => ({});\n\nconst mapDispatchToProps = (dispatch) => ({\n setPathLengthRange: (pathLengthRange) => dispatch(setPathLengthRange(pathLengthRange)),\n});\n\nexport const PathLengthFilter = connect(mapStateToProps, mapDispatchToProps)(PathLengthFilterFull);\n","import * as React from 'react';\nimport { Autocomplete, createFilterOptions, TextField } from '@mui/material';\n\ninterface SelectFeatureComponentProps {\n label: string;\n default_val: string;\n categoryOptions: string[];\n onChange: (value: string) => void;\n column_info;\n}\n\nexport function SelectFeatureComponent({ label, default_val, categoryOptions, onChange, column_info }: SelectFeatureComponentProps) {\n let autocomplete_options = [];\n let autocomplete_filterOptions = null;\n if (categoryOptions != null) {\n autocomplete_options = autocomplete_options.concat(\n categoryOptions.map((attribute) => {\n let group = null;\n if (column_info != null && attribute in column_info) {\n group = column_info[attribute].featureLabel;\n }\n return {\n value: attribute,\n group,\n };\n }),\n );\n autocomplete_filterOptions = createFilterOptions({\n stringify: (option: any) => {\n return option.group + option.value;\n },\n });\n }\n\n return (\n {\n onChange((newValue as any)?.value ?? null);\n }}\n options={autocomplete_options.sort((a, b) => {\n if (a.group === b.group) {\n return -b.value.localeCompare(a.value);\n }\n return -b.group.localeCompare(a.group);\n })}\n size=\"small\"\n groupBy={(option) => option.group}\n getOptionLabel={(option) => option.value}\n isOptionEqualToValue={(option: any, value) => {\n return option.value === value?.value;\n }}\n value={autocomplete_options.find((option) => option.value === default_val) ?? null}\n renderInput={(params) => }\n />\n );\n}\n","/* eslint-disable @typescript-eslint/ban-ts-comment */\nimport * as React from 'react';\nimport { Checkbox } from '@mui/material';\nimport * as clone from 'clone';\n// @ts-ignore\nimport { makeStyles } from '@mui/styles';\n// @ts-ignore\nimport StarSymbol from '../../../../textures/sprites/star.png';\n// @ts-ignore\nimport CircleSymbol from '../../../../textures/sprites/circle.png';\n// @ts-ignore\nimport CrossSymbol from '../../../../textures/sprites/cross.png';\n// @ts-ignore\nimport SquareSymbol from '../../../../textures/sprites/square.png';\n\nconst useStyles = makeStyles(() => ({\n root: {\n padding: '3px 9px !important',\n },\n}));\n\nfunction ShapeSymbol({ symbol, text, checked, onCheck }) {\n const classes = useStyles();\n\n const paths = {\n star: StarSymbol,\n circle: CircleSymbol,\n square: SquareSymbol,\n cross: CrossSymbol,\n };\n\n return (\n
    \n {\n onCheck(event, symbol);\n }}\n disableRipple\n inputProps={{ 'aria-label': 'decorative checkbox' }}\n />\n\n \n \n {text}\n \n
    \n );\n}\n\nfunction defaultState() {\n return {\n cross: true,\n circle: true,\n star: true,\n square: true,\n };\n}\n\n/**\n * Simple shape legend\n * put a category in props\n */\nexport function ShapeLegend({ dataset, category, onChange }) {\n const [state, setState] = React.useState(defaultState());\n\n React.useEffect(() => {\n setState(defaultState());\n }, [category, dataset]);\n\n const defaults = [\n { symbol: 'cross', text: 'First State' },\n { symbol: 'circle', text: 'Intermediate State' },\n { symbol: 'star', text: 'Last State' },\n ];\n\n if (category == null) {\n return (\n
    \n {defaults.map((def) => {\n return (\n {\n const newState = clone(state);\n newState[def.symbol] = event.target.checked;\n setState(newState);\n\n onChange(newState);\n }}\n />\n );\n })}\n
    \n );\n }\n\n return (\n
    \n {category.values.map((v) => {\n return (\n {\n const newState = clone(state);\n newState[v.to] = event.target.checked;\n setState(newState);\n\n onChange(newState);\n }}\n />\n );\n })}\n
    \n );\n}\n","import * as React from 'react';\nimport { Typography, Slider } from '@mui/material';\nimport { connect } from 'react-redux';\nimport { setGlobalPointSize } from '../../Ducks/GlobalPointSizeDuck';\n\nexport const SizeSliderMarks = [\n {\n value: 0,\n label: '0',\n },\n {\n value: 1,\n label: `1`,\n },\n {\n value: 2,\n label: `2`,\n },\n {\n value: 3,\n label: `3`,\n },\n {\n value: 4,\n label: `4`,\n },\n {\n value: 5,\n label: `5`,\n },\n];\n\nfunction SizeSliderFull({ globalPointSize, setRange }) {\n return (\n \n \n Size Scale\n \n\n setRange(newValue)}\n step={0.25}\n marks={SizeSliderMarks}\n valueLabelDisplay=\"auto\"\n />\n
    \n );\n}\n\nconst mapStateToProps = (state) => ({});\n\nconst mapDispatchToProps = (dispatch) => ({\n setRange: (value) => dispatch(setGlobalPointSize(value)),\n});\n\nexport const SizeSlider = connect(mapStateToProps, mapDispatchToProps)(SizeSliderFull);\n","/* eslint-disable react-hooks/rules-of-hooks */\nimport { connect, ConnectedProps, useDispatch, useSelector } from 'react-redux';\nimport * as React from 'react';\nimport { Grid, Typography, Box, Accordion, AccordionSummary, AccordionDetails, createFilterOptions, Autocomplete, TextField } from '@mui/material';\nimport ExpandMoreIcon from '@mui/icons-material/ExpandMore';\nimport { makeStyles } from '@mui/styles';\nimport { ShapeLegend } from './ShapeLegend';\nimport { setVectorByShapeAction } from '../../Ducks/VectorByShapeDuck';\nimport type { RootState } from '../../Store/Store';\nimport { setSelectedLineBy } from '../../Ducks/SelectedLineByDuck';\nimport { setChannelBrightnessAction } from '../../Ducks/ChannelBrightnessDuck';\nimport { setGlobalPointBrightness } from '../../Ducks/GlobalPointBrightnessDuck';\nimport { BrightnessSlider } from './BrightnessSlider';\nimport { setChannelSize } from '../../Ducks/ChannelSize';\nimport { setGlobalPointSize } from '../../Ducks/GlobalPointSizeDuck';\nimport { SizeSlider } from './SizeSlider';\nimport { ColorScaleSelect } from './ColorScaleSelect';\nimport { AdvancedColoringPopover } from './AdvancedColoringPopover';\nimport { setChannelColor } from '../../Ducks/ChannelColorDuck';\nimport { setAdvancedColoringSelectionAction } from '../../Ducks/AdvancedColoringSelectionDuck';\nimport { PathLengthFilter } from './PathLengthFilter';\nimport { PathBrightnessSlider } from './PathBrightnessSlider';\nimport { CategoryOptionsAPI } from '../../WebGLView/CategoryOptions';\nimport { PointDisplayActions } from '../../Ducks/PointDisplayDuck';\nimport { EncodingChannel, BaseColorScale } from '../../../model';\nimport { ViewSelector } from '../../Ducks/ViewDuck';\nimport { PointColorScaleActions } from '../../Ducks';\nimport { ANormalized } from '../../Utility/NormalizedState';\n\nconst mapStateToProps = (state: RootState) => ({\n selectedLineBy: state.selectedLineBy,\n dataset: state.dataset,\n});\n\nconst mapDispatchToProps = (dispatch) => ({\n setVectorByShape: (vectorByShape) => dispatch(setVectorByShapeAction(vectorByShape)),\n setSelectedLineBy: (lineBy) => dispatch(setSelectedLineBy(lineBy)),\n setChannelBrightness: (value) => dispatch(setChannelBrightnessAction(value)),\n setGlobalPointBrightness: (value) => dispatch(setGlobalPointBrightness(value)),\n setChannelSize: (value) => dispatch(setChannelSize(value)),\n setGlobalPointSize: (value) => dispatch(setGlobalPointSize(value)),\n setAdvancedColoringSelection: (value) => dispatch(setAdvancedColoringSelectionAction(value)),\n});\n\nfunction SelectFeatureComponent({ label, default_val, categoryOptions, onChange, column_info, datacy }) {\n let autocomplete_options = [{ value: 'None', inputValue: 'None', group: null }];\n let autocomplete_filterOptions = null;\n if (categoryOptions != null) {\n autocomplete_options = autocomplete_options.concat(\n categoryOptions.attributes.map((attribute) => {\n let group = null;\n if (column_info != null && attribute.key in column_info) {\n group = column_info[attribute.key].featureLabel;\n }\n return {\n value: attribute.key,\n inputValue: attribute.name,\n group,\n };\n }),\n );\n autocomplete_filterOptions = createFilterOptions({\n stringify: (option: any) => {\n return option.group + option.value;\n },\n });\n }\n\n return (\n {\n // @ts-ignore\n if (newValue) onChange(newValue.value);\n }}\n options={autocomplete_options.sort((a, b) => {\n if (a.value === 'None') return -1;\n if (b.value === 'None') return 1;\n\n if (a.group === b.group) {\n return -b.value.localeCompare(a.value);\n }\n return -b.group.localeCompare(a.group);\n })}\n size=\"small\"\n groupBy={(option: any) => option.group}\n getOptionLabel={(option: any) => option.inputValue}\n isOptionEqualToValue={(option: any, value) => {\n return option.value === value.value;\n }}\n // @ts-ignore\n value={default_val ? autocomplete_options.filter((option: any) => option.value === default_val.key)[0] : autocomplete_options[0]}\n renderInput={(params) => }\n />\n );\n}\n\nconst connector = connect(mapStateToProps, mapDispatchToProps, null, { forwardRef: true });\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {\n encodings: EncodingChannel[];\n};\n\nconst useStyles = makeStyles(() => ({\n root: {\n width: '100%',\n },\n heading: {\n // fontSize: theme.typography.pxToRem(15),\n flexBasis: '33.33%',\n flexShrink: 0,\n },\n secondaryHeading: {\n // fontSize: theme.typography.pxToRem(15),\n // color: theme.palette.text.secondary,\n },\n details: {\n padding: '0px',\n display: 'flex',\n flexDirection: 'column',\n },\n}));\n\nexport function StatesTabPanelFull({\n dataset,\n setVectorByShape,\n setChannelBrightness,\n setGlobalPointBrightness,\n setChannelSize,\n setGlobalPointSize,\n encodings,\n setAdvancedColoringSelection,\n}: Props) {\n if (dataset == null) {\n return null;\n }\n\n const activeMultiple = useSelector(ViewSelector.defaultSelector);\n const {\n vectorByShape,\n channelBrightness,\n channelSize,\n channelColor,\n pointColorMapping,\n pointColorScale,\n lineBrightness,\n pathLengthRange,\n globalPointSize,\n globalPointBrightness,\n } = activeMultiple.attributes;\n const active = useSelector((state) => ANormalized.get(state.colorScales.scales, pointColorScale as string));\n\n const dispatch = useDispatch();\n\n const classes = useStyles();\n\n const [expanded, setExpanded] = React.useState(false);\n\n const handleChange = (panel) => (event, isExpanded) => {\n setExpanded(isExpanded ? panel : false);\n };\n\n const categoryOptions = dataset?.categories;\n\n const points_box = (\n \n {(!encodings || encodings.includes(EncodingChannel.Shape)) && categoryOptions != null && CategoryOptionsAPI.hasCategory(categoryOptions, 'shape') ? (\n {\n let attribute = CategoryOptionsAPI.getCategory(categoryOptions, 'shape').attributes.filter((a) => a.key === newValue)[0];\n\n if (attribute === undefined) {\n attribute = null;\n }\n setVectorByShape(attribute);\n }}\n />\n ) : (\n
    \n )}\n\n {(!encodings || encodings.includes(EncodingChannel.Shape)) && vectorByShape && (\n \n {\n dispatch(PointDisplayActions.setCheckedShapes(checkboxes));\n }}\n />\n \n )}\n\n {categoryOptions != null && CategoryOptionsAPI.hasCategory(categoryOptions, 'transparency') ? (\n {\n let attribute = CategoryOptionsAPI.getCategory(categoryOptions, 'transparency').attributes.filter((a) => a.key === newValue)[0];\n\n if (attribute === undefined) {\n attribute = null;\n }\n\n const pointBrightness = attribute ? [0.25, 1] : [1];\n setGlobalPointBrightness(pointBrightness);\n setChannelBrightness(attribute);\n }}\n />\n ) : (\n
    \n )}\n\n \n\n {categoryOptions != null && CategoryOptionsAPI.hasCategory(categoryOptions, 'size') ? (\n {\n let attribute = CategoryOptionsAPI.getCategory(categoryOptions, 'size').attributes.filter((a) => a.key === newValue)[0];\n if (attribute === undefined) {\n attribute = null;\n }\n\n const pointSize = attribute ? [1, 2] : [1];\n\n setGlobalPointSize(pointSize);\n\n setChannelSize(attribute);\n }}\n />\n ) : (\n
    \n )}\n\n \n\n {categoryOptions != null && CategoryOptionsAPI.hasCategory(categoryOptions, 'color') ? (\n {\n let attribute = null;\n if (newValue && newValue !== '') {\n attribute = CategoryOptionsAPI.getCategory(categoryOptions, 'color').attributes.filter((a) => a.key === newValue)[0];\n }\n if (attribute === undefined) {\n attribute = null;\n }\n\n setAdvancedColoringSelection(new Array(10000).fill(true));\n dispatch(setChannelColor(attribute));\n\n if (attribute) {\n dispatch(PointColorScaleActions.initScaleByType(attribute.type));\n }\n }}\n />\n ) : (\n
    \n )}\n\n \n \n \n\n {channelColor != null ? (\n \n {channelColor.type === 'categorical' ? : null}\n \n ) : null}\n \n );\n\n const accordion = (\n
    \n \n } aria-controls=\"panel1bh-content\" id=\"panel1bh-header\">\n Lines\n \n \n {dataset && dataset.isSequential && (\n
    \n \n {\n // \n }\n\n \n\n {/** * */}\n \n\n
    \n\n \n \n
    \n )}\n \n \n\n \n } aria-controls=\"panel1bh-content\" id=\"panel1bh-header\">\n Points\n \n {points_box}\n \n
    \n );\n\n return
    {dataset && dataset.isSequential ? accordion : points_box}
    ;\n}\n\nexport const StatesTabPanel = connector(StatesTabPanelFull);\n","export * from './AdvancedColoringLegend';\nexport * from './AdvancedColoringPopover';\nexport * from './BrightnessSlider';\nexport * from './ColorScaleSelect';\nexport * from './LineSelection';\nexport * from './PathBrightnessSlider';\nexport * from './PathLengthFilter';\nexport * from './ShapeLegend';\nexport * from './SizeSlider';\nexport * from './StatesTabPanel';\n","export * from './ClusteringTabPanel';\nexport * from './DatasetTabPanel';\nexport * from './DetailsTabPanel';\nexport * from './EmbeddingTabPanel';\nexport * from './HoverTabPanel';\nexport * from './StatesTabPanel';\n","import { createAction, createReducer } from '@reduxjs/toolkit';\n\nexport const setActiveLine = createAction('ducks/activeLine/SET');\n\nexport const activeLine = createReducer(null, (builder) => {\n builder.addCase(setActiveLine, (_, action) => {\n return action.payload;\n });\n});\n","const SET = 'ducks/advancedColoringSelection/SET';\n\nconst advancedColoringSelection = (state = new Array(100).fill(true), action) => {\n switch (action.type) {\n case SET:\n return action.advancedColoringSelection;\n default:\n return state;\n }\n};\n\nexport default advancedColoringSelection;\n\nexport const setAdvancedColoringSelectionAction = (advancedColoringSelection) => ({\n type: SET,\n advancedColoringSelection,\n});\n","import { EntityId, AnyAction } from '@reduxjs/toolkit';\nimport { ThunkAction } from 'redux-thunk';\nimport type { RootState } from '../Store/Store';\nimport { ICluster } from '../../model/ICluster';\nimport { IVector } from '../../model/Vector';\nimport { AStorytelling } from './StoriesDuck';\n\nconst THUNK_SET_VECTORS = 'ducks/THUNK_SET_VECTORS';\nconst THUNK_SET_CLUSTERS = 'ducks/THUNK_SET_CLUSTERS';\n\nfunction deriveFromClusters(clusters: ICluster[]): number[] {\n const agg = clusters.map((cluster) => cluster.indices).flat();\n return [...new Set(agg)];\n}\n\nfunction deriveFromSamples(samples: IVector[], clusters: { [id: string]: ICluster }): number[] {\n if (!clusters) {\n return [];\n }\n\n const labels = new Set();\n\n samples.forEach((sample) => {\n sample.groupLabel.forEach((label) => {\n labels.add(label);\n });\n });\n\n const arr = Array.from(labels);\n const result = [];\n\n for (const [key, cluster] of Object.entries(clusters)) {\n if (arr.includes(cluster.label)) {\n result.push(key);\n }\n }\n\n return result;\n}\n\nexport const selectVectors = (selection: number[], shiftKey = false) => {\n return (dispatch, getState): ThunkAction => {\n const state: RootState = getState();\n\n const clusters = AStorytelling.getActive(state.stories)?.clusters.entities;\n\n let newSelection = [];\n\n if (shiftKey) {\n const selectionSet = new Set(state.currentAggregation.aggregation);\n\n selection.forEach((index) => {\n if (selectionSet.has(index)) {\n selectionSet.delete(index);\n } else {\n selectionSet.add(index);\n }\n });\n\n newSelection = [...selectionSet];\n } else {\n newSelection = [...selection];\n }\n\n return dispatch({\n type: THUNK_SET_VECTORS,\n clusterSelection: deriveFromSamples(\n newSelection.map((i) => state.dataset.vectors[i]),\n clusters,\n ),\n vectorSelection: newSelection,\n });\n };\n};\n\nexport const selectClusters = (selection: (number | string)[], shiftKey = false) => {\n return (dispatch, getState): ThunkAction => {\n const state: RootState = getState();\n\n let newSelection = [];\n\n if (shiftKey) {\n const selectionSet = new Set(state.currentAggregation.selectedClusters);\n\n selection.forEach((index) => {\n if (selectionSet.has(index)) {\n selectionSet.delete(index);\n } else {\n selectionSet.add(index);\n }\n });\n\n newSelection = [...selectionSet];\n } else {\n newSelection = [...selection];\n }\n\n return dispatch({\n type: THUNK_SET_CLUSTERS,\n clusterSelection: newSelection,\n vectorSelection: deriveFromClusters(newSelection.map((i) => AStorytelling.getActive(state.stories).clusters.entities[i])),\n });\n };\n};\n\nconst initialState = {\n aggregation: [] as number[],\n selectedClusters: [] as (number | string)[],\n source: 'sample' as 'sample' | 'cluster',\n};\n\nconst currentAggregation = (state = initialState, action): typeof initialState => {\n switch (action.type) {\n case THUNK_SET_VECTORS: {\n return {\n aggregation: action.vectorSelection,\n selectedClusters: action.clusterSelection,\n source: 'sample',\n };\n }\n case THUNK_SET_CLUSTERS: {\n return {\n aggregation: action.vectorSelection,\n selectedClusters: action.clusterSelection,\n source: 'cluster',\n };\n }\n default:\n return state;\n }\n};\n\nexport default currentAggregation;\n","import { createAction, createReducer } from '@reduxjs/toolkit';\nimport { CategoryOption } from '../WebGLView/CategoryOptions';\n\nexport const setChannelBrightnessAction = createAction('ducks/channelBrightness/SET_SELECTION');\n\nexport const channelBrightness = createReducer(null, (builder) => {\n builder.addCase(setChannelBrightnessAction, (_, action) => {\n return action.payload;\n });\n});\n","import { createAction, createReducer } from '@reduxjs/toolkit';\nimport { CategoryOption } from '../WebGLView/CategoryOptions';\n\nexport const setChannelColor = createAction('ducks/channelColor/SET');\n\nexport const channelColor = createReducer(null, (builder) => {\n builder.addCase(setChannelColor, (_, action) => {\n return action.payload;\n });\n});\n","import { createAction, createReducer } from '@reduxjs/toolkit';\nimport { CategoryOption } from '../WebGLView/CategoryOptions';\n\nexport const setChannelSize = createAction('ducks/channelSize/SET');\n\nexport const channelSize = createReducer(null, (builder) => {\n builder.addCase(setChannelSize, (_, action) => {\n return action.payload;\n });\n});\n","const SET = 'ducks/clusterMode/SET';\n\nexport enum ClusterMode {\n Univariate,\n Multivariate,\n}\n\nexport const setClusterModeAction = (clusterMode) => ({\n type: SET,\n clusterMode,\n});\n\nexport default function clusterMode(state = ClusterMode.Univariate, action): ClusterMode {\n switch (action.type) {\n case SET:\n return action.clusterMode;\n default:\n return state;\n }\n}\n","import { ANormalized, NormalizedDictionary } from '../Utility/NormalizedState';\nimport { BaseColorScale } from '../../model/Palette';\n\n/**\n * Type for embedding state slice\n */\nexport type ColorScalesType = {\n scales: NormalizedDictionary;\n};\n\n/**\n * Initial state\n */\nconst initialState: ColorScalesType = (function () {\n const state = {\n scales: ANormalized.create(),\n };\n\n ANormalized.add(state.scales, {\n palette: 'dark2',\n type: 'categorical',\n dataClasses: 8,\n });\n\n ANormalized.add(state.scales, {\n palette: 'accent',\n type: 'categorical',\n });\n\n ANormalized.add(state.scales, {\n palette: 'paired',\n type: 'categorical',\n });\n\n ANormalized.add(state.scales, {\n palette: 'YlOrRd',\n type: 'sequential',\n });\n\n ANormalized.add(state.scales, {\n palette: 'Greys',\n type: 'sequential',\n });\n\n ANormalized.add(state.scales, {\n palette: 'Viridis',\n type: 'sequential',\n });\n\n ANormalized.add(state.scales, {\n palette: 'BrBG',\n type: 'diverging',\n });\n\n ANormalized.add(state.scales, {\n palette: 'PRGn',\n type: 'diverging',\n });\n\n ANormalized.add(state.scales, {\n palette: 'SHAP',\n type: 'diverging',\n });\n\n return state;\n})();\n\nexport default function colorScales(state = initialState, action?: any): ColorScalesType {\n switch (action?.type) {\n default:\n return state;\n }\n}\n","import type { Dataset } from '../../model/Dataset';\n\nconst initialState: Dataset = null;\n\nexport default function dataset(state = initialState): Dataset {\n return state;\n}\n","import { DatasetEntry } from '../../model/DatasetEntry';\nimport { ANormalized } from '../Utility/NormalizedState';\n\nconst SET = 'ducks/databaseentries/SET';\n\nexport function setDatasetEntriesAction(pdatasetEntries: Array) {\n const dict = ANormalized.create();\n\n for (const entry of pdatasetEntries) {\n ANormalized.add(dict, entry);\n }\n\n return {\n type: SET,\n ...dict,\n };\n}\n\ntype InitialType = {\n values: {\n byId: { [id: string]: DatasetEntry };\n allIds: string[];\n };\n};\n\nconst initialState: InitialType = {\n values: {\n byId: {},\n allIds: [],\n },\n};\n\nexport class DatasetEntriesAPI {\n static getTypes(state: InitialType) {\n return [...new Set(Object.values(state.values.byId).map((value) => value.type))];\n }\n\n static getByPath(state: InitialType, path: string) {\n return Object.values(state.values.byId).find((e) => e.path === path);\n }\n}\n\nexport default function datasetEntries(state = initialState, action): InitialType {\n switch (action.type) {\n case SET:\n return { ...state, values: { byId: action.byId, allIds: action.allIds } };\n default:\n return state;\n }\n}\n","import { createAction, createReducer } from '@reduxjs/toolkit';\n\nexport const setVisibility = createAction('detailView/setvisibility');\nexport const setActive = createAction('detailView/setActive');\n\nexport const detailView = createReducer(\n {\n open: false,\n active: '',\n },\n (builder) => {\n builder\n .addCase(setVisibility, (state, action) => {\n state.open = action.payload;\n })\n .addCase(setActive, (state, action) => {\n state.active = action.payload;\n });\n },\n);\n","const SET = 'differenceThreshold/SET';\n\nexport const differenceThreshold = (state = 0.25, action) => {\n switch (action.type) {\n case SET:\n return action.differenceThreshold;\n default:\n return state;\n }\n};\n\nexport const setDifferenceThreshold = (differenceThreshold) => ({\n type: SET,\n differenceThreshold,\n});\n\nexport default differenceThreshold;\n","const SET = 'reducers/DISPLAY_MODE';\n\nexport enum DisplayMode {\n None,\n OnlyStates,\n OnlyClusters,\n StatesAndClusters,\n}\n\nexport function displayModeSupportsStates(displayMode: DisplayMode) {\n return displayMode === DisplayMode.OnlyStates || displayMode === DisplayMode.StatesAndClusters;\n}\n\nexport function displayModeSuportsClusters(displayMode: DisplayMode) {\n return displayMode === DisplayMode.OnlyClusters || displayMode === DisplayMode.StatesAndClusters;\n}\n\nexport default function displayMode(state = DisplayMode.StatesAndClusters, action): DisplayMode {\n // TODO: hide clusters by default for CHEM; frontend_utils.CHEM_PROJECT ? DisplayMode.OnlyStates: DisplayMode.StatesAndClusters\n switch (action.type) {\n case SET:\n return action.displayMode;\n default:\n return state;\n }\n}\n\nexport const setDisplayMode = (displayMode) => {\n return {\n type: SET,\n displayMode,\n };\n};\n","const SET = 'ducks/genericFingerprintAttributes/SET';\n\nexport const setGenericFingerprintAttributes = (genericFingerprintAttributes) => ({\n type: SET,\n genericFingerprintAttributes,\n});\n\nconst genericFingerprintAttributes = (state = [], action): any[] => {\n switch (action.type) {\n case SET:\n return action.genericFingerprintAttributes;\n default:\n return state;\n }\n};\n\nexport default genericFingerprintAttributes;\n","const SET = 'ducks/globalPointBrightness/SET';\n\nexport const setGlobalPointBrightness = (globalPointBrightness) => ({\n type: SET,\n globalPointBrightness,\n});\n\nconst globalPointBrightness = (state = [1], action): number[] => {\n switch (action.type) {\n case SET:\n return action.globalPointBrightness;\n default:\n return state;\n }\n};\n\nexport default globalPointBrightness;\n","const SET = 'ducks/globalPointSize/SET';\n\nexport const setGlobalPointSize = (globalPointSize) => ({\n type: SET,\n globalPointSize,\n});\n\nconst globalPointSize = (state = [1], action): number[] => {\n switch (action.type) {\n case SET:\n return action.globalPointSize;\n default:\n return state;\n }\n};\n\nexport default globalPointSize;\n","const SET = 'ducks/groupVisualizationMode/SET';\n\nexport const setGroupVisualizationMode = (groupVisualizationMode) => ({\n type: SET,\n groupVisualizationMode,\n});\n\nexport enum GroupVisualizationMode {\n None,\n StarVisualization,\n ConvexHull,\n}\n\nconst groupVisualizationMode = (state = GroupVisualizationMode.None, action) => {\n switch (action.type) {\n case SET:\n return action.groupVisualizationMode;\n default:\n return state;\n }\n};\n\nexport default groupVisualizationMode;\n","const SET = 'ducks/highlightedSequence/SET';\n\nexport const setHighlightedSequenceAction = (highlightedSequence) => ({\n type: SET,\n highlightedSequence,\n});\n\nconst highlightedSequence = (state = null, action) => {\n switch (action.type) {\n case SET:\n return action.highlightedSequence;\n default:\n return state;\n }\n};\n\nexport default highlightedSequence;\n","const SET = 'ducks/hoverSettings/SET_HOVER_WINDOW_MODE';\n\nexport const setHoverWindowMode = (windowMode) => ({\n type: SET,\n windowMode,\n});\n\nexport enum WindowMode {\n Embedded,\n Extern,\n}\n\ntype HoverSettingsType = {\n windowMode: WindowMode;\n};\n\nconst initialState: HoverSettingsType = {\n windowMode: WindowMode.Embedded,\n};\n\nconst hoverSettings = (state = initialState, action) => {\n switch (action.type) {\n case SET:\n return {\n windowMode: action.windowMode,\n };\n default:\n return state;\n }\n};\n\nexport default hoverSettings;\n","import { ICluster } from '../../model/ICluster';\nimport { IVector } from '../../model/Vector';\n\nconst SET = 'ducks/hoverState/SET';\n\nexport const setHoverState = (hoverState, updater) => ({\n type: SET,\n input: { data: hoverState, updater },\n});\n\nconst initialState: HoverStateType = {\n data: null,\n updater: '',\n};\n\nexport type HoverStateType = {\n data: IVector | ICluster;\n updater: string;\n};\n\nconst hoverState = (state = initialState, action): HoverStateType => {\n switch (action.type) {\n case SET:\n return { ...state, data: action.input?.data, updater: action.input?.updater };\n default:\n return state;\n }\n};\n\nexport default hoverState;\n","const SET = 'hoverStateOrientation/SET';\n\nexport enum HoverStateOrientation {\n SouthWest,\n NorthEast,\n}\n\nconst hoverStateOrientation = (state = HoverStateOrientation.NorthEast, action) => {\n switch (action.type) {\n case SET:\n return action.hoverStateOrientation;\n default:\n return state;\n }\n};\n\nexport const setHoverStateOrientation = (hoverStateOrientation) => ({\n type: SET,\n hoverStateOrientation,\n});\n\nexport default hoverStateOrientation;\n","const SET = 'lineBrightness/SET';\n\nconst lineBrightness = (state = 30, action) => {\n switch (action.type) {\n case SET:\n return action.lineBrightness;\n default:\n return state;\n }\n};\n\nexport const setLineBrightness = (lineBrightness) => ({\n type: SET,\n lineBrightness,\n});\n\nexport default lineBrightness;\n","const SET = 'ducks/openTab/SET';\n\nexport const setOpenTabAction = (openTab) => ({\n type: SET,\n openTab,\n});\n\nconst openTab = (state = 0, action) => {\n switch (action.type) {\n case SET:\n return action.openTab;\n default:\n return state;\n }\n};\n\nexport default openTab;\n","const SET = 'ducks/pathLengthRange/SET';\nconst SET_MAX = 'ducks/pathLengthRange/SET_MAX';\n\nexport const setPathLengthRange = (pathLengthRange) => ({\n type: SET,\n range: pathLengthRange,\n});\n\nexport const setPathLengthMaximum = (pathLengthMaximum) => ({\n type: SET_MAX,\n maximum: pathLengthMaximum,\n});\n\nconst pathLengthRange = (state = { range: [0, 100], maximum: 100 }, action) => {\n switch (action.type) {\n case SET:\n return {\n range: action.range,\n maximum: state.maximum,\n };\n case SET_MAX:\n return {\n range: state.range,\n maximum: action.maximum,\n };\n default:\n return state;\n }\n};\n\nexport default pathLengthRange;\n","import { EntityId } from '@reduxjs/toolkit';\nimport { ANormalized } from '../Utility/NormalizedState';\nimport type { RootState } from '../Store';\nimport { BaseColorScale } from '../../model/Palette';\n\nenum ActionTypes {\n PICK_SCALE = 'ducks/colorScales/PICK',\n}\n\ntype PickAction = {\n type: ActionTypes.PICK_SCALE;\n handle: string;\n};\n\nexport const PointColorScaleActions = {\n pickScale: (handle: string) => ({\n type: ActionTypes.PICK_SCALE,\n handle,\n }),\n initScaleByType: (type: string) => {\n return (dispatch, getState) => {\n const state: RootState = getState();\n\n const handle = ANormalized.entries(state.colorScales.scales).find(([, value]) => {\n return value.type === type;\n })[0];\n\n return dispatch({\n type: ActionTypes.PICK_SCALE,\n handle,\n });\n };\n },\n};\n\ntype Action = PickAction;\n\n/**\n * Type for embedding state slice\n */\nexport type ColorScalesType = EntityId;\n\n/**\n * Initial state\n */\nconst initialState: ColorScalesType = (function () {\n return null;\n})();\n\nexport default function colorScales(state = initialState, action?: Action): ColorScalesType {\n switch (action?.type) {\n case ActionTypes.PICK_SCALE: {\n return action.handle;\n }\n default:\n return state;\n }\n}\n","import { createSlice, PayloadAction } from '@reduxjs/toolkit';\n\ntype ICheckedMarks = { star: boolean; cross: boolean; circle: boolean; square: boolean };\n\ntype IPointDisplay = {\n checkedShapes: ICheckedMarks;\n};\n\nconst initialState: IPointDisplay = {\n checkedShapes: { star: true, cross: true, circle: true, square: true },\n};\n\nconst pointDisplaySlice = createSlice({\n name: 'pointDisplay',\n initialState,\n reducers: {\n setCheckedShapes(state, action: PayloadAction) {\n state.checkedShapes = { ...action.payload };\n },\n toggleShape(state, action: PayloadAction<{ key: string; value: boolean }>) {\n state.checkedShapes[action.payload.key] = action.payload.value;\n },\n },\n});\n\nexport const PointDisplayActions = pointDisplaySlice.actions;\nexport const PointDisplayReducer = pointDisplaySlice.reducer;\n","import { createAction, createReducer } from '@reduxjs/toolkit';\n\nexport interface ProjectionColumn {\n name: string;\n checked: boolean;\n normalized: boolean;\n range: string;\n featureLabel: string;\n}\n\nconst initialState = [] as ProjectionColumn[];\n\nexport const setProjectionColumnsAction = createAction('setprojectioncolumns');\n\nexport const projectionColumns = createReducer(initialState, (builder) => {\n builder.addCase(setProjectionColumnsAction, (state, action) => {\n return action.payload;\n });\n});\n\nexport default projectionColumns;\n","const SET = 'ducks/projectionOpen/SET';\n\nexport const setProjectionOpenAction = (projectionOpen) => ({\n type: SET,\n projectionOpen,\n});\n\nconst projectionOpen = (state = false, action) => {\n switch (action.type) {\n case SET:\n return action.projectionOpen;\n default:\n return state;\n }\n};\n\nexport default projectionOpen;\n","import { NormalizationMethod } from '../../model/NormalizationMethod';\nimport { DistanceMetric } from '../../model/DistanceMetric';\nimport { EncodingMethod } from '../../model/EncodingMethod';\n\nconst SET = 'ducks/projectionParams/SET';\n\nexport const setProjectionParamsAction = (projectionParams) => ({\n type: SET,\n projectionParams,\n});\n\nconst initialState = {\n perplexity: 50, // 50,\n learningRate: 50, // 50,\n nNeighbors: 15,\n iterations: 500, // 1000,\n seeded: false,\n useSelection: false,\n method: '',\n distanceMetric: DistanceMetric.EUCLIDEAN,\n normalizationMethod: NormalizationMethod.STANDARDIZE,\n encodingMethod: EncodingMethod.ONEHOT,\n};\n\nexport type ProjectionParamsType = typeof initialState;\n\nconst projectionParams = (state = initialState, action): ProjectionParamsType => {\n switch (action.type) {\n case SET:\n return action.projectionParams;\n default:\n return state;\n }\n};\n\nexport default projectionParams;\n","const SET = 'ducks/projectionWorker/SET';\n\nexport const setProjectionWorkerAction = (projectionWorker) => ({\n type: SET,\n projectionWorker,\n});\n\nconst initialState: Worker = null;\n\nexport default function projectionWorker(state = initialState, action): Worker {\n switch (action.type) {\n case SET:\n return action.projectionWorker;\n default:\n return state;\n }\n}\n","const SET = 'ducks/selectedLineBy/SET';\nconst OPT = 'ducks/selectedLineBy/OPT';\n\nexport const setSelectedLineBy = (lineBy) => ({\n type: SET,\n value: lineBy,\n});\n\nexport const setLineByOptions = (options) => ({\n type: OPT,\n options,\n});\n\nconst initialState = {\n value: '',\n options: [],\n};\n\nexport function selectedLineBy(state = initialState, action) {\n switch (action.type) {\n case SET:\n return {\n options: state.options,\n value: action.value,\n };\n case OPT:\n return {\n options: action.options,\n value: '',\n };\n default:\n return state;\n }\n}\n\nexport default selectedLineBy;\n","/* eslint-disable spaced-comment */\nimport { v4 as uuidv4 } from 'uuid';\nimport { createSlice, PayloadAction, createAsyncThunk, EntityId, createEntityAdapter, EntityState } from '@reduxjs/toolkit';\nimport { getSyncNodesAlt } from '../NumTs/NumTs';\nimport { ICluster } from '../../model/ICluster';\nimport { IEdge } from '../../model/Edge';\nimport { IBook } from '../../model/Book';\nimport { ObjectTypes } from '../../model/ObjectType';\n\nexport const bookAdapter = createEntityAdapter({\n selectId: (book) => book.id,\n});\n\nexport const edgeAdapter = createEntityAdapter({\n selectId: (edge) => edge.id,\n});\n\nexport const clusterAdapter = createEntityAdapter({\n selectId: (cluster) => cluster.id,\n sortComparer: (a, b) => {\n return b.indices.length - a.indices.length;\n },\n});\n\nfunction createGroupLabels(clusters: ICluster[]) {\n const groupLabels: { [key: number]: number[] } = {};\n\n // Create new labels from clusters\n clusters.forEach((cluster) => {\n cluster.indices.forEach((label) => {\n const labelGroup = groupLabels[label];\n if (labelGroup) {\n labelGroup.push(cluster.label);\n } else {\n groupLabels[label] = [cluster.label];\n }\n });\n });\n\n return groupLabels;\n}\n\nexport class AStorytelling {\n static createEmpty(): IStorytelling {\n return {\n stories: bookAdapter.getInitialState(),\n active: null,\n trace: null,\n activeTraceState: null,\n groupLabel: {},\n };\n }\n\n static emptyStory(metadata?): IBook {\n const story: IBook = {\n id: uuidv4(),\n clusters: clusterAdapter.getInitialState(),\n edges: edgeAdapter.getInitialState(),\n metadata: metadata ?? { method: 'custom' },\n };\n\n return story;\n }\n\n static getActive(stories: IStorytelling): IBook {\n if (stories && stories.stories) {\n return stories.stories.entities[stories.active];\n }\n\n return null;\n }\n\n static retrieveCluster(stories: IStorytelling, clusterIndex: EntityId): ICluster {\n return stories.stories.entities[stories.active].clusters.entities[clusterIndex];\n }\n\n static retreiveEdge(stories: IStorytelling, edgeIndex: EntityId): IEdge {\n return stories.stories.entities[stories.active].edges.entities[edgeIndex];\n }\n}\n\nconst initialState = AStorytelling.createEmpty();\n\nconst bookSlice = createSlice({\n name: 'stories',\n initialState,\n reducers: {\n changeClusterName(state, action: PayloadAction<{ cluster: EntityId; name: string }>) {\n const { name, cluster } = action.payload;\n const story = state.stories.entities[state.active];\n const entity = story.clusters.entities[cluster];\n\n entity.label = name;\n\n state.groupLabel = createGroupLabels(Object.values(story.clusters.entities));\n },\n selectSideBranch(state, action: PayloadAction) {\n const index = action.payload;\n\n const sidePath = { mainEdges: state.trace.mainEdges, mainPath: state.trace.mainPath };\n\n state.trace = {\n mainPath: state.trace.sidePaths[index].nodes,\n mainEdges: state.trace.sidePaths[index].edges,\n sidePaths: [...state.trace.sidePaths.slice(0, index), ...state.trace.sidePaths.slice(index + 1)],\n };\n\n state.trace.sidePaths.push({\n nodes: sidePath.mainPath,\n edges: sidePath.mainEdges,\n syncNodes: [],\n });\n\n state.trace.sidePaths.forEach((sidePath) => {\n sidePath.syncNodes = getSyncNodesAlt(state.trace.mainPath, sidePath.nodes);\n });\n\n state.activeTraceState = state.trace.mainPath[0];\n },\n addEdgeToActive(state, action: PayloadAction) {\n const active = state.stories.entities[state.active];\n edgeAdapter.addOne(active.edges, action.payload);\n },\n setActiveTraceState(state, action: PayloadAction) {\n state.activeTraceState = action.payload;\n },\n setActiveTrace(state, action: PayloadAction) {\n state.trace = action.payload;\n },\n removeEdgeFromActive(state, action: PayloadAction) {\n const active = state.stories.entities[state.active];\n edgeAdapter.removeOne(active.edges, action.payload);\n if (state.trace?.mainEdges?.includes(action.payload)) {\n state.activeTraceState = null;\n state.trace = null;\n }\n },\n changeBookName(state, action: PayloadAction<{ id: EntityId; name: string }>) {\n const { id, name } = action.payload;\n bookAdapter.updateOne(state.stories, { id, changes: { name } });\n },\n addBookAsync(state, action: PayloadAction<{ book; activate }>) {\n const { book, activate } = action.payload;\n\n bookAdapter.addOne(state.stories, book);\n\n state.trace = null;\n state.activeTraceState = null;\n\n if (activate) {\n state.active = book.id;\n }\n\n state.groupLabel = createGroupLabels(Object.values(book.clusters.entities));\n },\n addCluster(state, action: PayloadAction) {\n const active = state.stories.entities[state.active];\n\n action.payload.indices.forEach((i) => {\n if (Array.isArray(state.groupLabel[i])) {\n state.groupLabel[i].push(action.payload.label);\n } else {\n state.groupLabel[i] = [action.payload.label];\n }\n });\n\n clusterAdapter.addOne(active.clusters, action.payload);\n },\n deleteBookAsync(state, action: PayloadAction) {\n bookAdapter.removeOne(state.stories, action.payload);\n if (state.active === action.payload) {\n state.trace = null;\n state.activeTraceState = null;\n }\n\n state.groupLabel = createGroupLabels([]);\n },\n\n deleteCluster(state, action: PayloadAction) {\n const active = state.stories.entities[state.active];\n clusterAdapter.removeOne(active.clusters, action.payload.id);\n\n const entries = Object.entries(active.edges.entities).filter(([, edge]) => {\n return edge.source === action.payload.id || edge.destination === action.payload.id;\n });\n\n for (const [, edge] of entries) {\n edgeAdapter.removeOne(active.edges, edge.id);\n }\n\n if (state.trace?.mainPath?.includes(action.payload.id)) {\n state.trace = null;\n state.activeTraceState = null;\n }\n\n action.payload.indices.forEach((vectorIndex) => {\n if (Array.isArray(state.groupLabel[vectorIndex])) {\n state.groupLabel[vectorIndex].splice(state.groupLabel[vectorIndex].indexOf(action.payload.label), 1);\n }\n });\n },\n\n setActiveStoryBook(state, action: PayloadAction) {\n const storyBook = state.stories.entities[action.payload];\n\n state.trace = null;\n state.activeTraceState = null;\n\n if (storyBook && storyBook.clusters) {\n state.groupLabel = createGroupLabels(Object.values(storyBook.clusters.entities));\n state.active = storyBook.id;\n } else {\n state.groupLabel = createGroupLabels([]);\n state.active = null;\n }\n },\n\n addClusterToTrace(state, action: PayloadAction) {\n const active = state.stories.entities[state.active];\n clusterAdapter.addOne(active.clusters, action.payload);\n\n // Add edge that connects the active trace state with the current cluster\n if (state.trace.mainPath.length > 0) {\n const edge: IEdge = {\n id: uuidv4(),\n source: state.trace.mainPath[state.trace.mainPath.length - 1],\n destination: action.payload.id,\n objectType: ObjectTypes.Edge,\n };\n\n edgeAdapter.addOne(active.edges, edge);\n\n state.trace.mainEdges.push(edge.id);\n }\n\n // Add cluster to current trace\n state.trace.mainPath.push(action.payload.id);\n\n // Generate group labels\n state.groupLabel = createGroupLabels(Object.values(active.clusters.entities));\n },\n set(state, action: PayloadAction) {\n bookAdapter.addMany(state.stories, action.payload);\n const active = state.stories.entities[state.active];\n if (active) {\n state.groupLabel = createGroupLabels(Object.values(active.clusters.entities));\n }\n },\n },\n});\n\n/**\n * Type interface for stories slace of the redux store.\n */\nexport type IStorytelling = {\n stories: EntityState;\n\n active: EntityId;\n\n trace: { mainPath: EntityId[]; mainEdges: EntityId[]; sidePaths: { nodes: EntityId[]; edges: EntityId[]; syncNodes: number[] }[] };\n\n activeTraceState: EntityId;\n\n groupLabel: { [key: number]: number[] };\n};\n\nexport const StoriesActions = {\n ...bookSlice.actions,\n};\nexport const stories = bookSlice.reducer;\n","const SET_LENGTH = 'ducks/trailSettings/SET_LENGTH';\nconst SET_VISIBILITY = 'ducks/trailSettings/SET_VISIBILITY';\n\ntype TrailSettingsState = {\n length: number;\n show: boolean;\n};\n\nconst initialState: TrailSettingsState = {\n length: 50,\n show: true,\n};\n\nexport default function trailSettings(state = initialState, action) {\n switch (action.type) {\n case SET_LENGTH:\n return {\n show: state.show,\n length: action.length,\n };\n case SET_VISIBILITY:\n return {\n show: action.show,\n length: state.length,\n };\n default:\n return state;\n }\n}\n\nexport function setTrailLength(length: number) {\n return {\n type: SET_LENGTH,\n length,\n };\n}\n\nexport function setTrailVisibility(show: boolean) {\n return {\n type: SET_VISIBILITY,\n show,\n };\n}\n","const SET = 'ducks/vectorByShape/SET';\n\nexport const setVectorByShapeAction = (vectorByShape) => ({\n type: SET,\n vectorByShape,\n});\n\nconst vectorByShape = (state = null, action) => {\n switch (action.type) {\n case SET:\n return action.vectorByShape;\n default:\n return state;\n }\n};\n\nexport default vectorByShape;\n","import { v4 as uuidv4 } from 'uuid';\nimport {\n createSlice,\n combineReducers,\n createEntityAdapter,\n EntityId,\n PayloadAction,\n createReducer,\n createAction,\n Update,\n createSelector,\n} from '@reduxjs/toolkit';\nimport { channelColor } from './ChannelColorDuck';\nimport { channelSize } from './ChannelSize';\nimport { channelBrightness } from './ChannelBrightnessDuck';\nimport vectorByShape from './VectorByShapeDuck';\nimport lineBrightness from './LineBrightnessDuck';\nimport pointColorScale from './PointColorScaleDuck';\nimport pathLengthRange from './PathLengthRange';\nimport globalPointBrightness from './GlobalPointBrightnessDuck';\nimport globalPointSize from './GlobalPointSizeDuck';\nimport { ViewTransformType, viewTransform } from './ViewTransformDuck';\nimport type { RootState } from '../Store';\nimport { IProjection, ProjectionMethod, IPosition, Dataset, AProjection } from '../../model';\nimport { Mapping } from '../Utility';\nimport { CategoryOption } from '../WebGLView/CategoryOptions';\n\nexport const setWorkspaceAction = createAction('set/workspace');\n\nconst workspaceReducer = createReducer(null, (builder) => {\n builder.addCase(setWorkspaceAction, (state, action) => {\n return action.payload;\n });\n});\n\nconst pointColorMappingReducer = createReducer(null, (builder) => {\n builder.addDefaultCase((state, action) => {\n return state;\n });\n});\n\nexport const projectionAdapter = createEntityAdapter({\n // Assume IDs are stored in a field other than `book.id`\n selectId: (projection) => projection.hash,\n});\n\nexport function defaultAttributes(dataset?: Dataset) {\n const workspace = dataset\n ? AProjection.createProjection(\n dataset.vectors.map((vector) => ({ x: vector.x, y: vector.y })),\n 'Random Initialisation',\n { method: ProjectionMethod.RANDOM },\n )\n : null;\n\n return {\n channelBrightness: null,\n channelColor: null,\n channelSize: null,\n vectorByShape: null,\n viewTransform: {\n zoom: 0,\n width: 0,\n height: 0,\n centerX: 0,\n centerY: 0,\n },\n lineBrightness: 30,\n pointColorScale: null,\n pointColorMapping: null,\n pathLengthRange: { range: [0, 100], maximum: 100 },\n globalPointBrightness: [1],\n globalPointSize: [1],\n workspace,\n };\n}\n\nexport const attributesSlice = createSlice({\n name: 'attributes',\n initialState: defaultAttributes(),\n reducers: {},\n});\n\nexport type SingleMultipleAttributes = {\n channelColor: CategoryOption;\n channelBrightness: CategoryOption;\n channelSize: CategoryOption;\n vectorByShape: CategoryOption;\n viewTransform: ViewTransformType;\n lineBrightness: number;\n pointColorScale: number | string;\n pointColorMapping: Mapping;\n pathLengthRange: { range: number[]; maximum: number };\n globalPointSize: number[];\n globalPointBrightness: number[];\n workspace: number | string | IProjection;\n};\n\nexport type SingleMultiple = {\n id: number | string;\n attributes: SingleMultipleAttributes;\n};\n\nexport const multipleAdapter = createEntityAdapter({\n selectId: (multiple) => multiple.id,\n});\n\nconst initialState = {\n multiples: multipleAdapter.getInitialState(),\n active: null as number | string,\n projections: projectionAdapter.getInitialState(),\n};\n\nexport function isEntityId(value: string | number | IProjection): value is EntityId {\n return typeof value === 'string' || typeof value === 'number';\n}\n\nexport const singleTestReducer = combineReducers({\n channelColor,\n channelSize,\n channelBrightness,\n vectorByShape,\n viewTransform,\n lineBrightness,\n pointColorMapping: pointColorMappingReducer,\n pointColorScale,\n pathLengthRange,\n globalPointSize,\n globalPointBrightness,\n workspace: workspaceReducer,\n});\n\nexport const multiplesSlice = createSlice({\n name: 'multiples',\n initialState,\n reducers: {\n addView(state, action: PayloadAction) {\n multipleAdapter.addOne(state.multiples, {\n id: uuidv4(),\n attributes: defaultAttributes(action.payload),\n });\n },\n activateView(state, action: PayloadAction) {\n state.active = action.payload;\n },\n deleteView(state, action: PayloadAction) {\n multipleAdapter.removeOne(state.multiples, action.payload);\n if (action.payload === state.active) {\n state.active = state.multiples.ids[0];\n }\n },\n\n loadById(state, action: PayloadAction) {\n const active = state.multiples.entities[state.active];\n active.attributes.workspace = action.payload;\n },\n add(state, action: PayloadAction) {\n projectionAdapter.addOne(state.projections, action.payload);\n },\n copyFromWorkspace(state) {\n const active = state.multiples.entities[state.active];\n\n const deriveName = (metadata) => {\n if (metadata?.method === ProjectionMethod.RANDOM) {\n return 'Random Initialisation';\n }\n const time = new Date().toLocaleTimeString('en-US', { hour12: false, hour: 'numeric', minute: 'numeric' });\n\n return `${metadata?.method} at ${time}`;\n };\n\n if (typeof active.attributes.workspace === 'string' || typeof active.attributes.workspace === 'number') {\n const workspace = state.projections.entities[active.attributes.workspace];\n const hash = uuidv4();\n projectionAdapter.addOne(state.projections, { ...workspace, hash });\n active.attributes.workspace = hash;\n } else {\n const { workspace } = active.attributes;\n projectionAdapter.addOne(state.projections, { ...workspace, name: deriveName(workspace.metadata) });\n active.attributes.workspace = workspace.hash;\n }\n },\n updateActive(state, action: PayloadAction<{ positions: IPosition[]; metadata: any }>) {\n const active = state.multiples.entities[state.active];\n\n const bounds = AProjection.calculateBounds(undefined, undefined, undefined, action.payload.positions);\n\n if (typeof active.attributes.workspace === 'string' || typeof active.attributes.workspace === 'number') {\n active.attributes.workspace = {\n hash: uuidv4(),\n positions: action.payload.positions,\n metadata: action.payload.metadata,\n name: null,\n xChannel: undefined,\n yChannel: undefined,\n bounds,\n };\n } else {\n active.attributes.workspace.positions = action.payload.positions;\n active.attributes.workspace.metadata = action.payload.metadata;\n active.attributes.workspace.xChannel = undefined;\n active.attributes.workspace.yChannel = undefined;\n active.attributes.workspace.bounds = bounds;\n }\n },\n remove(state, action: PayloadAction) {\n const active = state.multiples.entities[state.active];\n\n if (isEntityId(active.attributes.workspace)) {\n active.attributes.workspace = { ...state.projections.entities[active.attributes.workspace], hash: uuidv4() };\n }\n projectionAdapter.removeOne(state.projections, action.payload);\n },\n save(state, action: PayloadAction>) {\n projectionAdapter.updateOne(state.projections, action.payload);\n },\n setPointColorMapping(state, action: PayloadAction<{ multipleId: EntityId; value: Mapping }>) {\n const { multipleId, value } = action.payload;\n const multiple = state.multiples.entities[multipleId];\n multiple.attributes.pointColorMapping = value;\n },\n changeDivergingRange(state, action: PayloadAction<[number, number, number] | [number, number]>) {\n const active = state.multiples.entities[state.active].attributes;\n if (active.pointColorMapping.type === 'diverging' || active.pointColorMapping.type === 'sequential') {\n active.pointColorMapping.range = action.payload;\n }\n },\n selectChannel(state, action: PayloadAction<{ dataset: Dataset; channel: 'x' | 'y'; value: string }>) {\n const active = state.multiples.entities[state.active].attributes;\n\n if (isEntityId(active.workspace)) {\n // Create new temporary projection\n\n active.workspace = {\n hash: uuidv4(),\n positions: null,\n metadata: { method: ProjectionMethod.CUSTOM },\n name: null,\n };\n }\n\n if (action.payload.channel === 'x') {\n active.workspace.xChannel = action.payload.value;\n active.workspace.bounds = AProjection.calculateBounds(action.payload.dataset, action.payload.value, undefined, undefined);\n } else {\n active.workspace.yChannel = action.payload.value;\n active.workspace.bounds = AProjection.calculateBounds(action.payload.dataset, undefined, action.payload.value, undefined);\n }\n\n if (!active.workspace.xChannel && !active.workspace.yChannel) {\n active.workspace.positions = action.payload.dataset.vectors.map((vector) => ({ x: vector.x, y: vector.y }));\n active.workspace.bounds = AProjection.calculateBounds(action.payload.dataset, undefined, undefined, active.workspace.positions);\n }\n },\n },\n extraReducers: (builder) => {\n builder.addDefaultCase((state, action) => {\n if (state.active !== null) {\n const active = state.multiples.entities[state.active];\n active.attributes = singleTestReducer(active.attributes, action);\n } else if (state.multiples.ids.length > 0) {\n const active = state.multiples.entities[state.multiples.ids[0]];\n active.attributes = singleTestReducer(active.attributes, action);\n }\n });\n },\n});\n\nconst defaultSelector = (state: RootState) => state.multiples.multiples.entities[state.multiples.active];\n\nexport const ViewActions = { ...multiplesSlice.actions };\n\nexport const ViewSelector = {\n selectAll: createSelector(\n (state: RootState) => state.multiples,\n (multiples) => multiples,\n ),\n defaultSelector,\n getWorkspaceById: createSelector(\n [\n // Usual first input - extract value from `state`\n (state: RootState) => state.multiples,\n // Take the second arg, `category`, and forward to the output selector\n (state, multipleId: EntityId) => multipleId,\n ],\n // Output selector gets (`items, category)` as args\n (multiples, multipleId) => {\n const active = multiples.multiples.entities[multipleId];\n const { workspace } = active.attributes;\n\n return typeof workspace === 'string' || typeof workspace === 'number' ? multiples.projections.entities[workspace] : workspace;\n },\n ),\n getWorkspace: createSelector(\n (state: RootState) => {\n const active = state.multiples.multiples.entities[state.multiples.active];\n if (active === undefined) {\n return null;\n }\n return typeof active.attributes.workspace === 'string' || typeof active.attributes.workspace === 'number'\n ? state.multiples.projections.entities[active.attributes.workspace]\n : active.attributes.workspace;\n },\n (items) => {\n return items;\n },\n ),\n workspaceIsTemporal: createSelector(\n (state: RootState) => typeof state.multiples.multiples.entities[state.multiples.active]?.attributes.workspace,\n (type) => {\n return type !== 'string' && type !== 'number';\n },\n ),\n};\n","const SET = 'ducks/viewTransform/SET';\nconst INVALIDATE = 'ducks/viewTransform/INVALIDATE';\n\nexport const setViewTransform = (camera, width, height) => ({\n type: SET,\n camera,\n width,\n height,\n});\n\nexport const invalidateTransform = () => ({\n type: INVALIDATE,\n});\n\n/**\n * Type specifying the camera transformation that all components should use.\n * From this an orthographic projection can be constructed.\n */\nexport type ViewTransformType = {\n // Width (px) of the viewport -> width for orthographic projections\n width: number;\n\n // Height (px) of the viewport -> height for orthographic projections\n height: number;\n\n // Center x coordinate of the camera\n centerX: number;\n\n // Center y coordinate of the camera\n centerY: number;\n\n // Zoom level of the camera\n zoom: number;\n};\n\nconst initialState: ViewTransformType = {\n zoom: 0,\n width: 0,\n height: 0,\n centerX: 0,\n centerY: 0,\n};\n\nexport const viewTransform = (state = initialState, action): ViewTransformType => {\n switch (action.type) {\n case SET:\n return {\n centerX: action.camera.position.x,\n centerY: action.camera.position.y,\n width: action.width,\n height: action.height,\n zoom: action.camera.zoom,\n };\n case INVALIDATE:\n return { ...state };\n default:\n return state;\n }\n};\n","export * from './ActiveLineDuck';\nexport * from './AdvancedColoringSelectionDuck';\nexport * from './AggregationDuck';\nexport * from './ChannelBrightnessDuck';\nexport * from './ChannelColorDuck';\nexport * from './ChannelSize';\nexport * from './ClusterModeDuck';\nexport * from './DifferenceThresholdDuck';\nexport * from './DisplayModeDuck';\nexport * from './GenericFingerprintAttributesDuck';\nexport * from './GlobalPointBrightnessDuck';\nexport * from './GlobalPointSizeDuck';\nexport * from './GroupVisualizationMode';\nexport * from './HighlightedSequenceDuck';\nexport * from './HoverSettingsDuck';\nexport * from './HoverStateDuck';\nexport * from './HoverStateOrientationDuck';\nexport * from './LineBrightnessDuck';\nexport * from './OpenTabDuck';\nexport * from './PathLengthRange';\nexport * from './PointColorScaleDuck';\nexport * from './ProjectionColumnsDuck';\nexport * from './ProjectionOpenDuck';\nexport * from './ProjectionParamsDuck';\nexport * from './ProjectionWorkerDuck';\nexport * from './SelectedLineByDuck';\nexport * from './TrailSettingsDuck';\nexport * from './VectorByShapeDuck';\nexport * from './ViewTransformDuck';\nexport * from './DetailViewDuck';\nexport * from './DatasetEntriesDuck';\nexport * from './StoriesDuck';\n","/**\n * Calculates the eclidean distance between 2 vectors\n *\n * @param x1 The x component of the first vector\n * @param y1 The y component of the first vector\n * @param x2 The x component of the second vector\n * @param y2 The y component of the second vector\n */\nexport function euclideanDistance(x1: number, y1: number, x2: number, y2: number) {\n return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));\n}\n\nexport function euclideanDistanceVec(v1: VectorType, v2: VectorType) {\n return euclideanDistance(v1.x, v1.y, v2.x, v2.y);\n}\n\nexport function getSyncNodesAlt(nodes1: any[], nodes2: any[]) {\n const convert = (nodes) => {\n const edges = [];\n nodes.forEach((node, index) => {\n if (index !== nodes.length - 1) {\n edges.push({ source: node, destination: nodes[index + 1] });\n }\n });\n\n return {\n nodes,\n edges,\n };\n };\n\n const main = convert(nodes1);\n const side = convert(nodes2);\n\n const splits = [];\n\n main.nodes.forEach((cluster, index) => {\n // Sync node needs to be in both\n if (!side.nodes.includes(cluster)) {\n return;\n }\n\n let outSplit = false;\n let inSplit = false;\n\n const mainIndex = index;\n const sideIndex = side.nodes.indexOf(cluster);\n\n const belowMainEdge = main.edges[mainIndex];\n const belowSideEdge = side.edges[sideIndex];\n\n const aboveMainEdge = main.edges[mainIndex - 1];\n const aboveSideEdge = side.edges[sideIndex - 1];\n\n // out direction differs\n if (belowMainEdge && belowSideEdge) {\n if (belowMainEdge.source !== belowSideEdge.source || belowMainEdge.destination !== belowSideEdge.destination) {\n outSplit = true;\n }\n }\n\n // in direction differs\n if (aboveMainEdge && aboveSideEdge) {\n if (aboveMainEdge.source !== aboveSideEdge.source || aboveMainEdge.destination !== aboveSideEdge.destination) {\n inSplit = true;\n }\n }\n\n if ((belowMainEdge && !belowSideEdge) || (!belowMainEdge && belowSideEdge)) {\n outSplit = true;\n }\n\n if ((!aboveMainEdge && aboveSideEdge) || (aboveMainEdge && !aboveSideEdge)) {\n inSplit = true;\n }\n\n if (outSplit || inSplit) {\n splits.push({ index, in: inSplit, out: outSplit });\n }\n });\n\n return splits;\n}\n\nexport type VectorType = {\n x: number;\n y: number;\n};\n\n/**\n * Math class for vector calculations.\n */\nexport class VectBase implements VectorType {\n x: number;\n\n y: number;\n\n constructor(x: number, y: number) {\n this.x = x;\n this.y = y;\n }\n\n lerp(v: VectorType, alpha: number) {\n this.x += (v.x - this.x) * alpha;\n this.y += (v.y - this.y) * alpha;\n\n return this;\n }\n\n angle() {\n return Math.atan2(-this.y, -this.x) + Math.PI;\n }\n\n multiplyScalar(scalar) {\n this.x *= scalar;\n this.y *= scalar;\n\n return this;\n }\n\n length() {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n }\n\n divideScalar(scalar) {\n return this.multiplyScalar(1 / scalar);\n }\n\n normalize() {\n return this.divideScalar(this.length() || 1);\n }\n\n static subtract(a, b) {\n return new VectBase(a.x - b.x, a.y - b.y);\n }\n\n static add(a, b) {\n return new VectBase(a.x + b.x, a.y + b.y);\n }\n}\n\nexport function std(array) {\n const n = array.length;\n const mean = array.reduce((a, b) => a + b) / n;\n return Math.sqrt(array.map((x) => (x - mean) ** 2).reduce((a, b) => a + b) / n);\n}\n\nexport function mean(array) {\n const n = array.length;\n const mean = array.reduce((a, b) => a + b) / n;\n return mean;\n}\n","import * as React from 'react';\n\n/**\n * Base component for layers behind and in front of the webgl view.\n */\nexport function PSELayer({ children }) {\n return (\n \n {children}\n
    \n );\n}\n","/* eslint-disable react-hooks/exhaustive-deps */\n/* eslint-disable react-hooks/rules-of-hooks */\nimport * as React from 'react';\nimport { Box, Card, Typography } from '@mui/material';\nimport { connect, ConnectedProps } from 'react-redux';\nimport * as ReactDOM from 'react-dom';\nimport { GenericLegend } from '../legends/Generic';\nimport { setHoverWindowMode, WindowMode } from '../Ducks/HoverSettingsDuck';\n\nimport { MyWindowPortal } from './WindowPortal';\nimport { isVector } from '../../model/Vector';\nimport type { RootState } from '../Store/Store';\n\nfunction HoverItemPortal(props) {\n return ReactDOM.createPortal(props.children, document.getElementById('HoverItemDiv'));\n}\n\nconst mapStateToProps = (state: RootState) => ({\n currentAggregation: state.currentAggregation,\n hoverState: state.hoverState,\n dataset: state.dataset,\n hoverSettings: state.hoverSettings,\n});\n\nconst mapDispatchToProps = (dispatch) => ({\n setHoverWindowMode: (value) => dispatch(setHoverWindowMode(value)),\n});\n\nconst connector = connect(mapStateToProps, mapDispatchToProps);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux;\n\nconst SelectionClustersFull = function ({ dataset, currentAggregation, hoverState, hoverSettings, setHoverWindowMode }: Props) {\n if (!dataset) {\n return null;\n }\n\n const [vectors, setVectors] = React.useState(currentAggregation.aggregation.map((i) => dataset.vectors[i]));\n\n React.useEffect(() => {\n setVectors(currentAggregation.aggregation.map((i) => dataset.vectors[i]));\n }, [currentAggregation]);\n\n const genericAggregateLegend =\n currentAggregation.aggregation && currentAggregation.aggregation.length > 0 ? (\n \n ) : (\n \n Select Points in the Embedding Space to show a Summary Visualization.\n \n );\n\n return (\n \n {hoverState && hoverState.data && isVector(hoverState.data) && (\n \n \n \n \n \n )}\n\n {hoverSettings.windowMode === WindowMode.Extern ? (\n {\n setHoverWindowMode(WindowMode.Embedded);\n }}\n >\n
    \n {genericAggregateLegend}\n
    \n \n ) : (\n \n {genericAggregateLegend}\n
    \n )}\n
    \n );\n};\n\nexport const SelectionClusters = connector(SelectionClustersFull);\n","/* eslint-disable react-hooks/exhaustive-deps */\n/* eslint-disable react-hooks/rules-of-hooks */\nimport { connect } from 'react-redux';\nimport * as React from 'react';\nimport { Typography, IconButton, Card, CardHeader } from '@mui/material';\nimport CloseIcon from '@mui/icons-material/Close';\nimport SkipPreviousIcon from '@mui/icons-material/SkipPrevious';\nimport PlayArrowIcon from '@mui/icons-material/PlayArrow';\nimport SkipNextIcon from '@mui/icons-material/SkipNext';\nimport StopIcon from '@mui/icons-material/Stop';\nimport { ResizeObserver } from 'resize-observer';\nimport { setActiveLine } from '../Ducks/ActiveLineDuck';\nimport { GenericLegend } from '../legends/Generic';\nimport { GenericChanges } from '../legends/GenericChanges';\nimport { DatasetType } from '../../model/DatasetType';\nimport { setHighlightedSequenceAction } from '../Ducks/HighlightedSequenceDuck';\nimport { Dataset } from '../../model/Dataset';\nimport { selectVectors } from '../Ducks/AggregationDuck';\n\ntype StateSequenceDrawerProps = {\n activeLine: string;\n setHighlightedSequence: any;\n dataset: Dataset;\n setActiveLine: any;\n setCurrentAggregation: (select: number[]) => void;\n};\n\nconst mainColor = '#007dad';\n\n/**\n * The StateSequenceDrawer is the UI element that is shown when one line is selected by the line selection tool. In this case\n * the user wants to navigate the sequence of one line only.\n */\nfunction StateSequenceDrawer({ activeLine, setHighlightedSequence, dataset, setActiveLine, setCurrentAggregation }: StateSequenceDrawerProps) {\n if (activeLine == null) {\n return
    ;\n }\n\n const { vectors } = dataset.segments.find((seg) => seg.lineKey === activeLine);\n\n const stateSize = 12;\n const midX = 32;\n const grayColor = '#808080';\n\n const [selected, setSelected] = React.useState(0);\n const [playing, setPlaying] = React.useState(null);\n\n const itemRef = React.useRef();\n const [dirtyFlag, setDirtyFlag] = React.useState(0);\n const [input, setInput] = React.useState(null);\n\n React.useEffect(() => {\n setSelected(0);\n\n setHighlightedSequence({\n previous: null,\n current: vectors[0],\n next: vectors[1],\n });\n setCurrentAggregation([vectors[0].__meta__.meshIndex]);\n setPlaying(null);\n }, [activeLine]);\n\n React.useEffect(() => {\n const observer = new ResizeObserver(() => {\n setDirtyFlag(Math.random());\n });\n observer.observe(itemRef.current);\n\n return () => {\n if (observer && itemRef.current) {\n observer.unobserve(itemRef.current);\n }\n };\n }, []);\n\n React.useEffect(() => {\n const { current } = itemRef;\n // @ts-ignore\n if (current && current.children.length > 0) {\n const state: { y: number; height: number; textY: number }[] = [];\n let elementHeight = 0;\n let firstDiv = 0;\n\n // @ts-ignore\n for (let i = 1; i < current.children.length; i++) {\n // @ts-ignore\n const child = current.children[i] as HTMLElement;\n elementHeight = child.offsetHeight;\n if (i === 1) {\n // @ts-ignore\n firstDiv = child.childNodes.item(0).offsetHeight + child.childNodes.item(1).offsetHeight / 2 + 16;\n }\n state.push({\n // @ts-ignore\n y: child.firstChild.offsetTop - itemRef.current.offsetTop + child.firstChild.offsetHeight / 2,\n height: child.offsetHeight,\n // @ts-ignore\n textY: child.firstChild.offsetTop,\n });\n }\n setInput({\n position: state,\n elementHeight,\n firstDiv,\n });\n }\n }, [dirtyFlag]);\n\n return (\n \n \n {\n setHighlightedSequence(null);\n setActiveLine(null);\n }}\n >\n \n \n }\n title={`Line ${activeLine}`}\n />\n \n {\n if (selected > 0) {\n setHighlightedSequence({\n previous: vectors[selected - 2],\n current: vectors[selected - 1],\n next: vectors[selected],\n });\n\n setCurrentAggregation([vectors[selected - 1].__meta__.meshIndex]);\n let myElement = document.getElementById(`ssdChild${selected - 2}`);\n if (myElement) {\n const topPos = myElement.offsetTop;\n document.getElementById('ssdParent').scrollTop = topPos;\n } else {\n myElement = document.getElementById(`ssdChild${selected - 1}`);\n const topPos = myElement.offsetTop;\n document.getElementById('ssdParent').scrollTop = topPos;\n }\n\n setSelected(selected - 1);\n } else {\n setHighlightedSequence({\n previous: undefined,\n current: vectors[vectors.length - 2],\n next: vectors[vectors.length - 1],\n });\n setCurrentAggregation([vectors[vectors.length - 2].__meta__.meshIndex]);\n const myElement = document.getElementById(`ssdChild${vectors.length - 3}`);\n const topPos = myElement.offsetTop;\n document.getElementById('ssdParent').scrollTop = topPos;\n\n setSelected(vectors.length - 1);\n }\n }}\n >\n \n \n {\n if (playing) {\n clearInterval(playing);\n setPlaying(null);\n } else {\n const interval = setInterval(() => {\n document.getElementById('nextBtn').click();\n }, 300);\n setPlaying(interval);\n }\n }}\n >\n {playing ? : }\n \n {\n if (selected + 1 < vectors.length) {\n setHighlightedSequence({\n previous: vectors[selected],\n current: vectors[selected + 1],\n next: vectors[selected + 2],\n });\n setCurrentAggregation([vectors[selected + 1].__meta__.meshIndex]);\n const myElement = document.getElementById(`ssdChild${selected}`);\n const topPos = myElement.offsetTop;\n document.getElementById('ssdParent').scrollTop = topPos;\n\n setSelected(selected + 1);\n } else {\n setHighlightedSequence({\n previous: vectors[0 - 1],\n current: vectors[0],\n next: vectors[0 + 1],\n });\n setCurrentAggregation([vectors[0].__meta__.meshIndex]);\n const myElement = document.getElementById(`ssdChild${0}`);\n const topPos = myElement.offsetTop;\n document.getElementById('ssdParent').scrollTop = topPos;\n\n setSelected(0);\n }\n }}\n >\n \n \n
    \n\n
    \n \n 0 ? input.position[input.position.length - 1].y + 100 : 200,\n width: '64px',\n }}\n >\n {\n // Generates the lines between the diamon\n input &&\n input.position.map((p, i) => {\n if (i !== input.position.length - 1) {\n const p1 = p;\n const p2 = input.position[i + 1];\n\n return ;\n }\n\n return null;\n })\n }\n\n {input &&\n input.position.map((p, index) => {\n return (\n \n {selected === index && }\n {}}\n />\n \n );\n })}\n \n\n
    \n \n State\n \n\n {vectors.map((vector, index) => {\n return (\n {\n setHighlightedSequence({\n previous: vectors[index - 1],\n current: vector,\n next: vectors[index + 1],\n });\n setCurrentAggregation([vector.__meta__.meshIndex]);\n setSelected(index);\n }}\n >\n {`Point ${index}`}\n\n \n \n
    \n
    \n );\n })}\n
    \n\n \n \n Change\n \n {input && (\n
    \n )}\n {input &&\n vectors.slice(0, vectors.length - 1).map((vector, index) => {\n return (\n \n \n \n
    \n
    \n );\n })}\n
    \n
    \n
    \n \n \n );\n}\n\nconst mapStateToProps = (state) => ({\n activeLine: state.activeLine,\n currentTool: state.currentTool,\n dataset: state.dataset,\n stories: state.stories,\n});\n\nconst mapDispatchToProps = (dispatch) => ({\n setHighlightedSequence: (highlightedSequence) => dispatch(setHighlightedSequenceAction(highlightedSequence)),\n setActiveLine: (activeLine) => dispatch(setActiveLine(activeLine)),\n // setCurrentAggregation: (currentAggregation, clusters) => dispatch(setAggregationAction(currentAggregation, clusters))\n setCurrentAggregation: (currentAggregation: number[]) => dispatch(selectVectors(currentAggregation)),\n});\n\nexport const StateSequenceDrawerRedux = connect(mapStateToProps, mapDispatchToProps)(StateSequenceDrawer);\n","/* eslint-disable react-hooks/exhaustive-deps */\n/* eslint-disable react/jsx-key */\nimport { EntityId } from '@reduxjs/toolkit';\nimport * as React from 'react';\nimport { Card, Typography, Tooltip, IconButton, CardHeader } from '@mui/material';\nimport { connect, ConnectedProps } from 'react-redux';\nimport CloseIcon from '@mui/icons-material/Close';\nimport SkipPreviousIcon from '@mui/icons-material/SkipPrevious';\nimport PlayArrowIcon from '@mui/icons-material/PlayArrow';\nimport SkipNextIcon from '@mui/icons-material/SkipNext';\nimport StopIcon from '@mui/icons-material/Stop';\nimport { ResizeObserver } from 'resize-observer';\nimport type { RootState } from '../Store/Store';\nimport { GenericChanges } from '../legends/GenericChanges';\nimport { Dataset } from '../../model/Dataset';\nimport { DatasetType } from '../../model/DatasetType';\nimport { GenericLegend } from '../legends/Generic';\nimport { ACluster } from '../../model/Cluster';\nimport { selectClusters } from '../Ducks/AggregationDuck';\nimport { StoriesActions, IStorytelling, AStorytelling } from '../Ducks/StoriesDuck';\nimport { ICluster } from '../../model/ICluster';\n\nconst mainColor = '#007dad';\n\nconst mapStateToProps = (state: RootState) => ({\n dataset: state.dataset,\n stories: state.stories,\n currentAggregation: state.currentAggregation,\n genericFingerprintAttributes: state.genericFingerprintAttributes,\n});\n\nconst mapDispatch = (dispatch) => ({\n addClusterToTrace: (cluster: ICluster) => dispatch(StoriesActions.addClusterToTrace(cluster)),\n setActiveTraceState: (cluster: EntityId) => dispatch(StoriesActions.setActiveTraceState(cluster)),\n selectSideBranch: (index: number) => dispatch(StoriesActions.selectSideBranch(index)),\n setActiveTrace: (trace: number) => dispatch(StoriesActions.setActiveTrace(trace)),\n setSelectedCluster: (clusters: EntityId[], shift) => dispatch(selectClusters(clusters, shift)),\n});\n\nconst connector = connect(mapStateToProps, mapDispatch);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {\n dataset: Dataset;\n};\n\nfunction Plus({ onClick, x, y, r }) {\n return (\n {\n onClick();\n }}\n >\n \n \n \n \n );\n}\n\nfunction SidePath({ dataset, syncPart, width, stroke, fill, x, y, height }) {\n return (\n \n {syncPart.map((node) => {\n return ;\n })}\n \n }\n >\n \n \n );\n}\n\nclass ProvenanceGraph extends React.PureComponent {\n constructor(props) {\n super(props);\n\n this.state = {\n pageOffset: 0,\n };\n }\n\n render() {\n const midX = 80;\n const rectWidth = 16;\n const margin = 12;\n\n const grayColor = '#808080';\n\n const fillColors = ['#DCDCDC', '#DCDCDC'];\n const strokeColors = [grayColor, grayColor];\n\n const stateSize = 12;\n\n if (!this.props.input) return null;\n\n const { position, stories, elementHeight }: { position: any; stories: IStorytelling; elementHeight: any } = this.props.input;\n\n const { currentAggregation } = this.props;\n const { selectSideBranch } = this.props;\n const { addClusterToTrace } = this.props;\n const { dataset } = this.props;\n const { pageOffset } = this.state;\n\n const numSidePaths = Math.min(2, stories.trace.sidePaths.length);\n\n return (\n
    \n
    \n 0 ? position[position.length - 1].y + 100 : 200,\n minWidth: '100px',\n }}\n >\n {(function () {\n const components = [];\n\n for (let si = 0; si < numSidePaths; si++) {\n const sidePathIndex = stories.trace.sidePaths.indexOf(stories.trace.sidePaths[(si + pageOffset) % stories.trace.sidePaths.length]);\n\n const sidePath = stories.trace.sidePaths[sidePathIndex];\n\n components.push(\n \n {\n // Rectangles between outgoing and ingoing sync nodes\n sidePath.syncNodes.map((node, i) => {\n const x = midX - rectWidth * (si + 1) - margin * (si + 1) + rectWidth / 2;\n\n // @ts-ignore\n if (i === sidePath.syncNodes.length - 1 && node.out) {\n // Case where its the last syncnode and its outgoing\n // @ts-ignore\n const pos1 = position[node.index];\n\n return (\n {\n selectSideBranch(sidePathIndex);\n }}\n >\n \n\n \n\n \n\n \n \n );\n }\n // @ts-ignore\n if (node.out && i !== sidePath.syncNodes.length - 1 && sidePath.syncNodes[i + 1].in) {\n // @ts-ignore\n const i1 = sidePath.syncNodes[i].index;\n // @ts-ignore\n const i2 = sidePath.syncNodes[i + 1].index;\n\n const sync1 = position[i1];\n const sync2 = position[i2];\n\n const syncLen = sidePath.nodes.indexOf(stories.trace.mainPath[i2]) - sidePath.nodes.indexOf(stories.trace.mainPath[i1]) - 1;\n const syncPart = sidePath.nodes.slice(\n sidePath.nodes.indexOf(stories.trace.mainPath[i1]) + 1,\n sidePath.nodes.indexOf(stories.trace.mainPath[i2]),\n );\n\n const lineY1 = sync1.y;\n const lineY2 = sync2.y;\n\n return (\n {\n selectSideBranch(sidePathIndex);\n }}\n >\n \n \n\n \n\n \n {syncLen}\n \n \n );\n }\n return ;\n })\n }\n ,\n );\n }\n\n return {components};\n })()}\n\n {\n // Generates the lines between the diamon\n position.map((p, i) => {\n if (i !== position.length - 1) {\n const p1 = p;\n const p2 = position[i + 1];\n\n return ;\n }\n const p1 = p;\n const p2 = { x: p1.x, y: p1.y + 40 };\n\n return (\n \n \n {\n const cluster = ACluster.fromSamples(this.props.dataset, currentAggregation.aggregation);\n\n addClusterToTrace(cluster);\n }}\n />\n \n );\n })\n }\n\n {\n // Generates the plus icon that is shown when its empty\n position.length === 0 && (\n \n \n {\n if (currentAggregation.aggregation.length > 0) {\n const cluster = ACluster.fromSamples(this.props.dataset, currentAggregation.aggregation);\n\n addClusterToTrace(cluster);\n }\n }}\n />\n\n \n \n Select points and\n \n \n start a story\n \n \n \n )\n }\n\n {\n // Generates the diamond shapes\n position.map((p, index) => {\n const cluster = stories.trace.mainPath[index];\n\n return (\n \n {stories.activeTraceState === cluster && }\n this.props.onClusterClicked(cluster)}\n />\n \n );\n })\n }\n \n
    \n
    \n );\n }\n}\n\ntype InputType = {\n stories: IStorytelling;\n position: { y: number; height: number; textY: number; mainEdge: string }[];\n elementHeight: number;\n firstDiv: number;\n};\n\nexport const Storytelling = connector(function ({\n dataset,\n stories,\n currentAggregation,\n addClusterToTrace,\n setActiveTraceState,\n setActiveTrace,\n selectSideBranch,\n setSelectedCluster,\n}: Props) {\n if (stories.trace === null || stories.active === null) {\n return null;\n }\n\n const itemRef = React.useRef();\n\n const [playing, setPlaying] = React.useState(null);\n const [dirtyFlag, setDirtyFlag] = React.useState(0);\n\n const [input, setInput] = React.useState(null);\n\n React.useEffect(() => {\n const observer = new ResizeObserver(() => {\n setDirtyFlag(Math.random());\n });\n observer.observe(itemRef.current);\n\n return () => {\n if (playing) {\n clearInterval(playing);\n }\n if (observer && itemRef.current) {\n observer.unobserve(itemRef.current);\n }\n };\n }, []);\n\n React.useEffect(() => {\n const { current } = itemRef;\n if (current) {\n const state: { y: number; height: number; textY: number; mainEdge: any }[] = [];\n let elementHeight = 0;\n let firstDiv = 0;\n\n for (let i = 1; i < current.children.length; i++) {\n const child = current.children[i] as HTMLElement;\n elementHeight = child.offsetHeight;\n if (i === 1) {\n // @ts-ignore\n firstDiv = child.childNodes.item(0).offsetHeight + child.childNodes.item(1).offsetHeight / 2 + 16;\n }\n state.push({\n // @ts-ignore\n y: child.firstChild.offsetTop - itemRef.current.offsetTop + child.firstChild.offsetHeight / 2,\n height: child.offsetHeight,\n // @ts-ignore\n textY: child.firstChild.offsetTop,\n mainEdge: stories.trace.mainEdges[i - 1],\n });\n }\n\n setInput({\n stories,\n position: state,\n elementHeight,\n firstDiv,\n });\n }\n }, [stories, dirtyFlag]);\n\n React.useEffect(() => {\n if (stories.trace && stories.trace.mainPath.length > 0) {\n setActiveTraceState(stories.trace.mainPath[0]);\n setSelectedCluster([stories.trace.mainPath[0]], false);\n }\n }, [stories.trace]);\n\n return (\n \n \n {\n setActiveTrace(null);\n }}\n >\n \n \n }\n title=\"Storytelling\"\n />\n\n \n {\n if (stories.activeTraceState) {\n const i = stories.trace.mainPath.indexOf(stories.activeTraceState);\n let c: EntityId = null;\n if (i === 0) {\n c = stories.trace.mainPath[stories.trace.mainPath.length - 1];\n } else {\n c = stories.trace.mainPath[(i - 1) % stories.trace.mainPath.length];\n }\n setActiveTraceState(c);\n setSelectedCluster([c], false);\n } else {\n setActiveTraceState(stories.trace.mainPath[0]);\n setSelectedCluster([stories.trace.mainPath[0]], false);\n }\n }}\n >\n \n \n {\n if (playing) {\n clearInterval(playing);\n setPlaying(null);\n } else {\n const interval = setInterval(() => {\n const btn = document.getElementById('nextBtn');\n if (btn) {\n btn.click();\n } else if (playing) {\n clearInterval(playing);\n }\n }, 2000);\n setPlaying(interval);\n }\n }}\n >\n {playing ? : }\n \n {\n if (stories.activeTraceState) {\n const i = stories.trace.mainPath.indexOf(stories.activeTraceState);\n const c = stories.trace.mainPath[(i + 1) % stories.trace.mainPath.length];\n setActiveTraceState(c);\n setSelectedCluster([c], false);\n } else {\n setActiveTraceState(stories.trace.mainPath[0]);\n setSelectedCluster([stories.trace.mainPath[0]], false);\n }\n }}\n >\n \n \n \n\n
    \n \n {\n setActiveTraceState(cluster);\n setSelectedCluster([cluster], false);\n }}\n />\n\n \n \n Summary\n \n\n {stories.trace?.mainPath.map((cluster) => {\n return (\n {\n setActiveTraceState(cluster);\n setSelectedCluster([cluster], false);\n }}\n >\n \n {ACluster.getTextRepresentation(AStorytelling.retrieveCluster(stories, cluster))}\n \n\n \n dataset.vectors[i])}\n scale={1}\n aggregate\n />\n
    \n \n );\n })}\n \n\n \n \n Difference\n \n {input && (\n
    \n )}\n {input &&\n input.position.slice(0, input.position.length - 1).map((elem, index) => {\n const edge = AStorytelling.retreiveEdge(stories, elem.mainEdge);\n return (\n \n \n dataset.vectors[i])}\n vectorsB={AStorytelling.retrieveCluster(stories, edge.destination).indices.map((i) => dataset.vectors[i])}\n />\n
    \n \n );\n })}\n \n \n \n \n \n );\n});\n","import { debounce } from 'lodash';\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\n\nfunction copyStyles(sourceDoc: Document, targetDoc: Document) {\n Array.from(targetDoc.querySelectorAll('style')).forEach((e) => e.remove());\n Array.from(targetDoc.querySelectorAll('link')).forEach((e) => e.remove());\n\n Array.from(sourceDoc.styleSheets).forEach((styleSheet) => {\n // @ts-ignore\n if (styleSheet.href) {\n const newLinkEl = sourceDoc.createElement('link');\n\n newLinkEl.rel = 'stylesheet';\n // @ts-ignore\n newLinkEl.href = styleSheet.href;\n targetDoc.head.appendChild(newLinkEl);\n // @ts-ignore\n } else if (styleSheet.cssRules && styleSheet.cssRules.length > 0) {\n const newStyleEl = sourceDoc.createElement('style');\n // @ts-ignore\n Array.from(styleSheet.cssRules).forEach((cssRule) => {\n // @ts-ignore\n newStyleEl.appendChild(sourceDoc.createTextNode(cssRule.cssText));\n });\n\n targetDoc.head.appendChild(newStyleEl);\n }\n });\n}\n\nexport class MyWindowPortal extends React.PureComponent {\n externalWindow: any;\n\n containerEl: any;\n\n constructor(props) {\n super(props);\n // STEP 1: create a container
    \n this.containerEl = document.createElement('div');\n this.externalWindow = null;\n }\n\n componentDidMount() {\n // STEP 3: open a new browser window and store a reference to it\n this.externalWindow = window.open('', '', 'width=300,height=600,left=0,top=0');\n\n copyStyles(document, this.externalWindow.document);\n\n // Options for the observer (which mutations to observe)\n const config = { attributes: true, childList: true, subtree: true };\n\n // Callback function to execute when mutations are observed\n const callback = debounce(\n (mutationList, observer) => {\n copyStyles(document, this.externalWindow.document);\n\n for (const mutation of mutationList) {\n if (mutation.type === 'childList') {\n console.log(mutation);\n }\n }\n },\n 50,\n { leading: true, trailing: true },\n );\n\n // Create an observer instance linked to the callback function\n const observer = new MutationObserver(callback);\n\n // Start observing the target node for configured mutations\n observer.observe(document.head, config);\n\n // Later, you can stop observing\n // TODO: unmount\n // observer.disconnect();\n\n this.externalWindow.addEventListener('beforeunload', () => {\n this.props.onClose();\n });\n\n // STEP 4: append the container
    (that has props.children appended to it) to the body of the new window\n this.externalWindow.document.body.appendChild(this.containerEl);\n\n this.externalWindow.document.title = 'Selection Summary';\n }\n\n componentWillUnmount() {\n // STEP 5: This will fire when this.state.showWindowPortal in the parent component becomes false\n // So we tidy up by closing the window\n this.externalWindow.close();\n }\n\n render() {\n // STEP 2: append props.children to the container
    that isn't mounted anywhere yet\n return ReactDOM.createPortal(this.props.children, this.containerEl);\n }\n}\n","export * from './SelectionClusters';\nexport * from './StateSequenceDrawer';\nexport * from './Storytelling';\nexport * from './WindowPortal';\nexport * from './PSELayer';\n","import { AppBar, Toolbar } from '@mui/material';\nimport * as React from 'react';\n\nexport function PseAppBar({ children, style }) {\n return (\n \n {children}\n \n );\n}\n","import { Reducer, Store, configureStore } from '@reduxjs/toolkit';\nimport thunk from 'redux-thunk';\nimport { v4 as uuidv4 } from 'uuid';\nimport { rootReducer, RootState } from './Store';\nimport { getStoreDiff } from './PluginScript';\nimport { RootActions } from './RootActions';\nimport { UtilityActions } from './Utility';\n\n/**\n * Main api class for PSE.\n */\nexport class API {\n store: Store;\n\n onStateChanged: (newState: T, difference: Partial, action: any) => void;\n\n id: string;\n\n /**\n * Creates a PSE API (store).\n *\n * @param dump the dump which contains parts of store state\n * @param reducer the root reducer of the store, MUST be created with PSE´s inbuilt createRootReducer method.\n */\n constructor(dump: any, reducer: Reducer, middleware?: any[]) {\n this.id = uuidv4();\n\n if (dump) {\n this.store = configureStore({\n reducer: reducer || rootReducer,\n preloadedState: dump,\n middleware: middleware ? [this.differenceMiddleware, thunk, ...middleware] : [this.differenceMiddleware, thunk],\n });\n } else {\n this.store = configureStore({\n reducer: reducer || rootReducer,\n middleware: middleware ? [this.differenceMiddleware, thunk, ...middleware] : [this.differenceMiddleware, thunk],\n });\n }\n }\n\n /**\n * Performs a partial store change.\n * This operation can have side effects depending on which parts you change that can break the app\n * (for example changing the dataset when there are still clusters)\n */\n partialHydrate(dump: any) {\n this.store.dispatch(RootActions.hydrate(dump));\n }\n\n reset() {\n this.store.dispatch(RootActions.reset());\n }\n\n serialize() {\n return JSON.stringify(this.store.getState());\n }\n\n /**\n * Creates a partial dump which excludes a list of columns.\n */\n partialDump(excluded: string[]): any {\n return UtilityActions.partialDump(this.store.getState(), excluded);\n }\n\n differenceMiddleware = (store) => (next) => (action) => {\n const oldState = store.getState();\n\n const newState = next(action);\n\n const diff = getStoreDiff(oldState, store.getState());\n\n if (this.onStateChanged) {\n this.onStateChanged(newState, diff, action);\n }\n\n return newState;\n };\n\n generateImage(\n width: number,\n height: number,\n padding: number,\n options: any,\n ctx?: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,\n ): Promise {\n return UtilityActions.generateImage(this.store.getState(), width, height, padding, options, ctx);\n }\n}\n","import { createTheme, ThemeProvider } from '@mui/material';\nimport { PropsWithChildren } from 'react';\nimport * as React from 'react';\nimport { Provider } from 'react-redux';\nimport { Store } from '@reduxjs/toolkit';\nimport { API } from './API';\n\ntype PSEContextProps = {\n context?: API;\n onStateChanged?: (values: any, keys: any) => void;\n};\n\nconst theme = createTheme({\n palette: {\n primary: {\n // light: will be calculated from palette.primary.main,\n main: '#007dad',\n // dark: will be calculated from palette.primary.main,\n // contrastText: will be calculated to contrast with palette.primary.main\n },\n },\n});\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function PSEContextProvider({ context, children, onStateChanged }: PropsWithChildren) {\n const [store, setStore] = React.useState(null);\n\n React.useEffect(() => {\n if (context) {\n setStore(context.store);\n } else {\n setStore(null);\n }\n }, [context]);\n\n return store ? (\n \n {children}\n \n ) : null;\n}\n","/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { Dataset } from '../../model/Dataset';\nimport { IVector } from '../../model/Vector';\n\nexport abstract class PSEPlugin {\n type: string;\n\n hasFileLayout(header: string[]) {\n return false;\n }\n\n abstract createFingerprint(dataset: Dataset, vectors: IVector[], scale: number, aggregate: boolean): JSX.Element;\n\n // Checks if the header has all the required columns\n hasLayout(header: string[], columns: string[]) {\n for (const key in columns) {\n const val = columns[key];\n\n if (!header.includes(val)) {\n return false;\n }\n }\n\n return true;\n }\n}\n","import { PSEPlugin } from './PSEPlugin';\n\nexport function getStoreDiff(storeA, storeB) {\n const diff = {};\n\n for (const key in storeA) {\n const valA = storeA[key];\n const valB = storeB[key];\n\n if (valA !== valB) {\n diff[key] = valB;\n }\n }\n\n return diff;\n}\n\nexport class PluginRegistry {\n private static instance: PluginRegistry;\n\n private plugins: PSEPlugin[] = [];\n\n private reducers: any[] = [];\n\n private constructor() {}\n\n public static getInstance(): PluginRegistry {\n if (!PluginRegistry.instance) {\n PluginRegistry.instance = new PluginRegistry();\n }\n\n return PluginRegistry.instance;\n }\n\n public getPlugin(type: string) {\n for (const plugin of this.plugins) {\n if (plugin.type === type) {\n return plugin;\n }\n }\n\n return null;\n }\n\n public registerPlugin(plugin: PSEPlugin) {\n this.plugins.push(plugin);\n }\n\n public registerReducer(reducer: any) {\n this.reducers.push(reducer);\n }\n\n public removePlugin(type: string) {\n this.plugins = this.plugins.filter((plugin) => plugin.type !== type);\n }\n}\n","import { Dataset } from '../../model';\n\nexport enum RootActionTypes {\n RESET = 'root/RESET',\n HYDRATE = 'root/HYDRATE',\n DATASET = 'root/DATASET',\n HARD_RESET = 'root/HARD_RESET',\n}\n\nexport const RootActions = {\n // Soft reset (keeping the dataset)\n reset: () => ({\n type: RootActionTypes.RESET,\n }),\n\n hydrate: (dump: any) => ({\n type: RootActionTypes.HYDRATE,\n dump,\n }),\n\n loadDataset: (dataset: Dataset) => ({\n type: RootActionTypes.DATASET,\n dataset,\n }),\n\n // Hard reset (throwing whole state away)\n hardReset: () => ({\n type: RootActionTypes.HARD_RESET,\n }),\n};\n","import { v4 as uuidv4 } from 'uuid';\nimport { createEntityAdapter, EntityState, EntityId } from '@reduxjs/toolkit';\nimport { combineReducers } from 'redux';\nimport clone from 'fast-clone';\nimport { useSelector } from 'react-redux';\nimport projectionOpen from '../Ducks/ProjectionOpenDuck';\nimport highlightedSequence from '../Ducks/HighlightedSequenceDuck';\nimport dataset from '../Ducks/DatasetDuck';\nimport openTab from '../Ducks/OpenTabDuck';\nimport clusterMode, { ClusterMode } from '../Ducks/ClusterModeDuck';\nimport advancedColoringSelection from '../Ducks/AdvancedColoringSelectionDuck';\nimport projectionColumns from '../Ducks/ProjectionColumnsDuck';\nimport displayMode from '../Ducks/DisplayModeDuck';\nimport { activeLine } from '../Ducks/ActiveLineDuck';\nimport currentAggregation from '../Ducks/AggregationDuck';\nimport projectionParams from '../Ducks/ProjectionParamsDuck';\nimport projectionWorker from '../Ducks/ProjectionWorkerDuck';\nimport trailSettings from '../Ducks/TrailSettingsDuck';\nimport { differenceThreshold } from '../Ducks/DifferenceThresholdDuck';\nimport hoverSettings from '../Ducks/HoverSettingsDuck';\nimport hoverState from '../Ducks/HoverStateDuck';\nimport { selectedLineBy } from '../Ducks/SelectedLineByDuck';\nimport groupVisualizationMode, { GroupVisualizationMode } from '../Ducks/GroupVisualizationMode';\nimport genericFingerprintAttributes from '../Ducks/GenericFingerprintAttributesDuck';\nimport hoverStateOrientation from '../Ducks/HoverStateOrientationDuck';\nimport { detailView } from '../Ducks/DetailViewDuck';\nimport datasetEntries from '../Ducks/DatasetEntriesDuck';\nimport { RootActionTypes } from './RootActions';\nimport { Dataset, ADataset, SegmentFN, AProjection, IBook, ProjectionMethod, IProjection, DefaultFeatureLabel } from '../../model';\nimport { CategoryOptionsAPI } from '../WebGLView/CategoryOptions';\nimport { ANormalized } from '../Utility/NormalizedState';\nimport { storyLayout, graphLayout, transformIndicesToHandles } from '../Utility/graphs';\nimport colorScales from '../Ducks/ColorScalesDuck';\nimport { BaseColorScale } from '../../model/Palette';\nimport { PointDisplayReducer } from '../Ducks/PointDisplayDuck';\nimport { multiplesSlice, multipleAdapter, defaultAttributes } from '../Ducks/ViewDuck';\nimport { stories, IStorytelling, AStorytelling } from '../Ducks/StoriesDuck';\n\n/**\n * Match all cases of view constants eg x1, y1, x2, y2...\n */\nconst viewRegexp = /^(x|y)[0-9]$/;\n\nconst allReducers = {\n currentAggregation,\n stories,\n openTab,\n pointDisplay: PointDisplayReducer,\n activeLine,\n dataset,\n highlightedSequence,\n advancedColoringSelection,\n projectionColumns,\n projectionOpen,\n projectionParams,\n projectionWorker,\n clusterMode,\n displayMode,\n hoverState,\n trailSettings,\n differenceThreshold,\n hoverSettings,\n selectedLineBy,\n groupVisualizationMode,\n genericFingerprintAttributes,\n hoverStateOrientation,\n detailView,\n datasetEntries,\n colorScales,\n multiples: multiplesSlice.reducer,\n};\n\nconst bookAdapter = createEntityAdapter({\n selectId: (book) => book.id,\n});\n\nconst appReducer = combineReducers(allReducers);\n\nexport function createInitialReducerState(dataset: Dataset): Partial {\n const clusterMode = dataset.multivariateLabels ? ClusterMode.Multivariate : ClusterMode.Univariate;\n const groupVisualizationMode = dataset.multivariateLabels ? GroupVisualizationMode.StarVisualization : GroupVisualizationMode.ConvexHull;\n\n // this.finite(dataset)\n\n const categoryOptions = dataset.categories;\n\n const pathLengthRange = {\n range: [0, SegmentFN.getMaxPathLength(dataset)],\n maximum: SegmentFN.getMaxPathLength(dataset),\n };\n\n let projections: EntityState = null;\n let workspace: IProjection | EntityId = null;\n\n if (dataset.hasInitialScalarTypes) {\n // When the dataset has initial positions, add this as a projection\n const initialProjection = AProjection.createProjection(\n dataset.vectors.map((vector) => ({ x: vector.x, y: vector.y })),\n 'Initial Projection',\n { method: ProjectionMethod.DATASET },\n );\n\n projections = {\n entities: { [initialProjection.hash]: initialProjection },\n ids: [initialProjection.hash],\n };\n\n workspace = initialProjection.hash;\n } else {\n // If no initial positions -> add temporary projection\n // When the dataset has initial positions, add this as a projection\n const initialProjection = AProjection.createProjection(\n dataset.vectors.map((vector) => ({ x: vector.x, y: vector.y })),\n 'Random Initialisation',\n { method: ProjectionMethod.RANDOM },\n );\n\n projections = {\n entities: {},\n ids: [],\n };\n\n workspace = initialProjection;\n }\n\n const genericFingerprintAttributes = ADataset.getColumns(dataset, true).map((column) => ({\n feature: column,\n show: dataset.columns[column].project,\n }));\n\n const formatRange = (range) => {\n try {\n return `${range.min.toFixed(2)} - ${range.max.toFixed(2)}`;\n } catch {\n return 'unknown';\n }\n };\n\n const projectionColumns = ADataset.getColumns(dataset, true).map((column) => ({\n name: column,\n checked: dataset.columns[column].project,\n normalized: true,\n range: dataset.columns[column].range ? formatRange(dataset.columns[column].range) : 'unknown',\n featureLabel: dataset.columns[column].featureLabel ? dataset.columns[column].featureLabel : DefaultFeatureLabel,\n }));\n\n const defaultSizeAttribute = CategoryOptionsAPI.getAttribute(categoryOptions, 'size', 'multiplicity', 'sequential');\n\n let globalPointSize;\n let channelSize;\n\n if (defaultSizeAttribute) {\n globalPointSize = [1, 2];\n channelSize = defaultSizeAttribute;\n } else {\n globalPointSize = [1];\n channelSize = null;\n }\n\n let channelColor;\n\n const defaultColorAttribute = CategoryOptionsAPI.getAttribute(categoryOptions, 'color', 'algo', 'categorical');\n if (defaultColorAttribute && !dataset.inferredColumns.includes('algo')) {\n channelColor = defaultColorAttribute;\n } else {\n channelColor = null;\n }\n\n const defaultBrightnessAttribute = CategoryOptionsAPI.getAttribute(categoryOptions, 'transparency', 'age', 'sequential');\n let channelBrightness;\n let globalPointBrightness;\n\n if (defaultBrightnessAttribute) {\n globalPointBrightness = [0.25, 1];\n channelBrightness = defaultBrightnessAttribute;\n } else {\n globalPointBrightness = [1];\n channelBrightness = null;\n }\n\n let stories: IStorytelling;\n if (dataset.clusters && dataset.clusters.length > 0) {\n const { clusters } = dataset;\n\n if (dataset.clusterEdges && dataset.clusterEdges.length > 0) {\n const story = transformIndicesToHandles(dataset.clusters, dataset.clusterEdges);\n const init = bookAdapter.getInitialState();\n init.entities = {\n [story.id]: story,\n };\n init.ids = [story.id];\n\n stories = {\n stories: init,\n active: null,\n trace: null,\n activeTraceState: null,\n groupLabel: {},\n };\n } else if (dataset.isSequential) {\n const [edges] = graphLayout(dataset, clusters);\n if (edges.length > 0) {\n const storyArr = storyLayout(clusters, edges);\n\n const init = bookAdapter.getInitialState();\n init.entities = storyArr.reduce((prev, cur) => {\n prev[cur.id] = cur;\n return prev;\n }, {});\n init.ids = Object.keys(init.entities);\n\n stories = {\n stories: init,\n active: null,\n trace: null,\n activeTraceState: null,\n groupLabel: {},\n };\n }\n }\n } else {\n stories = AStorytelling.createEmpty();\n }\n\n const colorScalesState = clone(colorScales());\n let pointColorScale = null;\n if (channelColor) {\n pointColorScale = ANormalized.entries(colorScalesState.scales).find(([, value]) => {\n return value.type === channelColor.type;\n })[0];\n }\n\n // Load views from dataset\n const xyChannels = {};\n\n const maxView = Object.entries(dataset.columns).reduce((prev, [key, curr]) => {\n try {\n const { view } = curr.metaInformation;\n if (Array.isArray(view)) {\n let max = prev;\n view.forEach((channel) => {\n if (typeof channel === 'string' && viewRegexp.test(channel)) {\n const vI = Number.parseInt(channel.charAt(1), 10);\n xyChannels[channel] = key;\n\n if (vI > max) {\n max = vI;\n }\n }\n });\n\n return max;\n }\n\n return prev;\n } catch (e) {\n return 0;\n }\n }, 0);\n\n let multiplesCollection = multipleAdapter.getInitialState();\n\n if (maxView > 0) {\n for (let i = 0; i < maxView; i++) {\n const vId = uuidv4();\n\n const xChannel = xyChannels[`x${i + 1}`];\n const yChannel = xyChannels[`y${i + 1}`];\n\n const view = {\n id: vId,\n attributes: {\n ...defaultAttributes(),\n workspace: AProjection.createManualProjection(dataset, xChannel, yChannel),\n },\n };\n\n multiplesCollection = multipleAdapter.addOne(multiplesCollection, view);\n }\n } else {\n const multipleId = uuidv4();\n\n const defaultView = {\n id: multipleId,\n attributes: {\n ...defaultAttributes(),\n channelBrightness,\n channelSize,\n channelColor,\n globalPointBrightness,\n globalPointSize,\n pathLengthRange,\n pointColorScale,\n workspace,\n },\n };\n\n multiplesCollection = multipleAdapter.addOne(multiplesCollection, defaultView);\n }\n\n const multiples = {\n multiples: multiplesCollection,\n active: multiplesCollection.ids[0],\n projections,\n };\n\n return {\n clusterMode,\n groupVisualizationMode,\n genericFingerprintAttributes,\n projectionColumns,\n stories,\n colorScales: colorScalesState,\n multiples,\n };\n}\n\nexport const rootReducer = (state, action) => {\n if (action.type === RootActionTypes.RESET) {\n const { dataset, openTab, viewTransform, datasetEntries } = state;\n state = { dataset, openTab, viewTransform, datasetEntries };\n }\n\n return appReducer(state, action);\n};\n\nexport function createRootReducer(reducers: any) {\n const root = { ...allReducers };\n Object.assign(root, reducers);\n\n const combined = combineReducers(root);\n\n return (state, action) => {\n if (action.type === RootActionTypes.RESET) {\n const { dataset, openTab, datasetEntries } = state;\n state = { dataset, openTab, datasetEntries };\n }\n\n if (action.type === RootActionTypes.HYDRATE) {\n const newState = { ...state };\n\n Object.assign(newState, action.dump);\n\n return newState;\n }\n\n if (action.type === RootActionTypes.DATASET) {\n const newState = { ...state };\n\n const partialRootState = createInitialReducerState(action.dataset);\n partialRootState.dataset = action.dataset;\n Object.assign(newState, partialRootState);\n\n return newState;\n }\n\n if (action.type === RootActionTypes.HARD_RESET) {\n const clone = { ...state };\n for (const key of Object.keys(allReducers)) {\n clone[key] = undefined;\n }\n state = clone;\n }\n\n return combined(state, action);\n };\n}\n\nexport type RootState = ReturnType;\n\nexport const usePSESelector = (fn: (state: RootState) => T) => useSelector(fn);\n","import * as THREE from 'three';\nimport { createLinearRangeScaler } from '../Utility/ScalingAndAxes';\nimport { SchemeColor } from '../Utility/Colors/SchemeColor';\nimport { IBaseProjection, IProjection } from '../../model/ProjectionInterfaces';\nimport { CubicBezierCurve } from '../../model/Curves';\nimport type { RootState } from './Store';\nimport { Dataset } from '../../model/Dataset';\nimport { mapValueToColor } from '../Utility';\n\nfunction calcBounds(positions: IBaseProjection) {\n // Get rectangle that fits around data set\n let minX = 1000;\n let maxX = -1000;\n let minY = 1000;\n let maxY = -1000;\n positions.forEach((sample) => {\n minX = Math.min(minX, sample.x);\n maxX = Math.max(maxX, sample.x);\n minY = Math.min(minY, sample.y);\n maxY = Math.max(maxY, sample.y);\n });\n\n return {\n x: minX,\n y: minY,\n width: maxX - minX,\n height: maxY - minY,\n left: minX,\n top: minY,\n right: maxX,\n bottom: maxY,\n };\n}\n\nfunction solve(data, k) {\n if (k == null) k = 1;\n\n const size = data.length;\n const last = size - 4;\n\n let path = `M${[data[0], data[1]]}`;\n\n for (let i = 0; i < size - 2; i += 2) {\n const x0 = i ? data[i - 2] : data[0];\n const y0 = i ? data[i - 1] : data[1];\n\n const x1 = data[i + 0];\n const y1 = data[i + 1];\n\n const x2 = data[i + 2];\n const y2 = data[i + 3];\n\n const x3 = i !== last ? data[i + 4] : x2;\n const y3 = i !== last ? data[i + 5] : y2;\n\n const cp1x = x1 + ((x2 - x0) / 6) * k;\n const cp1y = y1 + ((y2 - y0) / 6) * k;\n\n const cp2x = x2 - ((x3 - x1) / 6) * k;\n const cp2y = y2 - ((y3 - y1) / 6) * k;\n\n path += `C${[cp1x, cp1y, cp2x, cp2y, x2, y2]}`;\n }\n\n return path;\n}\n\nconst blobToBase64 = (blob) => {\n const reader = new FileReader();\n reader.readAsDataURL(blob);\n return new Promise((resolve) => {\n reader.onloadend = () => {\n let b64 = reader.result as string;\n\n b64 = b64.replace(/^data:.+;base64,/, '');\n\n resolve(b64);\n };\n });\n};\n\n/**\n * Creates a partial dump which excludes a list of columns.\n */\nexport class UtilityActions {\n static partialDump(state: any, excluded: string[]): any {\n const set = new Set(excluded);\n\n const partial = {};\n\n // Copy all included keys to partial object\n Object.keys(state)\n .filter((key) => !set.has(key))\n .forEach((key) => {\n partial[key] = state[key];\n });\n\n return partial;\n }\n\n static bezierLength(curve: CubicBezierCurve) {\n const tc = new THREE.CubicBezierCurve(\n new THREE.Vector2(curve.start.x, curve.start.y),\n new THREE.Vector2(curve.cp1.x, curve.cp1.y),\n new THREE.Vector2(curve.cp2.x, curve.cp2.y),\n new THREE.Vector2(curve.end.x, curve.end.y),\n );\n\n return tc.getLength();\n }\n\n static solveCatmullRom(data, k): CubicBezierCurve[] {\n if (k == null) k = 1;\n\n const size = data.length;\n const last = size - 4;\n\n const path: CubicBezierCurve[] = [];\n\n let startX = data[0];\n let startY = data[1];\n\n for (let i = 0; i < size - 2; i += 2) {\n const x0 = i ? data[i - 2] : data[0];\n const y0 = i ? data[i - 1] : data[1];\n\n const x1 = data[i + 0];\n const y1 = data[i + 1];\n\n const x2 = data[i + 2];\n const y2 = data[i + 3];\n\n const x3 = i !== last ? data[i + 4] : x2;\n const y3 = i !== last ? data[i + 5] : y2;\n\n const cp1x = x1 + ((x2 - x0) / 6) * k;\n const cp1y = y1 + ((y2 - y0) / 6) * k;\n\n const cp2x = x2 - ((x3 - x1) / 6) * k;\n const cp2y = y2 - ((y3 - y1) / 6) * k;\n\n path.push({ start: { x: startX, y: startY }, cp1: { x: cp1x, y: cp1y }, cp2: { x: cp2x, y: cp2y }, end: { x: x2, y: y2 } });\n\n startX = x2;\n startY = y2;\n }\n\n return path;\n }\n\n static partialBezierCurve(t: number, curve: CubicBezierCurve) {\n const p0 = curve.start;\n const p1 = curve.cp1;\n const p2 = curve.cp2;\n const p3 = curve.end;\n\n const cX = 3 * (p1.x - p0.x);\n const bX = 3 * (p2.x - p1.x) - cX;\n const aX = p3.x - p0.x - cX - bX;\n\n const cY = 3 * (p1.y - p0.y);\n const bY = 3 * (p2.y - p1.y) - cY;\n const aY = p3.y - p0.y - cY - bY;\n\n const x = aX * t ** 3 + bX * t ** 2 + cX * t + p0.x;\n const y = aY * t ** 3 + bY * t ** 2 + cY * t + p0.y;\n\n return { x, y };\n }\n\n static generateImage(\n state: RootState,\n width: number,\n height: number,\n padding: number,\n options: any,\n ctx?: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D,\n ) {\n function selectPositions(dataset: Dataset, projection: IProjection) {\n if (projection.xChannel || projection.yChannel) {\n return dataset.vectors.map((vector) => ({\n x: projection.xChannel ? vector[projection.xChannel] : 0,\n y: projection.yChannel ? vector[projection.yChannel] : 0,\n }));\n }\n\n return projection.positions;\n }\n\n try {\n const provided = ctx !== null && ctx !== undefined;\n\n const { channelColor, channelSize, globalPointSize, pointColorMapping, workspace } =\n state.multiples.multiples.entities[state.multiples.multiples.ids[0]].attributes;\n\n let canvas = null;\n if (!ctx) {\n canvas = new OffscreenCanvas(width, height);\n ctx = canvas.getContext('2d');\n }\n\n // This line is actually not even needed...\n ctx.beginPath();\n ctx.clearRect(0, 0, width, height);\n ctx.fillStyle = options?.backgroundColor ?? '#fff';\n ctx.rect(0, 0, width, height);\n ctx.fill();\n ctx.closePath();\n ctx.beginPath();\n\n const mapping = pointColorMapping;\n\n const positions =\n typeof workspace === 'string' || typeof workspace === 'number'\n ? selectPositions(state.dataset, state.multiples.projections.entities[workspace])\n : selectPositions(state.dataset, workspace);\n\n const bounds = calcBounds(positions);\n\n const offsetX = -bounds.left;\n const offsetY = -bounds.top;\n\n const innerAR = bounds.width / bounds.height;\n const outerAR = width / height;\n\n let xPad = 0;\n let yPad = 0;\n\n if (innerAR > outerAR) {\n // more broad than bounds allow... pad horizontal\n yPad = ((1 - outerAR / innerAR) * height) / 2;\n } else if (innerAR < outerAR) {\n // more narrow than bounds allow, pad vertical\n xPad = ((1 - innerAR / outerAR) * width) / 2;\n }\n\n const sx = (x: number) => {\n return padding + xPad + (offsetX + x) * ((width - 2 * (padding + xPad)) / bounds.width);\n };\n\n const sy = (y: number) => {\n return height - (padding + yPad + (offsetY + y) * ((height - 2 * (padding + yPad)) / bounds.height));\n };\n\n if (state.dataset.isSequential) {\n ctx.globalAlpha = 0.5;\n ctx.lineWidth = options?.lineWidth ?? 2;\n ctx.filter = options?.lineFilter ?? '';\n\n state.dataset.segments.forEach((segment) => {\n const points = segment.vectors.map((vector) => [sx(vector.x), sy(vector.y)]).flat();\n\n const path = new Path2D(solve(points, 1));\n\n ctx.strokeStyle = segment.__meta__.intrinsicColor.hex;\n ctx.stroke(path);\n });\n }\n\n ctx.lineWidth = 1;\n ctx.globalAlpha = 1;\n ctx.filter = options?.pointFilter ?? '';\n\n let pointSizeScaler = null;\n\n if (channelSize) {\n pointSizeScaler = createLinearRangeScaler(\n globalPointSize as any,\n state.dataset.columns[channelSize.key].range.min,\n state.dataset.columns[channelSize.key].range.max,\n );\n }\n\n let isSelected: (index: number) => boolean = () => true;\n\n if (state.currentAggregation.aggregation.length > 0) {\n const aggSet = new Set(state.currentAggregation.aggregation);\n isSelected = (index: number) => {\n return aggSet.has(index);\n };\n }\n\n positions.forEach((value, index) => {\n const { x, y } = value;\n\n const color = isSelected(index)\n ? mapping\n ? mapValueToColor(mapping, state.dataset.vectors[index][channelColor.key])\n : new SchemeColor('#7fc97f')\n : new SchemeColor('#c0c0c0');\n\n ctx.beginPath();\n\n ctx.fillStyle = color.hex;\n ctx.strokeStyle = color.hex;\n\n ctx.globalAlpha = options?.pointBrightness ?? 0.5;\n ctx.moveTo(sx(x), sy(y));\n ctx.arc(sx(x), sy(y), (options?.pointSize ?? 4) * (channelSize ? pointSizeScaler(state.dataset.vectors[index][channelSize.key]) : 1), 0, 2 * Math.PI);\n ctx.fill();\n ctx.stroke();\n });\n\n ctx.filter = '';\n ctx.globalAlpha = 1;\n\n return new Promise((resolve) => {\n if (!provided) {\n canvas\n .convertToBlob({\n type: 'image/jpeg',\n quality: 1,\n })\n .then((result) => {\n blobToBase64(result).then((result) => {\n resolve(result);\n });\n });\n } else {\n resolve('');\n }\n });\n } catch (e) {\n console.log(e);\n return new Promise((resolve) => {\n resolve('');\n });\n }\n }\n}\n","export * from './PluginScript';\nexport * from './PSEContext';\nexport * from './Store';\nexport * from './PSEPlugin';\nexport * from './API';\nexport * from './RootActions';\nexport * from './Utility';\n","/* eslint-disable react/prefer-stateless-function */\n/* eslint-disable react/no-array-index-key */\n/* eslint-disable @typescript-eslint/no-loop-func */\n/* eslint-disable react/no-unused-prop-types */\nimport './VirtualTable.scss';\nimport * as React from 'react';\n\ntype VirtualTableProps = {\n rows: any;\n rowHeight: number;\n tableHeight: number;\n};\n\ntype VirtualColumnProps = {\n width: number;\n name: string;\n renderer: (row: any) => any;\n};\n\nexport class VirtualColumn extends React.Component {}\n\nexport class VirtualTable extends React.Component {\n constructor(props) {\n // Initial props:\n super(props);\n\n // Initial state:\n this.state = {\n tableHeight: this.props.rowHeight * this.props.rows.length,\n scroll: {\n top: 0,\n index: 0,\n end: Math.ceil((this.props.tableHeight * 2) / this.props.rowHeight),\n },\n };\n\n // Event handlers:\n this.onScroll = this.onScroll.bind(this);\n }\n\n onScroll({ target }) {\n const { state } = this;\n\n const { scrollTop } = target;\n const { rowHeight } = this.props;\n const { tableHeight } = this.props;\n const index = Math.floor(scrollTop / rowHeight);\n const padding = Math.ceil((this.props.tableHeight * 2) / this.props.rowHeight);\n state.scroll.index = index - padding < 0 ? index : index - padding;\n state.scroll.end = index + Math.ceil((tableHeight * 2) / rowHeight);\n state.scroll.top = (scrollTop / rowHeight) * rowHeight;\n\n this.setState(state);\n }\n\n generateRows() {\n const { rowHeight } = this.props;\n const { rows } = this.props;\n let { index } = this.state.scroll;\n const items = [];\n\n do {\n if (index >= rows.length) {\n index = rows.length;\n break;\n }\n\n const rowAttrs = {\n style: {\n position: 'absolute',\n top: index * rowHeight,\n left: 0,\n height: rowHeight,\n lineHeight: `${rowHeight}px`,\n display: 'flex',\n flexDirection: 'row',\n alignItems: 'center',\n width: '100%',\n padding: 4,\n boxSizing: 'border-box',\n },\n className: `tr ${index % 2 === 0 ? 'tr-odd' : 'tr-even'}`,\n };\n\n items.push(\n // @ts-ignore\n
    \n {/* @ts-ignore */}\n {this.props.children.map((child, i) => {\n return (\n
    \n {child.props.renderer(rows[index])}\n
    \n );\n })}\n
    ,\n );\n\n index++;\n } while (index < this.state.scroll.end);\n\n return items;\n }\n\n render() {\n const attrs = {\n wrapper: { className: 'wrapper' },\n tr: { className: 'tr' },\n content: {\n className: 'table-content dorime',\n style: {\n height: this.props.tableHeight > this.state.tableHeight ? this.state.tableHeight + 2 : this.props.tableHeight,\n width: 500,\n },\n onScroll: this.onScroll,\n },\n tbody: {\n style: {\n position: 'relative',\n display: 'inline-block',\n height: this.state.tableHeight,\n maxHeight: this.state.tableHeight,\n width: '100%',\n },\n },\n };\n\n return (\n
    \n
    \n {/* @ts-ignore */}\n
    {this.generateRows()}
    \n
    \n
    \n );\n }\n}\n","export class ColorScheme {\n colors: any;\n\n mapping: any;\n\n constructor(colors) {\n this.colors = colors;\n }\n\n getMapping() {\n return this.mapping;\n }\n\n map(value) {\n return this.colors[value];\n }\n}\n","import * as d3v5 from 'd3v5';\nimport { SchemeColor } from './SchemeColor';\nimport { AShallowSet } from '../ShallowSet';\nimport { BaseColorScale } from '../../../model/Palette';\nimport { APalette } from '../../../model/palettes';\nimport { getMinMaxOfChannel } from '../../WebGLView/UtilityFunctions';\nimport { Dataset } from '../../../model/Dataset';\n\n// Color to use when the mapping is incomplete or impossible to map\nconst FALLBACK_COLOR = new SchemeColor('#000000');\n\nexport interface DiscreteMapping {\n scale: BaseColorScale;\n values: any[];\n type: 'categorical';\n}\n\nexport interface ContinuousMapping {\n scale: BaseColorScale;\n type: 'sequential';\n range: [number, number];\n}\n\nexport interface DivergingMapping {\n scale: BaseColorScale;\n range: [number, number, number];\n type: 'diverging';\n}\n\n/**\n * Helper function that maps a value to a color using a mapping\n *\n * @param mapping a mapping object\n * @param value any value\n * @returns a color\n */\nexport function mapValueToColor(mapping: ContinuousMapping | DivergingMapping | DiscreteMapping, value): SchemeColor {\n switch (mapping.type) {\n case 'sequential': {\n const [min, max] = mapping.range;\n\n const palette = typeof mapping.scale.palette === 'string' ? APalette.getByName(mapping.scale.palette) : mapping.scale.palette;\n\n if (min === max) {\n return palette[0];\n }\n\n const normalized = (value - min) / (max - min);\n\n const interpolator = d3v5\n .scaleLinear()\n .domain(palette.map((stop, index) => (1 / (palette.length - 1)) * index))\n // @ts-ignore\n .range(palette.map((stop) => stop.hex));\n // @ts-ignore\n const d3color = d3v5.color(interpolator(normalized));\n // @ts-ignore\n return d3color ? SchemeColor.rgbToHex(d3color.r, d3color.g, d3color.b) : FALLBACK_COLOR;\n }\n case 'diverging': {\n const palette = typeof mapping.scale.palette === 'string' ? APalette.getByName(mapping.scale.palette) : mapping.scale.palette;\n\n if (mapping.range[0] === mapping.range[1]) {\n return palette[1];\n }\n\n const paletteInterpolate = d3v5\n .scaleLinear()\n .domain(palette.map((stop, index) => (1 / (palette.length - 1)) * index))\n // @ts-ignore\n .range(palette.map((stop) => stop.hex));\n\n const interpolator = d3v5.scaleDiverging(paletteInterpolate).domain(mapping.range);\n\n // @ts-ignore\n const d3color = d3v5.color(interpolator(value)) as d3v5.RGBColor;\n\n return d3color ? SchemeColor.rgbToHex(d3color.r, d3color.g, d3color.b) : FALLBACK_COLOR;\n }\n case 'categorical': {\n const palette = typeof mapping.scale.palette === 'string' ? APalette.getByName(mapping.scale.palette) : mapping.scale.palette;\n return palette[AShallowSet.indexOf(mapping.values, value) % palette.length] ?? FALLBACK_COLOR;\n }\n default: {\n return FALLBACK_COLOR;\n }\n }\n}\n\n/**\n * Helper type that contains a union over all mappings\n */\nexport type Mapping = DiscreteMapping | DivergingMapping | ContinuousMapping;\n\n/**\n *\n * @param scale the color scale\n * @param key the key for the data values\n * @param dataset the dataset\n * @returns a mapping object\n */\nexport const mappingFromScale = (scale: BaseColorScale, key: string, dataset: Dataset, additionalColumns?: { [key: string]: { [key: number]: number[] } }) => {\n if (scale.type === 'categorical') {\n if (additionalColumns && key in additionalColumns) {\n const elements = additionalColumns[key];\n\n return {\n scale,\n values: AShallowSet.create(dataset.vectors.map((vector) => elements[vector.__meta__.meshIndex])),\n type: 'categorical',\n } as DiscreteMapping;\n }\n return {\n scale,\n values: AShallowSet.create(dataset.vectors.map((vector) => vector[key])),\n type: 'categorical',\n } as DiscreteMapping;\n }\n if (scale.type === 'sequential') {\n const { min, max } = getMinMaxOfChannel(dataset, key);\n\n return {\n scale,\n type: 'sequential',\n range: [min, max],\n } as ContinuousMapping;\n }\n if (scale.type === 'diverging') {\n const { min, max, center } = getMinMaxOfChannel(dataset, key);\n\n return {\n scale,\n type: 'diverging',\n range: [min, center ?? (min + max) / 2, max],\n } as DivergingMapping;\n }\n return null;\n};\n\n/**\n *\n * @param mapping a mapping object\n * @returns true if the given value is a numeric one\n */\nexport function isNumericMapping(mapping: Mapping): mapping is DivergingMapping | ContinuousMapping {\n return mapping?.type === 'diverging' || mapping?.type === 'sequential';\n}\n","export class SchemeColor {\n hex: string;\n\n rgb: { r; g; b };\n\n constructor(hex) {\n this.hex = hex;\n this.rgb = this.hexToRgb(this.hex);\n }\n\n hexToRgb(hex) {\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n return result\n ? {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n }\n : null;\n }\n\n static componentToHex(c) {\n const hex = c.toString(16);\n return hex.length === 1 ? `0${hex}` : hex;\n }\n\n static rgbToHex(r, g, b) {\n return new SchemeColor(`#${SchemeColor.componentToHex(r)}${SchemeColor.componentToHex(g)}${SchemeColor.componentToHex(b)}`);\n }\n}\n","export * from './ColorScheme';\nexport * from './Mapping';\nexport * from './SchemeColor';\n","/* eslint-disable no-prototype-builtins */\n/**\n * Dictionary containing all countries\n */\nconst isoCountries = {\n AF: 'Afghanistan',\n AX: 'Aland Islands',\n AL: 'Albania',\n DZ: 'Algeria',\n AS: 'American Samoa',\n AD: 'Andorra',\n AO: 'Angola',\n AI: 'Anguilla',\n AQ: 'Antarctica',\n AG: 'Antigua And Barbuda',\n AR: 'Argentina',\n AM: 'Armenia',\n AW: 'Aruba',\n AU: 'Australia',\n AT: 'Austria',\n AZ: 'Azerbaijan',\n BS: 'Bahamas',\n BH: 'Bahrain',\n BD: 'Bangladesh',\n BB: 'Barbados',\n BY: 'Belarus',\n BE: 'Belgium',\n BZ: 'Belize',\n BJ: 'Benin',\n BM: 'Bermuda',\n BT: 'Bhutan',\n BO: 'Bolivia',\n BA: 'Bosnia And Herzegovina',\n BW: 'Botswana',\n BV: 'Bouvet Island',\n BR: 'Brazil',\n IO: 'British Indian Ocean Territory',\n BN: 'Brunei Darussalam',\n BG: 'Bulgaria',\n BF: 'Burkina Faso',\n BI: 'Burundi',\n KH: 'Cambodia',\n CM: 'Cameroon',\n CA: 'Canada',\n CV: 'Cape Verde',\n KY: 'Cayman Islands',\n CF: 'Central African Republic',\n TD: 'Chad',\n CL: 'Chile',\n CN: 'China',\n CX: 'Christmas Island',\n CC: 'Cocos (Keeling) Islands',\n CO: 'Colombia',\n KM: 'Comoros',\n CG: 'Congo',\n CD: 'Congo, Democratic Republic',\n CK: 'Cook Islands',\n CR: 'Costa Rica',\n CI: \"Cote D'Ivoire\",\n HR: 'Croatia',\n CU: 'Cuba',\n CY: 'Cyprus',\n CZ: 'Czech Republic',\n DK: 'Denmark',\n DJ: 'Djibouti',\n DM: 'Dominica',\n DO: 'Dominican Republic',\n EC: 'Ecuador',\n EG: 'Egypt',\n SV: 'El Salvador',\n GQ: 'Equatorial Guinea',\n ER: 'Eritrea',\n EE: 'Estonia',\n ET: 'Ethiopia',\n FK: 'Falkland Islands (Malvinas)',\n FO: 'Faroe Islands',\n FJ: 'Fiji',\n FI: 'Finland',\n FR: 'France',\n GF: 'French Guiana',\n PF: 'French Polynesia',\n TF: 'French Southern Territories',\n GA: 'Gabon',\n GM: 'Gambia',\n GE: 'Georgia',\n DE: 'Germany',\n GH: 'Ghana',\n GI: 'Gibraltar',\n GR: 'Greece',\n GL: 'Greenland',\n GD: 'Grenada',\n GP: 'Guadeloupe',\n GU: 'Guam',\n GT: 'Guatemala',\n GG: 'Guernsey',\n GN: 'Guinea',\n GW: 'Guinea-Bissau',\n GY: 'Guyana',\n HT: 'Haiti',\n HM: 'Heard Island & Mcdonald Islands',\n VA: 'Holy See (Vatican City State)',\n HN: 'Honduras',\n HK: 'Hong Kong',\n HU: 'Hungary',\n IS: 'Iceland',\n IN: 'India',\n ID: 'Indonesia',\n IR: 'Iran, Islamic Republic Of',\n IQ: 'Iraq',\n IE: 'Ireland',\n IM: 'Isle Of Man',\n IL: 'Israel',\n IT: 'Italy',\n JM: 'Jamaica',\n JP: 'Japan',\n JE: 'Jersey',\n JO: 'Jordan',\n KZ: 'Kazakhstan',\n KE: 'Kenya',\n KI: 'Kiribati',\n KR: 'Korea',\n KW: 'Kuwait',\n KG: 'Kyrgyzstan',\n LA: \"Lao People's Democratic Republic\",\n LV: 'Latvia',\n LB: 'Lebanon',\n LS: 'Lesotho',\n LR: 'Liberia',\n LI: 'Liechtenstein',\n LT: 'Lithuania',\n LU: 'Luxembourg',\n MO: 'Macao',\n MG: 'Madagascar',\n MW: 'Malawi',\n MY: 'Malaysia',\n MV: 'Maldives',\n ML: 'Mali',\n MT: 'Malta',\n MH: 'Marshall Islands',\n MQ: 'Martinique',\n MR: 'Mauritania',\n MU: 'Mauritius',\n YT: 'Mayotte',\n MX: 'Mexico',\n FM: 'Micronesia, Federated States Of',\n MD: 'Moldova',\n MC: 'Monaco',\n MN: 'Mongolia',\n ME: 'Montenegro',\n MS: 'Montserrat',\n MA: 'Morocco',\n MZ: 'Mozambique',\n MM: 'Myanmar',\n NA: 'Namibia',\n NR: 'Nauru',\n NP: 'Nepal',\n NL: 'Netherlands',\n AN: 'Netherlands Antilles',\n NC: 'New Caledonia',\n NZ: 'New Zealand',\n NI: 'Nicaragua',\n NE: 'Niger',\n NG: 'Nigeria',\n NU: 'Niue',\n NF: 'Norfolk Island',\n MK: 'North Macedonia',\n MP: 'Northern Mariana Islands',\n NO: 'Norway',\n OM: 'Oman',\n PK: 'Pakistan',\n PW: 'Palau',\n PS: 'Palestinian Territory, Occupied',\n PA: 'Panama',\n PG: 'Papua New Guinea',\n PY: 'Paraguay',\n PE: 'Peru',\n PH: 'Philippines',\n PN: 'Pitcairn',\n PL: 'Poland',\n PT: 'Portugal',\n PR: 'Puerto Rico',\n QA: 'Qatar',\n RE: 'Reunion',\n RO: 'Romania',\n RU: 'Russian Federation',\n RW: 'Rwanda',\n BL: 'Saint Barthelemy',\n SH: 'Saint Helena',\n KN: 'Saint Kitts And Nevis',\n LC: 'Saint Lucia',\n MF: 'Saint Martin',\n PM: 'Saint Pierre And Miquelon',\n VC: 'Saint Vincent And Grenadines',\n WS: 'Samoa',\n SM: 'San Marino',\n ST: 'Sao Tome And Principe',\n SA: 'Saudi Arabia',\n SN: 'Senegal',\n RS: 'Serbia',\n SC: 'Seychelles',\n SL: 'Sierra Leone',\n SG: 'Singapore',\n SK: 'Slovakia',\n SI: 'Slovenia',\n SB: 'Solomon Islands',\n SO: 'Somalia',\n ZA: 'South Africa',\n GS: 'South Georgia And Sandwich Isl.',\n ES: 'Spain',\n LK: 'Sri Lanka',\n LY: 'State of Libya',\n SD: 'Sudan',\n SR: 'Suriname',\n SJ: 'Svalbard And Jan Mayen',\n SZ: 'Swaziland',\n SE: 'Sweden',\n CH: 'Switzerland',\n SY: 'Syrian Arab Republic',\n TW: 'Taiwan',\n TJ: 'Tajikistan',\n TZ: 'Tanzania',\n TH: 'Thailand',\n TL: 'Timor-Leste',\n TG: 'Togo',\n TK: 'Tokelau',\n TO: 'Tonga',\n TT: 'Trinidad And Tobago',\n TN: 'Tunisia',\n TR: 'Turkey',\n TM: 'Turkmenistan',\n TC: 'Turks And Caicos Islands',\n TV: 'Tuvalu',\n UG: 'Uganda',\n UA: 'Ukraine',\n AE: 'United Arab Emirates',\n GB: 'United Kingdom',\n US: 'United States',\n UM: 'United States Outlying Islands',\n UY: 'Uruguay',\n UZ: 'Uzbekistan',\n VU: 'Vanuatu',\n VE: 'Venezuela',\n VN: 'Viet Nam',\n VG: 'Virgin Islands, British',\n VI: 'Virgin Islands, U.S.',\n WF: 'Wallis And Futuna',\n EH: 'Western Sahara',\n YE: 'Yemen',\n ZM: 'Zambia',\n ZW: 'Zimbabwe',\n};\n\n/**\n * Maps a 2 letter ISO code to a country name\n * @param {*} countryCode the 2 letter ISO code\n */\nexport function getCountryName(countryCode) {\n if (isoCountries.hasOwnProperty(countryCode)) {\n return isoCountries[countryCode];\n }\n return countryCode;\n}\n/**\n * Maps a country name to the 2 letter ISO code\n * @param {*} countryName the name of the country\n */\nexport function getCountryCode(countryName) {\n // Some names often appear, but are not standardized such as Russia, handle them seperately\n if (countryName === 'Brunei') return getCountryCode('Brunei Darussalam');\n if (countryName === 'Congo, Dem. Rep') return getCountryCode('Congo, Democratic Republic');\n if (countryName === 'Congo, Rep') return getCountryCode('Congo');\n if (countryName === 'Iran') return getCountryCode('Iran, Islamic Republic Of');\n if (countryName === 'Islamic Republic of Iran') return getCountryCode('Iran, Islamic Republic Of');\n if (countryName === 'Laos') return getCountryCode(\"Lao People's Democratic Republic\");\n if (countryName === 'Micronesia, Fed. Sts.') return getCountryCode('Micronesia, Federated States Of');\n if (countryName === 'Macedonia, FYR') return getCountryCode('North Macedonia');\n if (countryName === 'Macedonia') return getCountryCode('North Macedonia');\n if (countryName === 'West Bank and Gaza') return getCountryCode('Palestinian Territory, Occupied');\n if (countryName === 'Russia') return getCountryCode('Russian Federation');\n if (countryName === 'Slovak Republic') return getCountryCode('Slovakia');\n if (countryName === 'Libya') return getCountryCode('State of Libya');\n if (countryName === 'Libyan Arab Jamahiriya') return getCountryCode('State of Libya');\n if (countryName === 'Eswatini') return getCountryCode('Swaziland');\n if (countryName === 'Syria') return getCountryCode('Syrian Arab Republic');\n if (countryName === 'Trinidad and Tobago') return getCountryCode('Trinidad And Tobago');\n if (countryName === 'Vietnam') return getCountryCode('Viet Nam');\n\n const f = Object.keys(isoCountries).find((key) => isoCountries[key] === countryName);\n\n return f != null ? f : countryName;\n}\n","import { requiredChessColumns } from '../../../plugins/Chess/ChessFingerprint/ChessFingerprint';\nimport { requiredRubikColumns } from '../../../plugins/Rubik/RubikFingerprint/RubikFingerprint';\nimport { DatasetType } from '../../../model/DatasetType';\nimport { IVector } from '../../../model/Vector';\n\n/**\n * Object responsible for infering things from the data structure of a csv file.\n * For example this class can infer the\n * - ranges of columns\n * - type of data file (rubik, story...)\n */\nexport class InferCategory {\n vectors: IVector[];\n\n constructor(vectors) {\n this.vectors = vectors;\n }\n\n /**\n * Infers the type of the dataset from the columns\n * @param {*} header\n */\n inferType() {\n const header = Object.keys(this.vectors[0]);\n\n // Checks if the header has all the required columns\n const hasLayout = (columns: string[]) => {\n // eslint-disable-next-line guard-for-in\n for (const key in columns) {\n const val = columns[key];\n\n if (!header.includes(val)) {\n return false;\n }\n }\n\n return true;\n };\n\n if (hasLayout(requiredRubikColumns)) {\n return DatasetType.Rubik;\n }\n\n if (header.includes('wav')) {\n return DatasetType.Sound;\n }\n\n if (header.includes('cf00')) {\n return DatasetType.Neural;\n }\n\n if (hasLayout(requiredChessColumns)) {\n return DatasetType.Chess;\n }\n\n if (header.includes('new_y')) {\n return DatasetType.Story;\n }\n\n if (header.includes('aa')) {\n return DatasetType.Go;\n }\n\n // if (header.toString().toLowerCase().includes('smiles')) {\n // return DatasetType.Chem;\n // }\n\n if (header.includes('selectedCoordsNorm')) {\n return DatasetType.Trrack;\n }\n\n return DatasetType.None;\n }\n}\n","/* eslint-disable no-param-reassign */\n/* eslint-disable operator-assignment */\nimport { IVector } from '../../../model/Vector';\n\n/**\n * Class that preprocesses the data set and checks for validity.\n * Will halucinate attributes like x, y, line, algo and multiplicity if\n * they are not present.\n */\n\nconst DEFAULT_ALGO = 'all';\n\nexport class Preprocessor {\n vectors: IVector[];\n\n constructor(vectors) {\n this.vectors = vectors;\n }\n\n /**\n * Returns an array of columns that are available in the vectors\n */\n getColumns() {\n const vector = this.vectors[0];\n return Object.keys(vector).filter((e) => e !== '__meta__');\n }\n\n /**\n * Returns a unique array of distinct line values.\n */\n distinctLines() {\n if (this.getColumns().includes('line')) {\n return [...new Set(this.vectors.map((vector) => vector.line))];\n }\n return [];\n }\n\n /**\n * Infers the multiplicity attribute for this dataset.\n */\n inferMultiplicity() {\n if (this.getColumns().includes('multiplicity') || !this.getColumns().includes('x') || !this.getColumns().includes('y')) {\n return;\n }\n\n let distinctLines = this.distinctLines();\n\n if (distinctLines.length > 0) {\n // Build line pools\n const linePools = {};\n this.distinctLines().forEach((line) => {\n // Dictionary holding the x/y values of the line\n linePools[line] = {};\n });\n\n // Builds x attributes for linepools\n this.vectors.forEach((vector) => {\n linePools[vector.line][vector.x] = {};\n });\n\n distinctLines = this.distinctLines();\n // Count multiplicities\n this.vectors.forEach((vector) => {\n distinctLines.forEach((line) => {\n if (linePools[line][vector.x] != null) {\n if (linePools[line][vector.x][vector.y] == null) {\n linePools[line][vector.x][vector.y] = 1;\n } else {\n linePools[line][vector.x][vector.y] = linePools[line][vector.x][vector.y] + 1;\n }\n }\n });\n });\n\n // Apply multiplicities\n this.vectors.forEach((vector) => {\n vector.multiplicity = linePools[vector.line][vector.x][vector.y];\n });\n } else {\n const pool = {};\n this.vectors.forEach((sample) => {\n if (sample.x in pool) {\n if (sample.y in pool[sample.x]) {\n pool[sample.x][sample.y] = pool[sample.x][sample.y] + 1;\n } else {\n pool[sample.x][sample.y] = 1;\n }\n } else {\n const o = {};\n pool[sample.x] = o;\n o[sample.y] = 1;\n }\n });\n\n this.vectors.forEach((sample) => {\n sample.multiplicity = pool[sample.x][sample.y];\n });\n }\n }\n\n preprocess(ranges) {\n this.inferMultiplicity();\n\n const inferredColumns = [];\n\n const { vectors } = this;\n const header = Object.keys(vectors[0]);\n\n // If data contains no x and y attributes, its invalid\n if (header.includes('x') && header.includes('y')) {\n vectors.forEach((vector) => {\n vector.x = +vector.x;\n vector.y = +vector.y;\n });\n } else {\n inferredColumns.push('x');\n inferredColumns.push('y');\n // In case we are missing x and y columns, we can just generate a uniformly distributed point cloud\n vectors.forEach((vector) => {\n vector.x = (Math.random() - 0.5) * 100;\n vector.y = (Math.random() - 0.5) * 100;\n });\n }\n\n // If data contains no line attribute, add one\n if (header.includes('line') && !header.includes('age')) {\n const segs = {};\n const distinct = [...new Set(vectors.map((vector) => vector.line))];\n distinct.forEach((a) => {\n segs[a] = 0;\n });\n vectors.forEach((vector) => {\n // vector.age = segs[vector.line]\n segs[vector.line] = segs[vector.line] + 1;\n });\n const cur = {};\n distinct.forEach((a) => {\n cur[a] = 0;\n });\n vectors.forEach((vector) => {\n vector.age = cur[vector.line] / segs[vector.line];\n cur[vector.line] = cur[vector.line] + 1;\n });\n ranges.age = { min: 0, max: 1 };\n inferredColumns.push('age');\n }\n\n // If data has no algo attribute, add DEFAULT_ALGO\n if (!header.includes('algo')) {\n vectors.forEach((vector) => {\n vector.algo = DEFAULT_ALGO;\n });\n inferredColumns.push('algo');\n }\n\n vectors.forEach(function (d) {\n if ('age' in d) {\n d.age = +d.age;\n }\n });\n\n // If data has no cluster labels, add default ones\n if (!header.includes('groupLabel')) {\n vectors.forEach((vector) => {\n vector.groupLabel = [];\n });\n inferredColumns.push('groupLabel');\n } else {\n // Support multivariate points ... eg each groupLabel is actually an array\n vectors.forEach((vector) => {\n try {\n if (Number.isNaN(vector.groupLabel)) {\n // convert string to array\n vector.groupLabel = JSON.parse(vector.groupLabel as never);\n } else if ((vector.groupLabel as unknown) < 0) {\n vector.groupLabel = [];\n } else {\n vector.groupLabel = [vector.groupLabel];\n }\n } catch {\n // default is empty array\n vector.groupLabel = [];\n }\n });\n }\n\n return [ranges, inferredColumns];\n }\n}\n","export * from './InferCategory';\nexport * from './Preprocessor';\n","export function pointInHull(seat: { x: number; y: number }, points) {\n if (points.length <= 1) {\n return false;\n }\n\n let selected = false;\n\n let intercessionCount = 0;\n for (let index = 1; index < points.length; index++) {\n const start = points[index - 1];\n const end = points[index];\n\n // Testes\n\n //* ************************************************\n //* Adicionar teste bounding box intersection aqui *\n //* ************************************************\n\n const ray = { Start: { x: seat.x, y: seat.y }, End: { x: 99999, y: 0 } };\n const segment = { Start: start, End: end };\n const rayDistance = {\n x: ray.End.x - ray.Start.x,\n y: ray.End.y - ray.Start.y,\n };\n const segDistance = {\n x: segment.End.x - segment.Start.x,\n y: segment.End.y - segment.Start.y,\n };\n\n const rayLength = Math.sqrt(rayDistance.x ** 2 + rayDistance.y ** 2);\n const segLength = Math.sqrt(segDistance.x ** 2 + segDistance.y ** 2);\n\n if (rayDistance.x / rayLength === segDistance.x / segLength && rayDistance.y / rayLength === segDistance.y / segLength) {\n continue;\n }\n\n const T2 =\n (rayDistance.x * (segment.Start.y - ray.Start.y) + rayDistance.y * (ray.Start.x - segment.Start.x)) /\n (segDistance.x * rayDistance.y - segDistance.y * rayDistance.x);\n const T1 = (segment.Start.x + segDistance.x * T2 - ray.Start.x) / rayDistance.x;\n\n // Parametric check.\n if (T1 < 0) {\n continue;\n }\n if (T2 < 0 || T2 > 1) {\n continue;\n }\n if (Number.isNaN(T1)) {\n continue;\n } // rayDistance.X = 0\n\n intercessionCount++;\n }\n\n if (intercessionCount === 0) {\n selected = false;\n return selected;\n }\n if (intercessionCount & 1) {\n selected = true;\n } else {\n selected = false;\n }\n\n return selected;\n}\n","/* eslint-disable @typescript-eslint/naming-convention */\nimport * as d3v5 from 'd3v5';\nimport { v4 as uuidv4 } from 'uuid';\n// @ts-ignore\nimport clusterWorker from 'worker-loader?inline=no-fallback!../../workers/cluster.worker';\nimport { FeatureType, stringToFeatureType } from '../../../model/FeatureType';\nimport { DatasetType } from '../../../model/DatasetType';\nimport { IVector, AVector } from '../../../model/Vector';\nimport { InferCategory } from '../Data/InferCategory';\nimport { Preprocessor } from '../Data/Preprocessor';\nimport { Dataset, DefaultFeatureLabel } from '../../../model/Dataset';\nimport { Loader } from './Loader';\nimport { ICluster } from '../../../model/ICluster';\nimport { ObjectTypes } from '../../../model/ObjectType';\nimport { DatasetEntry } from '../../../model/DatasetEntry';\nimport { Profiler } from './Profiler';\n\nfunction convertFromCSV(vectors) {\n return vectors.map((vector) => {\n return AVector.create(vector);\n });\n}\n\nexport class CSVLoader implements Loader {\n vectors: IVector[];\n\n datasetType: DatasetType;\n\n resolvePath(entry: DatasetEntry, finished) {\n d3v5.csv(entry.path).then((vectors) => {\n this.vectors = convertFromCSV(vectors);\n this.datasetType = entry.type;\n\n this.resolve(finished, this.vectors, this.datasetType, entry);\n });\n }\n\n parseRange(str) {\n const range = str.match(/-?\\d+\\.?\\d*/g);\n return { min: range[0], max: range[1], inferred: true };\n }\n\n resolveContent(content, finished) {\n const vectors = convertFromCSV(d3v5.csvParse(content));\n this.resolveVectors(vectors, finished);\n }\n\n resolveVectors(vectors, finished) {\n this.vectors = convertFromCSV(vectors);\n this.datasetType = new InferCategory(this.vectors).inferType();\n\n this.resolve(finished, this.vectors, this.datasetType, { display: '', type: this.datasetType, path: '' });\n }\n\n getFeatureType(x) {\n if (typeof x === 'number' || !Number.isNaN(Number(x))) {\n return 'number';\n }\n if (`${new Date(x)}` !== 'Invalid Date') {\n return 'date';\n }\n return 'arbitrary';\n }\n\n getClusters(vectors: IVector[], callback) {\n // const worker = new Worker(new URL('../../workers/cluster.worker', import.meta.url));\n // eslint-disable-next-line new-cap\n const worker = new clusterWorker();\n\n worker.onmessage = (e) => {\n // Point clustering\n const clusters = new Array();\n Object.keys(e.data).forEach((k) => {\n const t = e.data[k];\n clusters.push({\n id: uuidv4(),\n objectType: ObjectTypes.Cluster,\n indices: t.points.map((i) => i.meshIndex),\n label: k,\n });\n });\n\n callback(clusters);\n };\n\n worker.postMessage({\n type: 'extract',\n message: vectors.map((vector) => [vector.x, vector.y, vector.groupLabel]),\n });\n }\n\n async resolve(finished, vectors, datasetType, entry: DatasetEntry, p_metaInformation?): Promise {\n const profiler = new Profiler();\n profiler.profile('start');\n\n const header = Object.keys(vectors[0]);\n\n profiler.profile('getting header');\n\n // TODO: really not used anymore, let it here for backwards compatibility\n // The correct way now is to supply it in the metadata json\n let ranges = header.reduce((map, value) => {\n const matches = value.match(/\\[-?\\d+\\.?\\d* *; *-?\\d+\\.?\\d* *;? *.*\\]/);\n if (matches != null) {\n const cutHeader = value.substring(0, value.length - matches[0].length);\n vectors.forEach((vector) => {\n vector[cutHeader] = vector[value];\n delete vector[value];\n });\n // header[header.indexOf(value)] = cutHeader\n map[cutHeader] = this.parseRange(matches[0]);\n }\n return map;\n }, {});\n\n profiler.profile('parse ranges');\n\n // Check for JSON header inside column, store it as key/value pair\n const metaInformation =\n p_metaInformation ||\n header.reduce((map, value) => {\n const json = value.match(/[{].*[}]/);\n if (json != null) {\n const cutHeader = value.substring(0, value.length - json[0].length);\n\n vectors.forEach((vector) => {\n vector[cutHeader] = vector[value];\n delete vector[value];\n });\n map[cutHeader] = JSON.parse(json[0]);\n } else {\n map[value] = { featureLabel: DefaultFeatureLabel };\n }\n return map;\n }, {});\n\n // Set the ranges from the domains\n for (const key in metaInformation) {\n const val = metaInformation[key];\n\n if (val.domain) {\n ranges[key] = { min: val.domain[0], max: val.domain[val.domain.length - 1], center: val.domain.length === 3 ? val.domain[1] : null };\n }\n }\n\n profiler.profile('Parse meta information');\n\n let index = 0;\n const types = {};\n\n // decide the type of each feature - categorical/quantitative/date\n header.forEach(() => {\n const current_key = Object.keys(metaInformation)[index];\n const col_meta = metaInformation[current_key];\n\n if (col_meta?.dtype) {\n // In case the datatype was specified in the JSON attribute, take it from there instead of inferring it\n types[current_key] = stringToFeatureType(col_meta.dtype);\n } else {\n // Infer the datatype of the feature from the first N rows\n const contains_number = {};\n const contains_date = {};\n const contains_arbitrary = {};\n\n vectors.forEach((r) => {\n const type = this.getFeatureType(r[current_key]);\n if (type === 'number') {\n contains_number[current_key] = true;\n } else if (type === 'date') {\n contains_date[current_key] = true;\n } else {\n contains_arbitrary[current_key] = true;\n }\n });\n\n if (contains_number[current_key] && !contains_date[current_key] && !contains_arbitrary[current_key]) {\n // only numbers -> quantitative type\n types[current_key] = FeatureType.Quantitative;\n } else if (!contains_number[current_key] && contains_date[current_key] && !contains_arbitrary[current_key]) {\n // only date -> date type\n types[current_key] = FeatureType.Date;\n } else {\n // otherwise categorical\n types[current_key] = FeatureType.Categorical;\n }\n }\n\n index++;\n });\n\n profiler.profile('Getting data types');\n\n // replace date features by their numeric timestamp equivalent\n // and fix all quantitative features to be numbers\n // list of filter headers for date\n const dateFeatures = [];\n const quantFeatures = [];\n for (const key in types) {\n if (types[key] === FeatureType.Date) {\n dateFeatures.push(key);\n } else if (types[key] === FeatureType.Quantitative) {\n quantFeatures.push(key);\n }\n }\n // for all rows\n for (let i = 0; i < vectors.length; i++) {\n // for all date features f\n dateFeatures.forEach((f) => {\n // overwrite sample with its timestamp\n vectors[i][f] = Date.parse(vectors[i][f]);\n });\n quantFeatures.forEach((f) => {\n // overwrite sample with its timestamp\n vectors[i][f] = +vectors[i][f];\n });\n }\n\n profiler.profile('Replace numerical values and dates');\n\n const preprocessor = new Preprocessor(vectors);\n let inferredColumns = [];\n const hasScalarTypes = header.includes('x') && header.includes('y');\n\n [ranges, inferredColumns] = preprocessor.preprocess(ranges);\n\n profiler.profile('Preprocessing');\n\n const dataset = new Dataset(vectors, ranges, { type: datasetType, path: entry.path }, types, metaInformation);\n\n dataset.hasInitialScalarTypes = hasScalarTypes;\n dataset.inferredColumns = inferredColumns;\n\n profiler.profile('Creating dataset');\n\n const promise = new Promise((resolve) => {\n this.getClusters(vectors, (clusters) => {\n dataset.clusters = clusters;\n\n // Reset cluster label after extraction\n dataset.vectors.forEach((vector) => {\n vector.groupLabel = [];\n });\n\n dataset.categories = dataset.extractEncodingFeatures();\n\n profiler.profile('Extract encoding features');\n\n resolve(dataset);\n\n // Backwards compatibility\n if (finished) {\n finished(dataset);\n }\n });\n });\n\n return promise;\n }\n}\n","import * as d3v5 from 'd3v5';\nimport { v4 as uuidv4 } from 'uuid';\nimport { Loader } from './Loader';\nimport { FeatureType } from '../../../model/FeatureType';\nimport { DatasetType } from '../../../model/DatasetType';\nimport { AVector, IVector } from '../../../model/Vector';\nimport { InferCategory } from '../Data/InferCategory';\nimport { Preprocessor } from '../Data/Preprocessor';\nimport { Dataset } from '../../../model/Dataset';\nimport { ICluster } from '../../../model/ICluster';\nimport { IEdge } from '../../../model/Edge';\nimport { ObjectTypes } from '../../../model/ObjectType';\n\nexport class JSONLoader implements Loader {\n vectors: IVector[];\n\n datasetType: DatasetType;\n\n resolvePath(entry: any, finished: any) {\n d3v5.json(entry.path).then((file) => this.resolve(file, finished, null, { path: '' }));\n }\n\n resolveContent(content: any, finished: any) {\n const file = JSON.parse(content);\n this.resolve(file, finished, null, { path: '' });\n }\n\n inferRangeForAttribute(key: string) {\n const values = this.vectors.map((sample) => sample[key]);\n let numeric = true;\n let min = Number.MAX_SAFE_INTEGER;\n let max = Number.MIN_SAFE_INTEGER;\n\n values.forEach((value) => {\n if (Number.isNaN(value)) {\n numeric = false;\n } else if (numeric) {\n if (value < min) {\n min = value;\n } else if (value > max) {\n max = value;\n }\n }\n });\n\n return numeric ? { min, max } : null;\n }\n\n parseRange(str) {\n const range = str.match(/-?\\d+\\.?\\d*/g);\n return { min: parseFloat(range[0]), max: parseFloat(range[1]), inferred: true };\n }\n\n getFeatureType(x) {\n if (typeof x === 'number' || !Number.isNaN(Number(x))) {\n return 'number';\n }\n if (`${new Date(x)}` !== 'Invalid Date') {\n return 'date';\n }\n return 'arbitrary';\n }\n\n async resolve(content, finished, datasetType, entry) {\n const fileSamples = content.samples[0];\n\n let ranges = {};\n\n // Parse predefined ranges\n fileSamples.columns.forEach((column, ci) => {\n const matches = column.match(/\\[-?\\d+\\.?\\d* *; *-?\\d+\\.?\\d*\\]/);\n if (matches) {\n const prefix = column.substring(0, column.length - matches[0].length);\n\n fileSamples.columns[ci] = prefix;\n ranges[prefix] = this.parseRange(matches[0]);\n }\n });\n\n this.vectors = [];\n fileSamples.data.forEach((row) => {\n const data = {};\n fileSamples.columns.forEach((column, ci) => {\n data[column] = row[ci];\n });\n this.vectors.push(AVector.create(data));\n });\n\n const header = Object.keys(this.vectors[0]);\n // infer for each feature whether it contains numeric, date, or arbitrary values\n const contains_number = {};\n const contains_date = {};\n const contains_arbitrary = {};\n this.vectors.forEach((r) => {\n header.forEach((f) => {\n const type = this.getFeatureType(r[f]);\n if (type === 'number') {\n contains_number[f] = true;\n } else if (type === 'date') {\n contains_date[f] = true;\n } else {\n contains_arbitrary[f] = true;\n }\n });\n });\n const types = {};\n // decide the type of each feature - categorical/quantitative/date\n header.forEach((f) => {\n if (contains_number[f] && !contains_date[f] && !contains_arbitrary[f]) {\n // only numbers -> quantitative type\n // (no way to tell if a feature of only numbers should be categorical, even if it is all integers)\n types[f] = FeatureType.Quantitative;\n } else if (!contains_number[f] && contains_date[f] && !contains_arbitrary[f]) {\n // only date -> date type\n types[f] = FeatureType.Date;\n } else {\n // otherwise categorical\n types[f] = FeatureType.Categorical;\n }\n });\n\n // replace date features by their numeric timestamp equivalent\n // and fix all quantitative features to be numbers\n // list of filter headers for date\n const dateFeatures = [];\n const quantFeatures = [];\n for (const key in types) {\n if (types[key] === FeatureType.Date) {\n dateFeatures.push(key);\n } else if (types[key] === FeatureType.Quantitative) {\n quantFeatures.push(key);\n }\n }\n // for all rows\n for (let i = 0; i < this.vectors.length; i++) {\n // for all date features f\n dateFeatures.forEach((f) => {\n // overwrite sample with its timestamp\n this.vectors[i][f] = Date.parse(this.vectors[i][f]);\n });\n quantFeatures.forEach((f) => {\n // overwrite sample with its timestamp\n this.vectors[i][f] = +this.vectors[i][f];\n });\n }\n\n this.datasetType = datasetType || new InferCategory(this.vectors).inferType();\n\n const clusters: ICluster[] = [];\n content.clusters[0].data.forEach((row) => {\n const nameIndex = content.clusters[0].columns.indexOf('name');\n\n clusters.push({\n id: uuidv4(),\n objectType: ObjectTypes.Cluster,\n label: row[0],\n name: nameIndex >= 0 ? row[nameIndex] : undefined,\n indices: row[1],\n });\n });\n\n const edges = [];\n content.edges[0].data.forEach((row) => {\n const nameIndex = content.edges[0].columns.indexOf('name');\n\n const edge: IEdge = {\n id: uuidv4(),\n source: clusters.findIndex((cluster) => cluster.label === row[1]).toString(),\n destination: clusters.findIndex((cluster) => cluster.label === row[2]).toString(),\n objectType: ObjectTypes.Edge,\n };\n\n if (nameIndex >= 0) {\n edge.name = row[nameIndex];\n }\n\n edges.push(edge);\n });\n\n let preselection = null as any[];\n let metaInformation;\n if ('preselection' in content) {\n preselection = content.preselection[0].data.flat();\n\n metaInformation = {};\n\n header.forEach((column) => {\n metaInformation[column] = {\n project: preselection.includes(column),\n };\n });\n }\n let inferredColumns = [];\n const preprocessor = new Preprocessor(this.vectors);\n const hasScalarTypes = header.includes('x') && header.includes('y');\n [ranges, inferredColumns] = preprocessor.preprocess(ranges);\n\n const dataset = new Dataset(this.vectors, ranges, { type: this.datasetType, path: entry.path }, types, metaInformation);\n dataset.hasInitialScalarTypes = hasScalarTypes;\n\n dataset.clusters = clusters;\n dataset.clusterEdges = edges;\n dataset.inferredColumns = inferredColumns;\n dataset.categories = dataset.extractEncodingFeatures();\n\n finished(dataset);\n }\n}\n","/**\n * Convenience class which helpts to provide timing statistics.\n */\nexport class Profiler {\n t0: number;\n\n count: number;\n\n constructor() {\n this.t0 = Date.now();\n this.count = 0;\n }\n\n profile(label: string) {\n this.count += 1;\n const t = Date.now();\n console.log(`${this.count} ${label}: ${(t - this.t0) / 1000}`);\n this.t0 = t;\n }\n}\n","export * from './CSVLoader';\nexport * from './JSONLoader';\nexport * from './Loader';\nexport * from './Profiler';\n","/* eslint-disable no-param-reassign */\nimport { v4 as uuidv4 } from 'uuid';\n\n/**\n * Base type for normalized dictionaries\n */\nexport type NormalizedDictionary = {\n byId: { [id: string]: T };\n allIds: string[];\n};\n\nexport const ANormalized = {\n create(): NormalizedDictionary {\n return {\n byId: {},\n allIds: [],\n };\n },\n\n /**\n * Adds a value to a normalized dictionary\n *\n * @param dict the normalized dictionary\n * @param value the value to add\n */\n add: (dict: NormalizedDictionary, value: T): string => {\n const handle = uuidv4();\n\n dict.byId[handle] = value;\n dict.allIds.push(handle);\n\n return handle;\n },\n\n /**\n * Deletes a value by ref from the normalized dictionary\n *\n * @param dict the normalized dictionary\n * @param value the value to remove\n */\n deleteByRef: (dict: NormalizedDictionary, value: T): string => {\n const entry = Object.entries(dict.byId).find(([, val]) => val === value);\n\n if (entry === undefined) {\n throw Error(\n `ANormalized.deleteByRef was called but the ref was not in the dictionary. This should never happen and suggests that the API was used wrong.`,\n );\n }\n\n const handle = entry[0];\n\n delete dict.byId[handle];\n dict.allIds.splice(dict.allIds.indexOf(handle), 1);\n\n return handle;\n },\n\n /**\n * Deletes a value by handle from the normalized dictionary\n *\n * @param dict the normalized dictionary\n * @param value the value to remove\n */\n delete: (dict: NormalizedDictionary, handle: string): string => {\n if (!(handle in dict.byId) || !dict.allIds.includes(handle)) {\n throw Error(`ANormalized.delete was called but the handle was not in the dictionary. This should never happen and suggests that the API was used wrong.`);\n }\n\n delete dict.byId[handle];\n dict.allIds.splice(dict.allIds.indexOf(handle), 1);\n\n return handle;\n },\n\n get: (dict: NormalizedDictionary, handle: string) => {\n if (handle === null || handle === undefined) {\n return undefined;\n }\n\n if (!(handle in dict.byId)) {\n throw Error(`ANormalized.get was called but the handle was not in the dictionary. This should never happen and suggests that the API was used wrong.`);\n }\n\n return dict.byId[handle];\n },\n\n entries: (dict: NormalizedDictionary) => {\n return dict.allIds.map((id) => [id, dict.byId[id]] as [string, T]);\n },\n\n forEach: (dict: NormalizedDictionary, callbackfn: (value: [string, T]) => void) => {\n return dict.allIds.forEach((id) => callbackfn([id, dict.byId[id]]));\n },\n\n map: (dict: NormalizedDictionary, callbackfn: (value: [string, T]) => any) => {\n return dict.allIds.map((id) => callbackfn([id, dict.byId[id]]));\n },\n\n filter: (dict: NormalizedDictionary, callbackfn: (value: [string, T]) => any) => {\n return dict.allIds.filter((id) => callbackfn([id, dict.byId[id]])).map((id) => [id, dict.byId[id]]);\n },\n};\n","/**\n * Advanced RenderingContext that takes into account a specific pixel ratio.\n */\nexport class RenderingContextEx {\n context: CanvasRenderingContext2D = null;\n\n pixelRatio = 1;\n\n constructor(context, pixelRatio) {\n this.context = context;\n this.pixelRatio = pixelRatio;\n }\n\n set lineWidth(value) {\n this.context.lineWidth = value;\n }\n\n set lineDashOffset(value) {\n this.context.lineDashOffset = value;\n }\n\n set strokeStyle(value) {\n this.context.strokeStyle = value;\n }\n\n set lineCap(value) {\n this.context.lineCap = value;\n }\n\n setLineDash(value) {\n this.context.setLineDash(value);\n }\n\n beginPath() {\n this.context.beginPath();\n }\n\n closePath() {\n this.context.closePath();\n }\n\n arc(x, y, radius, startAngle, endAngle, anticlockwise) {\n this.context.arc(x * this.pixelRatio, y * this.pixelRatio, radius * this.pixelRatio, startAngle, endAngle, anticlockwise);\n }\n\n lineTo(x, y) {\n this.context.lineTo(x * this.pixelRatio, y * this.pixelRatio);\n }\n\n arrowTo(fromX, fromY, toX, toY, headlen = 50) {\n const { lineCap } = this.context;\n this.lineCap = 'round';\n const dx = toX - fromX;\n const dy = toY - fromY;\n const angle = Math.atan2(dy, dx);\n this.lineTo(toX, toY);\n this.moveTo(toX, toY);\n this.lineTo(toX - headlen * Math.cos(angle - Math.PI / 6), toY - headlen * Math.sin(angle - Math.PI / 6));\n this.moveTo(toX, toY);\n this.lineTo(toX - headlen * Math.cos(angle + Math.PI / 6), toY - headlen * Math.sin(angle + Math.PI / 6));\n this.moveTo(toX, toY);\n this.lineCap = lineCap;\n }\n\n stroke() {\n this.context.stroke();\n }\n\n moveTo(x, y) {\n this.context.moveTo(x * this.pixelRatio, y * this.pixelRatio);\n }\n}\n","/**\n * Creates a scaler function\n *\n * @param range the range of the channel\n * @param minValue the minimum value of the mapping\n * @param maxValue the maximum value of the mapping\n */\nexport function createLinearRangeScaler(range: [number] | [number, number], minValue: number, maxValue: number) {\n if (minValue === maxValue) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n return (value: number) => {\n return range[0];\n };\n }\n return (value: number) => {\n return range[0] + (range[1] - range[0]) * ((value - minValue) / (maxValue - minValue));\n };\n}\n","import { arraysEqual } from '../WebGLView/UtilityFunctions';\n\nexport class AShallowSet {\n static indexOf(set: any[], value) {\n if (value instanceof Array) {\n return set.findIndex((e) => arraysEqual(e, value));\n }\n\n return set.indexOf(value);\n }\n\n static has(set: any[], value) {\n if (value instanceof Array) {\n return set.find((e) => arraysEqual(e, value));\n }\n\n return set.includes(value);\n }\n\n static create(values: any[]) {\n const set = [];\n\n values.forEach((element) => {\n if (AShallowSet.has(set, element)) {\n return;\n }\n\n set.push(element);\n });\n\n return set;\n }\n}\n","/**\n * @license\n *\n * Copyright 2019 Google LLC. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ==============================================================================\n */\n\n/**\n * This is a JavaScript reimplementation of UMAP (original license below), from\n * the python implementation found at https://github.com/lmcinnes/umap.\n *\n * @author andycoenen@google.com (Andy Coenen)\n */\n\n/**\n * @license\n * BSD 3-Clause License\n *\n * Copyright (c) 2017, Leland McInnes\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport { RandomFn } from './umap';\nimport * as utils from './utils';\n\nexport type Heap = number[][][];\n\n/**\n * Constructor for the heap objects. The heaps are used\n * for approximate nearest neighbor search, maintaining a list of potential\n * neighbors sorted by their distance. We also flag if potential neighbors\n * are newly added to the list or not. Internally this is stored as\n * a single array; the first axis determines whether we are looking at the\n * array of candidate indices, the array of distances, or the flag array for\n * whether elements are new or not. Each of these arrays are of shape\n * (``nPoints``, ``size``)\n */\nexport function makeHeap(nPoints: number, size: number): Heap {\n const makeArrays = (fillValue: number) => {\n return utils.empty(nPoints).map(() => {\n return utils.filled(size, fillValue);\n });\n };\n\n const heap: Heap = [];\n heap.push(makeArrays(-1));\n heap.push(makeArrays(Infinity));\n heap.push(makeArrays(0));\n return heap;\n}\n\n/**\n * Generate n_samples many integers from 0 to pool_size such that no\n * integer is selected twice. The duplication constraint is achieved via\n * rejection sampling.\n */\nexport function rejectionSample(nSamples: number, poolSize: number, random: RandomFn) {\n const result = utils.zeros(nSamples);\n for (let i = 0; i < nSamples; i++) {\n let rejectSample = true;\n let j = 0;\n while (rejectSample) {\n j = utils.tauRandInt(poolSize, random);\n let broken = false;\n for (let k = 0; k < i; k++) {\n if (j === result[k]) {\n broken = true;\n break;\n }\n }\n if (!broken) rejectSample = false;\n }\n result[i] = j;\n }\n return result;\n}\n\n/**\n * Push a new element onto the heap. The heap stores potential neighbors\n * for each data point. The ``row`` parameter determines which data point we\n * are addressing, the ``weight`` determines the distance (for heap sorting),\n * the ``index`` is the element to add, and the flag determines whether this\n * is to be considered a new addition.\n */\nexport function heapPush(heap: Heap, row: number, weight: number, index: number, flag: number): number {\n row = Math.floor(row);\n const indices = heap[0][row];\n const weights = heap[1][row];\n const isNew = heap[2][row];\n\n if (weight >= weights[0]) {\n return 0;\n }\n\n // Break if we already have this element.\n for (let i = 0; i < indices.length; i++) {\n if (index === indices[i]) {\n return 0;\n }\n }\n\n return uncheckedHeapPush(heap, row, weight, index, flag);\n}\n\n/**\n * Push a new element onto the heap. The heap stores potential neighbors\n * for each data point. The ``row`` parameter determines which data point we\n * are addressing, the ``weight`` determines the distance (for heap sorting),\n * the ``index`` is the element to add, and the flag determines whether this\n * is to be considered a new addition.\n */\nexport function uncheckedHeapPush(heap: Heap, row: number, weight: number, index: number, flag: number): number {\n const indices = heap[0][row];\n const weights = heap[1][row];\n const isNew = heap[2][row];\n\n if (weight >= weights[0]) {\n return 0;\n }\n\n // Insert val at position zero\n weights[0] = weight;\n indices[0] = index;\n isNew[0] = flag;\n\n // Descend the heap, swapping values until the max heap criterion is met\n let i = 0;\n let iSwap = 0;\n while (true) {\n const ic1 = 2 * i + 1;\n const ic2 = ic1 + 1;\n\n const heapShape2 = heap[0][0].length;\n if (ic1 >= heapShape2) {\n break;\n } else if (ic2 >= heapShape2) {\n if (weights[ic1] > weight) {\n iSwap = ic1;\n } else {\n break;\n }\n } else if (weights[ic1] >= weights[ic2]) {\n if (weight < weights[ic1]) {\n iSwap = ic1;\n } else {\n break;\n }\n } else if (weight < weights[ic2]) {\n iSwap = ic2;\n } else {\n break;\n }\n\n weights[i] = weights[iSwap];\n indices[i] = indices[iSwap];\n isNew[i] = isNew[iSwap];\n\n i = iSwap;\n }\n\n weights[i] = weight;\n indices[i] = index;\n isNew[i] = flag;\n return 1;\n}\n\n/**\n * Build a heap of candidate neighbors for nearest neighbor descent. For\n * each vertex the candidate neighbors are any current neighbors, and any\n * vertices that have the vertex as one of their nearest neighbors.\n */\nexport function buildCandidates(currentGraph: Heap, nVertices: number, nNeighbors: number, maxCandidates: number, random: RandomFn) {\n const candidateNeighbors = makeHeap(nVertices, maxCandidates);\n for (let i = 0; i < nVertices; i++) {\n for (let j = 0; j < nNeighbors; j++) {\n if (currentGraph[0][i][j] < 0) {\n continue;\n }\n const idx = currentGraph[0][i][j];\n const isn = currentGraph[2][i][j];\n const d = utils.tauRand(random);\n heapPush(candidateNeighbors, i, d, idx, isn);\n heapPush(candidateNeighbors, idx, d, i, isn);\n currentGraph[2][i][j] = 0;\n }\n }\n return candidateNeighbors;\n}\n\n/**\n * Given an array of heaps (of indices and weights), unpack the heap\n * out to give and array of sorted lists of indices and weights by increasing\n * weight. This is effectively just the second half of heap sort (the first\n * half not being required since we already have the data in a heap).\n */\nexport function deheapSort(heap: Heap) {\n const indices = heap[0];\n const weights = heap[1];\n\n for (let i = 0; i < indices.length; i++) {\n const indHeap = indices[i];\n const distHeap = weights[i];\n\n for (let j = 0; j < indHeap.length - 1; j++) {\n const indHeapIndex = indHeap.length - j - 1;\n const distHeapIndex = distHeap.length - j - 1;\n\n const temp1 = indHeap[0];\n indHeap[0] = indHeap[indHeapIndex];\n indHeap[indHeapIndex] = temp1;\n\n const temp2 = distHeap[0];\n distHeap[0] = distHeap[distHeapIndex];\n distHeap[distHeapIndex] = temp2;\n\n siftDown(distHeap, indHeap, distHeapIndex, 0);\n }\n }\n return { indices, weights };\n}\n\n/**\n * Restore the heap property for a heap with an out of place element\n * at position ``elt``. This works with a heap pair where heap1 carries\n * the weights and heap2 holds the corresponding elements.\n */\nfunction siftDown(heap1: number[], heap2: number[], ceiling: number, elt: number) {\n while (elt * 2 + 1 < ceiling) {\n const leftChild = elt * 2 + 1;\n const rightChild = leftChild + 1;\n let swap = elt;\n\n if (heap1[swap] < heap1[leftChild]) {\n swap = leftChild;\n }\n if (rightChild < ceiling && heap1[swap] < heap1[rightChild]) {\n swap = rightChild;\n }\n\n if (swap === elt) {\n break;\n } else {\n const temp1 = heap1[elt];\n heap1[elt] = heap1[swap];\n heap1[swap] = temp1;\n\n const temp2 = heap2[elt];\n heap2[elt] = heap2[swap];\n heap2[swap] = temp2;\n elt = swap;\n }\n }\n}\n\n/**\n * Search the heap for the smallest element that is still flagged.\n */\nexport function smallestFlagged(heap: Heap, row: number) {\n const ind = heap[0][row];\n const dist = heap[1][row];\n const flag = heap[2][row];\n\n let minDist = Infinity;\n let resultIndex = -1;\n\n for (let i = 0; i > ind.length; i++) {\n if (flag[i] === 1 && dist[i] < minDist) {\n minDist = dist[i];\n resultIndex = i;\n }\n }\n\n if (resultIndex >= 0) {\n flag[resultIndex] = 0;\n return Math.floor(ind[resultIndex]);\n }\n return -1;\n}\n","/**\n * @license\n *\n * Copyright 2019 Google LLC. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ==============================================================================\n */\n\nexport { UMAP } from './umap';\n","/**\n * @license\n *\n * Copyright 2019 Google LLC. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ==============================================================================\n */\n\nimport * as utils from './utils';\n\ntype Entry = { value: number; row: number; col: number };\n\n/**\n * Internal 2-dimensional sparse matrix class\n */\nexport class SparseMatrix {\n private entries = new Map();\n\n readonly nRows: number = 0;\n\n readonly nCols: number = 0;\n\n constructor(rows: number[], cols: number[], values: number[], dims: number[]) {\n if (rows.length !== cols.length || rows.length !== values.length) {\n throw new Error('rows, cols and values arrays must all have the same length');\n }\n\n // TODO: Assert that dims are legit.\n this.nRows = dims[0];\n this.nCols = dims[1];\n for (let i = 0; i < values.length; i++) {\n const row = rows[i];\n const col = cols[i];\n this.checkDims(row, col);\n const key = this.makeKey(row, col);\n this.entries.set(key, { value: values[i], row, col });\n }\n }\n\n private makeKey(row: number, col: number): string {\n return `${row}:${col}`;\n }\n\n private checkDims(row: number, col: number) {\n const withinBounds = row < this.nRows && col < this.nCols;\n if (!withinBounds) {\n throw new Error('row and/or col specified outside of matrix dimensions');\n }\n }\n\n set(row: number, col: number, value: number) {\n this.checkDims(row, col);\n const key = this.makeKey(row, col);\n if (!this.entries.has(key)) {\n this.entries.set(key, { value, row, col });\n } else {\n this.entries.get(key)!.value = value;\n }\n }\n\n get(row: number, col: number, defaultValue = 0) {\n this.checkDims(row, col);\n const key = this.makeKey(row, col);\n if (this.entries.has(key)) {\n return this.entries.get(key)!.value;\n }\n return defaultValue;\n }\n\n getAll(ordered = true): { value: number; row: number; col: number }[] {\n const rowColValues: Entry[] = [];\n this.entries.forEach((value) => {\n rowColValues.push(value);\n });\n if (ordered) {\n // Ordering the result isn't required for processing but it does make it easier to write tests\n rowColValues.sort((a, b) => {\n if (a.row === b.row) {\n return a.col - b.col;\n }\n return a.row - b.row;\n });\n }\n return rowColValues;\n }\n\n getDims(): number[] {\n return [this.nRows, this.nCols];\n }\n\n getRows(): number[] {\n return Array.from(this.entries, ([key, value]) => value.row);\n }\n\n getCols(): number[] {\n return Array.from(this.entries, ([key, value]) => value.col);\n }\n\n getValues(): number[] {\n return Array.from(this.entries, ([key, value]) => value.value);\n }\n\n forEach(fn: (value: number, row: number, col: number) => void): void {\n this.entries.forEach((value) => fn(value.value, value.row, value.col));\n }\n\n map(fn: (value: number, row: number, col: number) => number): SparseMatrix {\n const vals: number[] = [];\n this.entries.forEach((value) => {\n vals.push(fn(value.value, value.row, value.col));\n });\n const dims = [this.nRows, this.nCols];\n return new SparseMatrix(this.getRows(), this.getCols(), vals, dims);\n }\n\n toArray() {\n const rows: undefined[] = utils.empty(this.nRows);\n const output = rows.map(() => {\n return utils.zeros(this.nCols);\n });\n this.entries.forEach((value) => {\n output[value.row][value.col] = value.value;\n });\n return output;\n }\n}\n\n/**\n * Transpose a sparse matrix\n */\nexport function transpose(matrix: SparseMatrix): SparseMatrix {\n const cols: number[] = [];\n const rows: number[] = [];\n const vals: number[] = [];\n\n matrix.forEach((value, row, col) => {\n cols.push(row);\n rows.push(col);\n vals.push(value);\n });\n\n const dims = [matrix.nCols, matrix.nRows];\n return new SparseMatrix(rows, cols, vals, dims);\n}\n\n/**\n * Construct a sparse identity matrix\n */\nexport function identity(size: number[]): SparseMatrix {\n const [rows] = size;\n const matrix = new SparseMatrix([], [], [], size);\n for (let i = 0; i < rows; i++) {\n matrix.set(i, i, 1);\n }\n return matrix;\n}\n\n/**\n * Element-wise multiplication of two matrices\n */\nexport function pairwiseMultiply(a: SparseMatrix, b: SparseMatrix): SparseMatrix {\n return elementWise(a, b, (x, y) => x * y);\n}\n\n/**\n * Element-wise addition of two matrices\n */\nexport function add(a: SparseMatrix, b: SparseMatrix): SparseMatrix {\n return elementWise(a, b, (x, y) => x + y);\n}\n\n/**\n * Element-wise subtraction of two matrices\n */\nexport function subtract(a: SparseMatrix, b: SparseMatrix): SparseMatrix {\n return elementWise(a, b, (x, y) => x - y);\n}\n\n/**\n * Element-wise maximum of two matrices\n */\nexport function maximum(a: SparseMatrix, b: SparseMatrix): SparseMatrix {\n return elementWise(a, b, (x, y) => (x > y ? x : y));\n}\n\n/**\n * Scalar multiplication of two matrices\n */\nexport function multiplyScalar(a: SparseMatrix, scalar: number): SparseMatrix {\n return a.map((value: number) => {\n return value * scalar;\n });\n}\n\n/**\n * Returns a new matrix with zero entries removed.\n */\nexport function eliminateZeros(m: SparseMatrix) {\n const zeroIndices = new Set();\n const values = m.getValues();\n const rows = m.getRows();\n const cols = m.getCols();\n for (let i = 0; i < values.length; i++) {\n if (values[i] === 0) {\n zeroIndices.add(i);\n }\n }\n const removeByZeroIndex = (_, index: number) => !zeroIndices.has(index);\n const nextValues = values.filter(removeByZeroIndex);\n const nextRows = rows.filter(removeByZeroIndex);\n const nextCols = cols.filter(removeByZeroIndex);\n\n return new SparseMatrix(nextRows, nextCols, nextValues, m.getDims());\n}\n\nexport const enum NormType {\n max = 'max',\n l1 = 'l1',\n l2 = 'l2',\n}\n\n/**\n * Normalization of a sparse matrix.\n */\nexport function normalize(m: SparseMatrix, normType = NormType.l2) {\n const normFn = normFns[normType];\n\n const colsByRow = new Map();\n m.forEach((_, row, col) => {\n const cols = colsByRow.get(row) || [];\n cols.push(col);\n colsByRow.set(row, cols);\n });\n\n const nextMatrix = new SparseMatrix([], [], [], m.getDims());\n\n for (const row of colsByRow.keys()) {\n const cols = colsByRow.get(row)!.sort();\n\n const vals = cols.map((col) => m.get(row, col));\n const norm = normFn(vals);\n for (let i = 0; i < norm.length; i++) {\n nextMatrix.set(row, cols[i], norm[i]);\n }\n }\n\n return nextMatrix;\n}\n\n/**\n * Vector normalization functions\n */\ntype NormFns = { [key in NormType]: (v: number[]) => number[] };\nconst normFns: NormFns = {\n [NormType.max]: (xs: number[]) => {\n let max = -Infinity;\n for (let i = 0; i < xs.length; i++) {\n max = xs[i] > max ? xs[i] : max;\n }\n return xs.map((x) => x / max);\n },\n [NormType.l1]: (xs: number[]) => {\n let sum = 0;\n for (let i = 0; i < xs.length; i++) {\n sum += xs[i];\n }\n return xs.map((x) => x / sum);\n },\n [NormType.l2]: (xs: number[]) => {\n let sum = 0;\n for (let i = 0; i < xs.length; i++) {\n sum += xs[i] ** 2;\n }\n return xs.map((x) => Math.sqrt(x ** 2 / sum));\n },\n};\n\n/**\n * Helper function for element-wise operations.\n */\nfunction elementWise(a: SparseMatrix, b: SparseMatrix, op: (x: number, y: number) => number): SparseMatrix {\n const visited = new Set();\n const rows: number[] = [];\n const cols: number[] = [];\n const vals: number[] = [];\n\n const operate = (row: number, col: number) => {\n rows.push(row);\n cols.push(col);\n const nextValue = op(a.get(row, col), b.get(row, col));\n vals.push(nextValue);\n };\n\n const valuesA = a.getValues();\n const rowsA = a.getRows();\n const colsA = a.getCols();\n for (let i = 0; i < valuesA.length; i++) {\n const row = rowsA[i];\n const col = colsA[i];\n const key = `${row}:${col}`;\n visited.add(key);\n operate(row, col);\n }\n\n const valuesB = b.getValues();\n const rowsB = b.getRows();\n const colsB = b.getCols();\n for (let i = 0; i < valuesB.length; i++) {\n const row = rowsB[i];\n const col = colsB[i];\n const key = `${row}:${col}`;\n if (visited.has(key)) continue;\n operate(row, col);\n }\n\n const dims = [a.nRows, a.nCols];\n return new SparseMatrix(rows, cols, vals, dims);\n}\n\n/**\n * Helper function for getting data, indices, and inptr arrays from a sparse\n * matrix to follow csr matrix conventions. Super inefficient (and kind of\n * defeats the purpose of this convention) but a lot of the ported python tree\n * search logic depends on this data format.\n */\nexport function getCSR(x: SparseMatrix) {\n const entries: Entry[] = [];\n\n x.forEach((value, row, col) => {\n entries.push({ value, row, col });\n });\n\n entries.sort((a, b) => {\n if (a.row === b.row) {\n return a.col - b.col;\n }\n return a.row - b.row;\n });\n\n const indices: number[] = [];\n const values: number[] = [];\n const indptr: number[] = [];\n\n let currentRow = -1;\n for (let i = 0; i < entries.length; i++) {\n const { row, col, value } = entries[i];\n if (row !== currentRow) {\n currentRow = row;\n indptr.push(i);\n }\n indices.push(col);\n values.push(value);\n }\n\n return { indices, values, indptr };\n}\n","/**\n * @license\n *\n * Copyright 2019 Google LLC. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ==============================================================================\n */\n\n/**\n * This is a JavaScript reimplementation of UMAP (original license below), from\n * the python implementation found at https://github.com/lmcinnes/umap.\n *\n * @author andycoenen@google.com (Andy Coenen)\n */\n\n/**\n * @license\n * BSD 3-Clause License\n *\n * Copyright (c) 2017, Leland McInnes\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport * as heap from './heap';\nimport * as matrix from './matrix';\nimport * as tree from './tree';\nimport * as utils from './utils';\nimport { RandomFn, Vectors, DistanceFn } from './umap';\n\n/**\n * Create a version of nearest neighbor descent.\n */\nexport function makeNNDescent(distanceFn: DistanceFn, random: RandomFn) {\n return function nNDescent(\n data: Vectors,\n leafArray: Vectors,\n nNeighbors: number,\n nIters = 10,\n maxCandidates = 50,\n delta = 0.001,\n rho = 0.5,\n rpTreeInit = true,\n ) {\n const nVertices = data.length;\n const currentGraph = heap.makeHeap(data.length, nNeighbors);\n\n for (let i = 0; i < data.length; i++) {\n const indices = heap.rejectionSample(nNeighbors, data.length, random);\n for (let j = 0; j < indices.length; j++) {\n const d = distanceFn(data[i], data[indices[j]]);\n\n heap.heapPush(currentGraph, i, d, indices[j], 1);\n heap.heapPush(currentGraph, indices[j], d, i, 1);\n }\n }\n if (rpTreeInit) {\n for (let n = 0; n < leafArray.length; n++) {\n for (let i = 0; i < leafArray[n].length; i++) {\n if (leafArray[n][i] < 0) {\n break;\n }\n for (let j = i + 1; j < leafArray[n].length; j++) {\n if (leafArray[n][j] < 0) {\n break;\n }\n const d = distanceFn(data[leafArray[n][i]], data[leafArray[n][j]]);\n heap.heapPush(currentGraph, leafArray[n][i], d, leafArray[n][j], 1);\n heap.heapPush(currentGraph, leafArray[n][j], d, leafArray[n][i], 1);\n }\n }\n }\n }\n\n for (let n = 0; n < nIters; n++) {\n const candidateNeighbors = heap.buildCandidates(currentGraph, nVertices, nNeighbors, maxCandidates, random);\n\n let c = 0;\n for (let i = 0; i < nVertices; i++) {\n for (let j = 0; j < maxCandidates; j++) {\n const p = Math.floor(candidateNeighbors[0][i][j]);\n if (p < 0 || utils.tauRand(random) < rho) {\n continue;\n }\n for (let k = 0; k < maxCandidates; k++) {\n const q = Math.floor(candidateNeighbors[0][i][k]);\n const cj = candidateNeighbors[2][i][j];\n const ck = candidateNeighbors[2][i][k];\n if (q < 0 || (!cj && !ck)) {\n continue;\n }\n\n const d = distanceFn(data[p], data[q]);\n c += heap.heapPush(currentGraph, p, d, q, 1);\n c += heap.heapPush(currentGraph, q, d, p, 1);\n }\n }\n }\n if (c <= delta * nNeighbors * data.length) {\n break;\n }\n }\n const sorted = heap.deheapSort(currentGraph);\n return sorted;\n };\n}\n\nexport type InitFromRandomFn = (nNeighbors: number, data: Vectors, queryPoints: Vectors, _heap: heap.Heap, random: RandomFn) => void;\n\nexport type InitFromTreeFn = (_tree: tree.FlatTree, data: Vectors, queryPoints: Vectors, _heap: heap.Heap, random: RandomFn) => void;\n\nexport function makeInitializations(distanceFn: DistanceFn) {\n function initFromRandom(nNeighbors: number, data: Vectors, queryPoints: Vectors, _heap: heap.Heap, random: RandomFn) {\n for (let i = 0; i < queryPoints.length; i++) {\n const indices = utils.rejectionSample(nNeighbors, data.length, random);\n for (let j = 0; j < indices.length; j++) {\n if (indices[j] < 0) {\n continue;\n }\n const d = distanceFn(data[indices[j]], queryPoints[i]);\n heap.heapPush(_heap, i, d, indices[j], 1);\n }\n }\n }\n\n function initFromTree(_tree: tree.FlatTree, data: Vectors, queryPoints: Vectors, _heap: heap.Heap, random: RandomFn) {\n for (let i = 0; i < queryPoints.length; i++) {\n const indices = tree.searchFlatTree(queryPoints[i], _tree, random);\n\n for (let j = 0; j < indices.length; j++) {\n if (indices[j] < 0) {\n return;\n }\n const d = distanceFn(data[indices[j]], queryPoints[i]);\n heap.heapPush(_heap, i, d, indices[j], 1);\n }\n }\n }\n\n return { initFromRandom, initFromTree };\n}\n\nexport type SearchFn = (data: Vectors, graph: matrix.SparseMatrix, initialization: heap.Heap, queryPoints: Vectors) => heap.Heap;\n\nexport function makeInitializedNNSearch(distanceFn: DistanceFn) {\n return function nnSearchFn(data: Vectors, graph: matrix.SparseMatrix, initialization: heap.Heap, queryPoints: Vectors) {\n const { indices, indptr } = matrix.getCSR(graph);\n\n for (let i = 0; i < queryPoints.length; i++) {\n const tried = new Set(initialization[0][i]);\n while (true) {\n // Find smallest flagged vertex\n const vertex = heap.smallestFlagged(initialization, i);\n\n if (vertex === -1) {\n break;\n }\n const candidates = indices.slice(indptr[vertex], indptr[vertex + 1]);\n for (const candidate of candidates) {\n if (candidate === vertex || candidate === -1 || tried.has(candidate)) {\n continue;\n }\n const d = distanceFn(data[candidate], queryPoints[i]);\n heap.uncheckedHeapPush(initialization, i, d, candidate, 1);\n tried.add(candidate);\n }\n }\n }\n return initialization;\n };\n}\n\nexport function initializeSearch(\n forest: tree.FlatTree[],\n data: Vectors,\n queryPoints: Vectors,\n nNeighbors: number,\n initFromRandom: InitFromRandomFn,\n initFromTree: InitFromTreeFn,\n random: RandomFn,\n) {\n const results = heap.makeHeap(queryPoints.length, nNeighbors);\n initFromRandom(nNeighbors, data, queryPoints, results, random);\n if (forest) {\n for (const tree of forest) {\n initFromTree(tree, data, queryPoints, results, random);\n }\n }\n return results;\n}\n","/**\n * @license\n *\n * Copyright 2019 Google LLC. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ==============================================================================\n */\n\n/**\n * This is a JavaScript reimplementation of UMAP (original license below), from\n * the python implementation found at https://github.com/lmcinnes/umap.\n *\n * @author andycoenen@google.com (Andy Coenen)\n */\n\n/**\n * @license\n * BSD 3-Clause License\n *\n * Copyright (c) 2017, Leland McInnes\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport * as utils from './utils';\nimport { RandomFn, Vector, Vectors } from './umap';\n\n/**\n * Tree functionality for approximating nearest neighbors\n */\ninterface RandomProjectionTreeNode {\n isLeaf: boolean;\n indices?: number[];\n leftChild?: RandomProjectionTreeNode;\n rightChild?: RandomProjectionTreeNode;\n hyperplane?: number[];\n offset?: number;\n}\n\nexport class FlatTree {\n constructor(public hyperplanes: number[][], public offsets: number[], public children: number[][], public indices: number[][]) {}\n}\n\n/**\n * Build a random projection forest with ``nTrees``.\n */\nexport function makeForest(data: Vectors, nNeighbors: number, nTrees: number, random: RandomFn) {\n const leafSize = Math.max(10, nNeighbors);\n\n const trees = utils.range(nTrees).map((_, i) => makeTree(data, leafSize, i, random));\n const forest = trees.map((tree) => flattenTree(tree, leafSize));\n\n return forest;\n}\n\n/**\n * Construct a random projection tree based on ``data`` with leaves\n * of size at most ``leafSize``\n */\nfunction makeTree(data: Vectors, leafSize = 30, n: number, random: RandomFn): RandomProjectionTreeNode {\n const indices = utils.range(data.length);\n const tree = makeEuclideanTree(data, indices, leafSize, n, random);\n return tree;\n}\n\nfunction makeEuclideanTree(data: Vectors, indices: number[], leafSize = 30, q: number, random: RandomFn): RandomProjectionTreeNode {\n if (indices.length > leafSize) {\n const splitResults = euclideanRandomProjectionSplit(data, indices, random);\n const { indicesLeft, indicesRight, hyperplane, offset } = splitResults;\n\n const leftChild = makeEuclideanTree(data, indicesLeft, leafSize, q + 1, random);\n const rightChild = makeEuclideanTree(data, indicesRight, leafSize, q + 1, random);\n\n const node = { leftChild, rightChild, isLeaf: false, hyperplane, offset };\n return node;\n }\n const node = { indices, isLeaf: true };\n return node;\n}\n\n/**\n * Given a set of ``indices`` for data points from ``data``, create\n * a random hyperplane to split the data, returning two arrays indices\n * that fall on either side of the hyperplane. This is the basis for a\n * random projection tree, which simply uses this splitting recursively.\n * This particular split uses euclidean distance to determine the hyperplane\n * and which side each data sample falls on.\n */\nfunction euclideanRandomProjectionSplit(data: Vectors, indices: number[], random: RandomFn) {\n const dim = data[0].length;\n\n // Select two random points, set the hyperplane between them\n const leftIndex = utils.tauRandInt(indices.length, random);\n let rightIndex = utils.tauRandInt(indices.length, random);\n rightIndex += leftIndex === rightIndex ? 1 : 0;\n rightIndex %= indices.length;\n const left = indices[leftIndex];\n const right = indices[rightIndex];\n\n // Compute the normal vector to the hyperplane (the vector between the two\n // points) and the offset from the origin\n let hyperplaneOffset = 0;\n const hyperplaneVector = utils.zeros(dim);\n\n for (let i = 0; i < hyperplaneVector.length; i++) {\n hyperplaneVector[i] = data[left][i] - data[right][i];\n hyperplaneOffset -= (hyperplaneVector[i] * (data[left][i] + data[right][i])) / 2.0;\n }\n\n // For each point compute the margin (project into normal vector)\n // If we are on lower side of the hyperplane put in one pile, otherwise\n // put it in the other pile (if we hit hyperplane on the nose, flip a coin)\n let nLeft = 0;\n let nRight = 0;\n const side = utils.zeros(indices.length);\n for (let i = 0; i < indices.length; i++) {\n let margin = hyperplaneOffset;\n for (let d = 0; d < dim; d++) {\n margin += hyperplaneVector[d] * data[indices[i]][d];\n }\n if (margin === 0) {\n side[i] = utils.tauRandInt(2, random);\n if (side[i] === 0) {\n nLeft += 1;\n } else {\n nRight += 1;\n }\n } else if (margin > 0) {\n side[i] = 0;\n nLeft += 1;\n } else {\n side[i] = 1;\n nRight += 1;\n }\n }\n\n // Now that we have the counts, allocate arrays\n const indicesLeft = utils.zeros(nLeft);\n const indicesRight = utils.zeros(nRight);\n\n // Populate the arrays with indices according to which side they fell on\n nLeft = 0;\n nRight = 0;\n for (const i in utils.range(side.length)) {\n if (side[i] === 0) {\n indicesLeft[nLeft] = indices[i];\n nLeft += 1;\n } else {\n indicesRight[nRight] = indices[i];\n nRight += 1;\n }\n }\n\n return {\n indicesLeft,\n indicesRight,\n hyperplane: hyperplaneVector,\n offset: hyperplaneOffset,\n };\n}\n\nfunction flattenTree(tree: RandomProjectionTreeNode, leafSize: number) {\n const nNodes = numNodes(tree);\n const nLeaves = numLeaves(tree);\n\n // TODO: Verify that sparse code is not relevant...\n const hyperplanes = utils.range(nNodes).map(() => utils.zeros(tree.hyperplane ? tree.hyperplane.length : 0));\n\n const offsets = utils.zeros(nNodes);\n const children = utils.range(nNodes).map(() => [-1, -1]);\n const indices = utils.range(nLeaves).map(() => utils.range(leafSize).map(() => -1));\n recursiveFlatten(tree, hyperplanes, offsets, children, indices, 0, 0);\n return new FlatTree(hyperplanes, offsets, children, indices);\n}\n\nfunction recursiveFlatten(\n tree: RandomProjectionTreeNode,\n hyperplanes: number[][],\n offsets: number[],\n children: number[][],\n indices: number[][],\n nodeNum: number,\n leafNum: number,\n): { nodeNum: number; leafNum: number } {\n if (tree.isLeaf) {\n children[nodeNum][0] = -leafNum;\n\n // TODO: Triple check this operation corresponds to\n // indices[leafNum : tree.indices.shape[0]] = tree.indices\n indices[leafNum].splice(0, tree.indices!.length, ...tree.indices!);\n leafNum += 1;\n return { nodeNum, leafNum };\n }\n hyperplanes[nodeNum] = tree.hyperplane!;\n offsets[nodeNum] = tree.offset!;\n children[nodeNum][0] = nodeNum + 1;\n const oldNodeNum = nodeNum;\n\n let res = recursiveFlatten(tree.leftChild!, hyperplanes, offsets, children, indices, nodeNum + 1, leafNum);\n nodeNum = res.nodeNum;\n leafNum = res.leafNum;\n\n children[oldNodeNum][1] = nodeNum + 1;\n\n res = recursiveFlatten(tree.rightChild!, hyperplanes, offsets, children, indices, nodeNum + 1, leafNum);\n return { nodeNum: res.nodeNum, leafNum: res.leafNum };\n}\n\nfunction numNodes(tree: RandomProjectionTreeNode): number {\n if (tree.isLeaf) {\n return 1;\n }\n return 1 + numNodes(tree.leftChild!) + numNodes(tree.rightChild!);\n}\n\nfunction numLeaves(tree: RandomProjectionTreeNode): number {\n if (tree.isLeaf) {\n return 1;\n }\n return numLeaves(tree.leftChild!) + numLeaves(tree.rightChild!);\n}\n\n/**\n * Generate an array of sets of candidate nearest neighbors by\n * constructing a random projection forest and taking the leaves of all the\n * trees. Any given tree has leaves that are a set of potential nearest\n * neighbors. Given enough trees the set of all such leaves gives a good\n * likelihood of getting a good set of nearest neighbors in composite. Since\n * such a random projection forest is inexpensive to compute, this can be a\n * useful means of seeding other nearest neighbor algorithms.\n */\nexport function makeLeafArray(rpForest: FlatTree[]): number[][] {\n if (rpForest.length > 0) {\n const output: number[][] = [];\n for (const tree of rpForest) {\n output.push(...tree.indices!);\n }\n return output;\n }\n return [[-1]];\n}\n\n/**\n * Selects the side of the tree to search during flat tree search.\n */\nfunction selectSide(hyperplane: number[], offset: number, point: Vector, random: RandomFn) {\n let margin = offset;\n for (let d = 0; d < point.length; d++) {\n margin += hyperplane[d] * point[d];\n }\n\n if (margin === 0) {\n const side = utils.tauRandInt(2, random);\n return side;\n }\n if (margin > 0) {\n return 0;\n }\n return 1;\n}\n\n/**\n * Searches a flattened rp-tree for a point.\n */\nexport function searchFlatTree(point: Vector, tree: FlatTree, random: RandomFn) {\n let node = 0;\n while (tree.children[node][0] > 0) {\n const side = selectSide(tree.hyperplanes[node], tree.offsets[node], point, random);\n if (side === 0) {\n node = tree.children[node][0];\n } else {\n node = tree.children[node][1];\n }\n }\n\n const index = -1 * tree.children[node][0];\n return tree.indices[index];\n}\n","/**\n * @license\n *\n * Copyright 2019 Google LLC. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ==============================================================================\n */\n\n/**\n * This is a JavaScript reimplementation of UMAP (original license below), from\n * the python implementation found at https://github.com/lmcinnes/umap.\n *\n * @author andycoenen@google.com (Andy Coenen)\n */\n\n/**\n * @license\n * BSD 3-Clause License\n *\n * Copyright (c) 2017, Leland McInnes\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\nimport LM from 'ml-levenberg-marquardt';\nimport * as heap from './heap';\nimport * as matrix from './matrix';\nimport * as nnDescent from './nn_descent';\nimport * as tree from './tree';\nimport * as utils from './utils';\nimport * as jaccard_dist from 'jaccard';\n\nexport type DistanceFn = (x: Vector, y: Vector) => number;\nexport type RandomFn = () => number;\nexport type EpochCallback = (epoch: number) => boolean | void;\nexport type Vector = number[];\nexport type Vectors = Vector[];\nexport const enum TargetMetric {\n categorical = 'categorical',\n l1 = 'l1',\n l2 = 'l2',\n}\n\nconst SMOOTH_K_TOLERANCE = 1e-5;\nconst MIN_K_DIST_SCALE = 1e-3;\n\nexport interface UMAPParameters {\n /**\n * The distance function with which to assess nearest neighbors, defaults\n * to euclidean distance.\n */\n distanceFn?: DistanceFn;\n /**\n * The initial learning rate for the embedding optimization.\n */\n learningRate?: number;\n /**\n * The local connectivity required -- i.e. the number of nearest\n * neighbors that should be assumed to be connected at a local level.\n * The higher this value the more connected the manifold becomes\n * locally. In practice this should be not more than the local intrinsic\n * dimension of the manifold.\n */\n localConnectivity?: number;\n /**\n * The effective minimum distance between embedded points. Smaller values\n * will result in a more clustered/clumped embedding where nearby points\n * on the manifold are drawn closer together, while larger values will\n * result on a more even dispersal of points. The value should be set\n * relative to the ``spread`` value, which determines the scale at which\n * embedded points will be spread out.\n */\n minDist?: number;\n /**\n * The dimension of the space to embed into. This defaults to 2 to\n * provide easy visualization, but can reasonably be set to any\n * integer value in the range 2 to 100.\n */\n nComponents?: number;\n /**\n * The number of training epochs to be used in optimizing the\n * low dimensional embedding. Larger values result in more accurate\n * embeddings. If None is specified a value will be selected based on\n * the size of the input dataset (200 for large datasets, 500 for small).\n */\n nEpochs?: number;\n /**\n * The size of local neighborhood (in terms of number of neighboring\n * sample points) used for manifold approximation. Larger values\n * result in more global views of the manifold, while smaller\n * values result in more local data being preserved. In general\n * values should be in the range 2 to 100.\n */\n nNeighbors?: number;\n /**\n * The number of negative samples to select per positive sample\n * in the optimization process. Increasing this value will result\n * in greater repulsive force being applied, greater optimization\n * cost, but slightly more accuracy.\n */\n negativeSampleRate?: number;\n /**\n * Weighting applied to negative samples in low dimensional embedding\n * optimization. Values higher than one will result in greater weight\n * being given to negative samples.\n */\n repulsionStrength?: number;\n /**\n * The pseudo-random number generator used by the stochastic parts of the\n * algorithm.\n */\n random?: RandomFn;\n /**\n * Interpolate between (fuzzy) union and intersection as the set operation\n * used to combine local fuzzy simplicial sets to obtain a global fuzzy\n * simplicial sets. Both fuzzy set operations use the product t-norm.\n * The value of this parameter should be between 0.0 and 1.0; a value of\n * 1.0 will use a pure fuzzy union, while 0.0 will use a pure fuzzy\n * intersection.\n */\n setOpMixRatio?: number;\n /**\n * The effective scale of embedded points. In combination with ``min_dist``\n * this determines how clustered/clumped the embedded points are.\n */\n spread?: number;\n /**\n * For transform operations (embedding new points using a trained model)\n * this will control how aggressively to search for nearest neighbors.\n * Larger values will result in slower performance but more accurate\n * nearest neighbor evaluation.\n */\n transformQueueSize?: number;\n}\n\nexport interface UMAPSupervisedParams {\n /**\n * The metric used to measure distance for a target array is using supervised\n * dimension reduction. By default this is 'categorical' which will measure\n * distance in terms of whether categories match or are different. Furthermore,\n * if semi-supervised is required target values of -1 will be treated as\n * unlabelled under the 'categorical' metric. If the target array takes\n * continuous values (e.g. for a regression problem) then metric of 'l1'\n * or 'l2' is probably more appropriate.\n */\n targetMetric?: TargetMetric;\n /**\n * Weighting factor between data topology and target topology. A value of\n * 0.0 weights entirely on data, a value of 1.0 weights entirely on target.\n * The default of 0.5 balances the weighting equally between data and target.\n */\n targetWeight?: number;\n /**\n * The number of nearest neighbors to use to construct the target simplcial\n * set. Defaults to the `nearestNeighbors` parameter.\n */\n targetNNeighbors?: number;\n}\n\n/**\n * UMAP projection system, based on the python implementation from McInnes, L,\n * Healy, J, UMAP: Uniform Manifold Approximation and Projection for Dimension\n * Reduction (https://github.com/lmcinnes/umap).\n *\n * This implementation differs in a few regards:\n * a) The initialization of the embedding for optimization is not computed using\n * a spectral method, rather it is initialized randomly. This avoids some\n * computationally intensive matrix eigen computations that aren't easily\n * ported to JavaScript.\n * b) A lot of \"extra\" functionality has been omitted from this implementation,\n * most notably a great deal of alternate distance functions.\n *\n * This implementation provides three methods of reducing dimensionality:\n * 1) fit: fit the data synchronously\n * 2) fitAsync: fit the data asynchronously, with a callback function provided\n * that is invoked on each optimization step.\n * 3) initializeFit / step: manually initialize the algorithm then explictly\n * step through each epoch of the SGD optimization\n */\nexport class UMAP {\n private learningRate = 1.0;\n\n private localConnectivity = 1.0;\n\n private minDist = 0.1;\n\n private nComponents = 2;\n\n private nEpochs = 0;\n\n private nNeighbors = 15;\n\n private negativeSampleRate = 5;\n\n private random = Math.random;\n\n private repulsionStrength = 1.0;\n\n private setOpMixRatio = 1.0;\n\n private spread = 1.0;\n\n private transformQueueSize = 4.0;\n\n // Supervised projection params\n private targetMetric = TargetMetric.categorical;\n\n private targetWeight = 0.5;\n\n private targetNNeighbors = this.nNeighbors;\n\n private distanceFn: DistanceFn = euclidean;\n\n // KNN state (can be precomputed and supplied via initializeFit)\n private knnIndices?: number[][];\n\n private knnDistances?: number[][];\n\n // Internal graph connectivity representation\n private graph!: matrix.SparseMatrix;\n\n private X!: Vectors;\n\n private isInitialized = false;\n\n private rpForest: tree.FlatTree[] = [];\n\n private initFromRandom!: nnDescent.InitFromRandomFn;\n\n private initFromTree!: nnDescent.InitFromTreeFn;\n\n private search!: nnDescent.SearchFn;\n\n private searchGraph!: matrix.SparseMatrix;\n\n // Supervised projection labels / targets\n private Y?: number[];\n\n // Projected embedding\n private embedding: number[][] = [];\n\n private optimizationState = new OptimizationState();\n\n constructor(params: UMAPParameters = {}) {\n const setParam = (key: string) => {\n if (params[key] !== undefined) this[key] = params[key];\n };\n\n setParam('distanceFn');\n setParam('learningRate');\n setParam('localConnectivity');\n setParam('minDist');\n setParam('nComponents');\n setParam('nEpochs');\n setParam('nNeighbors');\n setParam('negativeSampleRate');\n setParam('random');\n setParam('repulsionStrength');\n setParam('setOpMixRatio');\n setParam('spread');\n setParam('transformQueueSize');\n }\n\n /**\n * Fit the data to a projected embedding space synchronously.\n */\n fit(X: Vectors, initialEmbedding: any) {\n this.initializeFit(X, initialEmbedding);\n this.optimizeLayout();\n\n return this.embedding;\n }\n\n /**\n * Fit the data to a projected embedding space asynchronously, with a callback\n * function invoked on every epoch of optimization.\n */\n async fitAsync(X: Vectors, initialEmbedding: any, callback: (epochNumber: number) => void | boolean = () => true) {\n this.initializeFit(X, initialEmbedding);\n\n await this.optimizeLayoutAsync(callback);\n return this.embedding;\n }\n\n /**\n * Initializes parameters needed for supervised projection.\n */\n setSupervisedProjection(Y: number[], params: UMAPSupervisedParams = {}) {\n this.Y = Y;\n this.targetMetric = params.targetMetric || this.targetMetric;\n this.targetWeight = params.targetWeight || this.targetWeight;\n this.targetNNeighbors = params.targetNNeighbors || this.targetNNeighbors;\n }\n\n /**\n * Initializes umap with precomputed KNN indices and distances.\n */\n setPrecomputedKNN(knnIndices: number[][], knnDistances: number[][]) {\n this.knnIndices = knnIndices;\n this.knnDistances = knnDistances;\n }\n\n /**\n * Initializes fit by computing KNN and a fuzzy simplicial set, as well as\n * initializing the projected embeddings. Sets the optimization state ahead\n * of optimization steps. Returns the number of epochs to be used for the\n * SGD optimization.\n */\n initializeFit(X: Vectors, initialEmbedding: any): number {\n if (X.length <= this.nNeighbors) {\n throw new Error(`Not enough data points (${X.length}) to create nNeighbors: ${this.nNeighbors}. Add more data points or adjust the configuration.`);\n }\n\n // We don't need to reinitialize if we've already initialized for this data.\n if (this.X === X && this.isInitialized) {\n return this.getNEpochs();\n }\n\n this.X = X;\n\n if (!this.knnIndices && !this.knnDistances) {\n const knnResults = this.nearestNeighbors(X);\n this.knnIndices = knnResults.knnIndices;\n this.knnDistances = knnResults.knnDistances;\n }\n\n this.graph = this.fuzzySimplicialSet(X, this.nNeighbors, this.setOpMixRatio);\n\n // Set up the search graph for subsequent transformation.\n this.makeSearchFns();\n this.searchGraph = this.makeSearchGraph(X);\n\n // Check if supervised projection, then adjust the graph.\n this.processGraphForSupervisedProjection();\n\n const { head, tail, epochsPerSample } = this.initializeSimplicialSetEmbedding(initialEmbedding);\n\n // Set the optimization routine state\n this.optimizationState.head = head;\n this.optimizationState.tail = tail;\n this.optimizationState.epochsPerSample = epochsPerSample;\n\n // Now, initialize the optimization steps\n this.initializeOptimization();\n this.prepareForOptimizationLoop();\n this.isInitialized = true;\n\n return this.getNEpochs();\n }\n\n private makeSearchFns() {\n const { initFromTree, initFromRandom } = nnDescent.makeInitializations(this.distanceFn);\n this.initFromTree = initFromTree;\n this.initFromRandom = initFromRandom;\n this.search = nnDescent.makeInitializedNNSearch(this.distanceFn);\n }\n\n private makeSearchGraph(X: Vectors) {\n const knnIndices = this.knnIndices!;\n const knnDistances = this.knnDistances!;\n const dims = [X.length, X.length];\n const searchGraph = new matrix.SparseMatrix([], [], [], dims);\n for (let i = 0; i < knnIndices.length; i++) {\n const knn = knnIndices[i];\n const distances = knnDistances[i];\n for (let j = 0; j < knn.length; j++) {\n const neighbor = knn[j];\n const distance = distances[j];\n if (distance > 0) {\n searchGraph.set(i, neighbor, distance);\n }\n }\n }\n\n const transpose = matrix.transpose(searchGraph);\n return matrix.maximum(searchGraph, transpose);\n }\n\n /**\n * Transforms data to the existing embedding space.\n */\n transform(toTransform: Vectors) {\n // Use the previous rawData\n const rawData = this.X;\n if (rawData === undefined || rawData.length === 0) {\n throw new Error('No data has been fit.');\n }\n\n let nNeighbors = Math.floor(this.nNeighbors * this.transformQueueSize);\n nNeighbors = Math.min(rawData.length, nNeighbors);\n const init = nnDescent.initializeSearch(this.rpForest, rawData, toTransform, nNeighbors, this.initFromRandom, this.initFromTree, this.random);\n\n const result = this.search(rawData, this.searchGraph, init, toTransform);\n\n let { indices, weights: distances } = heap.deheapSort(result);\n\n indices = indices.map((x) => x.slice(0, this.nNeighbors));\n distances = distances.map((x) => x.slice(0, this.nNeighbors));\n\n const adjustedLocalConnectivity = Math.max(0, this.localConnectivity - 1);\n const { sigmas, rhos } = this.smoothKNNDistance(distances, this.nNeighbors, adjustedLocalConnectivity);\n\n const { rows, cols, vals } = this.computeMembershipStrengths(indices, distances, sigmas, rhos);\n\n const size = [toTransform.length, rawData.length];\n let graph = new matrix.SparseMatrix(rows, cols, vals, size);\n\n // This was a very specially constructed graph with constant degree.\n // That lets us do fancy unpacking by reshaping the csr matrix indices\n // and data. Doing so relies on the constant degree assumption!\n\n const normed = matrix.normalize(graph, matrix.NormType.l1);\n\n const csrMatrix = matrix.getCSR(normed);\n const nPoints = toTransform.length;\n\n const eIndices = utils.reshape2d(csrMatrix.indices, nPoints, this.nNeighbors);\n\n const eWeights = utils.reshape2d(csrMatrix.values, nPoints, this.nNeighbors);\n\n const embedding = initTransform(eIndices, eWeights, this.embedding);\n\n const nEpochs = this.nEpochs ? this.nEpochs / 3 : graph.nRows <= 10000 ? 100 : 30;\n\n const graphMax = graph.getValues().reduce((max, val) => (val > max ? val : max), 0);\n graph = graph.map((value) => (value < graphMax / nEpochs ? 0 : value));\n graph = matrix.eliminateZeros(graph);\n\n const epochsPerSample = this.makeEpochsPerSample(graph.getValues(), nEpochs);\n const head = graph.getRows();\n const tail = graph.getCols();\n\n // Initialize optimization slightly differently than the fit method.\n this.assignOptimizationStateParameters({\n headEmbedding: embedding,\n tailEmbedding: this.embedding,\n head,\n tail,\n currentEpoch: 0,\n nEpochs,\n nVertices: graph.getDims()[1],\n epochsPerSample,\n });\n this.prepareForOptimizationLoop();\n\n return this.optimizeLayout();\n }\n\n /**\n * Checks if we're using supervised projection, then process the graph\n * accordingly.\n */\n private processGraphForSupervisedProjection() {\n const { Y, X } = this;\n if (Y) {\n if (Y.length !== X.length) {\n throw new Error('Length of X and y must be equal');\n }\n\n if (this.targetMetric === TargetMetric.categorical) {\n const lt = this.targetWeight < 1.0;\n const farDist = lt ? 2.5 * (1.0 / (1.0 - this.targetWeight)) : 1.0e12;\n this.graph = this.categoricalSimplicialSetIntersection(this.graph, Y, farDist);\n }\n // TODO (andycoenen@): add non-categorical supervised embeddings.\n }\n }\n\n /**\n * Manually step through the optimization process one epoch at a time.\n */\n step() {\n const { currentEpoch } = this.optimizationState;\n\n if (currentEpoch < this.getNEpochs()) {\n this.optimizeLayoutStep(currentEpoch);\n }\n return this.optimizationState.currentEpoch;\n }\n\n /**\n * Returns the computed projected embedding.\n */\n getEmbedding() {\n return this.embedding;\n }\n\n /**\n * Compute the ``nNeighbors`` nearest points for each data point in ``X``\n * This may be exact, but more likely is approximated via nearest neighbor\n * descent.\n */\n private nearestNeighbors(X: Vectors) {\n const { distanceFn, nNeighbors } = this;\n const log2 = (n: number) => Math.log(n) / Math.log(2);\n const metricNNDescent = nnDescent.makeNNDescent(distanceFn, this.random);\n\n // Handle python3 rounding down from 0.5 discrpancy\n const round = (n: number) => {\n return n === 0.5 ? 0 : Math.round(n);\n };\n\n const nTrees = 5 + Math.floor(round(X.length ** 0.5 / 20.0));\n const nIters = Math.max(5, Math.floor(Math.round(log2(X.length))));\n\n this.rpForest = tree.makeForest(X, nNeighbors, nTrees, this.random);\n\n const leafArray = tree.makeLeafArray(this.rpForest);\n const { indices, weights } = metricNNDescent(X, leafArray, nNeighbors, nIters);\n return { knnIndices: indices, knnDistances: weights };\n }\n\n /**\n * Given a set of data X, a neighborhood size, and a measure of distance\n * compute the fuzzy simplicial set (here represented as a fuzzy graph in\n * the form of a sparse matrix) associated to the data. This is done by\n * locally approximating geodesic distance at each point, creating a fuzzy\n * simplicial set for each such point, and then combining all the local\n * fuzzy simplicial sets into a global one via a fuzzy union.\n */\n private fuzzySimplicialSet(X: Vectors, nNeighbors: number, setOpMixRatio = 1.0) {\n const { knnIndices = [], knnDistances = [], localConnectivity } = this;\n\n const { sigmas, rhos } = this.smoothKNNDistance(knnDistances, nNeighbors, localConnectivity);\n\n const { rows, cols, vals } = this.computeMembershipStrengths(knnIndices, knnDistances, sigmas, rhos);\n\n const size = [X.length, X.length];\n const sparseMatrix = new matrix.SparseMatrix(rows, cols, vals, size);\n\n const transpose = matrix.transpose(sparseMatrix);\n const prodMatrix = matrix.pairwiseMultiply(sparseMatrix, transpose);\n\n const a = matrix.subtract(matrix.add(sparseMatrix, transpose), prodMatrix);\n const b = matrix.multiplyScalar(a, setOpMixRatio);\n const c = matrix.multiplyScalar(prodMatrix, 1.0 - setOpMixRatio);\n const result = matrix.add(b, c);\n\n return result;\n }\n\n /**\n * Combine a fuzzy simplicial set with another fuzzy simplicial set\n * generated from categorical data using categorical distances. The target\n * data is assumed to be categorical label data (a vector of labels),\n * and this will update the fuzzy simplicial set to respect that label data.\n */\n private categoricalSimplicialSetIntersection(simplicialSet: matrix.SparseMatrix, target: number[], farDist: number, unknownDist = 1.0) {\n let intersection = fastIntersection(simplicialSet, target, unknownDist, farDist);\n intersection = matrix.eliminateZeros(intersection);\n return resetLocalConnectivity(intersection);\n }\n\n /**\n * Compute a continuous version of the distance to the kth nearest\n * neighbor. That is, this is similar to knn-distance but allows continuous\n * k values rather than requiring an integral k. In esscence we are simply\n * computing the distance such that the cardinality of fuzzy set we generate\n * is k.\n */\n private smoothKNNDistance(distances: Vectors, k: number, localConnectivity = 1.0, nIter = 64, bandwidth = 1.0) {\n const target = (Math.log(k) / Math.log(2)) * bandwidth;\n const rho = utils.zeros(distances.length);\n const result = utils.zeros(distances.length);\n\n for (let i = 0; i < distances.length; i++) {\n let lo = 0.0;\n let hi = Infinity;\n let mid = 1.0;\n\n // TODO: This is very inefficient, but will do for now. FIXME\n const ithDistances = distances[i];\n const nonZeroDists = ithDistances.filter((d) => d > 0.0);\n\n if (nonZeroDists.length >= localConnectivity) {\n const index = Math.floor(localConnectivity);\n const interpolation = localConnectivity - index;\n if (index > 0) {\n rho[i] = nonZeroDists[index - 1];\n if (interpolation > SMOOTH_K_TOLERANCE) {\n rho[i] += interpolation * (nonZeroDists[index] - nonZeroDists[index - 1]);\n }\n } else {\n rho[i] = interpolation * nonZeroDists[0];\n }\n } else if (nonZeroDists.length > 0) {\n rho[i] = utils.max(nonZeroDists);\n }\n\n for (let n = 0; n < nIter; n++) {\n let psum = 0.0;\n for (let j = 1; j < distances[i].length; j++) {\n const d = distances[i][j] - rho[i];\n if (d > 0) {\n psum += Math.exp(-(d / mid));\n } else {\n psum += 1.0;\n }\n }\n\n if (Math.abs(psum - target) < SMOOTH_K_TOLERANCE) {\n break;\n }\n\n if (psum > target) {\n hi = mid;\n mid = (lo + hi) / 2.0;\n } else {\n lo = mid;\n if (hi === Infinity) {\n mid *= 2;\n } else {\n mid = (lo + hi) / 2.0;\n }\n }\n }\n\n result[i] = mid;\n\n // TODO: This is very inefficient, but will do for now. FIXME\n if (rho[i] > 0.0) {\n const meanIthDistances = utils.mean(ithDistances);\n if (result[i] < MIN_K_DIST_SCALE * meanIthDistances) {\n result[i] = MIN_K_DIST_SCALE * meanIthDistances;\n }\n } else {\n const meanDistances = utils.mean(distances.map(utils.mean));\n if (result[i] < MIN_K_DIST_SCALE * meanDistances) {\n result[i] = MIN_K_DIST_SCALE * meanDistances;\n }\n }\n }\n\n return { sigmas: result, rhos: rho };\n }\n\n /**\n * Construct the membership strength data for the 1-skeleton of each local\n * fuzzy simplicial set -- this is formed as a sparse matrix where each row is\n * a local fuzzy simplicial set, with a membership strength for the\n * 1-simplex to each other data point.\n */\n private computeMembershipStrengths(\n knnIndices: Vectors,\n knnDistances: Vectors,\n sigmas: number[],\n rhos: number[],\n ): { rows: number[]; cols: number[]; vals: number[] } {\n const nSamples = knnIndices.length;\n const nNeighbors = knnIndices[0].length;\n\n const rows = utils.zeros(nSamples * nNeighbors);\n const cols = utils.zeros(nSamples * nNeighbors);\n const vals = utils.zeros(nSamples * nNeighbors);\n\n for (let i = 0; i < nSamples; i++) {\n for (let j = 0; j < nNeighbors; j++) {\n let val = 0;\n if (knnIndices[i][j] === -1) {\n continue; // We didn't get the full knn for i\n }\n if (knnIndices[i][j] === i) {\n val = 0.0;\n } else if (knnDistances[i][j] - rhos[i] <= 0.0) {\n val = 1.0;\n } else {\n val = Math.exp(-((knnDistances[i][j] - rhos[i]) / sigmas[i]));\n }\n\n rows[i * nNeighbors + j] = i;\n cols[i * nNeighbors + j] = knnIndices[i][j];\n vals[i * nNeighbors + j] = val;\n }\n }\n\n return { rows, cols, vals };\n }\n\n /**\n * Initialize a fuzzy simplicial set embedding, using a specified\n * initialisation method and then minimizing the fuzzy set cross entropy\n * between the 1-skeletons of the high and low dimensional fuzzy simplicial\n * sets.\n */\n private initializeSimplicialSetEmbedding(initialEmbedding: any) {\n const nEpochs = this.getNEpochs();\n\n const { nComponents } = this;\n const graphValues = this.graph.getValues();\n let graphMax = 0;\n for (let i = 0; i < graphValues.length; i++) {\n const value = graphValues[i];\n if (graphMax < graphValues[i]) {\n graphMax = value;\n }\n }\n\n const graph = this.graph.map((value) => {\n if (value < graphMax / nEpochs) {\n return 0;\n }\n return value;\n });\n\n // We're not computing the spectral initialization in this implementation\n // until we determine a better eigenvalue/eigenvector computation\n // approach\n if (initialEmbedding) {\n this.embedding = initialEmbedding;\n } else {\n this.embedding = utils.zeros(graph.nRows).map(() => {\n return utils.zeros(nComponents).map(() => {\n return utils.tauRand(this.random) * 20 + -10; // Random from -10 to 10\n });\n });\n }\n\n // Get graph data in ordered way...\n const weights: number[] = [];\n const head: number[] = [];\n const tail: number[] = [];\n const rowColValues = graph.getAll();\n for (let i = 0; i < rowColValues.length; i++) {\n const entry = rowColValues[i];\n if (entry.value) {\n weights.push(entry.value);\n tail.push(entry.row);\n head.push(entry.col);\n }\n }\n const epochsPerSample = this.makeEpochsPerSample(weights, nEpochs);\n\n return { head, tail, epochsPerSample };\n }\n\n /**\n * Given a set of weights and number of epochs generate the number of\n * epochs per sample for each weight.\n */\n private makeEpochsPerSample(weights: number[], nEpochs: number) {\n const result = utils.filled(weights.length, -1.0);\n const max = utils.max(weights);\n const nSamples = weights.map((w) => (w / max) * nEpochs);\n nSamples.forEach((n, i) => {\n if (n > 0) result[i] = nEpochs / nSamples[i];\n });\n return result;\n }\n\n /**\n * Assigns optimization state parameters from a partial optimization state.\n */\n private assignOptimizationStateParameters(state: Partial) {\n Object.assign(this.optimizationState, state);\n }\n\n /**\n * Sets a few optimization state parameters that are necessary before entering\n * the optimization step loop.\n */\n private prepareForOptimizationLoop() {\n // Hyperparameters\n const { repulsionStrength, learningRate, negativeSampleRate } = this;\n\n const { epochsPerSample, headEmbedding, tailEmbedding } = this.optimizationState;\n\n const dim = headEmbedding[0].length;\n const moveOther = headEmbedding.length === tailEmbedding.length;\n\n const epochsPerNegativeSample = epochsPerSample.map((e) => e / negativeSampleRate);\n const epochOfNextNegativeSample = [...epochsPerNegativeSample];\n const epochOfNextSample = [...epochsPerSample];\n\n this.assignOptimizationStateParameters({\n epochOfNextSample,\n epochOfNextNegativeSample,\n epochsPerNegativeSample,\n moveOther,\n initialAlpha: learningRate,\n alpha: learningRate,\n gamma: repulsionStrength,\n dim,\n });\n }\n\n /**\n * Initializes optimization state for stepwise optimization.\n */\n private initializeOptimization() {\n // Algorithm state\n const headEmbedding = this.embedding;\n const tailEmbedding = this.embedding;\n\n // Initialized in initializeSimplicialSetEmbedding()\n const { head, tail, epochsPerSample } = this.optimizationState;\n\n const nEpochs = this.getNEpochs();\n const nVertices = this.graph.nCols;\n\n const { a, b } = findABParams(this.spread, this.minDist);\n\n this.assignOptimizationStateParameters({\n headEmbedding,\n tailEmbedding,\n head,\n tail,\n epochsPerSample,\n a,\n b,\n nEpochs,\n nVertices,\n });\n }\n\n /**\n * Improve an embedding using stochastic gradient descent to minimize the\n * fuzzy set cross entropy between the 1-skeletons of the high dimensional\n * and low dimensional fuzzy simplicial sets. In practice this is done by\n * sampling edges based on their membership strength (with the (1-p) terms\n * coming from negative sampling similar to word2vec).\n */\n private optimizeLayoutStep(n: number) {\n const { optimizationState } = this;\n const {\n head,\n tail,\n headEmbedding,\n tailEmbedding,\n epochsPerSample,\n epochOfNextSample,\n epochOfNextNegativeSample,\n epochsPerNegativeSample,\n moveOther,\n initialAlpha,\n alpha,\n gamma,\n a,\n b,\n dim,\n nEpochs,\n nVertices,\n } = optimizationState;\n\n const clipValue = 4.0;\n\n for (let i = 0; i < epochsPerSample.length; i++) {\n if (epochOfNextSample[i] > n) {\n continue;\n }\n\n const j = head[i];\n const k = tail[i];\n\n const current = headEmbedding[j];\n const other = tailEmbedding[k];\n\n const distSquared = rDist(current, other);\n\n let gradCoeff = 0;\n if (distSquared > 0) {\n gradCoeff = -2.0 * a * b * distSquared ** (b - 1.0);\n gradCoeff /= a * distSquared ** b + 1.0;\n }\n\n for (let d = 0; d < dim; d++) {\n const gradD = clip(gradCoeff * (current[d] - other[d]), clipValue);\n current[d] += gradD * alpha;\n if (moveOther) {\n other[d] += -gradD * alpha;\n }\n }\n\n epochOfNextSample[i] += epochsPerSample[i];\n\n const nNegSamples = Math.floor((n - epochOfNextNegativeSample[i]) / epochsPerNegativeSample[i]);\n\n for (let p = 0; p < nNegSamples; p++) {\n const k = utils.tauRandInt(nVertices, this.random);\n const other = tailEmbedding[k];\n\n const distSquared = rDist(current, other);\n\n let gradCoeff = 0.0;\n if (distSquared > 0.0) {\n gradCoeff = 2.0 * gamma * b;\n gradCoeff /= (0.001 + distSquared) * (a * distSquared ** b + 1);\n } else if (j === k) {\n continue;\n }\n\n for (let d = 0; d < dim; d++) {\n let gradD = 4.0;\n if (gradCoeff > 0.0) {\n gradD = clip(gradCoeff * (current[d] - other[d]), clipValue);\n }\n current[d] += gradD * alpha;\n }\n }\n epochOfNextNegativeSample[i] += nNegSamples * epochsPerNegativeSample[i];\n }\n optimizationState.alpha = initialAlpha * (1.0 - n / nEpochs);\n\n optimizationState.currentEpoch += 1;\n return headEmbedding;\n }\n\n /**\n * Improve an embedding using stochastic gradient descent to minimize the\n * fuzzy set cross entropy between the 1-skeletons of the high dimensional\n * and low dimensional fuzzy simplicial sets. In practice this is done by\n * sampling edges based on their membership strength (with the (1-p) terms\n * coming from negative sampling similar to word2vec).\n */\n private optimizeLayoutAsync(epochCallback: (epochNumber: number) => void | boolean = () => true): Promise {\n return new Promise((resolve, reject) => {\n const step = async () => {\n try {\n const { nEpochs, currentEpoch } = this.optimizationState;\n this.embedding = this.optimizeLayoutStep(currentEpoch);\n const epochCompleted = this.optimizationState.currentEpoch;\n const shouldStop = epochCallback(epochCompleted) === false;\n const isFinished = epochCompleted === nEpochs;\n if (!shouldStop && !isFinished) {\n setTimeout(() => step(), 0);\n } else {\n return resolve(isFinished);\n }\n } catch (err) {\n reject(err);\n }\n };\n setTimeout(() => step(), 0);\n });\n }\n\n /**\n * Improve an embedding using stochastic gradient descent to minimize the\n * fuzzy set cross entropy between the 1-skeletons of the high dimensional\n * and low dimensional fuzzy simplicial sets. In practice this is done by\n * sampling edges based on their membership strength (with the (1-p) terms\n * coming from negative sampling similar to word2vec).\n */\n private optimizeLayout(epochCallback: (epochNumber: number) => void | boolean = () => true): Vectors {\n let isFinished = false;\n let embedding: Vectors = [];\n while (!isFinished) {\n const { nEpochs, currentEpoch } = this.optimizationState;\n embedding = this.optimizeLayoutStep(currentEpoch);\n const epochCompleted = this.optimizationState.currentEpoch;\n const shouldStop = epochCallback(epochCompleted) === false;\n isFinished = epochCompleted === nEpochs || shouldStop;\n }\n return embedding;\n }\n\n /**\n * Gets the number of epochs for optimizing the projection.\n * NOTE: This heuristic differs from the python version\n */\n private getNEpochs() {\n const { graph } = this;\n\n if (this.nEpochs > 0) {\n return this.nEpochs;\n }\n\n const length = graph.nRows;\n if (length <= 2500) {\n return 500;\n }\n if (length <= 5000) {\n return 400;\n }\n if (length <= 7500) {\n return 300;\n }\n return 200;\n }\n}\n\n// https://github.com/ecto/jaccard TODO: also for tsne and other projection methods\nexport function jaccard(x: Vector, y: Vector) {\n return jaccard_dist.index(x, y);\n}\n\nexport function euclidean(x: Vector, y: Vector) {\n let result = 0;\n for (let i = 0; i < x.length; i++) {\n result += (x[i] - y[i]) ** 2;\n }\n return Math.sqrt(result);\n}\n\nexport function cosine(x: Vector, y: Vector) {\n let result = 0.0;\n let normX = 0.0;\n let normY = 0.0;\n\n for (let i = 0; i < x.length; i++) {\n result += x[i] * y[i];\n normX += x[i] ** 2;\n normY += y[i] ** 2;\n }\n\n if (normX === 0 && normY === 0) {\n return 0;\n }\n if (normX === 0 || normY === 0) {\n return 1.0;\n }\n return 1.0 - result / Math.sqrt(normX * normY);\n}\n\n/**\n * An interface representing the optimization state tracked between steps of\n * the SGD optimization\n */\nclass OptimizationState {\n currentEpoch = 0;\n\n // Data tracked during optimization steps.\n headEmbedding: number[][] = [];\n\n tailEmbedding: number[][] = [];\n\n head: number[] = [];\n\n tail: number[] = [];\n\n epochsPerSample: number[] = [];\n\n epochOfNextSample: number[] = [];\n\n epochOfNextNegativeSample: number[] = [];\n\n epochsPerNegativeSample: number[] = [];\n\n moveOther = true;\n\n initialAlpha = 1.0;\n\n alpha = 1.0;\n\n gamma = 1.0;\n\n a = 1.5769434603113077;\n\n b = 0.8950608779109733;\n\n dim = 2;\n\n nEpochs = 500;\n\n nVertices = 0;\n}\n\n/**\n * Standard clamping of a value into a fixed range\n */\nfunction clip(x: number, clipValue: number) {\n if (x > clipValue) return clipValue;\n if (x < -clipValue) return -clipValue;\n return x;\n}\n\n/**\n * Reduced Euclidean distance.\n */\nfunction rDist(x: number[], y: number[]) {\n let result = 0.0;\n for (let i = 0; i < x.length; i++) {\n result += (x[i] - y[i]) ** 2;\n }\n return result;\n}\n\n/**\n * Fit a, b params for the differentiable curve used in lower\n * dimensional fuzzy simplicial complex construction. We want the\n * smooth curve (from a pre-defined family with simple gradient) that\n * best matches an offset exponential decay.\n */\nexport function findABParams(spread: number, minDist: number) {\n const curve =\n ([a, b]) =>\n (x: number) => {\n return 1.0 / (1.0 + a * x ** (2 * b));\n };\n\n const xv = utils.linear(0, spread * 3, 300).map((val) => (val < minDist ? 1.0 : val));\n\n const yv = utils.zeros(xv.length).map((val, index) => {\n const gte = xv[index] >= minDist;\n return gte ? Math.exp(-(xv[index] - minDist) / spread) : val;\n });\n\n const initialValues = [0.5, 0.5];\n const data = { x: xv, y: yv };\n\n // Default options for the algorithm (from github example)\n const options = {\n damping: 1.5,\n initialValues,\n gradientDifference: 10e-2,\n maxIterations: 100,\n errorTolerance: 10e-3,\n };\n\n const { parameterValues } = LM(data, curve, options);\n const [a, b] = parameterValues as number[];\n return { a, b };\n}\n\n/**\n * Under the assumption of categorical distance for the intersecting\n * simplicial set perform a fast intersection.\n */\nexport function fastIntersection(graph: matrix.SparseMatrix, target: number[], unknownDist = 1.0, farDist = 5.0) {\n return graph.map((value, row, col) => {\n if (target[row] === -1 || target[col] === -1) {\n return value * Math.exp(-unknownDist);\n }\n if (target[row] !== target[col]) {\n return value * Math.exp(-farDist);\n }\n return value;\n });\n}\n\n/**\n * Reset the local connectivity requirement -- each data sample should\n * have complete confidence in at least one 1-simplex in the simplicial set.\n * We can enforce this by locally rescaling confidences, and then remerging the\n * different local simplicial sets together.\n */\nexport function resetLocalConnectivity(simplicialSet: matrix.SparseMatrix) {\n simplicialSet = matrix.normalize(simplicialSet, matrix.NormType.max);\n const transpose = matrix.transpose(simplicialSet);\n const prodMatrix = matrix.pairwiseMultiply(transpose, simplicialSet);\n simplicialSet = matrix.add(simplicialSet, matrix.subtract(transpose, prodMatrix));\n return matrix.eliminateZeros(simplicialSet);\n}\n\n/**\n * Given indices and weights and an original embeddings\n * initialize the positions of new points relative to the\n * indices and weights (of their neighbors in the source data).\n */\nexport function initTransform(indices: number[][], weights: number[][], embedding: Vectors) {\n const result = utils.zeros(indices.length).map((z) => utils.zeros(embedding[0].length));\n\n for (let i = 0; i < indices.length; i++) {\n for (let j = 0; j < indices[0].length; j++) {\n for (let d = 0; d < embedding[0].length; d++) {\n const a = indices[i][j];\n result[i][d] += weights[i][j] * embedding[a][d];\n }\n }\n }\n return result;\n}\n","/**\n * @license\n *\n * Copyright 2019 Google LLC. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ==============================================================================\n */\n\nimport { RandomFn } from './umap';\n\n/**\n * Simple random integer function\n */\nexport function tauRandInt(n: number, random: RandomFn) {\n return Math.floor(random() * n);\n}\n\n/**\n * Simple random float function\n */\nexport function tauRand(random: RandomFn) {\n return random();\n}\n/**\n * Compute the (standard l2) norm of a vector.\n */\nexport function norm(vec: number[]) {\n let result = 0;\n for (const item of vec) {\n result += item ** 2;\n }\n return Math.sqrt(result);\n}\n\n/**\n * Creates an empty array (filled with undefined)\n */\nexport function empty(n: number): undefined[] {\n const output: undefined[] = [];\n for (let i = 0; i < n; i++) {\n output.push(undefined);\n }\n return output;\n}\n\n/**\n * Creates an array filled with index values\n */\nexport function range(n: number): number[] {\n return empty(n).map((_, i) => i);\n}\n\n/**\n * Creates an array filled with a specific value\n */\nexport function filled(n: number, v: number): number[] {\n return empty(n).map(() => v);\n}\n\n/**\n * Creates an array filled with zeros\n */\nexport function zeros(n: number): number[] {\n return filled(n, 0);\n}\n\n/**\n * Creates an array filled with ones\n */\nexport function ones(n: number): number[] {\n return filled(n, 1);\n}\n\n/**\n * Creates an array from a to b, of length len, inclusive\n */\nexport function linear(a: number, b: number, len: number): number[] {\n return empty(len).map((_, i) => {\n return a + i * ((b - a) / (len - 1));\n });\n}\n\n/**\n * Returns the sum of an array\n */\nexport function sum(input: number[]): number {\n return input.reduce((sum, val) => sum + val);\n}\n\n/**\n * Returns the mean of an array\n */\nexport function mean(input: number[]): number {\n return sum(input) / input.length;\n}\n\n/**\n * Returns the maximum value of an array\n */\nexport function max(input: number[]): number {\n let max = 0;\n for (let i = 0; i < input.length; i++) {\n max = input[i] > max ? input[i] : max;\n }\n return max;\n}\n\n/**\n * Returns the maximum value of a 2d array\n */\nexport function max2d(input: number[][]): number {\n let max = 0;\n for (let i = 0; i < input.length; i++) {\n for (let j = 0; j < input[i].length; j++) {\n max = input[i][j] > max ? input[i][j] : max;\n }\n }\n return max;\n}\n\n/**\n * Generate nSamples many integers from 0 to poolSize such that no\n * integer is selected twice. The duplication constraint is achieved via\n * rejection sampling.\n */\nexport function rejectionSample(nSamples: number, poolSize: number, random: RandomFn): number[] {\n const result = zeros(nSamples);\n for (let i = 0; i < nSamples; i++) {\n let rejectSample = true;\n while (rejectSample) {\n const j = tauRandInt(poolSize, random);\n let broken = false;\n for (let k = 0; k < i; k++) {\n if (j === result[k]) {\n broken = true;\n break;\n }\n }\n if (!broken) {\n rejectSample = false;\n }\n result[i] = j;\n }\n }\n return result;\n}\n\n/**\n * Reshapes a 1d array into a 2D of given dimensions.\n */\nexport function reshape2d(x: T[], a: number, b: number): T[][] {\n const rows: T[][] = [];\n let count = 0;\n let index = 0;\n\n if (x.length !== a * b) {\n throw new Error('Array dimensions must match input length.');\n }\n\n for (let i = 0; i < a; i++) {\n const col: T[] = [];\n for (let j = 0; j < b; j++) {\n col.push(x[index]);\n index += 1;\n }\n rows.push(col);\n count += 1;\n }\n return rows;\n}\n","/* eslint-disable no-param-reassign */\n/**\n * Directed graph library for javascript.\n */\n\nimport { createEntityAdapter } from '@reduxjs/toolkit';\nimport { v4 as uuidv4 } from 'uuid';\nimport { ICluster } from '../../model/ICluster';\nimport { Dataset } from '../../model/Dataset';\nimport { ObjectTypes } from '../../model/ObjectType';\nimport { IBook } from '../../model/Book';\nimport { IEdge } from '../../model/Edge';\nimport { clusterAdapter } from '../Ducks/StoriesDuck';\n\nconst edgeAdapter = createEntityAdapter({\n selectId: (edge) => edge.id,\n});\n\nexport function transformIndicesToHandles(clusterResult: ICluster[], edgeResult: IEdge[]) {\n const story: IBook = {\n id: uuidv4(),\n clusters: clusterAdapter.getInitialState(),\n edges: edgeAdapter.getInitialState(),\n };\n\n clusterResult.forEach((cluster, clusterIndex) => {\n const handle = clusterIndex.toString();\n\n story.clusters.entities[handle] = cluster;\n\n edgeResult.forEach((edge) => {\n if (edge.source === clusterIndex.toString()) {\n edge.source = handle;\n }\n if (edge.destination === clusterIndex.toString()) {\n edge.destination = handle;\n }\n });\n });\n\n edgeResult.forEach((edge, i) => {\n const handle = i;\n\n story.edges.entities[handle] = edge;\n });\n\n story.clusters.ids = Object.keys(story.clusters.entities);\n story.edges.ids = Object.keys(story.edges.entities);\n\n return story;\n}\n\n/**\n * Performs a basic path bundling algorithm and tries to extract\n * the most prominent edges between clusters.\n *\n * @param {Dataset} dataset the current dataset\n * @param {ICluster[]} clusters a list of clusters to perform the edge extraction\n */\nexport function graphLayout(dataset: Dataset, clusters: ICluster[]) {\n const edges: IEdge[] = [];\n\n // For each cluster,\n clusters.forEach((_, srcKey) => {\n const srcCluster = clusters[srcKey] as ICluster;\n clusters.forEach((_, dstKey) => {\n const dstCluster = clusters[dstKey] as ICluster;\n if (dstCluster !== srcCluster) {\n const bundle = [];\n\n // For each vector in source cluster, check if the direct ancestor is in the destination cluster\n srcCluster.indices\n .map((i) => dataset.vectors[i])\n .forEach((srcVec) => {\n if (\n dstCluster.indices\n .map((i) => dataset.vectors[i])\n .find((dstVec) => srcVec.line === dstVec.line && srcVec.__meta__.sequenceIndex + 1 === dstVec.__meta__.sequenceIndex)\n ) {\n bundle.push(srcVec.line);\n }\n });\n\n if (bundle.length > 10) {\n const edge: IEdge = {\n id: uuidv4(),\n objectType: ObjectTypes.Edge,\n source: srcKey.toString(),\n destination: dstKey.toString(),\n name: null,\n };\n edges.push(edge);\n }\n }\n });\n });\n\n return [edges];\n}\n\nexport function storyLayout(clusterInstances: ICluster[], edges: IEdge[]): IBook[] {\n const stories: IBook[] = [];\n const copy = edges.slice(0);\n let idx = -1;\n\n while (copy.length > 0) {\n const toProcess = [copy.splice(0, 1)[0]];\n\n const clusterSet = new Set();\n const edgeSet = new Set();\n\n while (toProcess.length > 0) {\n const edge = toProcess.splice(0, 1)[0];\n do {\n clusterSet.add(clusterInstances[edge.source]);\n clusterSet.add(clusterInstances[edge.destination]);\n\n edgeSet.add(edge);\n\n idx = copy.findIndex((value) => value.destination === edge.source || value.source === edge.destination);\n if (idx >= 0) {\n const removed = copy.splice(idx, 1)[0];\n clusterSet.add(clusterInstances[removed.source]);\n clusterSet.add(clusterInstances[removed.destination]);\n\n edgeSet.add(removed);\n toProcess.push(removed);\n }\n } while (idx >= 0);\n }\n\n const clusterResult = [...clusterSet];\n const edgeResult: IEdge[] = [...edgeSet].map((edge) => {\n return {\n id: uuidv4(),\n source: clusterResult.indexOf(clusterInstances[edge.source]).toString(),\n destination: clusterResult.indexOf(clusterInstances[edge.destination]).toString(),\n objectType: ObjectTypes.Edge,\n };\n });\n\n const story = transformIndicesToHandles(clusterResult, edgeResult);\n\n stories.push(story);\n }\n\n return stories;\n}\n","export * from './Colors';\nexport * from './CountryCodes';\nexport * from './Data';\nexport * from './graphs';\nexport * from './Loaders';\nexport * from './RenderingContextEx';\nexport * from './ShallowSet';\nexport * from './UMAP';\nexport * from './NormalizedState';\nexport * from './ScalingAndAxes';\n","import * as React from 'react';\nimport { useSelector, useDispatch } from 'react-redux';\nimport CloseIcon from '@mui/icons-material/Close';\nimport SplitscreenIcon from '@mui/icons-material/Splitscreen';\nimport { EntityId, EntityState } from '@reduxjs/toolkit';\nimport { IconButton, Typography } from '@mui/material';\nimport { WebGLView } from '../WebGLView/WebGLView';\nimport { ViewSelector, ViewActions, SingleMultiple } from '../Ducks/ViewDuck';\nimport { IPosition, IProjection } from '../../model/ProjectionInterfaces';\nimport { RootState } from '../Store';\nimport { Dataset } from '../../model/Dataset';\n\nfunction selectPositions(dataset: Dataset, projection: IProjection) {\n if (projection.xChannel || projection.yChannel) {\n return dataset.vectors.map((vector) => ({\n x: projection.xChannel ? vector[projection.xChannel] : 0,\n y: projection.yChannel ? vector[projection.yChannel] : 0,\n }));\n }\n\n return projection.positions;\n}\n\nfunction WebView({\n id,\n multiples,\n overrideComponents,\n onCloseView,\n}: {\n multiples: {\n multiples: EntityState;\n active: EntityId;\n projections: EntityState;\n };\n id: EntityId;\n overrideComponents;\n onCloseView;\n}) {\n const value = multiples.multiples.entities[id];\n\n const dataset = useSelector((state: RootState) => state.dataset);\n const dispatch = useDispatch();\n\n const projection =\n typeof value.attributes.workspace === 'string' || typeof value.attributes.workspace === 'number'\n ? multiples.projections.entities[value.attributes.workspace]\n : value.attributes.workspace;\n\n const positions = React.useMemo(() => {\n return selectPositions(dataset, projection);\n }, [dataset, projection]);\n\n const active = value.id === multiples.active;\n const boxShadow = '0px 5px 5px -3px rgb(0 0 0 / 20%), 0px 8px 10px 1px rgb(0 0 0 / 14%), 0px 3px 14px 2px rgb(0 0 0 / 12%)';\n\n return (\n \n \n \n \n {projection.metadata?.method}\n \n\n \n {projection.name ? ` - \"${projection.name}\"` : ''}\n {projection.xChannel || projection.yChannel ? ` [x: ${projection.xChannel}, y: ${projection.yChannel}]` : null}\n \n
    \n\n
    \n {value.id === multiples.multiples.ids[0] ? (\n dispatch(ViewActions.addView(dataset))}\n style={{ visibility: value.id === multiples.multiples.ids[0] ? 'visible' : 'hidden' }}\n >\n \n \n ) : null}\n\n onCloseView(value.id)}>\n \n \n
    \n
    \n
    \n {positions && projection ? (\n \n ) : null}\n
    \n
    \n );\n}\n\nexport function ViewMultiplexer({ overrideComponents }) {\n const multiples = useSelector(ViewSelector.selectAll);\n const dispatch = useDispatch();\n\n const count = multiples.multiples.ids.length;\n\n const onCloseView = (id: EntityId) => {\n dispatch(ViewActions.deleteView(id));\n };\n\n return (\n
    \n {count > 0 ? (\n
    \n \n
    \n ) : null}\n\n {count > 1 ? (\n
    \n {multiples.multiples.ids.slice(1).map((id) => {\n return ;\n })}\n
    \n ) : null}\n
    \n );\n}\n","import type { ViewTransformType } from '../Ducks';\n\n/**\n * Utility object that can convert screen coordinates to world coordinates and vice-versa.\n */\nexport class CameraTransformations {\n /**\n * Converts world coordinates to screen coordinates\n * @param {*} vec a vector containing x and y\n */\n static worldToScreen(vec, transform: ViewTransformType) {\n return {\n x: (vec.x - transform.centerX) * transform.zoom + transform.width / 2,\n y: (-vec.y + transform.centerY) * transform.zoom + transform.height / 2,\n };\n }\n\n /**\n * Converts world coordinates to screen coordinates ignoring the camera position\n * @param screen\n */\n static worldToScreenWithoutOffset(vec, transform: ViewTransformType) {\n return {\n x: vec.x * transform.zoom + transform.width / 2,\n y: -vec.y * transform.zoom + transform.height / 2,\n };\n }\n\n /**\n * Converts world coordinates to screen coordinates, but only the camera position\n * @param screen\n */\n static cameraOffsetToScreen(transform: ViewTransformType) {\n return {\n x: -transform.centerX * transform.zoom,\n y: transform.centerY * transform.zoom,\n };\n }\n\n /**\n * Converts screen coordinates in the range 0 - width, 0 - height to world coordinates taking into account\n * the position of the camera.\n */\n static screenToWorld(screen: { x: number; y: number }, transform: ViewTransformType) {\n return {\n x: (screen.x - transform.width / 2) / transform.zoom + transform.centerX,\n y: -(screen.y - transform.height / 2) / transform.zoom + transform.centerY,\n };\n }\n\n static pixelToWorldCoordinates(pixel: number, transform: ViewTransformType) {\n const v1 = CameraTransformations.screenToWorld({ x: 0, y: 0 }, transform);\n const v2 = CameraTransformations.screenToWorld({ x: transform.width, y: 0 }, transform);\n\n return ((v2.x - v1.x) / transform.width) * pixel;\n }\n}\n","export class CategoryOptionsAPI {\n static hasCategory(categoryOptions: CategoryOptions, catName) {\n if (categoryOptions == null) return false;\n return categoryOptions.filter((a) => a.category === catName).length > 0;\n }\n\n static getCategory(categoryOptions: CategoryOptions, catName) {\n if (categoryOptions == null) return null;\n return categoryOptions.filter((a) => a.category === catName)[0];\n }\n\n static getAttribute(categoryOptions: CategoryOptions, category, attribute, type) {\n try {\n return categoryOptions.find((c) => c.category === category).attributes.find((a) => a.key === attribute && a.type === type);\n } catch (e) {\n return null;\n }\n }\n}\n\nexport type CategoryOption = {\n key: string;\n name: string;\n type: 'sequential' | 'categorical';\n range;\n values;\n};\n\n/**\n * Helper class that manages the attribute categories.\n * These options are a top-level representation of all attributes eg\n * color by (att1, att2...)\n * size by (att1, att2...)\n * brightness by ...\n */\nexport type CategoryOptions = { category: string; attributes: CategoryOption[] }[];\n","import { Tool } from './Tool';\nimport { ICluster } from '../../model/ICluster';\nimport { RenderingContextEx } from '../Utility/RenderingContextEx';\n\nexport class ClusterDragTool implements Tool {\n cluster: ICluster;\n\n constructor(cluster) {\n this.cluster = cluster;\n }\n\n renderToContext(context: RenderingContextEx, start, end) {\n context.strokeStyle = 'rgba(0.5, 0.5, 0.5, 0.4)';\n context.lineWidth = '6';\n\n context.beginPath();\n context.moveTo(start.x, start.y);\n context.arrowTo(start.x, start.y, end.x, end.y, 10);\n context.stroke();\n context.closePath();\n }\n}\n","/* eslint-disable react/display-name */\nimport * as React from 'react';\nimport { connect } from 'react-redux';\nimport { RenderingContextEx } from '../Utility/RenderingContextEx';\nimport { CameraTransformations } from './CameraTransformations';\nimport type { ViewTransformType } from '../Ducks';\n\ntype LassoLayerProps = {\n viewTransform: ViewTransformType;\n};\n\nconst mapStateToProps = (state) => ({});\n\nconst LassoLayer = connect(mapStateToProps, null, null, { forwardRef: true })(\n class extends React.Component {\n constructor(props) {\n super(props);\n\n this.state = {\n canvasRef: React.createRef(),\n };\n }\n\n getContext() {\n return this.state.canvasRef.current.getContext('2d');\n }\n\n setDimensions(width, height) {\n this.state.canvasRef.current.setAttribute('width', width);\n this.state.canvasRef.current.setAttribute('height', height);\n }\n\n renderHighlightedSequence(context: CanvasRenderingContext2D, highlightedSequence: { previous; current; next }) {\n const ctx = new RenderingContextEx(context, window.devicePixelRatio);\n const current = CameraTransformations.worldToScreen({ x: highlightedSequence.current.x, y: highlightedSequence.current.y }, this.props.viewTransform);\n\n ctx.lineWidth = 6;\n\n // ctx.setLineDash([8, 8])\n // ctx.lineDashOffset = ((performance.now() / 30) % 16) * -1\n\n if (highlightedSequence.previous) {\n ctx.beginPath();\n const previous = CameraTransformations.worldToScreen(\n { x: highlightedSequence.previous.x, y: highlightedSequence.previous.y },\n this.props.viewTransform,\n );\n ctx.moveTo(previous.x, previous.y);\n\n ctx.strokeStyle = 'rgba(0.5, 0.5, 0.5, 0.4)';\n ctx.arrowTo(previous.x, previous.y, current.x, current.y, 30);\n ctx.stroke();\n ctx.closePath();\n }\n if (highlightedSequence.next) {\n const next = CameraTransformations.worldToScreen({ x: highlightedSequence.next.x, y: highlightedSequence.next.y }, this.props.viewTransform);\n ctx.beginPath();\n ctx.moveTo(current.x, current.y);\n\n ctx.strokeStyle = 'rgba(0.5, 0.5, 0.5, 0.6)';\n ctx.arrowTo(current.x, current.y, next.x, next.y, 30);\n ctx.stroke();\n }\n }\n\n render() {\n return (\n \n );\n }\n },\n);\n\nexport { LassoLayer };\n","class Layer {\n values: boolean[];\n\n active: boolean;\n\n constructor(size: number, active: boolean) {\n this.values = new Array(size).fill(false);\n this.active = active;\n }\n\n setValue(index: number, value: boolean) {\n this.values[index] = value;\n }\n\n getValue(index: number) {\n return this.values[index];\n }\n}\n\n/**\n * Helper class for cases where cross interaction could occur, one example would be that in the storytelling\n * the other lines should be grayed out, but a selection should overwrite this. This is solved by having 'layers'\n * of boolean values, each for one feature (1 layer for selection, 1 layer for storytelling) and solving the\n * actual value by the layer hierarchy.\n */\nexport class LayeringSystem {\n layers: Layer[] = [];\n\n layerSize: number;\n\n layerDictionary: { [index: number]: number } = {};\n\n constructor(layerSize: number) {\n this.layerSize = layerSize;\n }\n\n clearLayer(layer: number, value: boolean) {\n const e = this.layers[this.layerDictionary[layer]];\n for (let i = 0; i < this.layerSize; i++) {\n e.setValue(i, value);\n }\n }\n\n setLayerActive(layer: number, active: boolean) {\n this.layers[this.layerDictionary[layer]].active = active;\n }\n\n registerLayer(layer: number, active: boolean) {\n const i = this.layers.push(new Layer(this.layerSize, active)) - 1;\n this.layerDictionary[layer] = i;\n }\n\n setValue(index: number, layer: number, value: boolean) {\n const layerIndex = this.layerDictionary[layer];\n this.layers[layerIndex].setValue(index, value);\n }\n\n getValue(index: number) {\n const activeLayerIndex =\n this.layerDictionary[\n Object.keys(this.layerDictionary)\n .sort((a, b) => Number.parseInt(b, 10) - Number.parseInt(a, 10))\n .find((key) => this.layers[this.layerDictionary[key]].active)\n ];\n\n // console.log(activeLayerIndex)\n\n if (activeLayerIndex === undefined || activeLayerIndex < 0) {\n return false;\n }\n\n return this.layers[activeLayerIndex].getValue(index);\n }\n}\n","import * as nt from '../NumTs/NumTs';\n\nconst LEFT_BUTTON = 0;\nconst RIGHT_BUTTON = 2;\n\nenum Mode {\n None,\n Pressed,\n Drag,\n}\n\n/**\n * Keeps track of the mouse state eg. press, click, move etc\n */\nexport class MouseController {\n pressed = new Array(3).fill(false);\n\n pressedPosition: nt.VectorType = null;\n\n pressedButton = 0;\n\n mode: Mode = Mode.None;\n\n private mousePosition: nt.VectorType = { x: 0, y: 0 };\n\n onDragStart: (event: MouseEvent, button: number, initial: nt.VectorType) => void;\n\n onDragEnd: (event: MouseEvent, button: number) => void;\n\n onDragMove: (event: MouseEvent, button: number) => void;\n\n onContext: (event: MouseEvent, button: number) => void;\n\n onMouseUp: (event: MouseEvent) => void;\n\n onMouseMove: (event: MouseEvent) => void;\n\n onMouseLeave: (event: MouseEvent) => void;\n\n constructor() {}\n\n get currentMousePosition() {\n return this.mousePosition;\n }\n\n mouseLeave(event: MouseEvent) {\n if (this.onMouseLeave) {\n this.onMouseLeave(event);\n }\n }\n\n mouseDown(event: MouseEvent) {\n switch (event.button) {\n case LEFT_BUTTON:\n this.pressed[LEFT_BUTTON] = true;\n this.pressedPosition = { x: event.offsetX, y: event.offsetY };\n this.pressedButton = LEFT_BUTTON;\n break;\n case RIGHT_BUTTON:\n this.pressed[RIGHT_BUTTON] = true;\n this.pressedPosition = { x: event.offsetX, y: event.offsetY };\n this.pressedButton = RIGHT_BUTTON;\n break;\n default:\n break;\n }\n\n this.mode = Mode.Pressed;\n }\n\n mouseUp(event: MouseEvent) {\n if (this.mode === Mode.Drag) {\n this.mode = Mode.None;\n if (this.onDragEnd) {\n this.onDragEnd(event, this.pressedButton);\n }\n return;\n }\n\n switch (event.button) {\n case LEFT_BUTTON:\n this.pressed[LEFT_BUTTON] = false;\n\n if (this.mode === Mode.Pressed) {\n if (this.onContext) {\n this.onContext(event, LEFT_BUTTON);\n }\n\n this.mode = Mode.None;\n }\n break;\n case RIGHT_BUTTON:\n this.pressed[RIGHT_BUTTON] = false;\n\n if (this.mode === Mode.Pressed) {\n if (this.onContext) {\n this.onContext(event, RIGHT_BUTTON);\n }\n\n this.mode = Mode.None;\n }\n break;\n default:\n break;\n }\n }\n\n mouseMove(event: MouseEvent) {\n const mousePosition = { x: event.offsetX, y: event.offsetY };\n this.mousePosition = mousePosition;\n\n if (this.mode === Mode.Drag) {\n if (this.onDragMove) {\n this.onDragMove(event, this.pressedButton);\n }\n } else if (this.onMouseMove) {\n this.onMouseMove(event);\n }\n\n if (this.mode === Mode.Pressed && this.pressedPosition && nt.euclideanDistanceVec(this.pressedPosition, mousePosition) > 4) {\n if (this.onDragStart) {\n this.onDragStart(event, this.pressedButton, this.pressedPosition);\n this.mode = Mode.Drag;\n }\n }\n }\n}\n","/* eslint-disable react/display-name */\nimport * as d3v5 from 'd3v5';\nimport { Scene, Vector2, Vector3 } from 'three';\nimport { EntityId } from '@reduxjs/toolkit';\nimport * as THREE from 'three';\nimport * as React from 'react';\nimport { connect, ConnectedProps } from 'react-redux';\nimport { Typography } from '@mui/material';\nimport { IVector } from '../../model/Vector';\nimport { DisplayMode } from '../Ducks/DisplayModeDuck';\nimport type { RootState } from '../Store/Store';\nimport { TrailVisualization } from './TrailVisualization';\nimport { ACluster, isCluster } from '../../model/Cluster';\nimport { ICluster } from '../../model/ICluster';\nimport { CameraTransformations } from './CameraTransformations';\nimport { IBook } from '../../model/Book';\nimport * as nt from '../NumTs/NumTs';\n\nimport { GroupVisualizationMode } from '../Ducks/GroupVisualizationMode';\nimport { ViewTransformType } from '../Ducks';\nimport { SchemeColor } from '../Utility/Colors/SchemeColor';\nimport { AStorytelling } from '../Ducks/StoriesDuck';\nimport { IPosition } from '../../model/ProjectionInterfaces';\n\nconst SELECTED_COLOR = 0x007dad;\nconst DEFAULT_COLOR = 0x808080;\nconst GRAYED = 0xdcdcdc;\n\nconst WING_SIZE = 2.2;\nconst LINE_WIDTH = 1.5;\n\nconst CLUSTER_PIXEL_SIZE = 12;\n\nconst hoverLabel = (hoverState: ICluster, viewTransform: ViewTransformType, workspace) => {\n const screen = CameraTransformations.worldToScreen(ACluster.getCenterFromWorkspace(workspace, hoverState), viewTransform);\n\n return (\n \n {hoverState.name}\n \n );\n};\n\ntype ClusterObjectType = {\n cluster: EntityId;\n geometry: THREE.Geometry;\n material: THREE.MeshBasicMaterial;\n mesh: THREE.Mesh;\n children: { sample: number; visible: boolean }[];\n trailPositions: any[];\n lineColor: any;\n triangulatedMesh: any;\n sampleConnection: boolean;\n};\n\nconst mapState = (state: RootState) => ({\n dataset: state.dataset,\n displayMode: state.displayMode,\n trailSettings: state.trailSettings,\n stories: state.stories,\n currentAggregation: state.currentAggregation,\n hoverState: state.hoverState,\n groupVisualizationMode: state.groupVisualizationMode,\n});\n\nconst connector = connect(mapState, null, null, { forwardRef: true });\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {\n // Callback that is called when a rerender should happen\n onInvalidate?: () => void;\n viewTransform: ViewTransformType;\n workspace: IPosition[];\n globalPointSize;\n};\n\n/**\n * Clustering visualization as a React component.\n */\nexport const MultivariateClustering = connector(\n class extends React.Component {\n // arrowMesh\n arrowMesh: THREE.Mesh;\n\n trailMesh: THREE.Mesh;\n\n scene: Scene;\n\n lineMesh: THREE.Mesh;\n\n clusterObjects: ClusterObjectType[] = [];\n\n devicePixelRatio: number;\n\n scalingScene: Scene;\n\n clusterVis: THREE.Mesh[];\n\n trail: TrailVisualization;\n\n clusterScene: THREE.Scene;\n\n constructor(props) {\n super(props);\n\n this.devicePixelRatio = window.devicePixelRatio;\n this.scalingScene = new THREE.Scene();\n this.scene = new THREE.Scene();\n this.clusterScene = new THREE.Scene();\n\n const arrowMateral = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, vertexColors: true });\n arrowMateral.opacity = 0.8;\n arrowMateral.transparent = true;\n\n this.arrowMesh = new THREE.Mesh(new THREE.Geometry(), arrowMateral);\n this.scene.add(this.arrowMesh);\n\n this.trailMesh = new THREE.Mesh(new THREE.Geometry(), new THREE.MeshBasicMaterial({ color: 0xff0000, side: THREE.DoubleSide, vertexColors: true }));\n this.scene.add(this.trailMesh);\n\n this.trail = new TrailVisualization();\n this.trail.create();\n this.scene.add(this.trail.mesh);\n }\n\n componentDidMount() {\n if (this.props.stories.active !== null && this.props.workspace) {\n const activeStory = AStorytelling.getActive(this.props.stories);\n\n if (activeStory.clusters.ids.length > 0) {\n this.create();\n this.createTriangulatedMesh();\n }\n }\n }\n\n componentDidUpdate(prevProps: Props) {\n if (prevProps.trailSettings !== this.props.trailSettings) {\n this.trail.setVisible(this.props.trailSettings.show);\n this.trail.setLength(this.props.trailSettings.length);\n }\n\n // If we have clusters now... and are on clusters tab... create cluster visualization\n if (prevProps.stories !== this.props.stories && this.props.workspace) {\n this.destroy();\n this.disposeTriangulatedMesh();\n\n if (this.props.stories.active !== null) {\n const activeStory = AStorytelling.getActive(this.props.stories);\n\n if (activeStory.clusters.ids.length > 0) {\n this.create();\n this.createTriangulatedMesh();\n }\n }\n }\n\n if (prevProps.displayMode !== this.props.displayMode) {\n switch (this.props.displayMode) {\n case DisplayMode.StatesAndClusters:\n this.highlightCluster(this.props.currentAggregation.selectedClusters);\n this.clusterScene.visible = true;\n this.scalingScene.visible = true;\n this.scene.visible = true;\n break;\n case DisplayMode.OnlyClusters:\n this.clusterScene.visible = true;\n this.scalingScene.visible = true;\n this.scene.visible = true;\n this.clusterObjects.forEach((clusterObject) => {\n clusterObject.children.forEach((child) => {\n child.visible = false;\n });\n });\n break;\n case DisplayMode.OnlyStates:\n case DisplayMode.None:\n this.clusterScene.visible = false;\n this.scalingScene.visible = false;\n this.scene.visible = false;\n\n break;\n default:\n break;\n }\n }\n\n if (prevProps.currentAggregation !== this.props.currentAggregation || prevProps.groupVisualizationMode !== this.props.groupVisualizationMode) {\n this.deactivateAll();\n\n if (this.props.currentAggregation.source === 'sample') {\n this.highlightSamples(this.props.currentAggregation.aggregation.map((i) => this.props.dataset.vectors[i]));\n }\n\n // if the hoverCluster state changed and its a multivariate cluster, we need to enable the three js scene part\n if (this.props.currentAggregation.source === 'cluster') {\n this.highlightCluster(this.props.currentAggregation.selectedClusters);\n }\n }\n\n if (prevProps.workspace !== this.props.workspace && this.props.workspace) {\n // TODO: check performance implications\n this.updatePositions(this.props.viewTransform.zoom);\n this.createTriangulatedMesh();\n }\n\n if (this.props.onInvalidate) {\n this.props.onInvalidate();\n }\n }\n\n getColorForClusterObject(clusterObject: ClusterObjectType) {\n if (this.props.currentAggregation.selectedClusters.includes(clusterObject.cluster) || clusterObject.sampleConnection) {\n return new THREE.Color(SELECTED_COLOR);\n }\n const activeStory = AStorytelling.getActive(this.props.stories);\n if (activeStory?.clusters?.ids.includes(clusterObject.cluster)) {\n return new THREE.Color(DEFAULT_COLOR);\n }\n return new THREE.Color(GRAYED);\n }\n\n updateArrows(zoom: number) {\n if (!this.arrowMesh) {\n return;\n }\n\n this.arrowMesh.visible = true;\n this.arrowMesh.geometry.dispose();\n const arrowGeometry = new THREE.Geometry();\n arrowGeometry.vertices = [];\n arrowGeometry.faces = [];\n\n let index = 0;\n const activeStory = AStorytelling.getActive(this.props.stories);\n if (activeStory) {\n for (const [key, edge] of Object.entries(activeStory.edges.entities)) {\n let color = new THREE.Color(DEFAULT_COLOR);\n if (this.props.stories.trace && this.props.stories.trace.mainEdges.includes(key)) {\n color = new THREE.Color(SELECTED_COLOR);\n }\n\n const sourceCenter = ACluster.getCenterFromWorkspace(this.props.workspace, AStorytelling.retrieveCluster(this.props.stories, edge.source));\n const destCenter = ACluster.getCenterFromWorkspace(this.props.workspace, AStorytelling.retrieveCluster(this.props.stories, edge.destination));\n const start = new THREE.Vector2(sourceCenter.x, sourceCenter.y);\n const end = new THREE.Vector2(destCenter.x, destCenter.y);\n const middle = new THREE.Vector2().addVectors(start, new THREE.Vector2().subVectors(end, start).multiplyScalar(0.5));\n\n const dir = end.clone().sub(start).normalize();\n const left = new Vector2(-dir.y, dir.x).multiplyScalar(LINE_WIDTH);\n const right = new Vector2(dir.y, -dir.x).multiplyScalar(LINE_WIDTH);\n const offset = dir.clone().multiplyScalar(this.devicePixelRatio * CLUSTER_PIXEL_SIZE);\n\n // line without arrow\n arrowGeometry.vertices.push(new THREE.Vector3(start.x * zoom + left.x + offset.x, start.y * zoom + left.y + offset.y, 0));\n arrowGeometry.vertices.push(new THREE.Vector3(start.x * zoom + right.x + offset.x, start.y * zoom + right.y + offset.y, 0));\n arrowGeometry.vertices.push(new THREE.Vector3(end.x * zoom + left.x - offset.x, end.y * zoom + left.y - offset.y, 0));\n arrowGeometry.vertices.push(new THREE.Vector3(end.x * zoom + right.x - offset.x, end.y * zoom + right.y - offset.y, 0));\n\n // left wing\n arrowGeometry.vertices.push(new THREE.Vector3(middle.x * zoom + left.x - offset.x, middle.y * zoom + left.y - offset.y, 0));\n arrowGeometry.vertices.push(new THREE.Vector3(middle.x * zoom + left.x + offset.x, middle.y * zoom + left.y + offset.y, 0));\n arrowGeometry.vertices.push(new THREE.Vector3(middle.x * zoom + left.x * WING_SIZE - offset.x, middle.y * zoom + left.y * WING_SIZE - offset.y, 0));\n\n // Right wing\n arrowGeometry.vertices.push(new THREE.Vector3(middle.x * zoom + right.x - offset.x, middle.y * zoom + right.y - offset.y, 0));\n arrowGeometry.vertices.push(new THREE.Vector3(middle.x * zoom + right.x + offset.x, middle.y * zoom + right.y + offset.y, 0));\n arrowGeometry.vertices.push(new THREE.Vector3(middle.x * zoom + right.x * WING_SIZE - offset.x, middle.y * zoom + right.y * WING_SIZE - offset.y, 0));\n\n const i = index * 10;\n // line without arrow\n arrowGeometry.faces.push(new THREE.Face3(i, i + 1, i + 2, new Vector3(0, 0, -1), color));\n arrowGeometry.faces.push(new THREE.Face3(i + 1, i + 3, i + 2, new Vector3(0, 0, -1), color));\n\n // left wing\n arrowGeometry.faces.push(new THREE.Face3(i + 4, i + 6, i + 5, new Vector3(0, 0, -1), color));\n\n // Right wing\n arrowGeometry.faces.push(new THREE.Face3(i + 7, i + 9, i + 8, new Vector3(0, 0, -1), color));\n\n index += 1;\n }\n }\n\n this.arrowMesh.geometry = arrowGeometry;\n }\n\n /**\n * Updates geometry of the trail mesh.\n */\n updateTrail(zoom: number) {\n this.trail.update(this.clusterObjects, zoom);\n }\n\n iterateTrail() {\n const activeStory = AStorytelling.getActive(this.props.stories);\n this.clusterObjects.forEach((clusterObject) => {\n const center = ACluster.getCenterFromWorkspace(this.props.workspace, activeStory.clusters.entities[clusterObject.cluster]);\n\n const last = clusterObject.trailPositions[clusterObject.trailPositions.length - 1];\n if (!last || new THREE.Vector3(center.x, center.y, 0).distanceTo(last) > 0.1) {\n const positions = clusterObject.trailPositions;\n\n if (positions.length > this.props.trailSettings.length) {\n clusterObject.trailPositions.shift();\n }\n\n positions.push(new THREE.Vector3(center.x, center.y, 0));\n }\n });\n }\n\n updatePositions(zoom: number) {\n if (!this.scene || !this.lineMesh || !this.props.workspace) {\n return;\n }\n\n this.lineMesh.geometry.dispose();\n const lineGeometry = new THREE.Geometry();\n lineGeometry.vertices = [];\n lineGeometry.faces = [];\n lineGeometry.colors = [];\n\n let index = 0;\n\n const activeStory = AStorytelling.getActive(this.props.stories);\n this.clusterObjects.forEach((clusterObject) => {\n const { cluster } = clusterObject;\n const center = ACluster.getCenterFromWorkspace(this.props.workspace, activeStory.clusters.entities[cluster]);\n const { mesh } = clusterObject;\n\n mesh.position.set(center.x * zoom, center.y * zoom, -0.5);\n\n mesh.material.color = this.getColorForClusterObject(clusterObject);\n\n mesh.scale.set(this.props.globalPointSize[0], this.props.globalPointSize[0], this.props.globalPointSize[0]);\n\n clusterObject.children.forEach((child) => {\n if (child.visible && this.props.displayMode === DisplayMode.StatesAndClusters) {\n const { x, y } = this.props.workspace[child.sample];\n const dir = new THREE.Vector2(x - center.x, y - center.y).normalize();\n const rigth = new Vector2(dir.y, -dir.x).multiplyScalar(this.devicePixelRatio);\n const left = new Vector2(-dir.y, dir.x).multiplyScalar(this.devicePixelRatio);\n\n lineGeometry.vertices.push(new THREE.Vector3(center.x * zoom + left.x, center.y * zoom + left.y, 0));\n lineGeometry.vertices.push(new THREE.Vector3(center.x * zoom + rigth.x, center.y * zoom + rigth.y, 0));\n lineGeometry.vertices.push(new THREE.Vector3(x * zoom + left.x, y * zoom + left.y, 0));\n lineGeometry.vertices.push(new THREE.Vector3(x * zoom + rigth.x, y * zoom + rigth.y, 0));\n\n const i = index * 4;\n lineGeometry.faces.push(new THREE.Face3(i, i + 1, i + 2, new Vector3(0, 0, -1), new THREE.Color(clusterObject.lineColor.hex)));\n lineGeometry.faces.push(new THREE.Face3(i + 1, i + 3, i + 2, new Vector3(0, 0, -1), new THREE.Color(clusterObject.lineColor.hex)));\n\n index += 1;\n }\n });\n });\n\n this.lineMesh.geometry = lineGeometry;\n }\n\n /**\n * Creates the visualization.\n */\n create() {\n this.clusterObjects = [];\n\n const lineMateral = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide, vertexColors: true });\n\n lineMateral.opacity = 0.5;\n lineMateral.transparent = true;\n const lineGeometry = new THREE.Geometry();\n this.lineMesh = new THREE.Mesh(lineGeometry, lineMateral);\n this.lineMesh.position.set(0, 0, -1);\n this.scene.add(this.lineMesh);\n\n const activeStory = AStorytelling.getActive(this.props.stories);\n\n for (const [ci, cluster] of Object.entries(activeStory.clusters.entities)) {\n // Add circle to scene\n const geometry = new THREE.PlaneGeometry(this.devicePixelRatio * CLUSTER_PIXEL_SIZE, this.devicePixelRatio * CLUSTER_PIXEL_SIZE);\n geometry.rotateZ(Math.PI / 4);\n geometry.scale(0.85, 1.0, 1.0);\n\n const material = new THREE.MeshBasicMaterial({ color: new THREE.Color(DEFAULT_COLOR) });\n const circle = new THREE.Mesh(geometry, material);\n\n material.opacity = 0.92;\n\n material.transparent = true;\n\n const center = ACluster.getCenterFromWorkspace(this.props.workspace, cluster);\n circle.position.set(center.x, center.y, 0);\n this.clusterScene.add(circle);\n\n const clusterObject: ClusterObjectType = {\n cluster: ci,\n geometry,\n material,\n mesh: circle,\n children: [],\n trailPositions: [],\n lineColor: new SchemeColor(DEFAULT_COLOR),\n triangulatedMesh: {},\n sampleConnection: false,\n };\n\n material.color = this.getColorForClusterObject(clusterObject);\n\n this.clusterObjects.push(clusterObject);\n\n // Create line geometry\n cluster.indices.forEach((i) => {\n clusterObject.children.push({\n sample: i,\n visible: false,\n });\n });\n }\n }\n\n // Activates the lines from given samples to their corresponding clusters\n highlightSamples(samples: IVector[]) {\n // Deactivate all lines\n this.deactivateAll();\n\n const activeStory = AStorytelling.getActive(this.props.stories);\n\n this.clusterObjects.forEach((clusterObject) => {\n clusterObject.material.color = new THREE.Color(DEFAULT_COLOR);\n });\n\n samples.forEach((sample) => {\n sample.groupLabel.forEach((label) => {\n const clusterObject = this.clusterObjects.find((e) => activeStory.clusters.entities[e.cluster].label === label);\n\n if (clusterObject && this.props.groupVisualizationMode === GroupVisualizationMode.StarVisualization) {\n clusterObject.sampleConnection = true;\n\n clusterObject.children.forEach((child) => {\n if (child.sample === sample.__meta__.meshIndex) {\n child.visible = true;\n }\n });\n }\n });\n });\n }\n\n deactivateAll() {\n this.clusterObjects.forEach((clusterObject) => {\n clusterObject.sampleConnection = false;\n\n clusterObject.material.color = this.getColorForClusterObject(clusterObject);\n\n clusterObject.children.forEach((child) => {\n child.visible = false;\n });\n });\n if (this.clusterVis) {\n this.clusterVis.forEach((mesh) => {\n mesh.visible = false;\n });\n }\n }\n\n highlightCluster(indices?: EntityId[]) {\n this.clusterObjects.forEach((clusterObject, index) => {\n const visible = indices?.includes(clusterObject.cluster); // for paper used: true\n\n clusterObject.material.color = visible ? new THREE.Color(SELECTED_COLOR) : new THREE.Color(DEFAULT_COLOR);\n\n if (this.props.groupVisualizationMode === GroupVisualizationMode.StarVisualization) {\n clusterObject.children.forEach((child) => {\n child.visible = visible;\n });\n }\n\n if (this.clusterVis && this.props.groupVisualizationMode === GroupVisualizationMode.ConvexHull) {\n this.clusterVis[index].visible = visible;\n }\n });\n }\n\n /**\n * Destroys the visualization.\n */\n destroy() {\n if (this.clusterObjects && this.clusterObjects.length > 0) {\n this.clusterObjects.forEach((clusterObject) => {\n this.clusterScene.remove(clusterObject.mesh);\n clusterObject.geometry.dispose();\n clusterObject.material.dispose();\n });\n this.clusterObjects = [];\n }\n\n if (this.lineMesh) {\n this.scene.remove(this.lineMesh);\n\n const lineMaterial = this.lineMesh.material as THREE.Material;\n this.lineMesh.geometry.dispose();\n lineMaterial.dispose();\n }\n }\n\n /**\n * Creates the triangulated mesh that visualizes the clustering.\n * @param clusters an array of clusters\n */\n createTriangulatedMesh() {\n this.disposeTriangulatedMesh();\n\n if (this.props.groupVisualizationMode !== GroupVisualizationMode.ConvexHull) {\n return;\n }\n\n const lineMeshes = [];\n\n if (this.props.stories.active !== null) {\n const activeStory = AStorytelling.getActive(this.props.stories);\n\n for (const [, cluster] of Object.entries(activeStory.clusters.entities)) {\n const bounds = ACluster.calcBounds(this.props.workspace, cluster.indices);\n\n const xAxis = d3v5.scaleLinear().range([0, 100]).domain([bounds.left, bounds.right]);\n\n const yAxis = d3v5\n .scaleLinear()\n .range([0, 100 * (bounds.height / bounds.width)])\n .domain([bounds.top, bounds.bottom]);\n\n const contours = d3v5\n .contourDensity()\n .x((d) => xAxis(d[0]))\n .y((d) => yAxis(d[1]))\n .bandwidth(10)\n .thresholds(10)\n .size([100, bounds.width === 0 ? 1 : Math.floor(100 * (bounds.height / bounds.width))])(\n cluster.indices.map((i) => [this.props.workspace[i].x, this.props.workspace[i].y]),\n );\n\n const clusterObject = this.clusterObjects.find((e) => activeStory.clusters.entities[e.cluster].label === cluster.label);\n\n const material = new THREE.LineBasicMaterial({ color: clusterObject.lineColor.hex });\n\n const points = [];\n contours.forEach((contour) => {\n contour.coordinates.forEach((contourPolygon) => {\n const coordinates = contourPolygon[0];\n\n for (let i = 0; i < coordinates.length - 1; i++) {\n const cur = coordinates[i];\n const next = coordinates[i + 1];\n\n points.push(new THREE.Vector3(xAxis.invert(cur[0]), yAxis.invert(cur[1]), -5));\n points.push(new THREE.Vector3(xAxis.invert(next[0]), yAxis.invert(next[1]), -5));\n }\n });\n });\n const line = new THREE.LineSegments(new THREE.BufferGeometry().setFromPoints(points), material);\n\n line.visible = this.props.currentAggregation.source === 'cluster' && this.props.currentAggregation.selectedClusters.includes(clusterObject.cluster);\n\n this.scalingScene.add(line);\n\n lineMeshes.push(line);\n }\n }\n\n this.clusterVis = lineMeshes;\n }\n\n /**\n * Destroys the triangulated view of the clusters.\n */\n disposeTriangulatedMesh() {\n if (this.clusterVis != null) {\n const lineMeshes = this.clusterVis;\n lineMeshes?.forEach((mesh) => {\n mesh.geometry.dispose();\n mesh.material.dispose();\n this.scalingScene.remove(mesh);\n });\n\n this.clusterVis = null;\n }\n }\n\n /**\n * Creates textual representations of the edges of the story.\n */\n createStreetLabels(story?: IBook) {\n if (!story) {\n return [];\n }\n\n const labels = [];\n\n Object.values(story.edges.entities)\n .filter((edge) => edge.name && edge.name !== '')\n .forEach((edge) => {\n const source = CameraTransformations.worldToScreen(\n ACluster.getCenterFromWorkspace(this.props.workspace, AStorytelling.retrieveCluster(this.props.stories, edge.source)),\n this.props.viewTransform,\n );\n const dest = CameraTransformations.worldToScreen(\n ACluster.getCenterFromWorkspace(this.props.workspace, AStorytelling.retrieveCluster(this.props.stories, edge.destination)),\n this.props.viewTransform,\n );\n\n let angle = new nt.VectBase(dest.x - source.x, dest.y - source.y).angle();\n if (angle > Math.PI * 0.5 && angle < Math.PI * 1.5) {\n angle -= Math.PI;\n }\n\n // Only display edge name if it can fit inside the viewport\n if (nt.euclideanDistanceVec(source, dest) > edge.name.length * 10) {\n labels.push(\n \n {edge.name}\n ,\n );\n }\n });\n\n return labels;\n }\n\n /**\n * Render an empty div, so componentDidMount will get called.\n */\n render() {\n const activeStory = AStorytelling.getActive(this.props.stories);\n\n return (\n
    \n {this.props.stories.active !== null && this.createStreetLabels(activeStory)}\n\n {this.props.hoverState.data &&\n isCluster(this.props.hoverState.data) &&\n this.props.hoverState.data.name &&\n hoverLabel(this.props.hoverState.data as ICluster, this.props.viewTransform, this.props.workspace)}\n\n {this.props.stories.trace &&\n this.props.stories.trace.mainPath.map((cluster) => {\n const clusterInstance = AStorytelling.retrieveCluster(this.props.stories, cluster);\n\n const screen = CameraTransformations.worldToScreen(\n ACluster.getCenterFromWorkspace(this.props.workspace, clusterInstance),\n this.props.viewTransform,\n );\n\n return (\n \n {clusterInstance.label}\n \n );\n })}\n
    \n );\n }\n },\n);\n","export enum Shapes {\n Circle = 'circle',\n Star = 'star',\n Square = 'square',\n Cross = 'cross',\n}\n","import { ACluster } from '../../model/Cluster';\nimport { ICluster } from '../../model/ICluster';\nimport { RenderingContextEx } from '../Utility/RenderingContextEx';\nimport { CameraTransformations } from './CameraTransformations';\nimport { Tool } from './Tool';\nimport { ViewTransformType } from '../Ducks/ViewTransformDuck';\nimport { IBaseProjection } from '../../model/ProjectionInterfaces';\n\nexport class TraceSelectTool implements Tool {\n workspace: IBaseProjection;\n\n cluster: ICluster;\n\n viewTransform: ViewTransformType;\n\n mousePosition: { x: number; y: number };\n\n constructor(workspace: IBaseProjection, cluster: ICluster) {\n this.workspace = workspace;\n this.cluster = cluster;\n }\n\n renderToContext(context: RenderingContextEx) {\n if (!this.cluster || !this.viewTransform) {\n return;\n }\n const start = CameraTransformations.worldToScreen(ACluster.getCenterFromWorkspace(this.workspace, this.cluster), this.viewTransform);\n\n context.lineWidth = '2';\n\n context.beginPath();\n context.arc(start.x, start.y, 16, 0, 2 * Math.PI, false);\n context.stroke();\n\n context.strokeStyle = 'red';\n context.beginPath();\n context.arc(this.mousePosition.x, this.mousePosition.y, 21, 0, 2 * Math.PI, false);\n context.stroke();\n }\n}\n","/* eslint-disable @typescript-eslint/no-var-requires */\nimport * as THREE from 'three';\n\n// @ts-ignore\nimport WhiteSq from '../../../textures/sprites/square_white.png';\n\n// @ts-ignore\nimport fragmentShader from '../../shaders/trail_fragment.glsl?raw';\n// @ts-ignore\nimport vertexShader from '../../shaders/trail_vertex.glsl?raw';\n\nexport class TrailVisualization {\n mesh: THREE.Points;\n\n maxLength = 50;\n\n create() {\n // hardcoded for 30 clusters, needs to be changed\n const len = 100 * 30;\n\n const positions = new Float32Array(len * 3);\n const colors = new Float32Array(len * 4);\n const sizes = new Float32Array(len);\n const types = new Float32Array(len);\n const show = new Float32Array(len);\n const selected = new Float32Array(len);\n\n const pointGeometry = new THREE.BufferGeometry();\n pointGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));\n pointGeometry.setAttribute('customColor', new THREE.BufferAttribute(colors, 4));\n pointGeometry.setAttribute('size', new THREE.BufferAttribute(sizes, 1));\n pointGeometry.setAttribute('type', new THREE.BufferAttribute(types, 1));\n pointGeometry.setAttribute('show', new THREE.BufferAttribute(show, 1));\n pointGeometry.setAttribute('selected', new THREE.BufferAttribute(selected, 1));\n\n //\n const pointMaterial = new THREE.ShaderMaterial({\n uniforms: {\n zoom: { value: 1.0 },\n color: { value: new THREE.Color(0xffffff) },\n scale: { value: 1.0 },\n atlas: {\n value: new THREE.TextureLoader().load(WhiteSq),\n },\n },\n transparent: true,\n vertexShader,\n fragmentShader,\n alphaTest: 0.05,\n });\n\n this.mesh = new THREE.Points(pointGeometry, pointMaterial);\n this.mesh.frustumCulled = false;\n }\n\n update(clusterObjects, zoom) {\n let i = 0;\n\n const position = this.mesh.geometry.attributes.position as THREE.BufferAttribute;\n const color = this.mesh.geometry.attributes.customColor as THREE.BufferAttribute;\n clusterObjects.forEach((clusterObject) => {\n const range = Math.min(this.maxLength, clusterObject.trailPositions.length);\n\n for (let j = 0; j < range; j++, i++) {\n const vector = clusterObject.trailPositions[clusterObject.trailPositions.length - 1 - j];\n\n position.setXYZ(i, vector.x * zoom, vector.y * zoom, -2);\n color.setXYZW(i, 0.33, 0.33, 0.33, 0.5 * ((clusterObject.trailPositions.length - 1 - j) / clusterObject.trailPositions.length));\n\n i += 1;\n }\n });\n\n // Only draw necessary part\n this.mesh.geometry.setDrawRange(0, i);\n\n position.needsUpdate = true;\n color.needsUpdate = true;\n }\n\n setVisible(show: boolean) {\n this.mesh.visible = show;\n }\n\n setLength(length: number) {\n this.maxLength = length;\n }\n}\n","import { ADataset, ColumnType, Dataset, IBaseProjection } from '../../model';\nimport { IVector } from '../../model/Vector';\n\n/**\n * Calculates the default zoom factor by examining the bounds of the data set\n * and then dividing it by the height of the viewport.\n */\nexport function getDefaultZoom(dataset: Dataset, width, height, xChannel: string, yChannel: string, workspace: IBaseProjection) {\n // Get rectangle that fits around data set\n let minX = 1000;\n let maxX = -1000;\n let minY = 1000;\n let maxY = -1000;\n\n const spatial = ADataset.getSpatialData(dataset, xChannel, yChannel, workspace);\n\n spatial.forEach((s) => {\n minX = Math.min(minX, s.x);\n maxX = Math.max(maxX, s.x);\n minY = Math.min(minY, s.y);\n maxY = Math.max(maxY, s.y);\n });\n\n const x = (maxX + minX) / 2;\n const y = (maxY + minY) / 2;\n\n // Get biggest scale\n const maxAbsX = Math.abs(maxX - x);\n const maxAbsY = Math.abs(maxY - y);\n\n const horizontal = width / maxAbsX;\n const vertical = height / maxAbsY;\n\n return { zoom: Math.min(horizontal / 2, vertical / 2), x, y };\n}\n\nexport function interpolateLinear(min, max, k) {\n return min + (max - min) * k;\n}\n\nexport function centerOfMass(points) {\n let x = 0;\n let y = 0;\n\n points.forEach((p) => {\n x += p.x;\n y += p.y;\n });\n\n return {\n x: x / points.length,\n y: y / points.length,\n };\n}\n\nexport function arraysEqual(a, b) {\n if (a === b) return true;\n if (a == null || b == null) return false;\n if (a.length !== b.length) return false;\n\n // If you don't care about the order of the elements inside\n // the array, you should sort both arrays here.\n // Please note that calling sort on an array will modify that array.\n // you might want to clone your array first.\n\n for (let i = 0; i < a.length; ++i) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n/**\n * Checks if 2 dictionaries are equal\n * @param {*} a\n * @param {*} b\n */\nexport function dictEqual(a, b) {\n let res = true;\n Object.keys(a).forEach((aKey) => {\n if (a[aKey] !== b[aKey]) {\n res = false;\n }\n });\n return res;\n}\n\nexport function normalizeWheel(/* object */ event) /* object */ {\n // Reasonable defaults\n const PIXEL_STEP = 10;\n const LINE_HEIGHT = 40;\n const PAGE_HEIGHT = 800;\n\n let sX = 0;\n let sY = 0; // spinX, spinY\n let pX = 0;\n let pY = 0; // pixelX, pixelY\n\n // Legacy\n if ('detail' in event) {\n sY = event.detail;\n }\n if ('wheelDelta' in event) {\n sY = -event.wheelDelta / 120;\n }\n if ('wheelDeltaY' in event) {\n sY = -event.wheelDeltaY / 120;\n }\n if ('wheelDeltaX' in event) {\n sX = -event.wheelDeltaX / 120;\n }\n\n // side scrolling on FF with DOMMouseScroll\n if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) {\n sX = sY;\n sY = 0;\n }\n\n pX = sX * PIXEL_STEP;\n pY = sY * PIXEL_STEP;\n\n if ('deltaY' in event) {\n pY = event.deltaY;\n }\n if ('deltaX' in event) {\n pX = event.deltaX;\n }\n\n if ((pX || pY) && event.deltaMode) {\n if (event.deltaMode === 1) {\n // delta in LINE units\n pX *= LINE_HEIGHT;\n pY *= LINE_HEIGHT;\n } else {\n // delta in PAGE units\n pX *= PAGE_HEIGHT;\n pY *= PAGE_HEIGHT;\n }\n }\n\n // Fall-back if spin cannot be determined\n if (pX && !sX) {\n sX = pX < 1 ? -1 : 1;\n }\n if (pY && !sY) {\n sY = pY < 1 ? -1 : 1;\n }\n\n return {\n spinX: sX,\n spinY: sY,\n pixelX: pX,\n pixelY: pY,\n };\n}\n\nexport function valueInRange(value, range) {\n if (range == null) return true;\n return value >= range[0] && value <= range[1];\n}\n\nexport function getMinMaxOfChannel(dataset: Dataset, key: string, segment?) {\n let min = null;\n let max = null;\n let center = null;\n\n if (dataset.columns[key].range) {\n min = dataset.columns[key].range.min;\n max = dataset.columns[key].range.max;\n center = dataset.columns[key].range.center;\n } else if (dataset.isSequential && segment) {\n const filtered = segment.vectors.map((vector) => vector[key]);\n max = Math.max(...filtered);\n min = Math.min(...filtered);\n center = (min + max) / 2;\n } else {\n const filtered = dataset.vectors.map((vector) => vector[key]);\n max = Math.max(...filtered);\n min = Math.min(...filtered);\n center = (min + max) / 2;\n }\n\n return { min, max, center };\n}\n","/* eslint-disable react/no-unused-state */\n/* eslint-disable react/sort-comp */\n/* eslint-disable operator-assignment */\n/* eslint-disable no-empty */\n/* eslint-disable react/display-name */\n/* eslint-disable @typescript-eslint/no-unused-vars */\nimport { EntityId } from '@reduxjs/toolkit';\nimport * as React from 'react';\nimport * as THREE from 'three';\nimport { connect, ConnectedProps } from 'react-redux';\nimport { Camera } from 'three';\nimport { Menu, MenuItem } from '@mui/material';\nimport { v4 as uuidv4 } from 'uuid';\nimport { getDefaultZoom, arraysEqual, normalizeWheel, interpolateLinear } from './UtilityFunctions';\nimport { LassoSelection } from './tools';\nimport { LassoLayer } from './LassoLayer';\nimport { ACluster, isCluster } from '../../model/Cluster';\nimport { ICluster } from '../../model/ICluster';\nimport { TypedObject } from '../../model/TypedObject';\nimport { isVector, IVector } from '../../model/Vector';\nimport { setViewTransform, ViewTransformType } from '../Ducks/ViewTransformDuck';\nimport { selectClusters, selectVectors } from '../Ducks/AggregationDuck';\nimport { CameraTransformations } from './CameraTransformations';\nimport { LineVisualization, PointVisualization } from './meshes';\nimport { MultivariateClustering } from './MultivariateClustering';\nimport { DisplayMode, displayModeSupportsStates } from '../Ducks/DisplayModeDuck';\nimport { setActiveLine } from '../Ducks/ActiveLineDuck';\nimport type { RootState } from '../Store/Store';\nimport * as nt from '../NumTs/NumTs';\nimport { MouseController } from './MouseController';\nimport { IBook, ABook } from '../../model/Book';\nimport { RenderingContextEx } from '../Utility/RenderingContextEx';\nimport { IEdge, isEdge } from '../../model/Edge';\nimport { getSyncNodesAlt } from '../NumTs/NumTs';\nimport { ClusterDragTool } from './ClusterDragTool';\nimport { TraceSelectTool } from './TraceSelectTool';\nimport { setOpenTabAction } from '../Ducks/OpenTabDuck';\nimport { setHoverState } from '../Ducks/HoverStateDuck';\nimport { pointInHull } from '../Utility/Geometry/Intersection';\nimport { Dataset } from '../../model/Dataset';\nimport { DataLine } from '../../model/DataLine';\nimport { ObjectTypes } from '../../model/ObjectType';\nimport { ComponentConfig } from '../../BaseConfig';\nimport { ANormalized } from '../Utility/NormalizedState';\nimport { StoriesActions, AStorytelling } from '../Ducks/StoriesDuck';\nimport { Mapping, mappingFromScale } from '../Utility';\nimport { ViewActions, SingleMultipleAttributes } from '../Ducks/ViewDuck';\nimport { IPosition, IProjection } from '../../model';\n\ntype ViewState = {\n camera: Camera;\n menuX: number;\n menuY: number;\n menuTarget: TypedObject;\n};\n\nconst mapStateToProps = (state: RootState) => ({\n currentAggregation: state.currentAggregation,\n dataset: state.dataset,\n highlightedSequence: state.highlightedSequence,\n activeLine: state.activeLine,\n advancedColoringSelection: state.advancedColoringSelection,\n clusterMode: state.clusterMode,\n displayMode: state.displayMode,\n stories: state.stories,\n trailSettings: state.trailSettings,\n hoverState: state.hoverState,\n colorScales: state.colorScales,\n pointDisplay: state.pointDisplay,\n});\n\nconst mapDispatchToProps = (dispatch) => ({\n activateView: (id: EntityId) => dispatch(ViewActions.activateView(id)),\n addView: (dataset: Dataset) => dispatch(ViewActions.addView(dataset)),\n selectVectors: (vectors: number[], shiftKey: boolean) => dispatch(selectVectors(vectors, shiftKey)),\n setActiveLine: (activeLine) => dispatch(setActiveLine(activeLine)),\n setViewTransform: (camera, width, height) => dispatch(setViewTransform(camera, width, height)),\n setHoverState: (hoverState, updater) => dispatch(setHoverState(hoverState, updater)),\n setPointColorMapping: (id: EntityId, mapping) => dispatch(ViewActions.setPointColorMapping({ multipleId: id, value: mapping })),\n removeClusterFromStories: (cluster: ICluster) => dispatch(StoriesActions.deleteCluster(cluster)),\n addStory: (book: IBook, activate: boolean) => dispatch(StoriesActions.addBookAsync({ book, activate })),\n addClusterToStory: (cluster: ICluster) => dispatch(StoriesActions.addCluster(cluster)),\n addEdgeToActive: (edge: IEdge) => dispatch(StoriesActions.addEdgeToActive(edge)),\n setActiveTrace: (trace) => dispatch(StoriesActions.setActiveTrace(trace)),\n setOpenTab: (tab) => dispatch(setOpenTabAction(tab)),\n setSelectedCluster: (clusters: string[], shiftKey: boolean) => dispatch(selectClusters(clusters, shiftKey)),\n removeEdgeFromActive: (edge) => dispatch(StoriesActions.removeEdgeFromActive(edge)),\n});\n\nconst connector = connect(mapStateToProps, mapDispatchToProps, null, { forwardRef: true });\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {\n overrideComponents: ComponentConfig;\n\n // The id for this visualization, important for selecting the correct slice\n multipleId: EntityId;\n workspace: IPosition[];\n projection: IProjection;\n} & Omit;\n\nconst UPDATER = 'scatter';\n\nexport const WebGLView = connector(\n class extends React.Component {\n lasso: LassoSelection;\n\n clusterDrag: ClusterDragTool;\n\n traceSelect: TraceSelectTool;\n\n particles: PointVisualization;\n\n containerRef: any;\n\n selectionRef: any;\n\n mouseDown: any;\n\n physicsRef: any;\n\n mouse: any;\n\n mouseDownPosition: any;\n\n initialMousePosition: any;\n\n currentHover: TypedObject;\n\n camera: THREE.OrthographicCamera;\n\n vectors: IVector[];\n\n renderer: THREE.WebGLRenderer;\n\n lines: LineVisualization;\n\n scene: THREE.Scene;\n\n dataset: any;\n\n lineColorScheme: any;\n\n segments: DataLine[];\n\n pointScene: THREE.Scene;\n\n vectorMapping: Mapping;\n\n prevTime: number;\n\n sourcePosition: any;\n\n targetPosition: { x: number; y: number };\n\n sourceZoom: any;\n\n targetZoom: number;\n\n transitionTime: number;\n\n trees: any[];\n\n edgeClusters: any;\n\n lastTime: number;\n\n mouseMoveListener: any;\n\n mouseDownListener: any;\n\n mouseLeaveListener: any;\n\n keyDownListener: any;\n\n wheelListener: any;\n\n mouseUpListener: any;\n\n infoTimeout: any;\n\n multivariateClusterView: any = React.createRef();\n\n invalidated: boolean;\n\n mouseController: MouseController = new MouseController();\n\n constructor(props) {\n super(props);\n\n this.containerRef = React.createRef();\n this.selectionRef = React.createRef();\n this.physicsRef = React.createRef();\n\n this.initMouseController();\n\n this.mouse = { x: 0, y: 0 };\n\n this.currentHover = null;\n\n this.state = {\n // clusters to display using force-directed layout\n camera: null,\n menuX: null,\n menuY: null,\n menuTarget: null,\n };\n }\n\n chooseCluster(screenPosition: { x: number; y: number }): ICluster {\n let nearest: ICluster = null;\n let min = Number.MAX_SAFE_INTEGER;\n\n const activeStory = AStorytelling.getActive(this.props.stories);\n\n if (!activeStory) {\n return null;\n }\n\n for (const [key, cluster] of Object.entries(activeStory.clusters.entities)) {\n const clusterScreen = CameraTransformations.worldToScreen(\n new THREE.Vector2(ACluster.getCenterFromWorkspace(this.props.workspace, cluster).x, ACluster.getCenterFromWorkspace(this.props.workspace, cluster).y),\n this.createTransform(),\n );\n const dist = nt.euclideanDistance(screenPosition.x, screenPosition.y, clusterScreen.x, clusterScreen.y);\n\n if (dist < min && dist < 16) {\n nearest = cluster;\n min = dist;\n }\n }\n\n return nearest;\n }\n\n chooseEdge(position) {\n if (this.props.stories.active === null) {\n return null;\n }\n\n const activeStory = AStorytelling.getActive(this.props.stories);\n\n position = CameraTransformations.screenToWorld(position, this.createTransform());\n\n for (const edge of Object.values(activeStory.edges.entities)) {\n const a = ACluster.getCenterAsVector2(this.props.workspace, AStorytelling.retrieveCluster(this.props.stories, edge.source));\n const b = ACluster.getCenterAsVector2(this.props.workspace, AStorytelling.retrieveCluster(this.props.stories, edge.destination));\n const dir = b.clone().sub(a.clone()).normalize();\n const l = new THREE.Vector2(-dir.y, dir.x).multiplyScalar(0.5);\n const r = new THREE.Vector2(dir.y, -dir.x).multiplyScalar(0.5);\n\n const hull = [a.clone().add(l), b.clone().add(l), b.clone().add(r), a.clone().add(r)];\n\n if (pointInHull(position, hull)) {\n return edge;\n }\n }\n\n return null;\n }\n\n /**\n * Gives the index of the nearest sample.\n *\n * @param position - The position to pick a sample from\n * @returns The index of a sample\n */\n choose(position) {\n let best = 30 / (this.camera.zoom * 2.0);\n let res = -1;\n\n for (let index = 0; index < this.props.dataset.vectors.length; index++) {\n const value = this.props.workspace[index];\n\n // Skip points matching some criteria\n if (!this.particles.isPointVisible(this.props.dataset.vectors[index])) {\n continue;\n }\n\n const d = nt.euclideanDistance(position.x, position.y, value.x, value.y);\n\n if (d < best) {\n best = d;\n res = index;\n }\n }\n return res;\n }\n\n /**\n * Converts mouse coordinates to world coordinates.\n * @param {*} event a dom mouse event.\n */\n relativeMousePosition(event) {\n const rect = this.containerRef.current.getBoundingClientRect();\n\n return {\n x: event.clientX - rect.left,\n y: event.clientY - rect.top,\n };\n }\n\n normaliseMouse(event) {\n const vec = {\n x: (event.clientX / window.innerWidth) * 2 - 1,\n y: -(event.clientY / window.innerHeight) * 2 + 1,\n };\n return vec;\n }\n\n resize(width, height) {\n this.camera.left = width / -2;\n\n this.camera.right = width / 2;\n this.camera.top = height / 2;\n this.camera.bottom = height / -2;\n\n this.camera.updateProjectionMatrix();\n this.renderer.setSize(width, height);\n\n this.props.setViewTransform(this.camera, width, height);\n\n this.requestRender();\n }\n\n onKeyDown(event) {}\n\n onMouseLeave(event) {\n event.preventDefault();\n if (this.props.dataset) this.mouseController.mouseLeave(event);\n }\n\n onMouseDown(event) {\n event.preventDefault();\n this.props.activateView(this.props.multipleId);\n if (this.props.dataset) this.mouseController.mouseDown(event);\n }\n\n onMouseMove(event) {\n event.preventDefault();\n if (this.props.dataset) this.mouseController.mouseMove(event);\n }\n\n onMouseUp(event: MouseEvent) {\n event.preventDefault();\n this.props.activateView(this.props.multipleId);\n if (this.props.dataset) this.mouseController.mouseUp(event);\n }\n\n clearSelection() {\n this.lasso = null;\n\n if (this.props.dataset.isSequential) {\n this.lines.highlight([], this.getWidth(), this.getHeight(), this.scene);\n\n this.lines.groupHighlight([]);\n } else {\n this.particles.groupHighlight([]);\n }\n\n this.props.dataset.vectors.forEach((vector, index) => {\n vector.__meta__.selected = false;\n });\n\n this.props.selectVectors([], false);\n\n this.particles?.updateColor(this.createAdditionalColumns());\n }\n\n onWheel(event) {\n event.preventDefault();\n\n if (!this.props.dataset) {\n return;\n }\n\n const normalized = normalizeWheel(event);\n\n // AProjection.calculateBounds(this.props.dataset, this.props.projection.xChannel, this.props.projection.yChannel, this.props.workspace);\n\n // Store world position under mouse\n const bounds = this.containerRef.current.getBoundingClientRect();\n const worldBefore = CameraTransformations.screenToWorld({ x: event.clientX - bounds.left, y: event.clientY - bounds.top }, this.createTransform());\n const screenBefore = this.relativeMousePosition(event);\n\n const newZoom = this.camera.zoom - (normalized.pixelY * 0.013) / this.props.projection.bounds.scaleFactor;\n if (newZoom < 1.0 / this.props.projection.bounds.scaleFactor) {\n this.camera.zoom = 1.0 / this.props.projection.bounds.scaleFactor;\n } else {\n this.camera.zoom = newZoom;\n }\n\n // Restore camera position\n this.restoreCamera(worldBefore, screenBefore);\n\n // Adjust mesh zoom levels\n this.particles.zoom(this.camera.zoom, this.props.projection);\n\n if (this.props.dataset.isSequential) {\n this.lines.setZoom(this.camera.zoom);\n }\n\n // Update projection matrix\n this.camera.updateProjectionMatrix();\n\n this.props.setViewTransform(this.camera, this.getWidth(), this.getHeight());\n\n this.requestRender();\n }\n\n restoreCamera(world, screen) {\n this.camera.position.x = world.x - (screen.x - this.getWidth() / 2) / this.camera.zoom;\n this.camera.position.y = world.y + (screen.y - this.getHeight() / 2) / this.camera.zoom;\n }\n\n getWidth() {\n return this.containerRef.current?.offsetWidth;\n }\n\n getHeight() {\n return this.containerRef.current?.offsetHeight;\n }\n\n /**\n * Initializes the callbacks for the MouseController.\n */\n initMouseController() {\n this.mouseController.onMouseLeave = (event: MouseEvent) => {\n if (this.infoTimeout != null) {\n clearTimeout(this.infoTimeout);\n }\n\n this.particles?.highlight(null);\n\n if (this.props.dataset?.isSequential) {\n this.lines?.highlight([], this.getWidth(), this.getHeight(), this.scene);\n }\n\n if (this.currentHover) {\n this.currentHover = null;\n this.props.setHoverState(null, UPDATER);\n this.requestRender();\n }\n };\n\n this.mouseController.onDragStart = (event: MouseEvent, button: number, initial: nt.VectorType) => {\n switch (button) {\n case 0: {\n // Check if we have dragged from a cluster\n const cluster = this.chooseCluster(initial);\n if (cluster) {\n // Initiate action to let user drag an arrow to other cluster\n this.clusterDrag = new ClusterDragTool(cluster);\n } else {\n // Initiate lasso selection\n const initialWorld = CameraTransformations.screenToWorld(initial, this.createTransform());\n\n this.lasso = new LassoSelection();\n this.lasso.mouseDown(true, initialWorld.x, initialWorld.y);\n }\n break;\n }\n default:\n break;\n }\n };\n\n this.mouseController.onDragEnd = (event: MouseEvent, button: number) => {\n switch (button) {\n case 0: {\n const coords = CameraTransformations.screenToWorld({ x: event.offsetX, y: event.offsetY }, this.createTransform());\n\n // In case we dragged a cluster... connect them\n if (this.clusterDrag) {\n const cluster = this.chooseCluster({ x: event.offsetX, y: event.offsetY });\n\n if (cluster) {\n const activeStory = AStorytelling.getActive(this.props.stories);\n\n const source = Object.keys(activeStory.clusters.entities).find((key) => activeStory.clusters.entities[key] === this.clusterDrag.cluster);\n const destination = Object.keys(activeStory.clusters.entities).find((key) => activeStory.clusters.entities[key] === cluster);\n\n if (\n activeStory.edges.ids.map((id) => activeStory.edges.entities[id]).find((e) => e.source === source && e.destination === destination) ===\n undefined\n ) {\n this.props.addEdgeToActive({\n id: uuidv4(),\n source,\n destination,\n objectType: ObjectTypes.Edge,\n });\n }\n }\n\n this.clusterDrag = null;\n }\n\n // In case we have a lasso, select states\n if (this.lasso) {\n // If there is an active lasso, process it\n const wasDrawing = this.lasso.drawing;\n\n this.lasso.mouseUp(coords.x, coords.y);\n\n const indices = this.lasso.selection(this.props.dataset, this.props.workspace, (vector) => this.particles.isPointVisible(vector));\n if (indices.length > 0 && wasDrawing && displayModeSupportsStates(this.props.displayMode)) {\n this.props.selectVectors(indices, event.ctrlKey);\n\n this.props.setOpenTab(4);\n } else if (wasDrawing) {\n this.clearSelection();\n }\n\n this.lasso = null;\n }\n break;\n }\n default:\n break;\n }\n };\n\n this.mouseController.onDragMove = (event: MouseEvent, button: number) => {\n switch (button) {\n case 0: {\n const coords = CameraTransformations.screenToWorld({ x: event.offsetX, y: event.offsetY }, this.createTransform());\n this.lasso?.mouseMove(coords.x, coords.y);\n break;\n }\n case 2: {\n this.camera.position.x = this.camera.position.x - CameraTransformations.pixelToWorldCoordinates(event.movementX, this.createTransform());\n this.camera.position.y = this.camera.position.y + CameraTransformations.pixelToWorldCoordinates(event.movementY, this.createTransform());\n\n this.camera.updateProjectionMatrix();\n this.props.setViewTransform(this.camera, this.getWidth(), this.getHeight());\n\n this.requestRender();\n break;\n }\n default:\n break;\n }\n };\n\n this.mouseController.onContext = (event: MouseEvent, button: number) => {\n switch (button) {\n case 0:\n if (this.props.activeLine) {\n break;\n }\n\n if (this.traceSelect) {\n const target = this.chooseCluster({ x: event.offsetX, y: event.offsetY });\n\n if (target) {\n const activeStory = AStorytelling.getActive(this.props.stories);\n // We want to select a trace between 2 clusters\n const paths = ABook.depthFirstSearch(\n ABook.toGraph(activeStory),\n Object.entries(activeStory.clusters.entities).find(([key, value]) => value === this.traceSelect.cluster)[0],\n Object.entries(activeStory.clusters.entities).find(([key, value]) => value === target)[0],\n );\n\n if (paths.length > 0) {\n const mainPath = paths[0];\n const mainEdges = mainPath.slice(1).map((item, index) => {\n const [resultEdgeKey, _] = Object.entries(activeStory.edges.entities).find(\n ([key, edge]) => edge.source === mainPath[index] && edge.destination === item,\n );\n return resultEdgeKey;\n });\n this.props.setActiveTrace({\n mainPath,\n mainEdges,\n sidePaths: paths.slice(1).map((ids) => {\n const path = ids;\n const edges = path.slice(1).map((item, index) => {\n const [resultEdgeKey, _] = Object.entries(activeStory.edges.entities).find(\n ([key, edge]) => edge.source === path[index] && edge.destination === item,\n );\n return resultEdgeKey;\n });\n return {\n nodes: path,\n edges,\n syncNodes: getSyncNodesAlt(mainPath, path),\n };\n }),\n });\n }\n }\n\n this.traceSelect = null;\n } else if (this.currentHover && isVector(this.currentHover)) {\n // We click on a hover target\n this.props.selectVectors([this.currentHover.__meta__.meshIndex], event.ctrlKey);\n } else if (this.currentHover && isCluster(this.currentHover)) {\n const activeStory = AStorytelling.getActive(this.props.stories);\n this.props.setSelectedCluster(\n [Object.keys(activeStory.clusters.entities).find((key) => activeStory.clusters.entities[key] === this.currentHover)],\n event.ctrlKey,\n );\n }\n\n break;\n case 2: {\n const cluster = this.chooseCluster({ x: event.offsetX, y: event.offsetY });\n\n if (cluster) {\n this.setState({\n menuX: event.clientX,\n menuY: event.clientY,\n menuTarget: cluster,\n });\n } else {\n const edge = this.chooseEdge(this.mouseController.currentMousePosition);\n if (edge) {\n this.setState({\n menuX: event.clientX,\n menuY: event.clientY,\n menuTarget: edge,\n });\n } else {\n this.setState({\n menuX: event.clientX,\n menuY: event.clientY,\n menuTarget: null,\n });\n }\n }\n\n break;\n }\n default:\n break;\n }\n };\n\n this.mouseController.onMouseUp = (event: MouseEvent) => {};\n\n this.mouseController.onMouseMove = (event: MouseEvent) => {\n if (this.props.displayMode === DisplayMode.OnlyClusters) {\n return;\n }\n\n // In case we have a line in the sequence UI\n if (this.props.activeLine) {\n return;\n }\n\n if (this.infoTimeout != null) {\n clearTimeout(this.infoTimeout);\n }\n\n this.infoTimeout = setTimeout(() => {\n this.infoTimeout = null;\n\n const cluster = this.chooseCluster(this.mouseController.currentMousePosition);\n if (cluster) {\n if (this.currentHover !== cluster) {\n this.currentHover = cluster;\n this.props.setHoverState(cluster, UPDATER);\n\n if (this.props.dataset.isSequential) {\n this.lines.highlight([], this.getWidth(), this.getHeight(), this.scene);\n }\n this.particles.highlight(-1);\n\n this.requestRender();\n }\n } else {\n const coords = CameraTransformations.screenToWorld(this.mouseController.currentMousePosition, this.createTransform());\n\n const edge = this.chooseEdge(this.mouseController.currentMousePosition);\n\n if (edge) {\n if (this.currentHover !== edge) {\n this.currentHover = edge;\n this.props.setHoverState(edge, UPDATER);\n }\n } else {\n // Get index of selected node\n const idx = this.choose(coords);\n this.particles.highlight(idx);\n\n if (this.props.dataset.isSequential) {\n if (idx >= 0) {\n this.lines.highlight([this.props.dataset.vectors[idx].line], this.getWidth(), this.getHeight(), this.scene);\n } else {\n this.lines.highlight([], this.getWidth(), this.getHeight(), this.scene);\n }\n }\n\n if (idx >= 0) {\n if (this.currentHover !== this.props.dataset.vectors[idx]) {\n this.currentHover = this.props.dataset.vectors[idx];\n\n this.props.setHoverState(this.props.dataset.vectors[idx], UPDATER);\n this.requestRender();\n }\n } else if (this.currentHover) {\n this.currentHover = null;\n this.props.setHoverState(null, UPDATER);\n this.requestRender();\n }\n }\n }\n }, 10);\n };\n }\n\n setupRenderer() {\n this.renderer = new THREE.WebGLRenderer({\n antialias: true,\n alpha: true,\n });\n this.renderer.autoClear = true;\n this.renderer.autoClearColor = false;\n\n this.renderer.setPixelRatio(window.devicePixelRatio);\n this.renderer.setSize(this.getWidth(), this.getHeight());\n this.renderer.setClearColor(0x000000, 0);\n this.renderer.sortObjects = false;\n this.renderer.localClippingEnabled = false;\n\n this.camera = new THREE.OrthographicCamera(this.getWidth() / -2, this.getWidth() / 2, this.getHeight() / 2, this.getHeight() / -2, 0, 1000);\n this.camera.position.z = 1;\n this.camera.lookAt(new THREE.Vector3(0, 0, 0));\n this.camera.near = 0;\n this.camera.far = 100000;\n\n // this.camera.position.x = this.props.viewTransform.centerX\n // this.camera.position.y = this.props.viewTransform.centerY\n // this.camera.zoom = this.props.viewTransform.zoom\n\n this.camera.updateProjectionMatrix();\n\n this.containerRef.current.appendChild(this.renderer.domElement);\n\n this.prevTime = performance.now();\n }\n\n createVisualization(dataset, lineColorScheme, vectorMapping) {\n this.disposeScene();\n\n this.scene = new THREE.Scene();\n this.pointScene = new THREE.Scene();\n this.segments = dataset.segments;\n this.lineColorScheme = lineColorScheme;\n this.vectorMapping = vectorMapping;\n\n const { zoom, x, y } = getDefaultZoom(\n dataset,\n this.getWidth(),\n this.getHeight(),\n this.props.projection.xChannel,\n this.props.projection.yChannel,\n this.props.workspace,\n );\n\n // Update camera zoom to fit the problem\n this.camera.zoom = zoom;\n this.camera.position.x = x;\n this.camera.position.y = y;\n this.camera.position.z = 10;\n this.camera.updateProjectionMatrix();\n\n this.props.setViewTransform(this.camera, this.getWidth(), this.getHeight());\n\n this.setState({\n camera: this.camera,\n });\n\n if (this.props.dataset.isSequential) {\n this.lines = new LineVisualization(this.segments, this.lineColorScheme);\n this.lines.createMesh(this.props.lineBrightness);\n this.lines.setZoom(this.camera.zoom);\n\n // First add lines, then particles\n this.lines.meshes.forEach((line) => this.scene.add(line.line));\n }\n\n this.particles = new PointVisualization(\n this.vectorMapping,\n this.props.dataset,\n window.devicePixelRatio * 8,\n this.lines?.grayedLayerSystem,\n this.segments,\n );\n this.particles.createMesh(this.props.dataset.vectors, this.segments, () => {\n this.updateXY();\n this.requestRender();\n });\n this.particles.zoom(this.camera.zoom, this.props.projection);\n this.particles.update();\n\n // this.scene.add(this.particles.mesh);\n this.pointScene.add(this.particles.mesh);\n }\n\n initializeContainerEvents() {\n const container = this.containerRef.current;\n // Remove old listeners\n container.removeEventListener('mousemove', this.mouseMoveListener);\n container.removeEventListener('mousedown', this.mouseDownListener);\n container.removeEventListener('mouseup', this.mouseUpListener);\n container.removeEventListener('keydown', this.keyDownListener);\n container.removeEventListener('wheel', this.wheelListener);\n\n // Store new listeners\n this.wheelListener = (event) => this.onWheel(event);\n this.mouseDownListener = (event) => this.onMouseDown(event);\n this.mouseMoveListener = (event) => this.onMouseMove(event);\n this.mouseUpListener = (event) => this.onMouseUp(event);\n this.keyDownListener = (event) => this.onKeyDown(event);\n\n // Add new listeners\n container.addEventListener('mousemove', this.mouseMoveListener, false);\n container.addEventListener('mousedown', this.mouseDownListener, false);\n container.addEventListener('mouseup', this.mouseUpListener, false);\n container.addEventListener('keydown', this.keyDownListener);\n container.addEventListener('wheel', this.wheelListener, false);\n\n // @ts-ignore\n new ResizeObserver(() => {\n this.resize(container.offsetWidth, container.offsetHeight);\n }).observe(container);\n }\n\n filterLines(algo, show) {\n this.segments.forEach((segment) => {\n if (segment.vectors[0].algo === algo) {\n segment.__meta__.globalVisible = show;\n\n segment.vectors.forEach((vector) => {\n vector.__meta__.visible = show;\n });\n }\n });\n\n this.lines.update();\n this.particles.update();\n }\n\n /**\n *\n * @param checked\n */\n setLineFilter(checked) {\n this.segments.forEach((segment) => {\n const show = checked[segment.vectors[0].line];\n segment.__meta__.detailVisible = show;\n });\n this.lines.update();\n this.particles.update();\n }\n\n /**\n * Updates the x,y coordinates of the visualization only. This will also\n * recalculate the optimal camera zoom level.\n */\n updateXY() {\n if (this.props.workspace) {\n this.particles.updatePosition(this.props.workspace);\n\n if (this.props.dataset.isSequential) {\n this.lines.updatePosition(this.props.workspace);\n }\n\n // AProjection.calculateBounds(this.props.dataset, this.props.projection.xChannel, this.props.projection.yChannel, this.props.workspace);\n // ADataset.calculateBounds(this.props.dataset, this.props.projection.xChannel, this.props.projection.yChannel, this.props.workspace);\n\n const { zoom, x, y } = getDefaultZoom(\n this.props.dataset,\n this.getWidth(),\n this.getHeight(),\n this.props.projection.xChannel,\n this.props.projection.yChannel,\n this.props.workspace,\n );\n\n this.camera.zoom = zoom;\n\n this.camera.position.x = x;\n this.camera.position.y = y;\n\n this.camera.updateProjectionMatrix();\n\n this.requestRender();\n }\n }\n\n filterPoints(checkboxes) {\n this.particles.showSymbols = checkboxes;\n this.particles.update();\n }\n\n disposeScene() {\n this.currentHover = null;\n\n if (this.lines != null && this.scene != null) {\n this.lines.dispose(this.scene);\n this.lines = null;\n }\n\n if (this.particles != null && this.scene != null) {\n this.scene.remove(this.particles.mesh);\n this.particles.dispose();\n this.particles = null;\n }\n\n if (this.renderer != null) {\n this.renderer.renderLists.dispose();\n }\n }\n\n /**\n * Starts the render loop\n */\n startRendering() {\n requestAnimationFrame(() => this.startRendering());\n\n try {\n this.renderLoop();\n } catch {}\n }\n\n updateZoom(deltaTime) {\n if (this.targetPosition != null && this.targetZoom != null) {\n // Update transition time, maxing at 1\n this.transitionTime = Math.min(this.transitionTime + deltaTime, 1);\n\n // Update zoom level and position\n this.camera.position.x = interpolateLinear(this.sourcePosition.x, this.targetPosition.x, this.transitionTime);\n this.camera.position.y = interpolateLinear(this.sourcePosition.y, this.targetPosition.y, this.transitionTime);\n // this.camera.zoom = interpolateLinear(this.sourceZoom, this.targetZoom, this.transitionTime)\n this.camera.updateProjectionMatrix();\n\n this.requestRender();\n\n // End transition\n if (this.transitionTime === 1) {\n this.sourcePosition = null;\n this.sourceZoom = null;\n this.targetPosition = null;\n this.targetZoom = null;\n this.transitionTime = 0;\n }\n }\n }\n\n /**\n * Render function that gets called with the display refresh rate.\n * Only render overlays here like the lasso selection etc.\n * The rendering of the states + lines and stuff that does not need to be\n * re-rendered for animations should be put in 'requestRender'\n */\n renderLoop() {\n const ctx = this.selectionRef.current.getContext() as CanvasRenderingContext2D;\n const extended = new RenderingContextEx(ctx, window.devicePixelRatio);\n ctx.clearRect(0, 0, this.getWidth(), this.getHeight());\n\n this.selectionRef.current.setDimensions(this.getWidth() * window.devicePixelRatio, this.getHeight() * window.devicePixelRatio);\n\n this.renderLasso(ctx);\n\n if (this.clusterDrag) {\n this.clusterDrag.renderToContext(\n extended,\n CameraTransformations.worldToScreen(ACluster.getCenterFromWorkspace(this.props.workspace, this.clusterDrag.cluster), this.createTransform()),\n this.mouseController.currentMousePosition,\n );\n }\n\n if (this.traceSelect) {\n this.traceSelect.viewTransform = this.createTransform();\n this.traceSelect.mousePosition = this.mouseController.currentMousePosition;\n this.traceSelect.renderToContext(extended);\n }\n\n if (this.props.highlightedSequence != null) {\n this.selectionRef.current.renderHighlightedSequence(ctx, this.props.highlightedSequence);\n }\n }\n\n onClusterClicked(cluster: ICluster, shiftKey = false) {\n const activeStory = AStorytelling.getActive(this.props.stories);\n this.props.setSelectedCluster([Object.keys(activeStory.clusters.entities).find((key) => activeStory.clusters.entities[key] === cluster)], shiftKey);\n }\n\n renderFrame() {\n this.invalidated = false;\n\n // Calculate delta time\n const nextTime = performance.now();\n const deltaTime = (nextTime - this.lastTime) / 1000;\n this.lastTime = nextTime;\n\n // Update zoom in case a target has been set\n this.updateZoom(deltaTime);\n\n try {\n const camera = new THREE.OrthographicCamera(this.getWidth() / -2, this.getWidth() / 2, this.getHeight() / 2, this.getHeight() / -2, 1, 1000);\n camera.lookAt(0, 0, 0);\n camera.position.z = 1;\n camera.position.x = this.camera.position.x * this.camera.zoom;\n camera.position.y = this.camera.position.y * this.camera.zoom;\n // camera.position.x = this.props.viewTransform.centerX\n // camera.position.y = this.props.viewTransform.centerY\n // camera.zoom = this.props.viewTransform.zoom\n camera.updateProjectionMatrix();\n\n this.renderer.clear();\n this.renderer.render(this.scene, this.camera);\n\n if (this.multivariateClusterView.current) {\n this.multivariateClusterView.current.updatePositions(this.camera.zoom);\n this.multivariateClusterView.current.updateArrows(this.camera.zoom, this.props.stories.active);\n this.multivariateClusterView.current.updateTrail(this.camera.zoom);\n\n if (this.multivariateClusterView.current.scene) {\n this.renderer.render(this.multivariateClusterView.current.scene, camera);\n }\n if (this.multivariateClusterView.current.scalingScene) {\n this.renderer.render(this.multivariateClusterView.current.scalingScene, this.camera);\n }\n }\n\n if (this.pointScene) {\n this.renderer.render(this.pointScene, this.camera);\n }\n\n if (this.multivariateClusterView.current) {\n if (this.multivariateClusterView.current.clusterScene) {\n this.renderer.render(this.multivariateClusterView.current.clusterScene, camera);\n }\n }\n } catch (e) {}\n }\n\n updateItemClusterDisplay() {\n switch (this.props.displayMode) {\n case DisplayMode.StatesAndClusters:\n case DisplayMode.OnlyStates:\n if (this.props.dataset.isSequential) {\n this.lines.meshes.forEach((line) => {\n this.scene.remove(line.line);\n this.scene.add(line.line);\n });\n }\n\n this.pointScene.remove(this.particles.mesh);\n this.pointScene.add(this.particles.mesh);\n break;\n case DisplayMode.OnlyClusters:\n case DisplayMode.None:\n if (this.props.dataset.isSequential) {\n this.lines.meshes.forEach((line) => {\n this.scene.remove(line.line);\n });\n }\n\n this.pointScene.remove(this.particles.mesh);\n break;\n default:\n break;\n }\n }\n\n createAdditionalColumns() {\n return {\n groupLabel: this.props.stories.groupLabel,\n };\n }\n\n componentDidMount() {\n this.initializeContainerEvents();\n this.setupRenderer();\n if (this.props.dataset) {\n this.createVisualization(\n this.props.dataset,\n mappingFromScale({ type: 'categorical', palette: 'dark2' }, 'algo', this.props.dataset, this.createAdditionalColumns()),\n null,\n );\n\n this.particles?.updateColor(this.createAdditionalColumns());\n\n this.particles.sizeCat(this.props.channelSize, this.props.globalPointSize);\n this.particles.updateSize();\n\n if (this.props.channelColor && this.props.pointColorScale) {\n const mapping = mappingFromScale(\n ANormalized.get(this.props.colorScales.scales, this.props.pointColorScale as string),\n this.props.channelColor.key,\n this.props.dataset,\n );\n this.props.setPointColorMapping(this.props.multipleId, mapping);\n\n this.particles.setColorByChannel(this.props.channelColor, mapping, this.createAdditionalColumns());\n }\n }\n this.startRendering();\n }\n\n componentDidUpdate(prevProps: Props, prevState) {\n if (prevProps.dataset !== this.props.dataset) {\n this.createVisualization(\n this.props.dataset,\n mappingFromScale({ type: 'categorical', palette: 'dark2' }, 'algo', this.props.dataset, this.createAdditionalColumns()),\n null,\n );\n }\n\n if (\n prevProps.pointColorScale !== this.props.pointColorScale ||\n prevProps.stories !== this.props.stories ||\n prevProps.channelColor !== this.props.channelColor\n ) {\n if (this.props.channelColor && this.props.pointColorScale) {\n const mapping = mappingFromScale(\n ANormalized.get(this.props.colorScales.scales, this.props.pointColorScale as string),\n this.props.channelColor.key,\n this.props.dataset,\n this.createAdditionalColumns(),\n );\n this.props.setPointColorMapping(this.props.multipleId, mapping);\n } else {\n this.props.setPointColorMapping(this.props.multipleId, null);\n }\n }\n\n if (prevProps.pointColorMapping !== this.props.pointColorMapping) {\n this.particles?.setColorByChannel(this.props.channelColor, this.props.pointColorMapping, this.createAdditionalColumns());\n }\n\n if (prevProps.stories !== this.props.stories) {\n if (this.props.stories.active !== null) {\n this.particles?.storyTelling(this.props.stories);\n\n this.lines?.storyTelling(this.props.stories, this.props.dataset.vectors);\n this.lines?.update();\n\n this.particles?.update();\n this.particles?.updateColor(this.createAdditionalColumns());\n } else {\n this.particles?.storyTelling(null);\n\n this.lines?.storyTelling(this.props.stories, this.props.dataset.vectors);\n this.lines?.update();\n\n this.particles?.update();\n this.particles?.updateColor(this.createAdditionalColumns());\n }\n }\n\n if (prevProps.globalPointSize !== this.props.globalPointSize || (prevProps.channelSize !== this.props.channelSize && this.particles)) {\n this.particles.sizeCat(this.props.channelSize, this.props.globalPointSize);\n this.particles.updateSize();\n }\n\n if (\n prevProps.globalPointBrightness !== this.props.globalPointBrightness ||\n (prevProps.channelBrightness !== this.props.channelBrightness && this.particles)\n ) {\n this.particles.setBrightnessByChannel(this.props.channelBrightness, this.props.globalPointBrightness);\n this.particles.updateColor(this.createAdditionalColumns());\n this.particles.update();\n }\n\n if (prevProps.lineBrightness !== this.props.lineBrightness) {\n this.lines?.setBrightness(this.props.lineBrightness);\n }\n\n if (prevProps.displayMode !== this.props.displayMode) {\n this.updateItemClusterDisplay();\n }\n\n if (!arraysEqual(prevProps.currentAggregation.aggregation, this.props.currentAggregation.aggregation)) {\n const vectorSelection = this.props.currentAggregation.aggregation.map((i) => this.props.dataset.vectors[i]);\n\n if (this.props.dataset.isSequential) {\n const uniqueIndices = [...new Set(vectorSelection.map((vector) => vector.line))];\n\n this.lines.groupHighlight(uniqueIndices);\n } else {\n this.particles.groupHighlight(this.props.currentAggregation.aggregation);\n }\n\n this.props.dataset.vectors.forEach((sample) => {\n sample.__meta__.selected = false;\n });\n vectorSelection.forEach((sample) => {\n sample.__meta__.selected = true;\n });\n\n this.particles.update();\n this.particles.updateColor(this.createAdditionalColumns());\n }\n\n if (prevProps.hoverState !== this.props.hoverState) {\n const hover_item = this.props.hoverState.data;\n\n if (isVector(hover_item)) {\n const idx = hover_item.__meta__.meshIndex;\n\n this.particles.highlight(idx);\n if (this.props.dataset.isSequential) {\n if (idx >= 0) {\n this.lines.highlight([this.props.dataset.vectors[idx].line], this.getWidth(), this.getHeight(), this.scene);\n } else {\n this.lines.highlight([], this.getWidth(), this.getHeight(), this.scene);\n }\n }\n if (idx >= 0) {\n if (this.currentHover !== this.props.dataset.vectors[idx]) {\n this.currentHover = this.props.dataset.vectors[idx];\n this.requestRender();\n }\n } else if (this.currentHover) {\n this.currentHover = null;\n this.requestRender();\n }\n }\n }\n\n // Path length range has changed, update view accordingly\n if (this.props.dataset && this.props.dataset.isSequential && prevProps.pathLengthRange !== this.props.pathLengthRange) {\n // Set path length range on all segment views, and update them\n this.lines.pathLengthRange = this.props.pathLengthRange.range;\n this.particles.pathLengthRange = this.props.pathLengthRange.range;\n\n this.lines.update();\n this.particles.update();\n this.particles.updateColor(this.createAdditionalColumns());\n }\n\n if (prevProps.vectorByShape !== this.props.vectorByShape && this.particles) {\n this.filterPoints({ star: true, cross: true, circle: true, square: true });\n this.particles.setShapeByChannel(this.props.vectorByShape);\n }\n\n if (prevProps.pointDisplay.checkedShapes !== this.props.pointDisplay.checkedShapes && this.particles) {\n this.filterPoints(this.props.pointDisplay.checkedShapes);\n }\n\n if (prevProps.activeLine !== this.props.activeLine) {\n if (this.props.activeLine != null) {\n this.lines.highlight([this.props.activeLine], this.getWidth(), this.getHeight(), this.scene, true);\n } else {\n this.lines.highlight([], this.getWidth(), this.getHeight(), this.scene, true);\n this.particles.update();\n this.particles.updateColor(this.createAdditionalColumns());\n }\n }\n\n if (prevProps.advancedColoringSelection !== this.props.advancedColoringSelection && this.particles) {\n this.particles.colorFilter(this.props.advancedColoringSelection);\n }\n\n if (prevProps.workspace !== this.props.workspace) {\n this.updateXY();\n }\n\n this.requestRender();\n }\n\n requestRender() {\n if (this.invalidated) {\n return;\n }\n this.invalidated = true;\n requestAnimationFrame(() => this.renderFrame());\n }\n\n createTransform(): ViewTransformType {\n return {\n centerX: this.camera.position.x,\n centerY: this.camera.position.y,\n width: this.getWidth(),\n height: this.getHeight(),\n zoom: this.camera.zoom,\n };\n }\n\n renderLasso(ctx) {\n if (this.lasso == null) return;\n\n const { points } = this.lasso;\n\n if (points.length <= 1) {\n return;\n }\n\n ctx.setLineDash([5, 3]);\n ctx.strokeStyle = 'black';\n ctx.fillStyle = 'rgba(0,0,0,0.05)';\n ctx.lineWidth = 2 * window.devicePixelRatio;\n ctx.beginPath();\n for (let index = 0; index < points.length; index++) {\n let point = points[index];\n point = CameraTransformations.worldToScreen(point, this.createTransform());\n\n if (index === 0) {\n ctx.moveTo(point.x * window.devicePixelRatio, point.y * window.devicePixelRatio);\n } else {\n ctx.lineTo(point.x * window.devicePixelRatio, point.y * window.devicePixelRatio);\n }\n }\n\n if (!this.lasso.drawing) {\n const conv = CameraTransformations.worldToScreen(points[0], this.createTransform());\n ctx.lineTo(conv.x * window.devicePixelRatio, conv.y * window.devicePixelRatio);\n }\n\n ctx.fill();\n ctx.stroke();\n ctx.closePath();\n }\n\n onClusterZoom(cluster) {\n this.props.setSelectedCluster(cluster, false);\n }\n\n render() {\n const handleClose = () => {\n this.setState({\n menuX: null,\n menuY: null,\n });\n };\n\n return (\n {\n event.preventDefault();\n }}\n onMouseLeave={(event) => {\n this.onMouseLeave(event);\n }}\n style={{\n width: '100%',\n height: '100%',\n overflow: 'hidden',\n position: 'relative',\n }}\n >\n {\n // Layers which are behind the webgl view\n this.props.overrideComponents?.layers\n ?.filter((layer) => layer.order < 0)\n .map((layer) => {\n return React.isValidElement(layer.component)\n ? layer.component\n : React.createElement(layer.component as () => JSX.Element, { key: `layer${layer.order}` });\n })\n }\n\n \n\n \n\n {\n this.requestRender();\n }}\n ref={this.multivariateClusterView}\n />\n\n {\n // Layers which are in front of the webgl view\n this.props.overrideComponents?.layers\n ?.filter((layer) => layer.order > 0)\n .map((layer) => {\n return React.isValidElement(layer.component)\n ? layer.component\n : React.createElement(layer.component as () => JSX.Element, { key: `layer${layer.order}` });\n })\n }\n\n \n {\n handleClose();\n this.props.addView(this.props.dataset);\n }}\n >\n Create View\n \n\n {\n if (this.props.currentAggregation.aggregation.length > 0) {\n const cluster = ACluster.fromSamples(this.props.dataset, this.props.currentAggregation.aggregation);\n if (this.props.stories.active === null) {\n const story: IBook = {\n id: uuidv4(),\n clusters: {\n entities: {\n [cluster.id]: cluster,\n },\n ids: [cluster.id],\n },\n edges: {\n entities: {},\n ids: [],\n },\n metadata: { method: 'custom' },\n };\n this.props.addStory(story, true);\n } else {\n this.props.addClusterToStory(cluster);\n }\n }\n\n handleClose();\n }}\n >\n Create Group from Selection\n \n\n {this.props.dataset?.isSequential && (\n {\n const coords = CameraTransformations.screenToWorld(\n { x: this.mouseController.currentMousePosition.x, y: this.mouseController.currentMousePosition.y },\n this.createTransform(),\n );\n if (this.props.displayMode === DisplayMode.OnlyClusters) {\n return;\n }\n\n const idx = this.choose(coords);\n if (idx >= 0) {\n const vector = this.props.dataset.vectors[idx];\n this.props.setActiveLine(vector.line);\n }\n handleClose();\n }}\n >\n Investigate Line\n \n )}\n\n {this.props.overrideComponents?.contextMenuItems?.map((item) => (\n {\n const coords = CameraTransformations.screenToWorld(\n {\n x: this.mouseController.currentMousePosition.x,\n y: this.mouseController.currentMousePosition.y,\n },\n this.createTransform(),\n );\n item.function(coords);\n handleClose();\n }}\n >\n {item.title}\n \n ))}\n \n\n \n {\n if (isCluster(this.state.menuTarget)) {\n this.props.removeClusterFromStories(this.state.menuTarget);\n }\n\n handleClose();\n }}\n >\n Delete Group\n \n\n {\n if (!isCluster(this.state.menuTarget)) {\n handleClose();\n return;\n }\n\n const activeStory = AStorytelling.getActive(this.props.stories);\n\n const paths = ABook.getAllStoriesFromSource(\n activeStory,\n Object.entries(activeStory.clusters.entities).find(([key, val]) => val === this.state.menuTarget)[0],\n );\n\n if (paths.length > 0) {\n const mainPath = paths[0];\n const mainEdges = mainPath.slice(1).map((item, index) => {\n const [resultEdgeKey, _] = Object.entries(activeStory.edges.entities).find(\n ([key, edge]) => edge.source === mainPath[index] && edge.destination === item,\n );\n return resultEdgeKey;\n });\n this.props.setActiveTrace({\n mainPath,\n mainEdges,\n sidePaths: paths.slice(1).map((ids) => {\n const path = ids;\n const edges = path.slice(1).map((item, index) => {\n const [resultEdgeKey, _] = Object.entries(activeStory.edges.entities).find(\n ([key, edge]) => edge.source === path[index] && edge.destination === item,\n );\n return resultEdgeKey;\n });\n return {\n nodes: path,\n edges,\n syncNodes: getSyncNodesAlt(mainPath, path),\n };\n }),\n });\n }\n\n handleClose();\n }}\n >\n Stories ... Starting from this Group\n \n\n {\n if (!isCluster(this.state.menuTarget)) {\n handleClose();\n return;\n }\n\n this.traceSelect = new TraceSelectTool(this.props.workspace, this.state.menuTarget);\n handleClose();\n }}\n >\n Stories ... Between 2 Groups\n \n \n\n \n {\n this.props.removeEdgeFromActive((this.state.menuTarget as IEdge).id);\n\n handleClose();\n }}\n >\n Delete Edge\n \n \n \n );\n }\n },\n);\n","export * from './CameraTransformations';\nexport * from './CategoryOptions';\nexport * from './ClusterDragTool';\nexport * from './LassoLayer';\nexport * from './LayeringSystem';\nexport * from './meshes';\nexport * from './MouseController';\nexport * from './MultivariateClustering';\nexport * from './Tool';\nexport * from './tools';\nexport * from './TraceSelectTool';\nexport * from './TrailVisualization';\nexport * from './UtilityFunctions';\nexport * from './WebGLView';\nexport * from './Shapes';\n","/* eslint-disable prefer-destructuring */\n/* eslint-disable @typescript-eslint/no-var-requires */\nimport * as THREE from 'three';\nimport { BufferAttribute } from 'three';\nimport { getMinMaxOfChannel, valueInRange } from './UtilityFunctions';\nimport { isNumericMapping, Mapping, mapValueToColor } from '../Utility/Colors/Mapping';\nimport { DataLine } from '../../model/DataLine';\nimport { IVector } from '../../model/Vector';\nimport { Dataset } from '../../model/Dataset';\nimport { LayeringSystem } from './LayeringSystem';\n\n// @ts-ignore\nimport SpriteAtlas from '../../../textures/sprites/atlas.png';\nimport { IBaseProjection } from '../../model/ProjectionInterfaces';\nimport { createLinearRangeScaler } from '../Utility/ScalingAndAxes';\nimport { Shapes } from './Shapes';\nimport { IStorytelling, AStorytelling } from '../Ducks/StoriesDuck';\n\n// @ts-ignore\nimport fragmentShader from '../../shaders/fragment.glsl?raw';\n// @ts-ignore\nimport vertexShader from '../../shaders/vertex.glsl?raw';\n\nimport override from './meshline';\nimport { CategoryOption } from './CategoryOptions';\nimport { AShallowSet } from '../Utility/ShallowSet';\n\nexport function imageFromShape(value) {\n switch (value) {\n case Shapes.Cross:\n return './textures/sprites/cross.png';\n case Shapes.Square:\n return './textures/sprites/square.png';\n case Shapes.Circle:\n return './textures/sprites/circle.png';\n case Shapes.Star:\n return './textures/sprites/star.png';\n default:\n return '';\n }\n}\n\nfunction shapeFromInt(value) {\n if (value === 0) {\n return Shapes.Cross;\n }\n if (value === 1) {\n return Shapes.Square;\n }\n if (value === 2) {\n return Shapes.Circle;\n }\n if (value === 3) {\n return Shapes.Star;\n }\n\n return Shapes.Circle;\n}\n\nfunction shapeToInt(value) {\n switch (value) {\n case Shapes.Cross:\n return 0;\n case Shapes.Square:\n return 1;\n case Shapes.Circle:\n return 2;\n case Shapes.Star:\n return 3;\n default:\n return 2;\n }\n}\n\nclass LineVis {\n line: any;\n\n color: any;\n\n constructor(line) {\n this.line = line;\n this.color = this.line.material.color;\n }\n\n dispose() {\n this.line.material.dispose();\n this.line.geometry.dispose();\n\n this.line = null;\n }\n}\n\nexport class LineVisualization {\n segments: DataLine[];\n\n highlightIndices: any;\n\n lineColorScheme: any;\n\n meshes: any;\n\n zoom: any;\n\n highlightMeshes;\n\n grayedLayerSystem: LayeringSystem;\n\n pathLengthRange: any;\n\n constructor(segments, lineColorScheme) {\n this.segments = segments;\n this.highlightIndices = null;\n this.lineColorScheme = lineColorScheme;\n\n this.grayedLayerSystem = new LayeringSystem(this.segments.length);\n\n // selection layer\n this.grayedLayerSystem.registerLayer(5, true);\n this.grayedLayerSystem.setLayerActive(5, false);\n\n // trace layer\n this.grayedLayerSystem.registerLayer(4, true);\n\n // storybook layer\n this.grayedLayerSystem.registerLayer(3, true);\n }\n\n setBrightness(brightness: number) {\n this.segments.forEach((segment) => {\n segment.__meta__.lineMesh.material.opacity = brightness / 100;\n });\n }\n\n dispose(scene) {\n this.meshes.forEach((mesh) => {\n scene.remove(mesh.line);\n mesh.dispose();\n });\n }\n\n setZoom(zoom) {\n this.zoom = zoom;\n\n if (this.highlightMeshes != null) {\n this.highlightMeshes.forEach((mesh) => {\n mesh.material.lineWidth = 0.005;\n });\n }\n }\n\n groupHighlight(indices) {\n if (indices != null && indices.length > 0) {\n this.grayedLayerSystem.setLayerActive(5, true);\n this.grayedLayerSystem.clearLayer(5, true);\n\n indices.forEach((index) => {\n this.grayedLayerSystem.setValue(\n this.segments.findIndex((e) => e.lineKey === index),\n 5,\n false,\n );\n });\n } else {\n this.grayedLayerSystem.clearLayer(5, false);\n this.grayedLayerSystem.setLayerActive(5, false);\n }\n\n this.update();\n }\n\n storyTelling(stories: IStorytelling, vectors: IVector[]) {\n if (stories && stories.active) {\n this.grayedLayerSystem.clearLayer(3, true);\n\n const lineIndices = new Set();\n\n for (const [, cluster] of Object.entries(AStorytelling.getActive(stories).clusters.entities)) {\n cluster.indices.forEach((i) => {\n lineIndices.add(vectors[i].__meta__.lineIndex);\n });\n }\n\n lineIndices.forEach((lineIndex) => {\n this.grayedLayerSystem.setValue(lineIndex, 3, false);\n });\n\n this.grayedLayerSystem.setLayerActive(3, true);\n } else {\n this.grayedLayerSystem.clearLayer(3, false);\n this.grayedLayerSystem.setLayerActive(3, false);\n }\n\n if (stories && stories.trace) {\n this.grayedLayerSystem.clearLayer(4, true);\n this.grayedLayerSystem.setLayerActive(4, true);\n\n const lineIndices = new Set();\n stories.trace.mainPath.forEach((cluster) => {\n AStorytelling.retrieveCluster(stories, cluster).indices.forEach((i) => {\n lineIndices.add(vectors[i].__meta__.lineIndex);\n });\n });\n\n lineIndices.forEach((lineIndex) => {\n this.grayedLayerSystem.setValue(lineIndex, 4, false);\n });\n } else {\n this.grayedLayerSystem.clearLayer(4, false);\n this.grayedLayerSystem.setLayerActive(4, false);\n }\n }\n\n /**\n * Highlights the given lines that correspond to the indices\n *\n * @param {*} indices\n * @param {*} width\n * @param {*} height\n * @param {*} scene\n */\n highlight(indices, width, height, scene, grayout = false) {\n // Gray other lines if needed\n if (grayout) {\n this.groupHighlight(indices);\n }\n\n // Undo previous highlight\n if (this.highlightIndices != null) {\n this.highlightIndices.forEach((index) => {\n this.segments.find((e) => e.lineKey === index).__meta__.highlighted = false;\n });\n this.highlightMeshes.forEach((mesh) => {\n mesh.material.dispose();\n mesh.geometry.dispose();\n scene.remove(mesh);\n });\n }\n\n this.highlightIndices = indices;\n this.highlightMeshes = [];\n this.highlightIndices.forEach((index) => {\n const findSeg = this.segments.find((e) => e.lineKey === index);\n findSeg.__meta__.highlighted = true;\n\n const geometry = new THREE.Geometry();\n findSeg.__meta__.lineMesh.geometry.vertices.forEach((vertex) => {\n geometry.vertices.push(vertex);\n });\n\n const line = new override.MeshLine();\n line.setGeometry(geometry, function () {\n return 1;\n });\n const material = new override.MeshLineMaterial({\n color: new THREE.Color(findSeg.__meta__.lineMesh.material.color),\n resolution: new THREE.Vector2(width, height),\n lineWidth: 0.005,\n sizeAttenuation: true,\n transparent: true,\n opacity: 0.5,\n depthTest: false,\n });\n\n const m = new THREE.Mesh(line.geometry, material);\n this.highlightMeshes.push(m);\n scene.add(m);\n });\n\n this.update();\n }\n\n createMesh(lineBrightness: number) {\n const lines = [];\n\n console.log(this.lineColorScheme);\n this.segments.forEach((segment, index) => {\n segment.__meta__.intrinsicColor = this.lineColorScheme.map(segment.vectors[0].algo);\n\n const geometry = new THREE.Geometry();\n const material = new THREE.LineBasicMaterial({\n color: segment.__meta__.intrinsicColor.hex,\n transparent: true,\n\n // Calculate opacity\n opacity: lineBrightness / 100,\n // 1 - 1 100 - 0.1 200 - 0.05 50 - 0.2 25 - 0.4\n });\n\n const da = [];\n segment.vectors.forEach(function (vector) {\n da.push(new THREE.Vector2(vector.x, vector.y));\n vector.__meta__.lineIndex = index;\n });\n\n const curve = new THREE.SplineCurve(da);\n\n curve.getPoints(700).forEach(function (p) {\n geometry.vertices.push(new THREE.Vector3(p.x, p.y, -1.0));\n });\n const line = new THREE.Line(geometry, material);\n\n // Store line data in segment...\n segment.__meta__.lineMesh = line;\n\n lines.push(new LineVis(line));\n });\n\n this.meshes = lines;\n return lines;\n }\n\n updatePosition(positions: IBaseProjection) {\n this.segments.forEach((segment) => {\n const da = [];\n\n segment.vectors.forEach(function (v) {\n const vector = positions[v.__meta__.meshIndex];\n da.push(new THREE.Vector2(vector.x, vector.y));\n });\n\n const geometry = new THREE.Geometry();\n const curve = new THREE.SplineCurve(da);\n\n curve.getPoints(700).forEach(function (p) {\n geometry.vertices.push(new THREE.Vector3(p.x, p.y, -1.0));\n });\n\n segment.__meta__.lineMesh.geometry.dispose();\n segment.__meta__.lineMesh.geometry = geometry;\n segment.__meta__.lineMesh.geometry.verticesNeedUpdate = true;\n });\n }\n\n /**\n * Updates visibility based on settings in the lines\n */\n update() {\n this.segments.forEach((segment, si) => {\n segment.__meta__.lineMesh.material.color.setStyle(this.grayedLayerSystem.getValue(si) ? '#C0C0C0' : segment.__meta__.intrinsicColor.hex);\n\n segment.__meta__.lineMesh.visible =\n segment.__meta__.detailVisible &&\n segment.__meta__.globalVisible &&\n !segment.__meta__.highlighted &&\n valueInRange(segment.vectors.length, this.pathLengthRange);\n });\n }\n}\n\nexport class PointVisualization {\n highlightIndex: any;\n\n particleSize: any;\n\n vectorMapping: Mapping;\n\n dataset: Dataset;\n\n showSymbols: any;\n\n colorsChecked: any;\n\n segments: DataLine[];\n\n vectors: IVector[];\n\n vectorSegmentLookup: DataLine[];\n\n mesh: THREE.Points;\n\n sizeAttribute: any;\n\n colorAttribute;\n\n grayedLayerSystem: LayeringSystem;\n\n lineLayerSystem: LayeringSystem;\n\n pathLengthRange: any;\n\n baseSize: number[];\n\n constructor(vectorMapping: Mapping, dataset: Dataset, size, lineLayerSystem: LayeringSystem, segments) {\n this.highlightIndex = null;\n this.particleSize = size;\n this.vectorMapping = vectorMapping;\n this.dataset = dataset;\n\n this.showSymbols = { cross: true, square: true, circle: true, star: true };\n this.colorsChecked = null;\n\n this.grayedLayerSystem = new LayeringSystem(dataset.vectors.length);\n this.baseSize = new Array(dataset.vectors.length);\n\n // selection layer\n this.grayedLayerSystem.registerLayer(5, true);\n this.grayedLayerSystem.setLayerActive(5, false);\n\n // trace layer\n this.grayedLayerSystem.registerLayer(4, true);\n\n // story layer\n this.grayedLayerSystem.registerLayer(3, true);\n\n this.lineLayerSystem = lineLayerSystem;\n\n this.vectorSegmentLookup = new Array(this.dataset.vectors.length);\n if (dataset.isSequential) {\n for (const [i, v] of this.dataset.vectors.entries()) {\n this.vectorSegmentLookup[i] = segments.find((seg) => seg.lineKey === v.line);\n }\n }\n }\n\n createMesh(data, segments, onUpload) {\n this.segments = segments;\n this.vectors = data;\n\n const positions = new Float32Array(data.length * 3);\n const colors = new Float32Array(data.length * 4);\n const sizes = new Float32Array(data.length);\n const types = new Float32Array(data.length);\n const show = new Float32Array(data.length);\n const selected = new Float32Array(data.length);\n let i = 0;\n\n if (this.dataset.isSequential) {\n this.segments.forEach((segment) => {\n segment.vectors.forEach((vector, idx) => {\n new THREE.Vector3(vector.x, vector.y, 0.0).toArray(positions, i * 3);\n\n // Set the globalIndex which belongs to a specific vertex\n vector.__meta__.meshIndex = i;\n\n colors[i * 4] = 0;\n colors[i * 4 + 1] = 0;\n colors[i * 4 + 2] = 0;\n colors[i * 4 + 3] = 1.0;\n\n selected[i] = 0.0;\n\n show[i] = 1.0;\n\n // color.toArray( colors, i * 4 );\n this.baseSize[vector.__meta__.meshIndex] = this.particleSize;\n\n if (vector.age === 0) {\n // Starting point\n types[i] = 0;\n } else if (idx === segment.vectors.length - 1) {\n // Ending point\n types[i] = 3;\n } else {\n // Intermediate\n types[i] = 2;\n }\n vector.__meta__.shapeType = shapeFromInt(types[i]);\n vector.__meta__.highlighted = false;\n\n i++;\n });\n });\n } else {\n this.vectors.forEach((vector, i) => {\n new THREE.Vector3(vector.x, vector.y, 0.0).toArray(positions, i * 3);\n\n vector.__meta__.meshIndex = i;\n colors[i * 4] = 0;\n colors[i * 4 + 1] = 0;\n colors[i * 4 + 2] = 0;\n colors[i * 4 + 3] = 1.0;\n\n selected[i] = 0.0;\n\n show[i] = 1.0;\n this.baseSize[vector.__meta__.meshIndex] = this.particleSize;\n types[i] = 2;\n vector.__meta__.shapeType = shapeFromInt(types[i]);\n vector.__meta__.highlighted = false;\n });\n }\n\n const pointGeometry = new THREE.BufferGeometry();\n\n const attributes = {\n position: new THREE.BufferAttribute(positions, 3),\n customColor: new THREE.BufferAttribute(colors, 4),\n size: new THREE.BufferAttribute(sizes, 1),\n type: new THREE.BufferAttribute(types, 1),\n show: new THREE.BufferAttribute(show, 1),\n selected: new THREE.BufferAttribute(selected, 1),\n };\n\n for (const [key, attribute] of Object.entries(attributes)) {\n attribute.onUpload(onUpload);\n pointGeometry.setAttribute(key, attribute);\n }\n\n //\n const pointMaterial = new THREE.ShaderMaterial({\n uniforms: {\n zoom: { value: 1.0 },\n color: { value: new THREE.Color(0xffffff) },\n scale: { value: 1.0 },\n atlas: {\n value: new THREE.TextureLoader().load(SpriteAtlas),\n },\n },\n transparent: true,\n vertexShader,\n fragmentShader,\n alphaTest: 0.05,\n });\n\n this.mesh = new THREE.Points(pointGeometry, pointMaterial);\n\n this.sizeAttribute = this.mesh.geometry.attributes.size;\n }\n\n /**\n * Applies the gray-out effect on the particles based on the given story model\n *\n * @param stories The story model\n */\n storyTelling(stories: IStorytelling) {\n if (stories && stories.active) {\n this.grayedLayerSystem.setLayerActive(3, true);\n\n const vecIndices = new Set();\n for (const [, cluster] of Object.entries(AStorytelling.getActive(stories).clusters.entities)) {\n cluster.indices.forEach((sample) => {\n vecIndices.add(sample);\n });\n }\n\n vecIndices.forEach((value) => {\n this.grayedLayerSystem.setValue(value, 3, false);\n });\n } else {\n this.grayedLayerSystem.setLayerActive(3, false);\n }\n\n if (stories && stories.trace) {\n this.grayedLayerSystem.clearLayer(4, true);\n this.grayedLayerSystem.setLayerActive(4, true);\n\n const vecIndices = new Set();\n stories.trace.mainPath.forEach((cluster) => {\n AStorytelling.retrieveCluster(stories, cluster).indices.forEach((i) => {\n vecIndices.add(i);\n });\n });\n\n vecIndices.forEach((value) => {\n this.grayedLayerSystem.setValue(value, 4, false);\n });\n } else {\n this.grayedLayerSystem.clearLayer(4, false);\n this.grayedLayerSystem.setLayerActive(4, false);\n }\n }\n\n groupHighlight(samples: number[]) {\n if (samples && samples.length > 0) {\n this.grayedLayerSystem.clearLayer(5, true);\n this.grayedLayerSystem.setLayerActive(5, true);\n\n samples?.forEach((sample) => {\n this.grayedLayerSystem.setValue(sample, 5, null);\n });\n } else {\n this.grayedLayerSystem.clearLayer(5, null);\n this.grayedLayerSystem.setLayerActive(5, false);\n }\n }\n\n setPointScaling(pointScaling) {\n this.mesh.material.uniforms.scale.value = pointScaling;\n }\n\n /**\n * @param {*} category a feature to select the shape for\n */\n setShapeByChannel(category: CategoryOption) {\n const type = this.mesh.geometry.attributes.type as BufferAttribute;\n\n // default shapes used\n if (category == null) {\n if (this.dataset.isSequential) {\n this.segments.forEach((segment) => {\n segment.vectors.forEach((vector, index) => {\n let shape = 2;\n if (vector.age === 0) {\n // Starting point\n shape = 0;\n } else if (index === segment.vectors.length - 1) {\n // Ending point\n shape = 3;\n } else {\n // Intermediate\n shape = 2;\n }\n\n vector.__meta__.shapeType = shapeFromInt(shape);\n\n type.setX(vector.__meta__.meshIndex, shape);\n });\n });\n } else {\n this.vectors.forEach((vector) => {\n vector.__meta__.shapeType = Shapes.Circle;\n type.setX(vector.__meta__.meshIndex, shapeToInt(vector.__meta__.shapeType));\n });\n }\n } else if (category.type === 'categorical') {\n this.vectors.forEach((vector, index) => {\n const select = category.values.filter((value) => value.from === vector[category.key])[0];\n type.setX(index, shapeToInt(select.to));\n vector.__meta__.shapeType = select.to;\n });\n }\n\n // mark types array to receive an update\n type.needsUpdate = true;\n }\n\n setColorByChannel(category: CategoryOption, scale, additionalColumns?) {\n this.colorAttribute = category;\n\n if (category == null) {\n this.vectorMapping = null;\n } else {\n this.vectorMapping = scale;\n }\n\n this.updateColor(additionalColumns);\n }\n\n colorFilter(colorsChecked) {\n this.colorsChecked = colorsChecked;\n\n this.update();\n }\n\n getMapping() {\n return this.vectorMapping;\n }\n\n setColorScale(colorScale) {\n if (this.vectorMapping != null) {\n this.vectorMapping.scale = colorScale;\n }\n }\n\n setBrightnessByChannel(channel: CategoryOption, range) {\n // var color = this.mesh.geometry.attributes.customColor.array\n\n if (channel == null) {\n // default transparency\n this.vectors.forEach((sample) => {\n sample.__meta__.brightness = range[0];\n });\n } else if (channel.type === 'sequential') {\n if (this.dataset.isSequential) {\n this.segments.forEach((segment) => {\n const { min, max } = getMinMaxOfChannel(this.dataset, channel.key, segment);\n\n const scaler = createLinearRangeScaler(range, min, max);\n\n segment.vectors.forEach((vector) => {\n vector.__meta__.brightness = scaler(vector[channel.key]);\n });\n });\n } else {\n const { min, max } = getMinMaxOfChannel(this.dataset, channel.key);\n\n const scaler = createLinearRangeScaler(range, min, max);\n\n this.vectors.forEach((vector) => {\n vector.__meta__.brightness = scaler(vector[channel.key]);\n });\n }\n }\n\n this.updateColor();\n }\n\n sizeCat(category: CategoryOption, range) {\n if (category == null) {\n this.vectors.forEach((vector) => {\n this.baseSize[vector.__meta__.meshIndex] = this.particleSize * range[0];\n });\n } else if (category.type === 'sequential') {\n if (this.dataset.isSequential) {\n // dataset with lines, we have segments\n this.segments.forEach((segment) => {\n const { min, max } = getMinMaxOfChannel(this.dataset, category.key, segment);\n\n const sizeScaler = createLinearRangeScaler(range, min, max);\n\n segment.vectors.forEach((vector) => {\n this.baseSize[vector.__meta__.meshIndex] = this.particleSize * sizeScaler(vector[category.key]);\n });\n });\n } else {\n // for state based data, min and max is based on whole dataset\n const { min, max } = getMinMaxOfChannel(this.dataset, category.key);\n\n const sizeScaler = createLinearRangeScaler(range, min, max);\n\n this.vectors.forEach((vector) => {\n this.baseSize[vector.__meta__.meshIndex] = this.particleSize * sizeScaler(vector[category.key]);\n });\n }\n }\n\n this.updateSize();\n }\n\n updateSize() {\n const size = this.mesh.geometry.attributes.size as BufferAttribute;\n\n this.vectors.forEach((vector) => {\n size.setX(\n vector.__meta__.meshIndex,\n this.baseSize[vector.__meta__.meshIndex] * (vector.__meta__.highlighted ? 2.0 : 1.0) * (vector.__meta__.selected ? 1.2 : 1.0),\n );\n });\n\n size.needsUpdate = true;\n }\n\n updateColor(additionalColumns?: { [key: string]: { [key: number]: number[] } }) {\n const color = this.mesh.geometry.attributes.customColor as BufferAttribute;\n\n const gray = { r: 192, g: 192, b: 192 };\n const defaultColor = { r: 127.0, g: 201, b: 127 };\n\n this.vectors.forEach((vector) => {\n const i = vector.__meta__.meshIndex;\n let rgb = null;\n\n let vectorValue;\n\n if (additionalColumns && this.colorAttribute && additionalColumns[this.colorAttribute.key]) {\n vectorValue = additionalColumns[this.colorAttribute.key][i];\n } else if (this.colorAttribute) {\n vectorValue = vector[this.colorAttribute.key];\n }\n\n if (this.dataset.isSequential) {\n // sequential\n if (this.lineLayerSystem.getValue(vector.__meta__.lineIndex)) {\n rgb = gray;\n } else if (this.colorAttribute != null) {\n const m = mapValueToColor(this.vectorMapping, vectorValue);\n rgb = m.rgb;\n\n if (isNumericMapping(this.vectorMapping)) {\n vector.__meta__.intrinsicColor = null;\n } else {\n vector.__meta__.intrinsicColor = AShallowSet.indexOf(this.vectorMapping.values, vectorValue);\n }\n } else {\n const col = this.vectorSegmentLookup[i].__meta__.lineMesh.material.color;\n rgb = {\n r: col.r * 255.0,\n g: col.g * 255.0,\n b: col.b * 255.0,\n };\n vector.__meta__.intrinsicColor = null;\n }\n } else if (this.grayedLayerSystem.getValue(vector.__meta__.meshIndex)) {\n rgb = gray;\n } else if (this.colorAttribute != null) {\n const m = mapValueToColor(this.vectorMapping, vectorValue);\n rgb = m.rgb;\n\n if (isNumericMapping(this.vectorMapping)) {\n vector.__meta__.intrinsicColor = null;\n } else {\n vector.__meta__.intrinsicColor = AShallowSet.indexOf(this.vectorMapping.values, vectorValue);\n }\n } else {\n rgb = defaultColor;\n }\n\n color.setXYZ(i, rgb.r / 255.0, rgb.g / 255.0, rgb.b / 255.0);\n\n if (this.dataset.isSequential) {\n if (this.lineLayerSystem.getValue(vector.__meta__.lineIndex)) {\n color.setW(i, vector.__meta__.brightness * 0.4);\n } else {\n color.setW(i, vector.__meta__.brightness);\n }\n } else if (this.grayedLayerSystem.getValue(vector.__meta__.meshIndex)) {\n color.setW(i, vector.__meta__.brightness * 0.4);\n } else {\n color.setW(i, vector.__meta__.brightness);\n }\n });\n\n color.needsUpdate = true;\n }\n\n isPointVisible(vector: IVector) {\n const i = vector.__meta__.meshIndex;\n\n return (\n (this.vectorSegmentLookup[i] == null || this.vectorSegmentLookup[i].__meta__.detailVisible) &&\n (this.vectorSegmentLookup[i] == null || this.vectorSegmentLookup[i].__meta__.globalVisible) &&\n vector.__meta__.visible &&\n this.showSymbols[vector.__meta__.shapeType] &&\n (vector.__meta__.intrinsicColor != null && this.colorsChecked != null ? this.colorsChecked[vector.__meta__.intrinsicColor] : true) &&\n (this.vectorSegmentLookup[i] == null || valueInRange(this.vectorSegmentLookup[i].vectors.length, this.pathLengthRange)) &&\n !vector.__meta__.lineUpFiltered\n );\n }\n\n updatePosition(projection: IBaseProjection) {\n const position = this.mesh.geometry.attributes.position as BufferAttribute;\n\n this.vectors.forEach((vector, i) => {\n let z = 0.0;\n if (\n (!this.dataset.isSequential && this.grayedLayerSystem.getValue(vector.__meta__.meshIndex)) ||\n (this.dataset.isSequential && this.lineLayerSystem.getValue(vector.__meta__.lineIndex))\n ) {\n z = -0.1;\n }\n\n position.setXYZ(vector.__meta__.meshIndex, projection[i].x, projection[i].y, z);\n // new THREE.Vector3().toArray(position, vector.__meta__.meshIndex * 3);\n });\n\n position.needsUpdate = true;\n }\n\n update() {\n const show = this.mesh.geometry.attributes.show as BufferAttribute;\n const selected = this.mesh.geometry.attributes.selected as BufferAttribute;\n\n this.vectors.forEach((vector) => {\n if (this.isPointVisible(vector)) {\n show.setX(vector.__meta__.meshIndex, 1.0);\n } else {\n show.setX(vector.__meta__.meshIndex, 0.0);\n }\n selected.setX(vector.__meta__.meshIndex, vector.__meta__.selected ? 1.0 : 0.0);\n });\n\n // this.updateColor()\n this.updateSize();\n\n show.needsUpdate = true;\n selected.needsUpdate = true;\n }\n\n /**\n * Highlights a specific point index.\n */\n highlight(index) {\n if (this.highlightIndex != null && this.highlightIndex >= 0) {\n this.vectors[this.highlightIndex].__meta__.highlighted = false;\n }\n\n this.highlightIndex = index;\n\n if (this.highlightIndex != null && this.highlightIndex >= 0) {\n this.vectors[this.highlightIndex].__meta__.highlighted = true;\n }\n\n this.updateSize();\n }\n\n /**\n * Updates the zoom level.\n */\n zoom(zoom, projection) {\n this.mesh.material.uniforms.zoom.value = zoom * projection.bounds.scaleFactor;\n }\n\n /**\n * Cleans this object.\n */\n dispose() {\n this.segments = null;\n this.vectors = null;\n\n this.mesh.material.uniforms.atlas.value.dispose();\n\n this.mesh.geometry.dispose();\n this.mesh.material.dispose();\n\n this.mesh = null;\n }\n}\n","import { pointInHull } from '../Utility/Geometry/Intersection';\nimport type { IBaseProjection, Dataset } from '../../model';\n\nexport class LassoSelection {\n drawing: boolean;\n\n start: { x; y };\n\n points: { x; y }[];\n\n constructor() {\n this.drawing = false;\n this.start = { x: 0, y: 0 };\n this.points = [];\n }\n\n mouseDown(alt, x, y) {\n if (!this.drawing && alt) {\n this.drawing = true;\n\n this.start = { x, y };\n this.points = [this.start];\n }\n }\n\n mouseMove(x, y) {\n if (this.drawing) {\n this.points.push({ x, y });\n }\n }\n\n mouseUp(x, y) {\n if (this.drawing) {\n this.points.push({\n x,\n y,\n });\n\n this.points.push(this.start);\n\n this.drawing = false;\n }\n }\n\n selection(dataset: Dataset, positions: IBaseProjection, visible) {\n const indices = [];\n dataset.vectors.forEach((vector, index) => {\n if (visible(vector) && this.intersects(positions[index])) {\n indices.push(index);\n }\n });\n return indices;\n }\n\n intersects = (seat) => pointInHull(seat, this.points);\n}\n","export * from './DrawerTabPanels';\nexport * from './Ducks';\nexport * from './legends';\nexport * from './Overlays';\nexport * from './Store';\nexport * from './Utility';\nexport * from './WebGLView';\nexport * from './PseAppBar';\n","import * as React from 'react';\nimport { CoralLegend } from '../../plugins/Coral/CoralDetail/CoralDetail';\nimport { TrrackLegend } from '../../plugins/Trrack/TrrackDetail/TrrackDetail';\nimport { StoryLegend } from '../../plugins/Story/StoryDetail/StoryDetail';\nimport { RubikFingerprint } from '../../plugins/Rubik/RubikFingerprint/RubikFingerprint';\nimport { ChessFingerprint } from '../../plugins/Chess/ChessFingerprint/ChessFingerprint';\nimport { IVector } from '../../model/Vector';\nimport { PluginRegistry } from '../Store/PluginScript';\nimport { DatasetType } from '../../model/DatasetType';\nimport { GoLegend } from '../../plugins/Go/GoLegend';\nimport { usePSESelector } from '../Store';\n\ntype GenericLegendProps = {\n type: DatasetType;\n vectors: IVector[];\n aggregate: boolean;\n scale?: number;\n};\n\n// shows single and aggregated view\nexport function GenericLegend({ type, vectors, aggregate, scale = 2 }: GenericLegendProps) {\n const dataset = usePSESelector((state) => state.dataset);\n\n const plugin = PluginRegistry.getInstance().getPlugin(type);\n if (plugin) {\n // use plugin before defaults\n return plugin.createFingerprint(dataset, vectors, scale, aggregate);\n }\n // defaults... in case no plugin is specific\n switch (type) {\n case DatasetType.Story:\n return ;\n case DatasetType.Rubik:\n return ;\n case DatasetType.Chess:\n return ;\n case DatasetType.Cohort_Analysis:\n return ;\n case DatasetType.Trrack:\n return ;\n case DatasetType.Go:\n return ;\n default:\n return ;\n }\n}\n","import { connect } from 'react-redux';\nimport * as React from 'react';\nimport { DatasetType } from '../../model/DatasetType';\nimport { IVector } from '../../model/Vector';\nimport { Dataset } from '../../model/Dataset';\nimport { RubikChanges } from '../../plugins/Rubik/RubikChanges/RubikChanges';\nimport { ChessChanges } from '../../plugins/Chess/ChessChanges/ChessChanges';\nimport { CoralChanges } from '../../plugins/Coral/CoralChanges/CoralChanges';\n\ntype GenericChangesType = {\n vectorsA: Array;\n vectorsB: Array;\n dataset: Dataset;\n scale: number;\n};\n\nconst mapStateToProps = (state) => ({\n dataset: state.dataset,\n});\n\nconst mapDispatchToProps = () => ({});\n\nexport const GenericChanges = connect(\n mapStateToProps,\n mapDispatchToProps,\n)(({ vectorsA, vectorsB, dataset, scale }: GenericChangesType) => {\n switch (dataset.type) {\n case DatasetType.Rubik:\n return ;\n case DatasetType.Chess:\n return ;\n case DatasetType.Cohort_Analysis:\n return ;\n default:\n return ;\n }\n});\n","export * from './Generic';\nexport * from './GenericChanges';\n","/* eslint-disable no-param-reassign */\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { EntityId, EntityState } from '@reduxjs/toolkit';\nimport Graph from 'graphology';\nimport { IEdge } from './Edge';\nimport { ICluster } from './ICluster';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\n/**\n\nfunction* labelGenerator() {\n const code_0 = '0'.charCodeAt(0);\n const code_9 = '9'.charCodeAt(0);\n const code_A = 'A'.charCodeAt(0);\n const code_Z = 'Z'.charCodeAt(0);\n const code_a = 'a'.charCodeAt(0);\n\n function mapChar(c) {\n if (c >= code_0 && c <= code_9) {\n return String.fromCharCode(code_A + (c - code_0));\n }\n return String.fromCharCode(code_A + (c - code_a));\n }\n\n let i = 0;\n\n while (true) {\n const str = i.toString(26);\n const comb = Array.prototype.map.call(str, (e) => mapChar(e.charCodeAt(0))).join('');\n yield comb;\n i += 1;\n }\n}\n\n\n\n\n\n\n/**\n * Book API.\n */\nexport class ABook {\n /**\n * Performs depth first search between a source cluster and a target cluster,\n * returning a list of paths sorted by length.\n *\n * @param graph\n * @param source\n * @param target\n */\n static depthFirstSearch(graph, source, target) {\n const visited = {};\n const pathList = [source];\n const output = [];\n\n function DFS_iter(sourceInner, targetInner, visitedInner, pathListInner: unknown[]) {\n if (sourceInner === targetInner) {\n output.push(pathListInner.slice(0));\n return;\n }\n\n visitedInner[sourceInner] = true;\n\n graph.outNeighbors(sourceInner).forEach((neighbor) => {\n if (!visitedInner[neighbor]) {\n pathListInner.push(neighbor);\n\n DFS_iter(neighbor, targetInner, visitedInner, pathListInner);\n\n pathListInner.pop();\n }\n });\n\n visitedInner[sourceInner] = false;\n }\n\n DFS_iter(source, target, visited, pathList);\n\n return output.sort((a, b) => a.length - b.length);\n }\n\n /**\n * Converts this story to a graphology instance.\n */\n static toGraph(story: IBook) {\n const graph = new Graph();\n\n for (const cluster of Object.keys(story.clusters.entities)) {\n graph.addNode(cluster);\n }\n\n for (const edge of Object.values(story.edges.entities)) {\n graph.addDirectedEdge(edge.source, edge.destination);\n }\n\n return graph;\n }\n\n /**\n * Returns a list of paths that have a common start point.\n *\n * @param source A start label (of a cluster)\n */\n static getAllStoriesFromSource(storybook: IBook, source) {\n const graph = ABook.toGraph(storybook);\n\n const visited = {};\n const pathList = [source];\n const output = [];\n\n function DFS_iter(s, visitedInner, pathListInner: unknown[]) {\n if (graph.outNeighbors(s).length === 0) {\n output.push(pathListInner.slice(0));\n return;\n }\n\n visitedInner[s] = true;\n\n graph.outNeighbors(s).forEach((neighbor) => {\n if (!visitedInner[neighbor]) {\n pathListInner.push(neighbor);\n\n DFS_iter(neighbor, visitedInner, pathListInner);\n\n pathListInner.pop();\n } else {\n output.push(pathListInner.slice(0));\n }\n });\n\n visitedInner[s] = false;\n }\n\n DFS_iter(source, visited, pathList);\n\n return output.sort((a, b) => a.length - b.length);\n }\n}\n\n/**\n * Book type.\n */\nexport interface IBook {\n id: EntityId;\n clusters: EntityState;\n edges: EntityState;\n name?: string;\n\n metadata?: { [id: string]: any };\n}\n","import { v4 as uuidv4 } from 'uuid';\nimport * as THREE from 'three';\nimport { Dataset } from './Dataset';\nimport { ObjectTypes } from './ObjectType';\nimport { TypedObject } from './TypedObject';\nimport { IVector } from './Vector';\nimport { IBaseProjection } from './ProjectionInterfaces';\nimport { ICluster } from './ICluster';\n\n/**\n * Cluster API.\n */\nexport class ACluster {\n static calcBounds(positions: IBaseProjection, indices: number[]) {\n const samples = indices.map((i) => positions[i]);\n\n // Get rectangle that fits around data set\n let minX = 1000;\n let maxX = -1000;\n let minY = 1000;\n let maxY = -1000;\n\n samples.forEach((sample) => {\n minX = Math.min(minX, sample.x);\n maxX = Math.max(maxX, sample.x);\n minY = Math.min(minY, sample.y);\n maxY = Math.max(maxY, sample.y);\n });\n\n return {\n x: minX,\n y: minY,\n width: maxX - minX,\n height: maxY - minY,\n left: minX,\n top: minY,\n right: maxX,\n bottom: maxY,\n };\n }\n\n static fromSamples(dataset: Dataset, samples: number[], metadata?: any): ICluster {\n return {\n id: uuidv4(),\n objectType: ObjectTypes.Cluster,\n indices: samples,\n label: Math.floor(Math.random() * 1000),\n metadata,\n };\n }\n\n static getCenterFromWorkspace(positions: IBaseProjection, cluster: ICluster) {\n let x = 0;\n let y = 0;\n\n cluster.indices\n .map((i) => positions[i])\n .forEach((p) => {\n x += p.x;\n y += p.y;\n });\n\n return {\n x: x / cluster.indices.length,\n y: y / cluster.indices.length,\n };\n }\n\n static getCenterAsVector2(positions: IBaseProjection, cluster: ICluster) {\n const center = ACluster.getCenterFromWorkspace(positions, cluster);\n return new THREE.Vector2(center.x, center.y);\n }\n\n static getTextRepresentation(cluster: ICluster) {\n if (cluster.name) {\n return `${cluster.label} / ${cluster.name}`;\n }\n return `${cluster.label}`;\n }\n}\n\n/**\n * Cluster type guard.\n */\nexport function isCluster(object: TypedObject): object is ICluster {\n if (object?.objectType == null) return false;\n return object && object.objectType === ObjectTypes.Cluster;\n}\n","import { IVector } from './Vector';\n\n/**\n * View information for segments\n */\nexport class DataLineView {\n /**\n * Is this segment visible through the detailed selection? (line selection treeview)\n */\n detailVisible = true;\n\n /**\n * Is this segment visible through the global switch?\n */\n globalVisible = true;\n\n /**\n * Is this segment currently highlighted?\n */\n highlighted = false;\n\n /**\n * Color set for this line\n */\n intrinsicColor = null;\n\n /**\n * Line mesh\n */\n lineMesh = null;\n}\n\n/**\n * Main data class for lines\n */\n\nexport class DataLine {\n lineKey: any;\n\n vectors: IVector[];\n\n __meta__: DataLineView;\n\n constructor(lineKey, vectors) {\n this.lineKey = lineKey;\n this.vectors = vectors;\n\n this.__meta__ = new DataLineView();\n }\n}\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/naming-convention */\nimport { IEdge } from './Edge';\nimport { ICluster } from './ICluster';\nimport { FeatureType } from './FeatureType';\nimport { DatasetType } from './DatasetType';\nimport { DataLine } from './DataLine';\nimport type { IVector } from './Vector';\nimport { mean, std } from '../components/NumTs/NumTs';\nimport { EncodingMethod } from './EncodingMethod';\nimport { NormalizationMethod } from './NormalizationMethod';\nimport { IBaseProjection } from './ProjectionInterfaces';\n\nexport enum PrebuiltFeatures {\n Line = 'line',\n ClusterLabel = 'groupLabel',\n}\nexport const EXCLUDED_COLUMNS = ['__meta__', 'x', 'y', 'algo', 'age', 'multiplicity', 'objectType'];\nexport const EXCLUDED_COLUMNS_ALL = ['__meta__', 'x', 'y', 'algo', 'age', 'multiplicity', 'groupLabel', 'objectType'];\n\nexport const DefaultFeatureLabel = 'Default';\n\nconst shapes = ['circle', 'star', 'square', 'cross'];\n\nexport type ColumnType = {\n distinct: any;\n isNumeric: boolean;\n metaInformation: any;\n featureType: FeatureType;\n range: any;\n featureLabel: string;\n project: boolean;\n};\n\nexport class SegmentFN {\n /**\n * Calculates the maximum path length for this dataset.\n */\n static getMaxPathLength(dataset: Dataset) {\n if (dataset.isSequential) {\n return Math.max(...dataset.segments.map((segment) => segment.vectors.length));\n }\n return 1;\n }\n}\n\nexport class ADataset {\n /**\n * Reads out spatial information using the supplied channels.\n */\n static getSpatialData(dataset: Dataset, xChannel?: string, yChannel?: string, positions?: IBaseProjection) {\n if (positions) {\n return positions;\n }\n return dataset.vectors.map((vector) => ({\n x: xChannel ? vector[xChannel] : 0,\n y: yChannel ? vector[yChannel] : 0,\n }));\n }\n\n /**\n * Returns an array of columns that are available in the vectors\n */\n static getColumns(dataset: Dataset, excludeGenerated = false) {\n const vector = dataset.vectors[0];\n\n if (excludeGenerated) {\n return Object.keys(vector).filter((e) => !EXCLUDED_COLUMNS_ALL.includes(e));\n }\n return Object.keys(vector).filter((e) => e !== '__meta__');\n }\n\n /**\n * Returns the vectors in this dataset as a 2d array, which\n * can be used as input for tsne for example.\n */\n static asTensor(dataset: Dataset, projectionColumns, encodingMethod?, normalizationMethod?) {\n if (encodingMethod === undefined) {\n encodingMethod = EncodingMethod.ONEHOT;\n }\n if (normalizationMethod === undefined) {\n normalizationMethod = NormalizationMethod.STANDARDIZE;\n }\n\n const tensor = [];\n\n function oneHot(n, length) {\n const arr = new Array(length).fill(0);\n arr[n] = 1;\n return arr;\n }\n\n const lookup = {};\n\n dataset.vectors.forEach((vector) => {\n let data = [];\n projectionColumns.forEach((entry) => {\n const column = entry.name;\n if (dataset.columns[column].featureType === FeatureType.Array) {\n const array = JSON.parse(vector[column]);\n data.push(...array);\n } else if (dataset.columns[column].isNumeric) {\n if (dataset.columns[column].range && entry.normalized) {\n if (normalizationMethod === NormalizationMethod.STANDARDIZE) {\n // map to 0 mean and unit standarddeviation\n let m;\n let s;\n\n if (column in lookup) {\n m = lookup[column].mean;\n s = lookup[column].std;\n } else {\n m = mean(dataset.vectors.map((v) => +v[column]));\n s = std(dataset.vectors.map((v) => +v[column]));\n\n lookup[column] = {\n mean: m,\n std: s,\n };\n }\n\n if (s <= 0)\n // when all values are equal in a column, the standard deviation can be 0, which would lead to an error\n s = 1;\n\n data.push((+vector[column] - m) / s);\n } else {\n // map between [0;1]\n let div = dataset.columns[column].range.max - dataset.columns[column].range.min;\n div = div > 0 ? div : 1;\n data.push((+vector[column] - dataset.columns[column].range.min) / div);\n }\n } else {\n data.push(+vector[column]);\n }\n } else if (encodingMethod === EncodingMethod.ONEHOT) {\n // Non numeric data can be converted using one-hot encoding\n const hot_encoded = oneHot(dataset.columns[column].distinct.indexOf(vector[column]), dataset.columns[column].distinct.length);\n data = data.concat(hot_encoded);\n } else {\n // or just be integer encoded\n data.push(dataset.columns[column].distinct.indexOf(vector[column]));\n }\n });\n tensor.push(data);\n });\n\n const featureTypes = [];\n projectionColumns.forEach((entry) => {\n const column = entry.name;\n switch (dataset.columns[column].featureType) {\n case FeatureType.Binary:\n featureTypes.push(FeatureType.Binary);\n break;\n case FeatureType.Categorical:\n if (encodingMethod === EncodingMethod.ONEHOT) {\n // if the categorical attribute gets one hot encoded, we set all resulting columns to be binary\n featureTypes.concat(Array(dataset.columns[column].distinct.length).fill(FeatureType.Binary));\n } else {\n // otherwise, it is declared as categorical column that contains integer because we can only handle integers in the distance metrics\n featureTypes.push(FeatureType.Categorical);\n }\n break;\n case FeatureType.Date:\n // TODO: handle Date types\n break;\n case FeatureType.Ordinal:\n // TODO: handle Ordinal types\n break;\n case FeatureType.Quantitative:\n featureTypes.push(FeatureType.Quantitative);\n break;\n case FeatureType.String:\n // TODO: handle String types\n break;\n default:\n break;\n }\n });\n\n return { tensor, featureTypes };\n }\n}\n\n/**\n * Dataset class that holds all data, the ranges and additional stuff\n */\nexport class Dataset {\n vectors: IVector[];\n\n segments: DataLine[];\n\n info: { path: string; type: DatasetType };\n\n columns: { [name: string]: ColumnType };\n\n // The type of the dataset (or unknown if not possible to derive)\n type: DatasetType;\n\n // True if the dataset has multiple labels per sample\n multivariateLabels: boolean;\n\n // True if the dataset has sequential information (line attribute)\n isSequential: boolean;\n\n // True if the dataset has a projection provided\n hasInitialScalarTypes: boolean;\n\n clusters: ICluster[];\n\n // The edges between clusters.\n clusterEdges: IEdge[];\n\n inferredColumns: string[];\n\n // Dictionary containing the key/value pairs for each column\n metaInformation;\n\n categories: any;\n\n constructor(vectors, ranges, info, featureTypes, metaInformation = {}) {\n this.vectors = vectors;\n this.info = info;\n this.columns = {};\n this.type = this.info.type;\n this.metaInformation = metaInformation;\n this.hasInitialScalarTypes = false;\n\n this.calculateColumnTypes(ranges, featureTypes, metaInformation);\n this.checkLabels();\n\n // If the dataset is sequential, calculate the segments\n this.isSequential = this.checkSequential();\n if (this.isSequential) {\n this.segments = this.getSegs();\n }\n }\n\n getSegs(key = 'line') {\n const { vectors } = this;\n\n // Get a list of lines that are in the set\n const lineKeys = [...new Set(vectors.map((vector) => vector[key]))];\n\n const segments = lineKeys.map((lineKey) => {\n const l = new DataLine(\n lineKey,\n vectors.filter((vector) => vector[key] === lineKey).sort((a, b) => a.age - b.age),\n );\n // Set segment of vectors\n l.vectors.forEach((v, vi) => {\n v.__meta__.sequenceIndex = vi;\n });\n return l;\n });\n\n return segments;\n }\n\n // Checks if the dataset contains sequential data\n checkSequential() {\n const header = ADataset.getColumns(this);\n\n // If we have no line attribute, its not sequential\n if (!header.includes(PrebuiltFeatures.Line)) {\n return false;\n }\n\n // If each sample is a different line, its not sequential either\n const set = new Set(this.vectors.map((vector) => vector.line));\n\n return set.size !== this.vectors.length;\n }\n\n checkLabels() {\n this.multivariateLabels = false;\n this.vectors.forEach((vector) => {\n if (vector.groupLabel.length > 1) {\n this.multivariateLabels = true;\n }\n });\n }\n\n inferRangeForAttribute(key: string) {\n const values = this.vectors.map((sample) => sample[key]);\n let numeric = true;\n let min = Number.MAX_SAFE_INTEGER;\n let max = Number.MIN_SAFE_INTEGER;\n\n values.forEach((value) => {\n value = parseFloat(value);\n if (Number.isNaN(value)) {\n numeric = false;\n } else if (numeric) {\n if (value < min) {\n min = value;\n }\n if (value > max) {\n max = value;\n }\n }\n });\n\n return numeric ? { min, max, inferred: true } : null; // false\n }\n\n /**\n * Creates a map which shows the distinct types and data types of the columns.\n */\n calculateColumnTypes(ranges, featureTypes, metaInformation) {\n const columnNames = Object.keys(this.vectors[0]);\n\n if ('algo' in this.columns) this.columns.algo.featureType = FeatureType.Categorical;\n if ('groupLabel' in this.columns) this.columns.groupLabel.featureType = FeatureType.Categorical;\n if ('x' in this.columns) this.columns.x.featureType = FeatureType.Quantitative;\n if ('y' in this.columns) this.columns.y.featureType = FeatureType.Quantitative;\n\n featureTypes.algo = FeatureType.Categorical;\n delete ranges.algo;\n\n featureTypes.groupLabel = FeatureType.Categorical;\n delete ranges.groupLabel;\n\n columnNames.forEach((columnName) => {\n this.columns[columnName] = {} as any;\n\n this.columns[columnName].featureType = featureTypes[columnName];\n\n // Store dictionary with key/value pairs in column\n const columnMetaInformation = metaInformation[columnName] ?? {};\n this.columns[columnName].metaInformation = columnMetaInformation;\n\n // Extract featureLabel from dictionary\n if ('featureLabel' in columnMetaInformation) {\n this.columns[columnName].featureLabel = columnMetaInformation.featureLabel;\n } else {\n this.columns[columnName].featureLabel = DefaultFeatureLabel;\n }\n\n // Extract included\n if ('project' in columnMetaInformation) {\n this.columns[columnName].project = columnMetaInformation.project;\n } else {\n this.columns[columnName].project = true;\n }\n\n // Check data type\n if (columnName in ranges) {\n this.columns[columnName].range = ranges[columnName];\n this.columns[columnName].isNumeric = true;\n } else if (this.columns[columnName].featureType === FeatureType.Array) {\n this.columns[columnName].isNumeric = false;\n } else if (this.vectors.find((vector) => Number.isNaN(vector[columnName])) || this.columns[columnName].featureType === FeatureType.Categorical) {\n this.columns[columnName].isNumeric = false;\n this.columns[columnName].distinct = Array.from(new Set([...this.vectors.map((vector) => vector[columnName])]));\n } else {\n this.columns[columnName].isNumeric = true;\n this.columns[columnName].range = this.inferRangeForAttribute(columnName);\n }\n });\n }\n\n /**\n * Infers an array of attributes that can be filtered after, these can be\n * categorical, sequential or continuous attribues.\n * @param {*} ranges\n */\n extractEncodingFeatures() {\n if (this.vectors.length <= 0) {\n return [];\n }\n\n const shape_options = [];\n const size_options = [];\n const transparency_options = [];\n const color_options = [];\n\n const { columns } = this;\n const header = Object.keys(columns);\n // var header = Object.keys(this.vectors[0]).filter(a => a != \"line\");\n\n header.forEach((key) => {\n if (key === PrebuiltFeatures.ClusterLabel) {\n color_options.push({\n key,\n name: key,\n type: 'categorical',\n });\n } else {\n switch (columns[key].featureType) {\n case FeatureType.Binary:\n color_options.push({\n key,\n name: key,\n type: 'categorical',\n });\n\n shape_options.push({\n key,\n name: key,\n type: 'categorical',\n values: columns[key].distinct.map((value, index) => {\n return {\n from: value,\n to: shapes[index],\n };\n }),\n });\n break;\n case FeatureType.Categorical:\n color_options.push({\n key,\n name: key,\n type: 'categorical',\n });\n\n if (columns[key].distinct.length <= 4) {\n shape_options.push({\n key,\n name: key,\n type: 'categorical',\n values: columns[key].distinct.map((value, index) => {\n return {\n from: value,\n to: shapes[index],\n };\n }),\n });\n }\n break;\n case FeatureType.Date:\n break;\n case FeatureType.Ordinal:\n color_options.push({\n key,\n name: key,\n type: 'sequential', // TODO: add ordinal color scale\n range: columns[key].range,\n });\n transparency_options.push({\n key,\n name: key,\n type: 'sequential', // TODO: transparancy for ordered data?\n range: columns[key].range,\n values: {\n range: [0.3, 1.0],\n },\n });\n size_options.push({\n key,\n name: key,\n type: 'sequential', // TODO: size for ordered data?\n range: columns[key].range,\n values: {\n range: [1, 2],\n },\n });\n break;\n case FeatureType.Quantitative:\n color_options.push({\n key,\n name: key,\n type: 'sequential',\n range: columns[key].range,\n });\n transparency_options.push({\n key,\n name: key,\n type: 'sequential',\n range: columns[key].range,\n values: {\n range: [0.3, 1.0],\n },\n });\n size_options.push({\n key,\n name: key,\n type: 'sequential',\n range: columns[key].range,\n values: {\n range: [1, 2],\n },\n });\n break;\n case FeatureType.String:\n break;\n default:\n break;\n }\n }\n });\n\n const options = [\n {\n category: 'shape',\n attributes: shape_options,\n },\n {\n category: 'size',\n attributes: size_options,\n },\n {\n category: 'transparency',\n attributes: transparency_options,\n },\n {\n category: 'color',\n attributes: color_options,\n },\n ];\n\n return options;\n }\n}\n","/**\n * An enum holding each predefined dataset type like Rubik, Chess etc\n */\nexport enum DatasetType {\n Rubik = 'rubik',\n Chess = 'chess',\n Neural = 'neural',\n Go = 'go',\n Test = 'test',\n Story = 'story',\n Cohort_Analysis = 'cohort_analysis',\n Chem = 'chem',\n Trrack = 'trrack',\n None = 'none',\n Subsampled = 'subsampled',\n Experiments_Only = 'experiments_only',\n Subsampled_with_Sugestions = 'subsampled_with_suggestions',\n Experiments_Only_with_Sugestions = 'experiments_only_with_suggestions',\n Parameterspace_and_Experiments = 'parameterspace_and_experiments',\n Sound = 'sound',\n}\n","export enum DistanceMetric {\n EUCLIDEAN = 'euclidean',\n JACCARD = 'jaccard',\n GOWER = 'gower',\n COSINE = 'cosine',\n MANHATTAN = 'manhattan',\n}\n","import { EntityId } from '@reduxjs/toolkit';\nimport { ObjectTypes } from './ObjectType';\nimport { TypedObject } from './TypedObject';\n\n/**\n * Edge type.\n */\nexport interface IEdge extends TypedObject {\n id: EntityId;\n\n /**\n * Object type.\n */\n objectType: string;\n\n /**\n * Handle to source cluster.\n */\n source: EntityId;\n\n /**\n * Handle to destination cluster.\n */\n destination: EntityId;\n\n /**\n * Optional name for this edge (will be displayed like a street name).\n */\n name?: string;\n}\n\n/**\n * Edge type guard.\n */\nexport function isEdge(value: TypedObject): value is IEdge {\n if (value?.objectType == null) return false;\n return value && value.objectType === ObjectTypes.Edge;\n}\n","export enum EncodingChannel {\n Color = 'color',\n Opacity = 'opacity',\n Shape = 'shape',\n Size = 'size',\n}\n","export enum EncodingMethod { // for categorical features\n ONEHOT = 'onehot',\n NUMERIC = 'numeric',\n}\n","/**\n * The data type of a feature\n */\nexport enum FeatureType {\n /**\n * Means all values have no other group they belong to\n */\n String = 'String',\n\n /**\n * Means all values are real numbers e.g. 0.23, 0.13, 1, 2...\n */\n Quantitative = 'Quantitative',\n\n /**\n * Means the values represent groups\n */\n Categorical = 'Categorical',\n\n /**\n * Means all values are date timestamps\n */\n Date = 'Date',\n\n /**\n * Means there exist only 2 groups (stricter than categorical)\n */\n Binary = 'Binary',\n\n Ordinal = 'Ordinal',\n\n /**\n * Means all values are arrays of other values.\n */\n Array = 'Array',\n}\n\nexport function stringToFeatureType(value: string) {\n switch (value.toLowerCase()) {\n case 'array':\n return FeatureType.Array;\n case 'date':\n return FeatureType.Date;\n case 'categorical':\n return FeatureType.Categorical;\n case 'quantitative':\n return FeatureType.Quantitative;\n default:\n return FeatureType.String;\n }\n}\n","export enum NormalizationMethod {\n STANDARDIZE = 'standardize', // values are mapped to have 0 mean and unit standard deviation\n NORMALIZE01 = 'normalize01', // values are mapped between [0;1]\n}\n","export enum ObjectTypes {\n Cluster = 'cluster',\n Vector = 'vector',\n Edge = 'edge',\n}\n","import { v4 as uuidv4 } from 'uuid';\nimport { IBaseProjection, IProjection, ProjectionMethod } from './ProjectionInterfaces';\nimport type { ProjectionParamsType } from '../components/Ducks/ProjectionParamsDuck';\nimport { ADataset, Dataset } from './Dataset';\n\n/**\n * Projection API.\n */\nexport class AProjection {\n static createProjection(positions: IBaseProjection, name, metadata?: any): IProjection {\n const hash = uuidv4();\n const bounds = this.calculateBoundsFromPositions(positions);\n\n const deriveName = (metadata: ProjectionParamsType) => {\n const time = new Date().toLocaleTimeString('en-US', { hour12: false, hour: 'numeric', minute: 'numeric' });\n\n return `${metadata.method} at ${time}`;\n };\n\n if (name === null && metadata) {\n return {\n positions: positions.map((p) => ({ x: p.x, y: p.y })),\n hash,\n name: deriveName(metadata),\n metadata,\n bounds,\n };\n }\n return {\n positions: positions.map((p) => ({ x: p.x, y: p.y })),\n hash,\n name,\n metadata,\n bounds,\n };\n }\n\n static createManualProjection(dataset: Dataset, xChannel: string, yChannel: string): IProjection {\n const hash = uuidv4();\n\n return {\n hash,\n xChannel,\n yChannel,\n metadata: {\n method: ProjectionMethod.CUSTOM,\n },\n positions: null,\n name: null,\n bounds: AProjection.calculateBounds(dataset, xChannel, yChannel),\n };\n }\n\n /**\n * Calculates the dataset bounds for this set, eg the minimum and maximum x,y values\n * which is needed for the zoom to work correctly\n */\n static calculateBoundsFromPositions(spatial: IBaseProjection) {\n let minX = Number.MAX_SAFE_INTEGER;\n let maxX = Number.MIN_SAFE_INTEGER;\n let minY = Number.MAX_SAFE_INTEGER;\n let maxY = Number.MIN_SAFE_INTEGER;\n\n spatial.forEach((s) => {\n minX = Math.min(minX, s.x);\n maxX = Math.max(maxX, s.x);\n minY = Math.min(minY, s.y);\n maxY = Math.max(maxY, s.y);\n });\n\n const scaleBase = 100;\n const absoluteMaximum = Math.max(Math.abs(minX), Math.abs(maxX), Math.abs(minY), Math.abs(maxY));\n\n return {\n scaleBase,\n scaleFactor: absoluteMaximum / scaleBase,\n x: {\n min: minX,\n max: maxX,\n },\n y: {\n min: minY,\n max: maxY,\n },\n };\n }\n\n /**\n * Calculates the dataset bounds for this set, eg the minimum and maximum x,y values\n * which is needed for the zoom to work correctly\n */\n static calculateBounds(dataset: Dataset, xChannel, yChannel, positions?) {\n const spatial = ADataset.getSpatialData(dataset, xChannel, yChannel, positions);\n\n return this.calculateBoundsFromPositions(spatial);\n }\n}\n","export const ProjectionMethod = {\n TSNE: 'tsne',\n UMAP: 'umap',\n FORCEATLAS2: 'forceatlas2',\n CUSTOM: 'custom',\n RANDOM: 'random',\n DATASET: 'dataset',\n};\n\n/**\n * position type containing x and y coordinates.\n */\n\nexport type IPosition = {\n x: number;\n y: number;\n};\n/**\n * Projection item that also contains a name and a hash\n */\n\nexport type IProjection = {\n positions: IBaseProjection;\n name: string;\n hash: string;\n\n xChannel?: string;\n yChannel?: string;\n\n metadata?: { [id: string]: any };\n\n bounds?: { x; y; scaleBase; scaleFactor };\n};\n\n/**\n * Base type for projections\n */\n\nexport type IBaseProjection = IPosition[];\n","import { Shapes } from '../components/WebGLView/Shapes';\nimport { TypedObject } from './TypedObject';\nimport { ObjectTypes } from './ObjectType';\n\n/**\n * Vector type.\n */\nexport interface IVector extends TypedObject {\n x: number;\n y: number;\n\n // cluster label and probability\n groupLabel: any[];\n\n // assigned line\n line: any;\n\n // number of occurences of this vector\n multiplicity: number;\n\n // algorithm (category)\n algo: any;\n\n // age (generated)\n age: number;\n\n __meta__: VectView;\n}\n\n/**\n * Vector methods.\n */\n\n/**\n * View information for a vector, this contains all attributes that are not data related, for\n * example the color or the index to the mesh vertex\n */\nexport class VectView {\n /**\n * Index to the vertice from three\n */\n meshIndex = -1;\n\n /**\n * Is this vector selected?\n */\n selected = false;\n\n /**\n * The segment index this vector belongs to.\n */\n lineIndex: any;\n\n /**\n * Index of sequence from 0 to n, this is needed because the key for the line might be sortable, but not numeric\n */\n sequenceIndex = -1;\n\n /**\n * Set color for this vertice, if null the color of the line is taken\n */\n intrinsicColor = null;\n\n /**\n * Is this vector visible?\n */\n visible = true;\n\n /**\n * Currently displayed shape of the vector.\n */\n shapeType = Shapes.Circle;\n\n highlighted = false;\n\n duplicateOf = null;\n\n // Brightness value of this sample.\n brightness = 1.0;\n\n // is this sample filtered out in lineup\n lineUpFiltered = false;\n}\n\n/**\n * Vector type guard.\n */\nexport function isVector(object: TypedObject): object is IVector {\n return object && object.objectType === ObjectTypes.Vector;\n}\n\nexport class AVector {\n static create(dict): IVector {\n const vect = {\n ...dict,\n __meta__: new VectView(),\n objectType: ObjectTypes.Vector,\n };\n\n return vect as IVector;\n }\n}\n","export * from './Book';\nexport * from './Cluster';\nexport * from './DataLine';\nexport * from './Dataset';\nexport * from './DatasetType';\nexport * from './Edge';\nexport * from './Projection';\nexport * from './FeatureType';\nexport * from './ObjectType';\nexport * from './TypedObject';\nexport * from './Vector';\nexport * from './DatasetEntry';\nexport * from './EncodingChannel';\nexport * from './palettes';\nexport * from './Palette';\nexport * from './ProjectionInterfaces';\nexport * from './ICluster';\nexport * from './Curves';\n","import { SchemeColor } from '../components/Utility/Colors/SchemeColor';\nimport { BaseColorScale } from './Palette';\n\nconst palettes = {\n // categorical\n dark2: [\n new SchemeColor('#1b9e77'),\n new SchemeColor('#d95f02'),\n new SchemeColor('#e7298a'),\n new SchemeColor('#7570b3'),\n new SchemeColor('#66a61e'),\n new SchemeColor('#e6ab02'),\n new SchemeColor('#a6761d'),\n new SchemeColor('#666666'),\n ],\n accent: [\n new SchemeColor('#7fc97f'),\n new SchemeColor('#beaed4'),\n new SchemeColor('#fdc086'),\n new SchemeColor('#ffff99'),\n new SchemeColor('#386cb0'),\n new SchemeColor('#f0027f'),\n new SchemeColor('#bf5b17'),\n new SchemeColor('#666666'),\n ],\n paired: [\n new SchemeColor('#a6cee3'),\n new SchemeColor('#1f78b4'),\n new SchemeColor('#b2df8a'),\n new SchemeColor('#33a02c'),\n new SchemeColor('#fb9a99'),\n new SchemeColor('#e31a1c'),\n new SchemeColor('#fdbf6f'),\n new SchemeColor('#ff7f00'),\n new SchemeColor('#cab2d6'),\n new SchemeColor('#6a3d9a'),\n new SchemeColor('#ffff99'),\n new SchemeColor('#b15928'),\n ],\n set3: [\n new SchemeColor('#8dd3c7'),\n new SchemeColor('#ffffb3'),\n new SchemeColor('#bebada'),\n new SchemeColor('#fb8072'),\n new SchemeColor('#80b1d3'),\n new SchemeColor('#fdb462'),\n new SchemeColor('#b3de69'),\n new SchemeColor('#fccde5'),\n new SchemeColor('#d9d9d9'),\n new SchemeColor('#bc80bd'),\n new SchemeColor('#ccebc5'),\n new SchemeColor('#ffed6f'),\n ],\n\n // sequential\n Greys: [new SchemeColor('#ffffff'), new SchemeColor('#000000')],\n YlOrRd: [new SchemeColor('#ffffcc'), new SchemeColor('#fd8d3c'), new SchemeColor('#800026')],\n Viridis: [\n new SchemeColor('#440154'),\n new SchemeColor('#482475'),\n new SchemeColor('#414487'),\n new SchemeColor('#355f8d'),\n new SchemeColor('#2a788e'),\n new SchemeColor('#21908d'),\n new SchemeColor('#22a884'),\n new SchemeColor('#42be71'),\n new SchemeColor('#7ad151'),\n new SchemeColor('#bddf26'),\n new SchemeColor('#bddf26'),\n ],\n\n // diverging\n BrBG: [new SchemeColor('#543005'), new SchemeColor('#f5f5f5'), new SchemeColor('#003c30')],\n PRGn: [new SchemeColor('#40004b'), new SchemeColor('#f7f7f7'), new SchemeColor('#00441b')],\n SHAP: [new SchemeColor('#1e88e5'), new SchemeColor('#ffffff'), new SchemeColor('#ff0d57')],\n};\n\nexport const APalette = {\n getByName: (palette: string) => {\n return palettes[palette] as SchemeColor[];\n },\n};\n","import * as React from 'react';\nimport { arraysEqual } from '../../../components/WebGLView/UtilityFunctions';\nimport { IVector } from '../../../model/Vector';\nimport { CHESS_TILE_BLACK, CHESS_TILE_WHITE } from '../ChessFingerprint/ChessFingerprint';\n// @ts-ignore\nimport WR from '../../../../textures/chess/Chess_rlt45.png';\n// @ts-ignore\nimport WN from '../../../../textures/chess/Chess_nlt45.png';\n// @ts-ignore\nimport WB from '../../../../textures/chess/Chess_blt45.png';\n// @ts-ignore\nimport WK from '../../../../textures/chess/Chess_klt45.png';\n// @ts-ignore\nimport WQ from '../../../../textures/chess/Chess_qlt45.png';\n// @ts-ignore\nimport WP from '../../../../textures/chess/Chess_plt45.png';\n// @ts-ignore\nimport BR from '../../../../textures/chess/Chess_rdt45.png';\n// @ts-ignore\nimport BN from '../../../../textures/chess/Chess_ndt45.png';\n// @ts-ignore\nimport BB from '../../../../textures/chess/Chess_bdt45.png';\n// @ts-ignore\nimport BK from '../../../../textures/chess/Chess_kdt45.png';\n// @ts-ignore\nimport BQ from '../../../../textures/chess/Chess_qdt45.png';\n// @ts-ignore\nimport BP from '../../../../textures/chess/Chess_pdt45.png';\n// @ts-ignore\n\n// Lookup table for chess UNICODE symbols\nconst symbols = {\n wr: WR,\n wn: WN,\n wb: WB,\n wk: WK,\n wq: WQ,\n wp: WP,\n br: BR,\n bn: BN,\n bb: BB,\n bk: BK,\n bq: BQ,\n bp: BP,\n '': '',\n};\n\nconst CHESS_TILE_CHANGES = '#007dad';\n\nObject.keys(symbols)\n .filter((key) => key != '')\n .forEach((key) => {\n const path = symbols[key];\n const img = new Image(45, 45);\n img.src = path;\n symbols[key] = img;\n });\n\ntype ChessChangesProps = {\n vectorsA: Array;\n vectorsB: Array;\n width?: number;\n height?: number;\n};\n\nfunction getOccurences(vectors: Array) {\n const aggregation = {};\n const keys = [];\n\n const nums = [1, 2, 3, 4, 5, 6, 7, 8];\n const chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];\n\n nums.forEach((index) => {\n chars.forEach((char) => {\n keys.push(`${char}${index}`);\n });\n });\n\n vectors.forEach((vector, index) => {\n keys.forEach((key, keyIndex) => {\n if (aggregation[key] == undefined) {\n aggregation[key] = [];\n aggregation[key].push({ key: 'total', count: 0, relative: 1.0 });\n }\n\n if (!aggregation[key].some((e) => e.key == vector[key])) {\n aggregation[key].push({ key: vector[key], count: 1, relative: 0 });\n aggregation[key].filter((e) => e.key == 'total')[0].count += 1;\n } else {\n aggregation[key].filter((e) => e.key == vector[key])[0].count += 1;\n aggregation[key].filter((e) => e.key == 'total')[0].count += 1;\n }\n });\n });\n\n // calculate relative counts\n vectors.forEach((vector, index) => {\n keys.forEach((key, keyIndex) => {\n const x = aggregation[key].filter((e) => e.key == vector[key])[0];\n const total = aggregation[key].filter((e) => e.key == 'total')[0].count;\n x.relative = x.count / total;\n });\n });\n\n return aggregation;\n}\n\nfunction getProminent(aggregation, key) {\n let max = 0.0;\n let total = 0;\n let content = '';\n let opacity = 1;\n for (const k in aggregation[key]) {\n if (aggregation[key][k].key === 'total') {\n continue;\n }\n const v = aggregation[key][k];\n total += v.count;\n\n if (v.count > max && symbols[aggregation[key][k].key] !== '' && symbols[aggregation[key][k].key] !== undefined) {\n max = v.count;\n content = aggregation[key][k].key;\n }\n }\n\n if (content == null) {\n content = '';\n }\n\n opacity = max / total;\n return [content, opacity];\n}\n\nexport class ChessChanges extends React.Component {\n canvasRef = React.createRef();\n\n canvasContext: CanvasRenderingContext2D = null;\n\n constructor(props: ChessChangesProps) {\n super(props);\n }\n\n renderToContext() {\n const { vectorsA } = this.props;\n const { vectorsB } = this.props;\n\n // Get layout size, on retina display, canvas width is actually larger\n const cssWidth = this.props.width ? this.props.width : this.canvasRef.current.getBoundingClientRect().width;\n const cssHeight = this.props.height ? this.props.height : this.canvasRef.current.getBoundingClientRect().height;\n\n // Set values to multiples of 9 so pixels arent smudged\n let width = cssWidth * window.devicePixelRatio;\n let height = cssHeight * window.devicePixelRatio;\n width = Math.floor(width / 8) * 8;\n height = Math.floor(height / 8) * 8;\n\n const size = (width * 10) / 82;\n const borderOffset = width / 82;\n\n this.canvasRef.current.setAttribute('width', width.toString());\n this.canvasRef.current.setAttribute('height', height.toString());\n\n // Generate chess keys\n let keys = [];\n\n const nums = [1, 2, 3, 4, 5, 6, 7, 8];\n const chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];\n\n nums.forEach((index) => {\n chars.forEach((char) => {\n keys.push(`${char}${index}`);\n });\n });\n\n const countA = getOccurences(vectorsA);\n const countB = getOccurences(vectorsB);\n\n // horizontal chess keys\n keys = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];\n\n // variable determining the current field color\n let col = CHESS_TILE_WHITE;\n\n // draw border around chess board\n this.canvasContext.globalAlpha = 1.0;\n this.canvasContext.fillStyle = CHESS_TILE_BLACK;\n try {\n this.canvasContext.save();\n this.canvasContext.globalAlpha = 1.0;\n this.canvasContext.fillRect(0, 0, width, height);\n this.canvasContext.restore();\n } catch (e) {}\n\n for (let i = 0; i < 64; i++) {\n const x = i % 8;\n const y = Math.floor(i / 8);\n if (i % 8 != 0) {\n if (col == CHESS_TILE_WHITE) {\n col = CHESS_TILE_BLACK;\n } else {\n col = CHESS_TILE_WHITE;\n }\n }\n\n const key = `${keys[i % 8]}${8 - ((i / 8) >> 0)}`;\n\n let content = '';\n const opacity = 1;\n let deleted = false;\n\n const [contentA, opacityA] = getProminent(countA, key) as [string, number];\n const [contentB, opacityB] = getProminent(countB, key) as [string, number];\n\n // calculate opacity for colour difference visualization for this field\n\n // collect fieldKeys that exist in both selections\n const keysA = [];\n const numsA = Object.keys(countA[key]);\n for (var num in numsA) {\n keysA.push(countA[key][num].key);\n }\n const keysB = [];\n const numsB = Object.keys(countB[key]);\n for (var num in numsB) {\n keysB.push(countB[key][num].key);\n }\n let allKeys = keysA.concat(keysB);\n allKeys = allKeys.filter((item, pos) => allKeys.indexOf(item) === pos);\n\n let diffSum = 0;\n\n // iterate over all keys\n for (const n in allKeys) {\n var fieldKey = allKeys[n];\n\n const entryA = countA[key].filter((e) => e.key == fieldKey);\n const entryB = countB[key].filter((e) => e.key == fieldKey);\n\n if (entryA[0] && entryB[0]) {\n diffSum += Math.abs(entryA[0].relative - entryB[0].relative);\n } else if (entryA[0]) {\n diffSum += Math.abs(entryA[0].relative);\n } else if (entryB[0]) {\n diffSum += Math.abs(entryB[0].relative);\n }\n }\n // opacity\n const difColourOpacity = diffSum / 2;\n\n if (contentA != contentB) {\n content = contentB;\n }\n if (contentA != '' && contentB == '') {\n deleted = true;\n }\n\n this.canvasContext.globalAlpha = 1.0;\n this.canvasContext.fillStyle = col;\n\n this.canvasContext.fillRect(x * size + borderOffset, y * size + borderOffset, size, size);\n\n try {\n this.canvasContext.save();\n // diff colour\n this.canvasContext.globalAlpha = difColourOpacity;\n this.canvasContext.fillStyle = CHESS_TILE_CHANGES;\n this.canvasContext.fillRect(x * size + borderOffset, y * size + borderOffset, size, size);\n\n // chess pieces\n this.canvasContext.globalAlpha = Math.max(opacityB, 0.0);\n this.canvasContext.drawImage(symbols[content], x * size + borderOffset, y * size + borderOffset, size, size);\n this.canvasContext.restore();\n } catch (e) {}\n }\n }\n\n componentDidMount() {\n this.canvasContext = this.canvasRef.current.getContext('2d');\n\n this.renderToContext();\n }\n\n componentDidUpdate(prevProps) {\n if (!arraysEqual(prevProps.vectorsA, this.props.vectorsA) || !arraysEqual(prevProps.vectorsB, this.props.vectorsB)) {\n this.renderToContext();\n }\n }\n\n render() {\n return (\n \n );\n }\n}\n","import * as React from 'react';\nimport { arraysEqual } from '../../../components/WebGLView/UtilityFunctions';\n// @ts-ignore\nimport WR from '../../../../textures/chess/Chess_rlt45.png';\n// @ts-ignore\nimport WN from '../../../../textures/chess/Chess_nlt45.png';\n// @ts-ignore\nimport WB from '../../../../textures/chess/Chess_blt45.png';\n// @ts-ignore\nimport WK from '../../../../textures/chess/Chess_klt45.png';\n// @ts-ignore\nimport WQ from '../../../../textures/chess/Chess_qlt45.png';\n// @ts-ignore\nimport WP from '../../../../textures/chess/Chess_plt45.png';\n// @ts-ignore\nimport BR from '../../../../textures/chess/Chess_rdt45.png';\n// @ts-ignore\nimport BN from '../../../../textures/chess/Chess_ndt45.png';\n// @ts-ignore\nimport BB from '../../../../textures/chess/Chess_bdt45.png';\n// @ts-ignore\nimport BK from '../../../../textures/chess/Chess_kdt45.png';\n// @ts-ignore\nimport BQ from '../../../../textures/chess/Chess_qdt45.png';\n// @ts-ignore\nimport BP from '../../../../textures/chess/Chess_pdt45.png';\n// @ts-ignore\n\n// Lookup table for chess UNICODE symbols\nconst symbols = {\n wr: WR,\n wn: WN,\n wb: WB,\n wk: WK,\n wq: WQ,\n wp: WP,\n br: BR,\n bn: BN,\n bb: BB,\n bk: BK,\n bq: BQ,\n bp: BP,\n '': '',\n};\n\nexport const CHESS_TILE_BLACK = '#edeeef';\nexport const CHESS_TILE_WHITE = '#ffffff';\n\nexport const requiredChessColumns = [];\n\n['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].forEach((c) => {\n [1, 2, 3, 4, 5, 6, 7, 8].forEach((n) => {\n requiredChessColumns.push(`${c}${n}`);\n });\n});\n\nObject.keys(symbols)\n .filter((key) => key != '')\n .forEach((key) => {\n const path = symbols[key];\n const img = new Image(45, 45);\n img.src = path;\n symbols[key] = img;\n });\n\ntype ChessFingerprintProps = {\n vectors: Array;\n width?: number;\n height?: number;\n};\n\nexport class ChessFingerprint extends React.Component {\n canvasRef = React.createRef();\n\n canvasContext: CanvasRenderingContext2D = null;\n\n constructor(props: ChessFingerprintProps) {\n super(props);\n }\n\n renderToContext() {\n const { vectors } = this.props;\n\n // Get layout size, on retina display, canvas width is actually larger\n const cssWidth = this.props.width ? this.props.width : this.canvasRef.current.getBoundingClientRect().width;\n const cssHeight = this.props.height ? this.props.height : this.canvasRef.current.getBoundingClientRect().height;\n\n // Set values to multiples of 9 so pixels arent smudged\n let width = cssWidth * window.devicePixelRatio;\n let height = cssHeight * window.devicePixelRatio;\n width = Math.floor(width / 8) * 8;\n height = Math.floor(height / 8) * 8;\n\n const size = (width * 10) / 82;\n const borderOffset = width / 82;\n\n this.canvasRef.current.setAttribute('width', width.toString());\n this.canvasRef.current.setAttribute('height', height.toString());\n\n // Generate chess keys\n let keys = [];\n\n const nums = [1, 2, 3, 4, 5, 6, 7, 8];\n const chars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];\n\n nums.forEach((index) => {\n chars.forEach((char) => {\n keys.push(`${char}${index}`);\n });\n });\n\n const aggregation = {};\n\n vectors.forEach((vector, index) => {\n keys.forEach((key, keyIndex) => {\n if (aggregation[key] == undefined) {\n aggregation[key] = [];\n }\n\n if (!aggregation[key].some((e) => e.key == vector[key])) {\n aggregation[key].push({ key: vector[key], count: 1 });\n } else {\n aggregation[key].filter((e) => e.key == vector[key])[0].count += 1;\n }\n });\n });\n\n // horizontal chess keys\n keys = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];\n\n // variable determining the current field color\n let col = CHESS_TILE_WHITE;\n\n // draw border around chess board\n this.canvasContext.globalAlpha = 1.0;\n this.canvasContext.fillStyle = CHESS_TILE_BLACK;\n try {\n this.canvasContext.save();\n this.canvasContext.globalAlpha = 1.0;\n this.canvasContext.fillRect(0, 0, width, height);\n this.canvasContext.restore();\n } catch (e) {}\n\n for (let i = 0; i < 64; i++) {\n const x = i % 8;\n const y = Math.floor(i / 8);\n if (i % 8 != 0) {\n if (col == CHESS_TILE_WHITE) {\n col = CHESS_TILE_BLACK;\n } else {\n col = CHESS_TILE_WHITE;\n }\n }\n\n const key = `${keys[i % 8]}${8 - ((i / 8) >> 0)}`;\n let content = '';\n let opacity = 1.0;\n\n if (vectors.length == 0) {\n content = '';\n } else if (aggregation[key].length == 1) {\n content = symbols[aggregation[key][0].key];\n content = aggregation[key][0].key;\n } else {\n let max = 0.0;\n let total = 0;\n for (const k in aggregation[key]) {\n const v = aggregation[key][k];\n total += v.count;\n\n if (v.count > max && symbols[aggregation[key][k].key] !== '' && symbols[aggregation[key][k].key] !== undefined) {\n max = v.count;\n content = symbols[aggregation[key][k].key];\n content = aggregation[key][k].key;\n }\n }\n\n opacity = Math.max(max / total, 0.0);\n }\n this.canvasContext.globalAlpha = 1.0;\n\n this.canvasContext.fillStyle = col;\n\n this.canvasContext.fillRect(x * size + borderOffset, y * size + borderOffset, size, size);\n\n try {\n this.canvasContext.save();\n this.canvasContext.globalAlpha = opacity;\n this.canvasContext.drawImage(symbols[content], x * size + borderOffset, y * size + borderOffset, size, size);\n this.canvasContext.restore();\n } catch (e) {}\n }\n }\n\n componentDidMount() {\n this.canvasContext = this.canvasRef.current.getContext('2d');\n\n this.renderToContext();\n }\n\n componentDidUpdate(prevProps) {\n if (!arraysEqual(prevProps.vectors, this.props.vectors)) {\n this.renderToContext();\n }\n }\n\n render() {\n return (\n \n );\n }\n}\n","import * as React from 'react';\nimport { IVector } from '../../model/Vector';\nimport { DatasetType } from '../../model/DatasetType';\nimport { PSEPlugin } from '../../components/Store/PSEPlugin';\nimport { ChessFingerprint } from './ChessFingerprint/ChessFingerprint';\nimport { Dataset } from '../../model/Dataset';\n\nexport class ChessPlugin extends PSEPlugin {\n type = DatasetType.Chess;\n\n hasFileLayout(header: string[]) {\n const requiredChessColumns = [];\n\n ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].forEach((c) => {\n [1, 2, 3, 4, 5, 6, 7, 8].forEach((n) => {\n requiredChessColumns.push(`${c}${n}`);\n });\n });\n\n return this.hasLayout(header, requiredChessColumns);\n }\n\n createFingerprint(dataset: Dataset, vectors: IVector[], scale: number, aggregate: boolean): JSX.Element {\n return ;\n }\n}\n","import * as jStat from 'jstat';\n\nexport class ChiSquareTest {\n public calc(setA: any[], setB: any[]) {\n const setACategories = setA.filter((item, index, self) => self.indexOf(item) === index);\n const setBCategories = setB.filter((item, index, self) => self.indexOf(item) === index);\n const allCategories = setACategories.concat(setBCategories).filter((item, index, self) => self.indexOf(item) === index);\n\n let score = 0;\n let pValue = -1;\n\n if (allCategories.length > 1) {\n const setASize = setA.length;\n const setBSize = setB.length;\n const overallSize = setASize + setBSize;\n\n const table = [];\n for (const currCat of allCategories) {\n const amountSetA = setA.filter((item) => item === currCat).length;\n const amountSetB = setB.filter((item) => item === currCat).length;\n const sum = amountSetA + amountSetB;\n const setAExp = (setASize * sum) / overallSize;\n const setAChi = (amountSetA - setAExp) ** 2 / setAExp;\n\n const setBExp = (setBSize * sum) / overallSize;\n const setBChi = (amountSetB - setBExp) ** 2 / setBExp;\n const sumChi = setAChi + setBChi;\n const currCell = {\n category: currCat,\n setA: amountSetA,\n setAExp,\n setAChi,\n setB: amountSetB,\n setBExp,\n setBChi,\n sum,\n sumChi,\n };\n table.push(currCell);\n }\n\n const allChiForCategories = table.map((a) => a.sumChi);\n const chiSquare = allChiForCategories.reduce(this.getSum);\n const rows = 2; // the two sets\n const columns = table.length; // number of categories in the two sets\n const df = (rows - 1) * (columns - 1);\n // Phi\n // const phi = Math.sqrt(chiSquare/overallSize);\n // Cramer's V\n const t = Math.min(rows - 1, columns - 1);\n const cramerV = Math.sqrt(chiSquare / (overallSize * t));\n\n score = cramerV;\n pValue = 1 - jStat.jStat.chisquare.cdf(chiSquare, df);\n }\n\n return {\n scoreValue: score,\n pValue,\n setSizeA: setA.length,\n setSizeB: setB.length,\n };\n }\n\n public getSum(total: number, numb: number) {\n return total + numb;\n }\n}\n","import * as d3v5 from 'd3v5';\nimport * as React from 'react';\nimport { connect, ConnectedProps } from 'react-redux';\nimport { Handler } from 'vega-tooltip';\nimport { makeStyles } from '@mui/styles';\nimport './coral.scss';\nimport { Table, TableBody, TableCell, TableHead, TableRow } from '@mui/material';\nimport { Dataset } from '../../../model/Dataset';\nimport { IVector } from '../../../model/Vector';\nimport { FeatureType } from '../../../model/FeatureType';\nimport type { RootState } from '../../../components/Store/Store';\nimport Boxplot from './VegaBoxplot';\nimport BarChanges from './VegaBarChanges';\nimport { ChiSquareTest } from './ChiSquare';\n\nconst useStyles = makeStyles({\n table: {\n maxWidth: 288,\n },\n});\n\nfunction getProjectionColumns(legendAttributes) {\n if (legendAttributes === null) {\n return [];\n }\n const pcol = [];\n for (let i = 0; i <= legendAttributes.length; i++) {\n if (legendAttributes[i] !== undefined && legendAttributes[i].show) {\n pcol.push(legendAttributes[i].feature);\n }\n }\n return pcol;\n}\n\nfunction getCounts(arr) {\n // [\"asd\", \"asd\", \"asd\", \"qwe\", \"yxc\"] -> [[\"asd\",\"qwe\",\"yxc\"], [[3,1,1]]\n const a = [];\n const b = [];\n let prev;\n\n arr.sort();\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] !== prev) {\n a.push(arr[i]);\n b.push(1);\n } else {\n b[b.length - 1]++;\n }\n prev = arr[i];\n }\n return [a, b];\n}\n\nfunction dictionary(list) {\n const map = {};\n for (let i = 0; i < list.length; ++i) {\n for (const key in list[i]) {\n if (key in map) {\n map[key].push(list[i][key]);\n } else {\n map[key] = [list[i][key]];\n }\n }\n }\n return map;\n}\n\nfunction sortByScore(a, b) {\n if (a.score === b.score) {\n return 0;\n }\n\n return a.score < b.score ? 1 : -1;\n}\n\nfunction createData(feature, category, score, char, difference) {\n return { feature, category, score, char, difference };\n}\n\nfunction getBins(a, n = 10) {\n const bin = d3v5.histogram().thresholds(n - 1);\n return bin(a);\n}\n\nfunction getMaxDif(a, b) {\n const aSum = a.reduce((x, y) => x + y, 0);\n const bSum = b.reduce((x, y) => x + y, 0);\n\n // get index where 2 arrays a and b differ the most + value\n let maxDif = 0;\n let maxDifIndex = 0;\n\n const x = a.map(function (item, index) {\n // In this case item corresponds to currentValue of array a,\n // using index to get value from array b\n // const dif = Math.abs(item - b[index])\n const dif = Math.abs(item / aSum - b[index] / bSum);\n maxDifIndex = dif > maxDif ? index : maxDifIndex;\n maxDif = dif > maxDif ? dif : maxDif;\n return dif;\n });\n return [maxDif, maxDifIndex];\n}\n\nfunction getCombinedCounts(a, b) {\n // a = [[\"qwe\",\"asd\"][3,1]], b = [[\"asd\",\"yxc\"],\"2,2\"]\n // -> [[\"qwe\",\"asd\",\"yxc\"],[3,1,0],[0,2,2]]\n const featuresA = a[0];\n const valuesA = a[1];\n const featuresB = b[0];\n const valuesB = b[1];\n const featureDictA = [];\n const featureDictB = [];\n\n for (let i = 0; i < a.length; i++) {\n var key = featuresA[i];\n var value = valuesA[i];\n featureDictA[key] = value;\n featureDictB[key] = 0;\n }\n\n for (let i = 0; i < a.length; i++) {\n var key = featuresB[i];\n var value = valuesB[i];\n featureDictB[key] = value;\n if (!(key in featureDictA)) featureDictA[key] = 0;\n }\n\n return [Object.keys(featureDictA), Object.values(featureDictA), Object.values(featureDictB)];\n}\n\nfunction getFeaturesCounts(a, b) {\n // data like [\"asd\", \"asd\", \"qwe\", ...]\n // turn into [\"asd\", \"qwe\", ...], [2, 43, ...]\n const countsA = getCounts(a);\n const countsB = getCounts(b);\n // add missing features that didn't occur in respectively other array\n const combinedCounts = getCombinedCounts(countsA, countsB);\n return combinedCounts;\n}\n\nfunction isInBin(x, i, lowerBounds, upperBounds) {\n return x >= lowerBounds[i] && x <= upperBounds[i];\n}\n\nfunction getFlattenedBins(a, b) {\n // bin a,b together to find sensible bins\n // then e.g. if resulting bins are 1: [1,2] and 2: [2,3]\n // and a = [1.2, 1.7, 2.2, 2.8, 3.0]\n // returns [1, 1, 2, 2, 2] for a\n // similar for b\n\n // find sensible bins for both a,b together\n const bin = d3v5.histogram().thresholds(10 - 1);\n const binned = bin(a.concat(b));\n const lowerBounds = [];\n const upperBounds = [];\n binned.forEach((e) => {\n lowerBounds.push(e.x0);\n upperBounds.push(e.x1);\n });\n\n a = a.sort();\n b = b.sort();\n\n const retA = [];\n const retB = [];\n\n let binIdx = 0;\n\n // go over each element of a\n for (var i = 0; i < a.length; i++) {\n const e = a[i];\n // starting at lowest bin, go to next bin until current element fits in\n while (!isInBin(e, binIdx, lowerBounds, upperBounds) && binIdx < lowerBounds.length) {\n binIdx++;\n }\n retA.push(binIdx);\n }\n\n binIdx = 0;\n\n // go over each element of b\n for (var i = 0; i < b.length; i++) {\n const e = b[i];\n // starting at lowest bin, go to next bin until current element fits in\n while (!isInBin(e, binIdx, lowerBounds, upperBounds) && binIdx < lowerBounds.length) {\n binIdx++;\n }\n retB.push(binIdx);\n }\n\n return [retA, retB];\n}\n\nfunction getMostDifferingCategory(setA, setB): [number, string] {\n const data = [];\n\n const setACategories = setA.filter((item, index, self) => self.indexOf(item) === index);\n const setBCategories = setB.filter((item, index, self) => self.indexOf(item) === index);\n const allCategories = setACategories.concat(setBCategories).filter((item, index, self) => self.indexOf(item) === index);\n\n const setASize = setA.length;\n const setBSize = setB.length;\n const overallSize = setASize + setBSize;\n\n for (const currCat of allCategories) {\n const amountSetA = setA.filter((item) => item === currCat).length;\n const amountSetB = setB.filter((item) => item === currCat).length;\n\n // const relDif = (amountSetB - amountSetA) / amountSetA\n const relDif = amountSetB / setBSize - amountSetA / setASize;\n data.push({ category: currCat, difference: relDif });\n }\n\n const sorted = data.sort(sortByAbsDifference);\n\n return [sorted[0].difference, sorted[0].category];\n}\n\nfunction oldGetMostDifferingCategory(a, b): [number, string] {\n // return max dif value, max dif index\n if (!a || !b) {\n return [0, ''];\n }\n const featuresCounts = getFeaturesCounts(a, b);\n const features = featuresCounts[0];\n a = featuresCounts[1];\n b = featuresCounts[2];\n const ret = getMaxDif(a, b);\n\n return [ret[0], features[ret[1]]];\n}\n\nfunction getDifference(a, b, type): [number, string, number] {\n if (!a || !b) {\n return [0, '', 0];\n }\n\n // a, b are arrays of values of the same feature for both selections A and B\n // a = [\"qwe\", \"qwe\", \"qwe\", \"asd\", ...]\n // or\n // a = [1, 1, 1, 1, 1, 1, 1, 2.3, 2.3, 2.3, ...]\n // determine difference score\n\n let maxDifFeature = '';\n let maxDifVal = 0;\n\n if (type !== FeatureType.Categorical) {\n // bin continuous data and turn into categorical data using bin numbers\n const flatBins = getFlattenedBins(a, b);\n a = flatBins[0];\n b = flatBins[1];\n } else {\n // find most differing category\n [maxDifVal, maxDifFeature] = getMostDifferingCategory(a, b);\n }\n\n // calculate chi-sqaure score\n const test = new ChiSquareTest();\n const dif = test.calc(a, b);\n\n // for quantitative data use score avlue as difference\n if (type !== FeatureType.Categorical) {\n maxDifVal = dif.scoreValue;\n }\n\n return [dif.scoreValue, maxDifFeature, maxDifVal];\n}\n\nfunction sortByAbsDifference(a, b) {\n if (Math.abs(a.difference) === Math.abs(b.difference)) {\n return 0;\n }\n\n return Math.abs(a.difference) < Math.abs(b.difference) ? 1 : -1;\n}\n\nfunction mapCategoricalChangesData(setA, setB, feature) {\n if (!setA || !setB) {\n return { values: [] };\n }\n // a, b like [\"qwe\",\"qwe\",\"asd\"], ...\n // turn into {'values': [{'category': 'qwe', 'difference': 0.8}, {'category': 'asd', 'difference': -0.6}]\n // should be sorted by absolute difference\n\n const data = [];\n\n const setACategories = setA.filter((item, index, self) => self.indexOf(item) === index);\n const setBCategories = setB.filter((item, index, self) => self.indexOf(item) === index);\n const allCategories = setACategories.concat(setBCategories).filter((item, index, self) => self.indexOf(item) === index);\n\n const setASize = setA.length;\n const setBSize = setB.length;\n const overallSize = setASize + setBSize;\n\n for (const currCat of allCategories) {\n const amountSetA = setA.filter((item) => item === currCat).length;\n const amountSetB = setB.filter((item) => item === currCat).length;\n\n // const relDif = (amountSetB - amountSetA) / amountSetA\n const relDif = amountSetB / setBSize - amountSetA / setASize;\n data.push({ category: currCat, difference: relDif });\n }\n\n const sorted = data.sort(sortByAbsDifference);\n for (let i = 0; i < sorted.length; i++) {\n sorted[i].rank = i + 1;\n }\n\n return { values: sorted };\n}\n\nfunction getCategoricalVis(a, b, feature) {\n const data = mapCategoricalChangesData(a, b, feature);\n return (\n
    \n {feature}\n
    \n \n
    \n );\n}\n\nfunction mapContinuousChangesData(a, b, feature) {\n const data = [];\n a.forEach((e) => {\n data.push({ val: e, selection: 'A' });\n });\n b.forEach((e) => {\n data.push({ val: e, selection: 'B' });\n });\n return { values: data };\n}\n\nfunction getContinuousVis(a, b, feature) {\n const data = mapContinuousChangesData(a, b, feature);\n return (\n
    \n {feature}\n
    \n \n
    \n );\n}\n\nfunction getVis(a, b, type, feature) {\n if (type === FeatureType.Categorical) {\n return getCategoricalVis(a, b, feature);\n }\n return getContinuousVis(a, b, feature);\n}\n\nfunction genRows(vectorsA, vectorsB, legendAttributes, dataset) {\n if (dataset === undefined) {\n return [];\n }\n const rows = [];\n const dictOfArraysA = dictionary(vectorsA);\n const dictOfArraysB = dictionary(vectorsB);\n const preselect = getProjectionColumns(legendAttributes);\n\n // for each feature in preselect\n preselect.forEach((key) => {\n const type = dataset.columns[key]?.featureType;\n const valuesA = dictOfArraysA[key];\n const valuesB = dictOfArraysB[key];\n // calc difference between A and B and\n const [difScore, mostDifCat, difVal] = getDifference(valuesA, valuesB, type);\n\n // append dif to rows\n // create visualization for those features and append to rows\n const vis = getVis(valuesA, valuesB, type, key);\n\n // append to rows: key, most differing category, dif score, vis, difVal\n if (dataset.columns[key]?.metaInformation.noLineUp) {\n // dont do anything, if column should not be shown\n } else {\n rows.push([key, mostDifCat, difScore, vis, difVal]);\n }\n });\n\n // turn into array of dicts\n const ret = [];\n for (let i = 0; i < rows.length; i++) {\n ret.push(createData(rows[i][0], rows[i][1], rows[i][2], rows[i][3], rows[i][4]));\n }\n\n // sort rows by score\n ret.sort(sortByScore);\n\n return ret;\n}\n\nconst mapStateToProps = (state: RootState) => {\n return {\n dataset: state.dataset,\n differenceThreshold: state.differenceThreshold,\n legendAttributes: state.genericFingerprintAttributes,\n };\n};\n\nconst mapDispatch = (dispatch) => ({\n // legendAttributes and dataset should not be changed from within this component\n});\n\nconst connector = connect(mapStateToProps, mapDispatch);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {\n width?: number;\n height?: number;\n vectorsA: Array;\n vectorsB: Array;\n dataset: Dataset;\n scale: number;\n};\n\n/**\n * filter rows within vega specs according to threshold\n * @param rows array of [{ feature, category, score, char, difference }, ...]\n * @param threshold filter all r={...} with r.difference < threshold, except for quantitative data\n * @param dataset dataset from props to lookup feature type\n */\nfunction filterReactVega(rows, threshold, dataset) {\n for (let i = 0; i < rows.length; i++) {\n const type = dataset.columns[rows[i].feature]?.featureType;\n\n if (type === FeatureType.Categorical) {\n rows[i].char.props.children[2].props.data.values = rows[i].char.props.children[2].props.data.values.filter((v) => {\n return Math.abs(v.difference) >= threshold;\n });\n }\n }\n return rows;\n}\n\nexport const CoralChanges = connector(\n class extends React.Component {\n rows: any[];\n\n constructor(props) {\n super(props);\n }\n\n render() {\n // generate rows including vega specs for table div\n this.rows = genRows(this.props.vectorsA, this.props.vectorsB, this.props.legendAttributes, this.props.dataset);\n // filter entire vega specs with threshold\n this.rows = this.rows.filter((r) => {\n return Math.abs(r.difference) >= this.props.differenceThreshold;\n });\n // filter individual categorical vega spec bars with threshold\n this.rows = filterReactVega(this.rows, this.props.differenceThreshold, this.props.dataset);\n\n return (\n \n \n \n \n {this.rows.map((row) => (\n \n {row.char}\n \n ))}\n \n
    \n \n );\n }\n },\n);\n","import * as React from 'react';\nimport { createClassFromSpec, VisualizationSpec, VegaLite } from 'react-vega';\nimport { VegaLiteProps } from 'react-vega/lib/VegaLite';\n\nconst spec: VisualizationSpec = {\n width: 100,\n transform: [\n { calculate: 'abs(datum.difference)', as: 'abs' },\n {\n window: [\n {\n op: 'rank',\n as: 'rank',\n },\n ],\n sort: [{ field: 'abs', order: 'descending' }],\n },\n ],\n\n encoding: {\n x: {\n field: 'difference',\n type: 'quantitative',\n scale: { domain: [-1, 1] },\n axis: { format: ',%', title: '', grid: false },\n },\n y: { field: 'category', type: 'ordinal', sort: { field: 'datum.abs' }, axis: { title: null, labelLimit: 50, orient: 'right', ticks: false } },\n text: { field: 'category', type: 'nominal' },\n color: {\n condition: {\n test: \"indexof(['null', 'undefined', 'unknown', 'none', 'Null', 'Undefined', 'Unknown', 'None', 'NULL', 'UNDEFINED', 'UNKNOWN', 'NONE'], datum.category) >= 0 || datum.category === null\",\n value: '#aaaaaa',\n },\n value: '#007dad',\n legend: null,\n },\n },\n\n layer: [\n {\n mark: { type: 'bar', tooltip: true },\n height: { step: 10 },\n },\n ],\n config: {\n view: { strokeWidth: 0 },\n axisY: { domainColor: 'white' },\n axisX: { domainColor: '#ddd', tickColor: '#ddd' },\n },\n data: { name: 'values' },\n};\n\nexport default function (props: Omit) {\n return ;\n}\n\n// , \"scale\": {\"domain\": [0, 1]}\n// rank != 1 and switching color scale range would be a workaround to make sure when there is only 1 datapoint it has the rank 1 colour\n","import * as React from 'react';\nimport { VisualizationSpec, VegaLite } from 'react-vega';\nimport { VegaLiteProps } from 'react-vega/lib/VegaLite';\n\nconst spec: VisualizationSpec = {\n width: 100,\n mark: {\n type: 'boxplot',\n extent: 'min-max',\n median: { color: 'black' },\n },\n encoding: {\n y: { field: 'selection', type: 'nominal', axis: null },\n x: {\n field: 'val',\n type: 'quantitative',\n scale: { zero: false },\n axis: { title: null, grid: false },\n },\n color: {\n value: '#007dad',\n },\n },\n data: { name: 'values' },\n};\n\nexport default function (props: Omit) {\n return ;\n}\n\n// , \"scale\": {\"domain\": [0, 1]}\n// rank != 1 and switching color scale range would be a workaround to make sure when there is only 1 datapoint it has the rank 1 colour\n","import * as React from 'react';\nimport { createClassFromSpec, VisualizationSpec, VegaLite } from 'react-vega';\nimport { VegaLiteProps } from 'react-vega/lib/VegaLite';\n\nconst spec: VisualizationSpec = {\n width: 50,\n height: 50,\n transform: [\n {\n window: [\n {\n op: 'row_number',\n as: 'rank',\n },\n ],\n sort: [{ field: 'count', order: 'descending' }],\n },\n {\n filter: 'datum.rank <= 5',\n },\n ],\n mark: { type: 'bar', tooltip: true },\n encoding: {\n x: { field: 'category', type: 'ordinal', axis: null, sort: '-y' },\n y: { field: 'count', type: 'quantitative', axis: null },\n color: {\n condition: {\n test: \"indexof(['null', 'undefined', 'unknown', 'none', 'Null', 'Undefined', 'Unknown', 'None', 'NULL', 'UNDEFINED', 'UNKNOWN', 'NONE'], datum.category) >= 0 || datum.category === null\",\n value: '#aaaaaa',\n },\n value: '#007dad',\n legend: null,\n },\n },\n data: { name: 'values' },\n};\n\nexport default function (props: Omit) {\n return ;\n}\n\n// , \"scale\": {\"domain\": [0, 1]}\n// rank != 1 and switching color scale range would be a workaround to make sure when there is only 1 datapoint it has the rank 1 colour\n","import * as React from 'react';\nimport { connect, ConnectedProps } from 'react-redux';\nimport { Handler } from 'vega-tooltip';\nimport { makeStyles } from '@mui/styles';\nimport './coral.scss';\nimport { Table, TableBody, TableCell, TableHead, TableRow } from '@mui/material';\nimport * as vegaImport from 'vega';\nimport { FeatureType } from '../../../model/FeatureType';\nimport { IVector } from '../../../model/Vector';\nimport BarChart from './BarChart';\nimport VegaDensity from './VegaDensity';\nimport VegaDate from './VegaDate';\nimport type { RootState } from '../../../components/Store/Store';\n\nconst useStyles = makeStyles({\n table: {\n maxWidth: 288,\n },\n tableRow: {\n height: '66px',\n },\n});\n\nfunction createData(feature, category, score, char) {\n return { feature, category, score, char };\n}\n\nfunction mapHistData(data, feature) {\n const mapped = data.map((d) => {\n return {\n feature: +d[feature],\n };\n });\n return { values: mapped };\n}\n\nfunction mapDensityData(allData, selectedData, feature) {\n const mappedData = allData.map((d, i) => {\n return {\n feature: +d[feature],\n selection: 'all',\n };\n });\n const mappedSelection = selectedData.map((d, i) => {\n return {\n feature: +d[feature],\n selection: 'selection',\n };\n });\n const mapped = [...mappedSelection, ...mappedData];\n return { values: mapped };\n}\n\nfunction mapBarChartData(data, feature) {\n const counts = {};\n for (let i = 0; i < data.length; i++) {\n if (data[i][feature] in counts) {\n counts[data[i][feature]] += 1;\n } else {\n counts[data[i][feature]] = 1;\n }\n }\n\n const sortCountDesc = (a, b) => {\n return b.count - a.count;\n };\n\n const barChartData = [];\n for (const key in counts) {\n let count = counts[key] / data.length;\n count = isFinite(count) ? count : 0;\n barChartData.push({ category: key, count });\n }\n barChartData.sort(sortCountDesc);\n return { values: barChartData };\n}\n\nconst getSTD = (data) => {\n const total = data.reduce(function (a, b) {\n return a + b;\n });\n let mean = total / data.length;\n mean = isFinite(mean) ? mean : 0;\n function var_numerator(value) {\n return (value - mean) * (value - mean);\n }\n let variance = data.map(var_numerator);\n variance = variance.reduce(function (a, b) {\n return a + b;\n });\n variance /= data.length;\n variance = isFinite(variance) ? variance : 1;\n const std = Math.sqrt(variance);\n return std;\n};\n\nfunction dictionary(list) {\n const map = {};\n for (let i = 0; i < list.length; ++i) {\n for (const key in list[i]) {\n if (key in map) {\n map[key].push(list[i][key]);\n } else {\n map[key] = [list[i][key]];\n }\n }\n }\n return map;\n}\n\nfunction getMaxMean(data) {\n let max = Number.NEGATIVE_INFINITY;\n data = data.values;\n for (let i = 0; i < data.length; i++) {\n if (data[i].count > max) {\n max = data[i].count;\n }\n }\n return max;\n}\n\nfunction sortByScore(a, b) {\n if (a.score === b.score) {\n return 0;\n }\n\n return a.score < b.score ? 1 : -1;\n}\n\nfunction getExplainingFeatures(data) {\n // data format [{'category': x, 'count': y}, ...]\n // data should be sorted descendingly\n const n = data.length;\n const features = [];\n for (let i = 0; i < n; i++) {\n if (data[i].count >= 1 / n) {\n features.push(data[i].category);\n } else {\n return features;\n }\n }\n return features;\n}\n\nfunction getProjectionColumns(legendAttributes) {\n if (legendAttributes === null) {\n return [];\n }\n const pcol = [];\n for (let i = 0; i <= legendAttributes.length; i++) {\n if (legendAttributes[i] !== undefined && legendAttributes[i].show) {\n pcol.push(legendAttributes[i].feature);\n }\n }\n return pcol;\n}\n\nfunction getNormalizedSTD(data, min, max) {\n if (min === max) {\n return 0;\n }\n data.forEach((x, i, self) => {\n self[i] = (+x - +min) / (+max - +min);\n });\n\n return getSTD(data);\n}\n\nfunction genRows(vectors, aggregation, legendAttributes, dataset) {\n if (dataset === undefined) {\n return [];\n }\n\n // if(!aggregation){ // TODO: if it shows the hover state, we don't need to generate all rows because we can't scroll anyway\n // return []\n // }\n\n const rows = [];\n const dictOfArrays = dictionary(vectors);\n const preselect = getProjectionColumns(legendAttributes);\n\n // loop through dict\n for (const key in dictOfArrays) {\n // filter for preselect features\n if (preselect.indexOf(key) > -1) {\n if (dataset.columns[key]?.metaInformation.noLineUp) {\n // dont do anything, if column should not be shown\n } else if (dataset.columns[key]?.featureType === FeatureType.Quantitative) {\n // quantitative feature\n const densityData = mapDensityData(dataset.vectors, vectors, key);\n // logLevel={vegaImport.Debug} | {vegaImport.Warn} | {vegaImport.Error} | {vegaImport.None} | {vegaImport.Info}\n rows.push([\n key,\n '',\n 1 - getNormalizedSTD(dictOfArrays[key], dataset.columns[key].range.min, dataset.columns[key].range.max),\n ,\n ]);\n } else if (dataset.columns[key]?.featureType === FeatureType.Categorical) {\n // categorical feature\n const barData = mapBarChartData(vectors, key);\n var barChart;\n if (Object.keys(barData.values).length != 1) {\n // logLevel={vegaImport.Debug} | {vegaImport.Warn} | {vegaImport.Error} | {vegaImport.None} | {vegaImport.Info}\n barChart = ;\n } else {\n barChart = null;\n }\n rows.push([key, barData.values[0].category, getMaxMean(barData), barChart]);\n } else if (dataset.columns[key]?.featureType === FeatureType.Date) {\n // date feature\n const histData = mapHistData(vectors, key);\n rows.push([\n key,\n '',\n 1 - getNormalizedSTD(dictOfArrays[key], dataset.columns[key].range.min, dataset.columns[key].range.max),\n ,\n ]);\n }\n }\n }\n\n // turn into array of dicts\n const ret = [];\n for (let i = 0; i < rows.length; i++) {\n ret.push(createData(rows[i][0], rows[i][1], rows[i][2], rows[i][3]));\n }\n\n // sort rows by score\n ret.sort(sortByScore);\n\n return ret;\n}\n\nfunction getTable(vectors, aggregation, legendAttributes, dataset) {\n const classes = useStyles();\n const rows = genRows(vectors, aggregation, legendAttributes, dataset);\n\n return (\n
    \n \n \n \n \n {rows.map((row) => (\n \n \n
    \n {row.feature}\n
    \n {row.category}\n
    \n
    \n {row.char}\n
    \n ))}\n
    \n
    \n
    \n \n );\n}\n\nconst mapState = (state: RootState) => {\n return {\n legendAttributes: state.genericFingerprintAttributes,\n dataset: state.dataset,\n };\n};\n\nconst mapDispatch = (dispatch) => ({});\n\nconst connector = connect(mapState, mapDispatch);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {\n aggregate: boolean;\n selection: IVector[];\n};\n\nexport var CoralLegend = connector(({ selection, aggregate, legendAttributes, dataset }: Props) => {\n return getTable(selection, aggregate, legendAttributes, dataset);\n});\n","import * as React from 'react';\nimport { createClassFromSpec, VisualizationSpec, VegaLite } from 'react-vega';\nimport { VegaLiteProps } from 'react-vega/lib/VegaLite';\n\nconst spec: VisualizationSpec = {\n width: 50,\n height: 50,\n mark: { type: 'bar', tooltip: true },\n transform: [{ filter: 'datum.feature != null' }],\n encoding: {\n x: {\n field: 'feature',\n type: 'temporal',\n bin: {\n maxbins: 10,\n },\n axis: null,\n },\n y: {\n aggregate: 'count',\n axis: null,\n },\n color: {\n value: '#007dad',\n },\n },\n data: { name: 'values' },\n};\n\nexport default function (props: Omit) {\n return ;\n}\n\n// , \"scale\": {\"domain\": [0, 1]}\n// rank != 1 and switching color scale range would be a workaround to make sure when there is only 1 datapoint it has the rank 1 colour\n","import * as React from 'react';\nimport { createClassFromSpec, VisualizationSpec, VegaLite } from 'react-vega';\nimport { VegaLiteProps } from 'react-vega/lib/VegaLite';\n\nconst spec: VisualizationSpec = {\n width: 50,\n height: 50,\n transform: [{ density: 'feature', groupby: ['selection'], bandwidth: 0.3, steps: 15 }],\n mark: { type: 'area', tooltip: true },\n encoding: {\n x: { field: 'value', title: 'feature', type: 'quantitative', axis: null },\n y: { field: 'density', type: 'quantitative', axis: null },\n color: { field: 'selection', type: 'nominal', legend: null, scale: { range: ['(170,170,170,0)', '#007dad'] } },\n // \"fillOpacity\": {\"field\": \"selection\", \"type\": \"nominal\", \"legend\": null, \"scale\": {\"range\": [\"0\", \"1.0\"]}},\n stroke: { field: 'selection', type: 'nominal', legend: null, scale: { range: ['#000000', '#007dad'] } },\n },\n data: { name: 'values' },\n};\n\nexport default function (props: Omit) {\n return ;\n}\n\n// , \"scale\": {\"domain\": [0, 1]}\n// rank != 1 and switching color scale range would be a workaround to make sure when there is only 1 datapoint it has the rank 1 colour\n","import * as React from 'react';\nimport { IVector } from '../../model/Vector';\nimport { DatasetType } from '../../model/DatasetType';\nimport { CoralLegend } from './CoralDetail/CoralDetail';\nimport { PSEPlugin } from '../../components/Store/PSEPlugin';\nimport { Dataset } from '../../model/Dataset';\n\nexport class CoralPlugin extends PSEPlugin {\n type = DatasetType.Cohort_Analysis;\n\n createFingerprint(dataset: Dataset, vectors: IVector[], scale: number, aggregate: boolean): JSX.Element {\n return ;\n }\n}\n","/* eslint-disable react-hooks/rules-of-hooks */\nimport * as React from 'react';\n\n/**\n * Go Legend, implemented using a canvas element and React effect hooks\n */\n\n// Piece size in pixels\nconst P = 13;\n\n// Width in pixels\nconst W = 20 * P;\n\n// Height in pixels\nconst H = 20 * P;\n\nexport function GoLegend({ selection, aggregate }) {\n if (aggregate) {\n return
    Not applicable
    ;\n }\n\n const canvasRef = React.useRef(null);\n\n React.useEffect(() => {\n // Redraw go field whenever selection changes\n const canvas = canvasRef.current;\n const ctx = canvas.getContext('2d');\n\n ctx.clearRect(0, 0, W, H);\n\n ctx.fillStyle = '#C19A6B';\n ctx.fillRect(0, 0, W, H);\n\n ctx.strokeStyle = '#000000';\n ctx.beginPath();\n for (let x = 0; x < 19; x++) {\n const cx = P + 0.5 + x * P;\n const cy = P + 0.5 + x * P;\n\n ctx.moveTo(cx, P + 0.5);\n ctx.lineTo(cx, P * 19 + 0.5);\n\n ctx.moveTo(P + 0.5, cy);\n ctx.lineTo(P * 19 + 0.5, cy);\n }\n ctx.stroke();\n\n // Draw go pieces\n if (selection.length === 1) {\n const vector = selection[0];\n\n for (let x = 0; x < 19; x++) {\n for (let y = 0; y < 19; y++) {\n const cx = P + 0.5 + x * P;\n const cy = P + 0.5 + y * P;\n\n const key = String.fromCharCode('a'.charCodeAt(0) + x) + String.fromCharCode('a'.charCodeAt(0) + y);\n\n if (vector[key] === 'b' || vector[key] === 'w') {\n if (vector[key] === 'b') {\n ctx.fillStyle = '#000000';\n }\n if (vector[key] === 'w') {\n ctx.fillStyle = '#ffffff';\n }\n ctx.beginPath();\n ctx.arc(cx, cy, P / 2, 0, Math.PI * 2);\n ctx.fill();\n }\n }\n }\n }\n }, [selection]);\n\n return ;\n}\n","import * as React from 'react';\nimport { IVector } from '../../model/Vector';\nimport { DatasetType } from '../../model/DatasetType';\nimport { PSEPlugin } from '../../components/Store/PSEPlugin';\nimport { GoLegend } from './GoLegend';\nimport { Dataset } from '../../model/Dataset';\n\nexport class GoPlugin extends PSEPlugin {\n type = DatasetType.Go;\n\n createFingerprint(dataset: Dataset, vectors: IVector[], scale = 1, aggregate: boolean): JSX.Element {\n return ;\n }\n}\n","import * as React from 'react';\nimport { IVector } from '../../../model/Vector';\nimport { arraysEqual } from '../../../components/WebGLView/UtilityFunctions';\n\ntype RubikChangesProps = {\n vectorsA: Array;\n vectorsB: Array;\n width?: number;\n height?: number;\n};\n\nfunction cubieToColour(str, opacity) {\n switch (str) {\n case 'O':\n return `rgb(255,137,33,${opacity})`;\n case 'Y':\n return `rgb(255,204,0,${opacity})`;\n case 'G':\n return `rgb(48,174,32,${opacity})`;\n case 'B':\n return `rgb(21,130,174,${opacity})`;\n case 'R':\n return `rgb(197,11,11,${opacity})`;\n case 'W':\n return `rgb(191,191,191,${opacity})`;\n default:\n return 'black';\n }\n}\n\nexport class RubikChanges extends React.Component {\n canvasRef = React.createRef();\n\n canvasContext: CanvasRenderingContext2D = null;\n\n constructor(props: RubikChangesProps) {\n super(props);\n }\n\n componentDidMount() {\n this.canvasContext = this.canvasRef.current.getContext('2d');\n\n this.renderToContext();\n }\n\n renderToContext() {\n const { vectorsA } = this.props;\n const { vectorsB } = this.props;\n const countA = getOccurences(vectorsA);\n const countB = getOccurences(vectorsB);\n\n // Get layout size, on retina display, canvas width is actually larger\n const cssWidth = this.props.width ? this.props.width : this.canvasRef.current.getBoundingClientRect().width;\n const cssHeight = this.props.height ? this.props.height : this.canvasRef.current.getBoundingClientRect().height;\n\n // Set values to multiples of 9 so pixels arent smudged\n let width = cssWidth * window.devicePixelRatio;\n let height = cssHeight * window.devicePixelRatio;\n width = Math.floor(width / 9) * 9;\n height = Math.floor(height / 12) * 12;\n\n const size = width / 9;\n\n this.canvasRef.current.setAttribute('width', width.toString());\n this.canvasRef.current.setAttribute('height', height.toString());\n\n const distance = 1;\n\n const offsetMap = {\n upXOffset: distance,\n upYOffset: distance,\n frontXOffset: distance,\n frontYOffset: 2 * distance,\n leftXOffset: 0,\n leftYOffset: distance,\n rightXOffset: 2 * distance,\n rightYOffset: distance,\n downXOffset: distance,\n downYOffset: 3 * distance,\n backXOffset: distance,\n backYOffset: 0 * distance,\n };\n const sides = ['front', 'up', 'left', 'right', 'down', 'back'];\n\n const aggregation = {};\n\n for (let side = 0; side < sides.length; side++) {\n for (let i1 = 0; i1 < 3; i1++) {\n for (let j = 0; j < 3; j++) {\n const key = sides[side] + i1 + j;\n let col = 'white' as string;\n let opacity = 1;\n const curKey = 0;\n\n if (vectorsB.length == 0) {\n col = '#F0F0F0';\n }\n\n const [opacityA, colA] = getProminent(countA, key) as [number, string];\n const [opacityB, colB] = getProminent(countB, key) as [number, string];\n\n if (colA != colB) {\n col = colB;\n opacity = opacityB;\n }\n\n this.canvasContext.fillStyle = '#F0F0F0';\n this.canvasContext.fillRect((offsetMap[`${sides[side]}XOffset`] * 3 + j) * size, (offsetMap[`${sides[side]}YOffset`] * 3 + i1) * size, size, size);\n\n const w = Math.floor(size * opacity);\n const h = Math.floor(size * opacity);\n const ox = Math.floor((size - w) / 2);\n const oy = Math.floor((size - h) / 2);\n\n this.canvasContext.fillStyle = col;\n this.canvasContext.fillRect(\n 1 + ox + (offsetMap[`${sides[side]}XOffset`] * 3 + j) * size,\n 1 + oy + (offsetMap[`${sides[side]}YOffset`] * 3 + i1) * size,\n w - 2,\n h - 2,\n );\n }\n }\n }\n }\n\n componentDidUpdate(prevProps) {\n if (!arraysEqual(prevProps.vectorsA, this.props.vectorsA) || !arraysEqual(prevProps.vectorsB, this.props.vectorsB)) {\n this.renderToContext();\n }\n }\n\n render() {\n return (\n \n );\n }\n}\n\nfunction getProminent(aggregation, key) {\n let col = 'white';\n let opacity = 1;\n let max = 0.0;\n let total = 0;\n let curKey = 0;\n for (const k in aggregation[key]) {\n const v = aggregation[key][k];\n total += v.count;\n\n if (v.count > max) {\n max = v.count;\n\n curKey = aggregation[key][k].key;\n }\n }\n\n opacity = max / total;\n col = cubieToColour(curKey, 1);\n\n return [opacity, col];\n}\n\nfunction getOccurences(vectors: Array) {\n const aggregation = {};\n const keys = [\n 'up00',\n 'up01',\n 'up02',\n 'up10',\n 'up11',\n 'up12',\n 'up20',\n 'up21',\n 'up22',\n 'front00',\n 'front01',\n 'front02',\n 'front10',\n 'front11',\n 'front12',\n 'front20',\n 'front21',\n 'front22',\n 'right00',\n 'right01',\n 'right02',\n 'right10',\n 'right11',\n 'right12',\n 'right20',\n 'right21',\n 'right22',\n 'left00',\n 'left01',\n 'left02',\n 'left10',\n 'left11',\n 'left12',\n 'left20',\n 'left21',\n 'left22',\n 'down00',\n 'down01',\n 'down02',\n 'down10',\n 'down11',\n 'down12',\n 'down20',\n 'down21',\n 'down22',\n 'back00',\n 'back01',\n 'back02',\n 'back10',\n 'back11',\n 'back12',\n 'back20',\n 'back21',\n 'back22',\n ];\n\n vectors.forEach((vector, index) => {\n keys.forEach((key, keyIndex) => {\n if (aggregation[key] == undefined) {\n aggregation[key] = [];\n }\n\n if (!aggregation[key].some((e) => e.key == vector[key])) {\n aggregation[key].push({ key: vector[key], count: 1 });\n } else {\n aggregation[key].filter((e) => e.key == vector[key])[0].count += 1;\n }\n });\n });\n\n return aggregation;\n}\n","import * as React from 'react';\nimport { arraysEqual } from '../../../components/WebGLView/UtilityFunctions';\n\ntype RubikFingerprintProps = {\n vectors: Array;\n width?: number;\n height?: number;\n};\n\nexport const requiredRubikColumns = [\n 'up00',\n 'up01',\n 'up02',\n 'up10',\n 'up11',\n 'up12',\n 'up20',\n 'up21',\n 'up22',\n 'front00',\n 'front01',\n 'front02',\n 'front10',\n 'front11',\n 'front12',\n 'front20',\n 'front21',\n 'front22',\n 'right00',\n 'right01',\n 'right02',\n 'right10',\n 'right11',\n 'right12',\n 'right20',\n 'right21',\n 'right22',\n 'left00',\n 'left01',\n 'left02',\n 'left10',\n 'left11',\n 'left12',\n 'left20',\n 'left21',\n 'left22',\n 'down00',\n 'down01',\n 'down02',\n 'down10',\n 'down11',\n 'down12',\n 'down20',\n 'down21',\n 'down22',\n 'back00',\n 'back01',\n 'back02',\n 'back10',\n 'back11',\n 'back12',\n 'back20',\n 'back21',\n 'back22',\n];\n\nfunction cubieToColour(str, opacity) {\n switch (str) {\n case 'O':\n return `rgb(255,137,33,${opacity})`;\n case 'Y':\n return `rgb(255,204,0,${opacity})`;\n case 'G':\n return `rgb(48,174,32,${opacity})`;\n case 'B':\n return `rgb(21,130,174,${opacity})`;\n case 'R':\n return `rgb(197,11,11,${opacity})`;\n case 'W':\n return `rgb(191,191,191,${opacity})`;\n default:\n return 'black';\n }\n}\n\nexport class RubikFingerprint extends React.Component {\n canvasRef = React.createRef();\n\n canvasContext: CanvasRenderingContext2D = null;\n\n constructor(props: RubikFingerprintProps) {\n super(props);\n }\n\n componentDidMount() {\n this.canvasContext = this.canvasRef.current.getContext('2d');\n\n if (this.props.vectors) {\n this.renderToContext();\n }\n }\n\n componentDidUpdate(prevProps) {\n if (!arraysEqual(prevProps.vectors, this.props.vectors) && this.props.vectors) {\n this.renderToContext();\n }\n }\n\n renderToContext() {\n const { vectors } = this.props;\n\n // Get layout size, on retina display, canvas width is actually larger\n const cssWidth = this.props.width ? this.props.width : this.canvasRef.current.getBoundingClientRect().width;\n const cssHeight = this.props.height ? this.props.height : this.canvasRef.current.getBoundingClientRect().height;\n\n // Set values to multiples of 9 so pixels arent smudged\n let width = cssWidth * window.devicePixelRatio;\n let height = cssHeight * window.devicePixelRatio;\n width = Math.floor(width / 9) * 9;\n height = Math.floor(height / 12) * 12;\n\n const size = width / 9;\n\n this.canvasRef.current.setAttribute('width', width.toString());\n this.canvasRef.current.setAttribute('height', height.toString());\n\n const distance = 1;\n\n const offsetMap = {\n upXOffset: distance,\n upYOffset: distance,\n frontXOffset: distance,\n frontYOffset: 2 * distance,\n leftXOffset: 0,\n leftYOffset: distance,\n rightXOffset: 2 * distance,\n rightYOffset: distance,\n downXOffset: distance,\n downYOffset: 3 * distance,\n backXOffset: distance,\n backYOffset: 0 * distance,\n };\n const sides = ['front', 'up', 'left', 'right', 'down', 'back'];\n\n const aggregation = {};\n const keys = [\n 'up00',\n 'up01',\n 'up02',\n 'up10',\n 'up11',\n 'up12',\n 'up20',\n 'up21',\n 'up22',\n 'front00',\n 'front01',\n 'front02',\n 'front10',\n 'front11',\n 'front12',\n 'front20',\n 'front21',\n 'front22',\n 'right00',\n 'right01',\n 'right02',\n 'right10',\n 'right11',\n 'right12',\n 'right20',\n 'right21',\n 'right22',\n 'left00',\n 'left01',\n 'left02',\n 'left10',\n 'left11',\n 'left12',\n 'left20',\n 'left21',\n 'left22',\n 'down00',\n 'down01',\n 'down02',\n 'down10',\n 'down11',\n 'down12',\n 'down20',\n 'down21',\n 'down22',\n 'back00',\n 'back01',\n 'back02',\n 'back10',\n 'back11',\n 'back12',\n 'back20',\n 'back21',\n 'back22',\n ];\n\n vectors.forEach((vector) => {\n keys.forEach((key) => {\n if (aggregation[key] === undefined) {\n aggregation[key] = [];\n }\n\n if (!aggregation[key].some((e) => e.key === vector[key])) {\n aggregation[key].push({ key: vector[key], count: 1 });\n } else {\n aggregation[key].filter((e) => e.key === vector[key])[0].count += 1;\n }\n });\n });\n\n for (let side = 0; side < sides.length; side++) {\n for (let i1 = 0; i1 < 3; i1++) {\n for (let j = 0; j < 3; j++) {\n const key = sides[side] + i1 + j;\n let col = 'white';\n let opacity = 1;\n let curKey = 0;\n\n if (vectors.length === 0) {\n col = '#F0F0F0';\n } else if (aggregation[key].length === 1) {\n col = cubieToColour(aggregation[key][0].key, 1);\n } else {\n let max = 0.0;\n let total = 0;\n for (const k in aggregation[key]) {\n const v = aggregation[key][k];\n total += v.count;\n\n if (v.count > max) {\n max = v.count;\n\n curKey = aggregation[key][k].key;\n }\n }\n\n opacity = max / total;\n col = cubieToColour(curKey, 1);\n }\n\n this.canvasContext.fillStyle = '#F0F0F0';\n this.canvasContext.fillRect((offsetMap[`${sides[side]}XOffset`] * 3 + j) * size, (offsetMap[`${sides[side]}YOffset`] * 3 + i1) * size, size, size);\n\n const w = Math.floor(size * opacity);\n const h = Math.floor(size * opacity);\n const ox = Math.floor((size - w) / 2);\n const oy = Math.floor((size - h) / 2);\n\n this.canvasContext.fillStyle = col;\n this.canvasContext.fillRect(\n 1 + ox + (offsetMap[`${sides[side]}XOffset`] * 3 + j) * size,\n 1 + oy + (offsetMap[`${sides[side]}YOffset`] * 3 + i1) * size,\n w - 2,\n h - 2,\n );\n }\n }\n }\n }\n\n render() {\n return (\n \n );\n }\n}\n","import * as React from 'react';\nimport { IVector } from '../../model/Vector';\nimport { DatasetType } from '../../model/DatasetType';\nimport { RubikFingerprint } from './RubikFingerprint/RubikFingerprint';\nimport { PSEPlugin } from '../../components/Store/PSEPlugin';\nimport { Dataset } from '../../model/Dataset';\n\nexport class RubikPlugin extends PSEPlugin {\n type = DatasetType.Rubik;\n\n hasFileLayout(header: string[]) {\n const requiredRubikColumns = [\n 'up00',\n 'up01',\n 'up02',\n 'up10',\n 'up11',\n 'up12',\n 'up20',\n 'up21',\n 'up22',\n 'front00',\n 'front01',\n 'front02',\n 'front10',\n 'front11',\n 'front12',\n 'front20',\n 'front21',\n 'front22',\n 'right00',\n 'right01',\n 'right02',\n 'right10',\n 'right11',\n 'right12',\n 'right20',\n 'right21',\n 'right22',\n 'left00',\n 'left01',\n 'left02',\n 'left10',\n 'left11',\n 'left12',\n 'left20',\n 'left21',\n 'left22',\n 'down00',\n 'down01',\n 'down02',\n 'down10',\n 'down11',\n 'down12',\n 'down20',\n 'down21',\n 'down22',\n 'back00',\n 'back01',\n 'back02',\n 'back10',\n 'back11',\n 'back12',\n 'back20',\n 'back21',\n 'back22',\n ];\n\n return this.hasLayout(header, requiredRubikColumns);\n }\n\n createFingerprint(dataset: Dataset, vectors: IVector[], scale = 1, aggregate: boolean): JSX.Element {\n return ;\n }\n}\n","import * as React from 'react';\nimport { createTheme, Divider, Grid, Table, TableBody, TableCell, TableRow, Typography } from '@mui/material';\nimport { makeStyles, ThemeProvider } from '@mui/styles';\nimport { getCountryCode } from '../../../components/Utility/CountryCodes';\n\nconst HEIGHT = 32;\nconst WIDTH = 44;\n\nconst useStyles = makeStyles({\n table: {\n width: WIDTH * 6,\n height: HEIGHT * 6,\n borderCollapse: 'collapse',\n tableLayout: 'fixed',\n },\n smalltable: {\n width: WIDTH * 6,\n borderCollapse: 'collapse',\n tableLayout: 'fixed',\n },\n textcell: {\n height: HEIGHT,\n margin: '0',\n padding: '0',\n border: '0px',\n },\n rowtextcell: {\n height: HEIGHT,\n margin: '0',\n padding: '0 15px 0 0',\n border: '0px',\n },\n cell: {\n width: WIDTH,\n height: HEIGHT,\n background: '#70AD47',\n margin: '0',\n padding: '0',\n borderWidth: '1px',\n borderStyle: 'dashed',\n borderColor: '#D9D9D9',\n },\n nocell: {\n width: WIDTH,\n height: HEIGHT,\n margin: '0',\n padding: '0',\n border: '1px solid black',\n borderWidth: '1px',\n borderStyle: 'dashed',\n borderColor: '#D9D9D9',\n },\n oldcell: {\n width: WIDTH,\n height: HEIGHT,\n margin: '0',\n padding: '0',\n background: '#D9D9D9',\n borderWidth: '1px',\n borderStyle: 'dashed',\n borderColor: '#D9D9D9',\n },\n});\n\nconst theme = createTheme({\n typography: {\n subtitle1: {\n fontSize: 11,\n },\n },\n});\n\nfunction Countries({ countries, countryCounts }) {\n if (countries == null || countries === undefined) return
    ;\n\n let countrySum = 0;\n Object.keys(countryCounts).forEach((key) => {\n if (countryCounts[key] > countrySum) {\n countrySum = countryCounts[key];\n }\n });\n\n return countries.map((countryName) => {\n return (\n \n );\n });\n}\n\nfunction SubColor({ selection, row }) {\n const classes = useStyles();\n\n if (selection.length === 1) {\n const selectionState = selection[0];\n const newVal = selectionState.new_color;\n const oldVal = selectionState.old_color;\n if (newVal === row) {\n return ;\n }\n if (newVal !== oldVal && oldVal === row) {\n return ;\n }\n return ;\n }\n const percent = selection.length > 0 ? selection.filter((value) => value.new_color === row).length / selection.length : 0;\n\n const W = WIDTH - 2;\n const H = HEIGHT - 2;\n const A = W * H;\n const A2 = W * H * percent;\n\n return (\n \n \n \n \n \n \n \n );\n}\n\nexport function YearAggComp({ selection }) {\n const lineStart = 20;\n const lineEnd = 232 - 20;\n if (selection == null || selection === undefined || selection.length === 0) {\n return (\n \n \n \n );\n }\n\n const years = [...new Set(selection.map((value) => value.new_year))] as any[];\n years.sort();\n const count = years.map((year) => selection.filter((s) => s.new_year === year).length);\n const max = Math.max(...count);\n const segmentWidth = 14;\n\n return (\n \n \n\n {years.map((year, i) => {\n const startX = (lineEnd - lineStart) / 2 - (segmentWidth * years.length) / 2;\n const newX = startX + i * segmentWidth;\n return (\n \n {year}\n \n );\n })}\n {years.map((year, i) => {\n const startX = (lineEnd - lineStart) / 2 - (segmentWidth * years.length) / 2;\n const newX = startX + i * segmentWidth;\n const h = (count[i] / max) * 30 + 2;\n return ;\n })}\n \n );\n}\n\nexport function YearComp({ oldYear, newYear }) {\n const lineStart = 60;\n const lineEnd = 232 - 60;\n const oldX = lineStart + (lineEnd - lineStart) * ((oldYear - 1800) / 215);\n const newX = lineStart + (lineEnd - lineStart) * ((newYear - 1800) / 215);\n\n return (\n \n \n\n \n\n \n\n \n {newYear}\n \n \n {oldYear}\n \n\n \n 1800\n \n \n 2015\n \n \n );\n}\n\nfunction parseCountries(countries) {\n if (countries == null) return [];\n\n try {\n const replaced = countries.replace(/'/g, '\"').replace(/;/g, ',');\n const parsed = JSON.parse(`{ \"result\": ${replaced} }`);\n if (parsed == null) {\n return [];\n }\n return parsed.result;\n } catch (e) {\n return ['error'];\n }\n}\n\ntype StoryLegendProps = {\n selection: any[];\n};\n\nexport function StoryLegend({ selection }: StoryLegendProps) {\n const classes = useStyles();\n\n if (selection == null) {\n return
    ;\n }\n\n const vertical = ['gdp', 'child_mortality', 'fertility', 'life_expect', 'population'];\n const horizontal = ['x', 'y', 'size'];\n\n const countryArray = selection.flatMap((s) => parseCountries(s.new_country));\n const countryCounts = {};\n countryArray.forEach((country) => {\n countryCounts[country] = countryCounts[country] ? countryCounts[country] + 1 : 1;\n });\n\n const allCountries = [...new Set(countryArray)];\n allCountries.sort((a, b) => {\n return countryCounts[b] - countryCounts[a];\n });\n\n return (\n \n \n \n \n \n \n \n X\n \n \n Y\n \n \n Size\n \n \n Color\n \n \n\n {selection.length === 1\n ? vertical.map((row) => {\n const selectionState = selection[0];\n return (\n \n \n {row}\n \n {horizontal.map((col) => {\n const newVal = selectionState[`new_${col}`];\n const oldVal = selectionState[`old_${col}`];\n if (newVal === row) {\n return ;\n }\n if (newVal !== oldVal && oldVal === row) {\n return ;\n }\n return ;\n })}\n \n );\n })\n : vertical.map((row) => {\n return (\n \n \n {row}\n \n\n {horizontal.map((col) => {\n // col is x, y, size\n // row is child_mortality... fertility\n\n const percent = selection.length > 0 ? selection.filter((value) => value[`new_${col}`] === row).length / selection.length : 0;\n\n const W = WIDTH - 2;\n const H = HEIGHT - 2;\n const A = W * H;\n const A2 = W * H * percent;\n\n return (\n \n \n \n \n \n \n \n );\n })}\n \n );\n })}\n \n
    \n\n \n\n \n \n \n \n Continent\n \n \n \n \n\n \n \n \n \n Religion\n \n \n \n \n\n \n \n \n
    \n\n {selection.length === 1 ? : }\n\n \n {selection.length === 1 ? (\n \n ) : (\n \n )}\n \n
    \n
    \n );\n}\n","import * as React from 'react';\nimport { connect, ConnectedProps } from 'react-redux';\nimport { Handler } from 'vega-tooltip';\nimport TrrackScatter from './TrrackScatter';\nimport { IVector } from '../../../model/Vector';\nimport type { RootState } from '../../../components/Store/Store';\n\nfunction getScatter(vectors) {\n // init empty \"data\" array\n const data = [];\n // iterate vectors v\n vectors.forEach((v) => {\n // parse v to array\n const parsed = JSON.parse(v.selectedCoordsNorm.replace(/'/g, '\"'));\n // concat parsed v to data\n data.push(...parsed);\n });\n\n return (\n
    \n \n \n
    \n
    \n );\n}\n\nconst mapState = (state: RootState) => {\n return {\n dataset: state.dataset,\n };\n};\n\nconst mapDispatch = () => ({});\n\nconst connector = connect(mapState, mapDispatch);\n\ntype PropsFromRedux = ConnectedProps;\n\ntype Props = PropsFromRedux & {\n aggregate: boolean;\n selection: IVector[];\n};\n\nexport const TrrackLegend = connector(({ selection }: Props) => {\n return getScatter(selection);\n});\n","import * as React from 'react';\nimport { createClassFromSpec, VisualizationSpec, VegaLite } from 'react-vega';\nimport { VegaLiteProps } from 'react-vega/lib/VegaLite';\n\nconst spec: VisualizationSpec = {\n width: 200,\n height: 200,\n mark: 'circle',\n encoding: {\n x: {\n field: 'x',\n type: 'quantitative',\n scale: { domain: [0, 1] },\n axis: {},\n },\n y: {\n field: 'y',\n type: 'quantitative',\n scale: {\n domain: [0, 1],\n },\n axis: {},\n },\n opacity: { value: 0.15 },\n },\n data: { name: 'values' },\n};\n\nexport default function (props: Omit) {\n return ;\n}\n","/* eslint-disable @typescript-eslint/ban-ts-comment */\n// @ts-ignore\nimport PseDataset from '../../textures/icons/pse-icon-dataset.svg';\n// @ts-ignore\nimport PseClusters from '../../textures/icons/pse-icon-clusters.svg';\n// @ts-ignore\nimport PseDetails from '../../textures/icons/pse-icon-details.svg';\n// @ts-ignore\nimport PseEncoding from '../../textures/icons/pse-icon-encoding.svg';\n// @ts-ignore\nimport PseProject from '../../textures/icons/pse-icon-project.svg';\n// @ts-ignore\nimport PseLineup from '../../textures/icons/pse-icon-lineup.svg';\n\n/**\n * Makes the inlined base64 icons accessible in apps that use PSE as a library.\n */\nexport const PSEIcons = {\n Dataset: PseDataset,\n Clusters: PseClusters,\n Details: PseDetails,\n Encoding: PseEncoding,\n Project: PseProject,\n PseLineup,\n};\n","// CONSTANTS\n\nfunction handle_errors(response) {\n if (!response.ok) {\n throw Error(response.statusText);\n }\n return response;\n}\nfunction handle_errors_json(data) {\n if (Object.keys(data).includes('error')) {\n alert(data.error);\n }\n return data;\n}\n\nexport async function calculate_hdbscan_clusters(X, min_cluster_size, min_cluster_samples, allow_single_cluster, baseUrl: string) {\n const formData = new FormData();\n formData.append('min_cluster_size', min_cluster_size);\n formData.append('min_cluster_samples', min_cluster_samples);\n formData.append('allow_single_cluster', allow_single_cluster);\n formData.append('X', X);\n return fetch(`${baseUrl}/segmentation`, {\n method: 'POST',\n body: formData,\n })\n .then(handle_errors)\n .then((response) => response.json())\n .then(handle_errors_json)\n .catch((error) => {\n alert('error when calculating clusters');\n console.log(error);\n });\n}\n","export * from './backend-connect';\nexport * from './promise-helpers';\nexport * from './PSEIcons';\n","/* eslint-disable @typescript-eslint/ban-ts-comment */\n// https://rajeshnaroth.medium.com/writing-a-react-hook-to-cancel-promises-when-a-component-unmounts-526efabf251f\nimport { useRef, useEffect } from 'react';\n\nexport function makeCancelable(promise) {\n let isCanceled = false;\n\n const wrappedPromise = new Promise((resolve, reject) => {\n promise\n .then((val) => (isCanceled ? reject(new Error(`Promise is canceled: ${isCanceled}`)) : resolve(val)))\n .catch((error) => (isCanceled ? reject(new Error(`Promise is canceled: ${isCanceled}`)) : reject(error)));\n });\n\n return {\n promise: wrappedPromise,\n cancel() {\n isCanceled = true;\n },\n };\n}\n\nexport function useCancellablePromise(cancelable = makeCancelable) {\n const emptyPromise = Promise.resolve(true);\n\n // test if the input argument is a cancelable promise generator\n if (cancelable(emptyPromise).cancel === undefined) {\n throw new Error('promise wrapper argument must provide a cancel() function');\n }\n\n const promises = useRef();\n const controllers = useRef();\n\n useEffect(() => {\n // @ts-ignore\n promises.current = promises.current || [];\n // @ts-ignore\n controllers.current = controllers.current || [];\n return function cancel() {\n // @ts-ignore\n controllers.current.forEach((p) => p.abort());\n // @ts-ignore\n controllers.current = [];\n // @ts-ignore\n promises.current.forEach((p) => p.cancel());\n // @ts-ignore\n promises.current = [];\n };\n }, []);\n\n function cancellablePromise(p: Promise, controller?: AbortController): Promise {\n const cPromise = cancelable(p);\n // @ts-ignore\n promises.current.push(cPromise);\n if (controller)\n // @ts-ignore\n controllers.current.push(controller);\n // @ts-ignore\n return cPromise.promise;\n }\n\n function cancelPromises() {\n // @ts-ignore\n controllers.current?.forEach((p) => p.abort());\n // @ts-ignore\n controllers.current = [];\n // @ts-ignore\n promises.current?.forEach((p) => p.cancel());\n // @ts-ignore\n promises.current = [];\n }\n\n return { cancellablePromise, cancelPromises };\n}\n","var clone = (function() {\n'use strict';\n\nfunction _instanceof(obj, type) {\n return type != null && obj instanceof type;\n}\n\nvar nativeMap;\ntry {\n nativeMap = Map;\n} catch(_) {\n // maybe a reference error because no `Map`. Give it a dummy value that no\n // value will ever be an instanceof.\n nativeMap = function() {};\n}\n\nvar nativeSet;\ntry {\n nativeSet = Set;\n} catch(_) {\n nativeSet = function() {};\n}\n\nvar nativePromise;\ntry {\n nativePromise = Promise;\n} catch(_) {\n nativePromise = function() {};\n}\n\n/**\n * Clones (copies) an Object using deep copying.\n *\n * This function supports circular references by default, but if you are certain\n * there are no circular references in your object, you can save some CPU time\n * by calling clone(obj, false).\n *\n * Caution: if `circular` is false and `parent` contains circular references,\n * your program may enter an infinite loop and crash.\n *\n * @param `parent` - the object to be cloned\n * @param `circular` - set to true if the object to be cloned may contain\n * circular references. (optional - true by default)\n * @param `depth` - set to a number if the object is only to be cloned to\n * a particular depth. (optional - defaults to Infinity)\n * @param `prototype` - sets the prototype to be used when cloning an object.\n * (optional - defaults to parent prototype).\n * @param `includeNonEnumerable` - set to true if the non-enumerable properties\n * should be cloned as well. Non-enumerable properties on the prototype\n * chain will be ignored. (optional - false by default)\n*/\nfunction clone(parent, circular, depth, prototype, includeNonEnumerable) {\n if (typeof circular === 'object') {\n depth = circular.depth;\n prototype = circular.prototype;\n includeNonEnumerable = circular.includeNonEnumerable;\n circular = circular.circular;\n }\n // maintain two arrays for circular references, where corresponding parents\n // and children have the same index\n var allParents = [];\n var allChildren = [];\n\n var useBuffer = typeof Buffer != 'undefined';\n\n if (typeof circular == 'undefined')\n circular = true;\n\n if (typeof depth == 'undefined')\n depth = Infinity;\n\n // recurse this function so we don't reset allParents and allChildren\n function _clone(parent, depth) {\n // cloning null always returns null\n if (parent === null)\n return null;\n\n if (depth === 0)\n return parent;\n\n var child;\n var proto;\n if (typeof parent != 'object') {\n return parent;\n }\n\n if (_instanceof(parent, nativeMap)) {\n child = new nativeMap();\n } else if (_instanceof(parent, nativeSet)) {\n child = new nativeSet();\n } else if (_instanceof(parent, nativePromise)) {\n child = new nativePromise(function (resolve, reject) {\n parent.then(function(value) {\n resolve(_clone(value, depth - 1));\n }, function(err) {\n reject(_clone(err, depth - 1));\n });\n });\n } else if (clone.__isArray(parent)) {\n child = [];\n } else if (clone.__isRegExp(parent)) {\n child = new RegExp(parent.source, __getRegExpFlags(parent));\n if (parent.lastIndex) child.lastIndex = parent.lastIndex;\n } else if (clone.__isDate(parent)) {\n child = new Date(parent.getTime());\n } else if (useBuffer && Buffer.isBuffer(parent)) {\n if (Buffer.allocUnsafe) {\n // Node.js >= 4.5.0\n child = Buffer.allocUnsafe(parent.length);\n } else {\n // Older Node.js versions\n child = new Buffer(parent.length);\n }\n parent.copy(child);\n return child;\n } else if (_instanceof(parent, Error)) {\n child = Object.create(parent);\n } else {\n if (typeof prototype == 'undefined') {\n proto = Object.getPrototypeOf(parent);\n child = Object.create(proto);\n }\n else {\n child = Object.create(prototype);\n proto = prototype;\n }\n }\n\n if (circular) {\n var index = allParents.indexOf(parent);\n\n if (index != -1) {\n return allChildren[index];\n }\n allParents.push(parent);\n allChildren.push(child);\n }\n\n if (_instanceof(parent, nativeMap)) {\n parent.forEach(function(value, key) {\n var keyChild = _clone(key, depth - 1);\n var valueChild = _clone(value, depth - 1);\n child.set(keyChild, valueChild);\n });\n }\n if (_instanceof(parent, nativeSet)) {\n parent.forEach(function(value) {\n var entryChild = _clone(value, depth - 1);\n child.add(entryChild);\n });\n }\n\n for (var i in parent) {\n var attrs;\n if (proto) {\n attrs = Object.getOwnPropertyDescriptor(proto, i);\n }\n\n if (attrs && attrs.set == null) {\n continue;\n }\n child[i] = _clone(parent[i], depth - 1);\n }\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(parent);\n for (var i = 0; i < symbols.length; i++) {\n // Don't need to worry about cloning a symbol because it is a primitive,\n // like a number or string.\n var symbol = symbols[i];\n var descriptor = Object.getOwnPropertyDescriptor(parent, symbol);\n if (descriptor && !descriptor.enumerable && !includeNonEnumerable) {\n continue;\n }\n child[symbol] = _clone(parent[symbol], depth - 1);\n if (!descriptor.enumerable) {\n Object.defineProperty(child, symbol, {\n enumerable: false\n });\n }\n }\n }\n\n if (includeNonEnumerable) {\n var allPropertyNames = Object.getOwnPropertyNames(parent);\n for (var i = 0; i < allPropertyNames.length; i++) {\n var propertyName = allPropertyNames[i];\n var descriptor = Object.getOwnPropertyDescriptor(parent, propertyName);\n if (descriptor && descriptor.enumerable) {\n continue;\n }\n child[propertyName] = _clone(parent[propertyName], depth - 1);\n Object.defineProperty(child, propertyName, {\n enumerable: false\n });\n }\n }\n\n return child;\n }\n\n return _clone(parent, depth);\n}\n\n/**\n * Simple flat clone using prototype, accepts only objects, usefull for property\n * override on FLAT configuration object (no nested props).\n *\n * USE WITH CAUTION! This may not behave as you wish if you do not know how this\n * works.\n */\nclone.clonePrototype = function clonePrototype(parent) {\n if (parent === null)\n return null;\n\n var c = function () {};\n c.prototype = parent;\n return new c();\n};\n\n// private utility functions\n\nfunction __objToStr(o) {\n return Object.prototype.toString.call(o);\n}\nclone.__objToStr = __objToStr;\n\nfunction __isDate(o) {\n return typeof o === 'object' && __objToStr(o) === '[object Date]';\n}\nclone.__isDate = __isDate;\n\nfunction __isArray(o) {\n return typeof o === 'object' && __objToStr(o) === '[object Array]';\n}\nclone.__isArray = __isArray;\n\nfunction __isRegExp(o) {\n return typeof o === 'object' && __objToStr(o) === '[object RegExp]';\n}\nclone.__isRegExp = __isRegExp;\n\nfunction __getRegExpFlags(re) {\n var flags = '';\n if (re.global) flags += 'g';\n if (re.ignoreCase) flags += 'i';\n if (re.multiline) flags += 'm';\n return flags;\n}\nclone.__getRegExpFlags = __getRegExpFlags;\n\nreturn clone;\n})();\n\nif (typeof module === 'object' && module.exports) {\n module.exports = clone;\n}\n","function r(e){var t,f,n=\"\";if(\"string\"==typeof e||\"number\"==typeof e)n+=e;else if(\"object\"==typeof e)if(Array.isArray(e))for(t=0;t b ? 1 : a >= b ? 0 : NaN;\n}\n","import ascending from \"./ascending.js\";\nimport bisector from \"./bisector.js\";\nimport number from \"./number.js\";\n\nconst ascendingBisect = bisector(ascending);\nexport const bisectRight = ascendingBisect.right;\nexport const bisectLeft = ascendingBisect.left;\nexport const bisectCenter = bisector(number).center;\nexport default bisectRight;\n","import ascending from \"./ascending.js\";\n\nexport default function(f) {\n let delta = f;\n let compare = f;\n\n if (f.length === 1) {\n delta = (d, x) => f(d) - x;\n compare = ascendingComparator(f);\n }\n\n function left(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (compare(a[mid], x) < 0) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n }\n\n function right(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n const mid = (lo + hi) >>> 1;\n if (compare(a[mid], x) > 0) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n }\n\n function center(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n const i = left(a, x, lo, hi - 1);\n return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i;\n }\n\n return {left, center, right};\n}\n\nfunction ascendingComparator(f) {\n return (d, x) => ascending(f(d), x);\n}\n","import variance from \"./variance.js\";\n\nexport default function deviation(values, valueof) {\n const v = variance(values, valueof);\n return v ? Math.sqrt(v) : v;\n}\n","// https://github.com/python/cpython/blob/a74eea238f5baba15797e2e8b570d153bc8690a7/Modules/mathmodule.c#L1423\nexport class Adder {\n constructor() {\n this._partials = new Float64Array(32);\n this._n = 0;\n }\n add(x) {\n const p = this._partials;\n let i = 0;\n for (let j = 0; j < this._n && j < 32; j++) {\n const y = p[j],\n hi = x + y,\n lo = Math.abs(x) < Math.abs(y) ? x - (hi - y) : y - (hi - x);\n if (lo) p[i++] = lo;\n x = hi;\n }\n p[i] = x;\n this._n = i + 1;\n return this;\n }\n valueOf() {\n const p = this._partials;\n let n = this._n, x, y, lo, hi = 0;\n if (n > 0) {\n hi = p[--n];\n while (n > 0) {\n x = hi;\n y = p[--n];\n hi = x + y;\n lo = y - (hi - x);\n if (lo) break;\n }\n if (n > 0 && ((lo < 0 && p[n - 1] < 0) || (lo > 0 && p[n - 1] > 0))) {\n y = lo * 2;\n x = hi + y;\n if (y == x - hi) hi = x;\n }\n }\n return hi;\n }\n}\n\nexport function fsum(values, valueof) {\n const adder = new Adder();\n if (valueof === undefined) {\n for (let value of values) {\n if (value = +value) {\n adder.add(value);\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if (value = +valueof(value, ++index, values)) {\n adder.add(value);\n }\n }\n }\n return +adder;\n}\n\nexport function fcumsum(values, valueof) {\n const adder = new Adder();\n let index = -1;\n return Float64Array.from(values, valueof === undefined\n ? v => adder.add(+v || 0)\n : v => adder.add(+valueof(v, ++index, values) || 0)\n );\n}\n","export default function max(values, valueof) {\n let max;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null\n && (max < value || (max === undefined && value >= value))) {\n max = value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null\n && (max < value || (max === undefined && value >= value))) {\n max = value;\n }\n }\n }\n return max;\n}\n","export default function mean(values, valueof) {\n let count = 0;\n let sum = 0;\n if (valueof === undefined) {\n for (let value of values) {\n if (value != null && (value = +value) >= value) {\n ++count, sum += value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {\n ++count, sum += value;\n }\n }\n }\n if (count) return sum / count;\n}\n","import quantile from \"./quantile.js\";\n\nexport default function(values, valueof) {\n return quantile(values, 0.5, valueof);\n}\n","function* flatten(arrays) {\n for (const array of arrays) {\n yield* array;\n }\n}\n\nexport default function merge(arrays) {\n return Array.from(flatten(arrays));\n}\n","export default function min(values, valueof) {\n let min;\n if (valueof === undefined) {\n for (const value of values) {\n if (value != null\n && (min > value || (min === undefined && value >= value))) {\n min = value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null\n && (min > value || (min === undefined && value >= value))) {\n min = value;\n }\n }\n }\n return min;\n}\n","export default function(x) {\n return x === null ? NaN : +x;\n}\n\nexport function* numbers(values, valueof) {\n if (valueof === undefined) {\n for (let value of values) {\n if (value != null && (value = +value) >= value) {\n yield value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {\n yield value;\n }\n }\n }\n}\n","export default function(source, keys) {\n return Array.from(keys, key => source[key]);\n}\n","import max from \"./max.js\";\nimport min from \"./min.js\";\nimport quickselect from \"./quickselect.js\";\nimport number, {numbers} from \"./number.js\";\n\nexport default function quantile(values, p, valueof) {\n values = Float64Array.from(numbers(values, valueof));\n if (!(n = values.length)) return;\n if ((p = +p) <= 0 || n < 2) return min(values);\n if (p >= 1) return max(values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = max(quickselect(values, i0).subarray(0, i0 + 1)),\n value1 = min(values.subarray(i0 + 1));\n return value0 + (value1 - value0) * (i - i0);\n}\n\nexport function quantileSorted(values, p, valueof = number) {\n if (!(n = values.length)) return;\n if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);\n if (p >= 1) return +valueof(values[n - 1], n - 1, values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = +valueof(values[i0], i0, values),\n value1 = +valueof(values[i0 + 1], i0 + 1, values);\n return value0 + (value1 - value0) * (i - i0);\n}\n","import ascending from \"./ascending.js\";\n\n// Based on https://github.com/mourner/quickselect\n// ISC license, Copyright 2018 Vladimir Agafonkin.\nexport default function quickselect(array, k, left = 0, right = array.length - 1, compare = ascending) {\n while (right > left) {\n if (right - left > 600) {\n const n = right - left + 1;\n const m = k - left + 1;\n const z = Math.log(n);\n const s = 0.5 * Math.exp(2 * z / 3);\n const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n quickselect(array, k, newLeft, newRight, compare);\n }\n\n const t = array[k];\n let i = left;\n let j = right;\n\n swap(array, left, k);\n if (compare(array[right], t) > 0) swap(array, left, right);\n\n while (i < j) {\n swap(array, i, j), ++i, --j;\n while (compare(array[i], t) < 0) ++i;\n while (compare(array[j], t) > 0) --j;\n }\n\n if (compare(array[left], t) === 0) swap(array, left, j);\n else ++j, swap(array, j, right);\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n return array;\n}\n\nfunction swap(array, i, j) {\n const t = array[i];\n array[i] = array[j];\n array[j] = t;\n}\n","export default function(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n","export default function sum(values, valueof) {\n let sum = 0;\n if (valueof === undefined) {\n for (let value of values) {\n if (value = +value) {\n sum += value;\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if (value = +valueof(value, ++index, values)) {\n sum += value;\n }\n }\n }\n return sum;\n}\n","var e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nexport default function(start, stop, count) {\n var reverse,\n i = -1,\n n,\n ticks,\n step;\n\n stop = +stop, start = +start, count = +count;\n if (start === stop && count > 0) return [start];\n if (reverse = stop < start) n = start, start = stop, stop = n;\n if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];\n\n if (step > 0) {\n let r0 = Math.round(start / step), r1 = Math.round(stop / step);\n if (r0 * step < start) ++r0;\n if (r1 * step > stop) --r1;\n ticks = new Array(n = r1 - r0 + 1);\n while (++i < n) ticks[i] = (r0 + i) * step;\n } else {\n step = -step;\n let r0 = Math.round(start * step), r1 = Math.round(stop * step);\n if (r0 / step < start) ++r0;\n if (r1 / step > stop) --r1;\n ticks = new Array(n = r1 - r0 + 1);\n while (++i < n) ticks[i] = (r0 + i) / step;\n }\n\n if (reverse) ticks.reverse();\n\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n var step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log(step) / Math.LN10),\n error = step / Math.pow(10, power);\n return power >= 0\n ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)\n : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);\n}\n\nexport function tickStep(start, stop, count) {\n var step0 = Math.abs(stop - start) / Math.max(0, count),\n step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),\n error = step0 / step1;\n if (error >= e10) step1 *= 10;\n else if (error >= e5) step1 *= 5;\n else if (error >= e2) step1 *= 2;\n return stop < start ? -step1 : step1;\n}\n","export default function variance(values, valueof) {\n let count = 0;\n let delta;\n let mean = 0;\n let sum = 0;\n if (valueof === undefined) {\n for (let value of values) {\n if (value != null && (value = +value) >= value) {\n delta = value - mean;\n mean += delta / ++count;\n sum += delta * (value - mean);\n }\n }\n } else {\n let index = -1;\n for (let value of values) {\n if ((value = valueof(value, ++index, values)) != null && (value = +value) >= value) {\n delta = value - mean;\n mean += delta / ++count;\n sum += delta * (value - mean);\n }\n }\n }\n if (count > 1) return sum / (count - 1);\n}\n","export var slice = Array.prototype.slice;\n","import {slice} from \"./array\";\nimport identity from \"./identity\";\n\nvar top = 1,\n right = 2,\n bottom = 3,\n left = 4,\n epsilon = 1e-6;\n\nfunction translateX(x) {\n return \"translate(\" + (x + 0.5) + \",0)\";\n}\n\nfunction translateY(y) {\n return \"translate(0,\" + (y + 0.5) + \")\";\n}\n\nfunction number(scale) {\n return function(d) {\n return +scale(d);\n };\n}\n\nfunction center(scale) {\n var offset = Math.max(0, scale.bandwidth() - 1) / 2; // Adjust for 0.5px offset.\n if (scale.round()) offset = Math.round(offset);\n return function(d) {\n return +scale(d) + offset;\n };\n}\n\nfunction entering() {\n return !this.__axis;\n}\n\nfunction axis(orient, scale) {\n var tickArguments = [],\n tickValues = null,\n tickFormat = null,\n tickSizeInner = 6,\n tickSizeOuter = 6,\n tickPadding = 3,\n k = orient === top || orient === left ? -1 : 1,\n x = orient === left || orient === right ? \"x\" : \"y\",\n transform = orient === top || orient === bottom ? translateX : translateY;\n\n function axis(context) {\n var values = tickValues == null ? (scale.ticks ? scale.ticks.apply(scale, tickArguments) : scale.domain()) : tickValues,\n format = tickFormat == null ? (scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments) : identity) : tickFormat,\n spacing = Math.max(tickSizeInner, 0) + tickPadding,\n range = scale.range(),\n range0 = +range[0] + 0.5,\n range1 = +range[range.length - 1] + 0.5,\n position = (scale.bandwidth ? center : number)(scale.copy()),\n selection = context.selection ? context.selection() : context,\n path = selection.selectAll(\".domain\").data([null]),\n tick = selection.selectAll(\".tick\").data(values, scale).order(),\n tickExit = tick.exit(),\n tickEnter = tick.enter().append(\"g\").attr(\"class\", \"tick\"),\n line = tick.select(\"line\"),\n text = tick.select(\"text\");\n\n path = path.merge(path.enter().insert(\"path\", \".tick\")\n .attr(\"class\", \"domain\")\n .attr(\"stroke\", \"currentColor\"));\n\n tick = tick.merge(tickEnter);\n\n line = line.merge(tickEnter.append(\"line\")\n .attr(\"stroke\", \"currentColor\")\n .attr(x + \"2\", k * tickSizeInner));\n\n text = text.merge(tickEnter.append(\"text\")\n .attr(\"fill\", \"currentColor\")\n .attr(x, k * spacing)\n .attr(\"dy\", orient === top ? \"0em\" : orient === bottom ? \"0.71em\" : \"0.32em\"));\n\n if (context !== selection) {\n path = path.transition(context);\n tick = tick.transition(context);\n line = line.transition(context);\n text = text.transition(context);\n\n tickExit = tickExit.transition(context)\n .attr(\"opacity\", epsilon)\n .attr(\"transform\", function(d) { return isFinite(d = position(d)) ? transform(d) : this.getAttribute(\"transform\"); });\n\n tickEnter\n .attr(\"opacity\", epsilon)\n .attr(\"transform\", function(d) { var p = this.parentNode.__axis; return transform(p && isFinite(p = p(d)) ? p : position(d)); });\n }\n\n tickExit.remove();\n\n path\n .attr(\"d\", orient === left || orient == right\n ? (tickSizeOuter ? \"M\" + k * tickSizeOuter + \",\" + range0 + \"H0.5V\" + range1 + \"H\" + k * tickSizeOuter : \"M0.5,\" + range0 + \"V\" + range1)\n : (tickSizeOuter ? \"M\" + range0 + \",\" + k * tickSizeOuter + \"V0.5H\" + range1 + \"V\" + k * tickSizeOuter : \"M\" + range0 + \",0.5H\" + range1));\n\n tick\n .attr(\"opacity\", 1)\n .attr(\"transform\", function(d) { return transform(position(d)); });\n\n line\n .attr(x + \"2\", k * tickSizeInner);\n\n text\n .attr(x, k * spacing)\n .text(format);\n\n selection.filter(entering)\n .attr(\"fill\", \"none\")\n .attr(\"font-size\", 10)\n .attr(\"font-family\", \"sans-serif\")\n .attr(\"text-anchor\", orient === right ? \"start\" : orient === left ? \"end\" : \"middle\");\n\n selection\n .each(function() { this.__axis = position; });\n }\n\n axis.scale = function(_) {\n return arguments.length ? (scale = _, axis) : scale;\n };\n\n axis.ticks = function() {\n return tickArguments = slice.call(arguments), axis;\n };\n\n axis.tickArguments = function(_) {\n return arguments.length ? (tickArguments = _ == null ? [] : slice.call(_), axis) : tickArguments.slice();\n };\n\n axis.tickValues = function(_) {\n return arguments.length ? (tickValues = _ == null ? null : slice.call(_), axis) : tickValues && tickValues.slice();\n };\n\n axis.tickFormat = function(_) {\n return arguments.length ? (tickFormat = _, axis) : tickFormat;\n };\n\n axis.tickSize = function(_) {\n return arguments.length ? (tickSizeInner = tickSizeOuter = +_, axis) : tickSizeInner;\n };\n\n axis.tickSizeInner = function(_) {\n return arguments.length ? (tickSizeInner = +_, axis) : tickSizeInner;\n };\n\n axis.tickSizeOuter = function(_) {\n return arguments.length ? (tickSizeOuter = +_, axis) : tickSizeOuter;\n };\n\n axis.tickPadding = function(_) {\n return arguments.length ? (tickPadding = +_, axis) : tickPadding;\n };\n\n return axis;\n}\n\nexport function axisTop(scale) {\n return axis(top, scale);\n}\n\nexport function axisRight(scale) {\n return axis(right, scale);\n}\n\nexport function axisBottom(scale) {\n return axis(bottom, scale);\n}\n\nexport function axisLeft(scale) {\n return axis(left, scale);\n}\n","export default function(x) {\n return x;\n}\n","export {\n axisTop,\n axisRight,\n axisBottom,\n axisLeft\n} from \"./axis\";\n","import {dispatch} from \"d3-dispatch\";\nimport {dragDisable, dragEnable} from \"d3-drag\";\nimport {interpolate} from \"d3-interpolate\";\nimport {customEvent, event, touch, mouse, select} from \"d3-selection\";\nimport {interrupt} from \"d3-transition\";\nimport constant from \"./constant.js\";\nimport BrushEvent from \"./event.js\";\nimport noevent, {nopropagation} from \"./noevent.js\";\n\nvar MODE_DRAG = {name: \"drag\"},\n MODE_SPACE = {name: \"space\"},\n MODE_HANDLE = {name: \"handle\"},\n MODE_CENTER = {name: \"center\"};\n\nfunction number1(e) {\n return [+e[0], +e[1]];\n}\n\nfunction number2(e) {\n return [number1(e[0]), number1(e[1])];\n}\n\nfunction toucher(identifier) {\n return function(target) {\n return touch(target, event.touches, identifier);\n };\n}\n\nvar X = {\n name: \"x\",\n handles: [\"w\", \"e\"].map(type),\n input: function(x, e) { return x == null ? null : [[+x[0], e[0][1]], [+x[1], e[1][1]]]; },\n output: function(xy) { return xy && [xy[0][0], xy[1][0]]; }\n};\n\nvar Y = {\n name: \"y\",\n handles: [\"n\", \"s\"].map(type),\n input: function(y, e) { return y == null ? null : [[e[0][0], +y[0]], [e[1][0], +y[1]]]; },\n output: function(xy) { return xy && [xy[0][1], xy[1][1]]; }\n};\n\nvar XY = {\n name: \"xy\",\n handles: [\"n\", \"w\", \"e\", \"s\", \"nw\", \"ne\", \"sw\", \"se\"].map(type),\n input: function(xy) { return xy == null ? null : number2(xy); },\n output: function(xy) { return xy; }\n};\n\nvar cursors = {\n overlay: \"crosshair\",\n selection: \"move\",\n n: \"ns-resize\",\n e: \"ew-resize\",\n s: \"ns-resize\",\n w: \"ew-resize\",\n nw: \"nwse-resize\",\n ne: \"nesw-resize\",\n se: \"nwse-resize\",\n sw: \"nesw-resize\"\n};\n\nvar flipX = {\n e: \"w\",\n w: \"e\",\n nw: \"ne\",\n ne: \"nw\",\n se: \"sw\",\n sw: \"se\"\n};\n\nvar flipY = {\n n: \"s\",\n s: \"n\",\n nw: \"sw\",\n ne: \"se\",\n se: \"ne\",\n sw: \"nw\"\n};\n\nvar signsX = {\n overlay: +1,\n selection: +1,\n n: null,\n e: +1,\n s: null,\n w: -1,\n nw: -1,\n ne: +1,\n se: +1,\n sw: -1\n};\n\nvar signsY = {\n overlay: +1,\n selection: +1,\n n: -1,\n e: null,\n s: +1,\n w: null,\n nw: -1,\n ne: -1,\n se: +1,\n sw: +1\n};\n\nfunction type(t) {\n return {type: t};\n}\n\n// Ignore right-click, since that should open the context menu.\nfunction defaultFilter() {\n return !event.ctrlKey && !event.button;\n}\n\nfunction defaultExtent() {\n var svg = this.ownerSVGElement || this;\n if (svg.hasAttribute(\"viewBox\")) {\n svg = svg.viewBox.baseVal;\n return [[svg.x, svg.y], [svg.x + svg.width, svg.y + svg.height]];\n }\n return [[0, 0], [svg.width.baseVal.value, svg.height.baseVal.value]];\n}\n\nfunction defaultTouchable() {\n return navigator.maxTouchPoints || (\"ontouchstart\" in this);\n}\n\n// Like d3.local, but with the name “__brush” rather than auto-generated.\nfunction local(node) {\n while (!node.__brush) if (!(node = node.parentNode)) return;\n return node.__brush;\n}\n\nfunction empty(extent) {\n return extent[0][0] === extent[1][0]\n || extent[0][1] === extent[1][1];\n}\n\nexport function brushSelection(node) {\n var state = node.__brush;\n return state ? state.dim.output(state.selection) : null;\n}\n\nexport function brushX() {\n return brush(X);\n}\n\nexport function brushY() {\n return brush(Y);\n}\n\nexport default function() {\n return brush(XY);\n}\n\nfunction brush(dim) {\n var extent = defaultExtent,\n filter = defaultFilter,\n touchable = defaultTouchable,\n keys = true,\n listeners = dispatch(\"start\", \"brush\", \"end\"),\n handleSize = 6,\n touchending;\n\n function brush(group) {\n var overlay = group\n .property(\"__brush\", initialize)\n .selectAll(\".overlay\")\n .data([type(\"overlay\")]);\n\n overlay.enter().append(\"rect\")\n .attr(\"class\", \"overlay\")\n .attr(\"pointer-events\", \"all\")\n .attr(\"cursor\", cursors.overlay)\n .merge(overlay)\n .each(function() {\n var extent = local(this).extent;\n select(this)\n .attr(\"x\", extent[0][0])\n .attr(\"y\", extent[0][1])\n .attr(\"width\", extent[1][0] - extent[0][0])\n .attr(\"height\", extent[1][1] - extent[0][1]);\n });\n\n group.selectAll(\".selection\")\n .data([type(\"selection\")])\n .enter().append(\"rect\")\n .attr(\"class\", \"selection\")\n .attr(\"cursor\", cursors.selection)\n .attr(\"fill\", \"#777\")\n .attr(\"fill-opacity\", 0.3)\n .attr(\"stroke\", \"#fff\")\n .attr(\"shape-rendering\", \"crispEdges\");\n\n var handle = group.selectAll(\".handle\")\n .data(dim.handles, function(d) { return d.type; });\n\n handle.exit().remove();\n\n handle.enter().append(\"rect\")\n .attr(\"class\", function(d) { return \"handle handle--\" + d.type; })\n .attr(\"cursor\", function(d) { return cursors[d.type]; });\n\n group\n .each(redraw)\n .attr(\"fill\", \"none\")\n .attr(\"pointer-events\", \"all\")\n .on(\"mousedown.brush\", started)\n .filter(touchable)\n .on(\"touchstart.brush\", started)\n .on(\"touchmove.brush\", touchmoved)\n .on(\"touchend.brush touchcancel.brush\", touchended)\n .style(\"touch-action\", \"none\")\n .style(\"-webkit-tap-highlight-color\", \"rgba(0,0,0,0)\");\n }\n\n brush.move = function(group, selection) {\n if (group.selection) {\n group\n .on(\"start.brush\", function() { emitter(this, arguments).beforestart().start(); })\n .on(\"interrupt.brush end.brush\", function() { emitter(this, arguments).end(); })\n .tween(\"brush\", function() {\n var that = this,\n state = that.__brush,\n emit = emitter(that, arguments),\n selection0 = state.selection,\n selection1 = dim.input(typeof selection === \"function\" ? selection.apply(this, arguments) : selection, state.extent),\n i = interpolate(selection0, selection1);\n\n function tween(t) {\n state.selection = t === 1 && selection1 === null ? null : i(t);\n redraw.call(that);\n emit.brush();\n }\n\n return selection0 !== null && selection1 !== null ? tween : tween(1);\n });\n } else {\n group\n .each(function() {\n var that = this,\n args = arguments,\n state = that.__brush,\n selection1 = dim.input(typeof selection === \"function\" ? selection.apply(that, args) : selection, state.extent),\n emit = emitter(that, args).beforestart();\n\n interrupt(that);\n state.selection = selection1 === null ? null : selection1;\n redraw.call(that);\n emit.start().brush().end();\n });\n }\n };\n\n brush.clear = function(group) {\n brush.move(group, null);\n };\n\n function redraw() {\n var group = select(this),\n selection = local(this).selection;\n\n if (selection) {\n group.selectAll(\".selection\")\n .style(\"display\", null)\n .attr(\"x\", selection[0][0])\n .attr(\"y\", selection[0][1])\n .attr(\"width\", selection[1][0] - selection[0][0])\n .attr(\"height\", selection[1][1] - selection[0][1]);\n\n group.selectAll(\".handle\")\n .style(\"display\", null)\n .attr(\"x\", function(d) { return d.type[d.type.length - 1] === \"e\" ? selection[1][0] - handleSize / 2 : selection[0][0] - handleSize / 2; })\n .attr(\"y\", function(d) { return d.type[0] === \"s\" ? selection[1][1] - handleSize / 2 : selection[0][1] - handleSize / 2; })\n .attr(\"width\", function(d) { return d.type === \"n\" || d.type === \"s\" ? selection[1][0] - selection[0][0] + handleSize : handleSize; })\n .attr(\"height\", function(d) { return d.type === \"e\" || d.type === \"w\" ? selection[1][1] - selection[0][1] + handleSize : handleSize; });\n }\n\n else {\n group.selectAll(\".selection,.handle\")\n .style(\"display\", \"none\")\n .attr(\"x\", null)\n .attr(\"y\", null)\n .attr(\"width\", null)\n .attr(\"height\", null);\n }\n }\n\n function emitter(that, args, clean) {\n var emit = that.__brush.emitter;\n return emit && (!clean || !emit.clean) ? emit : new Emitter(that, args, clean);\n }\n\n function Emitter(that, args, clean) {\n this.that = that;\n this.args = args;\n this.state = that.__brush;\n this.active = 0;\n this.clean = clean;\n }\n\n Emitter.prototype = {\n beforestart: function() {\n if (++this.active === 1) this.state.emitter = this, this.starting = true;\n return this;\n },\n start: function() {\n if (this.starting) this.starting = false, this.emit(\"start\");\n else this.emit(\"brush\");\n return this;\n },\n brush: function() {\n this.emit(\"brush\");\n return this;\n },\n end: function() {\n if (--this.active === 0) delete this.state.emitter, this.emit(\"end\");\n return this;\n },\n emit: function(type) {\n customEvent(new BrushEvent(brush, type, dim.output(this.state.selection)), listeners.apply, listeners, [type, this.that, this.args]);\n }\n };\n\n function started() {\n if (touchending && !event.touches) return;\n if (!filter.apply(this, arguments)) return;\n\n var that = this,\n type = event.target.__data__.type,\n mode = (keys && event.metaKey ? type = \"overlay\" : type) === \"selection\" ? MODE_DRAG : (keys && event.altKey ? MODE_CENTER : MODE_HANDLE),\n signX = dim === Y ? null : signsX[type],\n signY = dim === X ? null : signsY[type],\n state = local(that),\n extent = state.extent,\n selection = state.selection,\n W = extent[0][0], w0, w1,\n N = extent[0][1], n0, n1,\n E = extent[1][0], e0, e1,\n S = extent[1][1], s0, s1,\n dx = 0,\n dy = 0,\n moving,\n shifting = signX && signY && keys && event.shiftKey,\n lockX,\n lockY,\n pointer = event.touches ? toucher(event.changedTouches[0].identifier) : mouse,\n point0 = pointer(that),\n point = point0,\n emit = emitter(that, arguments, true).beforestart();\n\n if (type === \"overlay\") {\n if (selection) moving = true;\n state.selection = selection = [\n [w0 = dim === Y ? W : point0[0], n0 = dim === X ? N : point0[1]],\n [e0 = dim === Y ? E : w0, s0 = dim === X ? S : n0]\n ];\n } else {\n w0 = selection[0][0];\n n0 = selection[0][1];\n e0 = selection[1][0];\n s0 = selection[1][1];\n }\n\n w1 = w0;\n n1 = n0;\n e1 = e0;\n s1 = s0;\n\n var group = select(that)\n .attr(\"pointer-events\", \"none\");\n\n var overlay = group.selectAll(\".overlay\")\n .attr(\"cursor\", cursors[type]);\n\n if (event.touches) {\n emit.moved = moved;\n emit.ended = ended;\n } else {\n var view = select(event.view)\n .on(\"mousemove.brush\", moved, true)\n .on(\"mouseup.brush\", ended, true);\n if (keys) view\n .on(\"keydown.brush\", keydowned, true)\n .on(\"keyup.brush\", keyupped, true)\n\n dragDisable(event.view);\n }\n\n nopropagation();\n interrupt(that);\n redraw.call(that);\n emit.start();\n\n function moved() {\n var point1 = pointer(that);\n if (shifting && !lockX && !lockY) {\n if (Math.abs(point1[0] - point[0]) > Math.abs(point1[1] - point[1])) lockY = true;\n else lockX = true;\n }\n point = point1;\n moving = true;\n noevent();\n move();\n }\n\n function move() {\n var t;\n\n dx = point[0] - point0[0];\n dy = point[1] - point0[1];\n\n switch (mode) {\n case MODE_SPACE:\n case MODE_DRAG: {\n if (signX) dx = Math.max(W - w0, Math.min(E - e0, dx)), w1 = w0 + dx, e1 = e0 + dx;\n if (signY) dy = Math.max(N - n0, Math.min(S - s0, dy)), n1 = n0 + dy, s1 = s0 + dy;\n break;\n }\n case MODE_HANDLE: {\n if (signX < 0) dx = Math.max(W - w0, Math.min(E - w0, dx)), w1 = w0 + dx, e1 = e0;\n else if (signX > 0) dx = Math.max(W - e0, Math.min(E - e0, dx)), w1 = w0, e1 = e0 + dx;\n if (signY < 0) dy = Math.max(N - n0, Math.min(S - n0, dy)), n1 = n0 + dy, s1 = s0;\n else if (signY > 0) dy = Math.max(N - s0, Math.min(S - s0, dy)), n1 = n0, s1 = s0 + dy;\n break;\n }\n case MODE_CENTER: {\n if (signX) w1 = Math.max(W, Math.min(E, w0 - dx * signX)), e1 = Math.max(W, Math.min(E, e0 + dx * signX));\n if (signY) n1 = Math.max(N, Math.min(S, n0 - dy * signY)), s1 = Math.max(N, Math.min(S, s0 + dy * signY));\n break;\n }\n }\n\n if (e1 < w1) {\n signX *= -1;\n t = w0, w0 = e0, e0 = t;\n t = w1, w1 = e1, e1 = t;\n if (type in flipX) overlay.attr(\"cursor\", cursors[type = flipX[type]]);\n }\n\n if (s1 < n1) {\n signY *= -1;\n t = n0, n0 = s0, s0 = t;\n t = n1, n1 = s1, s1 = t;\n if (type in flipY) overlay.attr(\"cursor\", cursors[type = flipY[type]]);\n }\n\n if (state.selection) selection = state.selection; // May be set by brush.move!\n if (lockX) w1 = selection[0][0], e1 = selection[1][0];\n if (lockY) n1 = selection[0][1], s1 = selection[1][1];\n\n if (selection[0][0] !== w1\n || selection[0][1] !== n1\n || selection[1][0] !== e1\n || selection[1][1] !== s1) {\n state.selection = [[w1, n1], [e1, s1]];\n redraw.call(that);\n emit.brush();\n }\n }\n\n function ended() {\n nopropagation();\n if (event.touches) {\n if (event.touches.length) return;\n if (touchending) clearTimeout(touchending);\n touchending = setTimeout(function() { touchending = null; }, 500); // Ghost clicks are delayed!\n } else {\n dragEnable(event.view, moving);\n view.on(\"keydown.brush keyup.brush mousemove.brush mouseup.brush\", null);\n }\n group.attr(\"pointer-events\", \"all\");\n overlay.attr(\"cursor\", cursors.overlay);\n if (state.selection) selection = state.selection; // May be set by brush.move (on start)!\n if (empty(selection)) state.selection = null, redraw.call(that);\n emit.end();\n }\n\n function keydowned() {\n switch (event.keyCode) {\n case 16: { // SHIFT\n shifting = signX && signY;\n break;\n }\n case 18: { // ALT\n if (mode === MODE_HANDLE) {\n if (signX) e0 = e1 - dx * signX, w0 = w1 + dx * signX;\n if (signY) s0 = s1 - dy * signY, n0 = n1 + dy * signY;\n mode = MODE_CENTER;\n move();\n }\n break;\n }\n case 32: { // SPACE; takes priority over ALT\n if (mode === MODE_HANDLE || mode === MODE_CENTER) {\n if (signX < 0) e0 = e1 - dx; else if (signX > 0) w0 = w1 - dx;\n if (signY < 0) s0 = s1 - dy; else if (signY > 0) n0 = n1 - dy;\n mode = MODE_SPACE;\n overlay.attr(\"cursor\", cursors.selection);\n move();\n }\n break;\n }\n default: return;\n }\n noevent();\n }\n\n function keyupped() {\n switch (event.keyCode) {\n case 16: { // SHIFT\n if (shifting) {\n lockX = lockY = shifting = false;\n move();\n }\n break;\n }\n case 18: { // ALT\n if (mode === MODE_CENTER) {\n if (signX < 0) e0 = e1; else if (signX > 0) w0 = w1;\n if (signY < 0) s0 = s1; else if (signY > 0) n0 = n1;\n mode = MODE_HANDLE;\n move();\n }\n break;\n }\n case 32: { // SPACE\n if (mode === MODE_SPACE) {\n if (event.altKey) {\n if (signX) e0 = e1 - dx * signX, w0 = w1 + dx * signX;\n if (signY) s0 = s1 - dy * signY, n0 = n1 + dy * signY;\n mode = MODE_CENTER;\n } else {\n if (signX < 0) e0 = e1; else if (signX > 0) w0 = w1;\n if (signY < 0) s0 = s1; else if (signY > 0) n0 = n1;\n mode = MODE_HANDLE;\n }\n overlay.attr(\"cursor\", cursors[type]);\n move();\n }\n break;\n }\n default: return;\n }\n noevent();\n }\n }\n\n function touchmoved() {\n emitter(this, arguments).moved();\n }\n\n function touchended() {\n emitter(this, arguments).ended();\n }\n\n function initialize() {\n var state = this.__brush || {selection: null};\n state.extent = number2(extent.apply(this, arguments));\n state.dim = dim;\n return state;\n }\n\n brush.extent = function(_) {\n return arguments.length ? (extent = typeof _ === \"function\" ? _ : constant(number2(_)), brush) : extent;\n };\n\n brush.filter = function(_) {\n return arguments.length ? (filter = typeof _ === \"function\" ? _ : constant(!!_), brush) : filter;\n };\n\n brush.touchable = function(_) {\n return arguments.length ? (touchable = typeof _ === \"function\" ? _ : constant(!!_), brush) : touchable;\n };\n\n brush.handleSize = function(_) {\n return arguments.length ? (handleSize = +_, brush) : handleSize;\n };\n\n brush.keyModifiers = function(_) {\n return arguments.length ? (keys = !!_, brush) : keys;\n };\n\n brush.on = function() {\n var value = listeners.on.apply(listeners, arguments);\n return value === listeners ? brush : value;\n };\n\n return brush;\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","export default function(target, type, selection) {\n this.target = target;\n this.type = type;\n this.selection = selection;\n}\n","export {\n default as brush,\n brushX,\n brushY,\n brushSelection\n} from \"./brush.js\";\n","import {event} from \"d3-selection\";\n\nexport function nopropagation() {\n event.stopImmediatePropagation();\n}\n\nexport default function() {\n event.preventDefault();\n event.stopImmediatePropagation();\n}\n","var array = Array.prototype;\n\nexport var slice = array.slice;\nexport var map = array.map;\n","export default function(a, b) {\n return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n","import ascending from \"./ascending\";\nimport bisector from \"./bisector\";\n\nvar ascendingBisect = bisector(ascending);\nexport var bisectRight = ascendingBisect.right;\nexport var bisectLeft = ascendingBisect.left;\nexport default bisectRight;\n","import ascending from \"./ascending\";\n\nexport default function(compare) {\n if (compare.length === 1) compare = ascendingComparator(compare);\n return {\n left: function(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n var mid = lo + hi >>> 1;\n if (compare(a[mid], x) < 0) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n },\n right: function(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n var mid = lo + hi >>> 1;\n if (compare(a[mid], x) > 0) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n }\n };\n}\n\nfunction ascendingComparator(f) {\n return function(d, x) {\n return ascending(f(d), x);\n };\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","import {pair} from \"./pairs\";\n\nexport default function(values0, values1, reduce) {\n var n0 = values0.length,\n n1 = values1.length,\n values = new Array(n0 * n1),\n i0,\n i1,\n i,\n value0;\n\n if (reduce == null) reduce = pair;\n\n for (i0 = i = 0; i0 < n0; ++i0) {\n for (value0 = values0[i0], i1 = 0; i1 < n1; ++i1, ++i) {\n values[i] = reduce(value0, values1[i1]);\n }\n }\n\n return values;\n}\n","export default function(a, b) {\n return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;\n}\n","import variance from \"./variance\";\n\nexport default function(array, f) {\n var v = variance(array, f);\n return v ? Math.sqrt(v) : v;\n}\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n min,\n max;\n\n if (valueof == null) {\n while (++i < n) { // Find the first comparable value.\n if ((value = values[i]) != null && value >= value) {\n min = max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = values[i]) != null) {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n }\n }\n\n else {\n while (++i < n) { // Find the first comparable value.\n if ((value = valueof(values[i], i, values)) != null && value >= value) {\n min = max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = valueof(values[i], i, values)) != null) {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n }\n }\n\n return [min, max];\n}\n","import {slice} from \"./array\";\nimport bisect from \"./bisect\";\nimport constant from \"./constant\";\nimport extent from \"./extent\";\nimport identity from \"./identity\";\nimport range from \"./range\";\nimport {tickStep} from \"./ticks\";\nimport sturges from \"./threshold/sturges\";\n\nexport default function() {\n var value = identity,\n domain = extent,\n threshold = sturges;\n\n function histogram(data) {\n var i,\n n = data.length,\n x,\n values = new Array(n);\n\n for (i = 0; i < n; ++i) {\n values[i] = value(data[i], i, data);\n }\n\n var xz = domain(values),\n x0 = xz[0],\n x1 = xz[1],\n tz = threshold(values, x0, x1);\n\n // Convert number of thresholds into uniform thresholds.\n if (!Array.isArray(tz)) {\n tz = tickStep(x0, x1, tz);\n tz = range(Math.ceil(x0 / tz) * tz, x1, tz); // exclusive\n }\n\n // Remove any thresholds outside the domain.\n var m = tz.length;\n while (tz[0] <= x0) tz.shift(), --m;\n while (tz[m - 1] > x1) tz.pop(), --m;\n\n var bins = new Array(m + 1),\n bin;\n\n // Initialize bins.\n for (i = 0; i <= m; ++i) {\n bin = bins[i] = [];\n bin.x0 = i > 0 ? tz[i - 1] : x0;\n bin.x1 = i < m ? tz[i] : x1;\n }\n\n // Assign data to bins by value, ignoring any outside the domain.\n for (i = 0; i < n; ++i) {\n x = values[i];\n if (x0 <= x && x <= x1) {\n bins[bisect(tz, x, 0, m)].push(data[i]);\n }\n }\n\n return bins;\n }\n\n histogram.value = function(_) {\n return arguments.length ? (value = typeof _ === \"function\" ? _ : constant(_), histogram) : value;\n };\n\n histogram.domain = function(_) {\n return arguments.length ? (domain = typeof _ === \"function\" ? _ : constant([_[0], _[1]]), histogram) : domain;\n };\n\n histogram.thresholds = function(_) {\n return arguments.length ? (threshold = typeof _ === \"function\" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), histogram) : threshold;\n };\n\n return histogram;\n}\n","export default function(x) {\n return x;\n}\n","export {default as bisect, bisectRight, bisectLeft} from \"./bisect\";\nexport {default as ascending} from \"./ascending\";\nexport {default as bisector} from \"./bisector\";\nexport {default as cross} from \"./cross\";\nexport {default as descending} from \"./descending\";\nexport {default as deviation} from \"./deviation\";\nexport {default as extent} from \"./extent\";\nexport {default as histogram} from \"./histogram\";\nexport {default as thresholdFreedmanDiaconis} from \"./threshold/freedmanDiaconis\";\nexport {default as thresholdScott} from \"./threshold/scott\";\nexport {default as thresholdSturges} from \"./threshold/sturges\";\nexport {default as max} from \"./max\";\nexport {default as mean} from \"./mean\";\nexport {default as median} from \"./median\";\nexport {default as merge} from \"./merge\";\nexport {default as min} from \"./min\";\nexport {default as pairs} from \"./pairs\";\nexport {default as permute} from \"./permute\";\nexport {default as quantile} from \"./quantile\";\nexport {default as range} from \"./range\";\nexport {default as scan} from \"./scan\";\nexport {default as shuffle} from \"./shuffle\";\nexport {default as sum} from \"./sum\";\nexport {default as ticks, tickIncrement, tickStep} from \"./ticks\";\nexport {default as transpose} from \"./transpose\";\nexport {default as variance} from \"./variance\";\nexport {default as zip} from \"./zip\";\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n max;\n\n if (valueof == null) {\n while (++i < n) { // Find the first comparable value.\n if ((value = values[i]) != null && value >= value) {\n max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = values[i]) != null && value > max) {\n max = value;\n }\n }\n }\n }\n }\n\n else {\n while (++i < n) { // Find the first comparable value.\n if ((value = valueof(values[i], i, values)) != null && value >= value) {\n max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = valueof(values[i], i, values)) != null && value > max) {\n max = value;\n }\n }\n }\n }\n }\n\n return max;\n}\n","import number from \"./number\";\n\nexport default function(values, valueof) {\n var n = values.length,\n m = n,\n i = -1,\n value,\n sum = 0;\n\n if (valueof == null) {\n while (++i < n) {\n if (!isNaN(value = number(values[i]))) sum += value;\n else --m;\n }\n }\n\n else {\n while (++i < n) {\n if (!isNaN(value = number(valueof(values[i], i, values)))) sum += value;\n else --m;\n }\n }\n\n if (m) return sum / m;\n}\n","import ascending from \"./ascending\";\nimport number from \"./number\";\nimport quantile from \"./quantile\";\n\nexport default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n numbers = [];\n\n if (valueof == null) {\n while (++i < n) {\n if (!isNaN(value = number(values[i]))) {\n numbers.push(value);\n }\n }\n }\n\n else {\n while (++i < n) {\n if (!isNaN(value = number(valueof(values[i], i, values)))) {\n numbers.push(value);\n }\n }\n }\n\n return quantile(numbers.sort(ascending), 0.5);\n}\n","export default function(arrays) {\n var n = arrays.length,\n m,\n i = -1,\n j = 0,\n merged,\n array;\n\n while (++i < n) j += arrays[i].length;\n merged = new Array(j);\n\n while (--n >= 0) {\n array = arrays[n];\n m = array.length;\n while (--m >= 0) {\n merged[--j] = array[m];\n }\n }\n\n return merged;\n}\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n min;\n\n if (valueof == null) {\n while (++i < n) { // Find the first comparable value.\n if ((value = values[i]) != null && value >= value) {\n min = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = values[i]) != null && min > value) {\n min = value;\n }\n }\n }\n }\n }\n\n else {\n while (++i < n) { // Find the first comparable value.\n if ((value = valueof(values[i], i, values)) != null && value >= value) {\n min = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = valueof(values[i], i, values)) != null && min > value) {\n min = value;\n }\n }\n }\n }\n }\n\n return min;\n}\n","export default function(x) {\n return x === null ? NaN : +x;\n}\n","export default function(array, f) {\n if (f == null) f = pair;\n var i = 0, n = array.length - 1, p = array[0], pairs = new Array(n < 0 ? 0 : n);\n while (i < n) pairs[i] = f(p, p = array[++i]);\n return pairs;\n}\n\nexport function pair(a, b) {\n return [a, b];\n}\n","export default function(array, indexes) {\n var i = indexes.length, permutes = new Array(i);\n while (i--) permutes[i] = array[indexes[i]];\n return permutes;\n}\n","import number from \"./number\";\n\nexport default function(values, p, valueof) {\n if (valueof == null) valueof = number;\n if (!(n = values.length)) return;\n if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);\n if (p >= 1) return +valueof(values[n - 1], n - 1, values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = +valueof(values[i0], i0, values),\n value1 = +valueof(values[i0 + 1], i0 + 1, values);\n return value0 + (value1 - value0) * (i - i0);\n}\n","export default function(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n","import ascending from \"./ascending\";\n\nexport default function(values, compare) {\n if (!(n = values.length)) return;\n var n,\n i = 0,\n j = 0,\n xi,\n xj = values[j];\n\n if (compare == null) compare = ascending;\n\n while (++i < n) {\n if (compare(xi = values[i], xj) < 0 || compare(xj, xj) !== 0) {\n xj = xi, j = i;\n }\n }\n\n if (compare(xj, xj) === 0) return j;\n}\n","export default function(array, i0, i1) {\n var m = (i1 == null ? array.length : i1) - (i0 = i0 == null ? 0 : +i0),\n t,\n i;\n\n while (m) {\n i = Math.random() * m-- | 0;\n t = array[m + i0];\n array[m + i0] = array[i + i0];\n array[i + i0] = t;\n }\n\n return array;\n}\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n sum = 0;\n\n if (valueof == null) {\n while (++i < n) {\n if (value = +values[i]) sum += value; // Note: zero and null are equivalent.\n }\n }\n\n else {\n while (++i < n) {\n if (value = +valueof(values[i], i, values)) sum += value;\n }\n }\n\n return sum;\n}\n","import {map} from \"../array\";\nimport ascending from \"../ascending\";\nimport number from \"../number\";\nimport quantile from \"../quantile\";\n\nexport default function(values, min, max) {\n values = map.call(values, number).sort(ascending);\n return Math.ceil((max - min) / (2 * (quantile(values, 0.75) - quantile(values, 0.25)) * Math.pow(values.length, -1 / 3)));\n}\n","import deviation from \"../deviation\";\n\nexport default function(values, min, max) {\n return Math.ceil((max - min) / (3.5 * deviation(values) * Math.pow(values.length, -1 / 3)));\n}\n","export default function(values) {\n return Math.ceil(Math.log(values.length) / Math.LN2) + 1;\n}\n","var e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nexport default function(start, stop, count) {\n var reverse,\n i = -1,\n n,\n ticks,\n step;\n\n stop = +stop, start = +start, count = +count;\n if (start === stop && count > 0) return [start];\n if (reverse = stop < start) n = start, start = stop, stop = n;\n if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];\n\n if (step > 0) {\n start = Math.ceil(start / step);\n stop = Math.floor(stop / step);\n ticks = new Array(n = Math.ceil(stop - start + 1));\n while (++i < n) ticks[i] = (start + i) * step;\n } else {\n start = Math.floor(start * step);\n stop = Math.ceil(stop * step);\n ticks = new Array(n = Math.ceil(start - stop + 1));\n while (++i < n) ticks[i] = (start - i) / step;\n }\n\n if (reverse) ticks.reverse();\n\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n var step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log(step) / Math.LN10),\n error = step / Math.pow(10, power);\n return power >= 0\n ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)\n : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);\n}\n\nexport function tickStep(start, stop, count) {\n var step0 = Math.abs(stop - start) / Math.max(0, count),\n step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),\n error = step0 / step1;\n if (error >= e10) step1 *= 10;\n else if (error >= e5) step1 *= 5;\n else if (error >= e2) step1 *= 2;\n return stop < start ? -step1 : step1;\n}\n","import min from \"./min\";\n\nexport default function(matrix) {\n if (!(n = matrix.length)) return [];\n for (var i = -1, m = min(matrix, length), transpose = new Array(m); ++i < m;) {\n for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n;) {\n row[j] = matrix[j][i];\n }\n }\n return transpose;\n}\n\nfunction length(d) {\n return d.length;\n}\n","import number from \"./number\";\n\nexport default function(values, valueof) {\n var n = values.length,\n m = 0,\n i = -1,\n mean = 0,\n value,\n delta,\n sum = 0;\n\n if (valueof == null) {\n while (++i < n) {\n if (!isNaN(value = number(values[i]))) {\n delta = value - mean;\n mean += delta / ++m;\n sum += delta * (value - mean);\n }\n }\n }\n\n else {\n while (++i < n) {\n if (!isNaN(value = number(valueof(values[i], i, values)))) {\n delta = value - mean;\n mean += delta / ++m;\n sum += delta * (value - mean);\n }\n }\n }\n\n if (m > 1) return sum / (m - 1);\n}\n","import transpose from \"./transpose\";\n\nexport default function() {\n return transpose(arguments);\n}\n","export var slice = Array.prototype.slice;\n","import {range} from \"d3-array\";\nimport {max, tau} from \"./math\";\n\nfunction compareValue(compare) {\n return function(a, b) {\n return compare(\n a.source.value + a.target.value,\n b.source.value + b.target.value\n );\n };\n}\n\nexport default function() {\n var padAngle = 0,\n sortGroups = null,\n sortSubgroups = null,\n sortChords = null;\n\n function chord(matrix) {\n var n = matrix.length,\n groupSums = [],\n groupIndex = range(n),\n subgroupIndex = [],\n chords = [],\n groups = chords.groups = new Array(n),\n subgroups = new Array(n * n),\n k,\n x,\n x0,\n dx,\n i,\n j;\n\n // Compute the sum.\n k = 0, i = -1; while (++i < n) {\n x = 0, j = -1; while (++j < n) {\n x += matrix[i][j];\n }\n groupSums.push(x);\n subgroupIndex.push(range(n));\n k += x;\n }\n\n // Sort groups…\n if (sortGroups) groupIndex.sort(function(a, b) {\n return sortGroups(groupSums[a], groupSums[b]);\n });\n\n // Sort subgroups…\n if (sortSubgroups) subgroupIndex.forEach(function(d, i) {\n d.sort(function(a, b) {\n return sortSubgroups(matrix[i][a], matrix[i][b]);\n });\n });\n\n // Convert the sum to scaling factor for [0, 2pi].\n // TODO Allow start and end angle to be specified?\n // TODO Allow padding to be specified as percentage?\n k = max(0, tau - padAngle * n) / k;\n dx = k ? padAngle : tau / n;\n\n // Compute the start and end angle for each group and subgroup.\n // Note: Opera has a bug reordering object literal properties!\n x = 0, i = -1; while (++i < n) {\n x0 = x, j = -1; while (++j < n) {\n var di = groupIndex[i],\n dj = subgroupIndex[di][j],\n v = matrix[di][dj],\n a0 = x,\n a1 = x += v * k;\n subgroups[dj * n + di] = {\n index: di,\n subindex: dj,\n startAngle: a0,\n endAngle: a1,\n value: v\n };\n }\n groups[di] = {\n index: di,\n startAngle: x0,\n endAngle: x,\n value: groupSums[di]\n };\n x += dx;\n }\n\n // Generate chords for each (non-empty) subgroup-subgroup link.\n i = -1; while (++i < n) {\n j = i - 1; while (++j < n) {\n var source = subgroups[j * n + i],\n target = subgroups[i * n + j];\n if (source.value || target.value) {\n chords.push(source.value < target.value\n ? {source: target, target: source}\n : {source: source, target: target});\n }\n }\n }\n\n return sortChords ? chords.sort(sortChords) : chords;\n }\n\n chord.padAngle = function(_) {\n return arguments.length ? (padAngle = max(0, _), chord) : padAngle;\n };\n\n chord.sortGroups = function(_) {\n return arguments.length ? (sortGroups = _, chord) : sortGroups;\n };\n\n chord.sortSubgroups = function(_) {\n return arguments.length ? (sortSubgroups = _, chord) : sortSubgroups;\n };\n\n chord.sortChords = function(_) {\n return arguments.length ? (_ == null ? sortChords = null : (sortChords = compareValue(_))._ = _, chord) : sortChords && sortChords._;\n };\n\n return chord;\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","export {default as chord} from \"./chord\";\nexport {default as ribbon} from \"./ribbon\";\n","export var cos = Math.cos;\nexport var sin = Math.sin;\nexport var pi = Math.PI;\nexport var halfPi = pi / 2;\nexport var tau = pi * 2;\nexport var max = Math.max;\n","import {slice} from \"./array\";\nimport constant from \"./constant\";\nimport {cos, halfPi, sin} from \"./math\";\nimport {path} from \"d3-path\";\n\nfunction defaultSource(d) {\n return d.source;\n}\n\nfunction defaultTarget(d) {\n return d.target;\n}\n\nfunction defaultRadius(d) {\n return d.radius;\n}\n\nfunction defaultStartAngle(d) {\n return d.startAngle;\n}\n\nfunction defaultEndAngle(d) {\n return d.endAngle;\n}\n\nexport default function() {\n var source = defaultSource,\n target = defaultTarget,\n radius = defaultRadius,\n startAngle = defaultStartAngle,\n endAngle = defaultEndAngle,\n context = null;\n\n function ribbon() {\n var buffer,\n argv = slice.call(arguments),\n s = source.apply(this, argv),\n t = target.apply(this, argv),\n sr = +radius.apply(this, (argv[0] = s, argv)),\n sa0 = startAngle.apply(this, argv) - halfPi,\n sa1 = endAngle.apply(this, argv) - halfPi,\n sx0 = sr * cos(sa0),\n sy0 = sr * sin(sa0),\n tr = +radius.apply(this, (argv[0] = t, argv)),\n ta0 = startAngle.apply(this, argv) - halfPi,\n ta1 = endAngle.apply(this, argv) - halfPi;\n\n if (!context) context = buffer = path();\n\n context.moveTo(sx0, sy0);\n context.arc(0, 0, sr, sa0, sa1);\n if (sa0 !== ta0 || sa1 !== ta1) { // TODO sr !== tr?\n context.quadraticCurveTo(0, 0, tr * cos(ta0), tr * sin(ta0));\n context.arc(0, 0, tr, ta0, ta1);\n }\n context.quadraticCurveTo(0, 0, sx0, sy0);\n context.closePath();\n\n if (buffer) return context = null, buffer + \"\" || null;\n }\n\n ribbon.radius = function(_) {\n return arguments.length ? (radius = typeof _ === \"function\" ? _ : constant(+_), ribbon) : radius;\n };\n\n ribbon.startAngle = function(_) {\n return arguments.length ? (startAngle = typeof _ === \"function\" ? _ : constant(+_), ribbon) : startAngle;\n };\n\n ribbon.endAngle = function(_) {\n return arguments.length ? (endAngle = typeof _ === \"function\" ? _ : constant(+_), ribbon) : endAngle;\n };\n\n ribbon.source = function(_) {\n return arguments.length ? (source = _, ribbon) : source;\n };\n\n ribbon.target = function(_) {\n return arguments.length ? (target = _, ribbon) : target;\n };\n\n ribbon.context = function(_) {\n return arguments.length ? ((context = _ == null ? null : _), ribbon) : context;\n };\n\n return ribbon;\n}\n","export default function(map) {\n var entries = [];\n for (var key in map) entries.push({key: key, value: map[key]});\n return entries;\n}\n","export {default as nest} from \"./nest\";\nexport {default as set} from \"./set\";\nexport {default as map} from \"./map\";\nexport {default as keys} from \"./keys\";\nexport {default as values} from \"./values\";\nexport {default as entries} from \"./entries\";\n","export default function(map) {\n var keys = [];\n for (var key in map) keys.push(key);\n return keys;\n}\n","export var prefix = \"$\";\n\nfunction Map() {}\n\nMap.prototype = map.prototype = {\n constructor: Map,\n has: function(key) {\n return (prefix + key) in this;\n },\n get: function(key) {\n return this[prefix + key];\n },\n set: function(key, value) {\n this[prefix + key] = value;\n return this;\n },\n remove: function(key) {\n var property = prefix + key;\n return property in this && delete this[property];\n },\n clear: function() {\n for (var property in this) if (property[0] === prefix) delete this[property];\n },\n keys: function() {\n var keys = [];\n for (var property in this) if (property[0] === prefix) keys.push(property.slice(1));\n return keys;\n },\n values: function() {\n var values = [];\n for (var property in this) if (property[0] === prefix) values.push(this[property]);\n return values;\n },\n entries: function() {\n var entries = [];\n for (var property in this) if (property[0] === prefix) entries.push({key: property.slice(1), value: this[property]});\n return entries;\n },\n size: function() {\n var size = 0;\n for (var property in this) if (property[0] === prefix) ++size;\n return size;\n },\n empty: function() {\n for (var property in this) if (property[0] === prefix) return false;\n return true;\n },\n each: function(f) {\n for (var property in this) if (property[0] === prefix) f(this[property], property.slice(1), this);\n }\n};\n\nfunction map(object, f) {\n var map = new Map;\n\n // Copy constructor.\n if (object instanceof Map) object.each(function(value, key) { map.set(key, value); });\n\n // Index array by numeric index or specified key function.\n else if (Array.isArray(object)) {\n var i = -1,\n n = object.length,\n o;\n\n if (f == null) while (++i < n) map.set(i, object[i]);\n else while (++i < n) map.set(f(o = object[i], i, object), o);\n }\n\n // Convert object to map.\n else if (object) for (var key in object) map.set(key, object[key]);\n\n return map;\n}\n\nexport default map;\n","import map from \"./map\";\n\nexport default function() {\n var keys = [],\n sortKeys = [],\n sortValues,\n rollup,\n nest;\n\n function apply(array, depth, createResult, setResult) {\n if (depth >= keys.length) {\n if (sortValues != null) array.sort(sortValues);\n return rollup != null ? rollup(array) : array;\n }\n\n var i = -1,\n n = array.length,\n key = keys[depth++],\n keyValue,\n value,\n valuesByKey = map(),\n values,\n result = createResult();\n\n while (++i < n) {\n if (values = valuesByKey.get(keyValue = key(value = array[i]) + \"\")) {\n values.push(value);\n } else {\n valuesByKey.set(keyValue, [value]);\n }\n }\n\n valuesByKey.each(function(values, key) {\n setResult(result, key, apply(values, depth, createResult, setResult));\n });\n\n return result;\n }\n\n function entries(map, depth) {\n if (++depth > keys.length) return map;\n var array, sortKey = sortKeys[depth - 1];\n if (rollup != null && depth >= keys.length) array = map.entries();\n else array = [], map.each(function(v, k) { array.push({key: k, values: entries(v, depth)}); });\n return sortKey != null ? array.sort(function(a, b) { return sortKey(a.key, b.key); }) : array;\n }\n\n return nest = {\n object: function(array) { return apply(array, 0, createObject, setObject); },\n map: function(array) { return apply(array, 0, createMap, setMap); },\n entries: function(array) { return entries(apply(array, 0, createMap, setMap), 0); },\n key: function(d) { keys.push(d); return nest; },\n sortKeys: function(order) { sortKeys[keys.length - 1] = order; return nest; },\n sortValues: function(order) { sortValues = order; return nest; },\n rollup: function(f) { rollup = f; return nest; }\n };\n}\n\nfunction createObject() {\n return {};\n}\n\nfunction setObject(object, key, value) {\n object[key] = value;\n}\n\nfunction createMap() {\n return map();\n}\n\nfunction setMap(map, key, value) {\n map.set(key, value);\n}\n","import {default as map, prefix} from \"./map\";\n\nfunction Set() {}\n\nvar proto = map.prototype;\n\nSet.prototype = set.prototype = {\n constructor: Set,\n has: proto.has,\n add: function(value) {\n value += \"\";\n this[prefix + value] = value;\n return this;\n },\n remove: proto.remove,\n clear: proto.clear,\n values: proto.keys,\n size: proto.size,\n empty: proto.empty,\n each: proto.each\n};\n\nfunction set(object, f) {\n var set = new Set;\n\n // Copy constructor.\n if (object instanceof Set) object.each(function(value) { set.add(value); });\n\n // Otherwise, assume it’s an array.\n else if (object) {\n var i = -1, n = object.length;\n if (f == null) while (++i < n) set.add(object[i]);\n else while (++i < n) set.add(f(object[i], i, object));\n }\n\n return set;\n}\n\nexport default set;\n","export default function(map) {\n var values = [];\n for (var key in map) values.push(map[key]);\n return values;\n}\n","import define, {extend} from \"./define.js\";\n\nexport function Color() {}\n\nexport var darker = 0.7;\nexport var brighter = 1 / darker;\n\nvar reI = \"\\\\s*([+-]?\\\\d+)\\\\s*\",\n reN = \"\\\\s*([+-]?\\\\d*\\\\.?\\\\d+(?:[eE][+-]?\\\\d+)?)\\\\s*\",\n reP = \"\\\\s*([+-]?\\\\d*\\\\.?\\\\d+(?:[eE][+-]?\\\\d+)?)%\\\\s*\",\n reHex = /^#([0-9a-f]{3,8})$/,\n reRgbInteger = new RegExp(\"^rgb\\\\(\" + [reI, reI, reI] + \"\\\\)$\"),\n reRgbPercent = new RegExp(\"^rgb\\\\(\" + [reP, reP, reP] + \"\\\\)$\"),\n reRgbaInteger = new RegExp(\"^rgba\\\\(\" + [reI, reI, reI, reN] + \"\\\\)$\"),\n reRgbaPercent = new RegExp(\"^rgba\\\\(\" + [reP, reP, reP, reN] + \"\\\\)$\"),\n reHslPercent = new RegExp(\"^hsl\\\\(\" + [reN, reP, reP] + \"\\\\)$\"),\n reHslaPercent = new RegExp(\"^hsla\\\\(\" + [reN, reP, reP, reN] + \"\\\\)$\");\n\nvar named = {\n aliceblue: 0xf0f8ff,\n antiquewhite: 0xfaebd7,\n aqua: 0x00ffff,\n aquamarine: 0x7fffd4,\n azure: 0xf0ffff,\n beige: 0xf5f5dc,\n bisque: 0xffe4c4,\n black: 0x000000,\n blanchedalmond: 0xffebcd,\n blue: 0x0000ff,\n blueviolet: 0x8a2be2,\n brown: 0xa52a2a,\n burlywood: 0xdeb887,\n cadetblue: 0x5f9ea0,\n chartreuse: 0x7fff00,\n chocolate: 0xd2691e,\n coral: 0xff7f50,\n cornflowerblue: 0x6495ed,\n cornsilk: 0xfff8dc,\n crimson: 0xdc143c,\n cyan: 0x00ffff,\n darkblue: 0x00008b,\n darkcyan: 0x008b8b,\n darkgoldenrod: 0xb8860b,\n darkgray: 0xa9a9a9,\n darkgreen: 0x006400,\n darkgrey: 0xa9a9a9,\n darkkhaki: 0xbdb76b,\n darkmagenta: 0x8b008b,\n darkolivegreen: 0x556b2f,\n darkorange: 0xff8c00,\n darkorchid: 0x9932cc,\n darkred: 0x8b0000,\n darksalmon: 0xe9967a,\n darkseagreen: 0x8fbc8f,\n darkslateblue: 0x483d8b,\n darkslategray: 0x2f4f4f,\n darkslategrey: 0x2f4f4f,\n darkturquoise: 0x00ced1,\n darkviolet: 0x9400d3,\n deeppink: 0xff1493,\n deepskyblue: 0x00bfff,\n dimgray: 0x696969,\n dimgrey: 0x696969,\n dodgerblue: 0x1e90ff,\n firebrick: 0xb22222,\n floralwhite: 0xfffaf0,\n forestgreen: 0x228b22,\n fuchsia: 0xff00ff,\n gainsboro: 0xdcdcdc,\n ghostwhite: 0xf8f8ff,\n gold: 0xffd700,\n goldenrod: 0xdaa520,\n gray: 0x808080,\n green: 0x008000,\n greenyellow: 0xadff2f,\n grey: 0x808080,\n honeydew: 0xf0fff0,\n hotpink: 0xff69b4,\n indianred: 0xcd5c5c,\n indigo: 0x4b0082,\n ivory: 0xfffff0,\n khaki: 0xf0e68c,\n lavender: 0xe6e6fa,\n lavenderblush: 0xfff0f5,\n lawngreen: 0x7cfc00,\n lemonchiffon: 0xfffacd,\n lightblue: 0xadd8e6,\n lightcoral: 0xf08080,\n lightcyan: 0xe0ffff,\n lightgoldenrodyellow: 0xfafad2,\n lightgray: 0xd3d3d3,\n lightgreen: 0x90ee90,\n lightgrey: 0xd3d3d3,\n lightpink: 0xffb6c1,\n lightsalmon: 0xffa07a,\n lightseagreen: 0x20b2aa,\n lightskyblue: 0x87cefa,\n lightslategray: 0x778899,\n lightslategrey: 0x778899,\n lightsteelblue: 0xb0c4de,\n lightyellow: 0xffffe0,\n lime: 0x00ff00,\n limegreen: 0x32cd32,\n linen: 0xfaf0e6,\n magenta: 0xff00ff,\n maroon: 0x800000,\n mediumaquamarine: 0x66cdaa,\n mediumblue: 0x0000cd,\n mediumorchid: 0xba55d3,\n mediumpurple: 0x9370db,\n mediumseagreen: 0x3cb371,\n mediumslateblue: 0x7b68ee,\n mediumspringgreen: 0x00fa9a,\n mediumturquoise: 0x48d1cc,\n mediumvioletred: 0xc71585,\n midnightblue: 0x191970,\n mintcream: 0xf5fffa,\n mistyrose: 0xffe4e1,\n moccasin: 0xffe4b5,\n navajowhite: 0xffdead,\n navy: 0x000080,\n oldlace: 0xfdf5e6,\n olive: 0x808000,\n olivedrab: 0x6b8e23,\n orange: 0xffa500,\n orangered: 0xff4500,\n orchid: 0xda70d6,\n palegoldenrod: 0xeee8aa,\n palegreen: 0x98fb98,\n paleturquoise: 0xafeeee,\n palevioletred: 0xdb7093,\n papayawhip: 0xffefd5,\n peachpuff: 0xffdab9,\n peru: 0xcd853f,\n pink: 0xffc0cb,\n plum: 0xdda0dd,\n powderblue: 0xb0e0e6,\n purple: 0x800080,\n rebeccapurple: 0x663399,\n red: 0xff0000,\n rosybrown: 0xbc8f8f,\n royalblue: 0x4169e1,\n saddlebrown: 0x8b4513,\n salmon: 0xfa8072,\n sandybrown: 0xf4a460,\n seagreen: 0x2e8b57,\n seashell: 0xfff5ee,\n sienna: 0xa0522d,\n silver: 0xc0c0c0,\n skyblue: 0x87ceeb,\n slateblue: 0x6a5acd,\n slategray: 0x708090,\n slategrey: 0x708090,\n snow: 0xfffafa,\n springgreen: 0x00ff7f,\n steelblue: 0x4682b4,\n tan: 0xd2b48c,\n teal: 0x008080,\n thistle: 0xd8bfd8,\n tomato: 0xff6347,\n turquoise: 0x40e0d0,\n violet: 0xee82ee,\n wheat: 0xf5deb3,\n white: 0xffffff,\n whitesmoke: 0xf5f5f5,\n yellow: 0xffff00,\n yellowgreen: 0x9acd32\n};\n\ndefine(Color, color, {\n copy: function(channels) {\n return Object.assign(new this.constructor, this, channels);\n },\n displayable: function() {\n return this.rgb().displayable();\n },\n hex: color_formatHex, // Deprecated! Use color.formatHex.\n formatHex: color_formatHex,\n formatHsl: color_formatHsl,\n formatRgb: color_formatRgb,\n toString: color_formatRgb\n});\n\nfunction color_formatHex() {\n return this.rgb().formatHex();\n}\n\nfunction color_formatHsl() {\n return hslConvert(this).formatHsl();\n}\n\nfunction color_formatRgb() {\n return this.rgb().formatRgb();\n}\n\nexport default function color(format) {\n var m, l;\n format = (format + \"\").trim().toLowerCase();\n return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000\n : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00\n : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000\n : l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000\n : null) // invalid hex\n : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)\n : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)\n : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)\n : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)\n : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)\n : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)\n : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins\n : format === \"transparent\" ? new Rgb(NaN, NaN, NaN, 0)\n : null;\n}\n\nfunction rgbn(n) {\n return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);\n}\n\nfunction rgba(r, g, b, a) {\n if (a <= 0) r = g = b = NaN;\n return new Rgb(r, g, b, a);\n}\n\nexport function rgbConvert(o) {\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Rgb;\n o = o.rgb();\n return new Rgb(o.r, o.g, o.b, o.opacity);\n}\n\nexport function rgb(r, g, b, opacity) {\n return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);\n}\n\nexport function Rgb(r, g, b, opacity) {\n this.r = +r;\n this.g = +g;\n this.b = +b;\n this.opacity = +opacity;\n}\n\ndefine(Rgb, rgb, extend(Color, {\n brighter: function(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n darker: function(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);\n },\n rgb: function() {\n return this;\n },\n displayable: function() {\n return (-0.5 <= this.r && this.r < 255.5)\n && (-0.5 <= this.g && this.g < 255.5)\n && (-0.5 <= this.b && this.b < 255.5)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n hex: rgb_formatHex, // Deprecated! Use color.formatHex.\n formatHex: rgb_formatHex,\n formatRgb: rgb_formatRgb,\n toString: rgb_formatRgb\n}));\n\nfunction rgb_formatHex() {\n return \"#\" + hex(this.r) + hex(this.g) + hex(this.b);\n}\n\nfunction rgb_formatRgb() {\n var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));\n return (a === 1 ? \"rgb(\" : \"rgba(\")\n + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + \", \"\n + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + \", \"\n + Math.max(0, Math.min(255, Math.round(this.b) || 0))\n + (a === 1 ? \")\" : \", \" + a + \")\");\n}\n\nfunction hex(value) {\n value = Math.max(0, Math.min(255, Math.round(value) || 0));\n return (value < 16 ? \"0\" : \"\") + value.toString(16);\n}\n\nfunction hsla(h, s, l, a) {\n if (a <= 0) h = s = l = NaN;\n else if (l <= 0 || l >= 1) h = s = NaN;\n else if (s <= 0) h = NaN;\n return new Hsl(h, s, l, a);\n}\n\nexport function hslConvert(o) {\n if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);\n if (!(o instanceof Color)) o = color(o);\n if (!o) return new Hsl;\n if (o instanceof Hsl) return o;\n o = o.rgb();\n var r = o.r / 255,\n g = o.g / 255,\n b = o.b / 255,\n min = Math.min(r, g, b),\n max = Math.max(r, g, b),\n h = NaN,\n s = max - min,\n l = (max + min) / 2;\n if (s) {\n if (r === max) h = (g - b) / s + (g < b) * 6;\n else if (g === max) h = (b - r) / s + 2;\n else h = (r - g) / s + 4;\n s /= l < 0.5 ? max + min : 2 - max - min;\n h *= 60;\n } else {\n s = l > 0 && l < 1 ? 0 : h;\n }\n return new Hsl(h, s, l, o.opacity);\n}\n\nexport function hsl(h, s, l, opacity) {\n return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);\n}\n\nfunction Hsl(h, s, l, opacity) {\n this.h = +h;\n this.s = +s;\n this.l = +l;\n this.opacity = +opacity;\n}\n\ndefine(Hsl, hsl, extend(Color, {\n brighter: function(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n darker: function(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Hsl(this.h, this.s, this.l * k, this.opacity);\n },\n rgb: function() {\n var h = this.h % 360 + (this.h < 0) * 360,\n s = isNaN(h) || isNaN(this.s) ? 0 : this.s,\n l = this.l,\n m2 = l + (l < 0.5 ? l : 1 - l) * s,\n m1 = 2 * l - m2;\n return new Rgb(\n hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),\n hsl2rgb(h, m1, m2),\n hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),\n this.opacity\n );\n },\n displayable: function() {\n return (0 <= this.s && this.s <= 1 || isNaN(this.s))\n && (0 <= this.l && this.l <= 1)\n && (0 <= this.opacity && this.opacity <= 1);\n },\n formatHsl: function() {\n var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));\n return (a === 1 ? \"hsl(\" : \"hsla(\")\n + (this.h || 0) + \", \"\n + (this.s || 0) * 100 + \"%, \"\n + (this.l || 0) * 100 + \"%\"\n + (a === 1 ? \")\" : \", \" + a + \")\");\n }\n}));\n\n/* From FvD 13.37, CSS Color Module Level 3 */\nfunction hsl2rgb(h, m1, m2) {\n return (h < 60 ? m1 + (m2 - m1) * h / 60\n : h < 180 ? m2\n : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60\n : m1) * 255;\n}\n","import define, {extend} from \"./define.js\";\nimport {Color, rgbConvert, Rgb, darker, brighter} from \"./color.js\";\nimport {deg2rad, rad2deg} from \"./math.js\";\n\nvar A = -0.14861,\n B = +1.78277,\n C = -0.29227,\n D = -0.90649,\n E = +1.97294,\n ED = E * D,\n EB = E * B,\n BC_DA = B * C - D * A;\n\nfunction cubehelixConvert(o) {\n if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity);\n if (!(o instanceof Rgb)) o = rgbConvert(o);\n var r = o.r / 255,\n g = o.g / 255,\n b = o.b / 255,\n l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB),\n bl = b - l,\n k = (E * (g - l) - C * bl) / D,\n s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1\n h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN;\n return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity);\n}\n\nexport default function cubehelix(h, s, l, opacity) {\n return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity);\n}\n\nexport function Cubehelix(h, s, l, opacity) {\n this.h = +h;\n this.s = +s;\n this.l = +l;\n this.opacity = +opacity;\n}\n\ndefine(Cubehelix, cubehelix, extend(Color, {\n brighter: function(k) {\n k = k == null ? brighter : Math.pow(brighter, k);\n return new Cubehelix(this.h, this.s, this.l * k, this.opacity);\n },\n darker: function(k) {\n k = k == null ? darker : Math.pow(darker, k);\n return new Cubehelix(this.h, this.s, this.l * k, this.opacity);\n },\n rgb: function() {\n var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad,\n l = +this.l,\n a = isNaN(this.s) ? 0 : this.s * l * (1 - l),\n cosh = Math.cos(h),\n sinh = Math.sin(h);\n return new Rgb(\n 255 * (l + a * (A * cosh + B * sinh)),\n 255 * (l + a * (C * cosh + D * sinh)),\n 255 * (l + a * (E * cosh)),\n this.opacity\n );\n }\n}));\n","export default function(constructor, factory, prototype) {\n constructor.prototype = factory.prototype = prototype;\n prototype.constructor = constructor;\n}\n\nexport function extend(parent, definition) {\n var prototype = Object.create(parent.prototype);\n for (var key in definition) prototype[key] = definition[key];\n return prototype;\n}\n","export {default as color, rgb, hsl} from \"./color.js\";\nexport {default as lab, hcl, lch, gray} from \"./lab.js\";\nexport {default as cubehelix} from \"./cubehelix.js\";\n","import define, {extend} from \"./define.js\";\nimport {Color, rgbConvert, Rgb} from \"./color.js\";\nimport {deg2rad, rad2deg} from \"./math.js\";\n\n// https://observablehq.com/@mbostock/lab-and-rgb\nvar K = 18,\n Xn = 0.96422,\n Yn = 1,\n Zn = 0.82521,\n t0 = 4 / 29,\n t1 = 6 / 29,\n t2 = 3 * t1 * t1,\n t3 = t1 * t1 * t1;\n\nfunction labConvert(o) {\n if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity);\n if (o instanceof Hcl) return hcl2lab(o);\n if (!(o instanceof Rgb)) o = rgbConvert(o);\n var r = rgb2lrgb(o.r),\n g = rgb2lrgb(o.g),\n b = rgb2lrgb(o.b),\n y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z;\n if (r === g && g === b) x = z = y; else {\n x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn);\n z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn);\n }\n return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity);\n}\n\nexport function gray(l, opacity) {\n return new Lab(l, 0, 0, opacity == null ? 1 : opacity);\n}\n\nexport default function lab(l, a, b, opacity) {\n return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity);\n}\n\nexport function Lab(l, a, b, opacity) {\n this.l = +l;\n this.a = +a;\n this.b = +b;\n this.opacity = +opacity;\n}\n\ndefine(Lab, lab, extend(Color, {\n brighter: function(k) {\n return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity);\n },\n darker: function(k) {\n return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity);\n },\n rgb: function() {\n var y = (this.l + 16) / 116,\n x = isNaN(this.a) ? y : y + this.a / 500,\n z = isNaN(this.b) ? y : y - this.b / 200;\n x = Xn * lab2xyz(x);\n y = Yn * lab2xyz(y);\n z = Zn * lab2xyz(z);\n return new Rgb(\n lrgb2rgb( 3.1338561 * x - 1.6168667 * y - 0.4906146 * z),\n lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z),\n lrgb2rgb( 0.0719453 * x - 0.2289914 * y + 1.4052427 * z),\n this.opacity\n );\n }\n}));\n\nfunction xyz2lab(t) {\n return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;\n}\n\nfunction lab2xyz(t) {\n return t > t1 ? t * t * t : t2 * (t - t0);\n}\n\nfunction lrgb2rgb(x) {\n return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);\n}\n\nfunction rgb2lrgb(x) {\n return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);\n}\n\nfunction hclConvert(o) {\n if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity);\n if (!(o instanceof Lab)) o = labConvert(o);\n if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity);\n var h = Math.atan2(o.b, o.a) * rad2deg;\n return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity);\n}\n\nexport function lch(l, c, h, opacity) {\n return arguments.length === 1 ? hclConvert(l) : new Hcl(h, c, l, opacity == null ? 1 : opacity);\n}\n\nexport function hcl(h, c, l, opacity) {\n return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity);\n}\n\nexport function Hcl(h, c, l, opacity) {\n this.h = +h;\n this.c = +c;\n this.l = +l;\n this.opacity = +opacity;\n}\n\nfunction hcl2lab(o) {\n if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity);\n var h = o.h * deg2rad;\n return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity);\n}\n\ndefine(Hcl, hcl, extend(Color, {\n brighter: function(k) {\n return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity);\n },\n darker: function(k) {\n return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity);\n },\n rgb: function() {\n return hcl2lab(this).rgb();\n }\n}));\n","export var deg2rad = Math.PI / 180;\nexport var rad2deg = 180 / Math.PI;\n","import Delaunator from \"delaunator\";\nimport Path from \"./path.js\";\nimport Polygon from \"./polygon.js\";\nimport Voronoi from \"./voronoi.js\";\n\nconst tau = 2 * Math.PI, pow = Math.pow;\n\nfunction pointX(p) {\n return p[0];\n}\n\nfunction pointY(p) {\n return p[1];\n}\n\n// A triangulation is collinear if all its triangles have a non-null area\nfunction collinear(d) {\n const {triangles, coords} = d;\n for (let i = 0; i < triangles.length; i += 3) {\n const a = 2 * triangles[i],\n b = 2 * triangles[i + 1],\n c = 2 * triangles[i + 2],\n cross = (coords[c] - coords[a]) * (coords[b + 1] - coords[a + 1])\n - (coords[b] - coords[a]) * (coords[c + 1] - coords[a + 1]);\n if (cross > 1e-10) return false;\n }\n return true;\n}\n\nfunction jitter(x, y, r) {\n return [x + Math.sin(x + y) * r, y + Math.cos(x - y) * r];\n}\n\nexport default class Delaunay {\n static from(points, fx = pointX, fy = pointY, that) {\n return new Delaunay(\"length\" in points\n ? flatArray(points, fx, fy, that)\n : Float64Array.from(flatIterable(points, fx, fy, that)));\n }\n constructor(points) {\n this._delaunator = new Delaunator(points);\n this.inedges = new Int32Array(points.length / 2);\n this._hullIndex = new Int32Array(points.length / 2);\n this.points = this._delaunator.coords;\n this._init();\n }\n update() {\n this._delaunator.update();\n this._init();\n return this;\n }\n _init() {\n const d = this._delaunator, points = this.points;\n\n // check for collinear\n if (d.hull && d.hull.length > 2 && collinear(d)) {\n this.collinear = Int32Array.from({length: points.length/2}, (_,i) => i)\n .sort((i, j) => points[2 * i] - points[2 * j] || points[2 * i + 1] - points[2 * j + 1]); // for exact neighbors\n const e = this.collinear[0], f = this.collinear[this.collinear.length - 1],\n bounds = [ points[2 * e], points[2 * e + 1], points[2 * f], points[2 * f + 1] ],\n r = 1e-8 * Math.hypot(bounds[3] - bounds[1], bounds[2] - bounds[0]);\n for (let i = 0, n = points.length / 2; i < n; ++i) {\n const p = jitter(points[2 * i], points[2 * i + 1], r);\n points[2 * i] = p[0];\n points[2 * i + 1] = p[1];\n }\n this._delaunator = new Delaunator(points);\n } else {\n delete this.collinear;\n }\n\n const halfedges = this.halfedges = this._delaunator.halfedges;\n const hull = this.hull = this._delaunator.hull;\n const triangles = this.triangles = this._delaunator.triangles;\n const inedges = this.inedges.fill(-1);\n const hullIndex = this._hullIndex.fill(-1);\n\n // Compute an index from each point to an (arbitrary) incoming halfedge\n // Used to give the first neighbor of each point; for this reason,\n // on the hull we give priority to exterior halfedges\n for (let e = 0, n = halfedges.length; e < n; ++e) {\n const p = triangles[e % 3 === 2 ? e - 2 : e + 1];\n if (halfedges[e] === -1 || inedges[p] === -1) inedges[p] = e;\n }\n for (let i = 0, n = hull.length; i < n; ++i) {\n hullIndex[hull[i]] = i;\n }\n\n // degenerate case: 1 or 2 (distinct) points\n if (hull.length <= 2 && hull.length > 0) {\n this.triangles = new Int32Array(3).fill(-1);\n this.halfedges = new Int32Array(3).fill(-1);\n this.triangles[0] = hull[0];\n this.triangles[1] = hull[1];\n this.triangles[2] = hull[1];\n inedges[hull[0]] = 1;\n if (hull.length === 2) inedges[hull[1]] = 0;\n }\n }\n voronoi(bounds) {\n return new Voronoi(this, bounds);\n }\n *neighbors(i) {\n const {inedges, hull, _hullIndex, halfedges, triangles, collinear} = this;\n\n // degenerate case with several collinear points\n if (collinear) {\n const l = collinear.indexOf(i);\n if (l > 0) yield collinear[l - 1];\n if (l < collinear.length - 1) yield collinear[l + 1];\n return;\n }\n\n const e0 = inedges[i];\n if (e0 === -1) return; // coincident point\n let e = e0, p0 = -1;\n do {\n yield p0 = triangles[e];\n e = e % 3 === 2 ? e - 2 : e + 1;\n if (triangles[e] !== i) return; // bad triangulation\n e = halfedges[e];\n if (e === -1) {\n const p = hull[(_hullIndex[i] + 1) % hull.length];\n if (p !== p0) yield p;\n return;\n }\n } while (e !== e0);\n }\n find(x, y, i = 0) {\n if ((x = +x, x !== x) || (y = +y, y !== y)) return -1;\n const i0 = i;\n let c;\n while ((c = this._step(i, x, y)) >= 0 && c !== i && c !== i0) i = c;\n return c;\n }\n _step(i, x, y) {\n const {inedges, hull, _hullIndex, halfedges, triangles, points} = this;\n if (inedges[i] === -1 || !points.length) return (i + 1) % (points.length >> 1);\n let c = i;\n let dc = pow(x - points[i * 2], 2) + pow(y - points[i * 2 + 1], 2);\n const e0 = inedges[i];\n let e = e0;\n do {\n let t = triangles[e];\n const dt = pow(x - points[t * 2], 2) + pow(y - points[t * 2 + 1], 2);\n if (dt < dc) dc = dt, c = t;\n e = e % 3 === 2 ? e - 2 : e + 1;\n if (triangles[e] !== i) break; // bad triangulation\n e = halfedges[e];\n if (e === -1) {\n e = hull[(_hullIndex[i] + 1) % hull.length];\n if (e !== t) {\n if (pow(x - points[e * 2], 2) + pow(y - points[e * 2 + 1], 2) < dc) return e;\n }\n break;\n }\n } while (e !== e0);\n return c;\n }\n render(context) {\n const buffer = context == null ? context = new Path : undefined;\n const {points, halfedges, triangles} = this;\n for (let i = 0, n = halfedges.length; i < n; ++i) {\n const j = halfedges[i];\n if (j < i) continue;\n const ti = triangles[i] * 2;\n const tj = triangles[j] * 2;\n context.moveTo(points[ti], points[ti + 1]);\n context.lineTo(points[tj], points[tj + 1]);\n }\n this.renderHull(context);\n return buffer && buffer.value();\n }\n renderPoints(context, r = 2) {\n const buffer = context == null ? context = new Path : undefined;\n const {points} = this;\n for (let i = 0, n = points.length; i < n; i += 2) {\n const x = points[i], y = points[i + 1];\n context.moveTo(x + r, y);\n context.arc(x, y, r, 0, tau);\n }\n return buffer && buffer.value();\n }\n renderHull(context) {\n const buffer = context == null ? context = new Path : undefined;\n const {hull, points} = this;\n const h = hull[0] * 2, n = hull.length;\n context.moveTo(points[h], points[h + 1]);\n for (let i = 1; i < n; ++i) {\n const h = 2 * hull[i];\n context.lineTo(points[h], points[h + 1]);\n }\n context.closePath();\n return buffer && buffer.value();\n }\n hullPolygon() {\n const polygon = new Polygon;\n this.renderHull(polygon);\n return polygon.value();\n }\n renderTriangle(i, context) {\n const buffer = context == null ? context = new Path : undefined;\n const {points, triangles} = this;\n const t0 = triangles[i *= 3] * 2;\n const t1 = triangles[i + 1] * 2;\n const t2 = triangles[i + 2] * 2;\n context.moveTo(points[t0], points[t0 + 1]);\n context.lineTo(points[t1], points[t1 + 1]);\n context.lineTo(points[t2], points[t2 + 1]);\n context.closePath();\n return buffer && buffer.value();\n }\n *trianglePolygons() {\n const {triangles} = this;\n for (let i = 0, n = triangles.length / 3; i < n; ++i) {\n yield this.trianglePolygon(i);\n }\n }\n trianglePolygon(i) {\n const polygon = new Polygon;\n this.renderTriangle(i, polygon);\n return polygon.value();\n }\n}\n\nfunction flatArray(points, fx, fy, that) {\n const n = points.length;\n const array = new Float64Array(n * 2);\n for (let i = 0; i < n; ++i) {\n const p = points[i];\n array[i * 2] = fx.call(that, p, i, points);\n array[i * 2 + 1] = fy.call(that, p, i, points);\n }\n return array;\n}\n\nfunction* flatIterable(points, fx, fy, that) {\n let i = 0;\n for (const p of points) {\n yield fx.call(that, p, i, points);\n yield fy.call(that, p, i, points);\n ++i;\n }\n}\n","const epsilon = 1e-6;\n\nexport default class Path {\n constructor() {\n this._x0 = this._y0 = // start of current subpath\n this._x1 = this._y1 = null; // end of current subpath\n this._ = \"\";\n }\n moveTo(x, y) {\n this._ += `M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}`;\n }\n closePath() {\n if (this._x1 !== null) {\n this._x1 = this._x0, this._y1 = this._y0;\n this._ += \"Z\";\n }\n }\n lineTo(x, y) {\n this._ += `L${this._x1 = +x},${this._y1 = +y}`;\n }\n arc(x, y, r) {\n x = +x, y = +y, r = +r;\n const x0 = x + r;\n const y0 = y;\n if (r < 0) throw new Error(\"negative radius\");\n if (this._x1 === null) this._ += `M${x0},${y0}`;\n else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) this._ += \"L\" + x0 + \",\" + y0;\n if (!r) return;\n this._ += `A${r},${r},0,1,1,${x - r},${y}A${r},${r},0,1,1,${this._x1 = x0},${this._y1 = y0}`;\n }\n rect(x, y, w, h) {\n this._ += `M${this._x0 = this._x1 = +x},${this._y0 = this._y1 = +y}h${+w}v${+h}h${-w}Z`;\n }\n value() {\n return this._ || null;\n }\n}\n","export default class Polygon {\n constructor() {\n this._ = [];\n }\n moveTo(x, y) {\n this._.push([x, y]);\n }\n closePath() {\n this._.push(this._[0].slice());\n }\n lineTo(x, y) {\n this._.push([x, y]);\n }\n value() {\n return this._.length ? this._ : null;\n }\n}\n","import Path from \"./path.js\";\nimport Polygon from \"./polygon.js\";\n\nexport default class Voronoi {\n constructor(delaunay, [xmin, ymin, xmax, ymax] = [0, 0, 960, 500]) {\n if (!((xmax = +xmax) >= (xmin = +xmin)) || !((ymax = +ymax) >= (ymin = +ymin))) throw new Error(\"invalid bounds\");\n this.delaunay = delaunay;\n this._circumcenters = new Float64Array(delaunay.points.length * 2);\n this.vectors = new Float64Array(delaunay.points.length * 2);\n this.xmax = xmax, this.xmin = xmin;\n this.ymax = ymax, this.ymin = ymin;\n this._init();\n }\n update() {\n this.delaunay.update();\n this._init();\n return this;\n }\n _init() {\n const {delaunay: {points, hull, triangles}, vectors} = this;\n\n // Compute circumcenters.\n const circumcenters = this.circumcenters = this._circumcenters.subarray(0, triangles.length / 3 * 2);\n for (let i = 0, j = 0, n = triangles.length, x, y; i < n; i += 3, j += 2) {\n const t1 = triangles[i] * 2;\n const t2 = triangles[i + 1] * 2;\n const t3 = triangles[i + 2] * 2;\n const x1 = points[t1];\n const y1 = points[t1 + 1];\n const x2 = points[t2];\n const y2 = points[t2 + 1];\n const x3 = points[t3];\n const y3 = points[t3 + 1];\n\n const dx = x2 - x1;\n const dy = y2 - y1;\n const ex = x3 - x1;\n const ey = y3 - y1;\n const bl = dx * dx + dy * dy;\n const cl = ex * ex + ey * ey;\n const ab = (dx * ey - dy * ex) * 2;\n\n if (!ab) {\n // degenerate case (collinear diagram)\n x = (x1 + x3) / 2 - 1e8 * ey;\n y = (y1 + y3) / 2 + 1e8 * ex;\n }\n else if (Math.abs(ab) < 1e-8) {\n // almost equal points (degenerate triangle)\n x = (x1 + x3) / 2;\n y = (y1 + y3) / 2;\n } else {\n const d = 1 / ab;\n x = x1 + (ey * bl - dy * cl) * d;\n y = y1 + (dx * cl - ex * bl) * d;\n }\n circumcenters[j] = x;\n circumcenters[j + 1] = y;\n }\n\n // Compute exterior cell rays.\n let h = hull[hull.length - 1];\n let p0, p1 = h * 4;\n let x0, x1 = points[2 * h];\n let y0, y1 = points[2 * h + 1];\n vectors.fill(0);\n for (let i = 0; i < hull.length; ++i) {\n h = hull[i];\n p0 = p1, x0 = x1, y0 = y1;\n p1 = h * 4, x1 = points[2 * h], y1 = points[2 * h + 1];\n vectors[p0 + 2] = vectors[p1] = y0 - y1;\n vectors[p0 + 3] = vectors[p1 + 1] = x1 - x0;\n }\n }\n render(context) {\n const buffer = context == null ? context = new Path : undefined;\n const {delaunay: {halfedges, inedges, hull}, circumcenters, vectors} = this;\n if (hull.length <= 1) return null;\n for (let i = 0, n = halfedges.length; i < n; ++i) {\n const j = halfedges[i];\n if (j < i) continue;\n const ti = Math.floor(i / 3) * 2;\n const tj = Math.floor(j / 3) * 2;\n const xi = circumcenters[ti];\n const yi = circumcenters[ti + 1];\n const xj = circumcenters[tj];\n const yj = circumcenters[tj + 1];\n this._renderSegment(xi, yi, xj, yj, context);\n }\n let h0, h1 = hull[hull.length - 1];\n for (let i = 0; i < hull.length; ++i) {\n h0 = h1, h1 = hull[i];\n const t = Math.floor(inedges[h1] / 3) * 2;\n const x = circumcenters[t];\n const y = circumcenters[t + 1];\n const v = h0 * 4;\n const p = this._project(x, y, vectors[v + 2], vectors[v + 3]);\n if (p) this._renderSegment(x, y, p[0], p[1], context);\n }\n return buffer && buffer.value();\n }\n renderBounds(context) {\n const buffer = context == null ? context = new Path : undefined;\n context.rect(this.xmin, this.ymin, this.xmax - this.xmin, this.ymax - this.ymin);\n return buffer && buffer.value();\n }\n renderCell(i, context) {\n const buffer = context == null ? context = new Path : undefined;\n const points = this._clip(i);\n if (points === null || !points.length) return;\n context.moveTo(points[0], points[1]);\n let n = points.length;\n while (points[0] === points[n-2] && points[1] === points[n-1] && n > 1) n -= 2;\n for (let i = 2; i < n; i += 2) {\n if (points[i] !== points[i-2] || points[i+1] !== points[i-1])\n context.lineTo(points[i], points[i + 1]);\n }\n context.closePath();\n return buffer && buffer.value();\n }\n *cellPolygons() {\n const {delaunay: {points}} = this;\n for (let i = 0, n = points.length / 2; i < n; ++i) {\n const cell = this.cellPolygon(i);\n if (cell) cell.index = i, yield cell;\n }\n }\n cellPolygon(i) {\n const polygon = new Polygon;\n this.renderCell(i, polygon);\n return polygon.value();\n }\n _renderSegment(x0, y0, x1, y1, context) {\n let S;\n const c0 = this._regioncode(x0, y0);\n const c1 = this._regioncode(x1, y1);\n if (c0 === 0 && c1 === 0) {\n context.moveTo(x0, y0);\n context.lineTo(x1, y1);\n } else if (S = this._clipSegment(x0, y0, x1, y1, c0, c1)) {\n context.moveTo(S[0], S[1]);\n context.lineTo(S[2], S[3]);\n }\n }\n contains(i, x, y) {\n if ((x = +x, x !== x) || (y = +y, y !== y)) return false;\n return this.delaunay._step(i, x, y) === i;\n }\n *neighbors(i) {\n const ci = this._clip(i);\n if (ci) for (const j of this.delaunay.neighbors(i)) {\n const cj = this._clip(j);\n // find the common edge\n if (cj) loop: for (let ai = 0, li = ci.length; ai < li; ai += 2) {\n for (let aj = 0, lj = cj.length; aj < lj; aj += 2) {\n if (ci[ai] == cj[aj]\n && ci[ai + 1] == cj[aj + 1]\n && ci[(ai + 2) % li] == cj[(aj + lj - 2) % lj]\n && ci[(ai + 3) % li] == cj[(aj + lj - 1) % lj]\n ) {\n yield j;\n break loop;\n }\n }\n }\n }\n }\n _cell(i) {\n const {circumcenters, delaunay: {inedges, halfedges, triangles}} = this;\n const e0 = inedges[i];\n if (e0 === -1) return null; // coincident point\n const points = [];\n let e = e0;\n do {\n const t = Math.floor(e / 3);\n points.push(circumcenters[t * 2], circumcenters[t * 2 + 1]);\n e = e % 3 === 2 ? e - 2 : e + 1;\n if (triangles[e] !== i) break; // bad triangulation\n e = halfedges[e];\n } while (e !== e0 && e !== -1);\n return points;\n }\n _clip(i) {\n // degenerate case (1 valid point: return the box)\n if (i === 0 && this.delaunay.hull.length === 1) {\n return [this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax, this.xmin, this.ymin];\n }\n const points = this._cell(i);\n if (points === null) return null;\n const {vectors: V} = this;\n const v = i * 4;\n return V[v] || V[v + 1]\n ? this._clipInfinite(i, points, V[v], V[v + 1], V[v + 2], V[v + 3])\n : this._clipFinite(i, points);\n }\n _clipFinite(i, points) {\n const n = points.length;\n let P = null;\n let x0, y0, x1 = points[n - 2], y1 = points[n - 1];\n let c0, c1 = this._regioncode(x1, y1);\n let e0, e1;\n for (let j = 0; j < n; j += 2) {\n x0 = x1, y0 = y1, x1 = points[j], y1 = points[j + 1];\n c0 = c1, c1 = this._regioncode(x1, y1);\n if (c0 === 0 && c1 === 0) {\n e0 = e1, e1 = 0;\n if (P) P.push(x1, y1);\n else P = [x1, y1];\n } else {\n let S, sx0, sy0, sx1, sy1;\n if (c0 === 0) {\n if ((S = this._clipSegment(x0, y0, x1, y1, c0, c1)) === null) continue;\n [sx0, sy0, sx1, sy1] = S;\n } else {\n if ((S = this._clipSegment(x1, y1, x0, y0, c1, c0)) === null) continue;\n [sx1, sy1, sx0, sy0] = S;\n e0 = e1, e1 = this._edgecode(sx0, sy0);\n if (e0 && e1) this._edge(i, e0, e1, P, P.length);\n if (P) P.push(sx0, sy0);\n else P = [sx0, sy0];\n }\n e0 = e1, e1 = this._edgecode(sx1, sy1);\n if (e0 && e1) this._edge(i, e0, e1, P, P.length);\n if (P) P.push(sx1, sy1);\n else P = [sx1, sy1];\n }\n }\n if (P) {\n e0 = e1, e1 = this._edgecode(P[0], P[1]);\n if (e0 && e1) this._edge(i, e0, e1, P, P.length);\n } else if (this.contains(i, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) {\n return [this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax, this.xmin, this.ymin];\n }\n return P;\n }\n _clipSegment(x0, y0, x1, y1, c0, c1) {\n while (true) {\n if (c0 === 0 && c1 === 0) return [x0, y0, x1, y1];\n if (c0 & c1) return null;\n let x, y, c = c0 || c1;\n if (c & 0b1000) x = x0 + (x1 - x0) * (this.ymax - y0) / (y1 - y0), y = this.ymax;\n else if (c & 0b0100) x = x0 + (x1 - x0) * (this.ymin - y0) / (y1 - y0), y = this.ymin;\n else if (c & 0b0010) y = y0 + (y1 - y0) * (this.xmax - x0) / (x1 - x0), x = this.xmax;\n else y = y0 + (y1 - y0) * (this.xmin - x0) / (x1 - x0), x = this.xmin;\n if (c0) x0 = x, y0 = y, c0 = this._regioncode(x0, y0);\n else x1 = x, y1 = y, c1 = this._regioncode(x1, y1);\n }\n }\n _clipInfinite(i, points, vx0, vy0, vxn, vyn) {\n let P = Array.from(points), p;\n if (p = this._project(P[0], P[1], vx0, vy0)) P.unshift(p[0], p[1]);\n if (p = this._project(P[P.length - 2], P[P.length - 1], vxn, vyn)) P.push(p[0], p[1]);\n if (P = this._clipFinite(i, P)) {\n for (let j = 0, n = P.length, c0, c1 = this._edgecode(P[n - 2], P[n - 1]); j < n; j += 2) {\n c0 = c1, c1 = this._edgecode(P[j], P[j + 1]);\n if (c0 && c1) j = this._edge(i, c0, c1, P, j), n = P.length;\n }\n } else if (this.contains(i, (this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2)) {\n P = [this.xmin, this.ymin, this.xmax, this.ymin, this.xmax, this.ymax, this.xmin, this.ymax];\n }\n return P;\n }\n _edge(i, e0, e1, P, j) {\n while (e0 !== e1) {\n let x, y;\n switch (e0) {\n case 0b0101: e0 = 0b0100; continue; // top-left\n case 0b0100: e0 = 0b0110, x = this.xmax, y = this.ymin; break; // top\n case 0b0110: e0 = 0b0010; continue; // top-right\n case 0b0010: e0 = 0b1010, x = this.xmax, y = this.ymax; break; // right\n case 0b1010: e0 = 0b1000; continue; // bottom-right\n case 0b1000: e0 = 0b1001, x = this.xmin, y = this.ymax; break; // bottom\n case 0b1001: e0 = 0b0001; continue; // bottom-left\n case 0b0001: e0 = 0b0101, x = this.xmin, y = this.ymin; break; // left\n }\n if ((P[j] !== x || P[j + 1] !== y) && this.contains(i, x, y)) {\n P.splice(j, 0, x, y), j += 2;\n }\n }\n if (P.length > 4) {\n for (let i = 0; i < P.length; i+= 2) {\n const j = (i + 2) % P.length, k = (i + 4) % P.length;\n if (P[i] === P[j] && P[j] === P[k]\n || P[i + 1] === P[j + 1] && P[j + 1] === P[k + 1])\n P.splice(j, 2), i -= 2;\n }\n }\n return j;\n }\n _project(x0, y0, vx, vy) {\n let t = Infinity, c, x, y;\n if (vy < 0) { // top\n if (y0 <= this.ymin) return null;\n if ((c = (this.ymin - y0) / vy) < t) y = this.ymin, x = x0 + (t = c) * vx;\n } else if (vy > 0) { // bottom\n if (y0 >= this.ymax) return null;\n if ((c = (this.ymax - y0) / vy) < t) y = this.ymax, x = x0 + (t = c) * vx;\n }\n if (vx > 0) { // right\n if (x0 >= this.xmax) return null;\n if ((c = (this.xmax - x0) / vx) < t) x = this.xmax, y = y0 + (t = c) * vy;\n } else if (vx < 0) { // left\n if (x0 <= this.xmin) return null;\n if ((c = (this.xmin - x0) / vx) < t) x = this.xmin, y = y0 + (t = c) * vy;\n }\n return [x, y];\n }\n _edgecode(x, y) {\n return (x === this.xmin ? 0b0001\n : x === this.xmax ? 0b0010 : 0b0000)\n | (y === this.ymin ? 0b0100\n : y === this.ymax ? 0b1000 : 0b0000);\n }\n _regioncode(x, y) {\n return (x < this.xmin ? 0b0001\n : x > this.xmax ? 0b0010 : 0b0000)\n | (y < this.ymin ? 0b0100\n : y > this.ymax ? 0b1000 : 0b0000);\n }\n}\n","var noop = {value: function() {}};\n\nfunction dispatch() {\n for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) {\n if (!(t = arguments[i] + \"\") || (t in _) || /[\\s.]/.test(t)) throw new Error(\"illegal type: \" + t);\n _[t] = [];\n }\n return new Dispatch(_);\n}\n\nfunction Dispatch(_) {\n this._ = _;\n}\n\nfunction parseTypenames(typenames, types) {\n return typenames.trim().split(/^|\\s+/).map(function(t) {\n var name = \"\", i = t.indexOf(\".\");\n if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);\n if (t && !types.hasOwnProperty(t)) throw new Error(\"unknown type: \" + t);\n return {type: t, name: name};\n });\n}\n\nDispatch.prototype = dispatch.prototype = {\n constructor: Dispatch,\n on: function(typename, callback) {\n var _ = this._,\n T = parseTypenames(typename + \"\", _),\n t,\n i = -1,\n n = T.length;\n\n // If no callback was specified, return the callback of the given type and name.\n if (arguments.length < 2) {\n while (++i < n) if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) return t;\n return;\n }\n\n // If a type was specified, set the callback for the given type and name.\n // Otherwise, if a null callback was specified, remove callbacks of the given name.\n if (callback != null && typeof callback !== \"function\") throw new Error(\"invalid callback: \" + callback);\n while (++i < n) {\n if (t = (typename = T[i]).type) _[t] = set(_[t], typename.name, callback);\n else if (callback == null) for (t in _) _[t] = set(_[t], typename.name, null);\n }\n\n return this;\n },\n copy: function() {\n var copy = {}, _ = this._;\n for (var t in _) copy[t] = _[t].slice();\n return new Dispatch(copy);\n },\n call: function(type, that) {\n if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2];\n if (!this._.hasOwnProperty(type)) throw new Error(\"unknown type: \" + type);\n for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);\n },\n apply: function(type, that, args) {\n if (!this._.hasOwnProperty(type)) throw new Error(\"unknown type: \" + type);\n for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args);\n }\n};\n\nfunction get(type, name) {\n for (var i = 0, n = type.length, c; i < n; ++i) {\n if ((c = type[i]).name === name) {\n return c.value;\n }\n }\n}\n\nfunction set(type, name, callback) {\n for (var i = 0, n = type.length; i < n; ++i) {\n if (type[i].name === name) {\n type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1));\n break;\n }\n }\n if (callback != null) type.push({name: name, value: callback});\n return type;\n}\n\nexport default dispatch;\n","export {default as dispatch} from \"./dispatch.js\";\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","import {dispatch} from \"d3-dispatch\";\nimport {event, customEvent, select, mouse, touch} from \"d3-selection\";\nimport nodrag, {yesdrag} from \"./nodrag.js\";\nimport noevent, {nopropagation} from \"./noevent.js\";\nimport constant from \"./constant.js\";\nimport DragEvent from \"./event.js\";\n\n// Ignore right-click, since that should open the context menu.\nfunction defaultFilter() {\n return !event.ctrlKey && !event.button;\n}\n\nfunction defaultContainer() {\n return this.parentNode;\n}\n\nfunction defaultSubject(d) {\n return d == null ? {x: event.x, y: event.y} : d;\n}\n\nfunction defaultTouchable() {\n return navigator.maxTouchPoints || (\"ontouchstart\" in this);\n}\n\nexport default function() {\n var filter = defaultFilter,\n container = defaultContainer,\n subject = defaultSubject,\n touchable = defaultTouchable,\n gestures = {},\n listeners = dispatch(\"start\", \"drag\", \"end\"),\n active = 0,\n mousedownx,\n mousedowny,\n mousemoving,\n touchending,\n clickDistance2 = 0;\n\n function drag(selection) {\n selection\n .on(\"mousedown.drag\", mousedowned)\n .filter(touchable)\n .on(\"touchstart.drag\", touchstarted)\n .on(\"touchmove.drag\", touchmoved)\n .on(\"touchend.drag touchcancel.drag\", touchended)\n .style(\"touch-action\", \"none\")\n .style(\"-webkit-tap-highlight-color\", \"rgba(0,0,0,0)\");\n }\n\n function mousedowned() {\n if (touchending || !filter.apply(this, arguments)) return;\n var gesture = beforestart(\"mouse\", container.apply(this, arguments), mouse, this, arguments);\n if (!gesture) return;\n select(event.view).on(\"mousemove.drag\", mousemoved, true).on(\"mouseup.drag\", mouseupped, true);\n nodrag(event.view);\n nopropagation();\n mousemoving = false;\n mousedownx = event.clientX;\n mousedowny = event.clientY;\n gesture(\"start\");\n }\n\n function mousemoved() {\n noevent();\n if (!mousemoving) {\n var dx = event.clientX - mousedownx, dy = event.clientY - mousedowny;\n mousemoving = dx * dx + dy * dy > clickDistance2;\n }\n gestures.mouse(\"drag\");\n }\n\n function mouseupped() {\n select(event.view).on(\"mousemove.drag mouseup.drag\", null);\n yesdrag(event.view, mousemoving);\n noevent();\n gestures.mouse(\"end\");\n }\n\n function touchstarted() {\n if (!filter.apply(this, arguments)) return;\n var touches = event.changedTouches,\n c = container.apply(this, arguments),\n n = touches.length, i, gesture;\n\n for (i = 0; i < n; ++i) {\n if (gesture = beforestart(touches[i].identifier, c, touch, this, arguments)) {\n nopropagation();\n gesture(\"start\");\n }\n }\n }\n\n function touchmoved() {\n var touches = event.changedTouches,\n n = touches.length, i, gesture;\n\n for (i = 0; i < n; ++i) {\n if (gesture = gestures[touches[i].identifier]) {\n noevent();\n gesture(\"drag\");\n }\n }\n }\n\n function touchended() {\n var touches = event.changedTouches,\n n = touches.length, i, gesture;\n\n if (touchending) clearTimeout(touchending);\n touchending = setTimeout(function() { touchending = null; }, 500); // Ghost clicks are delayed!\n for (i = 0; i < n; ++i) {\n if (gesture = gestures[touches[i].identifier]) {\n nopropagation();\n gesture(\"end\");\n }\n }\n }\n\n function beforestart(id, container, point, that, args) {\n var p = point(container, id), s, dx, dy,\n sublisteners = listeners.copy();\n\n if (!customEvent(new DragEvent(drag, \"beforestart\", s, id, active, p[0], p[1], 0, 0, sublisteners), function() {\n if ((event.subject = s = subject.apply(that, args)) == null) return false;\n dx = s.x - p[0] || 0;\n dy = s.y - p[1] || 0;\n return true;\n })) return;\n\n return function gesture(type) {\n var p0 = p, n;\n switch (type) {\n case \"start\": gestures[id] = gesture, n = active++; break;\n case \"end\": delete gestures[id], --active; // nobreak\n case \"drag\": p = point(container, id), n = active; break;\n }\n customEvent(new DragEvent(drag, type, s, id, n, p[0] + dx, p[1] + dy, p[0] - p0[0], p[1] - p0[1], sublisteners), sublisteners.apply, sublisteners, [type, that, args]);\n };\n }\n\n drag.filter = function(_) {\n return arguments.length ? (filter = typeof _ === \"function\" ? _ : constant(!!_), drag) : filter;\n };\n\n drag.container = function(_) {\n return arguments.length ? (container = typeof _ === \"function\" ? _ : constant(_), drag) : container;\n };\n\n drag.subject = function(_) {\n return arguments.length ? (subject = typeof _ === \"function\" ? _ : constant(_), drag) : subject;\n };\n\n drag.touchable = function(_) {\n return arguments.length ? (touchable = typeof _ === \"function\" ? _ : constant(!!_), drag) : touchable;\n };\n\n drag.on = function() {\n var value = listeners.on.apply(listeners, arguments);\n return value === listeners ? drag : value;\n };\n\n drag.clickDistance = function(_) {\n return arguments.length ? (clickDistance2 = (_ = +_) * _, drag) : Math.sqrt(clickDistance2);\n };\n\n return drag;\n}\n","export default function DragEvent(target, type, subject, id, active, x, y, dx, dy, dispatch) {\n this.target = target;\n this.type = type;\n this.subject = subject;\n this.identifier = id;\n this.active = active;\n this.x = x;\n this.y = y;\n this.dx = dx;\n this.dy = dy;\n this._ = dispatch;\n}\n\nDragEvent.prototype.on = function() {\n var value = this._.on.apply(this._, arguments);\n return value === this._ ? this : value;\n};\n","export {default as drag} from \"./drag.js\";\nexport {default as dragDisable, yesdrag as dragEnable} from \"./nodrag.js\";\n","import {select} from \"d3-selection\";\nimport noevent from \"./noevent.js\";\n\nexport default function(view) {\n var root = view.document.documentElement,\n selection = select(view).on(\"dragstart.drag\", noevent, true);\n if (\"onselectstart\" in root) {\n selection.on(\"selectstart.drag\", noevent, true);\n } else {\n root.__noselect = root.style.MozUserSelect;\n root.style.MozUserSelect = \"none\";\n }\n}\n\nexport function yesdrag(view, noclick) {\n var root = view.document.documentElement,\n selection = select(view).on(\"dragstart.drag\", null);\n if (noclick) {\n selection.on(\"click.drag\", noevent, true);\n setTimeout(function() { selection.on(\"click.drag\", null); }, 0);\n }\n if (\"onselectstart\" in root) {\n selection.on(\"selectstart.drag\", null);\n } else {\n root.style.MozUserSelect = root.__noselect;\n delete root.__noselect;\n }\n}\n","import {event} from \"d3-selection\";\n\nexport function nopropagation() {\n event.stopImmediatePropagation();\n}\n\nexport default function() {\n event.preventDefault();\n event.stopImmediatePropagation();\n}\n","export default function autoType(object) {\n for (var key in object) {\n var value = object[key].trim(), number, m;\n if (!value) value = null;\n else if (value === \"true\") value = true;\n else if (value === \"false\") value = false;\n else if (value === \"NaN\") value = NaN;\n else if (!isNaN(number = +value)) value = number;\n else if (m = value.match(/^([-+]\\d{2})?\\d{4}(-\\d{2}(-\\d{2})?)?(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d{3})?)?(Z|[-+]\\d{2}:\\d{2})?)?$/)) {\n if (fixtz && !!m[4] && !m[7]) value = value.replace(/-/g, \"/\").replace(/T/, \" \");\n value = new Date(value);\n }\n else continue;\n object[key] = value;\n }\n return object;\n}\n\n// https://github.com/d3/d3-dsv/issues/45\nvar fixtz = new Date(\"2019-01-01T00:00\").getHours() || new Date(\"2019-07-01T00:00\").getHours();","import dsv from \"./dsv.js\";\n\nvar csv = dsv(\",\");\n\nexport var csvParse = csv.parse;\nexport var csvParseRows = csv.parseRows;\nexport var csvFormat = csv.format;\nexport var csvFormatBody = csv.formatBody;\nexport var csvFormatRows = csv.formatRows;\nexport var csvFormatRow = csv.formatRow;\nexport var csvFormatValue = csv.formatValue;\n","var EOL = {},\n EOF = {},\n QUOTE = 34,\n NEWLINE = 10,\n RETURN = 13;\n\nfunction objectConverter(columns) {\n return new Function(\"d\", \"return {\" + columns.map(function(name, i) {\n return JSON.stringify(name) + \": d[\" + i + \"] || \\\"\\\"\";\n }).join(\",\") + \"}\");\n}\n\nfunction customConverter(columns, f) {\n var object = objectConverter(columns);\n return function(row, i) {\n return f(object(row), i, columns);\n };\n}\n\n// Compute unique columns in order of discovery.\nfunction inferColumns(rows) {\n var columnSet = Object.create(null),\n columns = [];\n\n rows.forEach(function(row) {\n for (var column in row) {\n if (!(column in columnSet)) {\n columns.push(columnSet[column] = column);\n }\n }\n });\n\n return columns;\n}\n\nfunction pad(value, width) {\n var s = value + \"\", length = s.length;\n return length < width ? new Array(width - length + 1).join(0) + s : s;\n}\n\nfunction formatYear(year) {\n return year < 0 ? \"-\" + pad(-year, 6)\n : year > 9999 ? \"+\" + pad(year, 6)\n : pad(year, 4);\n}\n\nfunction formatDate(date) {\n var hours = date.getUTCHours(),\n minutes = date.getUTCMinutes(),\n seconds = date.getUTCSeconds(),\n milliseconds = date.getUTCMilliseconds();\n return isNaN(date) ? \"Invalid Date\"\n : formatYear(date.getUTCFullYear(), 4) + \"-\" + pad(date.getUTCMonth() + 1, 2) + \"-\" + pad(date.getUTCDate(), 2)\n + (milliseconds ? \"T\" + pad(hours, 2) + \":\" + pad(minutes, 2) + \":\" + pad(seconds, 2) + \".\" + pad(milliseconds, 3) + \"Z\"\n : seconds ? \"T\" + pad(hours, 2) + \":\" + pad(minutes, 2) + \":\" + pad(seconds, 2) + \"Z\"\n : minutes || hours ? \"T\" + pad(hours, 2) + \":\" + pad(minutes, 2) + \"Z\"\n : \"\");\n}\n\nexport default function(delimiter) {\n var reFormat = new RegExp(\"[\\\"\" + delimiter + \"\\n\\r]\"),\n DELIMITER = delimiter.charCodeAt(0);\n\n function parse(text, f) {\n var convert, columns, rows = parseRows(text, function(row, i) {\n if (convert) return convert(row, i - 1);\n columns = row, convert = f ? customConverter(row, f) : objectConverter(row);\n });\n rows.columns = columns || [];\n return rows;\n }\n\n function parseRows(text, f) {\n var rows = [], // output rows\n N = text.length,\n I = 0, // current character index\n n = 0, // current line number\n t, // current token\n eof = N <= 0, // current token followed by EOF?\n eol = false; // current token followed by EOL?\n\n // Strip the trailing newline.\n if (text.charCodeAt(N - 1) === NEWLINE) --N;\n if (text.charCodeAt(N - 1) === RETURN) --N;\n\n function token() {\n if (eof) return EOF;\n if (eol) return eol = false, EOL;\n\n // Unescape quotes.\n var i, j = I, c;\n if (text.charCodeAt(j) === QUOTE) {\n while (I++ < N && text.charCodeAt(I) !== QUOTE || text.charCodeAt(++I) === QUOTE);\n if ((i = I) >= N) eof = true;\n else if ((c = text.charCodeAt(I++)) === NEWLINE) eol = true;\n else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }\n return text.slice(j + 1, i - 1).replace(/\"\"/g, \"\\\"\");\n }\n\n // Find next delimiter or newline.\n while (I < N) {\n if ((c = text.charCodeAt(i = I++)) === NEWLINE) eol = true;\n else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; }\n else if (c !== DELIMITER) continue;\n return text.slice(j, i);\n }\n\n // Return last token before EOF.\n return eof = true, text.slice(j, N);\n }\n\n while ((t = token()) !== EOF) {\n var row = [];\n while (t !== EOL && t !== EOF) row.push(t), t = token();\n if (f && (row = f(row, n++)) == null) continue;\n rows.push(row);\n }\n\n return rows;\n }\n\n function preformatBody(rows, columns) {\n return rows.map(function(row) {\n return columns.map(function(column) {\n return formatValue(row[column]);\n }).join(delimiter);\n });\n }\n\n function format(rows, columns) {\n if (columns == null) columns = inferColumns(rows);\n return [columns.map(formatValue).join(delimiter)].concat(preformatBody(rows, columns)).join(\"\\n\");\n }\n\n function formatBody(rows, columns) {\n if (columns == null) columns = inferColumns(rows);\n return preformatBody(rows, columns).join(\"\\n\");\n }\n\n function formatRows(rows) {\n return rows.map(formatRow).join(\"\\n\");\n }\n\n function formatRow(row) {\n return row.map(formatValue).join(delimiter);\n }\n\n function formatValue(value) {\n return value == null ? \"\"\n : value instanceof Date ? formatDate(value)\n : reFormat.test(value += \"\") ? \"\\\"\" + value.replace(/\"/g, \"\\\"\\\"\") + \"\\\"\"\n : value;\n }\n\n return {\n parse: parse,\n parseRows: parseRows,\n format: format,\n formatBody: formatBody,\n formatRows: formatRows,\n formatRow: formatRow,\n formatValue: formatValue\n };\n}\n","export {default as dsvFormat} from \"./dsv.js\";\nexport {csvParse, csvParseRows, csvFormat, csvFormatBody, csvFormatRows, csvFormatRow, csvFormatValue} from \"./csv.js\";\nexport {tsvParse, tsvParseRows, tsvFormat, tsvFormatBody, tsvFormatRows, tsvFormatRow, tsvFormatValue} from \"./tsv.js\";\nexport {default as autoType} from \"./autoType.js\";\n","import dsv from \"./dsv.js\";\n\nvar tsv = dsv(\"\\t\");\n\nexport var tsvParse = tsv.parse;\nexport var tsvParseRows = tsv.parseRows;\nexport var tsvFormat = tsv.format;\nexport var tsvFormatBody = tsv.formatBody;\nexport var tsvFormatRows = tsv.formatRows;\nexport var tsvFormatRow = tsv.formatRow;\nexport var tsvFormatValue = tsv.formatValue;\n","var overshoot = 1.70158;\n\nexport var backIn = (function custom(s) {\n s = +s;\n\n function backIn(t) {\n return (t = +t) * t * (s * (t - 1) + t);\n }\n\n backIn.overshoot = custom;\n\n return backIn;\n})(overshoot);\n\nexport var backOut = (function custom(s) {\n s = +s;\n\n function backOut(t) {\n return --t * t * ((t + 1) * s + t) + 1;\n }\n\n backOut.overshoot = custom;\n\n return backOut;\n})(overshoot);\n\nexport var backInOut = (function custom(s) {\n s = +s;\n\n function backInOut(t) {\n return ((t *= 2) < 1 ? t * t * ((s + 1) * t - s) : (t -= 2) * t * ((s + 1) * t + s) + 2) / 2;\n }\n\n backInOut.overshoot = custom;\n\n return backInOut;\n})(overshoot);\n","var b1 = 4 / 11,\n b2 = 6 / 11,\n b3 = 8 / 11,\n b4 = 3 / 4,\n b5 = 9 / 11,\n b6 = 10 / 11,\n b7 = 15 / 16,\n b8 = 21 / 22,\n b9 = 63 / 64,\n b0 = 1 / b1 / b1;\n\nexport function bounceIn(t) {\n return 1 - bounceOut(1 - t);\n}\n\nexport function bounceOut(t) {\n return (t = +t) < b1 ? b0 * t * t : t < b3 ? b0 * (t -= b2) * t + b4 : t < b6 ? b0 * (t -= b5) * t + b7 : b0 * (t -= b8) * t + b9;\n}\n\nexport function bounceInOut(t) {\n return ((t *= 2) <= 1 ? 1 - bounceOut(1 - t) : bounceOut(t - 1) + 1) / 2;\n}\n","export function circleIn(t) {\n return 1 - Math.sqrt(1 - t * t);\n}\n\nexport function circleOut(t) {\n return Math.sqrt(1 - --t * t);\n}\n\nexport function circleInOut(t) {\n return ((t *= 2) <= 1 ? 1 - Math.sqrt(1 - t * t) : Math.sqrt(1 - (t -= 2) * t) + 1) / 2;\n}\n","export function cubicIn(t) {\n return t * t * t;\n}\n\nexport function cubicOut(t) {\n return --t * t * t + 1;\n}\n\nexport function cubicInOut(t) {\n return ((t *= 2) <= 1 ? t * t * t : (t -= 2) * t * t + 2) / 2;\n}\n","import {tpmt} from \"./math.js\";\n\nvar tau = 2 * Math.PI,\n amplitude = 1,\n period = 0.3;\n\nexport var elasticIn = (function custom(a, p) {\n var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);\n\n function elasticIn(t) {\n return a * tpmt(-(--t)) * Math.sin((s - t) / p);\n }\n\n elasticIn.amplitude = function(a) { return custom(a, p * tau); };\n elasticIn.period = function(p) { return custom(a, p); };\n\n return elasticIn;\n})(amplitude, period);\n\nexport var elasticOut = (function custom(a, p) {\n var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);\n\n function elasticOut(t) {\n return 1 - a * tpmt(t = +t) * Math.sin((t + s) / p);\n }\n\n elasticOut.amplitude = function(a) { return custom(a, p * tau); };\n elasticOut.period = function(p) { return custom(a, p); };\n\n return elasticOut;\n})(amplitude, period);\n\nexport var elasticInOut = (function custom(a, p) {\n var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau);\n\n function elasticInOut(t) {\n return ((t = t * 2 - 1) < 0\n ? a * tpmt(-t) * Math.sin((s - t) / p)\n : 2 - a * tpmt(t) * Math.sin((s + t) / p)) / 2;\n }\n\n elasticInOut.amplitude = function(a) { return custom(a, p * tau); };\n elasticInOut.period = function(p) { return custom(a, p); };\n\n return elasticInOut;\n})(amplitude, period);\n","import {tpmt} from \"./math.js\";\n\nexport function expIn(t) {\n return tpmt(1 - +t);\n}\n\nexport function expOut(t) {\n return 1 - tpmt(t);\n}\n\nexport function expInOut(t) {\n return ((t *= 2) <= 1 ? tpmt(1 - t) : 2 - tpmt(t - 1)) / 2;\n}\n","export {\n linear as easeLinear\n} from \"./linear.js\";\n\nexport {\n quadInOut as easeQuad,\n quadIn as easeQuadIn,\n quadOut as easeQuadOut,\n quadInOut as easeQuadInOut\n} from \"./quad.js\";\n\nexport {\n cubicInOut as easeCubic,\n cubicIn as easeCubicIn,\n cubicOut as easeCubicOut,\n cubicInOut as easeCubicInOut\n} from \"./cubic.js\";\n\nexport {\n polyInOut as easePoly,\n polyIn as easePolyIn,\n polyOut as easePolyOut,\n polyInOut as easePolyInOut\n} from \"./poly.js\";\n\nexport {\n sinInOut as easeSin,\n sinIn as easeSinIn,\n sinOut as easeSinOut,\n sinInOut as easeSinInOut\n} from \"./sin.js\";\n\nexport {\n expInOut as easeExp,\n expIn as easeExpIn,\n expOut as easeExpOut,\n expInOut as easeExpInOut\n} from \"./exp.js\";\n\nexport {\n circleInOut as easeCircle,\n circleIn as easeCircleIn,\n circleOut as easeCircleOut,\n circleInOut as easeCircleInOut\n} from \"./circle.js\";\n\nexport {\n bounceOut as easeBounce,\n bounceIn as easeBounceIn,\n bounceOut as easeBounceOut,\n bounceInOut as easeBounceInOut\n} from \"./bounce.js\";\n\nexport {\n backInOut as easeBack,\n backIn as easeBackIn,\n backOut as easeBackOut,\n backInOut as easeBackInOut\n} from \"./back.js\";\n\nexport {\n elasticOut as easeElastic,\n elasticIn as easeElasticIn,\n elasticOut as easeElasticOut,\n elasticInOut as easeElasticInOut\n} from \"./elastic.js\";\n","export function linear(t) {\n return +t;\n}\n","// tpmt is two power minus ten times t scaled to [0,1]\nexport function tpmt(x) {\n return (Math.pow(2, -10 * x) - 0.0009765625) * 1.0009775171065494;\n}\n","var exponent = 3;\n\nexport var polyIn = (function custom(e) {\n e = +e;\n\n function polyIn(t) {\n return Math.pow(t, e);\n }\n\n polyIn.exponent = custom;\n\n return polyIn;\n})(exponent);\n\nexport var polyOut = (function custom(e) {\n e = +e;\n\n function polyOut(t) {\n return 1 - Math.pow(1 - t, e);\n }\n\n polyOut.exponent = custom;\n\n return polyOut;\n})(exponent);\n\nexport var polyInOut = (function custom(e) {\n e = +e;\n\n function polyInOut(t) {\n return ((t *= 2) <= 1 ? Math.pow(t, e) : 2 - Math.pow(2 - t, e)) / 2;\n }\n\n polyInOut.exponent = custom;\n\n return polyInOut;\n})(exponent);\n","export function quadIn(t) {\n return t * t;\n}\n\nexport function quadOut(t) {\n return t * (2 - t);\n}\n\nexport function quadInOut(t) {\n return ((t *= 2) <= 1 ? t * t : --t * (2 - t) + 1) / 2;\n}\n","var pi = Math.PI,\n halfPi = pi / 2;\n\nexport function sinIn(t) {\n return (+t === 1) ? 1 : 1 - Math.cos(t * halfPi);\n}\n\nexport function sinOut(t) {\n return Math.sin(t * halfPi);\n}\n\nexport function sinInOut(t) {\n return (1 - Math.cos(pi * t)) / 2;\n}\n","function responseBlob(response) {\n if (!response.ok) throw new Error(response.status + \" \" + response.statusText);\n return response.blob();\n}\n\nexport default function(input, init) {\n return fetch(input, init).then(responseBlob);\n}\n","function responseArrayBuffer(response) {\n if (!response.ok) throw new Error(response.status + \" \" + response.statusText);\n return response.arrayBuffer();\n}\n\nexport default function(input, init) {\n return fetch(input, init).then(responseArrayBuffer);\n}\n","import {csvParse, dsvFormat, tsvParse} from \"d3-dsv\";\nimport text from \"./text.js\";\n\nfunction dsvParse(parse) {\n return function(input, init, row) {\n if (arguments.length === 2 && typeof init === \"function\") row = init, init = undefined;\n return text(input, init).then(function(response) {\n return parse(response, row);\n });\n };\n}\n\nexport default function dsv(delimiter, input, init, row) {\n if (arguments.length === 3 && typeof init === \"function\") row = init, init = undefined;\n var format = dsvFormat(delimiter);\n return text(input, init).then(function(response) {\n return format.parse(response, row);\n });\n}\n\nexport var csv = dsvParse(csvParse);\nexport var tsv = dsvParse(tsvParse);\n","export default function(input, init) {\n return new Promise(function(resolve, reject) {\n var image = new Image;\n for (var key in init) image[key] = init[key];\n image.onerror = reject;\n image.onload = function() { resolve(image); };\n image.src = input;\n });\n}\n","export {default as blob} from \"./blob.js\";\nexport {default as buffer} from \"./buffer.js\";\nexport {default as dsv, csv, tsv} from \"./dsv.js\";\nexport {default as image} from \"./image.js\";\nexport {default as json} from \"./json.js\";\nexport {default as text} from \"./text.js\";\nexport {default as xml, html, svg} from \"./xml.js\";\n","function responseJson(response) {\n if (!response.ok) throw new Error(response.status + \" \" + response.statusText);\n if (response.status === 204 || response.status === 205) return;\n return response.json();\n}\n\nexport default function(input, init) {\n return fetch(input, init).then(responseJson);\n}\n","function responseText(response) {\n if (!response.ok) throw new Error(response.status + \" \" + response.statusText);\n return response.text();\n}\n\nexport default function(input, init) {\n return fetch(input, init).then(responseText);\n}\n","import text from \"./text.js\";\n\nfunction parser(type) {\n return function(input, init) {\n return text(input, init).then(function(text) {\n return (new DOMParser).parseFromString(text, type);\n });\n };\n}\n\nexport default parser(\"application/xml\");\n\nexport var html = parser(\"text/html\");\n\nexport var svg = parser(\"image/svg+xml\");\n","export default function(x, y) {\n var nodes;\n\n if (x == null) x = 0;\n if (y == null) y = 0;\n\n function force() {\n var i,\n n = nodes.length,\n node,\n sx = 0,\n sy = 0;\n\n for (i = 0; i < n; ++i) {\n node = nodes[i], sx += node.x, sy += node.y;\n }\n\n for (sx = sx / n - x, sy = sy / n - y, i = 0; i < n; ++i) {\n node = nodes[i], node.x -= sx, node.y -= sy;\n }\n }\n\n force.initialize = function(_) {\n nodes = _;\n };\n\n force.x = function(_) {\n return arguments.length ? (x = +_, force) : x;\n };\n\n force.y = function(_) {\n return arguments.length ? (y = +_, force) : y;\n };\n\n return force;\n}\n","import constant from \"./constant\";\nimport jiggle from \"./jiggle\";\nimport {quadtree} from \"d3-quadtree\";\n\nfunction x(d) {\n return d.x + d.vx;\n}\n\nfunction y(d) {\n return d.y + d.vy;\n}\n\nexport default function(radius) {\n var nodes,\n radii,\n strength = 1,\n iterations = 1;\n\n if (typeof radius !== \"function\") radius = constant(radius == null ? 1 : +radius);\n\n function force() {\n var i, n = nodes.length,\n tree,\n node,\n xi,\n yi,\n ri,\n ri2;\n\n for (var k = 0; k < iterations; ++k) {\n tree = quadtree(nodes, x, y).visitAfter(prepare);\n for (i = 0; i < n; ++i) {\n node = nodes[i];\n ri = radii[node.index], ri2 = ri * ri;\n xi = node.x + node.vx;\n yi = node.y + node.vy;\n tree.visit(apply);\n }\n }\n\n function apply(quad, x0, y0, x1, y1) {\n var data = quad.data, rj = quad.r, r = ri + rj;\n if (data) {\n if (data.index > node.index) {\n var x = xi - data.x - data.vx,\n y = yi - data.y - data.vy,\n l = x * x + y * y;\n if (l < r * r) {\n if (x === 0) x = jiggle(), l += x * x;\n if (y === 0) y = jiggle(), l += y * y;\n l = (r - (l = Math.sqrt(l))) / l * strength;\n node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj));\n node.vy += (y *= l) * r;\n data.vx -= x * (r = 1 - r);\n data.vy -= y * r;\n }\n }\n return;\n }\n return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r;\n }\n }\n\n function prepare(quad) {\n if (quad.data) return quad.r = radii[quad.data.index];\n for (var i = quad.r = 0; i < 4; ++i) {\n if (quad[i] && quad[i].r > quad.r) {\n quad.r = quad[i].r;\n }\n }\n }\n\n function initialize() {\n if (!nodes) return;\n var i, n = nodes.length, node;\n radii = new Array(n);\n for (i = 0; i < n; ++i) node = nodes[i], radii[node.index] = +radius(node, i, nodes);\n }\n\n force.initialize = function(_) {\n nodes = _;\n initialize();\n };\n\n force.iterations = function(_) {\n return arguments.length ? (iterations = +_, force) : iterations;\n };\n\n force.strength = function(_) {\n return arguments.length ? (strength = +_, force) : strength;\n };\n\n force.radius = function(_) {\n return arguments.length ? (radius = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : radius;\n };\n\n return force;\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","export {default as forceCenter} from \"./center\";\nexport {default as forceCollide} from \"./collide\";\nexport {default as forceLink} from \"./link\";\nexport {default as forceManyBody} from \"./manyBody\";\nexport {default as forceRadial} from \"./radial\";\nexport {default as forceSimulation} from \"./simulation\";\nexport {default as forceX} from \"./x\";\nexport {default as forceY} from \"./y\";\n","export default function() {\n return (Math.random() - 0.5) * 1e-6;\n}\n","import constant from \"./constant\";\nimport jiggle from \"./jiggle\";\nimport {map} from \"d3-collection\";\n\nfunction index(d) {\n return d.index;\n}\n\nfunction find(nodeById, nodeId) {\n var node = nodeById.get(nodeId);\n if (!node) throw new Error(\"missing: \" + nodeId);\n return node;\n}\n\nexport default function(links) {\n var id = index,\n strength = defaultStrength,\n strengths,\n distance = constant(30),\n distances,\n nodes,\n count,\n bias,\n iterations = 1;\n\n if (links == null) links = [];\n\n function defaultStrength(link) {\n return 1 / Math.min(count[link.source.index], count[link.target.index]);\n }\n\n function force(alpha) {\n for (var k = 0, n = links.length; k < iterations; ++k) {\n for (var i = 0, link, source, target, x, y, l, b; i < n; ++i) {\n link = links[i], source = link.source, target = link.target;\n x = target.x + target.vx - source.x - source.vx || jiggle();\n y = target.y + target.vy - source.y - source.vy || jiggle();\n l = Math.sqrt(x * x + y * y);\n l = (l - distances[i]) / l * alpha * strengths[i];\n x *= l, y *= l;\n target.vx -= x * (b = bias[i]);\n target.vy -= y * b;\n source.vx += x * (b = 1 - b);\n source.vy += y * b;\n }\n }\n }\n\n function initialize() {\n if (!nodes) return;\n\n var i,\n n = nodes.length,\n m = links.length,\n nodeById = map(nodes, id),\n link;\n\n for (i = 0, count = new Array(n); i < m; ++i) {\n link = links[i], link.index = i;\n if (typeof link.source !== \"object\") link.source = find(nodeById, link.source);\n if (typeof link.target !== \"object\") link.target = find(nodeById, link.target);\n count[link.source.index] = (count[link.source.index] || 0) + 1;\n count[link.target.index] = (count[link.target.index] || 0) + 1;\n }\n\n for (i = 0, bias = new Array(m); i < m; ++i) {\n link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]);\n }\n\n strengths = new Array(m), initializeStrength();\n distances = new Array(m), initializeDistance();\n }\n\n function initializeStrength() {\n if (!nodes) return;\n\n for (var i = 0, n = links.length; i < n; ++i) {\n strengths[i] = +strength(links[i], i, links);\n }\n }\n\n function initializeDistance() {\n if (!nodes) return;\n\n for (var i = 0, n = links.length; i < n; ++i) {\n distances[i] = +distance(links[i], i, links);\n }\n }\n\n force.initialize = function(_) {\n nodes = _;\n initialize();\n };\n\n force.links = function(_) {\n return arguments.length ? (links = _, initialize(), force) : links;\n };\n\n force.id = function(_) {\n return arguments.length ? (id = _, force) : id;\n };\n\n force.iterations = function(_) {\n return arguments.length ? (iterations = +_, force) : iterations;\n };\n\n force.strength = function(_) {\n return arguments.length ? (strength = typeof _ === \"function\" ? _ : constant(+_), initializeStrength(), force) : strength;\n };\n\n force.distance = function(_) {\n return arguments.length ? (distance = typeof _ === \"function\" ? _ : constant(+_), initializeDistance(), force) : distance;\n };\n\n return force;\n}\n","import constant from \"./constant\";\nimport jiggle from \"./jiggle\";\nimport {quadtree} from \"d3-quadtree\";\nimport {x, y} from \"./simulation\";\n\nexport default function() {\n var nodes,\n node,\n alpha,\n strength = constant(-30),\n strengths,\n distanceMin2 = 1,\n distanceMax2 = Infinity,\n theta2 = 0.81;\n\n function force(_) {\n var i, n = nodes.length, tree = quadtree(nodes, x, y).visitAfter(accumulate);\n for (alpha = _, i = 0; i < n; ++i) node = nodes[i], tree.visit(apply);\n }\n\n function initialize() {\n if (!nodes) return;\n var i, n = nodes.length, node;\n strengths = new Array(n);\n for (i = 0; i < n; ++i) node = nodes[i], strengths[node.index] = +strength(node, i, nodes);\n }\n\n function accumulate(quad) {\n var strength = 0, q, c, weight = 0, x, y, i;\n\n // For internal nodes, accumulate forces from child quadrants.\n if (quad.length) {\n for (x = y = i = 0; i < 4; ++i) {\n if ((q = quad[i]) && (c = Math.abs(q.value))) {\n strength += q.value, weight += c, x += c * q.x, y += c * q.y;\n }\n }\n quad.x = x / weight;\n quad.y = y / weight;\n }\n\n // For leaf nodes, accumulate forces from coincident quadrants.\n else {\n q = quad;\n q.x = q.data.x;\n q.y = q.data.y;\n do strength += strengths[q.data.index];\n while (q = q.next);\n }\n\n quad.value = strength;\n }\n\n function apply(quad, x1, _, x2) {\n if (!quad.value) return true;\n\n var x = quad.x - node.x,\n y = quad.y - node.y,\n w = x2 - x1,\n l = x * x + y * y;\n\n // Apply the Barnes-Hut approximation if possible.\n // Limit forces for very close nodes; randomize direction if coincident.\n if (w * w / theta2 < l) {\n if (l < distanceMax2) {\n if (x === 0) x = jiggle(), l += x * x;\n if (y === 0) y = jiggle(), l += y * y;\n if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);\n node.vx += x * quad.value * alpha / l;\n node.vy += y * quad.value * alpha / l;\n }\n return true;\n }\n\n // Otherwise, process points directly.\n else if (quad.length || l >= distanceMax2) return;\n\n // Limit forces for very close nodes; randomize direction if coincident.\n if (quad.data !== node || quad.next) {\n if (x === 0) x = jiggle(), l += x * x;\n if (y === 0) y = jiggle(), l += y * y;\n if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l);\n }\n\n do if (quad.data !== node) {\n w = strengths[quad.data.index] * alpha / l;\n node.vx += x * w;\n node.vy += y * w;\n } while (quad = quad.next);\n }\n\n force.initialize = function(_) {\n nodes = _;\n initialize();\n };\n\n force.strength = function(_) {\n return arguments.length ? (strength = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : strength;\n };\n\n force.distanceMin = function(_) {\n return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2);\n };\n\n force.distanceMax = function(_) {\n return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2);\n };\n\n force.theta = function(_) {\n return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2);\n };\n\n return force;\n}\n","import constant from \"./constant\";\n\nexport default function(radius, x, y) {\n var nodes,\n strength = constant(0.1),\n strengths,\n radiuses;\n\n if (typeof radius !== \"function\") radius = constant(+radius);\n if (x == null) x = 0;\n if (y == null) y = 0;\n\n function force(alpha) {\n for (var i = 0, n = nodes.length; i < n; ++i) {\n var node = nodes[i],\n dx = node.x - x || 1e-6,\n dy = node.y - y || 1e-6,\n r = Math.sqrt(dx * dx + dy * dy),\n k = (radiuses[i] - r) * strengths[i] * alpha / r;\n node.vx += dx * k;\n node.vy += dy * k;\n }\n }\n\n function initialize() {\n if (!nodes) return;\n var i, n = nodes.length;\n strengths = new Array(n);\n radiuses = new Array(n);\n for (i = 0; i < n; ++i) {\n radiuses[i] = +radius(nodes[i], i, nodes);\n strengths[i] = isNaN(radiuses[i]) ? 0 : +strength(nodes[i], i, nodes);\n }\n }\n\n force.initialize = function(_) {\n nodes = _, initialize();\n };\n\n force.strength = function(_) {\n return arguments.length ? (strength = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : strength;\n };\n\n force.radius = function(_) {\n return arguments.length ? (radius = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : radius;\n };\n\n force.x = function(_) {\n return arguments.length ? (x = +_, force) : x;\n };\n\n force.y = function(_) {\n return arguments.length ? (y = +_, force) : y;\n };\n\n return force;\n}\n","import {dispatch} from \"d3-dispatch\";\nimport {map} from \"d3-collection\";\nimport {timer} from \"d3-timer\";\n\nexport function x(d) {\n return d.x;\n}\n\nexport function y(d) {\n return d.y;\n}\n\nvar initialRadius = 10,\n initialAngle = Math.PI * (3 - Math.sqrt(5));\n\nexport default function(nodes) {\n var simulation,\n alpha = 1,\n alphaMin = 0.001,\n alphaDecay = 1 - Math.pow(alphaMin, 1 / 300),\n alphaTarget = 0,\n velocityDecay = 0.6,\n forces = map(),\n stepper = timer(step),\n event = dispatch(\"tick\", \"end\");\n\n if (nodes == null) nodes = [];\n\n function step() {\n tick();\n event.call(\"tick\", simulation);\n if (alpha < alphaMin) {\n stepper.stop();\n event.call(\"end\", simulation);\n }\n }\n\n function tick(iterations) {\n var i, n = nodes.length, node;\n\n if (iterations === undefined) iterations = 1;\n\n for (var k = 0; k < iterations; ++k) {\n alpha += (alphaTarget - alpha) * alphaDecay;\n\n forces.each(function (force) {\n force(alpha);\n });\n\n for (i = 0; i < n; ++i) {\n node = nodes[i];\n if (node.fx == null) node.x += node.vx *= velocityDecay;\n else node.x = node.fx, node.vx = 0;\n if (node.fy == null) node.y += node.vy *= velocityDecay;\n else node.y = node.fy, node.vy = 0;\n }\n }\n\n return simulation;\n }\n\n function initializeNodes() {\n for (var i = 0, n = nodes.length, node; i < n; ++i) {\n node = nodes[i], node.index = i;\n if (node.fx != null) node.x = node.fx;\n if (node.fy != null) node.y = node.fy;\n if (isNaN(node.x) || isNaN(node.y)) {\n var radius = initialRadius * Math.sqrt(i), angle = i * initialAngle;\n node.x = radius * Math.cos(angle);\n node.y = radius * Math.sin(angle);\n }\n if (isNaN(node.vx) || isNaN(node.vy)) {\n node.vx = node.vy = 0;\n }\n }\n }\n\n function initializeForce(force) {\n if (force.initialize) force.initialize(nodes);\n return force;\n }\n\n initializeNodes();\n\n return simulation = {\n tick: tick,\n\n restart: function() {\n return stepper.restart(step), simulation;\n },\n\n stop: function() {\n return stepper.stop(), simulation;\n },\n\n nodes: function(_) {\n return arguments.length ? (nodes = _, initializeNodes(), forces.each(initializeForce), simulation) : nodes;\n },\n\n alpha: function(_) {\n return arguments.length ? (alpha = +_, simulation) : alpha;\n },\n\n alphaMin: function(_) {\n return arguments.length ? (alphaMin = +_, simulation) : alphaMin;\n },\n\n alphaDecay: function(_) {\n return arguments.length ? (alphaDecay = +_, simulation) : +alphaDecay;\n },\n\n alphaTarget: function(_) {\n return arguments.length ? (alphaTarget = +_, simulation) : alphaTarget;\n },\n\n velocityDecay: function(_) {\n return arguments.length ? (velocityDecay = 1 - _, simulation) : 1 - velocityDecay;\n },\n\n force: function(name, _) {\n return arguments.length > 1 ? ((_ == null ? forces.remove(name) : forces.set(name, initializeForce(_))), simulation) : forces.get(name);\n },\n\n find: function(x, y, radius) {\n var i = 0,\n n = nodes.length,\n dx,\n dy,\n d2,\n node,\n closest;\n\n if (radius == null) radius = Infinity;\n else radius *= radius;\n\n for (i = 0; i < n; ++i) {\n node = nodes[i];\n dx = x - node.x;\n dy = y - node.y;\n d2 = dx * dx + dy * dy;\n if (d2 < radius) closest = node, radius = d2;\n }\n\n return closest;\n },\n\n on: function(name, _) {\n return arguments.length > 1 ? (event.on(name, _), simulation) : event.on(name);\n }\n };\n}\n","import constant from \"./constant\";\n\nexport default function(x) {\n var strength = constant(0.1),\n nodes,\n strengths,\n xz;\n\n if (typeof x !== \"function\") x = constant(x == null ? 0 : +x);\n\n function force(alpha) {\n for (var i = 0, n = nodes.length, node; i < n; ++i) {\n node = nodes[i], node.vx += (xz[i] - node.x) * strengths[i] * alpha;\n }\n }\n\n function initialize() {\n if (!nodes) return;\n var i, n = nodes.length;\n strengths = new Array(n);\n xz = new Array(n);\n for (i = 0; i < n; ++i) {\n strengths[i] = isNaN(xz[i] = +x(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);\n }\n }\n\n force.initialize = function(_) {\n nodes = _;\n initialize();\n };\n\n force.strength = function(_) {\n return arguments.length ? (strength = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : strength;\n };\n\n force.x = function(_) {\n return arguments.length ? (x = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : x;\n };\n\n return force;\n}\n","import constant from \"./constant\";\n\nexport default function(y) {\n var strength = constant(0.1),\n nodes,\n strengths,\n yz;\n\n if (typeof y !== \"function\") y = constant(y == null ? 0 : +y);\n\n function force(alpha) {\n for (var i = 0, n = nodes.length, node; i < n; ++i) {\n node = nodes[i], node.vy += (yz[i] - node.y) * strengths[i] * alpha;\n }\n }\n\n function initialize() {\n if (!nodes) return;\n var i, n = nodes.length;\n strengths = new Array(n);\n yz = new Array(n);\n for (i = 0; i < n; ++i) {\n strengths[i] = isNaN(yz[i] = +y(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes);\n }\n }\n\n force.initialize = function(_) {\n nodes = _;\n initialize();\n };\n\n force.strength = function(_) {\n return arguments.length ? (strength = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : strength;\n };\n\n force.y = function(_) {\n return arguments.length ? (y = typeof _ === \"function\" ? _ : constant(+_), initialize(), force) : y;\n };\n\n return force;\n}\n","import formatLocale from \"./locale.js\";\n\nvar locale;\nexport var format;\nexport var formatPrefix;\n\ndefaultLocale({\n decimal: \".\",\n thousands: \",\",\n grouping: [3],\n currency: [\"$\", \"\"],\n minus: \"-\"\n});\n\nexport default function defaultLocale(definition) {\n locale = formatLocale(definition);\n format = locale.format;\n formatPrefix = locale.formatPrefix;\n return locale;\n}\n","import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport default function(x) {\n return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN;\n}\n","export default function(x) {\n return Math.abs(x = Math.round(x)) >= 1e21\n ? x.toLocaleString(\"en\").replace(/,/g, \"\")\n : x.toString(10);\n}\n\n// Computes the decimal coefficient and exponent of the specified number x with\n// significant digits p, where x is positive and p is in [1, 21] or undefined.\n// For example, formatDecimalParts(1.23) returns [\"123\", 0].\nexport function formatDecimalParts(x, p) {\n if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf(\"e\")) < 0) return null; // NaN, ±Infinity\n var i, coefficient = x.slice(0, i);\n\n // The string returned by toExponential either has the form \\d\\.\\d+e[-+]\\d+\n // (e.g., 1.2e+3) or the form \\de[-+]\\d+ (e.g., 1e+3).\n return [\n coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient,\n +x.slice(i + 1)\n ];\n}\n","export default function(grouping, thousands) {\n return function(value, width) {\n var i = value.length,\n t = [],\n j = 0,\n g = grouping[0],\n length = 0;\n\n while (i > 0 && g > 0) {\n if (length + g + 1 > width) g = Math.max(1, width - length);\n t.push(value.substring(i -= g, i + g));\n if ((length += g + 1) > width) break;\n g = grouping[j = (j + 1) % grouping.length];\n }\n\n return t.reverse().join(thousands);\n };\n}\n","export default function(numerals) {\n return function(value) {\n return value.replace(/[0-9]/g, function(i) {\n return numerals[+i];\n });\n };\n}\n","import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport var prefixExponent;\n\nexport default function(x, p) {\n var d = formatDecimalParts(x, p);\n if (!d) return x + \"\";\n var coefficient = d[0],\n exponent = d[1],\n i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1,\n n = coefficient.length;\n return i === n ? coefficient\n : i > n ? coefficient + new Array(i - n + 1).join(\"0\")\n : i > 0 ? coefficient.slice(0, i) + \".\" + coefficient.slice(i)\n : \"0.\" + new Array(1 - i).join(\"0\") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; // less than 1y!\n}\n","import {formatDecimalParts} from \"./formatDecimal.js\";\n\nexport default function(x, p) {\n var d = formatDecimalParts(x, p);\n if (!d) return x + \"\";\n var coefficient = d[0],\n exponent = d[1];\n return exponent < 0 ? \"0.\" + new Array(-exponent).join(\"0\") + coefficient\n : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + \".\" + coefficient.slice(exponent + 1)\n : coefficient + new Array(exponent - coefficient.length + 2).join(\"0\");\n}\n","// [[fill]align][sign][symbol][0][width][,][.precision][~][type]\nvar re = /^(?:(.)?([<>=^]))?([+\\-( ])?([$#])?(0)?(\\d+)?(,)?(\\.\\d+)?(~)?([a-z%])?$/i;\n\nexport default function formatSpecifier(specifier) {\n if (!(match = re.exec(specifier))) throw new Error(\"invalid format: \" + specifier);\n var match;\n return new FormatSpecifier({\n fill: match[1],\n align: match[2],\n sign: match[3],\n symbol: match[4],\n zero: match[5],\n width: match[6],\n comma: match[7],\n precision: match[8] && match[8].slice(1),\n trim: match[9],\n type: match[10]\n });\n}\n\nformatSpecifier.prototype = FormatSpecifier.prototype; // instanceof\n\nexport function FormatSpecifier(specifier) {\n this.fill = specifier.fill === undefined ? \" \" : specifier.fill + \"\";\n this.align = specifier.align === undefined ? \">\" : specifier.align + \"\";\n this.sign = specifier.sign === undefined ? \"-\" : specifier.sign + \"\";\n this.symbol = specifier.symbol === undefined ? \"\" : specifier.symbol + \"\";\n this.zero = !!specifier.zero;\n this.width = specifier.width === undefined ? undefined : +specifier.width;\n this.comma = !!specifier.comma;\n this.precision = specifier.precision === undefined ? undefined : +specifier.precision;\n this.trim = !!specifier.trim;\n this.type = specifier.type === undefined ? \"\" : specifier.type + \"\";\n}\n\nFormatSpecifier.prototype.toString = function() {\n return this.fill\n + this.align\n + this.sign\n + this.symbol\n + (this.zero ? \"0\" : \"\")\n + (this.width === undefined ? \"\" : Math.max(1, this.width | 0))\n + (this.comma ? \",\" : \"\")\n + (this.precision === undefined ? \"\" : \".\" + Math.max(0, this.precision | 0))\n + (this.trim ? \"~\" : \"\")\n + this.type;\n};\n","// Trims insignificant zeros, e.g., replaces 1.2000k with 1.2k.\nexport default function(s) {\n out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) {\n switch (s[i]) {\n case \".\": i0 = i1 = i; break;\n case \"0\": if (i0 === 0) i0 = i; i1 = i; break;\n default: if (!+s[i]) break out; if (i0 > 0) i0 = 0; break;\n }\n }\n return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s;\n}\n","import formatDecimal from \"./formatDecimal.js\";\nimport formatPrefixAuto from \"./formatPrefixAuto.js\";\nimport formatRounded from \"./formatRounded.js\";\n\nexport default {\n \"%\": function(x, p) { return (x * 100).toFixed(p); },\n \"b\": function(x) { return Math.round(x).toString(2); },\n \"c\": function(x) { return x + \"\"; },\n \"d\": formatDecimal,\n \"e\": function(x, p) { return x.toExponential(p); },\n \"f\": function(x, p) { return x.toFixed(p); },\n \"g\": function(x, p) { return x.toPrecision(p); },\n \"o\": function(x) { return Math.round(x).toString(8); },\n \"p\": function(x, p) { return formatRounded(x * 100, p); },\n \"r\": formatRounded,\n \"s\": formatPrefixAuto,\n \"X\": function(x) { return Math.round(x).toString(16).toUpperCase(); },\n \"x\": function(x) { return Math.round(x).toString(16); }\n};\n","export default function(x) {\n return x;\n}\n","export {default as formatDefaultLocale, format, formatPrefix} from \"./defaultLocale.js\";\nexport {default as formatLocale} from \"./locale.js\";\nexport {default as formatSpecifier, FormatSpecifier} from \"./formatSpecifier.js\";\nexport {default as precisionFixed} from \"./precisionFixed.js\";\nexport {default as precisionPrefix} from \"./precisionPrefix.js\";\nexport {default as precisionRound} from \"./precisionRound.js\";\n","import exponent from \"./exponent.js\";\nimport formatGroup from \"./formatGroup.js\";\nimport formatNumerals from \"./formatNumerals.js\";\nimport formatSpecifier from \"./formatSpecifier.js\";\nimport formatTrim from \"./formatTrim.js\";\nimport formatTypes from \"./formatTypes.js\";\nimport {prefixExponent} from \"./formatPrefixAuto.js\";\nimport identity from \"./identity.js\";\n\nvar map = Array.prototype.map,\n prefixes = [\"y\",\"z\",\"a\",\"f\",\"p\",\"n\",\"µ\",\"m\",\"\",\"k\",\"M\",\"G\",\"T\",\"P\",\"E\",\"Z\",\"Y\"];\n\nexport default function(locale) {\n var group = locale.grouping === undefined || locale.thousands === undefined ? identity : formatGroup(map.call(locale.grouping, Number), locale.thousands + \"\"),\n currencyPrefix = locale.currency === undefined ? \"\" : locale.currency[0] + \"\",\n currencySuffix = locale.currency === undefined ? \"\" : locale.currency[1] + \"\",\n decimal = locale.decimal === undefined ? \".\" : locale.decimal + \"\",\n numerals = locale.numerals === undefined ? identity : formatNumerals(map.call(locale.numerals, String)),\n percent = locale.percent === undefined ? \"%\" : locale.percent + \"\",\n minus = locale.minus === undefined ? \"-\" : locale.minus + \"\",\n nan = locale.nan === undefined ? \"NaN\" : locale.nan + \"\";\n\n function newFormat(specifier) {\n specifier = formatSpecifier(specifier);\n\n var fill = specifier.fill,\n align = specifier.align,\n sign = specifier.sign,\n symbol = specifier.symbol,\n zero = specifier.zero,\n width = specifier.width,\n comma = specifier.comma,\n precision = specifier.precision,\n trim = specifier.trim,\n type = specifier.type;\n\n // The \"n\" type is an alias for \",g\".\n if (type === \"n\") comma = true, type = \"g\";\n\n // The \"\" type, and any invalid type, is an alias for \".12~g\".\n else if (!formatTypes[type]) precision === undefined && (precision = 12), trim = true, type = \"g\";\n\n // If zero fill is specified, padding goes after sign and before digits.\n if (zero || (fill === \"0\" && align === \"=\")) zero = true, fill = \"0\", align = \"=\";\n\n // Compute the prefix and suffix.\n // For SI-prefix, the suffix is lazily computed.\n var prefix = symbol === \"$\" ? currencyPrefix : symbol === \"#\" && /[boxX]/.test(type) ? \"0\" + type.toLowerCase() : \"\",\n suffix = symbol === \"$\" ? currencySuffix : /[%p]/.test(type) ? percent : \"\";\n\n // What format function should we use?\n // Is this an integer type?\n // Can this type generate exponential notation?\n var formatType = formatTypes[type],\n maybeSuffix = /[defgprs%]/.test(type);\n\n // Set the default precision if not specified,\n // or clamp the specified precision to the supported range.\n // For significant precision, it must be in [1, 21].\n // For fixed precision, it must be in [0, 20].\n precision = precision === undefined ? 6\n : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision))\n : Math.max(0, Math.min(20, precision));\n\n function format(value) {\n var valuePrefix = prefix,\n valueSuffix = suffix,\n i, n, c;\n\n if (type === \"c\") {\n valueSuffix = formatType(value) + valueSuffix;\n value = \"\";\n } else {\n value = +value;\n\n // Determine the sign. -0 is not less than 0, but 1 / -0 is!\n var valueNegative = value < 0 || 1 / value < 0;\n\n // Perform the initial formatting.\n value = isNaN(value) ? nan : formatType(Math.abs(value), precision);\n\n // Trim insignificant zeros.\n if (trim) value = formatTrim(value);\n\n // If a negative value rounds to zero after formatting, and no explicit positive sign is requested, hide the sign.\n if (valueNegative && +value === 0 && sign !== \"+\") valueNegative = false;\n\n // Compute the prefix and suffix.\n valuePrefix = (valueNegative ? (sign === \"(\" ? sign : minus) : sign === \"-\" || sign === \"(\" ? \"\" : sign) + valuePrefix;\n valueSuffix = (type === \"s\" ? prefixes[8 + prefixExponent / 3] : \"\") + valueSuffix + (valueNegative && sign === \"(\" ? \")\" : \"\");\n\n // Break the formatted value into the integer “value” part that can be\n // grouped, and fractional or exponential “suffix” part that is not.\n if (maybeSuffix) {\n i = -1, n = value.length;\n while (++i < n) {\n if (c = value.charCodeAt(i), 48 > c || c > 57) {\n valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix;\n value = value.slice(0, i);\n break;\n }\n }\n }\n }\n\n // If the fill character is not \"0\", grouping is applied before padding.\n if (comma && !zero) value = group(value, Infinity);\n\n // Compute the padding.\n var length = valuePrefix.length + value.length + valueSuffix.length,\n padding = length < width ? new Array(width - length + 1).join(fill) : \"\";\n\n // If the fill character is \"0\", grouping is applied after padding.\n if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = \"\";\n\n // Reconstruct the final output based on the desired alignment.\n switch (align) {\n case \"<\": value = valuePrefix + value + valueSuffix + padding; break;\n case \"=\": value = valuePrefix + padding + value + valueSuffix; break;\n case \"^\": value = padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); break;\n default: value = padding + valuePrefix + value + valueSuffix; break;\n }\n\n return numerals(value);\n }\n\n format.toString = function() {\n return specifier + \"\";\n };\n\n return format;\n }\n\n function formatPrefix(specifier, value) {\n var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = \"f\", specifier)),\n e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3,\n k = Math.pow(10, -e),\n prefix = prefixes[8 + e / 3];\n return function(value) {\n return f(k * value) + prefix;\n };\n }\n\n return {\n format: newFormat,\n formatPrefix: formatPrefix\n };\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step) {\n return Math.max(0, -exponent(Math.abs(step)));\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step, value) {\n return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step)));\n}\n","import exponent from \"./exponent.js\";\n\nexport default function(step, max) {\n step = Math.abs(step), max = Math.abs(max) - step;\n return Math.max(0, exponent(max) - exponent(step)) + 1;\n}\n","export var abs = Math.abs;\nexport var atan = Math.atan;\nexport var atan2 = Math.atan2;\nexport var ceil = Math.ceil;\nexport var cos = Math.cos;\nexport var exp = Math.exp;\nexport var floor = Math.floor;\nexport var log = Math.log;\nexport var max = Math.max;\nexport var min = Math.min;\nexport var pow = Math.pow;\nexport var round = Math.round;\nexport var sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };\nexport var sin = Math.sin;\nexport var tan = Math.tan;\n\nexport var epsilon = 1e-6;\nexport var epsilon2 = 1e-12;\nexport var pi = Math.PI;\nexport var halfPi = pi / 2;\nexport var quarterPi = pi / 4;\nexport var sqrt1_2 = Math.SQRT1_2;\nexport var sqrt2 = sqrt(2);\nexport var sqrtPi = sqrt(pi);\nexport var tau = pi * 2;\nexport var degrees = 180 / pi;\nexport var radians = pi / 180;\n\nexport function sinci(x) {\n return x ? x / Math.sin(x) : 1;\n}\n\nexport function asin(x) {\n return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);\n}\n\nexport function acos(x) {\n return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);\n}\n\nexport function sqrt(x) {\n return x > 0 ? Math.sqrt(x) : 0;\n}\n\nexport function tanh(x) {\n x = exp(2 * x);\n return (x - 1) / (x + 1);\n}\n\nexport function sinh(x) {\n return (exp(x) - exp(-x)) / 2;\n}\n\nexport function cosh(x) {\n return (exp(x) + exp(-x)) / 2;\n}\n\nexport function arsinh(x) {\n return log(x + sqrt(x * x + 1));\n}\n\nexport function arcosh(x) {\n return log(x + sqrt(x * x - 1));\n}\n","import {geoProjection as projection} from \"d3-geo\";\nimport {abs, asin, cos, epsilon, halfPi, pi, sin, sqrt2} from \"./math.js\";\n\nexport function mollweideBromleyTheta(cp, phi) {\n var cpsinPhi = cp * sin(phi), i = 30, delta;\n do phi -= delta = (phi + sin(phi) - cpsinPhi) / (1 + cos(phi));\n while (abs(delta) > epsilon && --i > 0);\n return phi / 2;\n}\n\nexport function mollweideBromleyRaw(cx, cy, cp) {\n\n function forward(lambda, phi) {\n return [cx * lambda * cos(phi = mollweideBromleyTheta(cp, phi)), cy * sin(phi)];\n }\n\n forward.invert = function(x, y) {\n return y = asin(y / cy), [x / (cx * cos(y)), asin((2 * y + sin(2 * y)) / cp)];\n };\n\n return forward;\n}\n\nexport var mollweideRaw = mollweideBromleyRaw(sqrt2 / halfPi, sqrt2, pi);\n\nexport default function() {\n return projection(mollweideRaw)\n .scale(169.529);\n}\n","var array = Array.prototype;\n\nexport var slice = array.slice;\nexport var map = array.map;\n","export default function(a, b) {\n return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n","import ascending from \"./ascending\";\nimport bisector from \"./bisector\";\n\nvar ascendingBisect = bisector(ascending);\nexport var bisectRight = ascendingBisect.right;\nexport var bisectLeft = ascendingBisect.left;\nexport default bisectRight;\n","import ascending from \"./ascending\";\n\nexport default function(compare) {\n if (compare.length === 1) compare = ascendingComparator(compare);\n return {\n left: function(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n var mid = lo + hi >>> 1;\n if (compare(a[mid], x) < 0) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n },\n right: function(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n var mid = lo + hi >>> 1;\n if (compare(a[mid], x) > 0) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n }\n };\n}\n\nfunction ascendingComparator(f) {\n return function(d, x) {\n return ascending(f(d), x);\n };\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","import {pair} from \"./pairs\";\n\nexport default function(values0, values1, reduce) {\n var n0 = values0.length,\n n1 = values1.length,\n values = new Array(n0 * n1),\n i0,\n i1,\n i,\n value0;\n\n if (reduce == null) reduce = pair;\n\n for (i0 = i = 0; i0 < n0; ++i0) {\n for (value0 = values0[i0], i1 = 0; i1 < n1; ++i1, ++i) {\n values[i] = reduce(value0, values1[i1]);\n }\n }\n\n return values;\n}\n","export default function(a, b) {\n return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;\n}\n","import variance from \"./variance\";\n\nexport default function(array, f) {\n var v = variance(array, f);\n return v ? Math.sqrt(v) : v;\n}\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n min,\n max;\n\n if (valueof == null) {\n while (++i < n) { // Find the first comparable value.\n if ((value = values[i]) != null && value >= value) {\n min = max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = values[i]) != null) {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n }\n }\n\n else {\n while (++i < n) { // Find the first comparable value.\n if ((value = valueof(values[i], i, values)) != null && value >= value) {\n min = max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = valueof(values[i], i, values)) != null) {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n }\n }\n\n return [min, max];\n}\n","import {slice} from \"./array\";\nimport bisect from \"./bisect\";\nimport constant from \"./constant\";\nimport extent from \"./extent\";\nimport identity from \"./identity\";\nimport range from \"./range\";\nimport {tickStep} from \"./ticks\";\nimport sturges from \"./threshold/sturges\";\n\nexport default function() {\n var value = identity,\n domain = extent,\n threshold = sturges;\n\n function histogram(data) {\n var i,\n n = data.length,\n x,\n values = new Array(n);\n\n for (i = 0; i < n; ++i) {\n values[i] = value(data[i], i, data);\n }\n\n var xz = domain(values),\n x0 = xz[0],\n x1 = xz[1],\n tz = threshold(values, x0, x1);\n\n // Convert number of thresholds into uniform thresholds.\n if (!Array.isArray(tz)) {\n tz = tickStep(x0, x1, tz);\n tz = range(Math.ceil(x0 / tz) * tz, x1, tz); // exclusive\n }\n\n // Remove any thresholds outside the domain.\n var m = tz.length;\n while (tz[0] <= x0) tz.shift(), --m;\n while (tz[m - 1] > x1) tz.pop(), --m;\n\n var bins = new Array(m + 1),\n bin;\n\n // Initialize bins.\n for (i = 0; i <= m; ++i) {\n bin = bins[i] = [];\n bin.x0 = i > 0 ? tz[i - 1] : x0;\n bin.x1 = i < m ? tz[i] : x1;\n }\n\n // Assign data to bins by value, ignoring any outside the domain.\n for (i = 0; i < n; ++i) {\n x = values[i];\n if (x0 <= x && x <= x1) {\n bins[bisect(tz, x, 0, m)].push(data[i]);\n }\n }\n\n return bins;\n }\n\n histogram.value = function(_) {\n return arguments.length ? (value = typeof _ === \"function\" ? _ : constant(_), histogram) : value;\n };\n\n histogram.domain = function(_) {\n return arguments.length ? (domain = typeof _ === \"function\" ? _ : constant([_[0], _[1]]), histogram) : domain;\n };\n\n histogram.thresholds = function(_) {\n return arguments.length ? (threshold = typeof _ === \"function\" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), histogram) : threshold;\n };\n\n return histogram;\n}\n","export default function(x) {\n return x;\n}\n","export {default as bisect, bisectRight, bisectLeft} from \"./bisect\";\nexport {default as ascending} from \"./ascending\";\nexport {default as bisector} from \"./bisector\";\nexport {default as cross} from \"./cross\";\nexport {default as descending} from \"./descending\";\nexport {default as deviation} from \"./deviation\";\nexport {default as extent} from \"./extent\";\nexport {default as histogram} from \"./histogram\";\nexport {default as thresholdFreedmanDiaconis} from \"./threshold/freedmanDiaconis\";\nexport {default as thresholdScott} from \"./threshold/scott\";\nexport {default as thresholdSturges} from \"./threshold/sturges\";\nexport {default as max} from \"./max\";\nexport {default as mean} from \"./mean\";\nexport {default as median} from \"./median\";\nexport {default as merge} from \"./merge\";\nexport {default as min} from \"./min\";\nexport {default as pairs} from \"./pairs\";\nexport {default as permute} from \"./permute\";\nexport {default as quantile} from \"./quantile\";\nexport {default as range} from \"./range\";\nexport {default as scan} from \"./scan\";\nexport {default as shuffle} from \"./shuffle\";\nexport {default as sum} from \"./sum\";\nexport {default as ticks, tickIncrement, tickStep} from \"./ticks\";\nexport {default as transpose} from \"./transpose\";\nexport {default as variance} from \"./variance\";\nexport {default as zip} from \"./zip\";\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n max;\n\n if (valueof == null) {\n while (++i < n) { // Find the first comparable value.\n if ((value = values[i]) != null && value >= value) {\n max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = values[i]) != null && value > max) {\n max = value;\n }\n }\n }\n }\n }\n\n else {\n while (++i < n) { // Find the first comparable value.\n if ((value = valueof(values[i], i, values)) != null && value >= value) {\n max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = valueof(values[i], i, values)) != null && value > max) {\n max = value;\n }\n }\n }\n }\n }\n\n return max;\n}\n","import number from \"./number\";\n\nexport default function(values, valueof) {\n var n = values.length,\n m = n,\n i = -1,\n value,\n sum = 0;\n\n if (valueof == null) {\n while (++i < n) {\n if (!isNaN(value = number(values[i]))) sum += value;\n else --m;\n }\n }\n\n else {\n while (++i < n) {\n if (!isNaN(value = number(valueof(values[i], i, values)))) sum += value;\n else --m;\n }\n }\n\n if (m) return sum / m;\n}\n","import ascending from \"./ascending\";\nimport number from \"./number\";\nimport quantile from \"./quantile\";\n\nexport default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n numbers = [];\n\n if (valueof == null) {\n while (++i < n) {\n if (!isNaN(value = number(values[i]))) {\n numbers.push(value);\n }\n }\n }\n\n else {\n while (++i < n) {\n if (!isNaN(value = number(valueof(values[i], i, values)))) {\n numbers.push(value);\n }\n }\n }\n\n return quantile(numbers.sort(ascending), 0.5);\n}\n","export default function(arrays) {\n var n = arrays.length,\n m,\n i = -1,\n j = 0,\n merged,\n array;\n\n while (++i < n) j += arrays[i].length;\n merged = new Array(j);\n\n while (--n >= 0) {\n array = arrays[n];\n m = array.length;\n while (--m >= 0) {\n merged[--j] = array[m];\n }\n }\n\n return merged;\n}\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n min;\n\n if (valueof == null) {\n while (++i < n) { // Find the first comparable value.\n if ((value = values[i]) != null && value >= value) {\n min = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = values[i]) != null && min > value) {\n min = value;\n }\n }\n }\n }\n }\n\n else {\n while (++i < n) { // Find the first comparable value.\n if ((value = valueof(values[i], i, values)) != null && value >= value) {\n min = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = valueof(values[i], i, values)) != null && min > value) {\n min = value;\n }\n }\n }\n }\n }\n\n return min;\n}\n","export default function(x) {\n return x === null ? NaN : +x;\n}\n","export default function(array, f) {\n if (f == null) f = pair;\n var i = 0, n = array.length - 1, p = array[0], pairs = new Array(n < 0 ? 0 : n);\n while (i < n) pairs[i] = f(p, p = array[++i]);\n return pairs;\n}\n\nexport function pair(a, b) {\n return [a, b];\n}\n","export default function(array, indexes) {\n var i = indexes.length, permutes = new Array(i);\n while (i--) permutes[i] = array[indexes[i]];\n return permutes;\n}\n","import number from \"./number\";\n\nexport default function(values, p, valueof) {\n if (valueof == null) valueof = number;\n if (!(n = values.length)) return;\n if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);\n if (p >= 1) return +valueof(values[n - 1], n - 1, values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = +valueof(values[i0], i0, values),\n value1 = +valueof(values[i0 + 1], i0 + 1, values);\n return value0 + (value1 - value0) * (i - i0);\n}\n","export default function(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n","import ascending from \"./ascending\";\n\nexport default function(values, compare) {\n if (!(n = values.length)) return;\n var n,\n i = 0,\n j = 0,\n xi,\n xj = values[j];\n\n if (compare == null) compare = ascending;\n\n while (++i < n) {\n if (compare(xi = values[i], xj) < 0 || compare(xj, xj) !== 0) {\n xj = xi, j = i;\n }\n }\n\n if (compare(xj, xj) === 0) return j;\n}\n","export default function(array, i0, i1) {\n var m = (i1 == null ? array.length : i1) - (i0 = i0 == null ? 0 : +i0),\n t,\n i;\n\n while (m) {\n i = Math.random() * m-- | 0;\n t = array[m + i0];\n array[m + i0] = array[i + i0];\n array[i + i0] = t;\n }\n\n return array;\n}\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n sum = 0;\n\n if (valueof == null) {\n while (++i < n) {\n if (value = +values[i]) sum += value; // Note: zero and null are equivalent.\n }\n }\n\n else {\n while (++i < n) {\n if (value = +valueof(values[i], i, values)) sum += value;\n }\n }\n\n return sum;\n}\n","import {map} from \"../array\";\nimport ascending from \"../ascending\";\nimport number from \"../number\";\nimport quantile from \"../quantile\";\n\nexport default function(values, min, max) {\n values = map.call(values, number).sort(ascending);\n return Math.ceil((max - min) / (2 * (quantile(values, 0.75) - quantile(values, 0.25)) * Math.pow(values.length, -1 / 3)));\n}\n","import deviation from \"../deviation\";\n\nexport default function(values, min, max) {\n return Math.ceil((max - min) / (3.5 * deviation(values) * Math.pow(values.length, -1 / 3)));\n}\n","export default function(values) {\n return Math.ceil(Math.log(values.length) / Math.LN2) + 1;\n}\n","var e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nexport default function(start, stop, count) {\n var reverse,\n i = -1,\n n,\n ticks,\n step;\n\n stop = +stop, start = +start, count = +count;\n if (start === stop && count > 0) return [start];\n if (reverse = stop < start) n = start, start = stop, stop = n;\n if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];\n\n if (step > 0) {\n start = Math.ceil(start / step);\n stop = Math.floor(stop / step);\n ticks = new Array(n = Math.ceil(stop - start + 1));\n while (++i < n) ticks[i] = (start + i) * step;\n } else {\n start = Math.floor(start * step);\n stop = Math.ceil(stop * step);\n ticks = new Array(n = Math.ceil(start - stop + 1));\n while (++i < n) ticks[i] = (start - i) / step;\n }\n\n if (reverse) ticks.reverse();\n\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n var step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log(step) / Math.LN10),\n error = step / Math.pow(10, power);\n return power >= 0\n ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)\n : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);\n}\n\nexport function tickStep(start, stop, count) {\n var step0 = Math.abs(stop - start) / Math.max(0, count),\n step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),\n error = step0 / step1;\n if (error >= e10) step1 *= 10;\n else if (error >= e5) step1 *= 5;\n else if (error >= e2) step1 *= 2;\n return stop < start ? -step1 : step1;\n}\n","import min from \"./min\";\n\nexport default function(matrix) {\n if (!(n = matrix.length)) return [];\n for (var i = -1, m = min(matrix, length), transpose = new Array(m); ++i < m;) {\n for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n;) {\n row[j] = matrix[j][i];\n }\n }\n return transpose;\n}\n\nfunction length(d) {\n return d.length;\n}\n","import number from \"./number\";\n\nexport default function(values, valueof) {\n var n = values.length,\n m = 0,\n i = -1,\n mean = 0,\n value,\n delta,\n sum = 0;\n\n if (valueof == null) {\n while (++i < n) {\n if (!isNaN(value = number(values[i]))) {\n delta = value - mean;\n mean += delta / ++m;\n sum += delta * (value - mean);\n }\n }\n }\n\n else {\n while (++i < n) {\n if (!isNaN(value = number(valueof(values[i], i, values)))) {\n delta = value - mean;\n mean += delta / ++m;\n sum += delta * (value - mean);\n }\n }\n }\n\n if (m > 1) return sum / (m - 1);\n}\n","import transpose from \"./transpose\";\n\nexport default function() {\n return transpose(arguments);\n}\n","// Adds floating point numbers with twice the normal precision.\n// Reference: J. R. Shewchuk, Adaptive Precision Floating-Point Arithmetic and\n// Fast Robust Geometric Predicates, Discrete & Computational Geometry 18(3)\n// 305–363 (1997).\n// Code adapted from GeographicLib by Charles F. F. Karney,\n// http://geographiclib.sourceforge.net/\n\nexport default function() {\n return new Adder;\n}\n\nfunction Adder() {\n this.reset();\n}\n\nAdder.prototype = {\n constructor: Adder,\n reset: function() {\n this.s = // rounded value\n this.t = 0; // exact error\n },\n add: function(y) {\n add(temp, y, this.t);\n add(this, temp.s, this.s);\n if (this.s) this.t += temp.t;\n else this.s = temp.t;\n },\n valueOf: function() {\n return this.s;\n }\n};\n\nvar temp = new Adder;\n\nfunction add(adder, a, b) {\n var x = adder.s = a + b,\n bv = x - a,\n av = x - bv;\n adder.t = (a - av) + (b - bv);\n}\n","import adder from \"./adder.js\";\nimport {atan2, cos, quarterPi, radians, sin, tau} from \"./math.js\";\nimport noop from \"./noop.js\";\nimport stream from \"./stream.js\";\n\nexport var areaRingSum = adder();\n\nvar areaSum = adder(),\n lambda00,\n phi00,\n lambda0,\n cosPhi0,\n sinPhi0;\n\nexport var areaStream = {\n point: noop,\n lineStart: noop,\n lineEnd: noop,\n polygonStart: function() {\n areaRingSum.reset();\n areaStream.lineStart = areaRingStart;\n areaStream.lineEnd = areaRingEnd;\n },\n polygonEnd: function() {\n var areaRing = +areaRingSum;\n areaSum.add(areaRing < 0 ? tau + areaRing : areaRing);\n this.lineStart = this.lineEnd = this.point = noop;\n },\n sphere: function() {\n areaSum.add(tau);\n }\n};\n\nfunction areaRingStart() {\n areaStream.point = areaPointFirst;\n}\n\nfunction areaRingEnd() {\n areaPoint(lambda00, phi00);\n}\n\nfunction areaPointFirst(lambda, phi) {\n areaStream.point = areaPoint;\n lambda00 = lambda, phi00 = phi;\n lambda *= radians, phi *= radians;\n lambda0 = lambda, cosPhi0 = cos(phi = phi / 2 + quarterPi), sinPhi0 = sin(phi);\n}\n\nfunction areaPoint(lambda, phi) {\n lambda *= radians, phi *= radians;\n phi = phi / 2 + quarterPi; // half the angular distance from south pole\n\n // Spherical excess E for a spherical triangle with vertices: south pole,\n // previous point, current point. Uses a formula derived from Cagnoli’s\n // theorem. See Todhunter, Spherical Trig. (1871), Sec. 103, Eq. (2).\n var dLambda = lambda - lambda0,\n sdLambda = dLambda >= 0 ? 1 : -1,\n adLambda = sdLambda * dLambda,\n cosPhi = cos(phi),\n sinPhi = sin(phi),\n k = sinPhi0 * sinPhi,\n u = cosPhi0 * cosPhi + k * cos(adLambda),\n v = k * sdLambda * sin(adLambda);\n areaRingSum.add(atan2(v, u));\n\n // Advance the previous points.\n lambda0 = lambda, cosPhi0 = cosPhi, sinPhi0 = sinPhi;\n}\n\nexport default function(object) {\n areaSum.reset();\n stream(object, areaStream);\n return areaSum * 2;\n}\n","import adder from \"./adder.js\";\nimport {areaStream, areaRingSum} from \"./area.js\";\nimport {cartesian, cartesianCross, cartesianNormalizeInPlace, spherical} from \"./cartesian.js\";\nimport {abs, degrees, epsilon, radians} from \"./math.js\";\nimport stream from \"./stream.js\";\n\nvar lambda0, phi0, lambda1, phi1, // bounds\n lambda2, // previous lambda-coordinate\n lambda00, phi00, // first point\n p0, // previous 3D point\n deltaSum = adder(),\n ranges,\n range;\n\nvar boundsStream = {\n point: boundsPoint,\n lineStart: boundsLineStart,\n lineEnd: boundsLineEnd,\n polygonStart: function() {\n boundsStream.point = boundsRingPoint;\n boundsStream.lineStart = boundsRingStart;\n boundsStream.lineEnd = boundsRingEnd;\n deltaSum.reset();\n areaStream.polygonStart();\n },\n polygonEnd: function() {\n areaStream.polygonEnd();\n boundsStream.point = boundsPoint;\n boundsStream.lineStart = boundsLineStart;\n boundsStream.lineEnd = boundsLineEnd;\n if (areaRingSum < 0) lambda0 = -(lambda1 = 180), phi0 = -(phi1 = 90);\n else if (deltaSum > epsilon) phi1 = 90;\n else if (deltaSum < -epsilon) phi0 = -90;\n range[0] = lambda0, range[1] = lambda1;\n },\n sphere: function() {\n lambda0 = -(lambda1 = 180), phi0 = -(phi1 = 90);\n }\n};\n\nfunction boundsPoint(lambda, phi) {\n ranges.push(range = [lambda0 = lambda, lambda1 = lambda]);\n if (phi < phi0) phi0 = phi;\n if (phi > phi1) phi1 = phi;\n}\n\nfunction linePoint(lambda, phi) {\n var p = cartesian([lambda * radians, phi * radians]);\n if (p0) {\n var normal = cartesianCross(p0, p),\n equatorial = [normal[1], -normal[0], 0],\n inflection = cartesianCross(equatorial, normal);\n cartesianNormalizeInPlace(inflection);\n inflection = spherical(inflection);\n var delta = lambda - lambda2,\n sign = delta > 0 ? 1 : -1,\n lambdai = inflection[0] * degrees * sign,\n phii,\n antimeridian = abs(delta) > 180;\n if (antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) {\n phii = inflection[1] * degrees;\n if (phii > phi1) phi1 = phii;\n } else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) {\n phii = -inflection[1] * degrees;\n if (phii < phi0) phi0 = phii;\n } else {\n if (phi < phi0) phi0 = phi;\n if (phi > phi1) phi1 = phi;\n }\n if (antimeridian) {\n if (lambda < lambda2) {\n if (angle(lambda0, lambda) > angle(lambda0, lambda1)) lambda1 = lambda;\n } else {\n if (angle(lambda, lambda1) > angle(lambda0, lambda1)) lambda0 = lambda;\n }\n } else {\n if (lambda1 >= lambda0) {\n if (lambda < lambda0) lambda0 = lambda;\n if (lambda > lambda1) lambda1 = lambda;\n } else {\n if (lambda > lambda2) {\n if (angle(lambda0, lambda) > angle(lambda0, lambda1)) lambda1 = lambda;\n } else {\n if (angle(lambda, lambda1) > angle(lambda0, lambda1)) lambda0 = lambda;\n }\n }\n }\n } else {\n ranges.push(range = [lambda0 = lambda, lambda1 = lambda]);\n }\n if (phi < phi0) phi0 = phi;\n if (phi > phi1) phi1 = phi;\n p0 = p, lambda2 = lambda;\n}\n\nfunction boundsLineStart() {\n boundsStream.point = linePoint;\n}\n\nfunction boundsLineEnd() {\n range[0] = lambda0, range[1] = lambda1;\n boundsStream.point = boundsPoint;\n p0 = null;\n}\n\nfunction boundsRingPoint(lambda, phi) {\n if (p0) {\n var delta = lambda - lambda2;\n deltaSum.add(abs(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta);\n } else {\n lambda00 = lambda, phi00 = phi;\n }\n areaStream.point(lambda, phi);\n linePoint(lambda, phi);\n}\n\nfunction boundsRingStart() {\n areaStream.lineStart();\n}\n\nfunction boundsRingEnd() {\n boundsRingPoint(lambda00, phi00);\n areaStream.lineEnd();\n if (abs(deltaSum) > epsilon) lambda0 = -(lambda1 = 180);\n range[0] = lambda0, range[1] = lambda1;\n p0 = null;\n}\n\n// Finds the left-right distance between two longitudes.\n// This is almost the same as (lambda1 - lambda0 + 360°) % 360°, except that we want\n// the distance between ±180° to be 360°.\nfunction angle(lambda0, lambda1) {\n return (lambda1 -= lambda0) < 0 ? lambda1 + 360 : lambda1;\n}\n\nfunction rangeCompare(a, b) {\n return a[0] - b[0];\n}\n\nfunction rangeContains(range, x) {\n return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;\n}\n\nexport default function(feature) {\n var i, n, a, b, merged, deltaMax, delta;\n\n phi1 = lambda1 = -(lambda0 = phi0 = Infinity);\n ranges = [];\n stream(feature, boundsStream);\n\n // First, sort ranges by their minimum longitudes.\n if (n = ranges.length) {\n ranges.sort(rangeCompare);\n\n // Then, merge any ranges that overlap.\n for (i = 1, a = ranges[0], merged = [a]; i < n; ++i) {\n b = ranges[i];\n if (rangeContains(a, b[0]) || rangeContains(a, b[1])) {\n if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];\n if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];\n } else {\n merged.push(a = b);\n }\n }\n\n // Finally, find the largest gap between the merged ranges.\n // The final bounding box will be the inverse of this gap.\n for (deltaMax = -Infinity, n = merged.length - 1, i = 0, a = merged[n]; i <= n; a = b, ++i) {\n b = merged[i];\n if ((delta = angle(a[1], b[0])) > deltaMax) deltaMax = delta, lambda0 = b[0], lambda1 = a[1];\n }\n }\n\n ranges = range = null;\n\n return lambda0 === Infinity || phi0 === Infinity\n ? [[NaN, NaN], [NaN, NaN]]\n : [[lambda0, phi0], [lambda1, phi1]];\n}\n","import {asin, atan2, cos, sin, sqrt} from \"./math.js\";\n\nexport function spherical(cartesian) {\n return [atan2(cartesian[1], cartesian[0]), asin(cartesian[2])];\n}\n\nexport function cartesian(spherical) {\n var lambda = spherical[0], phi = spherical[1], cosPhi = cos(phi);\n return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)];\n}\n\nexport function cartesianDot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n\nexport function cartesianCross(a, b) {\n 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]];\n}\n\n// TODO return a\nexport function cartesianAddInPlace(a, b) {\n a[0] += b[0], a[1] += b[1], a[2] += b[2];\n}\n\nexport function cartesianScale(vector, k) {\n return [vector[0] * k, vector[1] * k, vector[2] * k];\n}\n\n// TODO return d\nexport function cartesianNormalizeInPlace(d) {\n var l = sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);\n d[0] /= l, d[1] /= l, d[2] /= l;\n}\n","import {asin, atan2, cos, degrees, epsilon, epsilon2, radians, sin, sqrt} from \"./math.js\";\nimport noop from \"./noop.js\";\nimport stream from \"./stream.js\";\n\nvar W0, W1,\n X0, Y0, Z0,\n X1, Y1, Z1,\n X2, Y2, Z2,\n lambda00, phi00, // first point\n x0, y0, z0; // previous point\n\nvar centroidStream = {\n sphere: noop,\n point: centroidPoint,\n lineStart: centroidLineStart,\n lineEnd: centroidLineEnd,\n polygonStart: function() {\n centroidStream.lineStart = centroidRingStart;\n centroidStream.lineEnd = centroidRingEnd;\n },\n polygonEnd: function() {\n centroidStream.lineStart = centroidLineStart;\n centroidStream.lineEnd = centroidLineEnd;\n }\n};\n\n// Arithmetic mean of Cartesian vectors.\nfunction centroidPoint(lambda, phi) {\n lambda *= radians, phi *= radians;\n var cosPhi = cos(phi);\n centroidPointCartesian(cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi));\n}\n\nfunction centroidPointCartesian(x, y, z) {\n ++W0;\n X0 += (x - X0) / W0;\n Y0 += (y - Y0) / W0;\n Z0 += (z - Z0) / W0;\n}\n\nfunction centroidLineStart() {\n centroidStream.point = centroidLinePointFirst;\n}\n\nfunction centroidLinePointFirst(lambda, phi) {\n lambda *= radians, phi *= radians;\n var cosPhi = cos(phi);\n x0 = cosPhi * cos(lambda);\n y0 = cosPhi * sin(lambda);\n z0 = sin(phi);\n centroidStream.point = centroidLinePoint;\n centroidPointCartesian(x0, y0, z0);\n}\n\nfunction centroidLinePoint(lambda, phi) {\n lambda *= radians, phi *= radians;\n var cosPhi = cos(phi),\n x = cosPhi * cos(lambda),\n y = cosPhi * sin(lambda),\n z = sin(phi),\n w = atan2(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);\n W1 += w;\n X1 += w * (x0 + (x0 = x));\n Y1 += w * (y0 + (y0 = y));\n Z1 += w * (z0 + (z0 = z));\n centroidPointCartesian(x0, y0, z0);\n}\n\nfunction centroidLineEnd() {\n centroidStream.point = centroidPoint;\n}\n\n// See J. E. Brock, The Inertia Tensor for a Spherical Triangle,\n// J. Applied Mechanics 42, 239 (1975).\nfunction centroidRingStart() {\n centroidStream.point = centroidRingPointFirst;\n}\n\nfunction centroidRingEnd() {\n centroidRingPoint(lambda00, phi00);\n centroidStream.point = centroidPoint;\n}\n\nfunction centroidRingPointFirst(lambda, phi) {\n lambda00 = lambda, phi00 = phi;\n lambda *= radians, phi *= radians;\n centroidStream.point = centroidRingPoint;\n var cosPhi = cos(phi);\n x0 = cosPhi * cos(lambda);\n y0 = cosPhi * sin(lambda);\n z0 = sin(phi);\n centroidPointCartesian(x0, y0, z0);\n}\n\nfunction centroidRingPoint(lambda, phi) {\n lambda *= radians, phi *= radians;\n var cosPhi = cos(phi),\n x = cosPhi * cos(lambda),\n y = cosPhi * sin(lambda),\n z = sin(phi),\n cx = y0 * z - z0 * y,\n cy = z0 * x - x0 * z,\n cz = x0 * y - y0 * x,\n m = sqrt(cx * cx + cy * cy + cz * cz),\n w = asin(m), // line weight = angle\n v = m && -w / m; // area weight multiplier\n X2 += v * cx;\n Y2 += v * cy;\n Z2 += v * cz;\n W1 += w;\n X1 += w * (x0 + (x0 = x));\n Y1 += w * (y0 + (y0 = y));\n Z1 += w * (z0 + (z0 = z));\n centroidPointCartesian(x0, y0, z0);\n}\n\nexport default function(object) {\n W0 = W1 =\n X0 = Y0 = Z0 =\n X1 = Y1 = Z1 =\n X2 = Y2 = Z2 = 0;\n stream(object, centroidStream);\n\n var x = X2,\n y = Y2,\n z = Z2,\n m = x * x + y * y + z * z;\n\n // If the area-weighted ccentroid is undefined, fall back to length-weighted ccentroid.\n if (m < epsilon2) {\n x = X1, y = Y1, z = Z1;\n // If the feature has zero length, fall back to arithmetic mean of point vectors.\n if (W1 < epsilon) x = X0, y = Y0, z = Z0;\n m = x * x + y * y + z * z;\n // If the feature still has an undefined ccentroid, then return.\n if (m < epsilon2) return [NaN, NaN];\n }\n\n return [atan2(y, x) * degrees, asin(z / sqrt(m)) * degrees];\n}\n","import {cartesian, cartesianNormalizeInPlace, spherical} from \"./cartesian.js\";\nimport constant from \"./constant.js\";\nimport {acos, cos, degrees, epsilon, radians, sin, tau} from \"./math.js\";\nimport {rotateRadians} from \"./rotation.js\";\n\n// Generates a circle centered at [0°, 0°], with a given radius and precision.\nexport function circleStream(stream, radius, delta, direction, t0, t1) {\n if (!delta) return;\n var cosRadius = cos(radius),\n sinRadius = sin(radius),\n step = direction * delta;\n if (t0 == null) {\n t0 = radius + direction * tau;\n t1 = radius - step / 2;\n } else {\n t0 = circleRadius(cosRadius, t0);\n t1 = circleRadius(cosRadius, t1);\n if (direction > 0 ? t0 < t1 : t0 > t1) t0 += direction * tau;\n }\n for (var point, t = t0; direction > 0 ? t > t1 : t < t1; t -= step) {\n point = spherical([cosRadius, -sinRadius * cos(t), -sinRadius * sin(t)]);\n stream.point(point[0], point[1]);\n }\n}\n\n// Returns the signed angle of a cartesian point relative to [cosRadius, 0, 0].\nfunction circleRadius(cosRadius, point) {\n point = cartesian(point), point[0] -= cosRadius;\n cartesianNormalizeInPlace(point);\n var radius = acos(-point[1]);\n return ((-point[2] < 0 ? -radius : radius) + tau - epsilon) % tau;\n}\n\nexport default function() {\n var center = constant([0, 0]),\n radius = constant(90),\n precision = constant(6),\n ring,\n rotate,\n stream = {point: point};\n\n function point(x, y) {\n ring.push(x = rotate(x, y));\n x[0] *= degrees, x[1] *= degrees;\n }\n\n function circle() {\n var c = center.apply(this, arguments),\n r = radius.apply(this, arguments) * radians,\n p = precision.apply(this, arguments) * radians;\n ring = [];\n rotate = rotateRadians(-c[0] * radians, -c[1] * radians, 0).invert;\n circleStream(stream, r, p, 1);\n c = {type: \"Polygon\", coordinates: [ring]};\n ring = rotate = null;\n return c;\n }\n\n circle.center = function(_) {\n return arguments.length ? (center = typeof _ === \"function\" ? _ : constant([+_[0], +_[1]]), circle) : center;\n };\n\n circle.radius = function(_) {\n return arguments.length ? (radius = typeof _ === \"function\" ? _ : constant(+_), circle) : radius;\n };\n\n circle.precision = function(_) {\n return arguments.length ? (precision = typeof _ === \"function\" ? _ : constant(+_), circle) : precision;\n };\n\n return circle;\n}\n","import clip from \"./index.js\";\nimport {abs, atan, cos, epsilon, halfPi, pi, sin} from \"../math.js\";\n\nexport default clip(\n function() { return true; },\n clipAntimeridianLine,\n clipAntimeridianInterpolate,\n [-pi, -halfPi]\n);\n\n// Takes a line and cuts into visible segments. Return values: 0 - there were\n// intersections or the line was empty; 1 - no intersections; 2 - there were\n// intersections, and the first and last segments should be rejoined.\nfunction clipAntimeridianLine(stream) {\n var lambda0 = NaN,\n phi0 = NaN,\n sign0 = NaN,\n clean; // no intersections\n\n return {\n lineStart: function() {\n stream.lineStart();\n clean = 1;\n },\n point: function(lambda1, phi1) {\n var sign1 = lambda1 > 0 ? pi : -pi,\n delta = abs(lambda1 - lambda0);\n if (abs(delta - pi) < epsilon) { // line crosses a pole\n stream.point(lambda0, phi0 = (phi0 + phi1) / 2 > 0 ? halfPi : -halfPi);\n stream.point(sign0, phi0);\n stream.lineEnd();\n stream.lineStart();\n stream.point(sign1, phi0);\n stream.point(lambda1, phi0);\n clean = 0;\n } else if (sign0 !== sign1 && delta >= pi) { // line crosses antimeridian\n if (abs(lambda0 - sign0) < epsilon) lambda0 -= sign0 * epsilon; // handle degeneracies\n if (abs(lambda1 - sign1) < epsilon) lambda1 -= sign1 * epsilon;\n phi0 = clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1);\n stream.point(sign0, phi0);\n stream.lineEnd();\n stream.lineStart();\n stream.point(sign1, phi0);\n clean = 0;\n }\n stream.point(lambda0 = lambda1, phi0 = phi1);\n sign0 = sign1;\n },\n lineEnd: function() {\n stream.lineEnd();\n lambda0 = phi0 = NaN;\n },\n clean: function() {\n return 2 - clean; // if intersections, rejoin first and last segments\n }\n };\n}\n\nfunction clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1) {\n var cosPhi0,\n cosPhi1,\n sinLambda0Lambda1 = sin(lambda0 - lambda1);\n return abs(sinLambda0Lambda1) > epsilon\n ? atan((sin(phi0) * (cosPhi1 = cos(phi1)) * sin(lambda1)\n - sin(phi1) * (cosPhi0 = cos(phi0)) * sin(lambda0))\n / (cosPhi0 * cosPhi1 * sinLambda0Lambda1))\n : (phi0 + phi1) / 2;\n}\n\nfunction clipAntimeridianInterpolate(from, to, direction, stream) {\n var phi;\n if (from == null) {\n phi = direction * halfPi;\n stream.point(-pi, phi);\n stream.point(0, phi);\n stream.point(pi, phi);\n stream.point(pi, 0);\n stream.point(pi, -phi);\n stream.point(0, -phi);\n stream.point(-pi, -phi);\n stream.point(-pi, 0);\n stream.point(-pi, phi);\n } else if (abs(from[0] - to[0]) > epsilon) {\n var lambda = from[0] < to[0] ? pi : -pi;\n phi = direction * lambda / 2;\n stream.point(-lambda, phi);\n stream.point(0, phi);\n stream.point(lambda, phi);\n } else {\n stream.point(to[0], to[1]);\n }\n}\n","import noop from \"../noop.js\";\n\nexport default function() {\n var lines = [],\n line;\n return {\n point: function(x, y, m) {\n line.push([x, y, m]);\n },\n lineStart: function() {\n lines.push(line = []);\n },\n lineEnd: noop,\n rejoin: function() {\n if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));\n },\n result: function() {\n var result = lines;\n lines = [];\n line = null;\n return result;\n }\n };\n}\n","import {cartesian, cartesianAddInPlace, cartesianCross, cartesianDot, cartesianScale, spherical} from \"../cartesian.js\";\nimport {circleStream} from \"../circle.js\";\nimport {abs, cos, epsilon, pi, radians, sqrt} from \"../math.js\";\nimport pointEqual from \"../pointEqual.js\";\nimport clip from \"./index.js\";\n\nexport default function(radius) {\n var cr = cos(radius),\n delta = 6 * radians,\n smallRadius = cr > 0,\n notHemisphere = abs(cr) > epsilon; // TODO optimise for this common case\n\n function interpolate(from, to, direction, stream) {\n circleStream(stream, radius, delta, direction, from, to);\n }\n\n function visible(lambda, phi) {\n return cos(lambda) * cos(phi) > cr;\n }\n\n // Takes a line and cuts into visible segments. Return values used for polygon\n // clipping: 0 - there were intersections or the line was empty; 1 - no\n // intersections 2 - there were intersections, and the first and last segments\n // should be rejoined.\n function clipLine(stream) {\n var point0, // previous point\n c0, // code for previous point\n v0, // visibility of previous point\n v00, // visibility of first point\n clean; // no intersections\n return {\n lineStart: function() {\n v00 = v0 = false;\n clean = 1;\n },\n point: function(lambda, phi) {\n var point1 = [lambda, phi],\n point2,\n v = visible(lambda, phi),\n c = smallRadius\n ? v ? 0 : code(lambda, phi)\n : v ? code(lambda + (lambda < 0 ? pi : -pi), phi) : 0;\n if (!point0 && (v00 = v0 = v)) stream.lineStart();\n if (v !== v0) {\n point2 = intersect(point0, point1);\n if (!point2 || pointEqual(point0, point2) || pointEqual(point1, point2))\n point1[2] = 1;\n }\n if (v !== v0) {\n clean = 0;\n if (v) {\n // outside going in\n stream.lineStart();\n point2 = intersect(point1, point0);\n stream.point(point2[0], point2[1]);\n } else {\n // inside going out\n point2 = intersect(point0, point1);\n stream.point(point2[0], point2[1], 2);\n stream.lineEnd();\n }\n point0 = point2;\n } else if (notHemisphere && point0 && smallRadius ^ v) {\n var t;\n // If the codes for two points are different, or are both zero,\n // and there this segment intersects with the small circle.\n if (!(c & c0) && (t = intersect(point1, point0, true))) {\n clean = 0;\n if (smallRadius) {\n stream.lineStart();\n stream.point(t[0][0], t[0][1]);\n stream.point(t[1][0], t[1][1]);\n stream.lineEnd();\n } else {\n stream.point(t[1][0], t[1][1]);\n stream.lineEnd();\n stream.lineStart();\n stream.point(t[0][0], t[0][1], 3);\n }\n }\n }\n if (v && (!point0 || !pointEqual(point0, point1))) {\n stream.point(point1[0], point1[1]);\n }\n point0 = point1, v0 = v, c0 = c;\n },\n lineEnd: function() {\n if (v0) stream.lineEnd();\n point0 = null;\n },\n // Rejoin first and last segments if there were intersections and the first\n // and last points were visible.\n clean: function() {\n return clean | ((v00 && v0) << 1);\n }\n };\n }\n\n // Intersects the great circle between a and b with the clip circle.\n function intersect(a, b, two) {\n var pa = cartesian(a),\n pb = cartesian(b);\n\n // We have two planes, n1.p = d1 and n2.p = d2.\n // Find intersection line p(t) = c1 n1 + c2 n2 + t (n1 ⨯ n2).\n var n1 = [1, 0, 0], // normal\n n2 = cartesianCross(pa, pb),\n n2n2 = cartesianDot(n2, n2),\n n1n2 = n2[0], // cartesianDot(n1, n2),\n determinant = n2n2 - n1n2 * n1n2;\n\n // Two polar points.\n if (!determinant) return !two && a;\n\n var c1 = cr * n2n2 / determinant,\n c2 = -cr * n1n2 / determinant,\n n1xn2 = cartesianCross(n1, n2),\n A = cartesianScale(n1, c1),\n B = cartesianScale(n2, c2);\n cartesianAddInPlace(A, B);\n\n // Solve |p(t)|^2 = 1.\n var u = n1xn2,\n w = cartesianDot(A, u),\n uu = cartesianDot(u, u),\n t2 = w * w - uu * (cartesianDot(A, A) - 1);\n\n if (t2 < 0) return;\n\n var t = sqrt(t2),\n q = cartesianScale(u, (-w - t) / uu);\n cartesianAddInPlace(q, A);\n q = spherical(q);\n\n if (!two) return q;\n\n // Two intersection points.\n var lambda0 = a[0],\n lambda1 = b[0],\n phi0 = a[1],\n phi1 = b[1],\n z;\n\n if (lambda1 < lambda0) z = lambda0, lambda0 = lambda1, lambda1 = z;\n\n var delta = lambda1 - lambda0,\n polar = abs(delta - pi) < epsilon,\n meridian = polar || delta < epsilon;\n\n if (!polar && phi1 < phi0) z = phi0, phi0 = phi1, phi1 = z;\n\n // Check that the first point is between a and b.\n if (meridian\n ? polar\n ? phi0 + phi1 > 0 ^ q[1] < (abs(q[0] - lambda0) < epsilon ? phi0 : phi1)\n : phi0 <= q[1] && q[1] <= phi1\n : delta > pi ^ (lambda0 <= q[0] && q[0] <= lambda1)) {\n var q1 = cartesianScale(u, (-w + t) / uu);\n cartesianAddInPlace(q1, A);\n return [q, spherical(q1)];\n }\n }\n\n // Generates a 4-bit vector representing the location of a point relative to\n // the small circle's bounding box.\n function code(lambda, phi) {\n var r = smallRadius ? radius : pi - radius,\n code = 0;\n if (lambda < -r) code |= 1; // left\n else if (lambda > r) code |= 2; // right\n if (phi < -r) code |= 4; // below\n else if (phi > r) code |= 8; // above\n return code;\n }\n\n return clip(visible, clipLine, interpolate, smallRadius ? [0, -radius] : [-pi, radius - pi]);\n}\n","import clipRectangle from \"./rectangle.js\";\n\nexport default function() {\n var x0 = 0,\n y0 = 0,\n x1 = 960,\n y1 = 500,\n cache,\n cacheStream,\n clip;\n\n return clip = {\n stream: function(stream) {\n return cache && cacheStream === stream ? cache : cache = clipRectangle(x0, y0, x1, y1)(cacheStream = stream);\n },\n extent: function(_) {\n return arguments.length ? (x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1], cache = cacheStream = null, clip) : [[x0, y0], [x1, y1]];\n }\n };\n}\n","import clipBuffer from \"./buffer.js\";\nimport clipRejoin from \"./rejoin.js\";\nimport {epsilon, halfPi} from \"../math.js\";\nimport polygonContains from \"../polygonContains.js\";\nimport {merge} from \"d3-array\";\n\nexport default function(pointVisible, clipLine, interpolate, start) {\n return function(sink) {\n var line = clipLine(sink),\n ringBuffer = clipBuffer(),\n ringSink = clipLine(ringBuffer),\n polygonStarted = false,\n polygon,\n segments,\n ring;\n\n var clip = {\n point: point,\n lineStart: lineStart,\n lineEnd: lineEnd,\n polygonStart: function() {\n clip.point = pointRing;\n clip.lineStart = ringStart;\n clip.lineEnd = ringEnd;\n segments = [];\n polygon = [];\n },\n polygonEnd: function() {\n clip.point = point;\n clip.lineStart = lineStart;\n clip.lineEnd = lineEnd;\n segments = merge(segments);\n var startInside = polygonContains(polygon, start);\n if (segments.length) {\n if (!polygonStarted) sink.polygonStart(), polygonStarted = true;\n clipRejoin(segments, compareIntersection, startInside, interpolate, sink);\n } else if (startInside) {\n if (!polygonStarted) sink.polygonStart(), polygonStarted = true;\n sink.lineStart();\n interpolate(null, null, 1, sink);\n sink.lineEnd();\n }\n if (polygonStarted) sink.polygonEnd(), polygonStarted = false;\n segments = polygon = null;\n },\n sphere: function() {\n sink.polygonStart();\n sink.lineStart();\n interpolate(null, null, 1, sink);\n sink.lineEnd();\n sink.polygonEnd();\n }\n };\n\n function point(lambda, phi) {\n if (pointVisible(lambda, phi)) sink.point(lambda, phi);\n }\n\n function pointLine(lambda, phi) {\n line.point(lambda, phi);\n }\n\n function lineStart() {\n clip.point = pointLine;\n line.lineStart();\n }\n\n function lineEnd() {\n clip.point = point;\n line.lineEnd();\n }\n\n function pointRing(lambda, phi) {\n ring.push([lambda, phi]);\n ringSink.point(lambda, phi);\n }\n\n function ringStart() {\n ringSink.lineStart();\n ring = [];\n }\n\n function ringEnd() {\n pointRing(ring[0][0], ring[0][1]);\n ringSink.lineEnd();\n\n var clean = ringSink.clean(),\n ringSegments = ringBuffer.result(),\n i, n = ringSegments.length, m,\n segment,\n point;\n\n ring.pop();\n polygon.push(ring);\n ring = null;\n\n if (!n) return;\n\n // No intersections.\n if (clean & 1) {\n segment = ringSegments[0];\n if ((m = segment.length - 1) > 0) {\n if (!polygonStarted) sink.polygonStart(), polygonStarted = true;\n sink.lineStart();\n for (i = 0; i < m; ++i) sink.point((point = segment[i])[0], point[1]);\n sink.lineEnd();\n }\n return;\n }\n\n // Rejoin connected segments.\n // TODO reuse ringBuffer.rejoin()?\n if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));\n\n segments.push(ringSegments.filter(validSegment));\n }\n\n return clip;\n };\n}\n\nfunction validSegment(segment) {\n return segment.length > 1;\n}\n\n// Intersections are sorted along the clip edge. For both antimeridian cutting\n// and circle clipping, the same comparison is used.\nfunction compareIntersection(a, b) {\n return ((a = a.x)[0] < 0 ? a[1] - halfPi - epsilon : halfPi - a[1])\n - ((b = b.x)[0] < 0 ? b[1] - halfPi - epsilon : halfPi - b[1]);\n}\n","export default function(a, b, x0, y0, x1, y1) {\n var ax = a[0],\n ay = a[1],\n bx = b[0],\n by = b[1],\n t0 = 0,\n t1 = 1,\n dx = bx - ax,\n dy = by - ay,\n r;\n\n r = x0 - ax;\n if (!dx && r > 0) return;\n r /= dx;\n if (dx < 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n } else if (dx > 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n }\n\n r = x1 - ax;\n if (!dx && r < 0) return;\n r /= dx;\n if (dx < 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n } else if (dx > 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n }\n\n r = y0 - ay;\n if (!dy && r > 0) return;\n r /= dy;\n if (dy < 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n } else if (dy > 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n }\n\n r = y1 - ay;\n if (!dy && r < 0) return;\n r /= dy;\n if (dy < 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n } else if (dy > 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n }\n\n if (t0 > 0) a[0] = ax + t0 * dx, a[1] = ay + t0 * dy;\n if (t1 < 1) b[0] = ax + t1 * dx, b[1] = ay + t1 * dy;\n return true;\n}\n","import {abs, epsilon} from \"../math.js\";\nimport clipBuffer from \"./buffer.js\";\nimport clipLine from \"./line.js\";\nimport clipRejoin from \"./rejoin.js\";\nimport {merge} from \"d3-array\";\n\nvar clipMax = 1e9, clipMin = -clipMax;\n\n// TODO Use d3-polygon’s polygonContains here for the ring check?\n// TODO Eliminate duplicate buffering in clipBuffer and polygon.push?\n\nexport default function clipRectangle(x0, y0, x1, y1) {\n\n function visible(x, y) {\n return x0 <= x && x <= x1 && y0 <= y && y <= y1;\n }\n\n function interpolate(from, to, direction, stream) {\n var a = 0, a1 = 0;\n if (from == null\n || (a = corner(from, direction)) !== (a1 = corner(to, direction))\n || comparePoint(from, to) < 0 ^ direction > 0) {\n do stream.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);\n while ((a = (a + direction + 4) % 4) !== a1);\n } else {\n stream.point(to[0], to[1]);\n }\n }\n\n function corner(p, direction) {\n return abs(p[0] - x0) < epsilon ? direction > 0 ? 0 : 3\n : abs(p[0] - x1) < epsilon ? direction > 0 ? 2 : 1\n : abs(p[1] - y0) < epsilon ? direction > 0 ? 1 : 0\n : direction > 0 ? 3 : 2; // abs(p[1] - y1) < epsilon\n }\n\n function compareIntersection(a, b) {\n return comparePoint(a.x, b.x);\n }\n\n function comparePoint(a, b) {\n var ca = corner(a, 1),\n cb = corner(b, 1);\n return ca !== cb ? ca - cb\n : ca === 0 ? b[1] - a[1]\n : ca === 1 ? a[0] - b[0]\n : ca === 2 ? a[1] - b[1]\n : b[0] - a[0];\n }\n\n return function(stream) {\n var activeStream = stream,\n bufferStream = clipBuffer(),\n segments,\n polygon,\n ring,\n x__, y__, v__, // first point\n x_, y_, v_, // previous point\n first,\n clean;\n\n var clipStream = {\n point: point,\n lineStart: lineStart,\n lineEnd: lineEnd,\n polygonStart: polygonStart,\n polygonEnd: polygonEnd\n };\n\n function point(x, y) {\n if (visible(x, y)) activeStream.point(x, y);\n }\n\n function polygonInside() {\n var winding = 0;\n\n for (var i = 0, n = polygon.length; i < n; ++i) {\n for (var ring = polygon[i], j = 1, m = ring.length, point = ring[0], a0, a1, b0 = point[0], b1 = point[1]; j < m; ++j) {\n a0 = b0, a1 = b1, point = ring[j], b0 = point[0], b1 = point[1];\n if (a1 <= y1) { if (b1 > y1 && (b0 - a0) * (y1 - a1) > (b1 - a1) * (x0 - a0)) ++winding; }\n else { if (b1 <= y1 && (b0 - a0) * (y1 - a1) < (b1 - a1) * (x0 - a0)) --winding; }\n }\n }\n\n return winding;\n }\n\n // Buffer geometry within a polygon and then clip it en masse.\n function polygonStart() {\n activeStream = bufferStream, segments = [], polygon = [], clean = true;\n }\n\n function polygonEnd() {\n var startInside = polygonInside(),\n cleanInside = clean && startInside,\n visible = (segments = merge(segments)).length;\n if (cleanInside || visible) {\n stream.polygonStart();\n if (cleanInside) {\n stream.lineStart();\n interpolate(null, null, 1, stream);\n stream.lineEnd();\n }\n if (visible) {\n clipRejoin(segments, compareIntersection, startInside, interpolate, stream);\n }\n stream.polygonEnd();\n }\n activeStream = stream, segments = polygon = ring = null;\n }\n\n function lineStart() {\n clipStream.point = linePoint;\n if (polygon) polygon.push(ring = []);\n first = true;\n v_ = false;\n x_ = y_ = NaN;\n }\n\n // TODO rather than special-case polygons, simply handle them separately.\n // Ideally, coincident intersection points should be jittered to avoid\n // clipping issues.\n function lineEnd() {\n if (segments) {\n linePoint(x__, y__);\n if (v__ && v_) bufferStream.rejoin();\n segments.push(bufferStream.result());\n }\n clipStream.point = point;\n if (v_) activeStream.lineEnd();\n }\n\n function linePoint(x, y) {\n var v = visible(x, y);\n if (polygon) ring.push([x, y]);\n if (first) {\n x__ = x, y__ = y, v__ = v;\n first = false;\n if (v) {\n activeStream.lineStart();\n activeStream.point(x, y);\n }\n } else {\n if (v && v_) activeStream.point(x, y);\n else {\n var a = [x_ = Math.max(clipMin, Math.min(clipMax, x_)), y_ = Math.max(clipMin, Math.min(clipMax, y_))],\n b = [x = Math.max(clipMin, Math.min(clipMax, x)), y = Math.max(clipMin, Math.min(clipMax, y))];\n if (clipLine(a, b, x0, y0, x1, y1)) {\n if (!v_) {\n activeStream.lineStart();\n activeStream.point(a[0], a[1]);\n }\n activeStream.point(b[0], b[1]);\n if (!v) activeStream.lineEnd();\n clean = false;\n } else if (v) {\n activeStream.lineStart();\n activeStream.point(x, y);\n clean = false;\n }\n }\n }\n x_ = x, y_ = y, v_ = v;\n }\n\n return clipStream;\n };\n}\n","import pointEqual from \"../pointEqual.js\";\nimport {epsilon} from \"../math.js\";\n\nfunction Intersection(point, points, other, entry) {\n this.x = point;\n this.z = points;\n this.o = other; // another intersection\n this.e = entry; // is an entry?\n this.v = false; // visited\n this.n = this.p = null; // next & previous\n}\n\n// A generalized polygon clipping algorithm: given a polygon that has been cut\n// into its visible line segments, and rejoins the segments by interpolating\n// along the clip edge.\nexport default function(segments, compareIntersection, startInside, interpolate, stream) {\n var subject = [],\n clip = [],\n i,\n n;\n\n segments.forEach(function(segment) {\n if ((n = segment.length - 1) <= 0) return;\n var n, p0 = segment[0], p1 = segment[n], x;\n\n if (pointEqual(p0, p1)) {\n if (!p0[2] && !p1[2]) {\n stream.lineStart();\n for (i = 0; i < n; ++i) stream.point((p0 = segment[i])[0], p0[1]);\n stream.lineEnd();\n return;\n }\n // handle degenerate cases by moving the point\n p1[0] += 2 * epsilon;\n }\n\n subject.push(x = new Intersection(p0, segment, null, true));\n clip.push(x.o = new Intersection(p0, null, x, false));\n subject.push(x = new Intersection(p1, segment, null, false));\n clip.push(x.o = new Intersection(p1, null, x, true));\n });\n\n if (!subject.length) return;\n\n clip.sort(compareIntersection);\n link(subject);\n link(clip);\n\n for (i = 0, n = clip.length; i < n; ++i) {\n clip[i].e = startInside = !startInside;\n }\n\n var start = subject[0],\n points,\n point;\n\n while (1) {\n // Find first unvisited intersection.\n var current = start,\n isSubject = true;\n while (current.v) if ((current = current.n) === start) return;\n points = current.z;\n stream.lineStart();\n do {\n current.v = current.o.v = true;\n if (current.e) {\n if (isSubject) {\n for (i = 0, n = points.length; i < n; ++i) stream.point((point = points[i])[0], point[1]);\n } else {\n interpolate(current.x, current.n.x, 1, stream);\n }\n current = current.n;\n } else {\n if (isSubject) {\n points = current.p.z;\n for (i = points.length - 1; i >= 0; --i) stream.point((point = points[i])[0], point[1]);\n } else {\n interpolate(current.x, current.p.x, -1, stream);\n }\n current = current.p;\n }\n current = current.o;\n points = current.z;\n isSubject = !isSubject;\n } while (!current.v);\n stream.lineEnd();\n }\n}\n\nfunction link(array) {\n if (!(n = array.length)) return;\n var n,\n i = 0,\n a = array[0],\n b;\n while (++i < n) {\n a.n = b = array[i];\n b.p = a;\n a = b;\n }\n a.n = b = array[0];\n b.p = a;\n}\n","export default function(a, b) {\n\n function compose(x, y) {\n return x = a(x, y), b(x[0], x[1]);\n }\n\n if (a.invert && b.invert) compose.invert = function(x, y) {\n return x = b.invert(x, y), x && a.invert(x[0], x[1]);\n };\n\n return compose;\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","import {default as polygonContains} from \"./polygonContains.js\";\nimport {default as distance} from \"./distance.js\";\nimport {epsilon2, radians} from \"./math.js\";\n\nvar containsObjectType = {\n Feature: function(object, point) {\n return containsGeometry(object.geometry, point);\n },\n FeatureCollection: function(object, point) {\n var features = object.features, i = -1, n = features.length;\n while (++i < n) if (containsGeometry(features[i].geometry, point)) return true;\n return false;\n }\n};\n\nvar containsGeometryType = {\n Sphere: function() {\n return true;\n },\n Point: function(object, point) {\n return containsPoint(object.coordinates, point);\n },\n MultiPoint: function(object, point) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) if (containsPoint(coordinates[i], point)) return true;\n return false;\n },\n LineString: function(object, point) {\n return containsLine(object.coordinates, point);\n },\n MultiLineString: function(object, point) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) if (containsLine(coordinates[i], point)) return true;\n return false;\n },\n Polygon: function(object, point) {\n return containsPolygon(object.coordinates, point);\n },\n MultiPolygon: function(object, point) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) if (containsPolygon(coordinates[i], point)) return true;\n return false;\n },\n GeometryCollection: function(object, point) {\n var geometries = object.geometries, i = -1, n = geometries.length;\n while (++i < n) if (containsGeometry(geometries[i], point)) return true;\n return false;\n }\n};\n\nfunction containsGeometry(geometry, point) {\n return geometry && containsGeometryType.hasOwnProperty(geometry.type)\n ? containsGeometryType[geometry.type](geometry, point)\n : false;\n}\n\nfunction containsPoint(coordinates, point) {\n return distance(coordinates, point) === 0;\n}\n\nfunction containsLine(coordinates, point) {\n var ao, bo, ab;\n for (var i = 0, n = coordinates.length; i < n; i++) {\n bo = distance(coordinates[i], point);\n if (bo === 0) return true;\n if (i > 0) {\n ab = distance(coordinates[i], coordinates[i - 1]);\n if (\n ab > 0 &&\n ao <= ab &&\n bo <= ab &&\n (ao + bo - ab) * (1 - Math.pow((ao - bo) / ab, 2)) < epsilon2 * ab\n )\n return true;\n }\n ao = bo;\n }\n return false;\n}\n\nfunction containsPolygon(coordinates, point) {\n return !!polygonContains(coordinates.map(ringRadians), pointRadians(point));\n}\n\nfunction ringRadians(ring) {\n return ring = ring.map(pointRadians), ring.pop(), ring;\n}\n\nfunction pointRadians(point) {\n return [point[0] * radians, point[1] * radians];\n}\n\nexport default function(object, point) {\n return (object && containsObjectType.hasOwnProperty(object.type)\n ? containsObjectType[object.type]\n : containsGeometry)(object, point);\n}\n","import length from \"./length.js\";\n\nvar coordinates = [null, null],\n object = {type: \"LineString\", coordinates: coordinates};\n\nexport default function(a, b) {\n coordinates[0] = a;\n coordinates[1] = b;\n return length(object);\n}\n","import {range} from \"d3-array\";\nimport {abs, ceil, epsilon} from \"./math.js\";\n\nfunction graticuleX(y0, y1, dy) {\n var y = range(y0, y1 - epsilon, dy).concat(y1);\n return function(x) { return y.map(function(y) { return [x, y]; }); };\n}\n\nfunction graticuleY(x0, x1, dx) {\n var x = range(x0, x1 - epsilon, dx).concat(x1);\n return function(y) { return x.map(function(x) { return [x, y]; }); };\n}\n\nexport default function graticule() {\n var x1, x0, X1, X0,\n y1, y0, Y1, Y0,\n dx = 10, dy = dx, DX = 90, DY = 360,\n x, y, X, Y,\n precision = 2.5;\n\n function graticule() {\n return {type: \"MultiLineString\", coordinates: lines()};\n }\n\n function lines() {\n return range(ceil(X0 / DX) * DX, X1, DX).map(X)\n .concat(range(ceil(Y0 / DY) * DY, Y1, DY).map(Y))\n .concat(range(ceil(x0 / dx) * dx, x1, dx).filter(function(x) { return abs(x % DX) > epsilon; }).map(x))\n .concat(range(ceil(y0 / dy) * dy, y1, dy).filter(function(y) { return abs(y % DY) > epsilon; }).map(y));\n }\n\n graticule.lines = function() {\n return lines().map(function(coordinates) { return {type: \"LineString\", coordinates: coordinates}; });\n };\n\n graticule.outline = function() {\n return {\n type: \"Polygon\",\n coordinates: [\n X(X0).concat(\n Y(Y1).slice(1),\n X(X1).reverse().slice(1),\n Y(Y0).reverse().slice(1))\n ]\n };\n };\n\n graticule.extent = function(_) {\n if (!arguments.length) return graticule.extentMinor();\n return graticule.extentMajor(_).extentMinor(_);\n };\n\n graticule.extentMajor = function(_) {\n if (!arguments.length) return [[X0, Y0], [X1, Y1]];\n X0 = +_[0][0], X1 = +_[1][0];\n Y0 = +_[0][1], Y1 = +_[1][1];\n if (X0 > X1) _ = X0, X0 = X1, X1 = _;\n if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;\n return graticule.precision(precision);\n };\n\n graticule.extentMinor = function(_) {\n if (!arguments.length) return [[x0, y0], [x1, y1]];\n x0 = +_[0][0], x1 = +_[1][0];\n y0 = +_[0][1], y1 = +_[1][1];\n if (x0 > x1) _ = x0, x0 = x1, x1 = _;\n if (y0 > y1) _ = y0, y0 = y1, y1 = _;\n return graticule.precision(precision);\n };\n\n graticule.step = function(_) {\n if (!arguments.length) return graticule.stepMinor();\n return graticule.stepMajor(_).stepMinor(_);\n };\n\n graticule.stepMajor = function(_) {\n if (!arguments.length) return [DX, DY];\n DX = +_[0], DY = +_[1];\n return graticule;\n };\n\n graticule.stepMinor = function(_) {\n if (!arguments.length) return [dx, dy];\n dx = +_[0], dy = +_[1];\n return graticule;\n };\n\n graticule.precision = function(_) {\n if (!arguments.length) return precision;\n precision = +_;\n x = graticuleX(y0, y1, 90);\n y = graticuleY(x0, x1, precision);\n X = graticuleX(Y0, Y1, 90);\n Y = graticuleY(X0, X1, precision);\n return graticule;\n };\n\n return graticule\n .extentMajor([[-180, -90 + epsilon], [180, 90 - epsilon]])\n .extentMinor([[-180, -80 - epsilon], [180, 80 + epsilon]]);\n}\n\nexport function graticule10() {\n return graticule()();\n}\n","export default function(x) {\n return x;\n}\n","export {default as geoArea} from \"./area.js\";\nexport {default as geoBounds} from \"./bounds.js\";\nexport {default as geoCentroid} from \"./centroid.js\";\nexport {default as geoCircle} from \"./circle.js\";\nexport {default as geoClipAntimeridian} from \"./clip/antimeridian.js\";\nexport {default as geoClipCircle} from \"./clip/circle.js\";\nexport {default as geoClipExtent} from \"./clip/extent.js\"; // DEPRECATED! Use d3.geoIdentity().clipExtent(…).\nexport {default as geoClipRectangle} from \"./clip/rectangle.js\";\nexport {default as geoContains} from \"./contains.js\";\nexport {default as geoDistance} from \"./distance.js\";\nexport {default as geoGraticule, graticule10 as geoGraticule10} from \"./graticule.js\";\nexport {default as geoInterpolate} from \"./interpolate.js\";\nexport {default as geoLength} from \"./length.js\";\nexport {default as geoPath} from \"./path/index.js\";\nexport {default as geoAlbers} from \"./projection/albers.js\";\nexport {default as geoAlbersUsa} from \"./projection/albersUsa.js\";\nexport {default as geoAzimuthalEqualArea, azimuthalEqualAreaRaw as geoAzimuthalEqualAreaRaw} from \"./projection/azimuthalEqualArea.js\";\nexport {default as geoAzimuthalEquidistant, azimuthalEquidistantRaw as geoAzimuthalEquidistantRaw} from \"./projection/azimuthalEquidistant.js\";\nexport {default as geoConicConformal, conicConformalRaw as geoConicConformalRaw} from \"./projection/conicConformal.js\";\nexport {default as geoConicEqualArea, conicEqualAreaRaw as geoConicEqualAreaRaw} from \"./projection/conicEqualArea.js\";\nexport {default as geoConicEquidistant, conicEquidistantRaw as geoConicEquidistantRaw} from \"./projection/conicEquidistant.js\";\nexport {default as geoEqualEarth, equalEarthRaw as geoEqualEarthRaw} from \"./projection/equalEarth.js\";\nexport {default as geoEquirectangular, equirectangularRaw as geoEquirectangularRaw} from \"./projection/equirectangular.js\";\nexport {default as geoGnomonic, gnomonicRaw as geoGnomonicRaw} from \"./projection/gnomonic.js\";\nexport {default as geoIdentity} from \"./projection/identity.js\";\nexport {default as geoProjection, projectionMutator as geoProjectionMutator} from \"./projection/index.js\";\nexport {default as geoMercator, mercatorRaw as geoMercatorRaw} from \"./projection/mercator.js\";\nexport {default as geoNaturalEarth1, naturalEarth1Raw as geoNaturalEarth1Raw} from \"./projection/naturalEarth1.js\";\nexport {default as geoOrthographic, orthographicRaw as geoOrthographicRaw} from \"./projection/orthographic.js\";\nexport {default as geoStereographic, stereographicRaw as geoStereographicRaw} from \"./projection/stereographic.js\";\nexport {default as geoTransverseMercator, transverseMercatorRaw as geoTransverseMercatorRaw} from \"./projection/transverseMercator.js\";\nexport {default as geoRotation} from \"./rotation.js\";\nexport {default as geoStream} from \"./stream.js\";\nexport {default as geoTransform} from \"./transform.js\";\n","import {asin, atan2, cos, degrees, haversin, radians, sin, sqrt} from \"./math.js\";\n\nexport default function(a, b) {\n var x0 = a[0] * radians,\n y0 = a[1] * radians,\n x1 = b[0] * radians,\n y1 = b[1] * radians,\n cy0 = cos(y0),\n sy0 = sin(y0),\n cy1 = cos(y1),\n sy1 = sin(y1),\n kx0 = cy0 * cos(x0),\n ky0 = cy0 * sin(x0),\n kx1 = cy1 * cos(x1),\n ky1 = cy1 * sin(x1),\n d = 2 * asin(sqrt(haversin(y1 - y0) + cy0 * cy1 * haversin(x1 - x0))),\n k = sin(d);\n\n var interpolate = d ? function(t) {\n var B = sin(t *= d) / k,\n A = sin(d - t) / k,\n x = A * kx0 + B * kx1,\n y = A * ky0 + B * ky1,\n z = A * sy0 + B * sy1;\n return [\n atan2(y, x) * degrees,\n atan2(z, sqrt(x * x + y * y)) * degrees\n ];\n } : function() {\n return [x0 * degrees, y0 * degrees];\n };\n\n interpolate.distance = d;\n\n return interpolate;\n}\n","import adder from \"./adder.js\";\nimport {abs, atan2, cos, radians, sin, sqrt} from \"./math.js\";\nimport noop from \"./noop.js\";\nimport stream from \"./stream.js\";\n\nvar lengthSum = adder(),\n lambda0,\n sinPhi0,\n cosPhi0;\n\nvar lengthStream = {\n sphere: noop,\n point: noop,\n lineStart: lengthLineStart,\n lineEnd: noop,\n polygonStart: noop,\n polygonEnd: noop\n};\n\nfunction lengthLineStart() {\n lengthStream.point = lengthPointFirst;\n lengthStream.lineEnd = lengthLineEnd;\n}\n\nfunction lengthLineEnd() {\n lengthStream.point = lengthStream.lineEnd = noop;\n}\n\nfunction lengthPointFirst(lambda, phi) {\n lambda *= radians, phi *= radians;\n lambda0 = lambda, sinPhi0 = sin(phi), cosPhi0 = cos(phi);\n lengthStream.point = lengthPoint;\n}\n\nfunction lengthPoint(lambda, phi) {\n lambda *= radians, phi *= radians;\n var sinPhi = sin(phi),\n cosPhi = cos(phi),\n delta = abs(lambda - lambda0),\n cosDelta = cos(delta),\n sinDelta = sin(delta),\n x = cosPhi * sinDelta,\n y = cosPhi0 * sinPhi - sinPhi0 * cosPhi * cosDelta,\n z = sinPhi0 * sinPhi + cosPhi0 * cosPhi * cosDelta;\n lengthSum.add(atan2(sqrt(x * x + y * y), z));\n lambda0 = lambda, sinPhi0 = sinPhi, cosPhi0 = cosPhi;\n}\n\nexport default function(object) {\n lengthSum.reset();\n stream(object, lengthStream);\n return +lengthSum;\n}\n","export var epsilon = 1e-6;\nexport var epsilon2 = 1e-12;\nexport var pi = Math.PI;\nexport var halfPi = pi / 2;\nexport var quarterPi = pi / 4;\nexport var tau = pi * 2;\n\nexport var degrees = 180 / pi;\nexport var radians = pi / 180;\n\nexport var abs = Math.abs;\nexport var atan = Math.atan;\nexport var atan2 = Math.atan2;\nexport var cos = Math.cos;\nexport var ceil = Math.ceil;\nexport var exp = Math.exp;\nexport var floor = Math.floor;\nexport var log = Math.log;\nexport var pow = Math.pow;\nexport var sin = Math.sin;\nexport var sign = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; };\nexport var sqrt = Math.sqrt;\nexport var tan = Math.tan;\n\nexport function acos(x) {\n return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);\n}\n\nexport function asin(x) {\n return x > 1 ? halfPi : x < -1 ? -halfPi : Math.asin(x);\n}\n\nexport function haversin(x) {\n return (x = sin(x / 2)) * x;\n}\n","export default function noop() {}\n","import adder from \"../adder.js\";\nimport {abs} from \"../math.js\";\nimport noop from \"../noop.js\";\n\nvar areaSum = adder(),\n areaRingSum = adder(),\n x00,\n y00,\n x0,\n y0;\n\nvar areaStream = {\n point: noop,\n lineStart: noop,\n lineEnd: noop,\n polygonStart: function() {\n areaStream.lineStart = areaRingStart;\n areaStream.lineEnd = areaRingEnd;\n },\n polygonEnd: function() {\n areaStream.lineStart = areaStream.lineEnd = areaStream.point = noop;\n areaSum.add(abs(areaRingSum));\n areaRingSum.reset();\n },\n result: function() {\n var area = areaSum / 2;\n areaSum.reset();\n return area;\n }\n};\n\nfunction areaRingStart() {\n areaStream.point = areaPointFirst;\n}\n\nfunction areaPointFirst(x, y) {\n areaStream.point = areaPoint;\n x00 = x0 = x, y00 = y0 = y;\n}\n\nfunction areaPoint(x, y) {\n areaRingSum.add(y0 * x - x0 * y);\n x0 = x, y0 = y;\n}\n\nfunction areaRingEnd() {\n areaPoint(x00, y00);\n}\n\nexport default areaStream;\n","import noop from \"../noop.js\";\n\nvar x0 = Infinity,\n y0 = x0,\n x1 = -x0,\n y1 = x1;\n\nvar boundsStream = {\n point: boundsPoint,\n lineStart: noop,\n lineEnd: noop,\n polygonStart: noop,\n polygonEnd: noop,\n result: function() {\n var bounds = [[x0, y0], [x1, y1]];\n x1 = y1 = -(y0 = x0 = Infinity);\n return bounds;\n }\n};\n\nfunction boundsPoint(x, y) {\n if (x < x0) x0 = x;\n if (x > x1) x1 = x;\n if (y < y0) y0 = y;\n if (y > y1) y1 = y;\n}\n\nexport default boundsStream;\n","import {sqrt} from \"../math.js\";\n\n// TODO Enforce positive area for exterior, negative area for interior?\n\nvar X0 = 0,\n Y0 = 0,\n Z0 = 0,\n X1 = 0,\n Y1 = 0,\n Z1 = 0,\n X2 = 0,\n Y2 = 0,\n Z2 = 0,\n x00,\n y00,\n x0,\n y0;\n\nvar centroidStream = {\n point: centroidPoint,\n lineStart: centroidLineStart,\n lineEnd: centroidLineEnd,\n polygonStart: function() {\n centroidStream.lineStart = centroidRingStart;\n centroidStream.lineEnd = centroidRingEnd;\n },\n polygonEnd: function() {\n centroidStream.point = centroidPoint;\n centroidStream.lineStart = centroidLineStart;\n centroidStream.lineEnd = centroidLineEnd;\n },\n result: function() {\n var centroid = Z2 ? [X2 / Z2, Y2 / Z2]\n : Z1 ? [X1 / Z1, Y1 / Z1]\n : Z0 ? [X0 / Z0, Y0 / Z0]\n : [NaN, NaN];\n X0 = Y0 = Z0 =\n X1 = Y1 = Z1 =\n X2 = Y2 = Z2 = 0;\n return centroid;\n }\n};\n\nfunction centroidPoint(x, y) {\n X0 += x;\n Y0 += y;\n ++Z0;\n}\n\nfunction centroidLineStart() {\n centroidStream.point = centroidPointFirstLine;\n}\n\nfunction centroidPointFirstLine(x, y) {\n centroidStream.point = centroidPointLine;\n centroidPoint(x0 = x, y0 = y);\n}\n\nfunction centroidPointLine(x, y) {\n var dx = x - x0, dy = y - y0, z = sqrt(dx * dx + dy * dy);\n X1 += z * (x0 + x) / 2;\n Y1 += z * (y0 + y) / 2;\n Z1 += z;\n centroidPoint(x0 = x, y0 = y);\n}\n\nfunction centroidLineEnd() {\n centroidStream.point = centroidPoint;\n}\n\nfunction centroidRingStart() {\n centroidStream.point = centroidPointFirstRing;\n}\n\nfunction centroidRingEnd() {\n centroidPointRing(x00, y00);\n}\n\nfunction centroidPointFirstRing(x, y) {\n centroidStream.point = centroidPointRing;\n centroidPoint(x00 = x0 = x, y00 = y0 = y);\n}\n\nfunction centroidPointRing(x, y) {\n var dx = x - x0,\n dy = y - y0,\n z = sqrt(dx * dx + dy * dy);\n\n X1 += z * (x0 + x) / 2;\n Y1 += z * (y0 + y) / 2;\n Z1 += z;\n\n z = y0 * x - x0 * y;\n X2 += z * (x0 + x);\n Y2 += z * (y0 + y);\n Z2 += z * 3;\n centroidPoint(x0 = x, y0 = y);\n}\n\nexport default centroidStream;\n","import {tau} from \"../math.js\";\nimport noop from \"../noop.js\";\n\nexport default function PathContext(context) {\n this._context = context;\n}\n\nPathContext.prototype = {\n _radius: 4.5,\n pointRadius: function(_) {\n return this._radius = _, this;\n },\n polygonStart: function() {\n this._line = 0;\n },\n polygonEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line === 0) this._context.closePath();\n this._point = NaN;\n },\n point: function(x, y) {\n switch (this._point) {\n case 0: {\n this._context.moveTo(x, y);\n this._point = 1;\n break;\n }\n case 1: {\n this._context.lineTo(x, y);\n break;\n }\n default: {\n this._context.moveTo(x + this._radius, y);\n this._context.arc(x, y, this._radius, 0, tau);\n break;\n }\n }\n },\n result: noop\n};\n","import identity from \"../identity.js\";\nimport stream from \"../stream.js\";\nimport pathArea from \"./area.js\";\nimport pathBounds from \"./bounds.js\";\nimport pathCentroid from \"./centroid.js\";\nimport PathContext from \"./context.js\";\nimport pathMeasure from \"./measure.js\";\nimport PathString from \"./string.js\";\n\nexport default function(projection, context) {\n var pointRadius = 4.5,\n projectionStream,\n contextStream;\n\n function path(object) {\n if (object) {\n if (typeof pointRadius === \"function\") contextStream.pointRadius(+pointRadius.apply(this, arguments));\n stream(object, projectionStream(contextStream));\n }\n return contextStream.result();\n }\n\n path.area = function(object) {\n stream(object, projectionStream(pathArea));\n return pathArea.result();\n };\n\n path.measure = function(object) {\n stream(object, projectionStream(pathMeasure));\n return pathMeasure.result();\n };\n\n path.bounds = function(object) {\n stream(object, projectionStream(pathBounds));\n return pathBounds.result();\n };\n\n path.centroid = function(object) {\n stream(object, projectionStream(pathCentroid));\n return pathCentroid.result();\n };\n\n path.projection = function(_) {\n return arguments.length ? (projectionStream = _ == null ? (projection = null, identity) : (projection = _).stream, path) : projection;\n };\n\n path.context = function(_) {\n if (!arguments.length) return context;\n contextStream = _ == null ? (context = null, new PathString) : new PathContext(context = _);\n if (typeof pointRadius !== \"function\") contextStream.pointRadius(pointRadius);\n return path;\n };\n\n path.pointRadius = function(_) {\n if (!arguments.length) return pointRadius;\n pointRadius = typeof _ === \"function\" ? _ : (contextStream.pointRadius(+_), +_);\n return path;\n };\n\n return path.projection(projection).context(context);\n}\n","import adder from \"../adder.js\";\nimport {sqrt} from \"../math.js\";\nimport noop from \"../noop.js\";\n\nvar lengthSum = adder(),\n lengthRing,\n x00,\n y00,\n x0,\n y0;\n\nvar lengthStream = {\n point: noop,\n lineStart: function() {\n lengthStream.point = lengthPointFirst;\n },\n lineEnd: function() {\n if (lengthRing) lengthPoint(x00, y00);\n lengthStream.point = noop;\n },\n polygonStart: function() {\n lengthRing = true;\n },\n polygonEnd: function() {\n lengthRing = null;\n },\n result: function() {\n var length = +lengthSum;\n lengthSum.reset();\n return length;\n }\n};\n\nfunction lengthPointFirst(x, y) {\n lengthStream.point = lengthPoint;\n x00 = x0 = x, y00 = y0 = y;\n}\n\nfunction lengthPoint(x, y) {\n x0 -= x, y0 -= y;\n lengthSum.add(sqrt(x0 * x0 + y0 * y0));\n x0 = x, y0 = y;\n}\n\nexport default lengthStream;\n","export default function PathString() {\n this._string = [];\n}\n\nPathString.prototype = {\n _radius: 4.5,\n _circle: circle(4.5),\n pointRadius: function(_) {\n if ((_ = +_) !== this._radius) this._radius = _, this._circle = null;\n return this;\n },\n polygonStart: function() {\n this._line = 0;\n },\n polygonEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line === 0) this._string.push(\"Z\");\n this._point = NaN;\n },\n point: function(x, y) {\n switch (this._point) {\n case 0: {\n this._string.push(\"M\", x, \",\", y);\n this._point = 1;\n break;\n }\n case 1: {\n this._string.push(\"L\", x, \",\", y);\n break;\n }\n default: {\n if (this._circle == null) this._circle = circle(this._radius);\n this._string.push(\"M\", x, \",\", y, this._circle);\n break;\n }\n }\n },\n result: function() {\n if (this._string.length) {\n var result = this._string.join(\"\");\n this._string = [];\n return result;\n } else {\n return null;\n }\n }\n};\n\nfunction circle(radius) {\n return \"m0,\" + radius\n + \"a\" + radius + \",\" + radius + \" 0 1,1 0,\" + -2 * radius\n + \"a\" + radius + \",\" + radius + \" 0 1,1 0,\" + 2 * radius\n + \"z\";\n}\n","import {abs, epsilon} from \"./math.js\";\n\nexport default function(a, b) {\n return abs(a[0] - b[0]) < epsilon && abs(a[1] - b[1]) < epsilon;\n}\n","import adder from \"./adder.js\";\nimport {cartesian, cartesianCross, cartesianNormalizeInPlace} from \"./cartesian.js\";\nimport {abs, asin, atan2, cos, epsilon, halfPi, pi, quarterPi, sign, sin, tau} from \"./math.js\";\n\nvar sum = adder();\n\nfunction longitude(point) {\n if (abs(point[0]) <= pi)\n return point[0];\n else\n return sign(point[0]) * ((abs(point[0]) + pi) % tau - pi);\n}\n\nexport default function(polygon, point) {\n var lambda = longitude(point),\n phi = point[1],\n sinPhi = sin(phi),\n normal = [sin(lambda), -cos(lambda), 0],\n angle = 0,\n winding = 0;\n\n sum.reset();\n\n if (sinPhi === 1) phi = halfPi + epsilon;\n else if (sinPhi === -1) phi = -halfPi - epsilon;\n\n for (var i = 0, n = polygon.length; i < n; ++i) {\n if (!(m = (ring = polygon[i]).length)) continue;\n var ring,\n m,\n point0 = ring[m - 1],\n lambda0 = longitude(point0),\n phi0 = point0[1] / 2 + quarterPi,\n sinPhi0 = sin(phi0),\n cosPhi0 = cos(phi0);\n\n for (var j = 0; j < m; ++j, lambda0 = lambda1, sinPhi0 = sinPhi1, cosPhi0 = cosPhi1, point0 = point1) {\n var point1 = ring[j],\n lambda1 = longitude(point1),\n phi1 = point1[1] / 2 + quarterPi,\n sinPhi1 = sin(phi1),\n cosPhi1 = cos(phi1),\n delta = lambda1 - lambda0,\n sign = delta >= 0 ? 1 : -1,\n absDelta = sign * delta,\n antimeridian = absDelta > pi,\n k = sinPhi0 * sinPhi1;\n\n sum.add(atan2(k * sign * sin(absDelta), cosPhi0 * cosPhi1 + k * cos(absDelta)));\n angle += antimeridian ? delta + sign * tau : delta;\n\n // Are the longitudes either side of the point’s meridian (lambda),\n // and are the latitudes smaller than the parallel (phi)?\n if (antimeridian ^ lambda0 >= lambda ^ lambda1 >= lambda) {\n var arc = cartesianCross(cartesian(point0), cartesian(point1));\n cartesianNormalizeInPlace(arc);\n var intersection = cartesianCross(normal, arc);\n cartesianNormalizeInPlace(intersection);\n var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin(intersection[2]);\n if (phi > phiArc || phi === phiArc && (arc[0] || arc[1])) {\n winding += antimeridian ^ delta >= 0 ? 1 : -1;\n }\n }\n }\n }\n\n // First, determine whether the South pole is inside or outside:\n //\n // It is inside if:\n // * the polygon winds around it in a clockwise direction.\n // * the polygon does not (cumulatively) wind around it, but has a negative\n // (counter-clockwise) area.\n //\n // Second, count the (signed) number of times a segment crosses a lambda\n // from the point to the South pole. If it is zero, then the point is the\n // same side as the South pole.\n\n return (angle < -epsilon || angle < epsilon && sum < -epsilon) ^ (winding & 1);\n}\n","import conicEqualArea from \"./conicEqualArea.js\";\n\nexport default function() {\n return conicEqualArea()\n .parallels([29.5, 45.5])\n .scale(1070)\n .translate([480, 250])\n .rotate([96, 0])\n .center([-0.6, 38.7]);\n}\n","import {epsilon} from \"../math.js\";\nimport albers from \"./albers.js\";\nimport conicEqualArea from \"./conicEqualArea.js\";\nimport {fitExtent, fitSize, fitWidth, fitHeight} from \"./fit.js\";\n\n// The projections must have mutually exclusive clip regions on the sphere,\n// as this will avoid emitting interleaving lines and polygons.\nfunction multiplex(streams) {\n var n = streams.length;\n return {\n point: function(x, y) { var i = -1; while (++i < n) streams[i].point(x, y); },\n sphere: function() { var i = -1; while (++i < n) streams[i].sphere(); },\n lineStart: function() { var i = -1; while (++i < n) streams[i].lineStart(); },\n lineEnd: function() { var i = -1; while (++i < n) streams[i].lineEnd(); },\n polygonStart: function() { var i = -1; while (++i < n) streams[i].polygonStart(); },\n polygonEnd: function() { var i = -1; while (++i < n) streams[i].polygonEnd(); }\n };\n}\n\n// A composite projection for the United States, configured by default for\n// 960×500. The projection also works quite well at 960×600 if you change the\n// scale to 1285 and adjust the translate accordingly. The set of standard\n// parallels for each region comes from USGS, which is published here:\n// http://egsc.usgs.gov/isb/pubs/MapProjections/projections.html#albers\nexport default function() {\n var cache,\n cacheStream,\n lower48 = albers(), lower48Point,\n alaska = conicEqualArea().rotate([154, 0]).center([-2, 58.5]).parallels([55, 65]), alaskaPoint, // EPSG:3338\n hawaii = conicEqualArea().rotate([157, 0]).center([-3, 19.9]).parallels([8, 18]), hawaiiPoint, // ESRI:102007\n point, pointStream = {point: function(x, y) { point = [x, y]; }};\n\n function albersUsa(coordinates) {\n var x = coordinates[0], y = coordinates[1];\n return point = null,\n (lower48Point.point(x, y), point)\n || (alaskaPoint.point(x, y), point)\n || (hawaiiPoint.point(x, y), point);\n }\n\n albersUsa.invert = function(coordinates) {\n var k = lower48.scale(),\n t = lower48.translate(),\n x = (coordinates[0] - t[0]) / k,\n y = (coordinates[1] - t[1]) / k;\n return (y >= 0.120 && y < 0.234 && x >= -0.425 && x < -0.214 ? alaska\n : y >= 0.166 && y < 0.234 && x >= -0.214 && x < -0.115 ? hawaii\n : lower48).invert(coordinates);\n };\n\n albersUsa.stream = function(stream) {\n return cache && cacheStream === stream ? cache : cache = multiplex([lower48.stream(cacheStream = stream), alaska.stream(stream), hawaii.stream(stream)]);\n };\n\n albersUsa.precision = function(_) {\n if (!arguments.length) return lower48.precision();\n lower48.precision(_), alaska.precision(_), hawaii.precision(_);\n return reset();\n };\n\n albersUsa.scale = function(_) {\n if (!arguments.length) return lower48.scale();\n lower48.scale(_), alaska.scale(_ * 0.35), hawaii.scale(_);\n return albersUsa.translate(lower48.translate());\n };\n\n albersUsa.translate = function(_) {\n if (!arguments.length) return lower48.translate();\n var k = lower48.scale(), x = +_[0], y = +_[1];\n\n lower48Point = lower48\n .translate(_)\n .clipExtent([[x - 0.455 * k, y - 0.238 * k], [x + 0.455 * k, y + 0.238 * k]])\n .stream(pointStream);\n\n alaskaPoint = alaska\n .translate([x - 0.307 * k, y + 0.201 * k])\n .clipExtent([[x - 0.425 * k + epsilon, y + 0.120 * k + epsilon], [x - 0.214 * k - epsilon, y + 0.234 * k - epsilon]])\n .stream(pointStream);\n\n hawaiiPoint = hawaii\n .translate([x - 0.205 * k, y + 0.212 * k])\n .clipExtent([[x - 0.214 * k + epsilon, y + 0.166 * k + epsilon], [x - 0.115 * k - epsilon, y + 0.234 * k - epsilon]])\n .stream(pointStream);\n\n return reset();\n };\n\n albersUsa.fitExtent = function(extent, object) {\n return fitExtent(albersUsa, extent, object);\n };\n\n albersUsa.fitSize = function(size, object) {\n return fitSize(albersUsa, size, object);\n };\n\n albersUsa.fitWidth = function(width, object) {\n return fitWidth(albersUsa, width, object);\n };\n\n albersUsa.fitHeight = function(height, object) {\n return fitHeight(albersUsa, height, object);\n };\n\n function reset() {\n cache = cacheStream = null;\n return albersUsa;\n }\n\n return albersUsa.scale(1070);\n}\n","import {asin, atan2, cos, sin, sqrt} from \"../math.js\";\n\nexport function azimuthalRaw(scale) {\n return function(x, y) {\n var cx = cos(x),\n cy = cos(y),\n k = scale(cx * cy);\n return [\n k * cy * sin(x),\n k * sin(y)\n ];\n }\n}\n\nexport function azimuthalInvert(angle) {\n return function(x, y) {\n var z = sqrt(x * x + y * y),\n c = angle(z),\n sc = sin(c),\n cc = cos(c);\n return [\n atan2(x * sc, z * cc),\n asin(z && y * sc / z)\n ];\n }\n}\n","import {asin, sqrt} from \"../math.js\";\nimport {azimuthalRaw, azimuthalInvert} from \"./azimuthal.js\";\nimport projection from \"./index.js\";\n\nexport var azimuthalEqualAreaRaw = azimuthalRaw(function(cxcy) {\n return sqrt(2 / (1 + cxcy));\n});\n\nazimuthalEqualAreaRaw.invert = azimuthalInvert(function(z) {\n return 2 * asin(z / 2);\n});\n\nexport default function() {\n return projection(azimuthalEqualAreaRaw)\n .scale(124.75)\n .clipAngle(180 - 1e-3);\n}\n","import {acos, sin} from \"../math.js\";\nimport {azimuthalRaw, azimuthalInvert} from \"./azimuthal.js\";\nimport projection from \"./index.js\";\n\nexport var azimuthalEquidistantRaw = azimuthalRaw(function(c) {\n return (c = acos(c)) && c / sin(c);\n});\n\nazimuthalEquidistantRaw.invert = azimuthalInvert(function(z) {\n return z;\n});\n\nexport default function() {\n return projection(azimuthalEquidistantRaw)\n .scale(79.4188)\n .clipAngle(180 - 1e-3);\n}\n","import {degrees, pi, radians} from \"../math.js\";\nimport {projectionMutator} from \"./index.js\";\n\nexport function conicProjection(projectAt) {\n var phi0 = 0,\n phi1 = pi / 3,\n m = projectionMutator(projectAt),\n p = m(phi0, phi1);\n\n p.parallels = function(_) {\n return arguments.length ? m(phi0 = _[0] * radians, phi1 = _[1] * radians) : [phi0 * degrees, phi1 * degrees];\n };\n\n return p;\n}\n","import {abs, atan, atan2, cos, epsilon, halfPi, log, pi, pow, sign, sin, sqrt, tan} from \"../math.js\";\nimport {conicProjection} from \"./conic.js\";\nimport {mercatorRaw} from \"./mercator.js\";\n\nfunction tany(y) {\n return tan((halfPi + y) / 2);\n}\n\nexport function conicConformalRaw(y0, y1) {\n var cy0 = cos(y0),\n n = y0 === y1 ? sin(y0) : log(cy0 / cos(y1)) / log(tany(y1) / tany(y0)),\n f = cy0 * pow(tany(y0), n) / n;\n\n if (!n) return mercatorRaw;\n\n function project(x, y) {\n if (f > 0) { if (y < -halfPi + epsilon) y = -halfPi + epsilon; }\n else { if (y > halfPi - epsilon) y = halfPi - epsilon; }\n var r = f / pow(tany(y), n);\n return [r * sin(n * x), f - r * cos(n * x)];\n }\n\n project.invert = function(x, y) {\n var fy = f - y, r = sign(n) * sqrt(x * x + fy * fy),\n l = atan2(x, abs(fy)) * sign(fy);\n if (fy * n < 0)\n l -= pi * sign(x) * sign(fy);\n return [l / n, 2 * atan(pow(f / r, 1 / n)) - halfPi];\n };\n\n return project;\n}\n\nexport default function() {\n return conicProjection(conicConformalRaw)\n .scale(109.5)\n .parallels([30, 30]);\n}\n","import {abs, asin, atan2, cos, epsilon, pi, sign, sin, sqrt} from \"../math.js\";\nimport {conicProjection} from \"./conic.js\";\nimport {cylindricalEqualAreaRaw} from \"./cylindricalEqualArea.js\";\n\nexport function conicEqualAreaRaw(y0, y1) {\n var sy0 = sin(y0), n = (sy0 + sin(y1)) / 2;\n\n // Are the parallels symmetrical around the Equator?\n if (abs(n) < epsilon) return cylindricalEqualAreaRaw(y0);\n\n var c = 1 + sy0 * (2 * n - sy0), r0 = sqrt(c) / n;\n\n function project(x, y) {\n var r = sqrt(c - 2 * n * sin(y)) / n;\n return [r * sin(x *= n), r0 - r * cos(x)];\n }\n\n project.invert = function(x, y) {\n var r0y = r0 - y,\n l = atan2(x, abs(r0y)) * sign(r0y);\n if (r0y * n < 0)\n l -= pi * sign(x) * sign(r0y);\n return [l / n, asin((c - (x * x + r0y * r0y) * n * n) / (2 * n))];\n };\n\n return project;\n}\n\nexport default function() {\n return conicProjection(conicEqualAreaRaw)\n .scale(155.424)\n .center([0, 33.6442]);\n}\n","import {abs, atan2, cos, epsilon, pi, sign, sin, sqrt} from \"../math.js\";\nimport {conicProjection} from \"./conic.js\";\nimport {equirectangularRaw} from \"./equirectangular.js\";\n\nexport function conicEquidistantRaw(y0, y1) {\n var cy0 = cos(y0),\n n = y0 === y1 ? sin(y0) : (cy0 - cos(y1)) / (y1 - y0),\n g = cy0 / n + y0;\n\n if (abs(n) < epsilon) return equirectangularRaw;\n\n function project(x, y) {\n var gy = g - y, nx = n * x;\n return [gy * sin(nx), g - gy * cos(nx)];\n }\n\n project.invert = function(x, y) {\n var gy = g - y,\n l = atan2(x, abs(gy)) * sign(gy);\n if (gy * n < 0)\n l -= pi * sign(x) * sign(gy);\n return [l / n, g - sign(n) * sqrt(x * x + gy * gy)];\n };\n\n return project;\n}\n\nexport default function() {\n return conicProjection(conicEquidistantRaw)\n .scale(131.154)\n .center([0, 13.9389]);\n}\n","import {asin, cos, sin} from \"../math.js\";\n\nexport function cylindricalEqualAreaRaw(phi0) {\n var cosPhi0 = cos(phi0);\n\n function forward(lambda, phi) {\n return [lambda * cosPhi0, sin(phi) / cosPhi0];\n }\n\n forward.invert = function(x, y) {\n return [x / cosPhi0, asin(y * cosPhi0)];\n };\n\n return forward;\n}\n","import projection from \"./index.js\";\nimport {abs, asin, cos, epsilon2, sin, sqrt} from \"../math.js\";\n\nvar A1 = 1.340264,\n A2 = -0.081106,\n A3 = 0.000893,\n A4 = 0.003796,\n M = sqrt(3) / 2,\n iterations = 12;\n\nexport function equalEarthRaw(lambda, phi) {\n var l = asin(M * sin(phi)), l2 = l * l, l6 = l2 * l2 * l2;\n return [\n lambda * cos(l) / (M * (A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2))),\n l * (A1 + A2 * l2 + l6 * (A3 + A4 * l2))\n ];\n}\n\nequalEarthRaw.invert = function(x, y) {\n var l = y, l2 = l * l, l6 = l2 * l2 * l2;\n for (var i = 0, delta, fy, fpy; i < iterations; ++i) {\n fy = l * (A1 + A2 * l2 + l6 * (A3 + A4 * l2)) - y;\n fpy = A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2);\n l -= delta = fy / fpy, l2 = l * l, l6 = l2 * l2 * l2;\n if (abs(delta) < epsilon2) break;\n }\n return [\n M * x * (A1 + 3 * A2 * l2 + l6 * (7 * A3 + 9 * A4 * l2)) / cos(l),\n asin(sin(l) / M)\n ];\n};\n\nexport default function() {\n return projection(equalEarthRaw)\n .scale(177.158);\n}\n","import projection from \"./index.js\";\n\nexport function equirectangularRaw(lambda, phi) {\n return [lambda, phi];\n}\n\nequirectangularRaw.invert = equirectangularRaw;\n\nexport default function() {\n return projection(equirectangularRaw)\n .scale(152.63);\n}\n","import {default as geoStream} from \"../stream.js\";\nimport boundsStream from \"../path/bounds.js\";\n\nfunction fit(projection, fitBounds, object) {\n var clip = projection.clipExtent && projection.clipExtent();\n projection.scale(150).translate([0, 0]);\n if (clip != null) projection.clipExtent(null);\n geoStream(object, projection.stream(boundsStream));\n fitBounds(boundsStream.result());\n if (clip != null) projection.clipExtent(clip);\n return projection;\n}\n\nexport function fitExtent(projection, extent, object) {\n return fit(projection, function(b) {\n var w = extent[1][0] - extent[0][0],\n h = extent[1][1] - extent[0][1],\n k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1])),\n x = +extent[0][0] + (w - k * (b[1][0] + b[0][0])) / 2,\n y = +extent[0][1] + (h - k * (b[1][1] + b[0][1])) / 2;\n projection.scale(150 * k).translate([x, y]);\n }, object);\n}\n\nexport function fitSize(projection, size, object) {\n return fitExtent(projection, [[0, 0], size], object);\n}\n\nexport function fitWidth(projection, width, object) {\n return fit(projection, function(b) {\n var w = +width,\n k = w / (b[1][0] - b[0][0]),\n x = (w - k * (b[1][0] + b[0][0])) / 2,\n y = -k * b[0][1];\n projection.scale(150 * k).translate([x, y]);\n }, object);\n}\n\nexport function fitHeight(projection, height, object) {\n return fit(projection, function(b) {\n var h = +height,\n k = h / (b[1][1] - b[0][1]),\n x = -k * b[0][0],\n y = (h - k * (b[1][1] + b[0][1])) / 2;\n projection.scale(150 * k).translate([x, y]);\n }, object);\n}\n","import {atan, cos, sin} from \"../math.js\";\nimport {azimuthalInvert} from \"./azimuthal.js\";\nimport projection from \"./index.js\";\n\nexport function gnomonicRaw(x, y) {\n var cy = cos(y), k = cos(x) * cy;\n return [cy * sin(x) / k, sin(y) / k];\n}\n\ngnomonicRaw.invert = azimuthalInvert(atan);\n\nexport default function() {\n return projection(gnomonicRaw)\n .scale(144.049)\n .clipAngle(60);\n}\n","import clipRectangle from \"../clip/rectangle.js\";\nimport identity from \"../identity.js\";\nimport {transformer} from \"../transform.js\";\nimport {fitExtent, fitSize, fitWidth, fitHeight} from \"./fit.js\";\nimport {cos, degrees, radians, sin} from \"../math.js\";\n\nexport default function() {\n var k = 1, tx = 0, ty = 0, sx = 1, sy = 1, // scale, translate and reflect\n alpha = 0, ca, sa, // angle\n x0 = null, y0, x1, y1, // clip extent\n kx = 1, ky = 1,\n transform = transformer({\n point: function(x, y) {\n var p = projection([x, y])\n this.stream.point(p[0], p[1]);\n }\n }),\n postclip = identity,\n cache,\n cacheStream;\n\n function reset() {\n kx = k * sx;\n ky = k * sy;\n cache = cacheStream = null;\n return projection;\n }\n\n function projection (p) {\n var x = p[0] * kx, y = p[1] * ky;\n if (alpha) {\n var t = y * ca - x * sa;\n x = x * ca + y * sa;\n y = t;\n } \n return [x + tx, y + ty];\n }\n projection.invert = function(p) {\n var x = p[0] - tx, y = p[1] - ty;\n if (alpha) {\n var t = y * ca + x * sa;\n x = x * ca - y * sa;\n y = t;\n }\n return [x / kx, y / ky];\n };\n projection.stream = function(stream) {\n return cache && cacheStream === stream ? cache : cache = transform(postclip(cacheStream = stream));\n };\n projection.postclip = function(_) {\n return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;\n };\n projection.clipExtent = function(_) {\n return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, identity) : clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];\n };\n projection.scale = function(_) {\n return arguments.length ? (k = +_, reset()) : k;\n };\n projection.translate = function(_) {\n return arguments.length ? (tx = +_[0], ty = +_[1], reset()) : [tx, ty];\n }\n projection.angle = function(_) {\n return arguments.length ? (alpha = _ % 360 * radians, sa = sin(alpha), ca = cos(alpha), reset()) : alpha * degrees;\n };\n projection.reflectX = function(_) {\n return arguments.length ? (sx = _ ? -1 : 1, reset()) : sx < 0;\n };\n projection.reflectY = function(_) {\n return arguments.length ? (sy = _ ? -1 : 1, reset()) : sy < 0;\n };\n projection.fitExtent = function(extent, object) {\n return fitExtent(projection, extent, object);\n };\n projection.fitSize = function(size, object) {\n return fitSize(projection, size, object);\n };\n projection.fitWidth = function(width, object) {\n return fitWidth(projection, width, object);\n };\n projection.fitHeight = function(height, object) {\n return fitHeight(projection, height, object);\n };\n\n return projection;\n}\n","import clipAntimeridian from \"../clip/antimeridian.js\";\nimport clipCircle from \"../clip/circle.js\";\nimport clipRectangle from \"../clip/rectangle.js\";\nimport compose from \"../compose.js\";\nimport identity from \"../identity.js\";\nimport {cos, degrees, radians, sin, sqrt} from \"../math.js\";\nimport {rotateRadians} from \"../rotation.js\";\nimport {transformer} from \"../transform.js\";\nimport {fitExtent, fitSize, fitWidth, fitHeight} from \"./fit.js\";\nimport resample from \"./resample.js\";\n\nvar transformRadians = transformer({\n point: function(x, y) {\n this.stream.point(x * radians, y * radians);\n }\n});\n\nfunction transformRotate(rotate) {\n return transformer({\n point: function(x, y) {\n var r = rotate(x, y);\n return this.stream.point(r[0], r[1]);\n }\n });\n}\n\nfunction scaleTranslate(k, dx, dy, sx, sy) {\n function transform(x, y) {\n x *= sx; y *= sy;\n return [dx + k * x, dy - k * y];\n }\n transform.invert = function(x, y) {\n return [(x - dx) / k * sx, (dy - y) / k * sy];\n };\n return transform;\n}\n\nfunction scaleTranslateRotate(k, dx, dy, sx, sy, alpha) {\n var cosAlpha = cos(alpha),\n sinAlpha = sin(alpha),\n a = cosAlpha * k,\n b = sinAlpha * k,\n ai = cosAlpha / k,\n bi = sinAlpha / k,\n ci = (sinAlpha * dy - cosAlpha * dx) / k,\n fi = (sinAlpha * dx + cosAlpha * dy) / k;\n function transform(x, y) {\n x *= sx; y *= sy;\n return [a * x - b * y + dx, dy - b * x - a * y];\n }\n transform.invert = function(x, y) {\n return [sx * (ai * x - bi * y + ci), sy * (fi - bi * x - ai * y)];\n };\n return transform;\n}\n\nexport default function projection(project) {\n return projectionMutator(function() { return project; })();\n}\n\nexport function projectionMutator(projectAt) {\n var project,\n k = 150, // scale\n x = 480, y = 250, // translate\n lambda = 0, phi = 0, // center\n deltaLambda = 0, deltaPhi = 0, deltaGamma = 0, rotate, // pre-rotate\n alpha = 0, // post-rotate angle\n sx = 1, // reflectX\n sy = 1, // reflectX\n theta = null, preclip = clipAntimeridian, // pre-clip angle\n x0 = null, y0, x1, y1, postclip = identity, // post-clip extent\n delta2 = 0.5, // precision\n projectResample,\n projectTransform,\n projectRotateTransform,\n cache,\n cacheStream;\n\n function projection(point) {\n return projectRotateTransform(point[0] * radians, point[1] * radians);\n }\n\n function invert(point) {\n point = projectRotateTransform.invert(point[0], point[1]);\n return point && [point[0] * degrees, point[1] * degrees];\n }\n\n projection.stream = function(stream) {\n return cache && cacheStream === stream ? cache : cache = transformRadians(transformRotate(rotate)(preclip(projectResample(postclip(cacheStream = stream)))));\n };\n\n projection.preclip = function(_) {\n return arguments.length ? (preclip = _, theta = undefined, reset()) : preclip;\n };\n\n projection.postclip = function(_) {\n return arguments.length ? (postclip = _, x0 = y0 = x1 = y1 = null, reset()) : postclip;\n };\n\n projection.clipAngle = function(_) {\n return arguments.length ? (preclip = +_ ? clipCircle(theta = _ * radians) : (theta = null, clipAntimeridian), reset()) : theta * degrees;\n };\n\n projection.clipExtent = function(_) {\n return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, identity) : clipRectangle(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]];\n };\n\n projection.scale = function(_) {\n return arguments.length ? (k = +_, recenter()) : k;\n };\n\n projection.translate = function(_) {\n return arguments.length ? (x = +_[0], y = +_[1], recenter()) : [x, y];\n };\n\n projection.center = function(_) {\n return arguments.length ? (lambda = _[0] % 360 * radians, phi = _[1] % 360 * radians, recenter()) : [lambda * degrees, phi * degrees];\n };\n\n projection.rotate = function(_) {\n return arguments.length ? (deltaLambda = _[0] % 360 * radians, deltaPhi = _[1] % 360 * radians, deltaGamma = _.length > 2 ? _[2] % 360 * radians : 0, recenter()) : [deltaLambda * degrees, deltaPhi * degrees, deltaGamma * degrees];\n };\n\n projection.angle = function(_) {\n return arguments.length ? (alpha = _ % 360 * radians, recenter()) : alpha * degrees;\n };\n\n projection.reflectX = function(_) {\n return arguments.length ? (sx = _ ? -1 : 1, recenter()) : sx < 0;\n };\n\n projection.reflectY = function(_) {\n return arguments.length ? (sy = _ ? -1 : 1, recenter()) : sy < 0;\n };\n\n projection.precision = function(_) {\n return arguments.length ? (projectResample = resample(projectTransform, delta2 = _ * _), reset()) : sqrt(delta2);\n };\n\n projection.fitExtent = function(extent, object) {\n return fitExtent(projection, extent, object);\n };\n\n projection.fitSize = function(size, object) {\n return fitSize(projection, size, object);\n };\n\n projection.fitWidth = function(width, object) {\n return fitWidth(projection, width, object);\n };\n\n projection.fitHeight = function(height, object) {\n return fitHeight(projection, height, object);\n };\n\n function recenter() {\n var center = scaleTranslateRotate(k, 0, 0, sx, sy, alpha).apply(null, project(lambda, phi)),\n transform = (alpha ? scaleTranslateRotate : scaleTranslate)(k, x - center[0], y - center[1], sx, sy, alpha);\n rotate = rotateRadians(deltaLambda, deltaPhi, deltaGamma);\n projectTransform = compose(project, transform);\n projectRotateTransform = compose(rotate, projectTransform);\n projectResample = resample(projectTransform, delta2);\n return reset();\n }\n\n function reset() {\n cache = cacheStream = null;\n return projection;\n }\n\n return function() {\n project = projectAt.apply(this, arguments);\n projection.invert = project.invert && invert;\n return recenter();\n };\n}\n","import {atan, exp, halfPi, log, pi, tan, tau} from \"../math.js\";\nimport rotation from \"../rotation.js\";\nimport projection from \"./index.js\";\n\nexport function mercatorRaw(lambda, phi) {\n return [lambda, log(tan((halfPi + phi) / 2))];\n}\n\nmercatorRaw.invert = function(x, y) {\n return [x, 2 * atan(exp(y)) - halfPi];\n};\n\nexport default function() {\n return mercatorProjection(mercatorRaw)\n .scale(961 / tau);\n}\n\nexport function mercatorProjection(project) {\n var m = projection(project),\n center = m.center,\n scale = m.scale,\n translate = m.translate,\n clipExtent = m.clipExtent,\n x0 = null, y0, x1, y1; // clip extent\n\n m.scale = function(_) {\n return arguments.length ? (scale(_), reclip()) : scale();\n };\n\n m.translate = function(_) {\n return arguments.length ? (translate(_), reclip()) : translate();\n };\n\n m.center = function(_) {\n return arguments.length ? (center(_), reclip()) : center();\n };\n\n m.clipExtent = function(_) {\n return arguments.length ? ((_ == null ? x0 = y0 = x1 = y1 = null : (x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1])), reclip()) : x0 == null ? null : [[x0, y0], [x1, y1]];\n };\n\n function reclip() {\n var k = pi * scale(),\n t = m(rotation(m.rotate()).invert([0, 0]));\n return clipExtent(x0 == null\n ? [[t[0] - k, t[1] - k], [t[0] + k, t[1] + k]] : project === mercatorRaw\n ? [[Math.max(t[0] - k, x0), y0], [Math.min(t[0] + k, x1), y1]]\n : [[x0, Math.max(t[1] - k, y0)], [x1, Math.min(t[1] + k, y1)]]);\n }\n\n return reclip();\n}\n","import projection from \"./index.js\";\nimport {abs, epsilon} from \"../math.js\";\n\nexport function naturalEarth1Raw(lambda, phi) {\n var phi2 = phi * phi, phi4 = phi2 * phi2;\n return [\n lambda * (0.8707 - 0.131979 * phi2 + phi4 * (-0.013791 + phi4 * (0.003971 * phi2 - 0.001529 * phi4))),\n phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4)))\n ];\n}\n\nnaturalEarth1Raw.invert = function(x, y) {\n var phi = y, i = 25, delta;\n do {\n var phi2 = phi * phi, phi4 = phi2 * phi2;\n phi -= delta = (phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4))) - y) /\n (1.007226 + phi2 * (0.015085 * 3 + phi4 * (-0.044475 * 7 + 0.028874 * 9 * phi2 - 0.005916 * 11 * phi4)));\n } while (abs(delta) > epsilon && --i > 0);\n return [\n x / (0.8707 + (phi2 = phi * phi) * (-0.131979 + phi2 * (-0.013791 + phi2 * phi2 * phi2 * (0.003971 - 0.001529 * phi2)))),\n phi\n ];\n};\n\nexport default function() {\n return projection(naturalEarth1Raw)\n .scale(175.295);\n}\n","import {asin, cos, epsilon, sin} from \"../math.js\";\nimport {azimuthalInvert} from \"./azimuthal.js\";\nimport projection from \"./index.js\";\n\nexport function orthographicRaw(x, y) {\n return [cos(y) * sin(x), sin(y)];\n}\n\northographicRaw.invert = azimuthalInvert(asin);\n\nexport default function() {\n return projection(orthographicRaw)\n .scale(249.5)\n .clipAngle(90 + epsilon);\n}\n","import {cartesian} from \"../cartesian.js\";\nimport {abs, asin, atan2, cos, epsilon, radians, sqrt} from \"../math.js\";\nimport {transformer} from \"../transform.js\";\n\nvar maxDepth = 16, // maximum depth of subdivision\n cosMinDistance = cos(30 * radians); // cos(minimum angular distance)\n\nexport default function(project, delta2) {\n return +delta2 ? resample(project, delta2) : resampleNone(project);\n}\n\nfunction resampleNone(project) {\n return transformer({\n point: function(x, y) {\n x = project(x, y);\n this.stream.point(x[0], x[1]);\n }\n });\n}\n\nfunction resample(project, delta2) {\n\n function resampleLineTo(x0, y0, lambda0, a0, b0, c0, x1, y1, lambda1, a1, b1, c1, depth, stream) {\n var dx = x1 - x0,\n dy = y1 - y0,\n d2 = dx * dx + dy * dy;\n if (d2 > 4 * delta2 && depth--) {\n var a = a0 + a1,\n b = b0 + b1,\n c = c0 + c1,\n m = sqrt(a * a + b * b + c * c),\n phi2 = asin(c /= m),\n lambda2 = abs(abs(c) - 1) < epsilon || abs(lambda0 - lambda1) < epsilon ? (lambda0 + lambda1) / 2 : atan2(b, a),\n p = project(lambda2, phi2),\n x2 = p[0],\n y2 = p[1],\n dx2 = x2 - x0,\n dy2 = y2 - y0,\n dz = dy * dx2 - dx * dy2;\n if (dz * dz / d2 > delta2 // perpendicular projected distance\n || abs((dx * dx2 + dy * dy2) / d2 - 0.5) > 0.3 // midpoint close to an end\n || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { // angular distance\n resampleLineTo(x0, y0, lambda0, a0, b0, c0, x2, y2, lambda2, a /= m, b /= m, c, depth, stream);\n stream.point(x2, y2);\n resampleLineTo(x2, y2, lambda2, a, b, c, x1, y1, lambda1, a1, b1, c1, depth, stream);\n }\n }\n }\n return function(stream) {\n var lambda00, x00, y00, a00, b00, c00, // first point\n lambda0, x0, y0, a0, b0, c0; // previous point\n\n var resampleStream = {\n point: point,\n lineStart: lineStart,\n lineEnd: lineEnd,\n polygonStart: function() { stream.polygonStart(); resampleStream.lineStart = ringStart; },\n polygonEnd: function() { stream.polygonEnd(); resampleStream.lineStart = lineStart; }\n };\n\n function point(x, y) {\n x = project(x, y);\n stream.point(x[0], x[1]);\n }\n\n function lineStart() {\n x0 = NaN;\n resampleStream.point = linePoint;\n stream.lineStart();\n }\n\n function linePoint(lambda, phi) {\n var c = cartesian([lambda, phi]), p = project(lambda, phi);\n resampleLineTo(x0, y0, lambda0, a0, b0, c0, x0 = p[0], y0 = p[1], lambda0 = lambda, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);\n stream.point(x0, y0);\n }\n\n function lineEnd() {\n resampleStream.point = point;\n stream.lineEnd();\n }\n\n function ringStart() {\n lineStart();\n resampleStream.point = ringPoint;\n resampleStream.lineEnd = ringEnd;\n }\n\n function ringPoint(lambda, phi) {\n linePoint(lambda00 = lambda, phi), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;\n resampleStream.point = linePoint;\n }\n\n function ringEnd() {\n resampleLineTo(x0, y0, lambda0, a0, b0, c0, x00, y00, lambda00, a00, b00, c00, maxDepth, stream);\n resampleStream.lineEnd = lineEnd;\n lineEnd();\n }\n\n return resampleStream;\n };\n}\n","import {atan, cos, sin} from \"../math.js\";\nimport {azimuthalInvert} from \"./azimuthal.js\";\nimport projection from \"./index.js\";\n\nexport function stereographicRaw(x, y) {\n var cy = cos(y), k = 1 + cos(x) * cy;\n return [cy * sin(x) / k, sin(y) / k];\n}\n\nstereographicRaw.invert = azimuthalInvert(function(z) {\n return 2 * atan(z);\n});\n\nexport default function() {\n return projection(stereographicRaw)\n .scale(250)\n .clipAngle(142);\n}\n","import {atan, exp, halfPi, log, tan} from \"../math.js\";\nimport {mercatorProjection} from \"./mercator.js\";\n\nexport function transverseMercatorRaw(lambda, phi) {\n return [log(tan((halfPi + phi) / 2)), -lambda];\n}\n\ntransverseMercatorRaw.invert = function(x, y) {\n return [-y, 2 * atan(exp(x)) - halfPi];\n};\n\nexport default function() {\n var m = mercatorProjection(transverseMercatorRaw),\n center = m.center,\n rotate = m.rotate;\n\n m.center = function(_) {\n return arguments.length ? center([-_[1], _[0]]) : (_ = center(), [_[1], -_[0]]);\n };\n\n m.rotate = function(_) {\n return arguments.length ? rotate([_[0], _[1], _.length > 2 ? _[2] + 90 : 90]) : (_ = rotate(), [_[0], _[1], _[2] - 90]);\n };\n\n return rotate([0, 0, 90])\n .scale(159.155);\n}\n","import compose from \"./compose.js\";\nimport {abs, asin, atan2, cos, degrees, pi, radians, sin, tau} from \"./math.js\";\n\nfunction rotationIdentity(lambda, phi) {\n return [abs(lambda) > pi ? lambda + Math.round(-lambda / tau) * tau : lambda, phi];\n}\n\nrotationIdentity.invert = rotationIdentity;\n\nexport function rotateRadians(deltaLambda, deltaPhi, deltaGamma) {\n return (deltaLambda %= tau) ? (deltaPhi || deltaGamma ? compose(rotationLambda(deltaLambda), rotationPhiGamma(deltaPhi, deltaGamma))\n : rotationLambda(deltaLambda))\n : (deltaPhi || deltaGamma ? rotationPhiGamma(deltaPhi, deltaGamma)\n : rotationIdentity);\n}\n\nfunction forwardRotationLambda(deltaLambda) {\n return function(lambda, phi) {\n return lambda += deltaLambda, [lambda > pi ? lambda - tau : lambda < -pi ? lambda + tau : lambda, phi];\n };\n}\n\nfunction rotationLambda(deltaLambda) {\n var rotation = forwardRotationLambda(deltaLambda);\n rotation.invert = forwardRotationLambda(-deltaLambda);\n return rotation;\n}\n\nfunction rotationPhiGamma(deltaPhi, deltaGamma) {\n var cosDeltaPhi = cos(deltaPhi),\n sinDeltaPhi = sin(deltaPhi),\n cosDeltaGamma = cos(deltaGamma),\n sinDeltaGamma = sin(deltaGamma);\n\n function rotation(lambda, phi) {\n var cosPhi = cos(phi),\n x = cos(lambda) * cosPhi,\n y = sin(lambda) * cosPhi,\n z = sin(phi),\n k = z * cosDeltaPhi + x * sinDeltaPhi;\n return [\n atan2(y * cosDeltaGamma - k * sinDeltaGamma, x * cosDeltaPhi - z * sinDeltaPhi),\n asin(k * cosDeltaGamma + y * sinDeltaGamma)\n ];\n }\n\n rotation.invert = function(lambda, phi) {\n var cosPhi = cos(phi),\n x = cos(lambda) * cosPhi,\n y = sin(lambda) * cosPhi,\n z = sin(phi),\n k = z * cosDeltaGamma - y * sinDeltaGamma;\n return [\n atan2(y * cosDeltaGamma + z * sinDeltaGamma, x * cosDeltaPhi + k * sinDeltaPhi),\n asin(k * cosDeltaPhi - x * sinDeltaPhi)\n ];\n };\n\n return rotation;\n}\n\nexport default function(rotate) {\n rotate = rotateRadians(rotate[0] * radians, rotate[1] * radians, rotate.length > 2 ? rotate[2] * radians : 0);\n\n function forward(coordinates) {\n coordinates = rotate(coordinates[0] * radians, coordinates[1] * radians);\n return coordinates[0] *= degrees, coordinates[1] *= degrees, coordinates;\n }\n\n forward.invert = function(coordinates) {\n coordinates = rotate.invert(coordinates[0] * radians, coordinates[1] * radians);\n return coordinates[0] *= degrees, coordinates[1] *= degrees, coordinates;\n };\n\n return forward;\n}\n","function streamGeometry(geometry, stream) {\n if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) {\n streamGeometryType[geometry.type](geometry, stream);\n }\n}\n\nvar streamObjectType = {\n Feature: function(object, stream) {\n streamGeometry(object.geometry, stream);\n },\n FeatureCollection: function(object, stream) {\n var features = object.features, i = -1, n = features.length;\n while (++i < n) streamGeometry(features[i].geometry, stream);\n }\n};\n\nvar streamGeometryType = {\n Sphere: function(object, stream) {\n stream.sphere();\n },\n Point: function(object, stream) {\n object = object.coordinates;\n stream.point(object[0], object[1], object[2]);\n },\n MultiPoint: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]);\n },\n LineString: function(object, stream) {\n streamLine(object.coordinates, stream, 0);\n },\n MultiLineString: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) streamLine(coordinates[i], stream, 0);\n },\n Polygon: function(object, stream) {\n streamPolygon(object.coordinates, stream);\n },\n MultiPolygon: function(object, stream) {\n var coordinates = object.coordinates, i = -1, n = coordinates.length;\n while (++i < n) streamPolygon(coordinates[i], stream);\n },\n GeometryCollection: function(object, stream) {\n var geometries = object.geometries, i = -1, n = geometries.length;\n while (++i < n) streamGeometry(geometries[i], stream);\n }\n};\n\nfunction streamLine(coordinates, stream, closed) {\n var i = -1, n = coordinates.length - closed, coordinate;\n stream.lineStart();\n while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]);\n stream.lineEnd();\n}\n\nfunction streamPolygon(coordinates, stream) {\n var i = -1, n = coordinates.length;\n stream.polygonStart();\n while (++i < n) streamLine(coordinates[i], stream, 1);\n stream.polygonEnd();\n}\n\nexport default function(object, stream) {\n if (object && streamObjectType.hasOwnProperty(object.type)) {\n streamObjectType[object.type](object, stream);\n } else {\n streamGeometry(object, stream);\n }\n}\n","export default function(methods) {\n return {\n stream: transformer(methods)\n };\n}\n\nexport function transformer(methods) {\n return function(stream) {\n var s = new TransformStream;\n for (var key in methods) s[key] = methods[key];\n s.stream = stream;\n return s;\n };\n}\n\nfunction TransformStream() {}\n\nTransformStream.prototype = {\n constructor: TransformStream,\n point: function(x, y) { this.stream.point(x, y); },\n sphere: function() { this.stream.sphere(); },\n lineStart: function() { this.stream.lineStart(); },\n lineEnd: function() { this.stream.lineEnd(); },\n polygonStart: function() { this.stream.polygonStart(); },\n polygonEnd: function() { this.stream.polygonEnd(); }\n};\n","export function optional(f) {\n return f == null ? null : required(f);\n}\n\nexport function required(f) {\n if (typeof f !== \"function\") throw new Error;\n return f;\n}\n","export var slice = Array.prototype.slice;\n\nexport function shuffle(array) {\n var m = array.length,\n t,\n i;\n\n while (m) {\n i = Math.random() * m-- | 0;\n t = array[m];\n array[m] = array[i];\n array[i] = t;\n }\n\n return array;\n}\n","function defaultSeparation(a, b) {\n return a.parent === b.parent ? 1 : 2;\n}\n\nfunction meanX(children) {\n return children.reduce(meanXReduce, 0) / children.length;\n}\n\nfunction meanXReduce(x, c) {\n return x + c.x;\n}\n\nfunction maxY(children) {\n return 1 + children.reduce(maxYReduce, 0);\n}\n\nfunction maxYReduce(y, c) {\n return Math.max(y, c.y);\n}\n\nfunction leafLeft(node) {\n var children;\n while (children = node.children) node = children[0];\n return node;\n}\n\nfunction leafRight(node) {\n var children;\n while (children = node.children) node = children[children.length - 1];\n return node;\n}\n\nexport default function() {\n var separation = defaultSeparation,\n dx = 1,\n dy = 1,\n nodeSize = false;\n\n function cluster(root) {\n var previousNode,\n x = 0;\n\n // First walk, computing the initial x & y values.\n root.eachAfter(function(node) {\n var children = node.children;\n if (children) {\n node.x = meanX(children);\n node.y = maxY(children);\n } else {\n node.x = previousNode ? x += separation(node, previousNode) : 0;\n node.y = 0;\n previousNode = node;\n }\n });\n\n var left = leafLeft(root),\n right = leafRight(root),\n x0 = left.x - separation(left, right) / 2,\n x1 = right.x + separation(right, left) / 2;\n\n // Second walk, normalizing x & y to the desired size.\n return root.eachAfter(nodeSize ? function(node) {\n node.x = (node.x - root.x) * dx;\n node.y = (root.y - node.y) * dy;\n } : function(node) {\n node.x = (node.x - x0) / (x1 - x0) * dx;\n node.y = (1 - (root.y ? node.y / root.y : 1)) * dy;\n });\n }\n\n cluster.separation = function(x) {\n return arguments.length ? (separation = x, cluster) : separation;\n };\n\n cluster.size = function(x) {\n return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], cluster) : (nodeSize ? null : [dx, dy]);\n };\n\n cluster.nodeSize = function(x) {\n return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], cluster) : (nodeSize ? [dx, dy] : null);\n };\n\n return cluster;\n}\n","export function constantZero() {\n return 0;\n}\n\nexport default function(x) {\n return function() {\n return x;\n };\n}\n","export default function() {\n var node = this, nodes = [node];\n while (node = node.parent) {\n nodes.push(node);\n }\n return nodes;\n}\n","function count(node) {\n var sum = 0,\n children = node.children,\n i = children && children.length;\n if (!i) sum = 1;\n else while (--i >= 0) sum += children[i].value;\n node.value = sum;\n}\n\nexport default function() {\n return this.eachAfter(count);\n}\n","export default function() {\n var nodes = [];\n this.each(function(node) {\n nodes.push(node);\n });\n return nodes;\n}\n","export default function(callback) {\n var node = this, current, next = [node], children, i, n;\n do {\n current = next.reverse(), next = [];\n while (node = current.pop()) {\n callback(node), children = node.children;\n if (children) for (i = 0, n = children.length; i < n; ++i) {\n next.push(children[i]);\n }\n }\n } while (next.length);\n return this;\n}\n","export default function(callback) {\n var node = this, nodes = [node], next = [], children, i, n;\n while (node = nodes.pop()) {\n next.push(node), children = node.children;\n if (children) for (i = 0, n = children.length; i < n; ++i) {\n nodes.push(children[i]);\n }\n }\n while (node = next.pop()) {\n callback(node);\n }\n return this;\n}\n","export default function(callback) {\n var node = this, nodes = [node], children, i;\n while (node = nodes.pop()) {\n callback(node), children = node.children;\n if (children) for (i = children.length - 1; i >= 0; --i) {\n nodes.push(children[i]);\n }\n }\n return this;\n}\n","import node_count from \"./count.js\";\nimport node_each from \"./each.js\";\nimport node_eachBefore from \"./eachBefore.js\";\nimport node_eachAfter from \"./eachAfter.js\";\nimport node_sum from \"./sum.js\";\nimport node_sort from \"./sort.js\";\nimport node_path from \"./path.js\";\nimport node_ancestors from \"./ancestors.js\";\nimport node_descendants from \"./descendants.js\";\nimport node_leaves from \"./leaves.js\";\nimport node_links from \"./links.js\";\n\nexport default function hierarchy(data, children) {\n var root = new Node(data),\n valued = +data.value && (root.value = data.value),\n node,\n nodes = [root],\n child,\n childs,\n i,\n n;\n\n if (children == null) children = defaultChildren;\n\n while (node = nodes.pop()) {\n if (valued) node.value = +node.data.value;\n if ((childs = children(node.data)) && (n = childs.length)) {\n node.children = new Array(n);\n for (i = n - 1; i >= 0; --i) {\n nodes.push(child = node.children[i] = new Node(childs[i]));\n child.parent = node;\n child.depth = node.depth + 1;\n }\n }\n }\n\n return root.eachBefore(computeHeight);\n}\n\nfunction node_copy() {\n return hierarchy(this).eachBefore(copyData);\n}\n\nfunction defaultChildren(d) {\n return d.children;\n}\n\nfunction copyData(node) {\n node.data = node.data.data;\n}\n\nexport function computeHeight(node) {\n var height = 0;\n do node.height = height;\n while ((node = node.parent) && (node.height < ++height));\n}\n\nexport function Node(data) {\n this.data = data;\n this.depth =\n this.height = 0;\n this.parent = null;\n}\n\nNode.prototype = hierarchy.prototype = {\n constructor: Node,\n count: node_count,\n each: node_each,\n eachAfter: node_eachAfter,\n eachBefore: node_eachBefore,\n sum: node_sum,\n sort: node_sort,\n path: node_path,\n ancestors: node_ancestors,\n descendants: node_descendants,\n leaves: node_leaves,\n links: node_links,\n copy: node_copy\n};\n","export default function() {\n var leaves = [];\n this.eachBefore(function(node) {\n if (!node.children) {\n leaves.push(node);\n }\n });\n return leaves;\n}\n","export default function() {\n var root = this, links = [];\n root.each(function(node) {\n if (node !== root) { // Don’t include the root’s parent, if any.\n links.push({source: node.parent, target: node});\n }\n });\n return links;\n}\n","export default function(end) {\n var start = this,\n ancestor = leastCommonAncestor(start, end),\n nodes = [start];\n while (start !== ancestor) {\n start = start.parent;\n nodes.push(start);\n }\n var k = nodes.length;\n while (end !== ancestor) {\n nodes.splice(k, 0, end);\n end = end.parent;\n }\n return nodes;\n}\n\nfunction leastCommonAncestor(a, b) {\n if (a === b) return a;\n var aNodes = a.ancestors(),\n bNodes = b.ancestors(),\n c = null;\n a = aNodes.pop();\n b = bNodes.pop();\n while (a === b) {\n c = a;\n a = aNodes.pop();\n b = bNodes.pop();\n }\n return c;\n}\n","export default function(compare) {\n return this.eachBefore(function(node) {\n if (node.children) {\n node.children.sort(compare);\n }\n });\n}\n","export default function(value) {\n return this.eachAfter(function(node) {\n var sum = +value(node.data) || 0,\n children = node.children,\n i = children && children.length;\n while (--i >= 0) sum += children[i].value;\n node.value = sum;\n });\n}\n","export {default as cluster} from \"./cluster.js\";\nexport {default as hierarchy} from \"./hierarchy/index.js\";\nexport {default as pack} from \"./pack/index.js\";\nexport {default as packSiblings} from \"./pack/siblings.js\";\nexport {default as packEnclose} from \"./pack/enclose.js\";\nexport {default as partition} from \"./partition.js\";\nexport {default as stratify} from \"./stratify.js\";\nexport {default as tree} from \"./tree.js\";\nexport {default as treemap} from \"./treemap/index.js\";\nexport {default as treemapBinary} from \"./treemap/binary.js\";\nexport {default as treemapDice} from \"./treemap/dice.js\";\nexport {default as treemapSlice} from \"./treemap/slice.js\";\nexport {default as treemapSliceDice} from \"./treemap/sliceDice.js\";\nexport {default as treemapSquarify} from \"./treemap/squarify.js\";\nexport {default as treemapResquarify} from \"./treemap/resquarify.js\";\n","import {shuffle, slice} from \"../array.js\";\n\nexport default function(circles) {\n var i = 0, n = (circles = shuffle(slice.call(circles))).length, B = [], p, e;\n\n while (i < n) {\n p = circles[i];\n if (e && enclosesWeak(e, p)) ++i;\n else e = encloseBasis(B = extendBasis(B, p)), i = 0;\n }\n\n return e;\n}\n\nfunction extendBasis(B, p) {\n var i, j;\n\n if (enclosesWeakAll(p, B)) return [p];\n\n // If we get here then B must have at least one element.\n for (i = 0; i < B.length; ++i) {\n if (enclosesNot(p, B[i])\n && enclosesWeakAll(encloseBasis2(B[i], p), B)) {\n return [B[i], p];\n }\n }\n\n // If we get here then B must have at least two elements.\n for (i = 0; i < B.length - 1; ++i) {\n for (j = i + 1; j < B.length; ++j) {\n if (enclosesNot(encloseBasis2(B[i], B[j]), p)\n && enclosesNot(encloseBasis2(B[i], p), B[j])\n && enclosesNot(encloseBasis2(B[j], p), B[i])\n && enclosesWeakAll(encloseBasis3(B[i], B[j], p), B)) {\n return [B[i], B[j], p];\n }\n }\n }\n\n // If we get here then something is very wrong.\n throw new Error;\n}\n\nfunction enclosesNot(a, b) {\n var dr = a.r - b.r, dx = b.x - a.x, dy = b.y - a.y;\n return dr < 0 || dr * dr < dx * dx + dy * dy;\n}\n\nfunction enclosesWeak(a, b) {\n var dr = a.r - b.r + 1e-6, dx = b.x - a.x, dy = b.y - a.y;\n return dr > 0 && dr * dr > dx * dx + dy * dy;\n}\n\nfunction enclosesWeakAll(a, B) {\n for (var i = 0; i < B.length; ++i) {\n if (!enclosesWeak(a, B[i])) {\n return false;\n }\n }\n return true;\n}\n\nfunction encloseBasis(B) {\n switch (B.length) {\n case 1: return encloseBasis1(B[0]);\n case 2: return encloseBasis2(B[0], B[1]);\n case 3: return encloseBasis3(B[0], B[1], B[2]);\n }\n}\n\nfunction encloseBasis1(a) {\n return {\n x: a.x,\n y: a.y,\n r: a.r\n };\n}\n\nfunction encloseBasis2(a, b) {\n var x1 = a.x, y1 = a.y, r1 = a.r,\n x2 = b.x, y2 = b.y, r2 = b.r,\n x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1,\n l = Math.sqrt(x21 * x21 + y21 * y21);\n return {\n x: (x1 + x2 + x21 / l * r21) / 2,\n y: (y1 + y2 + y21 / l * r21) / 2,\n r: (l + r1 + r2) / 2\n };\n}\n\nfunction encloseBasis3(a, b, c) {\n var x1 = a.x, y1 = a.y, r1 = a.r,\n x2 = b.x, y2 = b.y, r2 = b.r,\n x3 = c.x, y3 = c.y, r3 = c.r,\n a2 = x1 - x2,\n a3 = x1 - x3,\n b2 = y1 - y2,\n b3 = y1 - y3,\n c2 = r2 - r1,\n c3 = r3 - r1,\n d1 = x1 * x1 + y1 * y1 - r1 * r1,\n d2 = d1 - x2 * x2 - y2 * y2 + r2 * r2,\n d3 = d1 - x3 * x3 - y3 * y3 + r3 * r3,\n ab = a3 * b2 - a2 * b3,\n xa = (b2 * d3 - b3 * d2) / (ab * 2) - x1,\n xb = (b3 * c2 - b2 * c3) / ab,\n ya = (a3 * d2 - a2 * d3) / (ab * 2) - y1,\n yb = (a2 * c3 - a3 * c2) / ab,\n A = xb * xb + yb * yb - 1,\n B = 2 * (r1 + xa * xb + ya * yb),\n C = xa * xa + ya * ya - r1 * r1,\n r = -(A ? (B + Math.sqrt(B * B - 4 * A * C)) / (2 * A) : C / B);\n return {\n x: x1 + xa + xb * r,\n y: y1 + ya + yb * r,\n r: r\n };\n}\n","import {packEnclose} from \"./siblings.js\";\nimport {optional} from \"../accessors.js\";\nimport constant, {constantZero} from \"../constant.js\";\n\nfunction defaultRadius(d) {\n return Math.sqrt(d.value);\n}\n\nexport default function() {\n var radius = null,\n dx = 1,\n dy = 1,\n padding = constantZero;\n\n function pack(root) {\n root.x = dx / 2, root.y = dy / 2;\n if (radius) {\n root.eachBefore(radiusLeaf(radius))\n .eachAfter(packChildren(padding, 0.5))\n .eachBefore(translateChild(1));\n } else {\n root.eachBefore(radiusLeaf(defaultRadius))\n .eachAfter(packChildren(constantZero, 1))\n .eachAfter(packChildren(padding, root.r / Math.min(dx, dy)))\n .eachBefore(translateChild(Math.min(dx, dy) / (2 * root.r)));\n }\n return root;\n }\n\n pack.radius = function(x) {\n return arguments.length ? (radius = optional(x), pack) : radius;\n };\n\n pack.size = function(x) {\n return arguments.length ? (dx = +x[0], dy = +x[1], pack) : [dx, dy];\n };\n\n pack.padding = function(x) {\n return arguments.length ? (padding = typeof x === \"function\" ? x : constant(+x), pack) : padding;\n };\n\n return pack;\n}\n\nfunction radiusLeaf(radius) {\n return function(node) {\n if (!node.children) {\n node.r = Math.max(0, +radius(node) || 0);\n }\n };\n}\n\nfunction packChildren(padding, k) {\n return function(node) {\n if (children = node.children) {\n var children,\n i,\n n = children.length,\n r = padding(node) * k || 0,\n e;\n\n if (r) for (i = 0; i < n; ++i) children[i].r += r;\n e = packEnclose(children);\n if (r) for (i = 0; i < n; ++i) children[i].r -= r;\n node.r = e + r;\n }\n };\n}\n\nfunction translateChild(k) {\n return function(node) {\n var parent = node.parent;\n node.r *= k;\n if (parent) {\n node.x = parent.x + k * node.x;\n node.y = parent.y + k * node.y;\n }\n };\n}\n","import enclose from \"./enclose.js\";\n\nfunction place(b, a, c) {\n var dx = b.x - a.x, x, a2,\n dy = b.y - a.y, y, b2,\n d2 = dx * dx + dy * dy;\n if (d2) {\n a2 = a.r + c.r, a2 *= a2;\n b2 = b.r + c.r, b2 *= b2;\n if (a2 > b2) {\n x = (d2 + b2 - a2) / (2 * d2);\n y = Math.sqrt(Math.max(0, b2 / d2 - x * x));\n c.x = b.x - x * dx - y * dy;\n c.y = b.y - x * dy + y * dx;\n } else {\n x = (d2 + a2 - b2) / (2 * d2);\n y = Math.sqrt(Math.max(0, a2 / d2 - x * x));\n c.x = a.x + x * dx - y * dy;\n c.y = a.y + x * dy + y * dx;\n }\n } else {\n c.x = a.x + c.r;\n c.y = a.y;\n }\n}\n\nfunction intersects(a, b) {\n var dr = a.r + b.r - 1e-6, dx = b.x - a.x, dy = b.y - a.y;\n return dr > 0 && dr * dr > dx * dx + dy * dy;\n}\n\nfunction score(node) {\n var a = node._,\n b = node.next._,\n ab = a.r + b.r,\n dx = (a.x * b.r + b.x * a.r) / ab,\n dy = (a.y * b.r + b.y * a.r) / ab;\n return dx * dx + dy * dy;\n}\n\nfunction Node(circle) {\n this._ = circle;\n this.next = null;\n this.previous = null;\n}\n\nexport function packEnclose(circles) {\n if (!(n = circles.length)) return 0;\n\n var a, b, c, n, aa, ca, i, j, k, sj, sk;\n\n // Place the first circle.\n a = circles[0], a.x = 0, a.y = 0;\n if (!(n > 1)) return a.r;\n\n // Place the second circle.\n b = circles[1], a.x = -b.r, b.x = a.r, b.y = 0;\n if (!(n > 2)) return a.r + b.r;\n\n // Place the third circle.\n place(b, a, c = circles[2]);\n\n // Initialize the front-chain using the first three circles a, b and c.\n a = new Node(a), b = new Node(b), c = new Node(c);\n a.next = c.previous = b;\n b.next = a.previous = c;\n c.next = b.previous = a;\n\n // Attempt to place each remaining circle…\n pack: for (i = 3; i < n; ++i) {\n place(a._, b._, c = circles[i]), c = new Node(c);\n\n // Find the closest intersecting circle on the front-chain, if any.\n // “Closeness” is determined by linear distance along the front-chain.\n // “Ahead” or “behind” is likewise determined by linear distance.\n j = b.next, k = a.previous, sj = b._.r, sk = a._.r;\n do {\n if (sj <= sk) {\n if (intersects(j._, c._)) {\n b = j, a.next = b, b.previous = a, --i;\n continue pack;\n }\n sj += j._.r, j = j.next;\n } else {\n if (intersects(k._, c._)) {\n a = k, a.next = b, b.previous = a, --i;\n continue pack;\n }\n sk += k._.r, k = k.previous;\n }\n } while (j !== k.next);\n\n // Success! Insert the new circle c between a and b.\n c.previous = a, c.next = b, a.next = b.previous = b = c;\n\n // Compute the new closest circle pair to the centroid.\n aa = score(a);\n while ((c = c.next) !== b) {\n if ((ca = score(c)) < aa) {\n a = c, aa = ca;\n }\n }\n b = a.next;\n }\n\n // Compute the enclosing circle of the front chain.\n a = [b._], c = b; while ((c = c.next) !== b) a.push(c._); c = enclose(a);\n\n // Translate the circles to put the enclosing circle around the origin.\n for (i = 0; i < n; ++i) a = circles[i], a.x -= c.x, a.y -= c.y;\n\n return c.r;\n}\n\nexport default function(circles) {\n packEnclose(circles);\n return circles;\n}\n","import roundNode from \"./treemap/round.js\";\nimport treemapDice from \"./treemap/dice.js\";\n\nexport default function() {\n var dx = 1,\n dy = 1,\n padding = 0,\n round = false;\n\n function partition(root) {\n var n = root.height + 1;\n root.x0 =\n root.y0 = padding;\n root.x1 = dx;\n root.y1 = dy / n;\n root.eachBefore(positionNode(dy, n));\n if (round) root.eachBefore(roundNode);\n return root;\n }\n\n function positionNode(dy, n) {\n return function(node) {\n if (node.children) {\n treemapDice(node, node.x0, dy * (node.depth + 1) / n, node.x1, dy * (node.depth + 2) / n);\n }\n var x0 = node.x0,\n y0 = node.y0,\n x1 = node.x1 - padding,\n y1 = node.y1 - padding;\n if (x1 < x0) x0 = x1 = (x0 + x1) / 2;\n if (y1 < y0) y0 = y1 = (y0 + y1) / 2;\n node.x0 = x0;\n node.y0 = y0;\n node.x1 = x1;\n node.y1 = y1;\n };\n }\n\n partition.round = function(x) {\n return arguments.length ? (round = !!x, partition) : round;\n };\n\n partition.size = function(x) {\n return arguments.length ? (dx = +x[0], dy = +x[1], partition) : [dx, dy];\n };\n\n partition.padding = function(x) {\n return arguments.length ? (padding = +x, partition) : padding;\n };\n\n return partition;\n}\n","import {required} from \"./accessors.js\";\nimport {Node, computeHeight} from \"./hierarchy/index.js\";\n\nvar keyPrefix = \"$\", // Protect against keys like “__proto__”.\n preroot = {depth: -1},\n ambiguous = {};\n\nfunction defaultId(d) {\n return d.id;\n}\n\nfunction defaultParentId(d) {\n return d.parentId;\n}\n\nexport default function() {\n var id = defaultId,\n parentId = defaultParentId;\n\n function stratify(data) {\n var d,\n i,\n n = data.length,\n root,\n parent,\n node,\n nodes = new Array(n),\n nodeId,\n nodeKey,\n nodeByKey = {};\n\n for (i = 0; i < n; ++i) {\n d = data[i], node = nodes[i] = new Node(d);\n if ((nodeId = id(d, i, data)) != null && (nodeId += \"\")) {\n nodeKey = keyPrefix + (node.id = nodeId);\n nodeByKey[nodeKey] = nodeKey in nodeByKey ? ambiguous : node;\n }\n }\n\n for (i = 0; i < n; ++i) {\n node = nodes[i], nodeId = parentId(data[i], i, data);\n if (nodeId == null || !(nodeId += \"\")) {\n if (root) throw new Error(\"multiple roots\");\n root = node;\n } else {\n parent = nodeByKey[keyPrefix + nodeId];\n if (!parent) throw new Error(\"missing: \" + nodeId);\n if (parent === ambiguous) throw new Error(\"ambiguous: \" + nodeId);\n if (parent.children) parent.children.push(node);\n else parent.children = [node];\n node.parent = parent;\n }\n }\n\n if (!root) throw new Error(\"no root\");\n root.parent = preroot;\n root.eachBefore(function(node) { node.depth = node.parent.depth + 1; --n; }).eachBefore(computeHeight);\n root.parent = null;\n if (n > 0) throw new Error(\"cycle\");\n\n return root;\n }\n\n stratify.id = function(x) {\n return arguments.length ? (id = required(x), stratify) : id;\n };\n\n stratify.parentId = function(x) {\n return arguments.length ? (parentId = required(x), stratify) : parentId;\n };\n\n return stratify;\n}\n","import {Node} from \"./hierarchy/index.js\";\n\nfunction defaultSeparation(a, b) {\n return a.parent === b.parent ? 1 : 2;\n}\n\n// function radialSeparation(a, b) {\n// return (a.parent === b.parent ? 1 : 2) / a.depth;\n// }\n\n// This function is used to traverse the left contour of a subtree (or\n// subforest). It returns the successor of v on this contour. This successor is\n// either given by the leftmost child of v or by the thread of v. The function\n// returns null if and only if v is on the highest level of its subtree.\nfunction nextLeft(v) {\n var children = v.children;\n return children ? children[0] : v.t;\n}\n\n// This function works analogously to nextLeft.\nfunction nextRight(v) {\n var children = v.children;\n return children ? children[children.length - 1] : v.t;\n}\n\n// Shifts the current subtree rooted at w+. This is done by increasing\n// prelim(w+) and mod(w+) by shift.\nfunction moveSubtree(wm, wp, shift) {\n var change = shift / (wp.i - wm.i);\n wp.c -= change;\n wp.s += shift;\n wm.c += change;\n wp.z += shift;\n wp.m += shift;\n}\n\n// All other shifts, applied to the smaller subtrees between w- and w+, are\n// performed by this function. To prepare the shifts, we have to adjust\n// change(w+), shift(w+), and change(w-).\nfunction executeShifts(v) {\n var shift = 0,\n change = 0,\n children = v.children,\n i = children.length,\n w;\n while (--i >= 0) {\n w = children[i];\n w.z += shift;\n w.m += shift;\n shift += w.s + (change += w.c);\n }\n}\n\n// If vi-’s ancestor is a sibling of v, returns vi-’s ancestor. Otherwise,\n// returns the specified (default) ancestor.\nfunction nextAncestor(vim, v, ancestor) {\n return vim.a.parent === v.parent ? vim.a : ancestor;\n}\n\nfunction TreeNode(node, i) {\n this._ = node;\n this.parent = null;\n this.children = null;\n this.A = null; // default ancestor\n this.a = this; // ancestor\n this.z = 0; // prelim\n this.m = 0; // mod\n this.c = 0; // change\n this.s = 0; // shift\n this.t = null; // thread\n this.i = i; // number\n}\n\nTreeNode.prototype = Object.create(Node.prototype);\n\nfunction treeRoot(root) {\n var tree = new TreeNode(root, 0),\n node,\n nodes = [tree],\n child,\n children,\n i,\n n;\n\n while (node = nodes.pop()) {\n if (children = node._.children) {\n node.children = new Array(n = children.length);\n for (i = n - 1; i >= 0; --i) {\n nodes.push(child = node.children[i] = new TreeNode(children[i], i));\n child.parent = node;\n }\n }\n }\n\n (tree.parent = new TreeNode(null, 0)).children = [tree];\n return tree;\n}\n\n// Node-link tree diagram using the Reingold-Tilford \"tidy\" algorithm\nexport default function() {\n var separation = defaultSeparation,\n dx = 1,\n dy = 1,\n nodeSize = null;\n\n function tree(root) {\n var t = treeRoot(root);\n\n // Compute the layout using Buchheim et al.’s algorithm.\n t.eachAfter(firstWalk), t.parent.m = -t.z;\n t.eachBefore(secondWalk);\n\n // If a fixed node size is specified, scale x and y.\n if (nodeSize) root.eachBefore(sizeNode);\n\n // If a fixed tree size is specified, scale x and y based on the extent.\n // Compute the left-most, right-most, and depth-most nodes for extents.\n else {\n var left = root,\n right = root,\n bottom = root;\n root.eachBefore(function(node) {\n if (node.x < left.x) left = node;\n if (node.x > right.x) right = node;\n if (node.depth > bottom.depth) bottom = node;\n });\n var s = left === right ? 1 : separation(left, right) / 2,\n tx = s - left.x,\n kx = dx / (right.x + s + tx),\n ky = dy / (bottom.depth || 1);\n root.eachBefore(function(node) {\n node.x = (node.x + tx) * kx;\n node.y = node.depth * ky;\n });\n }\n\n return root;\n }\n\n // Computes a preliminary x-coordinate for v. Before that, FIRST WALK is\n // applied recursively to the children of v, as well as the function\n // APPORTION. After spacing out the children by calling EXECUTE SHIFTS, the\n // node v is placed to the midpoint of its outermost children.\n function firstWalk(v) {\n var children = v.children,\n siblings = v.parent.children,\n w = v.i ? siblings[v.i - 1] : null;\n if (children) {\n executeShifts(v);\n var midpoint = (children[0].z + children[children.length - 1].z) / 2;\n if (w) {\n v.z = w.z + separation(v._, w._);\n v.m = v.z - midpoint;\n } else {\n v.z = midpoint;\n }\n } else if (w) {\n v.z = w.z + separation(v._, w._);\n }\n v.parent.A = apportion(v, w, v.parent.A || siblings[0]);\n }\n\n // Computes all real x-coordinates by summing up the modifiers recursively.\n function secondWalk(v) {\n v._.x = v.z + v.parent.m;\n v.m += v.parent.m;\n }\n\n // The core of the algorithm. Here, a new subtree is combined with the\n // previous subtrees. Threads are used to traverse the inside and outside\n // contours of the left and right subtree up to the highest common level. The\n // vertices used for the traversals are vi+, vi-, vo-, and vo+, where the\n // superscript o means outside and i means inside, the subscript - means left\n // subtree and + means right subtree. For summing up the modifiers along the\n // contour, we use respective variables si+, si-, so-, and so+. Whenever two\n // nodes of the inside contours conflict, we compute the left one of the\n // greatest uncommon ancestors using the function ANCESTOR and call MOVE\n // SUBTREE to shift the subtree and prepare the shifts of smaller subtrees.\n // Finally, we add a new thread (if necessary).\n function apportion(v, w, ancestor) {\n if (w) {\n var vip = v,\n vop = v,\n vim = w,\n vom = vip.parent.children[0],\n sip = vip.m,\n sop = vop.m,\n sim = vim.m,\n som = vom.m,\n shift;\n while (vim = nextRight(vim), vip = nextLeft(vip), vim && vip) {\n vom = nextLeft(vom);\n vop = nextRight(vop);\n vop.a = v;\n shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);\n if (shift > 0) {\n moveSubtree(nextAncestor(vim, v, ancestor), v, shift);\n sip += shift;\n sop += shift;\n }\n sim += vim.m;\n sip += vip.m;\n som += vom.m;\n sop += vop.m;\n }\n if (vim && !nextRight(vop)) {\n vop.t = vim;\n vop.m += sim - sop;\n }\n if (vip && !nextLeft(vom)) {\n vom.t = vip;\n vom.m += sip - som;\n ancestor = v;\n }\n }\n return ancestor;\n }\n\n function sizeNode(node) {\n node.x *= dx;\n node.y = node.depth * dy;\n }\n\n tree.separation = function(x) {\n return arguments.length ? (separation = x, tree) : separation;\n };\n\n tree.size = function(x) {\n return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], tree) : (nodeSize ? null : [dx, dy]);\n };\n\n tree.nodeSize = function(x) {\n return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], tree) : (nodeSize ? [dx, dy] : null);\n };\n\n return tree;\n}\n","export default function(parent, x0, y0, x1, y1) {\n var nodes = parent.children,\n i, n = nodes.length,\n sum, sums = new Array(n + 1);\n\n for (sums[0] = sum = i = 0; i < n; ++i) {\n sums[i + 1] = sum += nodes[i].value;\n }\n\n partition(0, n, parent.value, x0, y0, x1, y1);\n\n function partition(i, j, value, x0, y0, x1, y1) {\n if (i >= j - 1) {\n var node = nodes[i];\n node.x0 = x0, node.y0 = y0;\n node.x1 = x1, node.y1 = y1;\n return;\n }\n\n var valueOffset = sums[i],\n valueTarget = (value / 2) + valueOffset,\n k = i + 1,\n hi = j - 1;\n\n while (k < hi) {\n var mid = k + hi >>> 1;\n if (sums[mid] < valueTarget) k = mid + 1;\n else hi = mid;\n }\n\n if ((valueTarget - sums[k - 1]) < (sums[k] - valueTarget) && i + 1 < k) --k;\n\n var valueLeft = sums[k] - valueOffset,\n valueRight = value - valueLeft;\n\n if ((x1 - x0) > (y1 - y0)) {\n var xk = (x0 * valueRight + x1 * valueLeft) / value;\n partition(i, k, valueLeft, x0, y0, xk, y1);\n partition(k, j, valueRight, xk, y0, x1, y1);\n } else {\n var yk = (y0 * valueRight + y1 * valueLeft) / value;\n partition(i, k, valueLeft, x0, y0, x1, yk);\n partition(k, j, valueRight, x0, yk, x1, y1);\n }\n }\n}\n","export default function(parent, x0, y0, x1, y1) {\n var nodes = parent.children,\n node,\n i = -1,\n n = nodes.length,\n k = parent.value && (x1 - x0) / parent.value;\n\n while (++i < n) {\n node = nodes[i], node.y0 = y0, node.y1 = y1;\n node.x0 = x0, node.x1 = x0 += node.value * k;\n }\n}\n","import roundNode from \"./round.js\";\nimport squarify from \"./squarify.js\";\nimport {required} from \"../accessors.js\";\nimport constant, {constantZero} from \"../constant.js\";\n\nexport default function() {\n var tile = squarify,\n round = false,\n dx = 1,\n dy = 1,\n paddingStack = [0],\n paddingInner = constantZero,\n paddingTop = constantZero,\n paddingRight = constantZero,\n paddingBottom = constantZero,\n paddingLeft = constantZero;\n\n function treemap(root) {\n root.x0 =\n root.y0 = 0;\n root.x1 = dx;\n root.y1 = dy;\n root.eachBefore(positionNode);\n paddingStack = [0];\n if (round) root.eachBefore(roundNode);\n return root;\n }\n\n function positionNode(node) {\n var p = paddingStack[node.depth],\n x0 = node.x0 + p,\n y0 = node.y0 + p,\n x1 = node.x1 - p,\n y1 = node.y1 - p;\n if (x1 < x0) x0 = x1 = (x0 + x1) / 2;\n if (y1 < y0) y0 = y1 = (y0 + y1) / 2;\n node.x0 = x0;\n node.y0 = y0;\n node.x1 = x1;\n node.y1 = y1;\n if (node.children) {\n p = paddingStack[node.depth + 1] = paddingInner(node) / 2;\n x0 += paddingLeft(node) - p;\n y0 += paddingTop(node) - p;\n x1 -= paddingRight(node) - p;\n y1 -= paddingBottom(node) - p;\n if (x1 < x0) x0 = x1 = (x0 + x1) / 2;\n if (y1 < y0) y0 = y1 = (y0 + y1) / 2;\n tile(node, x0, y0, x1, y1);\n }\n }\n\n treemap.round = function(x) {\n return arguments.length ? (round = !!x, treemap) : round;\n };\n\n treemap.size = function(x) {\n return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [dx, dy];\n };\n\n treemap.tile = function(x) {\n return arguments.length ? (tile = required(x), treemap) : tile;\n };\n\n treemap.padding = function(x) {\n return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner();\n };\n\n treemap.paddingInner = function(x) {\n return arguments.length ? (paddingInner = typeof x === \"function\" ? x : constant(+x), treemap) : paddingInner;\n };\n\n treemap.paddingOuter = function(x) {\n return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop();\n };\n\n treemap.paddingTop = function(x) {\n return arguments.length ? (paddingTop = typeof x === \"function\" ? x : constant(+x), treemap) : paddingTop;\n };\n\n treemap.paddingRight = function(x) {\n return arguments.length ? (paddingRight = typeof x === \"function\" ? x : constant(+x), treemap) : paddingRight;\n };\n\n treemap.paddingBottom = function(x) {\n return arguments.length ? (paddingBottom = typeof x === \"function\" ? x : constant(+x), treemap) : paddingBottom;\n };\n\n treemap.paddingLeft = function(x) {\n return arguments.length ? (paddingLeft = typeof x === \"function\" ? x : constant(+x), treemap) : paddingLeft;\n };\n\n return treemap;\n}\n","import treemapDice from \"./dice.js\";\nimport treemapSlice from \"./slice.js\";\nimport {phi, squarifyRatio} from \"./squarify.js\";\n\nexport default (function custom(ratio) {\n\n function resquarify(parent, x0, y0, x1, y1) {\n if ((rows = parent._squarify) && (rows.ratio === ratio)) {\n var rows,\n row,\n nodes,\n i,\n j = -1,\n n,\n m = rows.length,\n value = parent.value;\n\n while (++j < m) {\n row = rows[j], nodes = row.children;\n for (i = row.value = 0, n = nodes.length; i < n; ++i) row.value += nodes[i].value;\n if (row.dice) treemapDice(row, x0, y0, x1, y0 += (y1 - y0) * row.value / value);\n else treemapSlice(row, x0, y0, x0 += (x1 - x0) * row.value / value, y1);\n value -= row.value;\n }\n } else {\n parent._squarify = rows = squarifyRatio(ratio, parent, x0, y0, x1, y1);\n rows.ratio = ratio;\n }\n }\n\n resquarify.ratio = function(x) {\n return custom((x = +x) > 1 ? x : 1);\n };\n\n return resquarify;\n})(phi);\n","export default function(node) {\n node.x0 = Math.round(node.x0);\n node.y0 = Math.round(node.y0);\n node.x1 = Math.round(node.x1);\n node.y1 = Math.round(node.y1);\n}\n","export default function(parent, x0, y0, x1, y1) {\n var nodes = parent.children,\n node,\n i = -1,\n n = nodes.length,\n k = parent.value && (y1 - y0) / parent.value;\n\n while (++i < n) {\n node = nodes[i], node.x0 = x0, node.x1 = x1;\n node.y0 = y0, node.y1 = y0 += node.value * k;\n }\n}\n","import dice from \"./dice.js\";\nimport slice from \"./slice.js\";\n\nexport default function(parent, x0, y0, x1, y1) {\n (parent.depth & 1 ? slice : dice)(parent, x0, y0, x1, y1);\n}\n","import treemapDice from \"./dice.js\";\nimport treemapSlice from \"./slice.js\";\n\nexport var phi = (1 + Math.sqrt(5)) / 2;\n\nexport function squarifyRatio(ratio, parent, x0, y0, x1, y1) {\n var rows = [],\n nodes = parent.children,\n row,\n nodeValue,\n i0 = 0,\n i1 = 0,\n n = nodes.length,\n dx, dy,\n value = parent.value,\n sumValue,\n minValue,\n maxValue,\n newRatio,\n minRatio,\n alpha,\n beta;\n\n while (i0 < n) {\n dx = x1 - x0, dy = y1 - y0;\n\n // Find the next non-empty node.\n do sumValue = nodes[i1++].value; while (!sumValue && i1 < n);\n minValue = maxValue = sumValue;\n alpha = Math.max(dy / dx, dx / dy) / (value * ratio);\n beta = sumValue * sumValue * alpha;\n minRatio = Math.max(maxValue / beta, beta / minValue);\n\n // Keep adding nodes while the aspect ratio maintains or improves.\n for (; i1 < n; ++i1) {\n sumValue += nodeValue = nodes[i1].value;\n if (nodeValue < minValue) minValue = nodeValue;\n if (nodeValue > maxValue) maxValue = nodeValue;\n beta = sumValue * sumValue * alpha;\n newRatio = Math.max(maxValue / beta, beta / minValue);\n if (newRatio > minRatio) { sumValue -= nodeValue; break; }\n minRatio = newRatio;\n }\n\n // Position and record the row orientation.\n rows.push(row = {value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1)});\n if (row.dice) treemapDice(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);\n else treemapSlice(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);\n value -= sumValue, i0 = i1;\n }\n\n return rows;\n}\n\nexport default (function custom(ratio) {\n\n function squarify(parent, x0, y0, x1, y1) {\n squarifyRatio(ratio, parent, x0, y0, x1, y1);\n }\n\n squarify.ratio = function(x) {\n return custom((x = +x) > 1 ? x : 1);\n };\n\n return squarify;\n})(phi);\n","import value from \"./value.js\";\nimport numberArray, {isNumberArray} from \"./numberArray.js\";\n\nexport default function(a, b) {\n return (isNumberArray(b) ? numberArray : genericArray)(a, b);\n}\n\nexport function genericArray(a, b) {\n var nb = b ? b.length : 0,\n na = a ? Math.min(nb, a.length) : 0,\n x = new Array(na),\n c = new Array(nb),\n i;\n\n for (i = 0; i < na; ++i) x[i] = value(a[i], b[i]);\n for (; i < nb; ++i) c[i] = b[i];\n\n return function(t) {\n for (i = 0; i < na; ++i) c[i] = x[i](t);\n return c;\n };\n}\n","export function basis(t1, v0, v1, v2, v3) {\n var t2 = t1 * t1, t3 = t2 * t1;\n return ((1 - 3 * t1 + 3 * t2 - t3) * v0\n + (4 - 6 * t2 + 3 * t3) * v1\n + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2\n + t3 * v3) / 6;\n}\n\nexport default function(values) {\n var n = values.length - 1;\n return function(t) {\n var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n),\n v1 = values[i],\n v2 = values[i + 1],\n v0 = i > 0 ? values[i - 1] : 2 * v1 - v2,\n v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1;\n return basis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n","import {basis} from \"./basis.js\";\n\nexport default function(values) {\n var n = values.length;\n return function(t) {\n var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n),\n v0 = values[(i + n - 1) % n],\n v1 = values[i % n],\n v2 = values[(i + 1) % n],\n v3 = values[(i + 2) % n];\n return basis((t - i / n) * n, v0, v1, v2, v3);\n };\n}\n","import constant from \"./constant.js\";\n\nfunction linear(a, d) {\n return function(t) {\n return a + t * d;\n };\n}\n\nfunction exponential(a, b, y) {\n return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) {\n return Math.pow(a + t * b, y);\n };\n}\n\nexport function hue(a, b) {\n var d = b - a;\n return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a);\n}\n\nexport function gamma(y) {\n return (y = +y) === 1 ? nogamma : function(a, b) {\n return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a);\n };\n}\n\nexport default function nogamma(a, b) {\n var d = b - a;\n return d ? linear(a, d) : constant(isNaN(a) ? b : a);\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","import {cubehelix as colorCubehelix} from \"d3-color\";\nimport color, {hue} from \"./color.js\";\n\nfunction cubehelix(hue) {\n return (function cubehelixGamma(y) {\n y = +y;\n\n function cubehelix(start, end) {\n var h = hue((start = colorCubehelix(start)).h, (end = colorCubehelix(end)).h),\n s = color(start.s, end.s),\n l = color(start.l, end.l),\n opacity = color(start.opacity, end.opacity);\n return function(t) {\n start.h = h(t);\n start.s = s(t);\n start.l = l(Math.pow(t, y));\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n\n cubehelix.gamma = cubehelixGamma;\n\n return cubehelix;\n })(1);\n}\n\nexport default cubehelix(hue);\nexport var cubehelixLong = cubehelix(color);\n","export default function(a, b) {\n var d = new Date;\n return a = +a, b = +b, function(t) {\n return d.setTime(a * (1 - t) + b * t), d;\n };\n}\n","export default function(range) {\n var n = range.length;\n return function(t) {\n return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];\n };\n}\n","import {hcl as colorHcl} from \"d3-color\";\nimport color, {hue} from \"./color.js\";\n\nfunction hcl(hue) {\n return function(start, end) {\n var h = hue((start = colorHcl(start)).h, (end = colorHcl(end)).h),\n c = color(start.c, end.c),\n l = color(start.l, end.l),\n opacity = color(start.opacity, end.opacity);\n return function(t) {\n start.h = h(t);\n start.c = c(t);\n start.l = l(t);\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n}\n\nexport default hcl(hue);\nexport var hclLong = hcl(color);\n","import {hsl as colorHsl} from \"d3-color\";\nimport color, {hue} from \"./color.js\";\n\nfunction hsl(hue) {\n return function(start, end) {\n var h = hue((start = colorHsl(start)).h, (end = colorHsl(end)).h),\n s = color(start.s, end.s),\n l = color(start.l, end.l),\n opacity = color(start.opacity, end.opacity);\n return function(t) {\n start.h = h(t);\n start.s = s(t);\n start.l = l(t);\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n}\n\nexport default hsl(hue);\nexport var hslLong = hsl(color);\n","import {hue} from \"./color.js\";\n\nexport default function(a, b) {\n var i = hue(+a, +b);\n return function(t) {\n var x = i(t);\n return x - 360 * Math.floor(x / 360);\n };\n}\n","export {default as interpolate} from \"./value.js\";\nexport {default as interpolateArray} from \"./array.js\";\nexport {default as interpolateBasis} from \"./basis.js\";\nexport {default as interpolateBasisClosed} from \"./basisClosed.js\";\nexport {default as interpolateDate} from \"./date.js\";\nexport {default as interpolateDiscrete} from \"./discrete.js\";\nexport {default as interpolateHue} from \"./hue.js\";\nexport {default as interpolateNumber} from \"./number.js\";\nexport {default as interpolateNumberArray} from \"./numberArray.js\";\nexport {default as interpolateObject} from \"./object.js\";\nexport {default as interpolateRound} from \"./round.js\";\nexport {default as interpolateString} from \"./string.js\";\nexport {interpolateTransformCss, interpolateTransformSvg} from \"./transform/index.js\";\nexport {default as interpolateZoom} from \"./zoom.js\";\nexport {default as interpolateRgb, rgbBasis as interpolateRgbBasis, rgbBasisClosed as interpolateRgbBasisClosed} from \"./rgb.js\";\nexport {default as interpolateHsl, hslLong as interpolateHslLong} from \"./hsl.js\";\nexport {default as interpolateLab} from \"./lab.js\";\nexport {default as interpolateHcl, hclLong as interpolateHclLong} from \"./hcl.js\";\nexport {default as interpolateCubehelix, cubehelixLong as interpolateCubehelixLong} from \"./cubehelix.js\";\nexport {default as piecewise} from \"./piecewise.js\";\nexport {default as quantize} from \"./quantize.js\";\n","import {lab as colorLab} from \"d3-color\";\nimport color from \"./color.js\";\n\nexport default function lab(start, end) {\n var l = color((start = colorLab(start)).l, (end = colorLab(end)).l),\n a = color(start.a, end.a),\n b = color(start.b, end.b),\n opacity = color(start.opacity, end.opacity);\n return function(t) {\n start.l = l(t);\n start.a = a(t);\n start.b = b(t);\n start.opacity = opacity(t);\n return start + \"\";\n };\n}\n","export default function(a, b) {\n return a = +a, b = +b, function(t) {\n return a * (1 - t) + b * t;\n };\n}\n","export default function(a, b) {\n if (!b) b = [];\n var n = a ? Math.min(b.length, a.length) : 0,\n c = b.slice(),\n i;\n return function(t) {\n for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t;\n return c;\n };\n}\n\nexport function isNumberArray(x) {\n return ArrayBuffer.isView(x) && !(x instanceof DataView);\n}\n","import value from \"./value.js\";\n\nexport default function(a, b) {\n var i = {},\n c = {},\n k;\n\n if (a === null || typeof a !== \"object\") a = {};\n if (b === null || typeof b !== \"object\") b = {};\n\n for (k in b) {\n if (k in a) {\n i[k] = value(a[k], b[k]);\n } else {\n c[k] = b[k];\n }\n }\n\n return function(t) {\n for (k in i) c[k] = i[k](t);\n return c;\n };\n}\n","export default function piecewise(interpolate, values) {\n var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n);\n while (i < n) I[i] = interpolate(v, v = values[++i]);\n return function(t) {\n var i = Math.max(0, Math.min(n - 1, Math.floor(t *= n)));\n return I[i](t - i);\n };\n}\n","export default function(interpolator, n) {\n var samples = new Array(n);\n for (var i = 0; i < n; ++i) samples[i] = interpolator(i / (n - 1));\n return samples;\n}\n","import {rgb as colorRgb} from \"d3-color\";\nimport basis from \"./basis.js\";\nimport basisClosed from \"./basisClosed.js\";\nimport nogamma, {gamma} from \"./color.js\";\n\nexport default (function rgbGamma(y) {\n var color = gamma(y);\n\n function rgb(start, end) {\n var r = color((start = colorRgb(start)).r, (end = colorRgb(end)).r),\n g = color(start.g, end.g),\n b = color(start.b, end.b),\n opacity = nogamma(start.opacity, end.opacity);\n return function(t) {\n start.r = r(t);\n start.g = g(t);\n start.b = b(t);\n start.opacity = opacity(t);\n return start + \"\";\n };\n }\n\n rgb.gamma = rgbGamma;\n\n return rgb;\n})(1);\n\nfunction rgbSpline(spline) {\n return function(colors) {\n var n = colors.length,\n r = new Array(n),\n g = new Array(n),\n b = new Array(n),\n i, color;\n for (i = 0; i < n; ++i) {\n color = colorRgb(colors[i]);\n r[i] = color.r || 0;\n g[i] = color.g || 0;\n b[i] = color.b || 0;\n }\n r = spline(r);\n g = spline(g);\n b = spline(b);\n color.opacity = 1;\n return function(t) {\n color.r = r(t);\n color.g = g(t);\n color.b = b(t);\n return color + \"\";\n };\n };\n}\n\nexport var rgbBasis = rgbSpline(basis);\nexport var rgbBasisClosed = rgbSpline(basisClosed);\n","export default function(a, b) {\n return a = +a, b = +b, function(t) {\n return Math.round(a * (1 - t) + b * t);\n };\n}\n","import number from \"./number.js\";\n\nvar reA = /[-+]?(?:\\d+\\.?\\d*|\\.?\\d+)(?:[eE][-+]?\\d+)?/g,\n reB = new RegExp(reA.source, \"g\");\n\nfunction zero(b) {\n return function() {\n return b;\n };\n}\n\nfunction one(b) {\n return function(t) {\n return b(t) + \"\";\n };\n}\n\nexport default function(a, b) {\n var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b\n am, // current match in a\n bm, // current match in b\n bs, // string preceding current number in b, if any\n i = -1, // index in s\n s = [], // string constants and placeholders\n q = []; // number interpolators\n\n // Coerce inputs to strings.\n a = a + \"\", b = b + \"\";\n\n // Interpolate pairs of numbers in a & b.\n while ((am = reA.exec(a))\n && (bm = reB.exec(b))) {\n if ((bs = bm.index) > bi) { // a string precedes the next number in b\n bs = b.slice(bi, bs);\n if (s[i]) s[i] += bs; // coalesce with previous string\n else s[++i] = bs;\n }\n if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match\n if (s[i]) s[i] += bm; // coalesce with previous string\n else s[++i] = bm;\n } else { // interpolate non-matching numbers\n s[++i] = null;\n q.push({i: i, x: number(am, bm)});\n }\n bi = reB.lastIndex;\n }\n\n // Add remains of b.\n if (bi < b.length) {\n bs = b.slice(bi);\n if (s[i]) s[i] += bs; // coalesce with previous string\n else s[++i] = bs;\n }\n\n // Special optimization for only a single match.\n // Otherwise, interpolate each of the numbers and rejoin the string.\n return s.length < 2 ? (q[0]\n ? one(q[0].x)\n : zero(b))\n : (b = q.length, function(t) {\n for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);\n return s.join(\"\");\n });\n}\n","var degrees = 180 / Math.PI;\n\nexport var identity = {\n translateX: 0,\n translateY: 0,\n rotate: 0,\n skewX: 0,\n scaleX: 1,\n scaleY: 1\n};\n\nexport default function(a, b, c, d, e, f) {\n var scaleX, scaleY, skewX;\n if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX;\n if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX;\n if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY;\n if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX;\n return {\n translateX: e,\n translateY: f,\n rotate: Math.atan2(b, a) * degrees,\n skewX: Math.atan(skewX) * degrees,\n scaleX: scaleX,\n scaleY: scaleY\n };\n}\n","import number from \"../number.js\";\nimport {parseCss, parseSvg} from \"./parse.js\";\n\nfunction interpolateTransform(parse, pxComma, pxParen, degParen) {\n\n function pop(s) {\n return s.length ? s.pop() + \" \" : \"\";\n }\n\n function translate(xa, ya, xb, yb, s, q) {\n if (xa !== xb || ya !== yb) {\n var i = s.push(\"translate(\", null, pxComma, null, pxParen);\n q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)});\n } else if (xb || yb) {\n s.push(\"translate(\" + xb + pxComma + yb + pxParen);\n }\n }\n\n function rotate(a, b, s, q) {\n if (a !== b) {\n if (a - b > 180) b += 360; else if (b - a > 180) a += 360; // shortest path\n q.push({i: s.push(pop(s) + \"rotate(\", null, degParen) - 2, x: number(a, b)});\n } else if (b) {\n s.push(pop(s) + \"rotate(\" + b + degParen);\n }\n }\n\n function skewX(a, b, s, q) {\n if (a !== b) {\n q.push({i: s.push(pop(s) + \"skewX(\", null, degParen) - 2, x: number(a, b)});\n } else if (b) {\n s.push(pop(s) + \"skewX(\" + b + degParen);\n }\n }\n\n function scale(xa, ya, xb, yb, s, q) {\n if (xa !== xb || ya !== yb) {\n var i = s.push(pop(s) + \"scale(\", null, \",\", null, \")\");\n q.push({i: i - 4, x: number(xa, xb)}, {i: i - 2, x: number(ya, yb)});\n } else if (xb !== 1 || yb !== 1) {\n s.push(pop(s) + \"scale(\" + xb + \",\" + yb + \")\");\n }\n }\n\n return function(a, b) {\n var s = [], // string constants and placeholders\n q = []; // number interpolators\n a = parse(a), b = parse(b);\n translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q);\n rotate(a.rotate, b.rotate, s, q);\n skewX(a.skewX, b.skewX, s, q);\n scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q);\n a = b = null; // gc\n return function(t) {\n var i = -1, n = q.length, o;\n while (++i < n) s[(o = q[i]).i] = o.x(t);\n return s.join(\"\");\n };\n };\n}\n\nexport var interpolateTransformCss = interpolateTransform(parseCss, \"px, \", \"px)\", \"deg)\");\nexport var interpolateTransformSvg = interpolateTransform(parseSvg, \", \", \")\", \")\");\n","import decompose, {identity} from \"./decompose.js\";\n\nvar cssNode,\n cssRoot,\n cssView,\n svgNode;\n\nexport function parseCss(value) {\n if (value === \"none\") return identity;\n if (!cssNode) cssNode = document.createElement(\"DIV\"), cssRoot = document.documentElement, cssView = document.defaultView;\n cssNode.style.transform = value;\n value = cssView.getComputedStyle(cssRoot.appendChild(cssNode), null).getPropertyValue(\"transform\");\n cssRoot.removeChild(cssNode);\n value = value.slice(7, -1).split(\",\");\n return decompose(+value[0], +value[1], +value[2], +value[3], +value[4], +value[5]);\n}\n\nexport function parseSvg(value) {\n if (value == null) return identity;\n if (!svgNode) svgNode = document.createElementNS(\"http://www.w3.org/2000/svg\", \"g\");\n svgNode.setAttribute(\"transform\", value);\n if (!(value = svgNode.transform.baseVal.consolidate())) return identity;\n value = value.matrix;\n return decompose(value.a, value.b, value.c, value.d, value.e, value.f);\n}\n","import {color} from \"d3-color\";\nimport rgb from \"./rgb.js\";\nimport {genericArray} from \"./array.js\";\nimport date from \"./date.js\";\nimport number from \"./number.js\";\nimport object from \"./object.js\";\nimport string from \"./string.js\";\nimport constant from \"./constant.js\";\nimport numberArray, {isNumberArray} from \"./numberArray.js\";\n\nexport default function(a, b) {\n var t = typeof b, c;\n return b == null || t === \"boolean\" ? constant(b)\n : (t === \"number\" ? number\n : t === \"string\" ? ((c = color(b)) ? (b = c, rgb) : string)\n : b instanceof color ? rgb\n : b instanceof Date ? date\n : isNumberArray(b) ? numberArray\n : Array.isArray(b) ? genericArray\n : typeof b.valueOf !== \"function\" && typeof b.toString !== \"function\" || isNaN(b) ? object\n : number)(a, b);\n}\n","var rho = Math.SQRT2,\n rho2 = 2,\n rho4 = 4,\n epsilon2 = 1e-12;\n\nfunction cosh(x) {\n return ((x = Math.exp(x)) + 1 / x) / 2;\n}\n\nfunction sinh(x) {\n return ((x = Math.exp(x)) - 1 / x) / 2;\n}\n\nfunction tanh(x) {\n return ((x = Math.exp(2 * x)) - 1) / (x + 1);\n}\n\n// p0 = [ux0, uy0, w0]\n// p1 = [ux1, uy1, w1]\nexport default function(p0, p1) {\n var ux0 = p0[0], uy0 = p0[1], w0 = p0[2],\n ux1 = p1[0], uy1 = p1[1], w1 = p1[2],\n dx = ux1 - ux0,\n dy = uy1 - uy0,\n d2 = dx * dx + dy * dy,\n i,\n S;\n\n // Special case for u0 ≅ u1.\n if (d2 < epsilon2) {\n S = Math.log(w1 / w0) / rho;\n i = function(t) {\n return [\n ux0 + t * dx,\n uy0 + t * dy,\n w0 * Math.exp(rho * t * S)\n ];\n }\n }\n\n // General case.\n else {\n var d1 = Math.sqrt(d2),\n b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1),\n b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1),\n r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0),\n r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);\n S = (r1 - r0) / rho;\n i = function(t) {\n var s = t * S,\n coshr0 = cosh(r0),\n u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0));\n return [\n ux0 + u * dx,\n uy0 + u * dy,\n w0 * coshr0 / cosh(rho * s + r0)\n ];\n }\n }\n\n i.duration = S * 1000;\n\n return i;\n}\n","export {default as path} from \"./path.js\";\n","var pi = Math.PI,\n tau = 2 * pi,\n epsilon = 1e-6,\n tauEpsilon = tau - epsilon;\n\nfunction Path() {\n this._x0 = this._y0 = // start of current subpath\n this._x1 = this._y1 = null; // end of current subpath\n this._ = \"\";\n}\n\nfunction path() {\n return new Path;\n}\n\nPath.prototype = path.prototype = {\n constructor: Path,\n moveTo: function(x, y) {\n this._ += \"M\" + (this._x0 = this._x1 = +x) + \",\" + (this._y0 = this._y1 = +y);\n },\n closePath: function() {\n if (this._x1 !== null) {\n this._x1 = this._x0, this._y1 = this._y0;\n this._ += \"Z\";\n }\n },\n lineTo: function(x, y) {\n this._ += \"L\" + (this._x1 = +x) + \",\" + (this._y1 = +y);\n },\n quadraticCurveTo: function(x1, y1, x, y) {\n this._ += \"Q\" + (+x1) + \",\" + (+y1) + \",\" + (this._x1 = +x) + \",\" + (this._y1 = +y);\n },\n bezierCurveTo: function(x1, y1, x2, y2, x, y) {\n this._ += \"C\" + (+x1) + \",\" + (+y1) + \",\" + (+x2) + \",\" + (+y2) + \",\" + (this._x1 = +x) + \",\" + (this._y1 = +y);\n },\n arcTo: function(x1, y1, x2, y2, r) {\n x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;\n var x0 = this._x1,\n y0 = this._y1,\n x21 = x2 - x1,\n y21 = y2 - y1,\n x01 = x0 - x1,\n y01 = y0 - y1,\n l01_2 = x01 * x01 + y01 * y01;\n\n // Is the radius negative? Error.\n if (r < 0) throw new Error(\"negative radius: \" + r);\n\n // Is this path empty? Move to (x1,y1).\n if (this._x1 === null) {\n this._ += \"M\" + (this._x1 = x1) + \",\" + (this._y1 = y1);\n }\n\n // Or, is (x1,y1) coincident with (x0,y0)? Do nothing.\n else if (!(l01_2 > epsilon));\n\n // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear?\n // Equivalently, is (x1,y1) coincident with (x2,y2)?\n // Or, is the radius zero? Line to (x1,y1).\n else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r) {\n this._ += \"L\" + (this._x1 = x1) + \",\" + (this._y1 = y1);\n }\n\n // Otherwise, draw an arc!\n else {\n var x20 = x2 - x0,\n y20 = y2 - y0,\n l21_2 = x21 * x21 + y21 * y21,\n l20_2 = x20 * x20 + y20 * y20,\n l21 = Math.sqrt(l21_2),\n l01 = Math.sqrt(l01_2),\n l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2),\n t01 = l / l01,\n t21 = l / l21;\n\n // If the start tangent is not coincident with (x0,y0), line to.\n if (Math.abs(t01 - 1) > epsilon) {\n this._ += \"L\" + (x1 + t01 * x01) + \",\" + (y1 + t01 * y01);\n }\n\n this._ += \"A\" + r + \",\" + r + \",0,0,\" + (+(y01 * x20 > x01 * y20)) + \",\" + (this._x1 = x1 + t21 * x21) + \",\" + (this._y1 = y1 + t21 * y21);\n }\n },\n arc: function(x, y, r, a0, a1, ccw) {\n x = +x, y = +y, r = +r, ccw = !!ccw;\n var dx = r * Math.cos(a0),\n dy = r * Math.sin(a0),\n x0 = x + dx,\n y0 = y + dy,\n cw = 1 ^ ccw,\n da = ccw ? a0 - a1 : a1 - a0;\n\n // Is the radius negative? Error.\n if (r < 0) throw new Error(\"negative radius: \" + r);\n\n // Is this path empty? Move to (x0,y0).\n if (this._x1 === null) {\n this._ += \"M\" + x0 + \",\" + y0;\n }\n\n // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0).\n else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) {\n this._ += \"L\" + x0 + \",\" + y0;\n }\n\n // Is this arc empty? We’re done.\n if (!r) return;\n\n // Does the angle go the wrong way? Flip the direction.\n if (da < 0) da = da % tau + tau;\n\n // Is this a complete circle? Draw two arcs to complete the circle.\n if (da > tauEpsilon) {\n this._ += \"A\" + r + \",\" + r + \",0,1,\" + cw + \",\" + (x - dx) + \",\" + (y - dy) + \"A\" + r + \",\" + r + \",0,1,\" + cw + \",\" + (this._x1 = x0) + \",\" + (this._y1 = y0);\n }\n\n // Is this arc non-empty? Draw an arc!\n else if (da > epsilon) {\n this._ += \"A\" + r + \",\" + r + \",0,\" + (+(da >= pi)) + \",\" + cw + \",\" + (this._x1 = x + r * Math.cos(a1)) + \",\" + (this._y1 = y + r * Math.sin(a1));\n }\n },\n rect: function(x, y, w, h) {\n this._ += \"M\" + (this._x0 = this._x1 = +x) + \",\" + (this._y0 = this._y1 = +y) + \"h\" + (+w) + \"v\" + (+h) + \"h\" + (-w) + \"Z\";\n },\n toString: function() {\n return this._;\n }\n};\n\nexport default path;\n","export default function(polygon) {\n var i = -1,\n n = polygon.length,\n a,\n b = polygon[n - 1],\n area = 0;\n\n while (++i < n) {\n a = b;\n b = polygon[i];\n area += a[1] * b[0] - a[0] * b[1];\n }\n\n return area / 2;\n}\n","export default function(polygon) {\n var i = -1,\n n = polygon.length,\n x = 0,\n y = 0,\n a,\n b = polygon[n - 1],\n c,\n k = 0;\n\n while (++i < n) {\n a = b;\n b = polygon[i];\n k += c = a[0] * b[1] - b[0] * a[1];\n x += (a[0] + b[0]) * c;\n y += (a[1] + b[1]) * c;\n }\n\n return k *= 3, [x / k, y / k];\n}\n","export default function(polygon, point) {\n var n = polygon.length,\n p = polygon[n - 1],\n x = point[0], y = point[1],\n x0 = p[0], y0 = p[1],\n x1, y1,\n inside = false;\n\n for (var i = 0; i < n; ++i) {\n p = polygon[i], x1 = p[0], y1 = p[1];\n if (((y1 > y) !== (y0 > y)) && (x < (x0 - x1) * (y - y1) / (y0 - y1) + x1)) inside = !inside;\n x0 = x1, y0 = y1;\n }\n\n return inside;\n}\n","// Returns the 2D cross product of AB and AC vectors, i.e., the z-component of\n// the 3D cross product in a quadrant I Cartesian coordinate system (+x is\n// right, +y is up). Returns a positive value if ABC is counter-clockwise,\n// negative if clockwise, and zero if the points are collinear.\nexport default function(a, b, c) {\n return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);\n}\n","import cross from \"./cross.js\";\n\nfunction lexicographicOrder(a, b) {\n return a[0] - b[0] || a[1] - b[1];\n}\n\n// Computes the upper convex hull per the monotone chain algorithm.\n// Assumes points.length >= 3, is sorted by x, unique in y.\n// Returns an array of indices into points in left-to-right order.\nfunction computeUpperHullIndexes(points) {\n var n = points.length,\n indexes = [0, 1],\n size = 2;\n\n for (var i = 2; i < n; ++i) {\n while (size > 1 && cross(points[indexes[size - 2]], points[indexes[size - 1]], points[i]) <= 0) --size;\n indexes[size++] = i;\n }\n\n return indexes.slice(0, size); // remove popped points\n}\n\nexport default function(points) {\n if ((n = points.length) < 3) return null;\n\n var i,\n n,\n sortedPoints = new Array(n),\n flippedPoints = new Array(n);\n\n for (i = 0; i < n; ++i) sortedPoints[i] = [+points[i][0], +points[i][1], i];\n sortedPoints.sort(lexicographicOrder);\n for (i = 0; i < n; ++i) flippedPoints[i] = [sortedPoints[i][0], -sortedPoints[i][1]];\n\n var upperIndexes = computeUpperHullIndexes(sortedPoints),\n lowerIndexes = computeUpperHullIndexes(flippedPoints);\n\n // Construct the hull polygon, removing possible duplicate endpoints.\n var skipLeft = lowerIndexes[0] === upperIndexes[0],\n skipRight = lowerIndexes[lowerIndexes.length - 1] === upperIndexes[upperIndexes.length - 1],\n hull = [];\n\n // Add upper hull in right-to-l order.\n // Then add lower hull in left-to-right order.\n for (i = upperIndexes.length - 1; i >= 0; --i) hull.push(points[sortedPoints[upperIndexes[i]][2]]);\n for (i = +skipLeft; i < lowerIndexes.length - skipRight; ++i) hull.push(points[sortedPoints[lowerIndexes[i]][2]]);\n\n return hull;\n}\n","export {default as polygonArea} from \"./area.js\";\nexport {default as polygonCentroid} from \"./centroid.js\";\nexport {default as polygonHull} from \"./hull.js\";\nexport {default as polygonContains} from \"./contains.js\";\nexport {default as polygonLength} from \"./length.js\";\n","export default function(polygon) {\n var i = -1,\n n = polygon.length,\n b = polygon[n - 1],\n xa,\n ya,\n xb = b[0],\n yb = b[1],\n perimeter = 0;\n\n while (++i < n) {\n xa = xb;\n ya = yb;\n b = polygon[i];\n xb = b[0];\n yb = b[1];\n xa -= xb;\n ya -= yb;\n perimeter += Math.sqrt(xa * xa + ya * ya);\n }\n\n return perimeter;\n}\n","export default function(d) {\n var x = +this._x.call(null, d),\n y = +this._y.call(null, d);\n return add(this.cover(x, y), x, y, d);\n}\n\nfunction add(tree, x, y, d) {\n if (isNaN(x) || isNaN(y)) return tree; // ignore invalid points\n\n var parent,\n node = tree._root,\n leaf = {data: d},\n x0 = tree._x0,\n y0 = tree._y0,\n x1 = tree._x1,\n y1 = tree._y1,\n xm,\n ym,\n xp,\n yp,\n right,\n bottom,\n i,\n j;\n\n // If the tree is empty, initialize the root as a leaf.\n if (!node) return tree._root = leaf, tree;\n\n // Find the existing leaf for the new point, or add it.\n while (node.length) {\n if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;\n if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;\n if (parent = node, !(node = node[i = bottom << 1 | right])) return parent[i] = leaf, tree;\n }\n\n // Is the new point is exactly coincident with the existing point?\n xp = +tree._x.call(null, node.data);\n yp = +tree._y.call(null, node.data);\n if (x === xp && y === yp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree;\n\n // Otherwise, split the leaf node until the old and new point are separated.\n do {\n parent = parent ? parent[i] = new Array(4) : tree._root = new Array(4);\n if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;\n if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;\n } while ((i = bottom << 1 | right) === (j = (yp >= ym) << 1 | (xp >= xm)));\n return parent[j] = node, parent[i] = leaf, tree;\n}\n\nexport function addAll(data) {\n var d, i, n = data.length,\n x,\n y,\n xz = new Array(n),\n yz = new Array(n),\n x0 = Infinity,\n y0 = Infinity,\n x1 = -Infinity,\n y1 = -Infinity;\n\n // Compute the points and their extent.\n for (i = 0; i < n; ++i) {\n if (isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d))) continue;\n xz[i] = x;\n yz[i] = y;\n if (x < x0) x0 = x;\n if (x > x1) x1 = x;\n if (y < y0) y0 = y;\n if (y > y1) y1 = y;\n }\n\n // If there were no (valid) points, abort.\n if (x0 > x1 || y0 > y1) return this;\n\n // Expand the tree to cover the new points.\n this.cover(x0, y0).cover(x1, y1);\n\n // Add the new points.\n for (i = 0; i < n; ++i) {\n add(this, xz[i], yz[i], data[i]);\n }\n\n return this;\n}\n","export default function(x, y) {\n if (isNaN(x = +x) || isNaN(y = +y)) return this; // ignore invalid points\n\n var x0 = this._x0,\n y0 = this._y0,\n x1 = this._x1,\n y1 = this._y1;\n\n // If the quadtree has no extent, initialize them.\n // Integer extent are necessary so that if we later double the extent,\n // the existing quadrant boundaries don’t change due to floating point error!\n if (isNaN(x0)) {\n x1 = (x0 = Math.floor(x)) + 1;\n y1 = (y0 = Math.floor(y)) + 1;\n }\n\n // Otherwise, double repeatedly to cover.\n else {\n var z = x1 - x0,\n node = this._root,\n parent,\n i;\n\n while (x0 > x || x >= x1 || y0 > y || y >= y1) {\n i = (y < y0) << 1 | (x < x0);\n parent = new Array(4), parent[i] = node, node = parent, z *= 2;\n switch (i) {\n case 0: x1 = x0 + z, y1 = y0 + z; break;\n case 1: x0 = x1 - z, y1 = y0 + z; break;\n case 2: x1 = x0 + z, y0 = y1 - z; break;\n case 3: x0 = x1 - z, y0 = y1 - z; break;\n }\n }\n\n if (this._root && this._root.length) this._root = node;\n }\n\n this._x0 = x0;\n this._y0 = y0;\n this._x1 = x1;\n this._y1 = y1;\n return this;\n}\n","export default function() {\n var data = [];\n this.visit(function(node) {\n if (!node.length) do data.push(node.data); while (node = node.next)\n });\n return data;\n}\n","export default function(_) {\n return arguments.length\n ? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1])\n : isNaN(this._x0) ? undefined : [[this._x0, this._y0], [this._x1, this._y1]];\n}\n","import Quad from \"./quad.js\";\n\nexport default function(x, y, radius) {\n var data,\n x0 = this._x0,\n y0 = this._y0,\n x1,\n y1,\n x2,\n y2,\n x3 = this._x1,\n y3 = this._y1,\n quads = [],\n node = this._root,\n q,\n i;\n\n if (node) quads.push(new Quad(node, x0, y0, x3, y3));\n if (radius == null) radius = Infinity;\n else {\n x0 = x - radius, y0 = y - radius;\n x3 = x + radius, y3 = y + radius;\n radius *= radius;\n }\n\n while (q = quads.pop()) {\n\n // Stop searching if this quadrant can’t contain a closer node.\n if (!(node = q.node)\n || (x1 = q.x0) > x3\n || (y1 = q.y0) > y3\n || (x2 = q.x1) < x0\n || (y2 = q.y1) < y0) continue;\n\n // Bisect the current quadrant.\n if (node.length) {\n var xm = (x1 + x2) / 2,\n ym = (y1 + y2) / 2;\n\n quads.push(\n new Quad(node[3], xm, ym, x2, y2),\n new Quad(node[2], x1, ym, xm, y2),\n new Quad(node[1], xm, y1, x2, ym),\n new Quad(node[0], x1, y1, xm, ym)\n );\n\n // Visit the closest quadrant first.\n if (i = (y >= ym) << 1 | (x >= xm)) {\n q = quads[quads.length - 1];\n quads[quads.length - 1] = quads[quads.length - 1 - i];\n quads[quads.length - 1 - i] = q;\n }\n }\n\n // Visit this point. (Visiting coincident points isn’t necessary!)\n else {\n var dx = x - +this._x.call(null, node.data),\n dy = y - +this._y.call(null, node.data),\n d2 = dx * dx + dy * dy;\n if (d2 < radius) {\n var d = Math.sqrt(radius = d2);\n x0 = x - d, y0 = y - d;\n x3 = x + d, y3 = y + d;\n data = node.data;\n }\n }\n }\n\n return data;\n}\n","export {default as quadtree} from \"./quadtree.js\";\n","export default function(node, x0, y0, x1, y1) {\n this.node = node;\n this.x0 = x0;\n this.y0 = y0;\n this.x1 = x1;\n this.y1 = y1;\n}\n","import tree_add, {addAll as tree_addAll} from \"./add.js\";\nimport tree_cover from \"./cover.js\";\nimport tree_data from \"./data.js\";\nimport tree_extent from \"./extent.js\";\nimport tree_find from \"./find.js\";\nimport tree_remove, {removeAll as tree_removeAll} from \"./remove.js\";\nimport tree_root from \"./root.js\";\nimport tree_size from \"./size.js\";\nimport tree_visit from \"./visit.js\";\nimport tree_visitAfter from \"./visitAfter.js\";\nimport tree_x, {defaultX} from \"./x.js\";\nimport tree_y, {defaultY} from \"./y.js\";\n\nexport default function quadtree(nodes, x, y) {\n var tree = new Quadtree(x == null ? defaultX : x, y == null ? defaultY : y, NaN, NaN, NaN, NaN);\n return nodes == null ? tree : tree.addAll(nodes);\n}\n\nfunction Quadtree(x, y, x0, y0, x1, y1) {\n this._x = x;\n this._y = y;\n this._x0 = x0;\n this._y0 = y0;\n this._x1 = x1;\n this._y1 = y1;\n this._root = undefined;\n}\n\nfunction leaf_copy(leaf) {\n var copy = {data: leaf.data}, next = copy;\n while (leaf = leaf.next) next = next.next = {data: leaf.data};\n return copy;\n}\n\nvar treeProto = quadtree.prototype = Quadtree.prototype;\n\ntreeProto.copy = function() {\n var copy = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1),\n node = this._root,\n nodes,\n child;\n\n if (!node) return copy;\n\n if (!node.length) return copy._root = leaf_copy(node), copy;\n\n nodes = [{source: node, target: copy._root = new Array(4)}];\n while (node = nodes.pop()) {\n for (var i = 0; i < 4; ++i) {\n if (child = node.source[i]) {\n if (child.length) nodes.push({source: child, target: node.target[i] = new Array(4)});\n else node.target[i] = leaf_copy(child);\n }\n }\n }\n\n return copy;\n};\n\ntreeProto.add = tree_add;\ntreeProto.addAll = tree_addAll;\ntreeProto.cover = tree_cover;\ntreeProto.data = tree_data;\ntreeProto.extent = tree_extent;\ntreeProto.find = tree_find;\ntreeProto.remove = tree_remove;\ntreeProto.removeAll = tree_removeAll;\ntreeProto.root = tree_root;\ntreeProto.size = tree_size;\ntreeProto.visit = tree_visit;\ntreeProto.visitAfter = tree_visitAfter;\ntreeProto.x = tree_x;\ntreeProto.y = tree_y;\n","export default function(d) {\n if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) return this; // ignore invalid points\n\n var parent,\n node = this._root,\n retainer,\n previous,\n next,\n x0 = this._x0,\n y0 = this._y0,\n x1 = this._x1,\n y1 = this._y1,\n x,\n y,\n xm,\n ym,\n right,\n bottom,\n i,\n j;\n\n // If the tree is empty, initialize the root as a leaf.\n if (!node) return this;\n\n // Find the leaf node for the point.\n // While descending, also retain the deepest parent with a non-removed sibling.\n if (node.length) while (true) {\n if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm;\n if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym;\n if (!(parent = node, node = node[i = bottom << 1 | right])) return this;\n if (!node.length) break;\n if (parent[(i + 1) & 3] || parent[(i + 2) & 3] || parent[(i + 3) & 3]) retainer = parent, j = i;\n }\n\n // Find the point to remove.\n while (node.data !== d) if (!(previous = node, node = node.next)) return this;\n if (next = node.next) delete node.next;\n\n // If there are multiple coincident points, remove just the point.\n if (previous) return (next ? previous.next = next : delete previous.next), this;\n\n // If this is the root point, remove it.\n if (!parent) return this._root = next, this;\n\n // Remove this leaf.\n next ? parent[i] = next : delete parent[i];\n\n // If the parent now contains exactly one leaf, collapse superfluous parents.\n if ((node = parent[0] || parent[1] || parent[2] || parent[3])\n && node === (parent[3] || parent[2] || parent[1] || parent[0])\n && !node.length) {\n if (retainer) retainer[j] = node;\n else this._root = node;\n }\n\n return this;\n}\n\nexport function removeAll(data) {\n for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]);\n return this;\n}\n","export default function() {\n return this._root;\n}\n","export default function() {\n var size = 0;\n this.visit(function(node) {\n if (!node.length) do ++size; while (node = node.next)\n });\n return size;\n}\n","import Quad from \"./quad.js\";\n\nexport default function(callback) {\n var quads = [], q, node = this._root, child, x0, y0, x1, y1;\n if (node) quads.push(new Quad(node, this._x0, this._y0, this._x1, this._y1));\n while (q = quads.pop()) {\n if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) {\n var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;\n if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1));\n if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1));\n if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym));\n if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym));\n }\n }\n return this;\n}\n","import Quad from \"./quad.js\";\n\nexport default function(callback) {\n var quads = [], next = [], q;\n if (this._root) quads.push(new Quad(this._root, this._x0, this._y0, this._x1, this._y1));\n while (q = quads.pop()) {\n var node = q.node;\n if (node.length) {\n var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2;\n if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym));\n if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym));\n if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1));\n if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1));\n }\n next.push(q);\n }\n while (q = next.pop()) {\n callback(q.node, q.x0, q.y0, q.x1, q.y1);\n }\n return this;\n}\n","export function defaultX(d) {\n return d[0];\n}\n\nexport default function(_) {\n return arguments.length ? (this._x = _, this) : this._x;\n}\n","export function defaultY(d) {\n return d[1];\n}\n\nexport default function(_) {\n return arguments.length ? (this._y = _, this) : this._y;\n}\n","import defaultSource from \"./defaultSource\";\nimport irwinHall from \"./irwinHall\";\n\nexport default (function sourceRandomBates(source) {\n function randomBates(n) {\n var randomIrwinHall = irwinHall.source(source)(n);\n return function() {\n return randomIrwinHall() / n;\n };\n }\n\n randomBates.source = sourceRandomBates;\n\n return randomBates;\n})(defaultSource);\n","export default function() {\n return Math.random();\n}\n","import defaultSource from \"./defaultSource\";\n\nexport default (function sourceRandomExponential(source) {\n function randomExponential(lambda) {\n return function() {\n return -Math.log(1 - source()) / lambda;\n };\n }\n\n randomExponential.source = sourceRandomExponential;\n\n return randomExponential;\n})(defaultSource);\n","export {default as randomUniform} from \"./uniform\";\nexport {default as randomNormal} from \"./normal\";\nexport {default as randomLogNormal} from \"./logNormal\";\nexport {default as randomBates} from \"./bates\";\nexport {default as randomIrwinHall} from \"./irwinHall\";\nexport {default as randomExponential} from \"./exponential\";\n","import defaultSource from \"./defaultSource\";\n\nexport default (function sourceRandomIrwinHall(source) {\n function randomIrwinHall(n) {\n return function() {\n for (var sum = 0, i = 0; i < n; ++i) sum += source();\n return sum;\n };\n }\n\n randomIrwinHall.source = sourceRandomIrwinHall;\n\n return randomIrwinHall;\n})(defaultSource);\n","import defaultSource from \"./defaultSource\";\nimport normal from \"./normal\";\n\nexport default (function sourceRandomLogNormal(source) {\n function randomLogNormal() {\n var randomNormal = normal.source(source).apply(this, arguments);\n return function() {\n return Math.exp(randomNormal());\n };\n }\n\n randomLogNormal.source = sourceRandomLogNormal;\n\n return randomLogNormal;\n})(defaultSource);\n","import defaultSource from \"./defaultSource\";\n\nexport default (function sourceRandomNormal(source) {\n function randomNormal(mu, sigma) {\n var x, r;\n mu = mu == null ? 0 : +mu;\n sigma = sigma == null ? 1 : +sigma;\n return function() {\n var y;\n\n // If available, use the second previously-generated uniform random.\n if (x != null) y = x, x = null;\n\n // Otherwise, generate a new x and y.\n else do {\n x = source() * 2 - 1;\n y = source() * 2 - 1;\n r = x * x + y * y;\n } while (!r || r > 1);\n\n return mu + sigma * y * Math.sqrt(-2 * Math.log(r) / r);\n };\n }\n\n randomNormal.source = sourceRandomNormal;\n\n return randomNormal;\n})(defaultSource);\n","import defaultSource from \"./defaultSource\";\n\nexport default (function sourceRandomUniform(source) {\n function randomUniform(min, max) {\n min = min == null ? 0 : +min;\n max = max == null ? 1 : +max;\n if (arguments.length === 1) max = min, min = 0;\n else max -= min;\n return function() {\n return source() * max + min;\n };\n }\n\n randomUniform.source = sourceRandomUniform;\n\n return randomUniform;\n})(defaultSource);\n","import colors from \"../colors.js\";\n\nexport default colors(\"7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666\");\n","import colors from \"../colors.js\";\n\nexport default colors(\"1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666\");\n","import colors from \"../colors.js\";\n\nexport default colors(\"a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928\");\n","import colors from \"../colors.js\";\n\nexport default colors(\"fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2\");\n","import colors from \"../colors.js\";\n\nexport default colors(\"b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc\");\n","import colors from \"../colors.js\";\n\nexport default colors(\"e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999\");\n","import colors from \"../colors.js\";\n\nexport default colors(\"66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3\");\n","import colors from \"../colors.js\";\n\nexport default colors(\"8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f\");\n","import colors from \"../colors.js\";\n\nexport default colors(\"4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab\");\n","import colors from \"../colors.js\";\n\nexport default colors(\"1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf\");\n","export default function(specifier) {\n var n = specifier.length / 6 | 0, colors = new Array(n), i = 0;\n while (i < n) colors[i] = \"#\" + specifier.slice(i * 6, ++i * 6);\n return colors;\n}\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"d8b365f5f5f55ab4ac\",\n \"a6611adfc27d80cdc1018571\",\n \"a6611adfc27df5f5f580cdc1018571\",\n \"8c510ad8b365f6e8c3c7eae55ab4ac01665e\",\n \"8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e\",\n \"8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e\",\n \"8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e\",\n \"5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30\",\n \"5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"af8dc3f7f7f77fbf7b\",\n \"7b3294c2a5cfa6dba0008837\",\n \"7b3294c2a5cff7f7f7a6dba0008837\",\n \"762a83af8dc3e7d4e8d9f0d37fbf7b1b7837\",\n \"762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837\",\n \"762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837\",\n \"762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837\",\n \"40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b\",\n \"40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e9a3c9f7f7f7a1d76a\",\n \"d01c8bf1b6dab8e1864dac26\",\n \"d01c8bf1b6daf7f7f7b8e1864dac26\",\n \"c51b7de9a3c9fde0efe6f5d0a1d76a4d9221\",\n \"c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221\",\n \"c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221\",\n \"c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221\",\n \"8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419\",\n \"8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"998ec3f7f7f7f1a340\",\n \"5e3c99b2abd2fdb863e66101\",\n \"5e3c99b2abd2f7f7f7fdb863e66101\",\n \"542788998ec3d8daebfee0b6f1a340b35806\",\n \"542788998ec3d8daebf7f7f7fee0b6f1a340b35806\",\n \"5427888073acb2abd2d8daebfee0b6fdb863e08214b35806\",\n \"5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806\",\n \"2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08\",\n \"2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"ef8a62f7f7f767a9cf\",\n \"ca0020f4a58292c5de0571b0\",\n \"ca0020f4a582f7f7f792c5de0571b0\",\n \"b2182bef8a62fddbc7d1e5f067a9cf2166ac\",\n \"b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac\",\n \"b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac\",\n \"b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac\",\n \"67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061\",\n \"67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"ef8a62ffffff999999\",\n \"ca0020f4a582bababa404040\",\n \"ca0020f4a582ffffffbababa404040\",\n \"b2182bef8a62fddbc7e0e0e09999994d4d4d\",\n \"b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d\",\n \"b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d\",\n \"b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d\",\n \"67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a\",\n \"67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fc8d59ffffbf91bfdb\",\n \"d7191cfdae61abd9e92c7bb6\",\n \"d7191cfdae61ffffbfabd9e92c7bb6\",\n \"d73027fc8d59fee090e0f3f891bfdb4575b4\",\n \"d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4\",\n \"d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4\",\n \"d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4\",\n \"a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695\",\n \"a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fc8d59ffffbf91cf60\",\n \"d7191cfdae61a6d96a1a9641\",\n \"d7191cfdae61ffffbfa6d96a1a9641\",\n \"d73027fc8d59fee08bd9ef8b91cf601a9850\",\n \"d73027fc8d59fee08bffffbfd9ef8b91cf601a9850\",\n \"d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850\",\n \"d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850\",\n \"a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837\",\n \"a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fc8d59ffffbf99d594\",\n \"d7191cfdae61abdda42b83ba\",\n \"d7191cfdae61ffffbfabdda42b83ba\",\n \"d53e4ffc8d59fee08be6f59899d5943288bd\",\n \"d53e4ffc8d59fee08bffffbfe6f59899d5943288bd\",\n \"d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd\",\n \"d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd\",\n \"9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2\",\n \"9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2\"\n).map(colors);\n\nexport default ramp(scheme);\n","export {default as schemeCategory10} from \"./categorical/category10.js\";\nexport {default as schemeAccent} from \"./categorical/Accent.js\";\nexport {default as schemeDark2} from \"./categorical/Dark2.js\";\nexport {default as schemePaired} from \"./categorical/Paired.js\";\nexport {default as schemePastel1} from \"./categorical/Pastel1.js\";\nexport {default as schemePastel2} from \"./categorical/Pastel2.js\";\nexport {default as schemeSet1} from \"./categorical/Set1.js\";\nexport {default as schemeSet2} from \"./categorical/Set2.js\";\nexport {default as schemeSet3} from \"./categorical/Set3.js\";\nexport {default as schemeTableau10} from \"./categorical/Tableau10.js\";\nexport {default as interpolateBrBG, scheme as schemeBrBG} from \"./diverging/BrBG.js\";\nexport {default as interpolatePRGn, scheme as schemePRGn} from \"./diverging/PRGn.js\";\nexport {default as interpolatePiYG, scheme as schemePiYG} from \"./diverging/PiYG.js\";\nexport {default as interpolatePuOr, scheme as schemePuOr} from \"./diverging/PuOr.js\";\nexport {default as interpolateRdBu, scheme as schemeRdBu} from \"./diverging/RdBu.js\";\nexport {default as interpolateRdGy, scheme as schemeRdGy} from \"./diverging/RdGy.js\";\nexport {default as interpolateRdYlBu, scheme as schemeRdYlBu} from \"./diverging/RdYlBu.js\";\nexport {default as interpolateRdYlGn, scheme as schemeRdYlGn} from \"./diverging/RdYlGn.js\";\nexport {default as interpolateSpectral, scheme as schemeSpectral} from \"./diverging/Spectral.js\";\nexport {default as interpolateBuGn, scheme as schemeBuGn} from \"./sequential-multi/BuGn.js\";\nexport {default as interpolateBuPu, scheme as schemeBuPu} from \"./sequential-multi/BuPu.js\";\nexport {default as interpolateGnBu, scheme as schemeGnBu} from \"./sequential-multi/GnBu.js\";\nexport {default as interpolateOrRd, scheme as schemeOrRd} from \"./sequential-multi/OrRd.js\";\nexport {default as interpolatePuBuGn, scheme as schemePuBuGn} from \"./sequential-multi/PuBuGn.js\";\nexport {default as interpolatePuBu, scheme as schemePuBu} from \"./sequential-multi/PuBu.js\";\nexport {default as interpolatePuRd, scheme as schemePuRd} from \"./sequential-multi/PuRd.js\";\nexport {default as interpolateRdPu, scheme as schemeRdPu} from \"./sequential-multi/RdPu.js\";\nexport {default as interpolateYlGnBu, scheme as schemeYlGnBu} from \"./sequential-multi/YlGnBu.js\";\nexport {default as interpolateYlGn, scheme as schemeYlGn} from \"./sequential-multi/YlGn.js\";\nexport {default as interpolateYlOrBr, scheme as schemeYlOrBr} from \"./sequential-multi/YlOrBr.js\";\nexport {default as interpolateYlOrRd, scheme as schemeYlOrRd} from \"./sequential-multi/YlOrRd.js\";\nexport {default as interpolateBlues, scheme as schemeBlues} from \"./sequential-single/Blues.js\";\nexport {default as interpolateGreens, scheme as schemeGreens} from \"./sequential-single/Greens.js\";\nexport {default as interpolateGreys, scheme as schemeGreys} from \"./sequential-single/Greys.js\";\nexport {default as interpolatePurples, scheme as schemePurples} from \"./sequential-single/Purples.js\";\nexport {default as interpolateReds, scheme as schemeReds} from \"./sequential-single/Reds.js\";\nexport {default as interpolateOranges, scheme as schemeOranges} from \"./sequential-single/Oranges.js\";\nexport {default as interpolateCividis} from \"./sequential-multi/cividis.js\";\nexport {default as interpolateCubehelixDefault} from \"./sequential-multi/cubehelix.js\";\nexport {default as interpolateRainbow, warm as interpolateWarm, cool as interpolateCool} from \"./sequential-multi/rainbow.js\";\nexport {default as interpolateSinebow} from \"./sequential-multi/sinebow.js\";\nexport {default as interpolateTurbo} from \"./sequential-multi/turbo.js\";\nexport {default as interpolateViridis, magma as interpolateMagma, inferno as interpolateInferno, plasma as interpolatePlasma} from \"./sequential-multi/viridis.js\";\n","import {interpolateRgbBasis} from \"d3-interpolate\";\n\nexport default function(scheme) {\n return interpolateRgbBasis(scheme[scheme.length - 1]);\n}\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e5f5f999d8c92ca25f\",\n \"edf8fbb2e2e266c2a4238b45\",\n \"edf8fbb2e2e266c2a42ca25f006d2c\",\n \"edf8fbccece699d8c966c2a42ca25f006d2c\",\n \"edf8fbccece699d8c966c2a441ae76238b45005824\",\n \"f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824\",\n \"f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e0ecf49ebcda8856a7\",\n \"edf8fbb3cde38c96c688419d\",\n \"edf8fbb3cde38c96c68856a7810f7c\",\n \"edf8fbbfd3e69ebcda8c96c68856a7810f7c\",\n \"edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b\",\n \"f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b\",\n \"f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e0f3dba8ddb543a2ca\",\n \"f0f9e8bae4bc7bccc42b8cbe\",\n \"f0f9e8bae4bc7bccc443a2ca0868ac\",\n \"f0f9e8ccebc5a8ddb57bccc443a2ca0868ac\",\n \"f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e\",\n \"f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e\",\n \"f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fee8c8fdbb84e34a33\",\n \"fef0d9fdcc8afc8d59d7301f\",\n \"fef0d9fdcc8afc8d59e34a33b30000\",\n \"fef0d9fdd49efdbb84fc8d59e34a33b30000\",\n \"fef0d9fdd49efdbb84fc8d59ef6548d7301f990000\",\n \"fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000\",\n \"fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"ece7f2a6bddb2b8cbe\",\n \"f1eef6bdc9e174a9cf0570b0\",\n \"f1eef6bdc9e174a9cf2b8cbe045a8d\",\n \"f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d\",\n \"f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b\",\n \"fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b\",\n \"fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"ece2f0a6bddb1c9099\",\n \"f6eff7bdc9e167a9cf02818a\",\n \"f6eff7bdc9e167a9cf1c9099016c59\",\n \"f6eff7d0d1e6a6bddb67a9cf1c9099016c59\",\n \"f6eff7d0d1e6a6bddb67a9cf3690c002818a016450\",\n \"fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450\",\n \"fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e7e1efc994c7dd1c77\",\n \"f1eef6d7b5d8df65b0ce1256\",\n \"f1eef6d7b5d8df65b0dd1c77980043\",\n \"f1eef6d4b9dac994c7df65b0dd1c77980043\",\n \"f1eef6d4b9dac994c7df65b0e7298ace125691003f\",\n \"f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f\",\n \"f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fde0ddfa9fb5c51b8a\",\n \"feebe2fbb4b9f768a1ae017e\",\n \"feebe2fbb4b9f768a1c51b8a7a0177\",\n \"feebe2fcc5c0fa9fb5f768a1c51b8a7a0177\",\n \"feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177\",\n \"fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177\",\n \"fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"f7fcb9addd8e31a354\",\n \"ffffccc2e69978c679238443\",\n \"ffffccc2e69978c67931a354006837\",\n \"ffffccd9f0a3addd8e78c67931a354006837\",\n \"ffffccd9f0a3addd8e78c67941ab5d238443005a32\",\n \"ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32\",\n \"ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"edf8b17fcdbb2c7fb8\",\n \"ffffcca1dab441b6c4225ea8\",\n \"ffffcca1dab441b6c42c7fb8253494\",\n \"ffffccc7e9b47fcdbb41b6c42c7fb8253494\",\n \"ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84\",\n \"ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84\",\n \"ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fff7bcfec44fd95f0e\",\n \"ffffd4fed98efe9929cc4c02\",\n \"ffffd4fed98efe9929d95f0e993404\",\n \"ffffd4fee391fec44ffe9929d95f0e993404\",\n \"ffffd4fee391fec44ffe9929ec7014cc4c028c2d04\",\n \"ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04\",\n \"ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"ffeda0feb24cf03b20\",\n \"ffffb2fecc5cfd8d3ce31a1c\",\n \"ffffb2fecc5cfd8d3cf03b20bd0026\",\n \"ffffb2fed976feb24cfd8d3cf03b20bd0026\",\n \"ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026\",\n \"ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026\",\n \"ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026\"\n).map(colors);\n\nexport default ramp(scheme);\n","export default function(t) {\n t = Math.max(0, Math.min(1, t));\n return \"rgb(\"\n + Math.max(0, Math.min(255, Math.round(-4.54 - t * (35.34 - t * (2381.73 - t * (6402.7 - t * (7024.72 - t * 2710.57))))))) + \", \"\n + Math.max(0, Math.min(255, Math.round(32.49 + t * (170.73 + t * (52.82 - t * (131.46 - t * (176.58 - t * 67.37))))))) + \", \"\n + Math.max(0, Math.min(255, Math.round(81.24 + t * (442.36 - t * (2482.43 - t * (6167.24 - t * (6614.94 - t * 2475.67)))))))\n + \")\";\n}\n","import {cubehelix} from \"d3-color\";\nimport {interpolateCubehelixLong} from \"d3-interpolate\";\n\nexport default interpolateCubehelixLong(cubehelix(300, 0.5, 0.0), cubehelix(-240, 0.5, 1.0));\n","import {cubehelix} from \"d3-color\";\nimport {interpolateCubehelixLong} from \"d3-interpolate\";\n\nexport var warm = interpolateCubehelixLong(cubehelix(-100, 0.75, 0.35), cubehelix(80, 1.50, 0.8));\n\nexport var cool = interpolateCubehelixLong(cubehelix(260, 0.75, 0.35), cubehelix(80, 1.50, 0.8));\n\nvar c = cubehelix();\n\nexport default function(t) {\n if (t < 0 || t > 1) t -= Math.floor(t);\n var ts = Math.abs(t - 0.5);\n c.h = 360 * t - 100;\n c.s = 1.5 - 1.5 * ts;\n c.l = 0.8 - 0.9 * ts;\n return c + \"\";\n}\n","import {rgb} from \"d3-color\";\n\nvar c = rgb(),\n pi_1_3 = Math.PI / 3,\n pi_2_3 = Math.PI * 2 / 3;\n\nexport default function(t) {\n var x;\n t = (0.5 - t) * Math.PI;\n c.r = 255 * (x = Math.sin(t)) * x;\n c.g = 255 * (x = Math.sin(t + pi_1_3)) * x;\n c.b = 255 * (x = Math.sin(t + pi_2_3)) * x;\n return c + \"\";\n}\n","export default function(t) {\n t = Math.max(0, Math.min(1, t));\n return \"rgb(\"\n + Math.max(0, Math.min(255, Math.round(34.61 + t * (1172.33 - t * (10793.56 - t * (33300.12 - t * (38394.49 - t * 14825.05))))))) + \", \"\n + Math.max(0, Math.min(255, Math.round(23.31 + t * (557.33 + t * (1225.33 - t * (3574.96 - t * (1073.77 + t * 707.56))))))) + \", \"\n + Math.max(0, Math.min(255, Math.round(27.2 + t * (3211.1 - t * (15327.97 - t * (27814 - t * (22569.18 - t * 6838.66)))))))\n + \")\";\n}\n","import colors from \"../colors.js\";\n\nfunction ramp(range) {\n var n = range.length;\n return function(t) {\n return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))];\n };\n}\n\nexport default ramp(colors(\"44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725\"));\n\nexport var magma = ramp(colors(\"00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf\"));\n\nexport var inferno = ramp(colors(\"00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4\"));\n\nexport var plasma = ramp(colors(\"0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921\"));\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"deebf79ecae13182bd\",\n \"eff3ffbdd7e76baed62171b5\",\n \"eff3ffbdd7e76baed63182bd08519c\",\n \"eff3ffc6dbef9ecae16baed63182bd08519c\",\n \"eff3ffc6dbef9ecae16baed64292c62171b5084594\",\n \"f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594\",\n \"f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"e5f5e0a1d99b31a354\",\n \"edf8e9bae4b374c476238b45\",\n \"edf8e9bae4b374c47631a354006d2c\",\n \"edf8e9c7e9c0a1d99b74c47631a354006d2c\",\n \"edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32\",\n \"f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32\",\n \"f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"f0f0f0bdbdbd636363\",\n \"f7f7f7cccccc969696525252\",\n \"f7f7f7cccccc969696636363252525\",\n \"f7f7f7d9d9d9bdbdbd969696636363252525\",\n \"f7f7f7d9d9d9bdbdbd969696737373525252252525\",\n \"fffffff0f0f0d9d9d9bdbdbd969696737373525252252525\",\n \"fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fee6cefdae6be6550d\",\n \"feeddefdbe85fd8d3cd94701\",\n \"feeddefdbe85fd8d3ce6550da63603\",\n \"feeddefdd0a2fdae6bfd8d3ce6550da63603\",\n \"feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04\",\n \"fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04\",\n \"fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"efedf5bcbddc756bb1\",\n \"f2f0f7cbc9e29e9ac86a51a3\",\n \"f2f0f7cbc9e29e9ac8756bb154278f\",\n \"f2f0f7dadaebbcbddc9e9ac8756bb154278f\",\n \"f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486\",\n \"fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486\",\n \"fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d\"\n).map(colors);\n\nexport default ramp(scheme);\n","import colors from \"../colors.js\";\nimport ramp from \"../ramp.js\";\n\nexport var scheme = new Array(3).concat(\n \"fee0d2fc9272de2d26\",\n \"fee5d9fcae91fb6a4acb181d\",\n \"fee5d9fcae91fb6a4ade2d26a50f15\",\n \"fee5d9fcbba1fc9272fb6a4ade2d26a50f15\",\n \"fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d\",\n \"fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d\",\n \"fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d\"\n).map(colors);\n\nexport default ramp(scheme);\n","var array = Array.prototype;\n\nexport var slice = array.slice;\nexport var map = array.map;\n","export default function(a, b) {\n return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n","import ascending from \"./ascending\";\nimport bisector from \"./bisector\";\n\nvar ascendingBisect = bisector(ascending);\nexport var bisectRight = ascendingBisect.right;\nexport var bisectLeft = ascendingBisect.left;\nexport default bisectRight;\n","import ascending from \"./ascending\";\n\nexport default function(compare) {\n if (compare.length === 1) compare = ascendingComparator(compare);\n return {\n left: function(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n var mid = lo + hi >>> 1;\n if (compare(a[mid], x) < 0) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n },\n right: function(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n var mid = lo + hi >>> 1;\n if (compare(a[mid], x) > 0) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n }\n };\n}\n\nfunction ascendingComparator(f) {\n return function(d, x) {\n return ascending(f(d), x);\n };\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","import {pair} from \"./pairs\";\n\nexport default function(values0, values1, reduce) {\n var n0 = values0.length,\n n1 = values1.length,\n values = new Array(n0 * n1),\n i0,\n i1,\n i,\n value0;\n\n if (reduce == null) reduce = pair;\n\n for (i0 = i = 0; i0 < n0; ++i0) {\n for (value0 = values0[i0], i1 = 0; i1 < n1; ++i1, ++i) {\n values[i] = reduce(value0, values1[i1]);\n }\n }\n\n return values;\n}\n","export default function(a, b) {\n return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;\n}\n","import variance from \"./variance\";\n\nexport default function(array, f) {\n var v = variance(array, f);\n return v ? Math.sqrt(v) : v;\n}\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n min,\n max;\n\n if (valueof == null) {\n while (++i < n) { // Find the first comparable value.\n if ((value = values[i]) != null && value >= value) {\n min = max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = values[i]) != null) {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n }\n }\n\n else {\n while (++i < n) { // Find the first comparable value.\n if ((value = valueof(values[i], i, values)) != null && value >= value) {\n min = max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = valueof(values[i], i, values)) != null) {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n }\n }\n\n return [min, max];\n}\n","import {slice} from \"./array\";\nimport bisect from \"./bisect\";\nimport constant from \"./constant\";\nimport extent from \"./extent\";\nimport identity from \"./identity\";\nimport range from \"./range\";\nimport {tickStep} from \"./ticks\";\nimport sturges from \"./threshold/sturges\";\n\nexport default function() {\n var value = identity,\n domain = extent,\n threshold = sturges;\n\n function histogram(data) {\n var i,\n n = data.length,\n x,\n values = new Array(n);\n\n for (i = 0; i < n; ++i) {\n values[i] = value(data[i], i, data);\n }\n\n var xz = domain(values),\n x0 = xz[0],\n x1 = xz[1],\n tz = threshold(values, x0, x1);\n\n // Convert number of thresholds into uniform thresholds.\n if (!Array.isArray(tz)) {\n tz = tickStep(x0, x1, tz);\n tz = range(Math.ceil(x0 / tz) * tz, x1, tz); // exclusive\n }\n\n // Remove any thresholds outside the domain.\n var m = tz.length;\n while (tz[0] <= x0) tz.shift(), --m;\n while (tz[m - 1] > x1) tz.pop(), --m;\n\n var bins = new Array(m + 1),\n bin;\n\n // Initialize bins.\n for (i = 0; i <= m; ++i) {\n bin = bins[i] = [];\n bin.x0 = i > 0 ? tz[i - 1] : x0;\n bin.x1 = i < m ? tz[i] : x1;\n }\n\n // Assign data to bins by value, ignoring any outside the domain.\n for (i = 0; i < n; ++i) {\n x = values[i];\n if (x0 <= x && x <= x1) {\n bins[bisect(tz, x, 0, m)].push(data[i]);\n }\n }\n\n return bins;\n }\n\n histogram.value = function(_) {\n return arguments.length ? (value = typeof _ === \"function\" ? _ : constant(_), histogram) : value;\n };\n\n histogram.domain = function(_) {\n return arguments.length ? (domain = typeof _ === \"function\" ? _ : constant([_[0], _[1]]), histogram) : domain;\n };\n\n histogram.thresholds = function(_) {\n return arguments.length ? (threshold = typeof _ === \"function\" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), histogram) : threshold;\n };\n\n return histogram;\n}\n","export default function(x) {\n return x;\n}\n","export {default as bisect, bisectRight, bisectLeft} from \"./bisect\";\nexport {default as ascending} from \"./ascending\";\nexport {default as bisector} from \"./bisector\";\nexport {default as cross} from \"./cross\";\nexport {default as descending} from \"./descending\";\nexport {default as deviation} from \"./deviation\";\nexport {default as extent} from \"./extent\";\nexport {default as histogram} from \"./histogram\";\nexport {default as thresholdFreedmanDiaconis} from \"./threshold/freedmanDiaconis\";\nexport {default as thresholdScott} from \"./threshold/scott\";\nexport {default as thresholdSturges} from \"./threshold/sturges\";\nexport {default as max} from \"./max\";\nexport {default as mean} from \"./mean\";\nexport {default as median} from \"./median\";\nexport {default as merge} from \"./merge\";\nexport {default as min} from \"./min\";\nexport {default as pairs} from \"./pairs\";\nexport {default as permute} from \"./permute\";\nexport {default as quantile} from \"./quantile\";\nexport {default as range} from \"./range\";\nexport {default as scan} from \"./scan\";\nexport {default as shuffle} from \"./shuffle\";\nexport {default as sum} from \"./sum\";\nexport {default as ticks, tickIncrement, tickStep} from \"./ticks\";\nexport {default as transpose} from \"./transpose\";\nexport {default as variance} from \"./variance\";\nexport {default as zip} from \"./zip\";\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n max;\n\n if (valueof == null) {\n while (++i < n) { // Find the first comparable value.\n if ((value = values[i]) != null && value >= value) {\n max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = values[i]) != null && value > max) {\n max = value;\n }\n }\n }\n }\n }\n\n else {\n while (++i < n) { // Find the first comparable value.\n if ((value = valueof(values[i], i, values)) != null && value >= value) {\n max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = valueof(values[i], i, values)) != null && value > max) {\n max = value;\n }\n }\n }\n }\n }\n\n return max;\n}\n","import number from \"./number\";\n\nexport default function(values, valueof) {\n var n = values.length,\n m = n,\n i = -1,\n value,\n sum = 0;\n\n if (valueof == null) {\n while (++i < n) {\n if (!isNaN(value = number(values[i]))) sum += value;\n else --m;\n }\n }\n\n else {\n while (++i < n) {\n if (!isNaN(value = number(valueof(values[i], i, values)))) sum += value;\n else --m;\n }\n }\n\n if (m) return sum / m;\n}\n","import ascending from \"./ascending\";\nimport number from \"./number\";\nimport quantile from \"./quantile\";\n\nexport default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n numbers = [];\n\n if (valueof == null) {\n while (++i < n) {\n if (!isNaN(value = number(values[i]))) {\n numbers.push(value);\n }\n }\n }\n\n else {\n while (++i < n) {\n if (!isNaN(value = number(valueof(values[i], i, values)))) {\n numbers.push(value);\n }\n }\n }\n\n return quantile(numbers.sort(ascending), 0.5);\n}\n","export default function(arrays) {\n var n = arrays.length,\n m,\n i = -1,\n j = 0,\n merged,\n array;\n\n while (++i < n) j += arrays[i].length;\n merged = new Array(j);\n\n while (--n >= 0) {\n array = arrays[n];\n m = array.length;\n while (--m >= 0) {\n merged[--j] = array[m];\n }\n }\n\n return merged;\n}\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n min;\n\n if (valueof == null) {\n while (++i < n) { // Find the first comparable value.\n if ((value = values[i]) != null && value >= value) {\n min = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = values[i]) != null && min > value) {\n min = value;\n }\n }\n }\n }\n }\n\n else {\n while (++i < n) { // Find the first comparable value.\n if ((value = valueof(values[i], i, values)) != null && value >= value) {\n min = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = valueof(values[i], i, values)) != null && min > value) {\n min = value;\n }\n }\n }\n }\n }\n\n return min;\n}\n","export default function(x) {\n return x === null ? NaN : +x;\n}\n","export default function(array, f) {\n if (f == null) f = pair;\n var i = 0, n = array.length - 1, p = array[0], pairs = new Array(n < 0 ? 0 : n);\n while (i < n) pairs[i] = f(p, p = array[++i]);\n return pairs;\n}\n\nexport function pair(a, b) {\n return [a, b];\n}\n","export default function(array, indexes) {\n var i = indexes.length, permutes = new Array(i);\n while (i--) permutes[i] = array[indexes[i]];\n return permutes;\n}\n","import number from \"./number\";\n\nexport default function(values, p, valueof) {\n if (valueof == null) valueof = number;\n if (!(n = values.length)) return;\n if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);\n if (p >= 1) return +valueof(values[n - 1], n - 1, values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = +valueof(values[i0], i0, values),\n value1 = +valueof(values[i0 + 1], i0 + 1, values);\n return value0 + (value1 - value0) * (i - i0);\n}\n","export default function(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n","import ascending from \"./ascending\";\n\nexport default function(values, compare) {\n if (!(n = values.length)) return;\n var n,\n i = 0,\n j = 0,\n xi,\n xj = values[j];\n\n if (compare == null) compare = ascending;\n\n while (++i < n) {\n if (compare(xi = values[i], xj) < 0 || compare(xj, xj) !== 0) {\n xj = xi, j = i;\n }\n }\n\n if (compare(xj, xj) === 0) return j;\n}\n","export default function(array, i0, i1) {\n var m = (i1 == null ? array.length : i1) - (i0 = i0 == null ? 0 : +i0),\n t,\n i;\n\n while (m) {\n i = Math.random() * m-- | 0;\n t = array[m + i0];\n array[m + i0] = array[i + i0];\n array[i + i0] = t;\n }\n\n return array;\n}\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n sum = 0;\n\n if (valueof == null) {\n while (++i < n) {\n if (value = +values[i]) sum += value; // Note: zero and null are equivalent.\n }\n }\n\n else {\n while (++i < n) {\n if (value = +valueof(values[i], i, values)) sum += value;\n }\n }\n\n return sum;\n}\n","import {map} from \"../array\";\nimport ascending from \"../ascending\";\nimport number from \"../number\";\nimport quantile from \"../quantile\";\n\nexport default function(values, min, max) {\n values = map.call(values, number).sort(ascending);\n return Math.ceil((max - min) / (2 * (quantile(values, 0.75) - quantile(values, 0.25)) * Math.pow(values.length, -1 / 3)));\n}\n","import deviation from \"../deviation\";\n\nexport default function(values, min, max) {\n return Math.ceil((max - min) / (3.5 * deviation(values) * Math.pow(values.length, -1 / 3)));\n}\n","export default function(values) {\n return Math.ceil(Math.log(values.length) / Math.LN2) + 1;\n}\n","var e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nexport default function(start, stop, count) {\n var reverse,\n i = -1,\n n,\n ticks,\n step;\n\n stop = +stop, start = +start, count = +count;\n if (start === stop && count > 0) return [start];\n if (reverse = stop < start) n = start, start = stop, stop = n;\n if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];\n\n if (step > 0) {\n start = Math.ceil(start / step);\n stop = Math.floor(stop / step);\n ticks = new Array(n = Math.ceil(stop - start + 1));\n while (++i < n) ticks[i] = (start + i) * step;\n } else {\n start = Math.floor(start * step);\n stop = Math.ceil(stop * step);\n ticks = new Array(n = Math.ceil(start - stop + 1));\n while (++i < n) ticks[i] = (start - i) / step;\n }\n\n if (reverse) ticks.reverse();\n\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n var step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log(step) / Math.LN10),\n error = step / Math.pow(10, power);\n return power >= 0\n ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)\n : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);\n}\n\nexport function tickStep(start, stop, count) {\n var step0 = Math.abs(stop - start) / Math.max(0, count),\n step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),\n error = step0 / step1;\n if (error >= e10) step1 *= 10;\n else if (error >= e5) step1 *= 5;\n else if (error >= e2) step1 *= 2;\n return stop < start ? -step1 : step1;\n}\n","import min from \"./min\";\n\nexport default function(matrix) {\n if (!(n = matrix.length)) return [];\n for (var i = -1, m = min(matrix, length), transpose = new Array(m); ++i < m;) {\n for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n;) {\n row[j] = matrix[j][i];\n }\n }\n return transpose;\n}\n\nfunction length(d) {\n return d.length;\n}\n","import number from \"./number\";\n\nexport default function(values, valueof) {\n var n = values.length,\n m = 0,\n i = -1,\n mean = 0,\n value,\n delta,\n sum = 0;\n\n if (valueof == null) {\n while (++i < n) {\n if (!isNaN(value = number(values[i]))) {\n delta = value - mean;\n mean += delta / ++m;\n sum += delta * (value - mean);\n }\n }\n }\n\n else {\n while (++i < n) {\n if (!isNaN(value = number(valueof(values[i], i, values)))) {\n delta = value - mean;\n mean += delta / ++m;\n sum += delta * (value - mean);\n }\n }\n }\n\n if (m > 1) return sum / (m - 1);\n}\n","import transpose from \"./transpose\";\n\nexport default function() {\n return transpose(arguments);\n}\n","var array = Array.prototype;\n\nexport var map = array.map;\nexport var slice = array.slice;\n","import {range as sequence} from \"d3-array\";\nimport {initRange} from \"./init\";\nimport ordinal from \"./ordinal\";\n\nexport default function band() {\n var scale = ordinal().unknown(undefined),\n domain = scale.domain,\n ordinalRange = scale.range,\n range = [0, 1],\n step,\n bandwidth,\n round = false,\n paddingInner = 0,\n paddingOuter = 0,\n align = 0.5;\n\n delete scale.unknown;\n\n function rescale() {\n var n = domain().length,\n reverse = range[1] < range[0],\n start = range[reverse - 0],\n stop = range[1 - reverse];\n step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2);\n if (round) step = Math.floor(step);\n start += (stop - start - step * (n - paddingInner)) * align;\n bandwidth = step * (1 - paddingInner);\n if (round) start = Math.round(start), bandwidth = Math.round(bandwidth);\n var values = sequence(n).map(function(i) { return start + step * i; });\n return ordinalRange(reverse ? values.reverse() : values);\n }\n\n scale.domain = function(_) {\n return arguments.length ? (domain(_), rescale()) : domain();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = [+_[0], +_[1]], rescale()) : range.slice();\n };\n\n scale.rangeRound = function(_) {\n return range = [+_[0], +_[1]], round = true, rescale();\n };\n\n scale.bandwidth = function() {\n return bandwidth;\n };\n\n scale.step = function() {\n return step;\n };\n\n scale.round = function(_) {\n return arguments.length ? (round = !!_, rescale()) : round;\n };\n\n scale.padding = function(_) {\n return arguments.length ? (paddingInner = Math.min(1, paddingOuter = +_), rescale()) : paddingInner;\n };\n\n scale.paddingInner = function(_) {\n return arguments.length ? (paddingInner = Math.min(1, _), rescale()) : paddingInner;\n };\n\n scale.paddingOuter = function(_) {\n return arguments.length ? (paddingOuter = +_, rescale()) : paddingOuter;\n };\n\n scale.align = function(_) {\n return arguments.length ? (align = Math.max(0, Math.min(1, _)), rescale()) : align;\n };\n\n scale.copy = function() {\n return band(domain(), range)\n .round(round)\n .paddingInner(paddingInner)\n .paddingOuter(paddingOuter)\n .align(align);\n };\n\n return initRange.apply(rescale(), arguments);\n}\n\nfunction pointish(scale) {\n var copy = scale.copy;\n\n scale.padding = scale.paddingOuter;\n delete scale.paddingInner;\n delete scale.paddingOuter;\n\n scale.copy = function() {\n return pointish(copy());\n };\n\n return scale;\n}\n\nexport function point() {\n return pointish(band.apply(null, arguments).paddingInner(1));\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","import {bisect} from \"d3-array\";\nimport {interpolate as interpolateValue, interpolateNumber, interpolateRound} from \"d3-interpolate\";\nimport {map, slice} from \"./array\";\nimport constant from \"./constant\";\nimport number from \"./number\";\n\nvar unit = [0, 1];\n\nexport function identity(x) {\n return x;\n}\n\nfunction normalize(a, b) {\n return (b -= (a = +a))\n ? function(x) { return (x - a) / b; }\n : constant(isNaN(b) ? NaN : 0.5);\n}\n\nfunction clamper(domain) {\n var a = domain[0], b = domain[domain.length - 1], t;\n if (a > b) t = a, a = b, b = t;\n return function(x) { return Math.max(a, Math.min(b, x)); };\n}\n\n// normalize(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1].\n// interpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding range value x in [a,b].\nfunction bimap(domain, range, interpolate) {\n var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1];\n if (d1 < d0) d0 = normalize(d1, d0), r0 = interpolate(r1, r0);\n else d0 = normalize(d0, d1), r0 = interpolate(r0, r1);\n return function(x) { return r0(d0(x)); };\n}\n\nfunction polymap(domain, range, interpolate) {\n var j = Math.min(domain.length, range.length) - 1,\n d = new Array(j),\n r = new Array(j),\n i = -1;\n\n // Reverse descending domains.\n if (domain[j] < domain[0]) {\n domain = domain.slice().reverse();\n range = range.slice().reverse();\n }\n\n while (++i < j) {\n d[i] = normalize(domain[i], domain[i + 1]);\n r[i] = interpolate(range[i], range[i + 1]);\n }\n\n return function(x) {\n var i = bisect(domain, x, 1, j) - 1;\n return r[i](d[i](x));\n };\n}\n\nexport function copy(source, target) {\n return target\n .domain(source.domain())\n .range(source.range())\n .interpolate(source.interpolate())\n .clamp(source.clamp())\n .unknown(source.unknown());\n}\n\nexport function transformer() {\n var domain = unit,\n range = unit,\n interpolate = interpolateValue,\n transform,\n untransform,\n unknown,\n clamp = identity,\n piecewise,\n output,\n input;\n\n function rescale() {\n piecewise = Math.min(domain.length, range.length) > 2 ? polymap : bimap;\n output = input = null;\n return scale;\n }\n\n function scale(x) {\n return isNaN(x = +x) ? unknown : (output || (output = piecewise(domain.map(transform), range, interpolate)))(transform(clamp(x)));\n }\n\n scale.invert = function(y) {\n return clamp(untransform((input || (input = piecewise(range, domain.map(transform), interpolateNumber)))(y)));\n };\n\n scale.domain = function(_) {\n return arguments.length ? (domain = map.call(_, number), clamp === identity || (clamp = clamper(domain)), rescale()) : domain.slice();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = slice.call(_), rescale()) : range.slice();\n };\n\n scale.rangeRound = function(_) {\n return range = slice.call(_), interpolate = interpolateRound, rescale();\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = _ ? clamper(domain) : identity, scale) : clamp !== identity;\n };\n\n scale.interpolate = function(_) {\n return arguments.length ? (interpolate = _, rescale()) : interpolate;\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t, u) {\n transform = t, untransform = u;\n return rescale();\n };\n}\n\nexport default function continuous(transform, untransform) {\n return transformer()(transform, untransform);\n}\n","import {identity} from \"./continuous\";\nimport {initInterpolator} from \"./init\";\nimport {linearish} from \"./linear\";\nimport {loggish} from \"./log\";\nimport {copy} from \"./sequential\";\nimport {symlogish} from \"./symlog\";\nimport {powish} from \"./pow\";\n\nfunction transformer() {\n var x0 = 0,\n x1 = 0.5,\n x2 = 1,\n t0,\n t1,\n t2,\n k10,\n k21,\n interpolator = identity,\n transform,\n clamp = false,\n unknown;\n\n function scale(x) {\n return isNaN(x = +x) ? unknown : (x = 0.5 + ((x = +transform(x)) - t1) * (x < t1 ? k10 : k21), interpolator(clamp ? Math.max(0, Math.min(1, x)) : x));\n }\n\n scale.domain = function(_) {\n return arguments.length ? (t0 = transform(x0 = +_[0]), t1 = transform(x1 = +_[1]), t2 = transform(x2 = +_[2]), k10 = t0 === t1 ? 0 : 0.5 / (t1 - t0), k21 = t1 === t2 ? 0 : 0.5 / (t2 - t1), scale) : [x0, x1, x2];\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = !!_, scale) : clamp;\n };\n\n scale.interpolator = function(_) {\n return arguments.length ? (interpolator = _, scale) : interpolator;\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t) {\n transform = t, t0 = t(x0), t1 = t(x1), t2 = t(x2), k10 = t0 === t1 ? 0 : 0.5 / (t1 - t0), k21 = t1 === t2 ? 0 : 0.5 / (t2 - t1);\n return scale;\n };\n}\n\nexport default function diverging() {\n var scale = linearish(transformer()(identity));\n\n scale.copy = function() {\n return copy(scale, diverging());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function divergingLog() {\n var scale = loggish(transformer()).domain([0.1, 1, 10]);\n\n scale.copy = function() {\n return copy(scale, divergingLog()).base(scale.base());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function divergingSymlog() {\n var scale = symlogish(transformer());\n\n scale.copy = function() {\n return copy(scale, divergingSymlog()).constant(scale.constant());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function divergingPow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, divergingPow()).exponent(scale.exponent());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function divergingSqrt() {\n return divergingPow.apply(null, arguments).exponent(0.5);\n}\n","import {map} from \"./array\";\nimport {linearish} from \"./linear\";\nimport number from \"./number\";\n\nexport default function identity(domain) {\n var unknown;\n\n function scale(x) {\n return isNaN(x = +x) ? unknown : x;\n }\n\n scale.invert = scale;\n\n scale.domain = scale.range = function(_) {\n return arguments.length ? (domain = map.call(_, number), scale) : domain.slice();\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.copy = function() {\n return identity(domain).unknown(unknown);\n };\n\n domain = arguments.length ? map.call(domain, number) : [0, 1];\n\n return linearish(scale);\n}\n","export {\n default as scaleBand,\n point as scalePoint\n} from \"./band\";\n\nexport {\n default as scaleIdentity\n} from \"./identity\";\n\nexport {\n default as scaleLinear\n} from \"./linear\";\n\nexport {\n default as scaleLog\n} from \"./log\";\n\nexport {\n default as scaleSymlog\n} from \"./symlog\";\n\nexport {\n default as scaleOrdinal,\n implicit as scaleImplicit\n} from \"./ordinal\";\n\nexport {\n default as scalePow,\n sqrt as scaleSqrt\n} from \"./pow\";\n\nexport {\n default as scaleQuantile\n} from \"./quantile\";\n\nexport {\n default as scaleQuantize\n} from \"./quantize\";\n\nexport {\n default as scaleThreshold\n} from \"./threshold\";\n\nexport {\n default as scaleTime\n} from \"./time\";\n\nexport {\n default as scaleUtc\n} from \"./utcTime\";\n\nexport {\n default as scaleSequential,\n sequentialLog as scaleSequentialLog,\n sequentialPow as scaleSequentialPow,\n sequentialSqrt as scaleSequentialSqrt,\n sequentialSymlog as scaleSequentialSymlog\n} from \"./sequential\";\n\nexport {\n default as scaleSequentialQuantile\n} from \"./sequentialQuantile\";\n\nexport {\n default as scaleDiverging,\n divergingLog as scaleDivergingLog,\n divergingPow as scaleDivergingPow,\n divergingSqrt as scaleDivergingSqrt,\n divergingSymlog as scaleDivergingSymlog\n} from \"./diverging\";\n\nexport {\n default as tickFormat\n} from \"./tickFormat\";\n","export function initRange(domain, range) {\n switch (arguments.length) {\n case 0: break;\n case 1: this.range(domain); break;\n default: this.range(range).domain(domain); break;\n }\n return this;\n}\n\nexport function initInterpolator(domain, interpolator) {\n switch (arguments.length) {\n case 0: break;\n case 1: this.interpolator(domain); break;\n default: this.interpolator(interpolator).domain(domain); break;\n }\n return this;\n}\n","import {ticks, tickIncrement} from \"d3-array\";\nimport continuous, {copy, identity} from \"./continuous\";\nimport {initRange} from \"./init\";\nimport tickFormat from \"./tickFormat\";\n\nexport function linearish(scale) {\n var domain = scale.domain;\n\n scale.ticks = function(count) {\n var d = domain();\n return ticks(d[0], d[d.length - 1], count == null ? 10 : count);\n };\n\n scale.tickFormat = function(count, specifier) {\n var d = domain();\n return tickFormat(d[0], d[d.length - 1], count == null ? 10 : count, specifier);\n };\n\n scale.nice = function(count) {\n if (count == null) count = 10;\n\n var d = domain(),\n i0 = 0,\n i1 = d.length - 1,\n start = d[i0],\n stop = d[i1],\n step;\n\n if (stop < start) {\n step = start, start = stop, stop = step;\n step = i0, i0 = i1, i1 = step;\n }\n\n step = tickIncrement(start, stop, count);\n\n if (step > 0) {\n start = Math.floor(start / step) * step;\n stop = Math.ceil(stop / step) * step;\n step = tickIncrement(start, stop, count);\n } else if (step < 0) {\n start = Math.ceil(start * step) / step;\n stop = Math.floor(stop * step) / step;\n step = tickIncrement(start, stop, count);\n }\n\n if (step > 0) {\n d[i0] = Math.floor(start / step) * step;\n d[i1] = Math.ceil(stop / step) * step;\n domain(d);\n } else if (step < 0) {\n d[i0] = Math.ceil(start * step) / step;\n d[i1] = Math.floor(stop * step) / step;\n domain(d);\n }\n\n return scale;\n };\n\n return scale;\n}\n\nexport default function linear() {\n var scale = continuous(identity, identity);\n\n scale.copy = function() {\n return copy(scale, linear());\n };\n\n initRange.apply(scale, arguments);\n\n return linearish(scale);\n}\n","import {ticks} from \"d3-array\";\nimport {format} from \"d3-format\";\nimport nice from \"./nice\";\nimport {copy, transformer} from \"./continuous\";\nimport {initRange} from \"./init\";\n\nfunction transformLog(x) {\n return Math.log(x);\n}\n\nfunction transformExp(x) {\n return Math.exp(x);\n}\n\nfunction transformLogn(x) {\n return -Math.log(-x);\n}\n\nfunction transformExpn(x) {\n return -Math.exp(-x);\n}\n\nfunction pow10(x) {\n return isFinite(x) ? +(\"1e\" + x) : x < 0 ? 0 : x;\n}\n\nfunction powp(base) {\n return base === 10 ? pow10\n : base === Math.E ? Math.exp\n : function(x) { return Math.pow(base, x); };\n}\n\nfunction logp(base) {\n return base === Math.E ? Math.log\n : base === 10 && Math.log10\n || base === 2 && Math.log2\n || (base = Math.log(base), function(x) { return Math.log(x) / base; });\n}\n\nfunction reflect(f) {\n return function(x) {\n return -f(-x);\n };\n}\n\nexport function loggish(transform) {\n var scale = transform(transformLog, transformExp),\n domain = scale.domain,\n base = 10,\n logs,\n pows;\n\n function rescale() {\n logs = logp(base), pows = powp(base);\n if (domain()[0] < 0) {\n logs = reflect(logs), pows = reflect(pows);\n transform(transformLogn, transformExpn);\n } else {\n transform(transformLog, transformExp);\n }\n return scale;\n }\n\n scale.base = function(_) {\n return arguments.length ? (base = +_, rescale()) : base;\n };\n\n scale.domain = function(_) {\n return arguments.length ? (domain(_), rescale()) : domain();\n };\n\n scale.ticks = function(count) {\n var d = domain(),\n u = d[0],\n v = d[d.length - 1],\n r;\n\n if (r = v < u) i = u, u = v, v = i;\n\n var i = logs(u),\n j = logs(v),\n p,\n k,\n t,\n n = count == null ? 10 : +count,\n z = [];\n\n if (!(base % 1) && j - i < n) {\n i = Math.round(i) - 1, j = Math.round(j) + 1;\n if (u > 0) for (; i < j; ++i) {\n for (k = 1, p = pows(i); k < base; ++k) {\n t = p * k;\n if (t < u) continue;\n if (t > v) break;\n z.push(t);\n }\n } else for (; i < j; ++i) {\n for (k = base - 1, p = pows(i); k >= 1; --k) {\n t = p * k;\n if (t < u) continue;\n if (t > v) break;\n z.push(t);\n }\n }\n } else {\n z = ticks(i, j, Math.min(j - i, n)).map(pows);\n }\n\n return r ? z.reverse() : z;\n };\n\n scale.tickFormat = function(count, specifier) {\n if (specifier == null) specifier = base === 10 ? \".0e\" : \",\";\n if (typeof specifier !== \"function\") specifier = format(specifier);\n if (count === Infinity) return specifier;\n if (count == null) count = 10;\n var k = Math.max(1, base * count / scale.ticks().length); // TODO fast estimate?\n return function(d) {\n var i = d / pows(Math.round(logs(d)));\n if (i * base < base - 0.5) i *= base;\n return i <= k ? specifier(d) : \"\";\n };\n };\n\n scale.nice = function() {\n return domain(nice(domain(), {\n floor: function(x) { return pows(Math.floor(logs(x))); },\n ceil: function(x) { return pows(Math.ceil(logs(x))); }\n }));\n };\n\n return scale;\n}\n\nexport default function log() {\n var scale = loggish(transformer()).domain([1, 10]);\n\n scale.copy = function() {\n return copy(scale, log()).base(scale.base());\n };\n\n initRange.apply(scale, arguments);\n\n return scale;\n}\n","export default function(domain, interval) {\n domain = domain.slice();\n\n var i0 = 0,\n i1 = domain.length - 1,\n x0 = domain[i0],\n x1 = domain[i1],\n t;\n\n if (x1 < x0) {\n t = i0, i0 = i1, i1 = t;\n t = x0, x0 = x1, x1 = t;\n }\n\n domain[i0] = interval.floor(x0);\n domain[i1] = interval.ceil(x1);\n return domain;\n}\n","export default function(x) {\n return +x;\n}\n","import {map} from \"d3-collection\";\nimport {slice} from \"./array\";\nimport {initRange} from \"./init\";\n\nexport var implicit = {name: \"implicit\"};\n\nexport default function ordinal() {\n var index = map(),\n domain = [],\n range = [],\n unknown = implicit;\n\n function scale(d) {\n var key = d + \"\", i = index.get(key);\n if (!i) {\n if (unknown !== implicit) return unknown;\n index.set(key, i = domain.push(d));\n }\n return range[(i - 1) % range.length];\n }\n\n scale.domain = function(_) {\n if (!arguments.length) return domain.slice();\n domain = [], index = map();\n var i = -1, n = _.length, d, key;\n while (++i < n) if (!index.has(key = (d = _[i]) + \"\")) index.set(key, domain.push(d));\n return scale;\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = slice.call(_), scale) : range.slice();\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.copy = function() {\n return ordinal(domain, range).unknown(unknown);\n };\n\n initRange.apply(scale, arguments);\n\n return scale;\n}\n","import {linearish} from \"./linear\";\nimport {copy, identity, transformer} from \"./continuous\";\nimport {initRange} from \"./init\";\n\nfunction transformPow(exponent) {\n return function(x) {\n return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent);\n };\n}\n\nfunction transformSqrt(x) {\n return x < 0 ? -Math.sqrt(-x) : Math.sqrt(x);\n}\n\nfunction transformSquare(x) {\n return x < 0 ? -x * x : x * x;\n}\n\nexport function powish(transform) {\n var scale = transform(identity, identity),\n exponent = 1;\n\n function rescale() {\n return exponent === 1 ? transform(identity, identity)\n : exponent === 0.5 ? transform(transformSqrt, transformSquare)\n : transform(transformPow(exponent), transformPow(1 / exponent));\n }\n\n scale.exponent = function(_) {\n return arguments.length ? (exponent = +_, rescale()) : exponent;\n };\n\n return linearish(scale);\n}\n\nexport default function pow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, pow()).exponent(scale.exponent());\n };\n\n initRange.apply(scale, arguments);\n\n return scale;\n}\n\nexport function sqrt() {\n return pow.apply(null, arguments).exponent(0.5);\n}\n","import {ascending, bisect, quantile as threshold} from \"d3-array\";\nimport {slice} from \"./array\";\nimport {initRange} from \"./init\";\n\nexport default function quantile() {\n var domain = [],\n range = [],\n thresholds = [],\n unknown;\n\n function rescale() {\n var i = 0, n = Math.max(1, range.length);\n thresholds = new Array(n - 1);\n while (++i < n) thresholds[i - 1] = threshold(domain, i / n);\n return scale;\n }\n\n function scale(x) {\n return isNaN(x = +x) ? unknown : range[bisect(thresholds, x)];\n }\n\n scale.invertExtent = function(y) {\n var i = range.indexOf(y);\n return i < 0 ? [NaN, NaN] : [\n i > 0 ? thresholds[i - 1] : domain[0],\n i < thresholds.length ? thresholds[i] : domain[domain.length - 1]\n ];\n };\n\n scale.domain = function(_) {\n if (!arguments.length) return domain.slice();\n domain = [];\n for (var i = 0, n = _.length, d; i < n; ++i) if (d = _[i], d != null && !isNaN(d = +d)) domain.push(d);\n domain.sort(ascending);\n return rescale();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = slice.call(_), rescale()) : range.slice();\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.quantiles = function() {\n return thresholds.slice();\n };\n\n scale.copy = function() {\n return quantile()\n .domain(domain)\n .range(range)\n .unknown(unknown);\n };\n\n return initRange.apply(scale, arguments);\n}\n","import {bisect} from \"d3-array\";\nimport {slice} from \"./array\";\nimport {linearish} from \"./linear\";\nimport {initRange} from \"./init\";\n\nexport default function quantize() {\n var x0 = 0,\n x1 = 1,\n n = 1,\n domain = [0.5],\n range = [0, 1],\n unknown;\n\n function scale(x) {\n return x <= x ? range[bisect(domain, x, 0, n)] : unknown;\n }\n\n function rescale() {\n var i = -1;\n domain = new Array(n);\n while (++i < n) domain[i] = ((i + 1) * x1 - (i - n) * x0) / (n + 1);\n return scale;\n }\n\n scale.domain = function(_) {\n return arguments.length ? (x0 = +_[0], x1 = +_[1], rescale()) : [x0, x1];\n };\n\n scale.range = function(_) {\n return arguments.length ? (n = (range = slice.call(_)).length - 1, rescale()) : range.slice();\n };\n\n scale.invertExtent = function(y) {\n var i = range.indexOf(y);\n return i < 0 ? [NaN, NaN]\n : i < 1 ? [x0, domain[0]]\n : i >= n ? [domain[n - 1], x1]\n : [domain[i - 1], domain[i]];\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : scale;\n };\n\n scale.thresholds = function() {\n return domain.slice();\n };\n\n scale.copy = function() {\n return quantize()\n .domain([x0, x1])\n .range(range)\n .unknown(unknown);\n };\n\n return initRange.apply(linearish(scale), arguments);\n}\n","import {identity} from \"./continuous\";\nimport {initInterpolator} from \"./init\";\nimport {linearish} from \"./linear\";\nimport {loggish} from \"./log\";\nimport {symlogish} from \"./symlog\";\nimport {powish} from \"./pow\";\n\nfunction transformer() {\n var x0 = 0,\n x1 = 1,\n t0,\n t1,\n k10,\n transform,\n interpolator = identity,\n clamp = false,\n unknown;\n\n function scale(x) {\n return isNaN(x = +x) ? unknown : interpolator(k10 === 0 ? 0.5 : (x = (transform(x) - t0) * k10, clamp ? Math.max(0, Math.min(1, x)) : x));\n }\n\n scale.domain = function(_) {\n return arguments.length ? (t0 = transform(x0 = +_[0]), t1 = transform(x1 = +_[1]), k10 = t0 === t1 ? 0 : 1 / (t1 - t0), scale) : [x0, x1];\n };\n\n scale.clamp = function(_) {\n return arguments.length ? (clamp = !!_, scale) : clamp;\n };\n\n scale.interpolator = function(_) {\n return arguments.length ? (interpolator = _, scale) : interpolator;\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n return function(t) {\n transform = t, t0 = t(x0), t1 = t(x1), k10 = t0 === t1 ? 0 : 1 / (t1 - t0);\n return scale;\n };\n}\n\nexport function copy(source, target) {\n return target\n .domain(source.domain())\n .interpolator(source.interpolator())\n .clamp(source.clamp())\n .unknown(source.unknown());\n}\n\nexport default function sequential() {\n var scale = linearish(transformer()(identity));\n\n scale.copy = function() {\n return copy(scale, sequential());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialLog() {\n var scale = loggish(transformer()).domain([1, 10]);\n\n scale.copy = function() {\n return copy(scale, sequentialLog()).base(scale.base());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialSymlog() {\n var scale = symlogish(transformer());\n\n scale.copy = function() {\n return copy(scale, sequentialSymlog()).constant(scale.constant());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialPow() {\n var scale = powish(transformer());\n\n scale.copy = function() {\n return copy(scale, sequentialPow()).exponent(scale.exponent());\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n\nexport function sequentialSqrt() {\n return sequentialPow.apply(null, arguments).exponent(0.5);\n}\n","import {ascending, bisect} from \"d3-array\";\nimport {identity} from \"./continuous\";\nimport {initInterpolator} from \"./init\";\n\nexport default function sequentialQuantile() {\n var domain = [],\n interpolator = identity;\n\n function scale(x) {\n if (!isNaN(x = +x)) return interpolator((bisect(domain, x) - 1) / (domain.length - 1));\n }\n\n scale.domain = function(_) {\n if (!arguments.length) return domain.slice();\n domain = [];\n for (var i = 0, n = _.length, d; i < n; ++i) if (d = _[i], d != null && !isNaN(d = +d)) domain.push(d);\n domain.sort(ascending);\n return scale;\n };\n\n scale.interpolator = function(_) {\n return arguments.length ? (interpolator = _, scale) : interpolator;\n };\n\n scale.copy = function() {\n return sequentialQuantile(interpolator).domain(domain);\n };\n\n return initInterpolator.apply(scale, arguments);\n}\n","import {linearish} from \"./linear\";\nimport {copy, transformer} from \"./continuous\";\nimport {initRange} from \"./init\";\n\nfunction transformSymlog(c) {\n return function(x) {\n return Math.sign(x) * Math.log1p(Math.abs(x / c));\n };\n}\n\nfunction transformSymexp(c) {\n return function(x) {\n return Math.sign(x) * Math.expm1(Math.abs(x)) * c;\n };\n}\n\nexport function symlogish(transform) {\n var c = 1, scale = transform(transformSymlog(c), transformSymexp(c));\n\n scale.constant = function(_) {\n return arguments.length ? transform(transformSymlog(c = +_), transformSymexp(c)) : c;\n };\n\n return linearish(scale);\n}\n\nexport default function symlog() {\n var scale = symlogish(transformer());\n\n scale.copy = function() {\n return copy(scale, symlog()).constant(scale.constant());\n };\n\n return initRange.apply(scale, arguments);\n}\n","import {bisect} from \"d3-array\";\nimport {slice} from \"./array\";\nimport {initRange} from \"./init\";\n\nexport default function threshold() {\n var domain = [0.5],\n range = [0, 1],\n unknown,\n n = 1;\n\n function scale(x) {\n return x <= x ? range[bisect(domain, x, 0, n)] : unknown;\n }\n\n scale.domain = function(_) {\n return arguments.length ? (domain = slice.call(_), n = Math.min(domain.length, range.length - 1), scale) : domain.slice();\n };\n\n scale.range = function(_) {\n return arguments.length ? (range = slice.call(_), n = Math.min(domain.length, range.length - 1), scale) : range.slice();\n };\n\n scale.invertExtent = function(y) {\n var i = range.indexOf(y);\n return [domain[i - 1], domain[i]];\n };\n\n scale.unknown = function(_) {\n return arguments.length ? (unknown = _, scale) : unknown;\n };\n\n scale.copy = function() {\n return threshold()\n .domain(domain)\n .range(range)\n .unknown(unknown);\n };\n\n return initRange.apply(scale, arguments);\n}\n","import {tickStep} from \"d3-array\";\nimport {format, formatPrefix, formatSpecifier, precisionFixed, precisionPrefix, precisionRound} from \"d3-format\";\n\nexport default function(start, stop, count, specifier) {\n var step = tickStep(start, stop, count),\n precision;\n specifier = formatSpecifier(specifier == null ? \",f\" : specifier);\n switch (specifier.type) {\n case \"s\": {\n var value = Math.max(Math.abs(start), Math.abs(stop));\n if (specifier.precision == null && !isNaN(precision = precisionPrefix(step, value))) specifier.precision = precision;\n return formatPrefix(specifier, value);\n }\n case \"\":\n case \"e\":\n case \"g\":\n case \"p\":\n case \"r\": {\n if (specifier.precision == null && !isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === \"e\");\n break;\n }\n case \"f\":\n case \"%\": {\n if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === \"%\") * 2;\n break;\n }\n }\n return format(specifier);\n}\n","import {bisector, tickStep} from \"d3-array\";\nimport {timeYear, timeMonth, timeWeek, timeDay, timeHour, timeMinute, timeSecond, timeMillisecond} from \"d3-time\";\nimport {timeFormat} from \"d3-time-format\";\nimport {map} from \"./array\";\nimport continuous, {copy, identity} from \"./continuous\";\nimport {initRange} from \"./init\";\nimport nice from \"./nice\";\n\nvar durationSecond = 1000,\n durationMinute = durationSecond * 60,\n durationHour = durationMinute * 60,\n durationDay = durationHour * 24,\n durationWeek = durationDay * 7,\n durationMonth = durationDay * 30,\n durationYear = durationDay * 365;\n\nfunction date(t) {\n return new Date(t);\n}\n\nfunction number(t) {\n return t instanceof Date ? +t : +new Date(+t);\n}\n\nexport function calendar(year, month, week, day, hour, minute, second, millisecond, format) {\n var scale = continuous(identity, identity),\n invert = scale.invert,\n domain = scale.domain;\n\n var formatMillisecond = format(\".%L\"),\n formatSecond = format(\":%S\"),\n formatMinute = format(\"%I:%M\"),\n formatHour = format(\"%I %p\"),\n formatDay = format(\"%a %d\"),\n formatWeek = format(\"%b %d\"),\n formatMonth = format(\"%B\"),\n formatYear = format(\"%Y\");\n\n var tickIntervals = [\n [second, 1, durationSecond],\n [second, 5, 5 * durationSecond],\n [second, 15, 15 * durationSecond],\n [second, 30, 30 * durationSecond],\n [minute, 1, durationMinute],\n [minute, 5, 5 * durationMinute],\n [minute, 15, 15 * durationMinute],\n [minute, 30, 30 * durationMinute],\n [ hour, 1, durationHour ],\n [ hour, 3, 3 * durationHour ],\n [ hour, 6, 6 * durationHour ],\n [ hour, 12, 12 * durationHour ],\n [ day, 1, durationDay ],\n [ day, 2, 2 * durationDay ],\n [ week, 1, durationWeek ],\n [ month, 1, durationMonth ],\n [ month, 3, 3 * durationMonth ],\n [ year, 1, durationYear ]\n ];\n\n function tickFormat(date) {\n return (second(date) < date ? formatMillisecond\n : minute(date) < date ? formatSecond\n : hour(date) < date ? formatMinute\n : day(date) < date ? formatHour\n : month(date) < date ? (week(date) < date ? formatDay : formatWeek)\n : year(date) < date ? formatMonth\n : formatYear)(date);\n }\n\n function tickInterval(interval, start, stop, step) {\n if (interval == null) interval = 10;\n\n // If a desired tick count is specified, pick a reasonable tick interval\n // based on the extent of the domain and a rough estimate of tick size.\n // Otherwise, assume interval is already a time interval and use it.\n if (typeof interval === \"number\") {\n var target = Math.abs(stop - start) / interval,\n i = bisector(function(i) { return i[2]; }).right(tickIntervals, target);\n if (i === tickIntervals.length) {\n step = tickStep(start / durationYear, stop / durationYear, interval);\n interval = year;\n } else if (i) {\n i = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i];\n step = i[1];\n interval = i[0];\n } else {\n step = Math.max(tickStep(start, stop, interval), 1);\n interval = millisecond;\n }\n }\n\n return step == null ? interval : interval.every(step);\n }\n\n scale.invert = function(y) {\n return new Date(invert(y));\n };\n\n scale.domain = function(_) {\n return arguments.length ? domain(map.call(_, number)) : domain().map(date);\n };\n\n scale.ticks = function(interval, step) {\n var d = domain(),\n t0 = d[0],\n t1 = d[d.length - 1],\n r = t1 < t0,\n t;\n if (r) t = t0, t0 = t1, t1 = t;\n t = tickInterval(interval, t0, t1, step);\n t = t ? t.range(t0, t1 + 1) : []; // inclusive stop\n return r ? t.reverse() : t;\n };\n\n scale.tickFormat = function(count, specifier) {\n return specifier == null ? tickFormat : format(specifier);\n };\n\n scale.nice = function(interval, step) {\n var d = domain();\n return (interval = tickInterval(interval, d[0], d[d.length - 1], step))\n ? domain(nice(d, interval))\n : scale;\n };\n\n scale.copy = function() {\n return copy(scale, calendar(year, month, week, day, hour, minute, second, millisecond, format));\n };\n\n return scale;\n}\n\nexport default function() {\n return initRange.apply(calendar(timeYear, timeMonth, timeWeek, timeDay, timeHour, timeMinute, timeSecond, timeMillisecond, timeFormat).domain([new Date(2000, 0, 1), new Date(2000, 0, 2)]), arguments);\n}\n","import {calendar} from \"./time\";\nimport {utcFormat} from \"d3-time-format\";\nimport {utcYear, utcMonth, utcWeek, utcDay, utcHour, utcMinute, utcSecond, utcMillisecond} from \"d3-time\";\nimport {initRange} from \"./init\";\n\nexport default function() {\n return initRange.apply(calendar(utcYear, utcMonth, utcWeek, utcDay, utcHour, utcMinute, utcSecond, utcMillisecond, utcFormat).domain([Date.UTC(2000, 0, 1), Date.UTC(2000, 0, 2)]), arguments);\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","import creator from \"./creator\";\nimport select from \"./select\";\n\nexport default function(name) {\n return select(creator(name).call(document.documentElement));\n}\n","import namespace from \"./namespace\";\nimport {xhtml} from \"./namespaces\";\n\nfunction creatorInherit(name) {\n return function() {\n var document = this.ownerDocument,\n uri = this.namespaceURI;\n return uri === xhtml && document.documentElement.namespaceURI === xhtml\n ? document.createElement(name)\n : document.createElementNS(uri, name);\n };\n}\n\nfunction creatorFixed(fullname) {\n return function() {\n return this.ownerDocument.createElementNS(fullname.space, fullname.local);\n };\n}\n\nexport default function(name) {\n var fullname = namespace(name);\n return (fullname.local\n ? creatorFixed\n : creatorInherit)(fullname);\n}\n","export {default as create} from \"./create\";\nexport {default as creator} from \"./creator\";\nexport {default as local} from \"./local\";\nexport {default as matcher} from \"./matcher\";\nexport {default as mouse} from \"./mouse\";\nexport {default as namespace} from \"./namespace\";\nexport {default as namespaces} from \"./namespaces\";\nexport {default as clientPoint} from \"./point\";\nexport {default as select} from \"./select\";\nexport {default as selectAll} from \"./selectAll\";\nexport {default as selection} from \"./selection/index\";\nexport {default as selector} from \"./selector\";\nexport {default as selectorAll} from \"./selectorAll\";\nexport {styleValue as style} from \"./selection/style\";\nexport {default as touch} from \"./touch\";\nexport {default as touches} from \"./touches\";\nexport {default as window} from \"./window\";\nexport {event, customEvent} from \"./selection/on\";\n","var nextId = 0;\n\nexport default function local() {\n return new Local;\n}\n\nfunction Local() {\n this._ = \"@\" + (++nextId).toString(36);\n}\n\nLocal.prototype = local.prototype = {\n constructor: Local,\n get: function(node) {\n var id = this._;\n while (!(id in node)) if (!(node = node.parentNode)) return;\n return node[id];\n },\n set: function(node, value) {\n return node[this._] = value;\n },\n remove: function(node) {\n return this._ in node && delete node[this._];\n },\n toString: function() {\n return this._;\n }\n};\n","export default function(selector) {\n return function() {\n return this.matches(selector);\n };\n}\n","import sourceEvent from \"./sourceEvent\";\nimport point from \"./point\";\n\nexport default function(node) {\n var event = sourceEvent();\n if (event.changedTouches) event = event.changedTouches[0];\n return point(node, event);\n}\n","import namespaces from \"./namespaces\";\n\nexport default function(name) {\n var prefix = name += \"\", i = prefix.indexOf(\":\");\n if (i >= 0 && (prefix = name.slice(0, i)) !== \"xmlns\") name = name.slice(i + 1);\n return namespaces.hasOwnProperty(prefix) ? {space: namespaces[prefix], local: name} : name;\n}\n","export var xhtml = \"http://www.w3.org/1999/xhtml\";\n\nexport default {\n svg: \"http://www.w3.org/2000/svg\",\n xhtml: xhtml,\n xlink: \"http://www.w3.org/1999/xlink\",\n xml: \"http://www.w3.org/XML/1998/namespace\",\n xmlns: \"http://www.w3.org/2000/xmlns/\"\n};\n","export default function(node, event) {\n var svg = node.ownerSVGElement || node;\n\n if (svg.createSVGPoint) {\n var point = svg.createSVGPoint();\n point.x = event.clientX, point.y = event.clientY;\n point = point.matrixTransform(node.getScreenCTM().inverse());\n return [point.x, point.y];\n }\n\n var rect = node.getBoundingClientRect();\n return [event.clientX - rect.left - node.clientLeft, event.clientY - rect.top - node.clientTop];\n}\n","import {Selection, root} from \"./selection/index\";\n\nexport default function(selector) {\n return typeof selector === \"string\"\n ? new Selection([[document.querySelector(selector)]], [document.documentElement])\n : new Selection([[selector]], root);\n}\n","import {Selection, root} from \"./selection/index\";\n\nexport default function(selector) {\n return typeof selector === \"string\"\n ? new Selection([document.querySelectorAll(selector)], [document.documentElement])\n : new Selection([selector == null ? [] : selector], root);\n}\n","import creator from \"../creator\";\n\nexport default function(name) {\n var create = typeof name === \"function\" ? name : creator(name);\n return this.select(function() {\n return this.appendChild(create.apply(this, arguments));\n });\n}\n","import namespace from \"../namespace\";\n\nfunction attrRemove(name) {\n return function() {\n this.removeAttribute(name);\n };\n}\n\nfunction attrRemoveNS(fullname) {\n return function() {\n this.removeAttributeNS(fullname.space, fullname.local);\n };\n}\n\nfunction attrConstant(name, value) {\n return function() {\n this.setAttribute(name, value);\n };\n}\n\nfunction attrConstantNS(fullname, value) {\n return function() {\n this.setAttributeNS(fullname.space, fullname.local, value);\n };\n}\n\nfunction attrFunction(name, value) {\n return function() {\n var v = value.apply(this, arguments);\n if (v == null) this.removeAttribute(name);\n else this.setAttribute(name, v);\n };\n}\n\nfunction attrFunctionNS(fullname, value) {\n return function() {\n var v = value.apply(this, arguments);\n if (v == null) this.removeAttributeNS(fullname.space, fullname.local);\n else this.setAttributeNS(fullname.space, fullname.local, v);\n };\n}\n\nexport default function(name, value) {\n var fullname = namespace(name);\n\n if (arguments.length < 2) {\n var node = this.node();\n return fullname.local\n ? node.getAttributeNS(fullname.space, fullname.local)\n : node.getAttribute(fullname);\n }\n\n return this.each((value == null\n ? (fullname.local ? attrRemoveNS : attrRemove) : (typeof value === \"function\"\n ? (fullname.local ? attrFunctionNS : attrFunction)\n : (fullname.local ? attrConstantNS : attrConstant)))(fullname, value));\n}\n","export default function() {\n var callback = arguments[0];\n arguments[0] = this;\n callback.apply(null, arguments);\n return this;\n}\n","function classArray(string) {\n return string.trim().split(/^|\\s+/);\n}\n\nfunction classList(node) {\n return node.classList || new ClassList(node);\n}\n\nfunction ClassList(node) {\n this._node = node;\n this._names = classArray(node.getAttribute(\"class\") || \"\");\n}\n\nClassList.prototype = {\n add: function(name) {\n var i = this._names.indexOf(name);\n if (i < 0) {\n this._names.push(name);\n this._node.setAttribute(\"class\", this._names.join(\" \"));\n }\n },\n remove: function(name) {\n var i = this._names.indexOf(name);\n if (i >= 0) {\n this._names.splice(i, 1);\n this._node.setAttribute(\"class\", this._names.join(\" \"));\n }\n },\n contains: function(name) {\n return this._names.indexOf(name) >= 0;\n }\n};\n\nfunction classedAdd(node, names) {\n var list = classList(node), i = -1, n = names.length;\n while (++i < n) list.add(names[i]);\n}\n\nfunction classedRemove(node, names) {\n var list = classList(node), i = -1, n = names.length;\n while (++i < n) list.remove(names[i]);\n}\n\nfunction classedTrue(names) {\n return function() {\n classedAdd(this, names);\n };\n}\n\nfunction classedFalse(names) {\n return function() {\n classedRemove(this, names);\n };\n}\n\nfunction classedFunction(names, value) {\n return function() {\n (value.apply(this, arguments) ? classedAdd : classedRemove)(this, names);\n };\n}\n\nexport default function(name, value) {\n var names = classArray(name + \"\");\n\n if (arguments.length < 2) {\n var list = classList(this.node()), i = -1, n = names.length;\n while (++i < n) if (!list.contains(names[i])) return false;\n return true;\n }\n\n return this.each((typeof value === \"function\"\n ? classedFunction : value\n ? classedTrue\n : classedFalse)(names, value));\n}\n","function selection_cloneShallow() {\n var clone = this.cloneNode(false), parent = this.parentNode;\n return parent ? parent.insertBefore(clone, this.nextSibling) : clone;\n}\n\nfunction selection_cloneDeep() {\n var clone = this.cloneNode(true), parent = this.parentNode;\n return parent ? parent.insertBefore(clone, this.nextSibling) : clone;\n}\n\nexport default function(deep) {\n return this.select(deep ? selection_cloneDeep : selection_cloneShallow);\n}\n","import {Selection} from \"./index\";\nimport {EnterNode} from \"./enter\";\nimport constant from \"../constant\";\n\nvar keyPrefix = \"$\"; // Protect against keys like “__proto__”.\n\nfunction bindIndex(parent, group, enter, update, exit, data) {\n var i = 0,\n node,\n groupLength = group.length,\n dataLength = data.length;\n\n // Put any non-null nodes that fit into update.\n // Put any null nodes into enter.\n // Put any remaining data into enter.\n for (; i < dataLength; ++i) {\n if (node = group[i]) {\n node.__data__ = data[i];\n update[i] = node;\n } else {\n enter[i] = new EnterNode(parent, data[i]);\n }\n }\n\n // Put any non-null nodes that don’t fit into exit.\n for (; i < groupLength; ++i) {\n if (node = group[i]) {\n exit[i] = node;\n }\n }\n}\n\nfunction bindKey(parent, group, enter, update, exit, data, key) {\n var i,\n node,\n nodeByKeyValue = {},\n groupLength = group.length,\n dataLength = data.length,\n keyValues = new Array(groupLength),\n keyValue;\n\n // Compute the key for each node.\n // If multiple nodes have the same key, the duplicates are added to exit.\n for (i = 0; i < groupLength; ++i) {\n if (node = group[i]) {\n keyValues[i] = keyValue = keyPrefix + key.call(node, node.__data__, i, group);\n if (keyValue in nodeByKeyValue) {\n exit[i] = node;\n } else {\n nodeByKeyValue[keyValue] = node;\n }\n }\n }\n\n // Compute the key for each datum.\n // If there a node associated with this key, join and add it to update.\n // If there is not (or the key is a duplicate), add it to enter.\n for (i = 0; i < dataLength; ++i) {\n keyValue = keyPrefix + key.call(parent, data[i], i, data);\n if (node = nodeByKeyValue[keyValue]) {\n update[i] = node;\n node.__data__ = data[i];\n nodeByKeyValue[keyValue] = null;\n } else {\n enter[i] = new EnterNode(parent, data[i]);\n }\n }\n\n // Add any remaining nodes that were not bound to data to exit.\n for (i = 0; i < groupLength; ++i) {\n if ((node = group[i]) && (nodeByKeyValue[keyValues[i]] === node)) {\n exit[i] = node;\n }\n }\n}\n\nexport default function(value, key) {\n if (!value) {\n data = new Array(this.size()), j = -1;\n this.each(function(d) { data[++j] = d; });\n return data;\n }\n\n var bind = key ? bindKey : bindIndex,\n parents = this._parents,\n groups = this._groups;\n\n if (typeof value !== \"function\") value = constant(value);\n\n for (var m = groups.length, update = new Array(m), enter = new Array(m), exit = new Array(m), j = 0; j < m; ++j) {\n var parent = parents[j],\n group = groups[j],\n groupLength = group.length,\n data = value.call(parent, parent && parent.__data__, j, parents),\n dataLength = data.length,\n enterGroup = enter[j] = new Array(dataLength),\n updateGroup = update[j] = new Array(dataLength),\n exitGroup = exit[j] = new Array(groupLength);\n\n bind(parent, group, enterGroup, updateGroup, exitGroup, data, key);\n\n // Now connect the enter nodes to their following update node, such that\n // appendChild can insert the materialized enter node before this node,\n // rather than at the end of the parent node.\n for (var i0 = 0, i1 = 0, previous, next; i0 < dataLength; ++i0) {\n if (previous = enterGroup[i0]) {\n if (i0 >= i1) i1 = i0 + 1;\n while (!(next = updateGroup[i1]) && ++i1 < dataLength);\n previous._next = next || null;\n }\n }\n }\n\n update = new Selection(update, parents);\n update._enter = enter;\n update._exit = exit;\n return update;\n}\n","export default function(value) {\n return arguments.length\n ? this.property(\"__data__\", value)\n : this.node().__data__;\n}\n","import defaultView from \"../window\";\n\nfunction dispatchEvent(node, type, params) {\n var window = defaultView(node),\n event = window.CustomEvent;\n\n if (typeof event === \"function\") {\n event = new event(type, params);\n } else {\n event = window.document.createEvent(\"Event\");\n if (params) event.initEvent(type, params.bubbles, params.cancelable), event.detail = params.detail;\n else event.initEvent(type, false, false);\n }\n\n node.dispatchEvent(event);\n}\n\nfunction dispatchConstant(type, params) {\n return function() {\n return dispatchEvent(this, type, params);\n };\n}\n\nfunction dispatchFunction(type, params) {\n return function() {\n return dispatchEvent(this, type, params.apply(this, arguments));\n };\n}\n\nexport default function(type, params) {\n return this.each((typeof params === \"function\"\n ? dispatchFunction\n : dispatchConstant)(type, params));\n}\n","export default function(callback) {\n\n for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {\n for (var group = groups[j], i = 0, n = group.length, node; i < n; ++i) {\n if (node = group[i]) callback.call(node, node.__data__, i, group);\n }\n }\n\n return this;\n}\n","export default function() {\n return !this.node();\n}\n","import sparse from \"./sparse\";\nimport {Selection} from \"./index\";\n\nexport default function() {\n return new Selection(this._enter || this._groups.map(sparse), this._parents);\n}\n\nexport function EnterNode(parent, datum) {\n this.ownerDocument = parent.ownerDocument;\n this.namespaceURI = parent.namespaceURI;\n this._next = null;\n this._parent = parent;\n this.__data__ = datum;\n}\n\nEnterNode.prototype = {\n constructor: EnterNode,\n appendChild: function(child) { return this._parent.insertBefore(child, this._next); },\n insertBefore: function(child, next) { return this._parent.insertBefore(child, next); },\n querySelector: function(selector) { return this._parent.querySelector(selector); },\n querySelectorAll: function(selector) { return this._parent.querySelectorAll(selector); }\n};\n","import sparse from \"./sparse\";\nimport {Selection} from \"./index\";\n\nexport default function() {\n return new Selection(this._exit || this._groups.map(sparse), this._parents);\n}\n","import {Selection} from \"./index\";\nimport matcher from \"../matcher\";\n\nexport default function(match) {\n if (typeof match !== \"function\") match = matcher(match);\n\n for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {\n for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {\n if ((node = group[i]) && match.call(node, node.__data__, i, group)) {\n subgroup.push(node);\n }\n }\n }\n\n return new Selection(subgroups, this._parents);\n}\n","function htmlRemove() {\n this.innerHTML = \"\";\n}\n\nfunction htmlConstant(value) {\n return function() {\n this.innerHTML = value;\n };\n}\n\nfunction htmlFunction(value) {\n return function() {\n var v = value.apply(this, arguments);\n this.innerHTML = v == null ? \"\" : v;\n };\n}\n\nexport default function(value) {\n return arguments.length\n ? this.each(value == null\n ? htmlRemove : (typeof value === \"function\"\n ? htmlFunction\n : htmlConstant)(value))\n : this.node().innerHTML;\n}\n","import selection_select from \"./select\";\nimport selection_selectAll from \"./selectAll\";\nimport selection_filter from \"./filter\";\nimport selection_data from \"./data\";\nimport selection_enter from \"./enter\";\nimport selection_exit from \"./exit\";\nimport selection_join from \"./join\";\nimport selection_merge from \"./merge\";\nimport selection_order from \"./order\";\nimport selection_sort from \"./sort\";\nimport selection_call from \"./call\";\nimport selection_nodes from \"./nodes\";\nimport selection_node from \"./node\";\nimport selection_size from \"./size\";\nimport selection_empty from \"./empty\";\nimport selection_each from \"./each\";\nimport selection_attr from \"./attr\";\nimport selection_style from \"./style\";\nimport selection_property from \"./property\";\nimport selection_classed from \"./classed\";\nimport selection_text from \"./text\";\nimport selection_html from \"./html\";\nimport selection_raise from \"./raise\";\nimport selection_lower from \"./lower\";\nimport selection_append from \"./append\";\nimport selection_insert from \"./insert\";\nimport selection_remove from \"./remove\";\nimport selection_clone from \"./clone\";\nimport selection_datum from \"./datum\";\nimport selection_on from \"./on\";\nimport selection_dispatch from \"./dispatch\";\n\nexport var root = [null];\n\nexport function Selection(groups, parents) {\n this._groups = groups;\n this._parents = parents;\n}\n\nfunction selection() {\n return new Selection([[document.documentElement]], root);\n}\n\nSelection.prototype = selection.prototype = {\n constructor: Selection,\n select: selection_select,\n selectAll: selection_selectAll,\n filter: selection_filter,\n data: selection_data,\n enter: selection_enter,\n exit: selection_exit,\n join: selection_join,\n merge: selection_merge,\n order: selection_order,\n sort: selection_sort,\n call: selection_call,\n nodes: selection_nodes,\n node: selection_node,\n size: selection_size,\n empty: selection_empty,\n each: selection_each,\n attr: selection_attr,\n style: selection_style,\n property: selection_property,\n classed: selection_classed,\n text: selection_text,\n html: selection_html,\n raise: selection_raise,\n lower: selection_lower,\n append: selection_append,\n insert: selection_insert,\n remove: selection_remove,\n clone: selection_clone,\n datum: selection_datum,\n on: selection_on,\n dispatch: selection_dispatch\n};\n\nexport default selection;\n","import creator from \"../creator\";\nimport selector from \"../selector\";\n\nfunction constantNull() {\n return null;\n}\n\nexport default function(name, before) {\n var create = typeof name === \"function\" ? name : creator(name),\n select = before == null ? constantNull : typeof before === \"function\" ? before : selector(before);\n return this.select(function() {\n return this.insertBefore(create.apply(this, arguments), select.apply(this, arguments) || null);\n });\n}\n","export default function(onenter, onupdate, onexit) {\n var enter = this.enter(), update = this, exit = this.exit();\n enter = typeof onenter === \"function\" ? onenter(enter) : enter.append(onenter + \"\");\n if (onupdate != null) update = onupdate(update);\n if (onexit == null) exit.remove(); else onexit(exit);\n return enter && update ? enter.merge(update).order() : update;\n}\n","function lower() {\n if (this.previousSibling) this.parentNode.insertBefore(this, this.parentNode.firstChild);\n}\n\nexport default function() {\n return this.each(lower);\n}\n","import {Selection} from \"./index\";\n\nexport default function(selection) {\n\n for (var groups0 = this._groups, groups1 = selection._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {\n for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {\n if (node = group0[i] || group1[i]) {\n merge[i] = node;\n }\n }\n }\n\n for (; j < m0; ++j) {\n merges[j] = groups0[j];\n }\n\n return new Selection(merges, this._parents);\n}\n","export default function() {\n\n for (var groups = this._groups, j = 0, m = groups.length; j < m; ++j) {\n for (var group = groups[j], i = 0, n = group.length; i < n; ++i) {\n var node = group[i];\n if (node) return node;\n }\n }\n\n return null;\n}\n","export default function() {\n var nodes = new Array(this.size()), i = -1;\n this.each(function() { nodes[++i] = this; });\n return nodes;\n}\n","var filterEvents = {};\n\nexport var event = null;\n\nif (typeof document !== \"undefined\") {\n var element = document.documentElement;\n if (!(\"onmouseenter\" in element)) {\n filterEvents = {mouseenter: \"mouseover\", mouseleave: \"mouseout\"};\n }\n}\n\nfunction filterContextListener(listener, index, group) {\n listener = contextListener(listener, index, group);\n return function(event) {\n var related = event.relatedTarget;\n if (!related || (related !== this && !(related.compareDocumentPosition(this) & 8))) {\n listener.call(this, event);\n }\n };\n}\n\nfunction contextListener(listener, index, group) {\n return function(event1) {\n var event0 = event; // Events can be reentrant (e.g., focus).\n event = event1;\n try {\n listener.call(this, this.__data__, index, group);\n } finally {\n event = event0;\n }\n };\n}\n\nfunction parseTypenames(typenames) {\n return typenames.trim().split(/^|\\s+/).map(function(t) {\n var name = \"\", i = t.indexOf(\".\");\n if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i);\n return {type: t, name: name};\n });\n}\n\nfunction onRemove(typename) {\n return function() {\n var on = this.__on;\n if (!on) return;\n for (var j = 0, i = -1, m = on.length, o; j < m; ++j) {\n if (o = on[j], (!typename.type || o.type === typename.type) && o.name === typename.name) {\n this.removeEventListener(o.type, o.listener, o.capture);\n } else {\n on[++i] = o;\n }\n }\n if (++i) on.length = i;\n else delete this.__on;\n };\n}\n\nfunction onAdd(typename, value, capture) {\n var wrap = filterEvents.hasOwnProperty(typename.type) ? filterContextListener : contextListener;\n return function(d, i, group) {\n var on = this.__on, o, listener = wrap(value, i, group);\n if (on) for (var j = 0, m = on.length; j < m; ++j) {\n if ((o = on[j]).type === typename.type && o.name === typename.name) {\n this.removeEventListener(o.type, o.listener, o.capture);\n this.addEventListener(o.type, o.listener = listener, o.capture = capture);\n o.value = value;\n return;\n }\n }\n this.addEventListener(typename.type, listener, capture);\n o = {type: typename.type, name: typename.name, value: value, listener: listener, capture: capture};\n if (!on) this.__on = [o];\n else on.push(o);\n };\n}\n\nexport default function(typename, value, capture) {\n var typenames = parseTypenames(typename + \"\"), i, n = typenames.length, t;\n\n if (arguments.length < 2) {\n var on = this.node().__on;\n if (on) for (var j = 0, m = on.length, o; j < m; ++j) {\n for (i = 0, o = on[j]; i < n; ++i) {\n if ((t = typenames[i]).type === o.type && t.name === o.name) {\n return o.value;\n }\n }\n }\n return;\n }\n\n on = value ? onAdd : onRemove;\n if (capture == null) capture = false;\n for (i = 0; i < n; ++i) this.each(on(typenames[i], value, capture));\n return this;\n}\n\nexport function customEvent(event1, listener, that, args) {\n var event0 = event;\n event1.sourceEvent = event;\n event = event1;\n try {\n return listener.apply(that, args);\n } finally {\n event = event0;\n }\n}\n","export default function() {\n\n for (var groups = this._groups, j = -1, m = groups.length; ++j < m;) {\n for (var group = groups[j], i = group.length - 1, next = group[i], node; --i >= 0;) {\n if (node = group[i]) {\n if (next && node.compareDocumentPosition(next) ^ 4) next.parentNode.insertBefore(node, next);\n next = node;\n }\n }\n }\n\n return this;\n}\n","function propertyRemove(name) {\n return function() {\n delete this[name];\n };\n}\n\nfunction propertyConstant(name, value) {\n return function() {\n this[name] = value;\n };\n}\n\nfunction propertyFunction(name, value) {\n return function() {\n var v = value.apply(this, arguments);\n if (v == null) delete this[name];\n else this[name] = v;\n };\n}\n\nexport default function(name, value) {\n return arguments.length > 1\n ? this.each((value == null\n ? propertyRemove : typeof value === \"function\"\n ? propertyFunction\n : propertyConstant)(name, value))\n : this.node()[name];\n}\n","function raise() {\n if (this.nextSibling) this.parentNode.appendChild(this);\n}\n\nexport default function() {\n return this.each(raise);\n}\n","function remove() {\n var parent = this.parentNode;\n if (parent) parent.removeChild(this);\n}\n\nexport default function() {\n return this.each(remove);\n}\n","import {Selection} from \"./index\";\nimport selector from \"../selector\";\n\nexport default function(select) {\n if (typeof select !== \"function\") select = selector(select);\n\n for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {\n for (var group = groups[j], n = group.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {\n if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {\n if (\"__data__\" in node) subnode.__data__ = node.__data__;\n subgroup[i] = subnode;\n }\n }\n }\n\n return new Selection(subgroups, this._parents);\n}\n","import {Selection} from \"./index\";\nimport selectorAll from \"../selectorAll\";\n\nexport default function(select) {\n if (typeof select !== \"function\") select = selectorAll(select);\n\n for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {\n for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {\n if (node = group[i]) {\n subgroups.push(select.call(node, node.__data__, i, group));\n parents.push(node);\n }\n }\n }\n\n return new Selection(subgroups, parents);\n}\n","export default function() {\n var size = 0;\n this.each(function() { ++size; });\n return size;\n}\n","import {Selection} from \"./index\";\n\nexport default function(compare) {\n if (!compare) compare = ascending;\n\n function compareNode(a, b) {\n return a && b ? compare(a.__data__, b.__data__) : !a - !b;\n }\n\n for (var groups = this._groups, m = groups.length, sortgroups = new Array(m), j = 0; j < m; ++j) {\n for (var group = groups[j], n = group.length, sortgroup = sortgroups[j] = new Array(n), node, i = 0; i < n; ++i) {\n if (node = group[i]) {\n sortgroup[i] = node;\n }\n }\n sortgroup.sort(compareNode);\n }\n\n return new Selection(sortgroups, this._parents).order();\n}\n\nfunction ascending(a, b) {\n return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n","export default function(update) {\n return new Array(update.length);\n}\n","import defaultView from \"../window\";\n\nfunction styleRemove(name) {\n return function() {\n this.style.removeProperty(name);\n };\n}\n\nfunction styleConstant(name, value, priority) {\n return function() {\n this.style.setProperty(name, value, priority);\n };\n}\n\nfunction styleFunction(name, value, priority) {\n return function() {\n var v = value.apply(this, arguments);\n if (v == null) this.style.removeProperty(name);\n else this.style.setProperty(name, v, priority);\n };\n}\n\nexport default function(name, value, priority) {\n return arguments.length > 1\n ? this.each((value == null\n ? styleRemove : typeof value === \"function\"\n ? styleFunction\n : styleConstant)(name, value, priority == null ? \"\" : priority))\n : styleValue(this.node(), name);\n}\n\nexport function styleValue(node, name) {\n return node.style.getPropertyValue(name)\n || defaultView(node).getComputedStyle(node, null).getPropertyValue(name);\n}\n","function textRemove() {\n this.textContent = \"\";\n}\n\nfunction textConstant(value) {\n return function() {\n this.textContent = value;\n };\n}\n\nfunction textFunction(value) {\n return function() {\n var v = value.apply(this, arguments);\n this.textContent = v == null ? \"\" : v;\n };\n}\n\nexport default function(value) {\n return arguments.length\n ? this.each(value == null\n ? textRemove : (typeof value === \"function\"\n ? textFunction\n : textConstant)(value))\n : this.node().textContent;\n}\n","function none() {}\n\nexport default function(selector) {\n return selector == null ? none : function() {\n return this.querySelector(selector);\n };\n}\n","function empty() {\n return [];\n}\n\nexport default function(selector) {\n return selector == null ? empty : function() {\n return this.querySelectorAll(selector);\n };\n}\n","import {event} from \"./selection/on\";\n\nexport default function() {\n var current = event, source;\n while (source = current.sourceEvent) current = source;\n return current;\n}\n","import sourceEvent from \"./sourceEvent\";\nimport point from \"./point\";\n\nexport default function(node, touches, identifier) {\n if (arguments.length < 3) identifier = touches, touches = sourceEvent().changedTouches;\n\n for (var i = 0, n = touches ? touches.length : 0, touch; i < n; ++i) {\n if ((touch = touches[i]).identifier === identifier) {\n return point(node, touch);\n }\n }\n\n return null;\n}\n","import sourceEvent from \"./sourceEvent\";\nimport point from \"./point\";\n\nexport default function(node, touches) {\n if (touches == null) touches = sourceEvent().touches;\n\n for (var i = 0, n = touches ? touches.length : 0, points = new Array(n); i < n; ++i) {\n points[i] = point(node, touches[i]);\n }\n\n return points;\n}\n","export default function(node) {\n return (node.ownerDocument && node.ownerDocument.defaultView) // node is a Node\n || (node.document && node) // node is a Window\n || node.defaultView; // node is a Document\n}\n","import {path} from \"d3-path\";\nimport constant from \"./constant.js\";\nimport {abs, acos, asin, atan2, cos, epsilon, halfPi, max, min, pi, sin, sqrt, tau} from \"./math.js\";\n\nfunction arcInnerRadius(d) {\n return d.innerRadius;\n}\n\nfunction arcOuterRadius(d) {\n return d.outerRadius;\n}\n\nfunction arcStartAngle(d) {\n return d.startAngle;\n}\n\nfunction arcEndAngle(d) {\n return d.endAngle;\n}\n\nfunction arcPadAngle(d) {\n return d && d.padAngle; // Note: optional!\n}\n\nfunction intersect(x0, y0, x1, y1, x2, y2, x3, y3) {\n var x10 = x1 - x0, y10 = y1 - y0,\n x32 = x3 - x2, y32 = y3 - y2,\n t = y32 * x10 - x32 * y10;\n if (t * t < epsilon) return;\n t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / t;\n return [x0 + t * x10, y0 + t * y10];\n}\n\n// Compute perpendicular offset line of length rc.\n// http://mathworld.wolfram.com/Circle-LineIntersection.html\nfunction cornerTangents(x0, y0, x1, y1, r1, rc, cw) {\n var x01 = x0 - x1,\n y01 = y0 - y1,\n lo = (cw ? rc : -rc) / sqrt(x01 * x01 + y01 * y01),\n ox = lo * y01,\n oy = -lo * x01,\n x11 = x0 + ox,\n y11 = y0 + oy,\n x10 = x1 + ox,\n y10 = y1 + oy,\n x00 = (x11 + x10) / 2,\n y00 = (y11 + y10) / 2,\n dx = x10 - x11,\n dy = y10 - y11,\n d2 = dx * dx + dy * dy,\n r = r1 - rc,\n D = x11 * y10 - x10 * y11,\n d = (dy < 0 ? -1 : 1) * sqrt(max(0, r * r * d2 - D * D)),\n cx0 = (D * dy - dx * d) / d2,\n cy0 = (-D * dx - dy * d) / d2,\n cx1 = (D * dy + dx * d) / d2,\n cy1 = (-D * dx + dy * d) / d2,\n dx0 = cx0 - x00,\n dy0 = cy0 - y00,\n dx1 = cx1 - x00,\n dy1 = cy1 - y00;\n\n // Pick the closer of the two intersection points.\n // TODO Is there a faster way to determine which intersection to use?\n if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;\n\n return {\n cx: cx0,\n cy: cy0,\n x01: -ox,\n y01: -oy,\n x11: cx0 * (r1 / r - 1),\n y11: cy0 * (r1 / r - 1)\n };\n}\n\nexport default function() {\n var innerRadius = arcInnerRadius,\n outerRadius = arcOuterRadius,\n cornerRadius = constant(0),\n padRadius = null,\n startAngle = arcStartAngle,\n endAngle = arcEndAngle,\n padAngle = arcPadAngle,\n context = null;\n\n function arc() {\n var buffer,\n r,\n r0 = +innerRadius.apply(this, arguments),\n r1 = +outerRadius.apply(this, arguments),\n a0 = startAngle.apply(this, arguments) - halfPi,\n a1 = endAngle.apply(this, arguments) - halfPi,\n da = abs(a1 - a0),\n cw = a1 > a0;\n\n if (!context) context = buffer = path();\n\n // Ensure that the outer radius is always larger than the inner radius.\n if (r1 < r0) r = r1, r1 = r0, r0 = r;\n\n // Is it a point?\n if (!(r1 > epsilon)) context.moveTo(0, 0);\n\n // Or is it a circle or annulus?\n else if (da > tau - epsilon) {\n context.moveTo(r1 * cos(a0), r1 * sin(a0));\n context.arc(0, 0, r1, a0, a1, !cw);\n if (r0 > epsilon) {\n context.moveTo(r0 * cos(a1), r0 * sin(a1));\n context.arc(0, 0, r0, a1, a0, cw);\n }\n }\n\n // Or is it a circular or annular sector?\n else {\n var a01 = a0,\n a11 = a1,\n a00 = a0,\n a10 = a1,\n da0 = da,\n da1 = da,\n ap = padAngle.apply(this, arguments) / 2,\n rp = (ap > epsilon) && (padRadius ? +padRadius.apply(this, arguments) : sqrt(r0 * r0 + r1 * r1)),\n rc = min(abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)),\n rc0 = rc,\n rc1 = rc,\n t0,\n t1;\n\n // Apply padding? Note that since r1 ≥ r0, da1 ≥ da0.\n if (rp > epsilon) {\n var p0 = asin(rp / r0 * sin(ap)),\n p1 = asin(rp / r1 * sin(ap));\n if ((da0 -= p0 * 2) > epsilon) p0 *= (cw ? 1 : -1), a00 += p0, a10 -= p0;\n else da0 = 0, a00 = a10 = (a0 + a1) / 2;\n if ((da1 -= p1 * 2) > epsilon) p1 *= (cw ? 1 : -1), a01 += p1, a11 -= p1;\n else da1 = 0, a01 = a11 = (a0 + a1) / 2;\n }\n\n var x01 = r1 * cos(a01),\n y01 = r1 * sin(a01),\n x10 = r0 * cos(a10),\n y10 = r0 * sin(a10);\n\n // Apply rounded corners?\n if (rc > epsilon) {\n var x11 = r1 * cos(a11),\n y11 = r1 * sin(a11),\n x00 = r0 * cos(a00),\n y00 = r0 * sin(a00),\n oc;\n\n // Restrict the corner radius according to the sector angle.\n if (da < pi && (oc = intersect(x01, y01, x00, y00, x11, y11, x10, y10))) {\n var ax = x01 - oc[0],\n ay = y01 - oc[1],\n bx = x11 - oc[0],\n by = y11 - oc[1],\n kc = 1 / sin(acos((ax * bx + ay * by) / (sqrt(ax * ax + ay * ay) * sqrt(bx * bx + by * by))) / 2),\n lc = sqrt(oc[0] * oc[0] + oc[1] * oc[1]);\n rc0 = min(rc, (r0 - lc) / (kc - 1));\n rc1 = min(rc, (r1 - lc) / (kc + 1));\n }\n }\n\n // Is the sector collapsed to a line?\n if (!(da1 > epsilon)) context.moveTo(x01, y01);\n\n // Does the sector’s outer ring have rounded corners?\n else if (rc1 > epsilon) {\n t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw);\n t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw);\n\n context.moveTo(t0.cx + t0.x01, t0.cy + t0.y01);\n\n // Have the corners merged?\n if (rc1 < rc) context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);\n\n // Otherwise, draw the two corners and the ring.\n else {\n context.arc(t0.cx, t0.cy, rc1, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);\n context.arc(0, 0, r1, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), !cw);\n context.arc(t1.cx, t1.cy, rc1, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);\n }\n }\n\n // Or is the outer ring just a circular arc?\n else context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw);\n\n // Is there no inner ring, and it’s a circular sector?\n // Or perhaps it’s an annular sector collapsed due to padding?\n if (!(r0 > epsilon) || !(da0 > epsilon)) context.lineTo(x10, y10);\n\n // Does the sector’s inner ring (or point) have rounded corners?\n else if (rc0 > epsilon) {\n t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw);\n t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw);\n\n context.lineTo(t0.cx + t0.x01, t0.cy + t0.y01);\n\n // Have the corners merged?\n if (rc0 < rc) context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t1.y01, t1.x01), !cw);\n\n // Otherwise, draw the two corners and the ring.\n else {\n context.arc(t0.cx, t0.cy, rc0, atan2(t0.y01, t0.x01), atan2(t0.y11, t0.x11), !cw);\n context.arc(0, 0, r0, atan2(t0.cy + t0.y11, t0.cx + t0.x11), atan2(t1.cy + t1.y11, t1.cx + t1.x11), cw);\n context.arc(t1.cx, t1.cy, rc0, atan2(t1.y11, t1.x11), atan2(t1.y01, t1.x01), !cw);\n }\n }\n\n // Or is the inner ring just a circular arc?\n else context.arc(0, 0, r0, a10, a00, cw);\n }\n\n context.closePath();\n\n if (buffer) return context = null, buffer + \"\" || null;\n }\n\n arc.centroid = function() {\n var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2,\n a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi / 2;\n return [cos(a) * r, sin(a) * r];\n };\n\n arc.innerRadius = function(_) {\n return arguments.length ? (innerRadius = typeof _ === \"function\" ? _ : constant(+_), arc) : innerRadius;\n };\n\n arc.outerRadius = function(_) {\n return arguments.length ? (outerRadius = typeof _ === \"function\" ? _ : constant(+_), arc) : outerRadius;\n };\n\n arc.cornerRadius = function(_) {\n return arguments.length ? (cornerRadius = typeof _ === \"function\" ? _ : constant(+_), arc) : cornerRadius;\n };\n\n arc.padRadius = function(_) {\n return arguments.length ? (padRadius = _ == null ? null : typeof _ === \"function\" ? _ : constant(+_), arc) : padRadius;\n };\n\n arc.startAngle = function(_) {\n return arguments.length ? (startAngle = typeof _ === \"function\" ? _ : constant(+_), arc) : startAngle;\n };\n\n arc.endAngle = function(_) {\n return arguments.length ? (endAngle = typeof _ === \"function\" ? _ : constant(+_), arc) : endAngle;\n };\n\n arc.padAngle = function(_) {\n return arguments.length ? (padAngle = typeof _ === \"function\" ? _ : constant(+_), arc) : padAngle;\n };\n\n arc.context = function(_) {\n return arguments.length ? ((context = _ == null ? null : _), arc) : context;\n };\n\n return arc;\n}\n","import {path} from \"d3-path\";\nimport constant from \"./constant.js\";\nimport curveLinear from \"./curve/linear.js\";\nimport line from \"./line.js\";\nimport {x as pointX, y as pointY} from \"./point.js\";\n\nexport default function() {\n var x0 = pointX,\n x1 = null,\n y0 = constant(0),\n y1 = pointY,\n defined = constant(true),\n context = null,\n curve = curveLinear,\n output = null;\n\n function area(data) {\n var i,\n j,\n k,\n n = data.length,\n d,\n defined0 = false,\n buffer,\n x0z = new Array(n),\n y0z = new Array(n);\n\n if (context == null) output = curve(buffer = path());\n\n for (i = 0; i <= n; ++i) {\n if (!(i < n && defined(d = data[i], i, data)) === defined0) {\n if (defined0 = !defined0) {\n j = i;\n output.areaStart();\n output.lineStart();\n } else {\n output.lineEnd();\n output.lineStart();\n for (k = i - 1; k >= j; --k) {\n output.point(x0z[k], y0z[k]);\n }\n output.lineEnd();\n output.areaEnd();\n }\n }\n if (defined0) {\n x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data);\n output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]);\n }\n }\n\n if (buffer) return output = null, buffer + \"\" || null;\n }\n\n function arealine() {\n return line().defined(defined).curve(curve).context(context);\n }\n\n area.x = function(_) {\n return arguments.length ? (x0 = typeof _ === \"function\" ? _ : constant(+_), x1 = null, area) : x0;\n };\n\n area.x0 = function(_) {\n return arguments.length ? (x0 = typeof _ === \"function\" ? _ : constant(+_), area) : x0;\n };\n\n area.x1 = function(_) {\n return arguments.length ? (x1 = _ == null ? null : typeof _ === \"function\" ? _ : constant(+_), area) : x1;\n };\n\n area.y = function(_) {\n return arguments.length ? (y0 = typeof _ === \"function\" ? _ : constant(+_), y1 = null, area) : y0;\n };\n\n area.y0 = function(_) {\n return arguments.length ? (y0 = typeof _ === \"function\" ? _ : constant(+_), area) : y0;\n };\n\n area.y1 = function(_) {\n return arguments.length ? (y1 = _ == null ? null : typeof _ === \"function\" ? _ : constant(+_), area) : y1;\n };\n\n area.lineX0 =\n area.lineY0 = function() {\n return arealine().x(x0).y(y0);\n };\n\n area.lineY1 = function() {\n return arealine().x(x0).y(y1);\n };\n\n area.lineX1 = function() {\n return arealine().x(x1).y(y0);\n };\n\n area.defined = function(_) {\n return arguments.length ? (defined = typeof _ === \"function\" ? _ : constant(!!_), area) : defined;\n };\n\n area.curve = function(_) {\n return arguments.length ? (curve = _, context != null && (output = curve(context)), area) : curve;\n };\n\n area.context = function(_) {\n return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), area) : context;\n };\n\n return area;\n}\n","import curveRadial, {curveRadialLinear} from \"./curve/radial.js\";\nimport area from \"./area.js\";\nimport {lineRadial} from \"./lineRadial.js\";\n\nexport default function() {\n var a = area().curve(curveRadialLinear),\n c = a.curve,\n x0 = a.lineX0,\n x1 = a.lineX1,\n y0 = a.lineY0,\n y1 = a.lineY1;\n\n a.angle = a.x, delete a.x;\n a.startAngle = a.x0, delete a.x0;\n a.endAngle = a.x1, delete a.x1;\n a.radius = a.y, delete a.y;\n a.innerRadius = a.y0, delete a.y0;\n a.outerRadius = a.y1, delete a.y1;\n a.lineStartAngle = function() { return lineRadial(x0()); }, delete a.lineX0;\n a.lineEndAngle = function() { return lineRadial(x1()); }, delete a.lineX1;\n a.lineInnerRadius = function() { return lineRadial(y0()); }, delete a.lineY0;\n a.lineOuterRadius = function() { return lineRadial(y1()); }, delete a.lineY1;\n\n a.curve = function(_) {\n return arguments.length ? c(curveRadial(_)) : c()._curve;\n };\n\n return a;\n}\n","export var slice = Array.prototype.slice;\n","export default function(x) {\n return function constant() {\n return x;\n };\n}\n","export function point(that, x, y) {\n that._context.bezierCurveTo(\n (2 * that._x0 + that._x1) / 3,\n (2 * that._y0 + that._y1) / 3,\n (that._x0 + 2 * that._x1) / 3,\n (that._y0 + 2 * that._y1) / 3,\n (that._x0 + 4 * that._x1 + x) / 6,\n (that._y0 + 4 * that._y1 + y) / 6\n );\n}\n\nexport function Basis(context) {\n this._context = context;\n}\n\nBasis.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 =\n this._y0 = this._y1 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 3: point(this, this._x1, this._y1); // proceed\n case 2: this._context.lineTo(this._x1, this._y1); break;\n }\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6); // proceed\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = x;\n this._y0 = this._y1, this._y1 = y;\n }\n};\n\nexport default function(context) {\n return new Basis(context);\n}\n","import noop from \"../noop.js\";\nimport {point} from \"./basis.js\";\n\nfunction BasisClosed(context) {\n this._context = context;\n}\n\nBasisClosed.prototype = {\n areaStart: noop,\n areaEnd: noop,\n lineStart: function() {\n this._x0 = this._x1 = this._x2 = this._x3 = this._x4 =\n this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 1: {\n this._context.moveTo(this._x2, this._y2);\n this._context.closePath();\n break;\n }\n case 2: {\n this._context.moveTo((this._x2 + 2 * this._x3) / 3, (this._y2 + 2 * this._y3) / 3);\n this._context.lineTo((this._x3 + 2 * this._x2) / 3, (this._y3 + 2 * this._y2) / 3);\n this._context.closePath();\n break;\n }\n case 3: {\n this.point(this._x2, this._y2);\n this.point(this._x3, this._y3);\n this.point(this._x4, this._y4);\n break;\n }\n }\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._x2 = x, this._y2 = y; break;\n case 1: this._point = 2; this._x3 = x, this._y3 = y; break;\n case 2: this._point = 3; this._x4 = x, this._y4 = y; this._context.moveTo((this._x0 + 4 * this._x1 + x) / 6, (this._y0 + 4 * this._y1 + y) / 6); break;\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = x;\n this._y0 = this._y1, this._y1 = y;\n }\n};\n\nexport default function(context) {\n return new BasisClosed(context);\n}\n","import {point} from \"./basis.js\";\n\nfunction BasisOpen(context) {\n this._context = context;\n}\n\nBasisOpen.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 =\n this._y0 = this._y1 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; var x0 = (this._x0 + 4 * this._x1 + x) / 6, y0 = (this._y0 + 4 * this._y1 + y) / 6; this._line ? this._context.lineTo(x0, y0) : this._context.moveTo(x0, y0); break;\n case 3: this._point = 4; // proceed\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = x;\n this._y0 = this._y1, this._y1 = y;\n }\n};\n\nexport default function(context) {\n return new BasisOpen(context);\n}\n","import {Basis} from \"./basis.js\";\n\nfunction Bundle(context, beta) {\n this._basis = new Basis(context);\n this._beta = beta;\n}\n\nBundle.prototype = {\n lineStart: function() {\n this._x = [];\n this._y = [];\n this._basis.lineStart();\n },\n lineEnd: function() {\n var x = this._x,\n y = this._y,\n j = x.length - 1;\n\n if (j > 0) {\n var x0 = x[0],\n y0 = y[0],\n dx = x[j] - x0,\n dy = y[j] - y0,\n i = -1,\n t;\n\n while (++i <= j) {\n t = i / j;\n this._basis.point(\n this._beta * x[i] + (1 - this._beta) * (x0 + t * dx),\n this._beta * y[i] + (1 - this._beta) * (y0 + t * dy)\n );\n }\n }\n\n this._x = this._y = null;\n this._basis.lineEnd();\n },\n point: function(x, y) {\n this._x.push(+x);\n this._y.push(+y);\n }\n};\n\nexport default (function custom(beta) {\n\n function bundle(context) {\n return beta === 1 ? new Basis(context) : new Bundle(context, beta);\n }\n\n bundle.beta = function(beta) {\n return custom(+beta);\n };\n\n return bundle;\n})(0.85);\n","export function point(that, x, y) {\n that._context.bezierCurveTo(\n that._x1 + that._k * (that._x2 - that._x0),\n that._y1 + that._k * (that._y2 - that._y0),\n that._x2 + that._k * (that._x1 - x),\n that._y2 + that._k * (that._y1 - y),\n that._x2,\n that._y2\n );\n}\n\nexport function Cardinal(context, tension) {\n this._context = context;\n this._k = (1 - tension) / 6;\n}\n\nCardinal.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 = this._x2 =\n this._y0 = this._y1 = this._y2 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 2: this._context.lineTo(this._x2, this._y2); break;\n case 3: point(this, this._x1, this._y1); break;\n }\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; this._x1 = x, this._y1 = y; break;\n case 2: this._point = 3; // proceed\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;\n this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;\n }\n};\n\nexport default (function custom(tension) {\n\n function cardinal(context) {\n return new Cardinal(context, tension);\n }\n\n cardinal.tension = function(tension) {\n return custom(+tension);\n };\n\n return cardinal;\n})(0);\n","import noop from \"../noop.js\";\nimport {point} from \"./cardinal.js\";\n\nexport function CardinalClosed(context, tension) {\n this._context = context;\n this._k = (1 - tension) / 6;\n}\n\nCardinalClosed.prototype = {\n areaStart: noop,\n areaEnd: noop,\n lineStart: function() {\n this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 =\n this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 1: {\n this._context.moveTo(this._x3, this._y3);\n this._context.closePath();\n break;\n }\n case 2: {\n this._context.lineTo(this._x3, this._y3);\n this._context.closePath();\n break;\n }\n case 3: {\n this.point(this._x3, this._y3);\n this.point(this._x4, this._y4);\n this.point(this._x5, this._y5);\n break;\n }\n }\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._x3 = x, this._y3 = y; break;\n case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break;\n case 2: this._point = 3; this._x5 = x, this._y5 = y; break;\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;\n this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;\n }\n};\n\nexport default (function custom(tension) {\n\n function cardinal(context) {\n return new CardinalClosed(context, tension);\n }\n\n cardinal.tension = function(tension) {\n return custom(+tension);\n };\n\n return cardinal;\n})(0);\n","import {point} from \"./cardinal.js\";\n\nexport function CardinalOpen(context, tension) {\n this._context = context;\n this._k = (1 - tension) / 6;\n}\n\nCardinalOpen.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 = this._x2 =\n this._y0 = this._y1 = this._y2 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break;\n case 3: this._point = 4; // proceed\n default: point(this, x, y); break;\n }\n this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;\n this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;\n }\n};\n\nexport default (function custom(tension) {\n\n function cardinal(context) {\n return new CardinalOpen(context, tension);\n }\n\n cardinal.tension = function(tension) {\n return custom(+tension);\n };\n\n return cardinal;\n})(0);\n","import {epsilon} from \"../math.js\";\nimport {Cardinal} from \"./cardinal.js\";\n\nexport function point(that, x, y) {\n var x1 = that._x1,\n y1 = that._y1,\n x2 = that._x2,\n y2 = that._y2;\n\n if (that._l01_a > epsilon) {\n var a = 2 * that._l01_2a + 3 * that._l01_a * that._l12_a + that._l12_2a,\n n = 3 * that._l01_a * (that._l01_a + that._l12_a);\n x1 = (x1 * a - that._x0 * that._l12_2a + that._x2 * that._l01_2a) / n;\n y1 = (y1 * a - that._y0 * that._l12_2a + that._y2 * that._l01_2a) / n;\n }\n\n if (that._l23_a > epsilon) {\n var b = 2 * that._l23_2a + 3 * that._l23_a * that._l12_a + that._l12_2a,\n m = 3 * that._l23_a * (that._l23_a + that._l12_a);\n x2 = (x2 * b + that._x1 * that._l23_2a - x * that._l12_2a) / m;\n y2 = (y2 * b + that._y1 * that._l23_2a - y * that._l12_2a) / m;\n }\n\n that._context.bezierCurveTo(x1, y1, x2, y2, that._x2, that._y2);\n}\n\nfunction CatmullRom(context, alpha) {\n this._context = context;\n this._alpha = alpha;\n}\n\nCatmullRom.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 = this._x2 =\n this._y0 = this._y1 = this._y2 = NaN;\n this._l01_a = this._l12_a = this._l23_a =\n this._l01_2a = this._l12_2a = this._l23_2a =\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 2: this._context.lineTo(this._x2, this._y2); break;\n case 3: this.point(this._x2, this._y2); break;\n }\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n\n if (this._point) {\n var x23 = this._x2 - x,\n y23 = this._y2 - y;\n this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));\n }\n\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; // proceed\n default: point(this, x, y); break;\n }\n\n this._l01_a = this._l12_a, this._l12_a = this._l23_a;\n this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;\n this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;\n this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;\n }\n};\n\nexport default (function custom(alpha) {\n\n function catmullRom(context) {\n return alpha ? new CatmullRom(context, alpha) : new Cardinal(context, 0);\n }\n\n catmullRom.alpha = function(alpha) {\n return custom(+alpha);\n };\n\n return catmullRom;\n})(0.5);\n","import {CardinalClosed} from \"./cardinalClosed.js\";\nimport noop from \"../noop.js\";\nimport {point} from \"./catmullRom.js\";\n\nfunction CatmullRomClosed(context, alpha) {\n this._context = context;\n this._alpha = alpha;\n}\n\nCatmullRomClosed.prototype = {\n areaStart: noop,\n areaEnd: noop,\n lineStart: function() {\n this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 =\n this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN;\n this._l01_a = this._l12_a = this._l23_a =\n this._l01_2a = this._l12_2a = this._l23_2a =\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 1: {\n this._context.moveTo(this._x3, this._y3);\n this._context.closePath();\n break;\n }\n case 2: {\n this._context.lineTo(this._x3, this._y3);\n this._context.closePath();\n break;\n }\n case 3: {\n this.point(this._x3, this._y3);\n this.point(this._x4, this._y4);\n this.point(this._x5, this._y5);\n break;\n }\n }\n },\n point: function(x, y) {\n x = +x, y = +y;\n\n if (this._point) {\n var x23 = this._x2 - x,\n y23 = this._y2 - y;\n this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));\n }\n\n switch (this._point) {\n case 0: this._point = 1; this._x3 = x, this._y3 = y; break;\n case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break;\n case 2: this._point = 3; this._x5 = x, this._y5 = y; break;\n default: point(this, x, y); break;\n }\n\n this._l01_a = this._l12_a, this._l12_a = this._l23_a;\n this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;\n this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;\n this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;\n }\n};\n\nexport default (function custom(alpha) {\n\n function catmullRom(context) {\n return alpha ? new CatmullRomClosed(context, alpha) : new CardinalClosed(context, 0);\n }\n\n catmullRom.alpha = function(alpha) {\n return custom(+alpha);\n };\n\n return catmullRom;\n})(0.5);\n","import {CardinalOpen} from \"./cardinalOpen.js\";\nimport {point} from \"./catmullRom.js\";\n\nfunction CatmullRomOpen(context, alpha) {\n this._context = context;\n this._alpha = alpha;\n}\n\nCatmullRomOpen.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 = this._x2 =\n this._y0 = this._y1 = this._y2 = NaN;\n this._l01_a = this._l12_a = this._l23_a =\n this._l01_2a = this._l12_2a = this._l23_2a =\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n\n if (this._point) {\n var x23 = this._x2 - x,\n y23 = this._y2 - y;\n this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha));\n }\n\n switch (this._point) {\n case 0: this._point = 1; break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break;\n case 3: this._point = 4; // proceed\n default: point(this, x, y); break;\n }\n\n this._l01_a = this._l12_a, this._l12_a = this._l23_a;\n this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a;\n this._x0 = this._x1, this._x1 = this._x2, this._x2 = x;\n this._y0 = this._y1, this._y1 = this._y2, this._y2 = y;\n }\n};\n\nexport default (function custom(alpha) {\n\n function catmullRom(context) {\n return alpha ? new CatmullRomOpen(context, alpha) : new CardinalOpen(context, 0);\n }\n\n catmullRom.alpha = function(alpha) {\n return custom(+alpha);\n };\n\n return catmullRom;\n})(0.5);\n","function Linear(context) {\n this._context = context;\n}\n\nLinear.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._point = 0;\n },\n lineEnd: function() {\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; // proceed\n default: this._context.lineTo(x, y); break;\n }\n }\n};\n\nexport default function(context) {\n return new Linear(context);\n}\n","import noop from \"../noop.js\";\n\nfunction LinearClosed(context) {\n this._context = context;\n}\n\nLinearClosed.prototype = {\n areaStart: noop,\n areaEnd: noop,\n lineStart: function() {\n this._point = 0;\n },\n lineEnd: function() {\n if (this._point) this._context.closePath();\n },\n point: function(x, y) {\n x = +x, y = +y;\n if (this._point) this._context.lineTo(x, y);\n else this._point = 1, this._context.moveTo(x, y);\n }\n};\n\nexport default function(context) {\n return new LinearClosed(context);\n}\n","function sign(x) {\n return x < 0 ? -1 : 1;\n}\n\n// Calculate the slopes of the tangents (Hermite-type interpolation) based on\n// the following paper: Steffen, M. 1990. A Simple Method for Monotonic\n// Interpolation in One Dimension. Astronomy and Astrophysics, Vol. 239, NO.\n// NOV(II), P. 443, 1990.\nfunction slope3(that, x2, y2) {\n var h0 = that._x1 - that._x0,\n h1 = x2 - that._x1,\n s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0),\n s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0),\n p = (s0 * h1 + s1 * h0) / (h0 + h1);\n return (sign(s0) + sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0;\n}\n\n// Calculate a one-sided slope.\nfunction slope2(that, t) {\n var h = that._x1 - that._x0;\n return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t;\n}\n\n// According to https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Representations\n// \"you can express cubic Hermite interpolation in terms of cubic Bézier curves\n// with respect to the four values p0, p0 + m0 / 3, p1 - m1 / 3, p1\".\nfunction point(that, t0, t1) {\n var x0 = that._x0,\n y0 = that._y0,\n x1 = that._x1,\n y1 = that._y1,\n dx = (x1 - x0) / 3;\n that._context.bezierCurveTo(x0 + dx, y0 + dx * t0, x1 - dx, y1 - dx * t1, x1, y1);\n}\n\nfunction MonotoneX(context) {\n this._context = context;\n}\n\nMonotoneX.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x0 = this._x1 =\n this._y0 = this._y1 =\n this._t0 = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n switch (this._point) {\n case 2: this._context.lineTo(this._x1, this._y1); break;\n case 3: point(this, this._t0, slope2(this, this._t0)); break;\n }\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n this._line = 1 - this._line;\n },\n point: function(x, y) {\n var t1 = NaN;\n\n x = +x, y = +y;\n if (x === this._x1 && y === this._y1) return; // Ignore coincident points.\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; break;\n case 2: this._point = 3; point(this, slope2(this, t1 = slope3(this, x, y)), t1); break;\n default: point(this, this._t0, t1 = slope3(this, x, y)); break;\n }\n\n this._x0 = this._x1, this._x1 = x;\n this._y0 = this._y1, this._y1 = y;\n this._t0 = t1;\n }\n}\n\nfunction MonotoneY(context) {\n this._context = new ReflectContext(context);\n}\n\n(MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x, y) {\n MonotoneX.prototype.point.call(this, y, x);\n};\n\nfunction ReflectContext(context) {\n this._context = context;\n}\n\nReflectContext.prototype = {\n moveTo: function(x, y) { this._context.moveTo(y, x); },\n closePath: function() { this._context.closePath(); },\n lineTo: function(x, y) { this._context.lineTo(y, x); },\n bezierCurveTo: function(x1, y1, x2, y2, x, y) { this._context.bezierCurveTo(y1, x1, y2, x2, y, x); }\n};\n\nexport function monotoneX(context) {\n return new MonotoneX(context);\n}\n\nexport function monotoneY(context) {\n return new MonotoneY(context);\n}\n","function Natural(context) {\n this._context = context;\n}\n\nNatural.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x = [];\n this._y = [];\n },\n lineEnd: function() {\n var x = this._x,\n y = this._y,\n n = x.length;\n\n if (n) {\n this._line ? this._context.lineTo(x[0], y[0]) : this._context.moveTo(x[0], y[0]);\n if (n === 2) {\n this._context.lineTo(x[1], y[1]);\n } else {\n var px = controlPoints(x),\n py = controlPoints(y);\n for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) {\n this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x[i1], y[i1]);\n }\n }\n }\n\n if (this._line || (this._line !== 0 && n === 1)) this._context.closePath();\n this._line = 1 - this._line;\n this._x = this._y = null;\n },\n point: function(x, y) {\n this._x.push(+x);\n this._y.push(+y);\n }\n};\n\n// See https://www.particleincell.com/2012/bezier-splines/ for derivation.\nfunction controlPoints(x) {\n var i,\n n = x.length - 1,\n m,\n a = new Array(n),\n b = new Array(n),\n r = new Array(n);\n a[0] = 0, b[0] = 2, r[0] = x[0] + 2 * x[1];\n for (i = 1; i < n - 1; ++i) a[i] = 1, b[i] = 4, r[i] = 4 * x[i] + 2 * x[i + 1];\n a[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x[n - 1] + x[n];\n for (i = 1; i < n; ++i) m = a[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1];\n a[n - 1] = r[n - 1] / b[n - 1];\n for (i = n - 2; i >= 0; --i) a[i] = (r[i] - a[i + 1]) / b[i];\n b[n - 1] = (x[n] + a[n - 1]) / 2;\n for (i = 0; i < n - 1; ++i) b[i] = 2 * x[i + 1] - a[i + 1];\n return [a, b];\n}\n\nexport default function(context) {\n return new Natural(context);\n}\n","import curveLinear from \"./linear.js\";\n\nexport var curveRadialLinear = curveRadial(curveLinear);\n\nfunction Radial(curve) {\n this._curve = curve;\n}\n\nRadial.prototype = {\n areaStart: function() {\n this._curve.areaStart();\n },\n areaEnd: function() {\n this._curve.areaEnd();\n },\n lineStart: function() {\n this._curve.lineStart();\n },\n lineEnd: function() {\n this._curve.lineEnd();\n },\n point: function(a, r) {\n this._curve.point(r * Math.sin(a), r * -Math.cos(a));\n }\n};\n\nexport default function curveRadial(curve) {\n\n function radial(context) {\n return new Radial(curve(context));\n }\n\n radial._curve = curve;\n\n return radial;\n}\n","function Step(context, t) {\n this._context = context;\n this._t = t;\n}\n\nStep.prototype = {\n areaStart: function() {\n this._line = 0;\n },\n areaEnd: function() {\n this._line = NaN;\n },\n lineStart: function() {\n this._x = this._y = NaN;\n this._point = 0;\n },\n lineEnd: function() {\n if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y);\n if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();\n if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line;\n },\n point: function(x, y) {\n x = +x, y = +y;\n switch (this._point) {\n case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;\n case 1: this._point = 2; // proceed\n default: {\n if (this._t <= 0) {\n this._context.lineTo(this._x, y);\n this._context.lineTo(x, y);\n } else {\n var x1 = this._x * (1 - this._t) + x * this._t;\n this._context.lineTo(x1, this._y);\n this._context.lineTo(x1, y);\n }\n break;\n }\n }\n this._x = x, this._y = y;\n }\n};\n\nexport default function(context) {\n return new Step(context, 0.5);\n}\n\nexport function stepBefore(context) {\n return new Step(context, 0);\n}\n\nexport function stepAfter(context) {\n return new Step(context, 1);\n}\n","export default function(a, b) {\n return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;\n}\n","export default function(d) {\n return d;\n}\n","export {default as arc} from \"./arc.js\";\nexport {default as area} from \"./area.js\";\nexport {default as line} from \"./line.js\";\nexport {default as pie} from \"./pie.js\";\nexport {default as areaRadial, default as radialArea} from \"./areaRadial.js\"; // Note: radialArea is deprecated!\nexport {default as lineRadial, default as radialLine} from \"./lineRadial.js\"; // Note: radialLine is deprecated!\nexport {default as pointRadial} from \"./pointRadial.js\";\nexport {linkHorizontal, linkVertical, linkRadial} from \"./link/index.js\";\n\nexport {default as symbol, symbols} from \"./symbol.js\";\nexport {default as symbolCircle} from \"./symbol/circle.js\";\nexport {default as symbolCross} from \"./symbol/cross.js\";\nexport {default as symbolDiamond} from \"./symbol/diamond.js\";\nexport {default as symbolSquare} from \"./symbol/square.js\";\nexport {default as symbolStar} from \"./symbol/star.js\";\nexport {default as symbolTriangle} from \"./symbol/triangle.js\";\nexport {default as symbolWye} from \"./symbol/wye.js\";\n\nexport {default as curveBasisClosed} from \"./curve/basisClosed.js\";\nexport {default as curveBasisOpen} from \"./curve/basisOpen.js\";\nexport {default as curveBasis} from \"./curve/basis.js\";\nexport {default as curveBundle} from \"./curve/bundle.js\";\nexport {default as curveCardinalClosed} from \"./curve/cardinalClosed.js\";\nexport {default as curveCardinalOpen} from \"./curve/cardinalOpen.js\";\nexport {default as curveCardinal} from \"./curve/cardinal.js\";\nexport {default as curveCatmullRomClosed} from \"./curve/catmullRomClosed.js\";\nexport {default as curveCatmullRomOpen} from \"./curve/catmullRomOpen.js\";\nexport {default as curveCatmullRom} from \"./curve/catmullRom.js\";\nexport {default as curveLinearClosed} from \"./curve/linearClosed.js\";\nexport {default as curveLinear} from \"./curve/linear.js\";\nexport {monotoneX as curveMonotoneX, monotoneY as curveMonotoneY} from \"./curve/monotone.js\";\nexport {default as curveNatural} from \"./curve/natural.js\";\nexport {default as curveStep, stepAfter as curveStepAfter, stepBefore as curveStepBefore} from \"./curve/step.js\";\n\nexport {default as stack} from \"./stack.js\";\nexport {default as stackOffsetExpand} from \"./offset/expand.js\";\nexport {default as stackOffsetDiverging} from \"./offset/diverging.js\";\nexport {default as stackOffsetNone} from \"./offset/none.js\";\nexport {default as stackOffsetSilhouette} from \"./offset/silhouette.js\";\nexport {default as stackOffsetWiggle} from \"./offset/wiggle.js\";\nexport {default as stackOrderAppearance} from \"./order/appearance.js\";\nexport {default as stackOrderAscending} from \"./order/ascending.js\";\nexport {default as stackOrderDescending} from \"./order/descending.js\";\nexport {default as stackOrderInsideOut} from \"./order/insideOut.js\";\nexport {default as stackOrderNone} from \"./order/none.js\";\nexport {default as stackOrderReverse} from \"./order/reverse.js\";\n","import {path} from \"d3-path\";\nimport constant from \"./constant.js\";\nimport curveLinear from \"./curve/linear.js\";\nimport {x as pointX, y as pointY} from \"./point.js\";\n\nexport default function() {\n var x = pointX,\n y = pointY,\n defined = constant(true),\n context = null,\n curve = curveLinear,\n output = null;\n\n function line(data) {\n var i,\n n = data.length,\n d,\n defined0 = false,\n buffer;\n\n if (context == null) output = curve(buffer = path());\n\n for (i = 0; i <= n; ++i) {\n if (!(i < n && defined(d = data[i], i, data)) === defined0) {\n if (defined0 = !defined0) output.lineStart();\n else output.lineEnd();\n }\n if (defined0) output.point(+x(d, i, data), +y(d, i, data));\n }\n\n if (buffer) return output = null, buffer + \"\" || null;\n }\n\n line.x = function(_) {\n return arguments.length ? (x = typeof _ === \"function\" ? _ : constant(+_), line) : x;\n };\n\n line.y = function(_) {\n return arguments.length ? (y = typeof _ === \"function\" ? _ : constant(+_), line) : y;\n };\n\n line.defined = function(_) {\n return arguments.length ? (defined = typeof _ === \"function\" ? _ : constant(!!_), line) : defined;\n };\n\n line.curve = function(_) {\n return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;\n };\n\n line.context = function(_) {\n return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;\n };\n\n return line;\n}\n","import curveRadial, {curveRadialLinear} from \"./curve/radial.js\";\nimport line from \"./line.js\";\n\nexport function lineRadial(l) {\n var c = l.curve;\n\n l.angle = l.x, delete l.x;\n l.radius = l.y, delete l.y;\n\n l.curve = function(_) {\n return arguments.length ? c(curveRadial(_)) : c()._curve;\n };\n\n return l;\n}\n\nexport default function() {\n return lineRadial(line().curve(curveRadialLinear));\n}\n","import {path} from \"d3-path\";\nimport {slice} from \"../array.js\";\nimport constant from \"../constant.js\";\nimport {x as pointX, y as pointY} from \"../point.js\";\nimport pointRadial from \"../pointRadial.js\";\n\nfunction linkSource(d) {\n return d.source;\n}\n\nfunction linkTarget(d) {\n return d.target;\n}\n\nfunction link(curve) {\n var source = linkSource,\n target = linkTarget,\n x = pointX,\n y = pointY,\n context = null;\n\n function link() {\n var buffer, argv = slice.call(arguments), s = source.apply(this, argv), t = target.apply(this, argv);\n if (!context) context = buffer = path();\n curve(context, +x.apply(this, (argv[0] = s, argv)), +y.apply(this, argv), +x.apply(this, (argv[0] = t, argv)), +y.apply(this, argv));\n if (buffer) return context = null, buffer + \"\" || null;\n }\n\n link.source = function(_) {\n return arguments.length ? (source = _, link) : source;\n };\n\n link.target = function(_) {\n return arguments.length ? (target = _, link) : target;\n };\n\n link.x = function(_) {\n return arguments.length ? (x = typeof _ === \"function\" ? _ : constant(+_), link) : x;\n };\n\n link.y = function(_) {\n return arguments.length ? (y = typeof _ === \"function\" ? _ : constant(+_), link) : y;\n };\n\n link.context = function(_) {\n return arguments.length ? ((context = _ == null ? null : _), link) : context;\n };\n\n return link;\n}\n\nfunction curveHorizontal(context, x0, y0, x1, y1) {\n context.moveTo(x0, y0);\n context.bezierCurveTo(x0 = (x0 + x1) / 2, y0, x0, y1, x1, y1);\n}\n\nfunction curveVertical(context, x0, y0, x1, y1) {\n context.moveTo(x0, y0);\n context.bezierCurveTo(x0, y0 = (y0 + y1) / 2, x1, y0, x1, y1);\n}\n\nfunction curveRadial(context, x0, y0, x1, y1) {\n var p0 = pointRadial(x0, y0),\n p1 = pointRadial(x0, y0 = (y0 + y1) / 2),\n p2 = pointRadial(x1, y0),\n p3 = pointRadial(x1, y1);\n context.moveTo(p0[0], p0[1]);\n context.bezierCurveTo(p1[0], p1[1], p2[0], p2[1], p3[0], p3[1]);\n}\n\nexport function linkHorizontal() {\n return link(curveHorizontal);\n}\n\nexport function linkVertical() {\n return link(curveVertical);\n}\n\nexport function linkRadial() {\n var l = link(curveRadial);\n l.angle = l.x, delete l.x;\n l.radius = l.y, delete l.y;\n return l;\n}\n","export var abs = Math.abs;\nexport var atan2 = Math.atan2;\nexport var cos = Math.cos;\nexport var max = Math.max;\nexport var min = Math.min;\nexport var sin = Math.sin;\nexport var sqrt = Math.sqrt;\n\nexport var epsilon = 1e-12;\nexport var pi = Math.PI;\nexport var halfPi = pi / 2;\nexport var tau = 2 * pi;\n\nexport function acos(x) {\n return x > 1 ? 0 : x < -1 ? pi : Math.acos(x);\n}\n\nexport function asin(x) {\n return x >= 1 ? halfPi : x <= -1 ? -halfPi : Math.asin(x);\n}\n","export default function() {}\n","export default function(series, order) {\n if (!((n = series.length) > 0)) return;\n for (var i, j = 0, d, dy, yp, yn, n, m = series[order[0]].length; j < m; ++j) {\n for (yp = yn = 0, i = 0; i < n; ++i) {\n if ((dy = (d = series[order[i]][j])[1] - d[0]) > 0) {\n d[0] = yp, d[1] = yp += dy;\n } else if (dy < 0) {\n d[1] = yn, d[0] = yn += dy;\n } else {\n d[0] = 0, d[1] = dy;\n }\n }\n }\n}\n","import none from \"./none.js\";\n\nexport default function(series, order) {\n if (!((n = series.length) > 0)) return;\n for (var i, n, j = 0, m = series[0].length, y; j < m; ++j) {\n for (y = i = 0; i < n; ++i) y += series[i][j][1] || 0;\n if (y) for (i = 0; i < n; ++i) series[i][j][1] /= y;\n }\n none(series, order);\n}\n","export default function(series, order) {\n if (!((n = series.length) > 1)) return;\n for (var i = 1, j, s0, s1 = series[order[0]], n, m = s1.length; i < n; ++i) {\n s0 = s1, s1 = series[order[i]];\n for (j = 0; j < m; ++j) {\n s1[j][1] += s1[j][0] = isNaN(s0[j][1]) ? s0[j][0] : s0[j][1];\n }\n }\n}\n","import none from \"./none.js\";\n\nexport default function(series, order) {\n if (!((n = series.length) > 0)) return;\n for (var j = 0, s0 = series[order[0]], n, m = s0.length; j < m; ++j) {\n for (var i = 0, y = 0; i < n; ++i) y += series[i][j][1] || 0;\n s0[j][1] += s0[j][0] = -y / 2;\n }\n none(series, order);\n}\n","import none from \"./none.js\";\n\nexport default function(series, order) {\n if (!((n = series.length) > 0) || !((m = (s0 = series[order[0]]).length) > 0)) return;\n for (var y = 0, j = 1, s0, m, n; j < m; ++j) {\n for (var i = 0, s1 = 0, s2 = 0; i < n; ++i) {\n var si = series[order[i]],\n sij0 = si[j][1] || 0,\n sij1 = si[j - 1][1] || 0,\n s3 = (sij0 - sij1) / 2;\n for (var k = 0; k < i; ++k) {\n var sk = series[order[k]],\n skj0 = sk[j][1] || 0,\n skj1 = sk[j - 1][1] || 0;\n s3 += skj0 - skj1;\n }\n s1 += sij0, s2 += s3 * sij0;\n }\n s0[j - 1][1] += s0[j - 1][0] = y;\n if (s1) y -= s2 / s1;\n }\n s0[j - 1][1] += s0[j - 1][0] = y;\n none(series, order);\n}\n","import none from \"./none.js\";\n\nexport default function(series) {\n var peaks = series.map(peak);\n return none(series).sort(function(a, b) { return peaks[a] - peaks[b]; });\n}\n\nfunction peak(series) {\n var i = -1, j = 0, n = series.length, vi, vj = -Infinity;\n while (++i < n) if ((vi = +series[i][1]) > vj) vj = vi, j = i;\n return j;\n}\n","import none from \"./none.js\";\n\nexport default function(series) {\n var sums = series.map(sum);\n return none(series).sort(function(a, b) { return sums[a] - sums[b]; });\n}\n\nexport function sum(series) {\n var s = 0, i = -1, n = series.length, v;\n while (++i < n) if (v = +series[i][1]) s += v;\n return s;\n}\n","import ascending from \"./ascending.js\";\n\nexport default function(series) {\n return ascending(series).reverse();\n}\n","import appearance from \"./appearance.js\";\nimport {sum} from \"./ascending.js\";\n\nexport default function(series) {\n var n = series.length,\n i,\n j,\n sums = series.map(sum),\n order = appearance(series),\n top = 0,\n bottom = 0,\n tops = [],\n bottoms = [];\n\n for (i = 0; i < n; ++i) {\n j = order[i];\n if (top < bottom) {\n top += sums[j];\n tops.push(j);\n } else {\n bottom += sums[j];\n bottoms.push(j);\n }\n }\n\n return bottoms.reverse().concat(tops);\n}\n","export default function(series) {\n var n = series.length, o = new Array(n);\n while (--n >= 0) o[n] = n;\n return o;\n}\n","import none from \"./none.js\";\n\nexport default function(series) {\n return none(series).reverse();\n}\n","import constant from \"./constant.js\";\nimport descending from \"./descending.js\";\nimport identity from \"./identity.js\";\nimport {tau} from \"./math.js\";\n\nexport default function() {\n var value = identity,\n sortValues = descending,\n sort = null,\n startAngle = constant(0),\n endAngle = constant(tau),\n padAngle = constant(0);\n\n function pie(data) {\n var i,\n n = data.length,\n j,\n k,\n sum = 0,\n index = new Array(n),\n arcs = new Array(n),\n a0 = +startAngle.apply(this, arguments),\n da = Math.min(tau, Math.max(-tau, endAngle.apply(this, arguments) - a0)),\n a1,\n p = Math.min(Math.abs(da) / n, padAngle.apply(this, arguments)),\n pa = p * (da < 0 ? -1 : 1),\n v;\n\n for (i = 0; i < n; ++i) {\n if ((v = arcs[index[i] = i] = +value(data[i], i, data)) > 0) {\n sum += v;\n }\n }\n\n // Optionally sort the arcs by previously-computed values or by data.\n if (sortValues != null) index.sort(function(i, j) { return sortValues(arcs[i], arcs[j]); });\n else if (sort != null) index.sort(function(i, j) { return sort(data[i], data[j]); });\n\n // Compute the arcs! They are stored in the original data's order.\n for (i = 0, k = sum ? (da - n * pa) / sum : 0; i < n; ++i, a0 = a1) {\n j = index[i], v = arcs[j], a1 = a0 + (v > 0 ? v * k : 0) + pa, arcs[j] = {\n data: data[j],\n index: i,\n value: v,\n startAngle: a0,\n endAngle: a1,\n padAngle: p\n };\n }\n\n return arcs;\n }\n\n pie.value = function(_) {\n return arguments.length ? (value = typeof _ === \"function\" ? _ : constant(+_), pie) : value;\n };\n\n pie.sortValues = function(_) {\n return arguments.length ? (sortValues = _, sort = null, pie) : sortValues;\n };\n\n pie.sort = function(_) {\n return arguments.length ? (sort = _, sortValues = null, pie) : sort;\n };\n\n pie.startAngle = function(_) {\n return arguments.length ? (startAngle = typeof _ === \"function\" ? _ : constant(+_), pie) : startAngle;\n };\n\n pie.endAngle = function(_) {\n return arguments.length ? (endAngle = typeof _ === \"function\" ? _ : constant(+_), pie) : endAngle;\n };\n\n pie.padAngle = function(_) {\n return arguments.length ? (padAngle = typeof _ === \"function\" ? _ : constant(+_), pie) : padAngle;\n };\n\n return pie;\n}\n","export function x(p) {\n return p[0];\n}\n\nexport function y(p) {\n return p[1];\n}\n","export default function(x, y) {\n return [(y = +y) * Math.cos(x -= Math.PI / 2), y * Math.sin(x)];\n}\n","import {slice} from \"./array.js\";\nimport constant from \"./constant.js\";\nimport offsetNone from \"./offset/none.js\";\nimport orderNone from \"./order/none.js\";\n\nfunction stackValue(d, key) {\n return d[key];\n}\n\nexport default function() {\n var keys = constant([]),\n order = orderNone,\n offset = offsetNone,\n value = stackValue;\n\n function stack(data) {\n var kz = keys.apply(this, arguments),\n i,\n m = data.length,\n n = kz.length,\n sz = new Array(n),\n oz;\n\n for (i = 0; i < n; ++i) {\n for (var ki = kz[i], si = sz[i] = new Array(m), j = 0, sij; j < m; ++j) {\n si[j] = sij = [0, +value(data[j], ki, j, data)];\n sij.data = data[j];\n }\n si.key = ki;\n }\n\n for (i = 0, oz = order(sz); i < n; ++i) {\n sz[oz[i]].index = i;\n }\n\n offset(sz, oz);\n return sz;\n }\n\n stack.keys = function(_) {\n return arguments.length ? (keys = typeof _ === \"function\" ? _ : constant(slice.call(_)), stack) : keys;\n };\n\n stack.value = function(_) {\n return arguments.length ? (value = typeof _ === \"function\" ? _ : constant(+_), stack) : value;\n };\n\n stack.order = function(_) {\n return arguments.length ? (order = _ == null ? orderNone : typeof _ === \"function\" ? _ : constant(slice.call(_)), stack) : order;\n };\n\n stack.offset = function(_) {\n return arguments.length ? (offset = _ == null ? offsetNone : _, stack) : offset;\n };\n\n return stack;\n}\n","import {path} from \"d3-path\";\nimport circle from \"./symbol/circle.js\";\nimport cross from \"./symbol/cross.js\";\nimport diamond from \"./symbol/diamond.js\";\nimport star from \"./symbol/star.js\";\nimport square from \"./symbol/square.js\";\nimport triangle from \"./symbol/triangle.js\";\nimport wye from \"./symbol/wye.js\";\nimport constant from \"./constant.js\";\n\nexport var symbols = [\n circle,\n cross,\n diamond,\n square,\n star,\n triangle,\n wye\n];\n\nexport default function() {\n var type = constant(circle),\n size = constant(64),\n context = null;\n\n function symbol() {\n var buffer;\n if (!context) context = buffer = path();\n type.apply(this, arguments).draw(context, +size.apply(this, arguments));\n if (buffer) return context = null, buffer + \"\" || null;\n }\n\n symbol.type = function(_) {\n return arguments.length ? (type = typeof _ === \"function\" ? _ : constant(_), symbol) : type;\n };\n\n symbol.size = function(_) {\n return arguments.length ? (size = typeof _ === \"function\" ? _ : constant(+_), symbol) : size;\n };\n\n symbol.context = function(_) {\n return arguments.length ? (context = _ == null ? null : _, symbol) : context;\n };\n\n return symbol;\n}\n","import {pi, tau} from \"../math.js\";\n\nexport default {\n draw: function(context, size) {\n var r = Math.sqrt(size / pi);\n context.moveTo(r, 0);\n context.arc(0, 0, r, 0, tau);\n }\n};\n","export default {\n draw: function(context, size) {\n var r = Math.sqrt(size / 5) / 2;\n context.moveTo(-3 * r, -r);\n context.lineTo(-r, -r);\n context.lineTo(-r, -3 * r);\n context.lineTo(r, -3 * r);\n context.lineTo(r, -r);\n context.lineTo(3 * r, -r);\n context.lineTo(3 * r, r);\n context.lineTo(r, r);\n context.lineTo(r, 3 * r);\n context.lineTo(-r, 3 * r);\n context.lineTo(-r, r);\n context.lineTo(-3 * r, r);\n context.closePath();\n }\n};\n","var tan30 = Math.sqrt(1 / 3),\n tan30_2 = tan30 * 2;\n\nexport default {\n draw: function(context, size) {\n var y = Math.sqrt(size / tan30_2),\n x = y * tan30;\n context.moveTo(0, -y);\n context.lineTo(x, 0);\n context.lineTo(0, y);\n context.lineTo(-x, 0);\n context.closePath();\n }\n};\n","export default {\n draw: function(context, size) {\n var w = Math.sqrt(size),\n x = -w / 2;\n context.rect(x, x, w, w);\n }\n};\n","import {pi, tau} from \"../math.js\";\n\nvar ka = 0.89081309152928522810,\n kr = Math.sin(pi / 10) / Math.sin(7 * pi / 10),\n kx = Math.sin(tau / 10) * kr,\n ky = -Math.cos(tau / 10) * kr;\n\nexport default {\n draw: function(context, size) {\n var r = Math.sqrt(size * ka),\n x = kx * r,\n y = ky * r;\n context.moveTo(0, -r);\n context.lineTo(x, y);\n for (var i = 1; i < 5; ++i) {\n var a = tau * i / 5,\n c = Math.cos(a),\n s = Math.sin(a);\n context.lineTo(s * r, -c * r);\n context.lineTo(c * x - s * y, s * x + c * y);\n }\n context.closePath();\n }\n};\n","var sqrt3 = Math.sqrt(3);\n\nexport default {\n draw: function(context, size) {\n var y = -Math.sqrt(size / (sqrt3 * 3));\n context.moveTo(0, y * 2);\n context.lineTo(-sqrt3 * y, -y);\n context.lineTo(sqrt3 * y, -y);\n context.closePath();\n }\n};\n","var c = -0.5,\n s = Math.sqrt(3) / 2,\n k = 1 / Math.sqrt(12),\n a = (k / 2 + 1) * 3;\n\nexport default {\n draw: function(context, size) {\n var r = Math.sqrt(size / a),\n x0 = r / 2,\n y0 = r * k,\n x1 = x0,\n y1 = r * k + r,\n x2 = -x1,\n y2 = y1;\n context.moveTo(x0, y0);\n context.lineTo(x1, y1);\n context.lineTo(x2, y2);\n context.lineTo(c * x0 - s * y0, s * x0 + c * y0);\n context.lineTo(c * x1 - s * y1, s * x1 + c * y1);\n context.lineTo(c * x2 - s * y2, s * x2 + c * y2);\n context.lineTo(c * x0 + s * y0, c * y0 - s * x0);\n context.lineTo(c * x1 + s * y1, c * y1 - s * x1);\n context.lineTo(c * x2 + s * y2, c * y2 - s * x2);\n context.closePath();\n }\n};\n","import formatLocale from \"./locale.js\";\n\nvar locale;\nexport var timeFormat;\nexport var timeParse;\nexport var utcFormat;\nexport var utcParse;\n\ndefaultLocale({\n dateTime: \"%x, %X\",\n date: \"%-m/%-d/%Y\",\n time: \"%-I:%M:%S %p\",\n periods: [\"AM\", \"PM\"],\n days: [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"],\n shortDays: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"],\n months: [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"],\n shortMonths: [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n});\n\nexport default function defaultLocale(definition) {\n locale = formatLocale(definition);\n timeFormat = locale.format;\n timeParse = locale.parse;\n utcFormat = locale.utcFormat;\n utcParse = locale.utcParse;\n return locale;\n}\n","export {default as timeFormatDefaultLocale, timeFormat, timeParse, utcFormat, utcParse} from \"./defaultLocale.js\";\nexport {default as timeFormatLocale} from \"./locale.js\";\nexport {default as isoFormat} from \"./isoFormat.js\";\nexport {default as isoParse} from \"./isoParse.js\";\n","import {utcFormat} from \"./defaultLocale.js\";\n\nexport var isoSpecifier = \"%Y-%m-%dT%H:%M:%S.%LZ\";\n\nfunction formatIsoNative(date) {\n return date.toISOString();\n}\n\nvar formatIso = Date.prototype.toISOString\n ? formatIsoNative\n : utcFormat(isoSpecifier);\n\nexport default formatIso;\n","import {isoSpecifier} from \"./isoFormat.js\";\nimport {utcParse} from \"./defaultLocale.js\";\n\nfunction parseIsoNative(string) {\n var date = new Date(string);\n return isNaN(date) ? null : date;\n}\n\nvar parseIso = +new Date(\"2000-01-01T00:00:00.000Z\")\n ? parseIsoNative\n : utcParse(isoSpecifier);\n\nexport default parseIso;\n","import {\n timeDay,\n timeSunday,\n timeMonday,\n timeThursday,\n timeYear,\n utcDay,\n utcSunday,\n utcMonday,\n utcThursday,\n utcYear\n} from \"d3-time\";\n\nfunction localDate(d) {\n if (0 <= d.y && d.y < 100) {\n var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L);\n date.setFullYear(d.y);\n return date;\n }\n return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L);\n}\n\nfunction utcDate(d) {\n if (0 <= d.y && d.y < 100) {\n var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L));\n date.setUTCFullYear(d.y);\n return date;\n }\n return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L));\n}\n\nfunction newDate(y, m, d) {\n return {y: y, m: m, d: d, H: 0, M: 0, S: 0, L: 0};\n}\n\nexport default function formatLocale(locale) {\n var locale_dateTime = locale.dateTime,\n locale_date = locale.date,\n locale_time = locale.time,\n locale_periods = locale.periods,\n locale_weekdays = locale.days,\n locale_shortWeekdays = locale.shortDays,\n locale_months = locale.months,\n locale_shortMonths = locale.shortMonths;\n\n var periodRe = formatRe(locale_periods),\n periodLookup = formatLookup(locale_periods),\n weekdayRe = formatRe(locale_weekdays),\n weekdayLookup = formatLookup(locale_weekdays),\n shortWeekdayRe = formatRe(locale_shortWeekdays),\n shortWeekdayLookup = formatLookup(locale_shortWeekdays),\n monthRe = formatRe(locale_months),\n monthLookup = formatLookup(locale_months),\n shortMonthRe = formatRe(locale_shortMonths),\n shortMonthLookup = formatLookup(locale_shortMonths);\n\n var formats = {\n \"a\": formatShortWeekday,\n \"A\": formatWeekday,\n \"b\": formatShortMonth,\n \"B\": formatMonth,\n \"c\": null,\n \"d\": formatDayOfMonth,\n \"e\": formatDayOfMonth,\n \"f\": formatMicroseconds,\n \"g\": formatYearISO,\n \"G\": formatFullYearISO,\n \"H\": formatHour24,\n \"I\": formatHour12,\n \"j\": formatDayOfYear,\n \"L\": formatMilliseconds,\n \"m\": formatMonthNumber,\n \"M\": formatMinutes,\n \"p\": formatPeriod,\n \"q\": formatQuarter,\n \"Q\": formatUnixTimestamp,\n \"s\": formatUnixTimestampSeconds,\n \"S\": formatSeconds,\n \"u\": formatWeekdayNumberMonday,\n \"U\": formatWeekNumberSunday,\n \"V\": formatWeekNumberISO,\n \"w\": formatWeekdayNumberSunday,\n \"W\": formatWeekNumberMonday,\n \"x\": null,\n \"X\": null,\n \"y\": formatYear,\n \"Y\": formatFullYear,\n \"Z\": formatZone,\n \"%\": formatLiteralPercent\n };\n\n var utcFormats = {\n \"a\": formatUTCShortWeekday,\n \"A\": formatUTCWeekday,\n \"b\": formatUTCShortMonth,\n \"B\": formatUTCMonth,\n \"c\": null,\n \"d\": formatUTCDayOfMonth,\n \"e\": formatUTCDayOfMonth,\n \"f\": formatUTCMicroseconds,\n \"g\": formatUTCYearISO,\n \"G\": formatUTCFullYearISO,\n \"H\": formatUTCHour24,\n \"I\": formatUTCHour12,\n \"j\": formatUTCDayOfYear,\n \"L\": formatUTCMilliseconds,\n \"m\": formatUTCMonthNumber,\n \"M\": formatUTCMinutes,\n \"p\": formatUTCPeriod,\n \"q\": formatUTCQuarter,\n \"Q\": formatUnixTimestamp,\n \"s\": formatUnixTimestampSeconds,\n \"S\": formatUTCSeconds,\n \"u\": formatUTCWeekdayNumberMonday,\n \"U\": formatUTCWeekNumberSunday,\n \"V\": formatUTCWeekNumberISO,\n \"w\": formatUTCWeekdayNumberSunday,\n \"W\": formatUTCWeekNumberMonday,\n \"x\": null,\n \"X\": null,\n \"y\": formatUTCYear,\n \"Y\": formatUTCFullYear,\n \"Z\": formatUTCZone,\n \"%\": formatLiteralPercent\n };\n\n var parses = {\n \"a\": parseShortWeekday,\n \"A\": parseWeekday,\n \"b\": parseShortMonth,\n \"B\": parseMonth,\n \"c\": parseLocaleDateTime,\n \"d\": parseDayOfMonth,\n \"e\": parseDayOfMonth,\n \"f\": parseMicroseconds,\n \"g\": parseYear,\n \"G\": parseFullYear,\n \"H\": parseHour24,\n \"I\": parseHour24,\n \"j\": parseDayOfYear,\n \"L\": parseMilliseconds,\n \"m\": parseMonthNumber,\n \"M\": parseMinutes,\n \"p\": parsePeriod,\n \"q\": parseQuarter,\n \"Q\": parseUnixTimestamp,\n \"s\": parseUnixTimestampSeconds,\n \"S\": parseSeconds,\n \"u\": parseWeekdayNumberMonday,\n \"U\": parseWeekNumberSunday,\n \"V\": parseWeekNumberISO,\n \"w\": parseWeekdayNumberSunday,\n \"W\": parseWeekNumberMonday,\n \"x\": parseLocaleDate,\n \"X\": parseLocaleTime,\n \"y\": parseYear,\n \"Y\": parseFullYear,\n \"Z\": parseZone,\n \"%\": parseLiteralPercent\n };\n\n // These recursive directive definitions must be deferred.\n formats.x = newFormat(locale_date, formats);\n formats.X = newFormat(locale_time, formats);\n formats.c = newFormat(locale_dateTime, formats);\n utcFormats.x = newFormat(locale_date, utcFormats);\n utcFormats.X = newFormat(locale_time, utcFormats);\n utcFormats.c = newFormat(locale_dateTime, utcFormats);\n\n function newFormat(specifier, formats) {\n return function(date) {\n var string = [],\n i = -1,\n j = 0,\n n = specifier.length,\n c,\n pad,\n format;\n\n if (!(date instanceof Date)) date = new Date(+date);\n\n while (++i < n) {\n if (specifier.charCodeAt(i) === 37) {\n string.push(specifier.slice(j, i));\n if ((pad = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i);\n else pad = c === \"e\" ? \" \" : \"0\";\n if (format = formats[c]) c = format(date, pad);\n string.push(c);\n j = i + 1;\n }\n }\n\n string.push(specifier.slice(j, i));\n return string.join(\"\");\n };\n }\n\n function newParse(specifier, Z) {\n return function(string) {\n var d = newDate(1900, undefined, 1),\n i = parseSpecifier(d, specifier, string += \"\", 0),\n week, day;\n if (i != string.length) return null;\n\n // If a UNIX timestamp is specified, return it.\n if (\"Q\" in d) return new Date(d.Q);\n if (\"s\" in d) return new Date(d.s * 1000 + (\"L\" in d ? d.L : 0));\n\n // If this is utcParse, never use the local timezone.\n if (Z && !(\"Z\" in d)) d.Z = 0;\n\n // The am-pm flag is 0 for AM, and 1 for PM.\n if (\"p\" in d) d.H = d.H % 12 + d.p * 12;\n\n // If the month was not specified, inherit from the quarter.\n if (d.m === undefined) d.m = \"q\" in d ? d.q : 0;\n\n // Convert day-of-week and week-of-year to day-of-year.\n if (\"V\" in d) {\n if (d.V < 1 || d.V > 53) return null;\n if (!(\"w\" in d)) d.w = 1;\n if (\"Z\" in d) {\n week = utcDate(newDate(d.y, 0, 1)), day = week.getUTCDay();\n week = day > 4 || day === 0 ? utcMonday.ceil(week) : utcMonday(week);\n week = utcDay.offset(week, (d.V - 1) * 7);\n d.y = week.getUTCFullYear();\n d.m = week.getUTCMonth();\n d.d = week.getUTCDate() + (d.w + 6) % 7;\n } else {\n week = localDate(newDate(d.y, 0, 1)), day = week.getDay();\n week = day > 4 || day === 0 ? timeMonday.ceil(week) : timeMonday(week);\n week = timeDay.offset(week, (d.V - 1) * 7);\n d.y = week.getFullYear();\n d.m = week.getMonth();\n d.d = week.getDate() + (d.w + 6) % 7;\n }\n } else if (\"W\" in d || \"U\" in d) {\n if (!(\"w\" in d)) d.w = \"u\" in d ? d.u % 7 : \"W\" in d ? 1 : 0;\n day = \"Z\" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay();\n d.m = 0;\n d.d = \"W\" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7;\n }\n\n // If a time zone is specified, all fields are interpreted as UTC and then\n // offset according to the specified time zone.\n if (\"Z\" in d) {\n d.H += d.Z / 100 | 0;\n d.M += d.Z % 100;\n return utcDate(d);\n }\n\n // Otherwise, all fields are in local time.\n return localDate(d);\n };\n }\n\n function parseSpecifier(d, specifier, string, j) {\n var i = 0,\n n = specifier.length,\n m = string.length,\n c,\n parse;\n\n while (i < n) {\n if (j >= m) return -1;\n c = specifier.charCodeAt(i++);\n if (c === 37) {\n c = specifier.charAt(i++);\n parse = parses[c in pads ? specifier.charAt(i++) : c];\n if (!parse || ((j = parse(d, string, j)) < 0)) return -1;\n } else if (c != string.charCodeAt(j++)) {\n return -1;\n }\n }\n\n return j;\n }\n\n function parsePeriod(d, string, i) {\n var n = periodRe.exec(string.slice(i));\n return n ? (d.p = periodLookup[n[0].toLowerCase()], i + n[0].length) : -1;\n }\n\n function parseShortWeekday(d, string, i) {\n var n = shortWeekdayRe.exec(string.slice(i));\n return n ? (d.w = shortWeekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;\n }\n\n function parseWeekday(d, string, i) {\n var n = weekdayRe.exec(string.slice(i));\n return n ? (d.w = weekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1;\n }\n\n function parseShortMonth(d, string, i) {\n var n = shortMonthRe.exec(string.slice(i));\n return n ? (d.m = shortMonthLookup[n[0].toLowerCase()], i + n[0].length) : -1;\n }\n\n function parseMonth(d, string, i) {\n var n = monthRe.exec(string.slice(i));\n return n ? (d.m = monthLookup[n[0].toLowerCase()], i + n[0].length) : -1;\n }\n\n function parseLocaleDateTime(d, string, i) {\n return parseSpecifier(d, locale_dateTime, string, i);\n }\n\n function parseLocaleDate(d, string, i) {\n return parseSpecifier(d, locale_date, string, i);\n }\n\n function parseLocaleTime(d, string, i) {\n return parseSpecifier(d, locale_time, string, i);\n }\n\n function formatShortWeekday(d) {\n return locale_shortWeekdays[d.getDay()];\n }\n\n function formatWeekday(d) {\n return locale_weekdays[d.getDay()];\n }\n\n function formatShortMonth(d) {\n return locale_shortMonths[d.getMonth()];\n }\n\n function formatMonth(d) {\n return locale_months[d.getMonth()];\n }\n\n function formatPeriod(d) {\n return locale_periods[+(d.getHours() >= 12)];\n }\n\n function formatQuarter(d) {\n return 1 + ~~(d.getMonth() / 3);\n }\n\n function formatUTCShortWeekday(d) {\n return locale_shortWeekdays[d.getUTCDay()];\n }\n\n function formatUTCWeekday(d) {\n return locale_weekdays[d.getUTCDay()];\n }\n\n function formatUTCShortMonth(d) {\n return locale_shortMonths[d.getUTCMonth()];\n }\n\n function formatUTCMonth(d) {\n return locale_months[d.getUTCMonth()];\n }\n\n function formatUTCPeriod(d) {\n return locale_periods[+(d.getUTCHours() >= 12)];\n }\n\n function formatUTCQuarter(d) {\n return 1 + ~~(d.getUTCMonth() / 3);\n }\n\n return {\n format: function(specifier) {\n var f = newFormat(specifier += \"\", formats);\n f.toString = function() { return specifier; };\n return f;\n },\n parse: function(specifier) {\n var p = newParse(specifier += \"\", false);\n p.toString = function() { return specifier; };\n return p;\n },\n utcFormat: function(specifier) {\n var f = newFormat(specifier += \"\", utcFormats);\n f.toString = function() { return specifier; };\n return f;\n },\n utcParse: function(specifier) {\n var p = newParse(specifier += \"\", true);\n p.toString = function() { return specifier; };\n return p;\n }\n };\n}\n\nvar pads = {\"-\": \"\", \"_\": \" \", \"0\": \"0\"},\n numberRe = /^\\s*\\d+/, // note: ignores next directive\n percentRe = /^%/,\n requoteRe = /[\\\\^$*+?|[\\]().{}]/g;\n\nfunction pad(value, fill, width) {\n var sign = value < 0 ? \"-\" : \"\",\n string = (sign ? -value : value) + \"\",\n length = string.length;\n return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);\n}\n\nfunction requote(s) {\n return s.replace(requoteRe, \"\\\\$&\");\n}\n\nfunction formatRe(names) {\n return new RegExp(\"^(?:\" + names.map(requote).join(\"|\") + \")\", \"i\");\n}\n\nfunction formatLookup(names) {\n var map = {}, i = -1, n = names.length;\n while (++i < n) map[names[i].toLowerCase()] = i;\n return map;\n}\n\nfunction parseWeekdayNumberSunday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.w = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekdayNumberMonday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.u = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberSunday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.U = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberISO(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.V = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseWeekNumberMonday(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.W = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseFullYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 4));\n return n ? (d.y = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1;\n}\n\nfunction parseZone(d, string, i) {\n var n = /^(Z)|([+-]\\d\\d)(?::?(\\d\\d))?/.exec(string.slice(i, i + 6));\n return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || \"00\")), i + n[0].length) : -1;\n}\n\nfunction parseQuarter(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 1));\n return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1;\n}\n\nfunction parseMonthNumber(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.m = n[0] - 1, i + n[0].length) : -1;\n}\n\nfunction parseDayOfMonth(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.d = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseDayOfYear(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 3));\n return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseHour24(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.H = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMinutes(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.M = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseSeconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 2));\n return n ? (d.S = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMilliseconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 3));\n return n ? (d.L = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseMicroseconds(d, string, i) {\n var n = numberRe.exec(string.slice(i, i + 6));\n return n ? (d.L = Math.floor(n[0] / 1000), i + n[0].length) : -1;\n}\n\nfunction parseLiteralPercent(d, string, i) {\n var n = percentRe.exec(string.slice(i, i + 1));\n return n ? i + n[0].length : -1;\n}\n\nfunction parseUnixTimestamp(d, string, i) {\n var n = numberRe.exec(string.slice(i));\n return n ? (d.Q = +n[0], i + n[0].length) : -1;\n}\n\nfunction parseUnixTimestampSeconds(d, string, i) {\n var n = numberRe.exec(string.slice(i));\n return n ? (d.s = +n[0], i + n[0].length) : -1;\n}\n\nfunction formatDayOfMonth(d, p) {\n return pad(d.getDate(), p, 2);\n}\n\nfunction formatHour24(d, p) {\n return pad(d.getHours(), p, 2);\n}\n\nfunction formatHour12(d, p) {\n return pad(d.getHours() % 12 || 12, p, 2);\n}\n\nfunction formatDayOfYear(d, p) {\n return pad(1 + timeDay.count(timeYear(d), d), p, 3);\n}\n\nfunction formatMilliseconds(d, p) {\n return pad(d.getMilliseconds(), p, 3);\n}\n\nfunction formatMicroseconds(d, p) {\n return formatMilliseconds(d, p) + \"000\";\n}\n\nfunction formatMonthNumber(d, p) {\n return pad(d.getMonth() + 1, p, 2);\n}\n\nfunction formatMinutes(d, p) {\n return pad(d.getMinutes(), p, 2);\n}\n\nfunction formatSeconds(d, p) {\n return pad(d.getSeconds(), p, 2);\n}\n\nfunction formatWeekdayNumberMonday(d) {\n var day = d.getDay();\n return day === 0 ? 7 : day;\n}\n\nfunction formatWeekNumberSunday(d, p) {\n return pad(timeSunday.count(timeYear(d) - 1, d), p, 2);\n}\n\nfunction dISO(d) {\n var day = d.getDay();\n return (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d);\n}\n\nfunction formatWeekNumberISO(d, p) {\n d = dISO(d);\n return pad(timeThursday.count(timeYear(d), d) + (timeYear(d).getDay() === 4), p, 2);\n}\n\nfunction formatWeekdayNumberSunday(d) {\n return d.getDay();\n}\n\nfunction formatWeekNumberMonday(d, p) {\n return pad(timeMonday.count(timeYear(d) - 1, d), p, 2);\n}\n\nfunction formatYear(d, p) {\n return pad(d.getFullYear() % 100, p, 2);\n}\n\nfunction formatYearISO(d, p) {\n d = dISO(d);\n return pad(d.getFullYear() % 100, p, 2);\n}\n\nfunction formatFullYear(d, p) {\n return pad(d.getFullYear() % 10000, p, 4);\n}\n\nfunction formatFullYearISO(d, p) {\n var day = d.getDay();\n d = (day >= 4 || day === 0) ? timeThursday(d) : timeThursday.ceil(d);\n return pad(d.getFullYear() % 10000, p, 4);\n}\n\nfunction formatZone(d) {\n var z = d.getTimezoneOffset();\n return (z > 0 ? \"-\" : (z *= -1, \"+\"))\n + pad(z / 60 | 0, \"0\", 2)\n + pad(z % 60, \"0\", 2);\n}\n\nfunction formatUTCDayOfMonth(d, p) {\n return pad(d.getUTCDate(), p, 2);\n}\n\nfunction formatUTCHour24(d, p) {\n return pad(d.getUTCHours(), p, 2);\n}\n\nfunction formatUTCHour12(d, p) {\n return pad(d.getUTCHours() % 12 || 12, p, 2);\n}\n\nfunction formatUTCDayOfYear(d, p) {\n return pad(1 + utcDay.count(utcYear(d), d), p, 3);\n}\n\nfunction formatUTCMilliseconds(d, p) {\n return pad(d.getUTCMilliseconds(), p, 3);\n}\n\nfunction formatUTCMicroseconds(d, p) {\n return formatUTCMilliseconds(d, p) + \"000\";\n}\n\nfunction formatUTCMonthNumber(d, p) {\n return pad(d.getUTCMonth() + 1, p, 2);\n}\n\nfunction formatUTCMinutes(d, p) {\n return pad(d.getUTCMinutes(), p, 2);\n}\n\nfunction formatUTCSeconds(d, p) {\n return pad(d.getUTCSeconds(), p, 2);\n}\n\nfunction formatUTCWeekdayNumberMonday(d) {\n var dow = d.getUTCDay();\n return dow === 0 ? 7 : dow;\n}\n\nfunction formatUTCWeekNumberSunday(d, p) {\n return pad(utcSunday.count(utcYear(d) - 1, d), p, 2);\n}\n\nfunction UTCdISO(d) {\n var day = d.getUTCDay();\n return (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);\n}\n\nfunction formatUTCWeekNumberISO(d, p) {\n d = UTCdISO(d);\n return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2);\n}\n\nfunction formatUTCWeekdayNumberSunday(d) {\n return d.getUTCDay();\n}\n\nfunction formatUTCWeekNumberMonday(d, p) {\n return pad(utcMonday.count(utcYear(d) - 1, d), p, 2);\n}\n\nfunction formatUTCYear(d, p) {\n return pad(d.getUTCFullYear() % 100, p, 2);\n}\n\nfunction formatUTCYearISO(d, p) {\n d = UTCdISO(d);\n return pad(d.getUTCFullYear() % 100, p, 2);\n}\n\nfunction formatUTCFullYear(d, p) {\n return pad(d.getUTCFullYear() % 10000, p, 4);\n}\n\nfunction formatUTCFullYearISO(d, p) {\n var day = d.getUTCDay();\n d = (day >= 4 || day === 0) ? utcThursday(d) : utcThursday.ceil(d);\n return pad(d.getUTCFullYear() % 10000, p, 4);\n}\n\nfunction formatUTCZone() {\n return \"+0000\";\n}\n\nfunction formatLiteralPercent() {\n return \"%\";\n}\n\nfunction formatUnixTimestamp(d) {\n return +d;\n}\n\nfunction formatUnixTimestampSeconds(d) {\n return Math.floor(+d / 1000);\n}\n","import interval from \"./interval.js\";\nimport {durationDay, durationMinute} from \"./duration.js\";\n\nvar day = interval(function(date) {\n date.setHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setDate(date.getDate() + step);\n}, function(start, end) {\n return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay;\n}, function(date) {\n return date.getDate() - 1;\n});\n\nexport default day;\nexport var days = day.range;\n","export var durationSecond = 1e3;\nexport var durationMinute = 6e4;\nexport var durationHour = 36e5;\nexport var durationDay = 864e5;\nexport var durationWeek = 6048e5;\n","import interval from \"./interval.js\";\nimport {durationHour, durationMinute, durationSecond} from \"./duration.js\";\n\nvar hour = interval(function(date) {\n date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond - date.getMinutes() * durationMinute);\n}, function(date, step) {\n date.setTime(+date + step * durationHour);\n}, function(start, end) {\n return (end - start) / durationHour;\n}, function(date) {\n return date.getHours();\n});\n\nexport default hour;\nexport var hours = hour.range;\n","export {\n default as timeInterval\n} from \"./interval.js\";\n\nexport {\n default as timeMillisecond,\n milliseconds as timeMilliseconds,\n default as utcMillisecond,\n milliseconds as utcMilliseconds\n} from \"./millisecond.js\";\n\nexport {\n default as timeSecond,\n seconds as timeSeconds,\n default as utcSecond,\n seconds as utcSeconds\n} from \"./second.js\";\n\nexport {\n default as timeMinute,\n minutes as timeMinutes\n} from \"./minute.js\";\n\nexport {\n default as timeHour,\n hours as timeHours\n} from \"./hour.js\";\n\nexport {\n default as timeDay,\n days as timeDays\n} from \"./day.js\";\n\nexport {\n sunday as timeWeek,\n sundays as timeWeeks,\n sunday as timeSunday,\n sundays as timeSundays,\n monday as timeMonday,\n mondays as timeMondays,\n tuesday as timeTuesday,\n tuesdays as timeTuesdays,\n wednesday as timeWednesday,\n wednesdays as timeWednesdays,\n thursday as timeThursday,\n thursdays as timeThursdays,\n friday as timeFriday,\n fridays as timeFridays,\n saturday as timeSaturday,\n saturdays as timeSaturdays\n} from \"./week.js\";\n\nexport {\n default as timeMonth,\n months as timeMonths\n} from \"./month.js\";\n\nexport {\n default as timeYear,\n years as timeYears\n} from \"./year.js\";\n\nexport {\n default as utcMinute,\n utcMinutes as utcMinutes\n} from \"./utcMinute.js\";\n\nexport {\n default as utcHour,\n utcHours as utcHours\n} from \"./utcHour.js\";\n\nexport {\n default as utcDay,\n utcDays as utcDays\n} from \"./utcDay.js\";\n\nexport {\n utcSunday as utcWeek,\n utcSundays as utcWeeks,\n utcSunday as utcSunday,\n utcSundays as utcSundays,\n utcMonday as utcMonday,\n utcMondays as utcMondays,\n utcTuesday as utcTuesday,\n utcTuesdays as utcTuesdays,\n utcWednesday as utcWednesday,\n utcWednesdays as utcWednesdays,\n utcThursday as utcThursday,\n utcThursdays as utcThursdays,\n utcFriday as utcFriday,\n utcFridays as utcFridays,\n utcSaturday as utcSaturday,\n utcSaturdays as utcSaturdays\n} from \"./utcWeek.js\";\n\nexport {\n default as utcMonth,\n utcMonths as utcMonths\n} from \"./utcMonth.js\";\n\nexport {\n default as utcYear,\n utcYears as utcYears\n} from \"./utcYear.js\";\n","var t0 = new Date,\n t1 = new Date;\n\nexport default function newInterval(floori, offseti, count, field) {\n\n function interval(date) {\n return floori(date = arguments.length === 0 ? new Date : new Date(+date)), date;\n }\n\n interval.floor = function(date) {\n return floori(date = new Date(+date)), date;\n };\n\n interval.ceil = function(date) {\n return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date;\n };\n\n interval.round = function(date) {\n var d0 = interval(date),\n d1 = interval.ceil(date);\n return date - d0 < d1 - date ? d0 : d1;\n };\n\n interval.offset = function(date, step) {\n return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date;\n };\n\n interval.range = function(start, stop, step) {\n var range = [], previous;\n start = interval.ceil(start);\n step = step == null ? 1 : Math.floor(step);\n if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date\n do range.push(previous = new Date(+start)), offseti(start, step), floori(start);\n while (previous < start && start < stop);\n return range;\n };\n\n interval.filter = function(test) {\n return newInterval(function(date) {\n if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1);\n }, function(date, step) {\n if (date >= date) {\n if (step < 0) while (++step <= 0) {\n while (offseti(date, -1), !test(date)) {} // eslint-disable-line no-empty\n } else while (--step >= 0) {\n while (offseti(date, +1), !test(date)) {} // eslint-disable-line no-empty\n }\n }\n });\n };\n\n if (count) {\n interval.count = function(start, end) {\n t0.setTime(+start), t1.setTime(+end);\n floori(t0), floori(t1);\n return Math.floor(count(t0, t1));\n };\n\n interval.every = function(step) {\n step = Math.floor(step);\n return !isFinite(step) || !(step > 0) ? null\n : !(step > 1) ? interval\n : interval.filter(field\n ? function(d) { return field(d) % step === 0; }\n : function(d) { return interval.count(0, d) % step === 0; });\n };\n }\n\n return interval;\n}\n","import interval from \"./interval.js\";\n\nvar millisecond = interval(function() {\n // noop\n}, function(date, step) {\n date.setTime(+date + step);\n}, function(start, end) {\n return end - start;\n});\n\n// An optimized implementation for this simple case.\nmillisecond.every = function(k) {\n k = Math.floor(k);\n if (!isFinite(k) || !(k > 0)) return null;\n if (!(k > 1)) return millisecond;\n return interval(function(date) {\n date.setTime(Math.floor(date / k) * k);\n }, function(date, step) {\n date.setTime(+date + step * k);\n }, function(start, end) {\n return (end - start) / k;\n });\n};\n\nexport default millisecond;\nexport var milliseconds = millisecond.range;\n","import interval from \"./interval.js\";\nimport {durationMinute, durationSecond} from \"./duration.js\";\n\nvar minute = interval(function(date) {\n date.setTime(date - date.getMilliseconds() - date.getSeconds() * durationSecond);\n}, function(date, step) {\n date.setTime(+date + step * durationMinute);\n}, function(start, end) {\n return (end - start) / durationMinute;\n}, function(date) {\n return date.getMinutes();\n});\n\nexport default minute;\nexport var minutes = minute.range;\n","import interval from \"./interval.js\";\n\nvar month = interval(function(date) {\n date.setDate(1);\n date.setHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setMonth(date.getMonth() + step);\n}, function(start, end) {\n return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12;\n}, function(date) {\n return date.getMonth();\n});\n\nexport default month;\nexport var months = month.range;\n","import interval from \"./interval.js\";\nimport {durationSecond} from \"./duration.js\";\n\nvar second = interval(function(date) {\n date.setTime(date - date.getMilliseconds());\n}, function(date, step) {\n date.setTime(+date + step * durationSecond);\n}, function(start, end) {\n return (end - start) / durationSecond;\n}, function(date) {\n return date.getUTCSeconds();\n});\n\nexport default second;\nexport var seconds = second.range;\n","import interval from \"./interval.js\";\nimport {durationDay} from \"./duration.js\";\n\nvar utcDay = interval(function(date) {\n date.setUTCHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setUTCDate(date.getUTCDate() + step);\n}, function(start, end) {\n return (end - start) / durationDay;\n}, function(date) {\n return date.getUTCDate() - 1;\n});\n\nexport default utcDay;\nexport var utcDays = utcDay.range;\n","import interval from \"./interval.js\";\nimport {durationHour} from \"./duration.js\";\n\nvar utcHour = interval(function(date) {\n date.setUTCMinutes(0, 0, 0);\n}, function(date, step) {\n date.setTime(+date + step * durationHour);\n}, function(start, end) {\n return (end - start) / durationHour;\n}, function(date) {\n return date.getUTCHours();\n});\n\nexport default utcHour;\nexport var utcHours = utcHour.range;\n","import interval from \"./interval.js\";\nimport {durationMinute} from \"./duration.js\";\n\nvar utcMinute = interval(function(date) {\n date.setUTCSeconds(0, 0);\n}, function(date, step) {\n date.setTime(+date + step * durationMinute);\n}, function(start, end) {\n return (end - start) / durationMinute;\n}, function(date) {\n return date.getUTCMinutes();\n});\n\nexport default utcMinute;\nexport var utcMinutes = utcMinute.range;\n","import interval from \"./interval.js\";\n\nvar utcMonth = interval(function(date) {\n date.setUTCDate(1);\n date.setUTCHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setUTCMonth(date.getUTCMonth() + step);\n}, function(start, end) {\n return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12;\n}, function(date) {\n return date.getUTCMonth();\n});\n\nexport default utcMonth;\nexport var utcMonths = utcMonth.range;\n","import interval from \"./interval.js\";\nimport {durationWeek} from \"./duration.js\";\n\nfunction utcWeekday(i) {\n return interval(function(date) {\n date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7);\n date.setUTCHours(0, 0, 0, 0);\n }, function(date, step) {\n date.setUTCDate(date.getUTCDate() + step * 7);\n }, function(start, end) {\n return (end - start) / durationWeek;\n });\n}\n\nexport var utcSunday = utcWeekday(0);\nexport var utcMonday = utcWeekday(1);\nexport var utcTuesday = utcWeekday(2);\nexport var utcWednesday = utcWeekday(3);\nexport var utcThursday = utcWeekday(4);\nexport var utcFriday = utcWeekday(5);\nexport var utcSaturday = utcWeekday(6);\n\nexport var utcSundays = utcSunday.range;\nexport var utcMondays = utcMonday.range;\nexport var utcTuesdays = utcTuesday.range;\nexport var utcWednesdays = utcWednesday.range;\nexport var utcThursdays = utcThursday.range;\nexport var utcFridays = utcFriday.range;\nexport var utcSaturdays = utcSaturday.range;\n","import interval from \"./interval.js\";\n\nvar utcYear = interval(function(date) {\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setUTCFullYear(date.getUTCFullYear() + step);\n}, function(start, end) {\n return end.getUTCFullYear() - start.getUTCFullYear();\n}, function(date) {\n return date.getUTCFullYear();\n});\n\n// An optimized implementation for this simple case.\nutcYear.every = function(k) {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : interval(function(date) {\n date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k);\n date.setUTCMonth(0, 1);\n date.setUTCHours(0, 0, 0, 0);\n }, function(date, step) {\n date.setUTCFullYear(date.getUTCFullYear() + step * k);\n });\n};\n\nexport default utcYear;\nexport var utcYears = utcYear.range;\n","import interval from \"./interval.js\";\nimport {durationMinute, durationWeek} from \"./duration.js\";\n\nfunction weekday(i) {\n return interval(function(date) {\n date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7);\n date.setHours(0, 0, 0, 0);\n }, function(date, step) {\n date.setDate(date.getDate() + step * 7);\n }, function(start, end) {\n return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek;\n });\n}\n\nexport var sunday = weekday(0);\nexport var monday = weekday(1);\nexport var tuesday = weekday(2);\nexport var wednesday = weekday(3);\nexport var thursday = weekday(4);\nexport var friday = weekday(5);\nexport var saturday = weekday(6);\n\nexport var sundays = sunday.range;\nexport var mondays = monday.range;\nexport var tuesdays = tuesday.range;\nexport var wednesdays = wednesday.range;\nexport var thursdays = thursday.range;\nexport var fridays = friday.range;\nexport var saturdays = saturday.range;\n","import interval from \"./interval.js\";\n\nvar year = interval(function(date) {\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n}, function(date, step) {\n date.setFullYear(date.getFullYear() + step);\n}, function(start, end) {\n return end.getFullYear() - start.getFullYear();\n}, function(date) {\n return date.getFullYear();\n});\n\n// An optimized implementation for this simple case.\nyear.every = function(k) {\n return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : interval(function(date) {\n date.setFullYear(Math.floor(date.getFullYear() / k) * k);\n date.setMonth(0, 1);\n date.setHours(0, 0, 0, 0);\n }, function(date, step) {\n date.setFullYear(date.getFullYear() + step * k);\n });\n};\n\nexport default year;\nexport var years = year.range;\n","export {\n now,\n timer,\n timerFlush\n} from \"./timer.js\";\n\nexport {\n default as timeout\n} from \"./timeout.js\";\n\nexport {\n default as interval\n} from \"./interval.js\";\n","import {Timer, now} from \"./timer.js\";\n\nexport default function(callback, delay, time) {\n var t = new Timer, total = delay;\n if (delay == null) return t.restart(callback, delay, time), t;\n delay = +delay, time = time == null ? now() : +time;\n t.restart(function tick(elapsed) {\n elapsed += total;\n t.restart(tick, total += delay, time);\n callback(elapsed);\n }, delay, time);\n return t;\n}\n","import {Timer} from \"./timer.js\";\n\nexport default function(callback, delay, time) {\n var t = new Timer;\n delay = delay == null ? 0 : +delay;\n t.restart(function(elapsed) {\n t.stop();\n callback(elapsed + delay);\n }, delay, time);\n return t;\n}\n","var frame = 0, // is an animation frame pending?\n timeout = 0, // is a timeout pending?\n interval = 0, // are any timers active?\n pokeDelay = 1000, // how frequently we check for clock skew\n taskHead,\n taskTail,\n clockLast = 0,\n clockNow = 0,\n clockSkew = 0,\n clock = typeof performance === \"object\" && performance.now ? performance : Date,\n setFrame = typeof window === \"object\" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function(f) { setTimeout(f, 17); };\n\nexport function now() {\n return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);\n}\n\nfunction clearNow() {\n clockNow = 0;\n}\n\nexport function Timer() {\n this._call =\n this._time =\n this._next = null;\n}\n\nTimer.prototype = timer.prototype = {\n constructor: Timer,\n restart: function(callback, delay, time) {\n if (typeof callback !== \"function\") throw new TypeError(\"callback is not a function\");\n time = (time == null ? now() : +time) + (delay == null ? 0 : +delay);\n if (!this._next && taskTail !== this) {\n if (taskTail) taskTail._next = this;\n else taskHead = this;\n taskTail = this;\n }\n this._call = callback;\n this._time = time;\n sleep();\n },\n stop: function() {\n if (this._call) {\n this._call = null;\n this._time = Infinity;\n sleep();\n }\n }\n};\n\nexport function timer(callback, delay, time) {\n var t = new Timer;\n t.restart(callback, delay, time);\n return t;\n}\n\nexport function timerFlush() {\n now(); // Get the current time, if not already set.\n ++frame; // Pretend we’ve set an alarm, if we haven’t already.\n var t = taskHead, e;\n while (t) {\n if ((e = clockNow - t._time) >= 0) t._call.call(null, e);\n t = t._next;\n }\n --frame;\n}\n\nfunction wake() {\n clockNow = (clockLast = clock.now()) + clockSkew;\n frame = timeout = 0;\n try {\n timerFlush();\n } finally {\n frame = 0;\n nap();\n clockNow = 0;\n }\n}\n\nfunction poke() {\n var now = clock.now(), delay = now - clockLast;\n if (delay > pokeDelay) clockSkew -= delay, clockLast = now;\n}\n\nfunction nap() {\n var t0, t1 = taskHead, t2, time = Infinity;\n while (t1) {\n if (t1._call) {\n if (time > t1._time) time = t1._time;\n t0 = t1, t1 = t1._next;\n } else {\n t2 = t1._next, t1._next = null;\n t1 = t0 ? t0._next = t2 : taskHead = t2;\n }\n }\n taskTail = t0;\n sleep(time);\n}\n\nfunction sleep(time) {\n if (frame) return; // Soonest alarm already set, or will be.\n if (timeout) timeout = clearTimeout(timeout);\n var delay = time - clockNow; // Strictly less than if we recomputed clockNow.\n if (delay > 24) {\n if (time < Infinity) timeout = setTimeout(wake, time - clock.now() - clockSkew);\n if (interval) interval = clearInterval(interval);\n } else {\n if (!interval) clockLast = clock.now(), interval = setInterval(poke, pokeDelay);\n frame = 1, setFrame(wake);\n }\n}\n","import {Transition} from \"./transition/index.js\";\nimport {SCHEDULED} from \"./transition/schedule.js\";\n\nvar root = [null];\n\nexport default function(node, name) {\n var schedules = node.__transition,\n schedule,\n i;\n\n if (schedules) {\n name = name == null ? null : name + \"\";\n for (i in schedules) {\n if ((schedule = schedules[i]).state > SCHEDULED && schedule.name === name) {\n return new Transition([[node]], root, name, +i);\n }\n }\n }\n\n return null;\n}\n","import \"./selection/index.js\";\nexport {default as transition} from \"./transition/index.js\";\nexport {default as active} from \"./active.js\";\nexport {default as interrupt} from \"./interrupt.js\";\n","import {STARTING, ENDING, ENDED} from \"./transition/schedule.js\";\n\nexport default function(node, name) {\n var schedules = node.__transition,\n schedule,\n active,\n empty = true,\n i;\n\n if (!schedules) return;\n\n name = name == null ? null : name + \"\";\n\n for (i in schedules) {\n if ((schedule = schedules[i]).name !== name) { empty = false; continue; }\n active = schedule.state > STARTING && schedule.state < ENDING;\n schedule.state = ENDED;\n schedule.timer.stop();\n schedule.on.call(active ? \"interrupt\" : \"cancel\", node, node.__data__, schedule.index, schedule.group);\n delete schedules[i];\n }\n\n if (empty) delete node.__transition;\n}\n","import {selection} from \"d3-selection\";\nimport selection_interrupt from \"./interrupt.js\";\nimport selection_transition from \"./transition.js\";\n\nselection.prototype.interrupt = selection_interrupt;\nselection.prototype.transition = selection_transition;\n","import interrupt from \"../interrupt.js\";\n\nexport default function(name) {\n return this.each(function() {\n interrupt(this, name);\n });\n}\n","import {Transition, newId} from \"../transition/index.js\";\nimport schedule from \"../transition/schedule.js\";\nimport {easeCubicInOut} from \"d3-ease\";\nimport {now} from \"d3-timer\";\n\nvar defaultTiming = {\n time: null, // Set on use.\n delay: 0,\n duration: 250,\n ease: easeCubicInOut\n};\n\nfunction inherit(node, id) {\n var timing;\n while (!(timing = node.__transition) || !(timing = timing[id])) {\n if (!(node = node.parentNode)) {\n return defaultTiming.time = now(), defaultTiming;\n }\n }\n return timing;\n}\n\nexport default function(name) {\n var id,\n timing;\n\n if (name instanceof Transition) {\n id = name._id, name = name._name;\n } else {\n id = newId(), (timing = defaultTiming).time = now(), name = name == null ? null : name + \"\";\n }\n\n for (var groups = this._groups, m = groups.length, j = 0; j < m; ++j) {\n for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {\n if (node = group[i]) {\n schedule(node, name, id, i, group, timing || inherit(node, id));\n }\n }\n }\n\n return new Transition(groups, this._parents, name, id);\n}\n","import {interpolateTransformSvg as interpolateTransform} from \"d3-interpolate\";\nimport {namespace} from \"d3-selection\";\nimport {tweenValue} from \"./tween.js\";\nimport interpolate from \"./interpolate.js\";\n\nfunction attrRemove(name) {\n return function() {\n this.removeAttribute(name);\n };\n}\n\nfunction attrRemoveNS(fullname) {\n return function() {\n this.removeAttributeNS(fullname.space, fullname.local);\n };\n}\n\nfunction attrConstant(name, interpolate, value1) {\n var string00,\n string1 = value1 + \"\",\n interpolate0;\n return function() {\n var string0 = this.getAttribute(name);\n return string0 === string1 ? null\n : string0 === string00 ? interpolate0\n : interpolate0 = interpolate(string00 = string0, value1);\n };\n}\n\nfunction attrConstantNS(fullname, interpolate, value1) {\n var string00,\n string1 = value1 + \"\",\n interpolate0;\n return function() {\n var string0 = this.getAttributeNS(fullname.space, fullname.local);\n return string0 === string1 ? null\n : string0 === string00 ? interpolate0\n : interpolate0 = interpolate(string00 = string0, value1);\n };\n}\n\nfunction attrFunction(name, interpolate, value) {\n var string00,\n string10,\n interpolate0;\n return function() {\n var string0, value1 = value(this), string1;\n if (value1 == null) return void this.removeAttribute(name);\n string0 = this.getAttribute(name);\n string1 = value1 + \"\";\n return string0 === string1 ? null\n : string0 === string00 && string1 === string10 ? interpolate0\n : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));\n };\n}\n\nfunction attrFunctionNS(fullname, interpolate, value) {\n var string00,\n string10,\n interpolate0;\n return function() {\n var string0, value1 = value(this), string1;\n if (value1 == null) return void this.removeAttributeNS(fullname.space, fullname.local);\n string0 = this.getAttributeNS(fullname.space, fullname.local);\n string1 = value1 + \"\";\n return string0 === string1 ? null\n : string0 === string00 && string1 === string10 ? interpolate0\n : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));\n };\n}\n\nexport default function(name, value) {\n var fullname = namespace(name), i = fullname === \"transform\" ? interpolateTransform : interpolate;\n return this.attrTween(name, typeof value === \"function\"\n ? (fullname.local ? attrFunctionNS : attrFunction)(fullname, i, tweenValue(this, \"attr.\" + name, value))\n : value == null ? (fullname.local ? attrRemoveNS : attrRemove)(fullname)\n : (fullname.local ? attrConstantNS : attrConstant)(fullname, i, value));\n}\n","import {namespace} from \"d3-selection\";\n\nfunction attrInterpolate(name, i) {\n return function(t) {\n this.setAttribute(name, i.call(this, t));\n };\n}\n\nfunction attrInterpolateNS(fullname, i) {\n return function(t) {\n this.setAttributeNS(fullname.space, fullname.local, i.call(this, t));\n };\n}\n\nfunction attrTweenNS(fullname, value) {\n var t0, i0;\n function tween() {\n var i = value.apply(this, arguments);\n if (i !== i0) t0 = (i0 = i) && attrInterpolateNS(fullname, i);\n return t0;\n }\n tween._value = value;\n return tween;\n}\n\nfunction attrTween(name, value) {\n var t0, i0;\n function tween() {\n var i = value.apply(this, arguments);\n if (i !== i0) t0 = (i0 = i) && attrInterpolate(name, i);\n return t0;\n }\n tween._value = value;\n return tween;\n}\n\nexport default function(name, value) {\n var key = \"attr.\" + name;\n if (arguments.length < 2) return (key = this.tween(key)) && key._value;\n if (value == null) return this.tween(key, null);\n if (typeof value !== \"function\") throw new Error;\n var fullname = namespace(name);\n return this.tween(key, (fullname.local ? attrTweenNS : attrTween)(fullname, value));\n}\n","import {get, init} from \"./schedule.js\";\n\nfunction delayFunction(id, value) {\n return function() {\n init(this, id).delay = +value.apply(this, arguments);\n };\n}\n\nfunction delayConstant(id, value) {\n return value = +value, function() {\n init(this, id).delay = value;\n };\n}\n\nexport default function(value) {\n var id = this._id;\n\n return arguments.length\n ? this.each((typeof value === \"function\"\n ? delayFunction\n : delayConstant)(id, value))\n : get(this.node(), id).delay;\n}\n","import {get, set} from \"./schedule.js\";\n\nfunction durationFunction(id, value) {\n return function() {\n set(this, id).duration = +value.apply(this, arguments);\n };\n}\n\nfunction durationConstant(id, value) {\n return value = +value, function() {\n set(this, id).duration = value;\n };\n}\n\nexport default function(value) {\n var id = this._id;\n\n return arguments.length\n ? this.each((typeof value === \"function\"\n ? durationFunction\n : durationConstant)(id, value))\n : get(this.node(), id).duration;\n}\n","import {get, set} from \"./schedule.js\";\n\nfunction easeConstant(id, value) {\n if (typeof value !== \"function\") throw new Error;\n return function() {\n set(this, id).ease = value;\n };\n}\n\nexport default function(value) {\n var id = this._id;\n\n return arguments.length\n ? this.each(easeConstant(id, value))\n : get(this.node(), id).ease;\n}\n","import {set} from \"./schedule.js\";\n\nexport default function() {\n var on0, on1, that = this, id = that._id, size = that.size();\n return new Promise(function(resolve, reject) {\n var cancel = {value: reject},\n end = {value: function() { if (--size === 0) resolve(); }};\n\n that.each(function() {\n var schedule = set(this, id),\n on = schedule.on;\n\n // If this node shared a dispatch with the previous node,\n // just assign the updated shared dispatch and we’re done!\n // Otherwise, copy-on-write.\n if (on !== on0) {\n on1 = (on0 = on).copy();\n on1._.cancel.push(cancel);\n on1._.interrupt.push(cancel);\n on1._.end.push(end);\n }\n\n schedule.on = on1;\n });\n });\n}\n","import {matcher} from \"d3-selection\";\nimport {Transition} from \"./index.js\";\n\nexport default function(match) {\n if (typeof match !== \"function\") match = matcher(match);\n\n for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {\n for (var group = groups[j], n = group.length, subgroup = subgroups[j] = [], node, i = 0; i < n; ++i) {\n if ((node = group[i]) && match.call(node, node.__data__, i, group)) {\n subgroup.push(node);\n }\n }\n }\n\n return new Transition(subgroups, this._parents, this._name, this._id);\n}\n","import {selection} from \"d3-selection\";\nimport transition_attr from \"./attr.js\";\nimport transition_attrTween from \"./attrTween.js\";\nimport transition_delay from \"./delay.js\";\nimport transition_duration from \"./duration.js\";\nimport transition_ease from \"./ease.js\";\nimport transition_filter from \"./filter.js\";\nimport transition_merge from \"./merge.js\";\nimport transition_on from \"./on.js\";\nimport transition_remove from \"./remove.js\";\nimport transition_select from \"./select.js\";\nimport transition_selectAll from \"./selectAll.js\";\nimport transition_selection from \"./selection.js\";\nimport transition_style from \"./style.js\";\nimport transition_styleTween from \"./styleTween.js\";\nimport transition_text from \"./text.js\";\nimport transition_textTween from \"./textTween.js\";\nimport transition_transition from \"./transition.js\";\nimport transition_tween from \"./tween.js\";\nimport transition_end from \"./end.js\";\n\nvar id = 0;\n\nexport function Transition(groups, parents, name, id) {\n this._groups = groups;\n this._parents = parents;\n this._name = name;\n this._id = id;\n}\n\nexport default function transition(name) {\n return selection().transition(name);\n}\n\nexport function newId() {\n return ++id;\n}\n\nvar selection_prototype = selection.prototype;\n\nTransition.prototype = transition.prototype = {\n constructor: Transition,\n select: transition_select,\n selectAll: transition_selectAll,\n filter: transition_filter,\n merge: transition_merge,\n selection: transition_selection,\n transition: transition_transition,\n call: selection_prototype.call,\n nodes: selection_prototype.nodes,\n node: selection_prototype.node,\n size: selection_prototype.size,\n empty: selection_prototype.empty,\n each: selection_prototype.each,\n on: transition_on,\n attr: transition_attr,\n attrTween: transition_attrTween,\n style: transition_style,\n styleTween: transition_styleTween,\n text: transition_text,\n textTween: transition_textTween,\n remove: transition_remove,\n tween: transition_tween,\n delay: transition_delay,\n duration: transition_duration,\n ease: transition_ease,\n end: transition_end\n};\n","import {color} from \"d3-color\";\nimport {interpolateNumber, interpolateRgb, interpolateString} from \"d3-interpolate\";\n\nexport default function(a, b) {\n var c;\n return (typeof b === \"number\" ? interpolateNumber\n : b instanceof color ? interpolateRgb\n : (c = color(b)) ? (b = c, interpolateRgb)\n : interpolateString)(a, b);\n}\n","import {Transition} from \"./index.js\";\n\nexport default function(transition) {\n if (transition._id !== this._id) throw new Error;\n\n for (var groups0 = this._groups, groups1 = transition._groups, m0 = groups0.length, m1 = groups1.length, m = Math.min(m0, m1), merges = new Array(m0), j = 0; j < m; ++j) {\n for (var group0 = groups0[j], group1 = groups1[j], n = group0.length, merge = merges[j] = new Array(n), node, i = 0; i < n; ++i) {\n if (node = group0[i] || group1[i]) {\n merge[i] = node;\n }\n }\n }\n\n for (; j < m0; ++j) {\n merges[j] = groups0[j];\n }\n\n return new Transition(merges, this._parents, this._name, this._id);\n}\n","import {get, set, init} from \"./schedule.js\";\n\nfunction start(name) {\n return (name + \"\").trim().split(/^|\\s+/).every(function(t) {\n var i = t.indexOf(\".\");\n if (i >= 0) t = t.slice(0, i);\n return !t || t === \"start\";\n });\n}\n\nfunction onFunction(id, name, listener) {\n var on0, on1, sit = start(name) ? init : set;\n return function() {\n var schedule = sit(this, id),\n on = schedule.on;\n\n // If this node shared a dispatch with the previous node,\n // just assign the updated shared dispatch and we’re done!\n // Otherwise, copy-on-write.\n if (on !== on0) (on1 = (on0 = on).copy()).on(name, listener);\n\n schedule.on = on1;\n };\n}\n\nexport default function(name, listener) {\n var id = this._id;\n\n return arguments.length < 2\n ? get(this.node(), id).on.on(name)\n : this.each(onFunction(id, name, listener));\n}\n","function removeFunction(id) {\n return function() {\n var parent = this.parentNode;\n for (var i in this.__transition) if (+i !== id) return;\n if (parent) parent.removeChild(this);\n };\n}\n\nexport default function() {\n return this.on(\"end.remove\", removeFunction(this._id));\n}\n","import {dispatch} from \"d3-dispatch\";\nimport {timer, timeout} from \"d3-timer\";\n\nvar emptyOn = dispatch(\"start\", \"end\", \"cancel\", \"interrupt\");\nvar emptyTween = [];\n\nexport var CREATED = 0;\nexport var SCHEDULED = 1;\nexport var STARTING = 2;\nexport var STARTED = 3;\nexport var RUNNING = 4;\nexport var ENDING = 5;\nexport var ENDED = 6;\n\nexport default function(node, name, id, index, group, timing) {\n var schedules = node.__transition;\n if (!schedules) node.__transition = {};\n else if (id in schedules) return;\n create(node, id, {\n name: name,\n index: index, // For context during callback.\n group: group, // For context during callback.\n on: emptyOn,\n tween: emptyTween,\n time: timing.time,\n delay: timing.delay,\n duration: timing.duration,\n ease: timing.ease,\n timer: null,\n state: CREATED\n });\n}\n\nexport function init(node, id) {\n var schedule = get(node, id);\n if (schedule.state > CREATED) throw new Error(\"too late; already scheduled\");\n return schedule;\n}\n\nexport function set(node, id) {\n var schedule = get(node, id);\n if (schedule.state > STARTED) throw new Error(\"too late; already running\");\n return schedule;\n}\n\nexport function get(node, id) {\n var schedule = node.__transition;\n if (!schedule || !(schedule = schedule[id])) throw new Error(\"transition not found\");\n return schedule;\n}\n\nfunction create(node, id, self) {\n var schedules = node.__transition,\n tween;\n\n // Initialize the self timer when the transition is created.\n // Note the actual delay is not known until the first callback!\n schedules[id] = self;\n self.timer = timer(schedule, 0, self.time);\n\n function schedule(elapsed) {\n self.state = SCHEDULED;\n self.timer.restart(start, self.delay, self.time);\n\n // If the elapsed delay is less than our first sleep, start immediately.\n if (self.delay <= elapsed) start(elapsed - self.delay);\n }\n\n function start(elapsed) {\n var i, j, n, o;\n\n // If the state is not SCHEDULED, then we previously errored on start.\n if (self.state !== SCHEDULED) return stop();\n\n for (i in schedules) {\n o = schedules[i];\n if (o.name !== self.name) continue;\n\n // While this element already has a starting transition during this frame,\n // defer starting an interrupting transition until that transition has a\n // chance to tick (and possibly end); see d3/d3-transition#54!\n if (o.state === STARTED) return timeout(start);\n\n // Interrupt the active transition, if any.\n if (o.state === RUNNING) {\n o.state = ENDED;\n o.timer.stop();\n o.on.call(\"interrupt\", node, node.__data__, o.index, o.group);\n delete schedules[i];\n }\n\n // Cancel any pre-empted transitions.\n else if (+i < id) {\n o.state = ENDED;\n o.timer.stop();\n o.on.call(\"cancel\", node, node.__data__, o.index, o.group);\n delete schedules[i];\n }\n }\n\n // Defer the first tick to end of the current frame; see d3/d3#1576.\n // Note the transition may be canceled after start and before the first tick!\n // Note this must be scheduled before the start event; see d3/d3-transition#16!\n // Assuming this is successful, subsequent callbacks go straight to tick.\n timeout(function() {\n if (self.state === STARTED) {\n self.state = RUNNING;\n self.timer.restart(tick, self.delay, self.time);\n tick(elapsed);\n }\n });\n\n // Dispatch the start event.\n // Note this must be done before the tween are initialized.\n self.state = STARTING;\n self.on.call(\"start\", node, node.__data__, self.index, self.group);\n if (self.state !== STARTING) return; // interrupted\n self.state = STARTED;\n\n // Initialize the tween, deleting null tween.\n tween = new Array(n = self.tween.length);\n for (i = 0, j = -1; i < n; ++i) {\n if (o = self.tween[i].value.call(node, node.__data__, self.index, self.group)) {\n tween[++j] = o;\n }\n }\n tween.length = j + 1;\n }\n\n function tick(elapsed) {\n var t = elapsed < self.duration ? self.ease.call(null, elapsed / self.duration) : (self.timer.restart(stop), self.state = ENDING, 1),\n i = -1,\n n = tween.length;\n\n while (++i < n) {\n tween[i].call(node, t);\n }\n\n // Dispatch the end event.\n if (self.state === ENDING) {\n self.on.call(\"end\", node, node.__data__, self.index, self.group);\n stop();\n }\n }\n\n function stop() {\n self.state = ENDED;\n self.timer.stop();\n delete schedules[id];\n for (var i in schedules) return; // eslint-disable-line no-unused-vars\n delete node.__transition;\n }\n}\n","import {selector} from \"d3-selection\";\nimport {Transition} from \"./index.js\";\nimport schedule, {get} from \"./schedule.js\";\n\nexport default function(select) {\n var name = this._name,\n id = this._id;\n\n if (typeof select !== \"function\") select = selector(select);\n\n for (var groups = this._groups, m = groups.length, subgroups = new Array(m), j = 0; j < m; ++j) {\n for (var group = groups[j], n = group.length, subgroup = subgroups[j] = new Array(n), node, subnode, i = 0; i < n; ++i) {\n if ((node = group[i]) && (subnode = select.call(node, node.__data__, i, group))) {\n if (\"__data__\" in node) subnode.__data__ = node.__data__;\n subgroup[i] = subnode;\n schedule(subgroup[i], name, id, i, subgroup, get(node, id));\n }\n }\n }\n\n return new Transition(subgroups, this._parents, name, id);\n}\n","import {selectorAll} from \"d3-selection\";\nimport {Transition} from \"./index.js\";\nimport schedule, {get} from \"./schedule.js\";\n\nexport default function(select) {\n var name = this._name,\n id = this._id;\n\n if (typeof select !== \"function\") select = selectorAll(select);\n\n for (var groups = this._groups, m = groups.length, subgroups = [], parents = [], j = 0; j < m; ++j) {\n for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {\n if (node = group[i]) {\n for (var children = select.call(node, node.__data__, i, group), child, inherit = get(node, id), k = 0, l = children.length; k < l; ++k) {\n if (child = children[k]) {\n schedule(child, name, id, k, children, inherit);\n }\n }\n subgroups.push(children);\n parents.push(node);\n }\n }\n }\n\n return new Transition(subgroups, parents, name, id);\n}\n","import {selection} from \"d3-selection\";\n\nvar Selection = selection.prototype.constructor;\n\nexport default function() {\n return new Selection(this._groups, this._parents);\n}\n","import {interpolateTransformCss as interpolateTransform} from \"d3-interpolate\";\nimport {style} from \"d3-selection\";\nimport {set} from \"./schedule.js\";\nimport {tweenValue} from \"./tween.js\";\nimport interpolate from \"./interpolate.js\";\n\nfunction styleNull(name, interpolate) {\n var string00,\n string10,\n interpolate0;\n return function() {\n var string0 = style(this, name),\n string1 = (this.style.removeProperty(name), style(this, name));\n return string0 === string1 ? null\n : string0 === string00 && string1 === string10 ? interpolate0\n : interpolate0 = interpolate(string00 = string0, string10 = string1);\n };\n}\n\nfunction styleRemove(name) {\n return function() {\n this.style.removeProperty(name);\n };\n}\n\nfunction styleConstant(name, interpolate, value1) {\n var string00,\n string1 = value1 + \"\",\n interpolate0;\n return function() {\n var string0 = style(this, name);\n return string0 === string1 ? null\n : string0 === string00 ? interpolate0\n : interpolate0 = interpolate(string00 = string0, value1);\n };\n}\n\nfunction styleFunction(name, interpolate, value) {\n var string00,\n string10,\n interpolate0;\n return function() {\n var string0 = style(this, name),\n value1 = value(this),\n string1 = value1 + \"\";\n if (value1 == null) string1 = value1 = (this.style.removeProperty(name), style(this, name));\n return string0 === string1 ? null\n : string0 === string00 && string1 === string10 ? interpolate0\n : (string10 = string1, interpolate0 = interpolate(string00 = string0, value1));\n };\n}\n\nfunction styleMaybeRemove(id, name) {\n var on0, on1, listener0, key = \"style.\" + name, event = \"end.\" + key, remove;\n return function() {\n var schedule = set(this, id),\n on = schedule.on,\n listener = schedule.value[key] == null ? remove || (remove = styleRemove(name)) : undefined;\n\n // If this node shared a dispatch with the previous node,\n // just assign the updated shared dispatch and we’re done!\n // Otherwise, copy-on-write.\n if (on !== on0 || listener0 !== listener) (on1 = (on0 = on).copy()).on(event, listener0 = listener);\n\n schedule.on = on1;\n };\n}\n\nexport default function(name, value, priority) {\n var i = (name += \"\") === \"transform\" ? interpolateTransform : interpolate;\n return value == null ? this\n .styleTween(name, styleNull(name, i))\n .on(\"end.style.\" + name, styleRemove(name))\n : typeof value === \"function\" ? this\n .styleTween(name, styleFunction(name, i, tweenValue(this, \"style.\" + name, value)))\n .each(styleMaybeRemove(this._id, name))\n : this\n .styleTween(name, styleConstant(name, i, value), priority)\n .on(\"end.style.\" + name, null);\n}\n","function styleInterpolate(name, i, priority) {\n return function(t) {\n this.style.setProperty(name, i.call(this, t), priority);\n };\n}\n\nfunction styleTween(name, value, priority) {\n var t, i0;\n function tween() {\n var i = value.apply(this, arguments);\n if (i !== i0) t = (i0 = i) && styleInterpolate(name, i, priority);\n return t;\n }\n tween._value = value;\n return tween;\n}\n\nexport default function(name, value, priority) {\n var key = \"style.\" + (name += \"\");\n if (arguments.length < 2) return (key = this.tween(key)) && key._value;\n if (value == null) return this.tween(key, null);\n if (typeof value !== \"function\") throw new Error;\n return this.tween(key, styleTween(name, value, priority == null ? \"\" : priority));\n}\n","import {tweenValue} from \"./tween.js\";\n\nfunction textConstant(value) {\n return function() {\n this.textContent = value;\n };\n}\n\nfunction textFunction(value) {\n return function() {\n var value1 = value(this);\n this.textContent = value1 == null ? \"\" : value1;\n };\n}\n\nexport default function(value) {\n return this.tween(\"text\", typeof value === \"function\"\n ? textFunction(tweenValue(this, \"text\", value))\n : textConstant(value == null ? \"\" : value + \"\"));\n}\n","function textInterpolate(i) {\n return function(t) {\n this.textContent = i.call(this, t);\n };\n}\n\nfunction textTween(value) {\n var t0, i0;\n function tween() {\n var i = value.apply(this, arguments);\n if (i !== i0) t0 = (i0 = i) && textInterpolate(i);\n return t0;\n }\n tween._value = value;\n return tween;\n}\n\nexport default function(value) {\n var key = \"text\";\n if (arguments.length < 1) return (key = this.tween(key)) && key._value;\n if (value == null) return this.tween(key, null);\n if (typeof value !== \"function\") throw new Error;\n return this.tween(key, textTween(value));\n}\n","import {Transition, newId} from \"./index.js\";\nimport schedule, {get} from \"./schedule.js\";\n\nexport default function() {\n var name = this._name,\n id0 = this._id,\n id1 = newId();\n\n for (var groups = this._groups, m = groups.length, j = 0; j < m; ++j) {\n for (var group = groups[j], n = group.length, node, i = 0; i < n; ++i) {\n if (node = group[i]) {\n var inherit = get(node, id0);\n schedule(node, name, id1, i, group, {\n time: inherit.time + inherit.delay + inherit.duration,\n delay: 0,\n duration: inherit.duration,\n ease: inherit.ease\n });\n }\n }\n }\n\n return new Transition(groups, this._parents, name, id1);\n}\n","import {get, set} from \"./schedule.js\";\n\nfunction tweenRemove(id, name) {\n var tween0, tween1;\n return function() {\n var schedule = set(this, id),\n tween = schedule.tween;\n\n // If this node shared tween with the previous node,\n // just assign the updated shared tween and we’re done!\n // Otherwise, copy-on-write.\n if (tween !== tween0) {\n tween1 = tween0 = tween;\n for (var i = 0, n = tween1.length; i < n; ++i) {\n if (tween1[i].name === name) {\n tween1 = tween1.slice();\n tween1.splice(i, 1);\n break;\n }\n }\n }\n\n schedule.tween = tween1;\n };\n}\n\nfunction tweenFunction(id, name, value) {\n var tween0, tween1;\n if (typeof value !== \"function\") throw new Error;\n return function() {\n var schedule = set(this, id),\n tween = schedule.tween;\n\n // If this node shared tween with the previous node,\n // just assign the updated shared tween and we’re done!\n // Otherwise, copy-on-write.\n if (tween !== tween0) {\n tween1 = (tween0 = tween).slice();\n for (var t = {name: name, value: value}, i = 0, n = tween1.length; i < n; ++i) {\n if (tween1[i].name === name) {\n tween1[i] = t;\n break;\n }\n }\n if (i === n) tween1.push(t);\n }\n\n schedule.tween = tween1;\n };\n}\n\nexport default function(name, value) {\n var id = this._id;\n\n name += \"\";\n\n if (arguments.length < 2) {\n var tween = get(this.node(), id).tween;\n for (var i = 0, n = tween.length, t; i < n; ++i) {\n if ((t = tween[i]).name === name) {\n return t.value;\n }\n }\n return null;\n }\n\n return this.each((value == null ? tweenRemove : tweenFunction)(id, name, value));\n}\n\nexport function tweenValue(transition, name, value) {\n var id = transition._id;\n\n transition.each(function() {\n var schedule = set(this, id);\n (schedule.value || (schedule.value = {}))[name] = value.apply(this, arguments);\n });\n\n return function(node) {\n return get(node, id).value[name];\n };\n}\n","import {RedBlackNode} from \"./RedBlackTree\";\nimport {createCell} from \"./Cell\";\nimport {attachCircle, detachCircle} from \"./Circle\";\nimport {createEdge, setEdgeEnd} from \"./Edge\";\nimport {beaches, epsilon} from \"./Diagram\";\n\nvar beachPool = [];\n\nfunction Beach() {\n RedBlackNode(this);\n this.edge =\n this.site =\n this.circle = null;\n}\n\nfunction createBeach(site) {\n var beach = beachPool.pop() || new Beach;\n beach.site = site;\n return beach;\n}\n\nfunction detachBeach(beach) {\n detachCircle(beach);\n beaches.remove(beach);\n beachPool.push(beach);\n RedBlackNode(beach);\n}\n\nexport function removeBeach(beach) {\n var circle = beach.circle,\n x = circle.x,\n y = circle.cy,\n vertex = [x, y],\n previous = beach.P,\n next = beach.N,\n disappearing = [beach];\n\n detachBeach(beach);\n\n var lArc = previous;\n while (lArc.circle\n && Math.abs(x - lArc.circle.x) < epsilon\n && Math.abs(y - lArc.circle.cy) < epsilon) {\n previous = lArc.P;\n disappearing.unshift(lArc);\n detachBeach(lArc);\n lArc = previous;\n }\n\n disappearing.unshift(lArc);\n detachCircle(lArc);\n\n var rArc = next;\n while (rArc.circle\n && Math.abs(x - rArc.circle.x) < epsilon\n && Math.abs(y - rArc.circle.cy) < epsilon) {\n next = rArc.N;\n disappearing.push(rArc);\n detachBeach(rArc);\n rArc = next;\n }\n\n disappearing.push(rArc);\n detachCircle(rArc);\n\n var nArcs = disappearing.length,\n iArc;\n for (iArc = 1; iArc < nArcs; ++iArc) {\n rArc = disappearing[iArc];\n lArc = disappearing[iArc - 1];\n setEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex);\n }\n\n lArc = disappearing[0];\n rArc = disappearing[nArcs - 1];\n rArc.edge = createEdge(lArc.site, rArc.site, null, vertex);\n\n attachCircle(lArc);\n attachCircle(rArc);\n}\n\nexport function addBeach(site) {\n var x = site[0],\n directrix = site[1],\n lArc,\n rArc,\n dxl,\n dxr,\n node = beaches._;\n\n while (node) {\n dxl = leftBreakPoint(node, directrix) - x;\n if (dxl > epsilon) node = node.L; else {\n dxr = x - rightBreakPoint(node, directrix);\n if (dxr > epsilon) {\n if (!node.R) {\n lArc = node;\n break;\n }\n node = node.R;\n } else {\n if (dxl > -epsilon) {\n lArc = node.P;\n rArc = node;\n } else if (dxr > -epsilon) {\n lArc = node;\n rArc = node.N;\n } else {\n lArc = rArc = node;\n }\n break;\n }\n }\n }\n\n createCell(site);\n var newArc = createBeach(site);\n beaches.insert(lArc, newArc);\n\n if (!lArc && !rArc) return;\n\n if (lArc === rArc) {\n detachCircle(lArc);\n rArc = createBeach(lArc.site);\n beaches.insert(newArc, rArc);\n newArc.edge = rArc.edge = createEdge(lArc.site, newArc.site);\n attachCircle(lArc);\n attachCircle(rArc);\n return;\n }\n\n if (!rArc) { // && lArc\n newArc.edge = createEdge(lArc.site, newArc.site);\n return;\n }\n\n // else lArc !== rArc\n detachCircle(lArc);\n detachCircle(rArc);\n\n var lSite = lArc.site,\n ax = lSite[0],\n ay = lSite[1],\n bx = site[0] - ax,\n by = site[1] - ay,\n rSite = rArc.site,\n cx = rSite[0] - ax,\n cy = rSite[1] - ay,\n d = 2 * (bx * cy - by * cx),\n hb = bx * bx + by * by,\n hc = cx * cx + cy * cy,\n vertex = [(cy * hb - by * hc) / d + ax, (bx * hc - cx * hb) / d + ay];\n\n setEdgeEnd(rArc.edge, lSite, rSite, vertex);\n newArc.edge = createEdge(lSite, site, null, vertex);\n rArc.edge = createEdge(site, rSite, null, vertex);\n attachCircle(lArc);\n attachCircle(rArc);\n}\n\nfunction leftBreakPoint(arc, directrix) {\n var site = arc.site,\n rfocx = site[0],\n rfocy = site[1],\n pby2 = rfocy - directrix;\n\n if (!pby2) return rfocx;\n\n var lArc = arc.P;\n if (!lArc) return -Infinity;\n\n site = lArc.site;\n var lfocx = site[0],\n lfocy = site[1],\n plby2 = lfocy - directrix;\n\n if (!plby2) return lfocx;\n\n var hl = lfocx - rfocx,\n aby2 = 1 / pby2 - 1 / plby2,\n b = hl / plby2;\n\n if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx;\n\n return (rfocx + lfocx) / 2;\n}\n\nfunction rightBreakPoint(arc, directrix) {\n var rArc = arc.N;\n if (rArc) return leftBreakPoint(rArc, directrix);\n var site = arc.site;\n return site[1] === directrix ? site[0] : Infinity;\n}\n","import {createBorderEdge} from \"./Edge\";\nimport {cells, edges, epsilon} from \"./Diagram\";\n\nexport function createCell(site) {\n return cells[site.index] = {\n site: site,\n halfedges: []\n };\n}\n\nfunction cellHalfedgeAngle(cell, edge) {\n var site = cell.site,\n va = edge.left,\n vb = edge.right;\n if (site === vb) vb = va, va = site;\n if (vb) return Math.atan2(vb[1] - va[1], vb[0] - va[0]);\n if (site === va) va = edge[1], vb = edge[0];\n else va = edge[0], vb = edge[1];\n return Math.atan2(va[0] - vb[0], vb[1] - va[1]);\n}\n\nexport function cellHalfedgeStart(cell, edge) {\n return edge[+(edge.left !== cell.site)];\n}\n\nexport function cellHalfedgeEnd(cell, edge) {\n return edge[+(edge.left === cell.site)];\n}\n\nexport function sortCellHalfedges() {\n for (var i = 0, n = cells.length, cell, halfedges, j, m; i < n; ++i) {\n if ((cell = cells[i]) && (m = (halfedges = cell.halfedges).length)) {\n var index = new Array(m),\n array = new Array(m);\n for (j = 0; j < m; ++j) index[j] = j, array[j] = cellHalfedgeAngle(cell, edges[halfedges[j]]);\n index.sort(function(i, j) { return array[j] - array[i]; });\n for (j = 0; j < m; ++j) array[j] = halfedges[index[j]];\n for (j = 0; j < m; ++j) halfedges[j] = array[j];\n }\n }\n}\n\nexport function clipCells(x0, y0, x1, y1) {\n var nCells = cells.length,\n iCell,\n cell,\n site,\n iHalfedge,\n halfedges,\n nHalfedges,\n start,\n startX,\n startY,\n end,\n endX,\n endY,\n cover = true;\n\n for (iCell = 0; iCell < nCells; ++iCell) {\n if (cell = cells[iCell]) {\n site = cell.site;\n halfedges = cell.halfedges;\n iHalfedge = halfedges.length;\n\n // Remove any dangling clipped edges.\n while (iHalfedge--) {\n if (!edges[halfedges[iHalfedge]]) {\n halfedges.splice(iHalfedge, 1);\n }\n }\n\n // Insert any border edges as necessary.\n iHalfedge = 0, nHalfedges = halfedges.length;\n while (iHalfedge < nHalfedges) {\n end = cellHalfedgeEnd(cell, edges[halfedges[iHalfedge]]), endX = end[0], endY = end[1];\n start = cellHalfedgeStart(cell, edges[halfedges[++iHalfedge % nHalfedges]]), startX = start[0], startY = start[1];\n if (Math.abs(endX - startX) > epsilon || Math.abs(endY - startY) > epsilon) {\n halfedges.splice(iHalfedge, 0, edges.push(createBorderEdge(site, end,\n Math.abs(endX - x0) < epsilon && y1 - endY > epsilon ? [x0, Math.abs(startX - x0) < epsilon ? startY : y1]\n : Math.abs(endY - y1) < epsilon && x1 - endX > epsilon ? [Math.abs(startY - y1) < epsilon ? startX : x1, y1]\n : Math.abs(endX - x1) < epsilon && endY - y0 > epsilon ? [x1, Math.abs(startX - x1) < epsilon ? startY : y0]\n : Math.abs(endY - y0) < epsilon && endX - x0 > epsilon ? [Math.abs(startY - y0) < epsilon ? startX : x0, y0]\n : null)) - 1);\n ++nHalfedges;\n }\n }\n\n if (nHalfedges) cover = false;\n }\n }\n\n // If there weren’t any edges, have the closest site cover the extent.\n // It doesn’t matter which corner of the extent we measure!\n if (cover) {\n var dx, dy, d2, dc = Infinity;\n\n for (iCell = 0, cover = null; iCell < nCells; ++iCell) {\n if (cell = cells[iCell]) {\n site = cell.site;\n dx = site[0] - x0;\n dy = site[1] - y0;\n d2 = dx * dx + dy * dy;\n if (d2 < dc) dc = d2, cover = cell;\n }\n }\n\n if (cover) {\n var v00 = [x0, y0], v01 = [x0, y1], v11 = [x1, y1], v10 = [x1, y0];\n cover.halfedges.push(\n edges.push(createBorderEdge(site = cover.site, v00, v01)) - 1,\n edges.push(createBorderEdge(site, v01, v11)) - 1,\n edges.push(createBorderEdge(site, v11, v10)) - 1,\n edges.push(createBorderEdge(site, v10, v00)) - 1\n );\n }\n }\n\n // Lastly delete any cells with no edges; these were entirely clipped.\n for (iCell = 0; iCell < nCells; ++iCell) {\n if (cell = cells[iCell]) {\n if (!cell.halfedges.length) {\n delete cells[iCell];\n }\n }\n }\n}\n","import {RedBlackNode} from \"./RedBlackTree\";\nimport {circles, epsilon2} from \"./Diagram\";\n\nvar circlePool = [];\n\nexport var firstCircle;\n\nfunction Circle() {\n RedBlackNode(this);\n this.x =\n this.y =\n this.arc =\n this.site =\n this.cy = null;\n}\n\nexport function attachCircle(arc) {\n var lArc = arc.P,\n rArc = arc.N;\n\n if (!lArc || !rArc) return;\n\n var lSite = lArc.site,\n cSite = arc.site,\n rSite = rArc.site;\n\n if (lSite === rSite) return;\n\n var bx = cSite[0],\n by = cSite[1],\n ax = lSite[0] - bx,\n ay = lSite[1] - by,\n cx = rSite[0] - bx,\n cy = rSite[1] - by;\n\n var d = 2 * (ax * cy - ay * cx);\n if (d >= -epsilon2) return;\n\n var ha = ax * ax + ay * ay,\n hc = cx * cx + cy * cy,\n x = (cy * ha - ay * hc) / d,\n y = (ax * hc - cx * ha) / d;\n\n var circle = circlePool.pop() || new Circle;\n circle.arc = arc;\n circle.site = cSite;\n circle.x = x + bx;\n circle.y = (circle.cy = y + by) + Math.sqrt(x * x + y * y); // y bottom\n\n arc.circle = circle;\n\n var before = null,\n node = circles._;\n\n while (node) {\n if (circle.y < node.y || (circle.y === node.y && circle.x <= node.x)) {\n if (node.L) node = node.L;\n else { before = node.P; break; }\n } else {\n if (node.R) node = node.R;\n else { before = node; break; }\n }\n }\n\n circles.insert(before, circle);\n if (!before) firstCircle = circle;\n}\n\nexport function detachCircle(arc) {\n var circle = arc.circle;\n if (circle) {\n if (!circle.P) firstCircle = circle.N;\n circles.remove(circle);\n circlePool.push(circle);\n RedBlackNode(circle);\n arc.circle = null;\n }\n}\n","import {addBeach, removeBeach} from \"./Beach\";\nimport {sortCellHalfedges, cellHalfedgeStart, clipCells} from \"./Cell\";\nimport {firstCircle} from \"./Circle\";\nimport {clipEdges} from \"./Edge\";\nimport RedBlackTree from \"./RedBlackTree\";\n\nexport var epsilon = 1e-6;\nexport var epsilon2 = 1e-12;\nexport var beaches;\nexport var cells;\nexport var circles;\nexport var edges;\n\nfunction triangleArea(a, b, c) {\n return (a[0] - c[0]) * (b[1] - a[1]) - (a[0] - b[0]) * (c[1] - a[1]);\n}\n\nfunction lexicographic(a, b) {\n return b[1] - a[1]\n || b[0] - a[0];\n}\n\nexport default function Diagram(sites, extent) {\n var site = sites.sort(lexicographic).pop(),\n x,\n y,\n circle;\n\n edges = [];\n cells = new Array(sites.length);\n beaches = new RedBlackTree;\n circles = new RedBlackTree;\n\n while (true) {\n circle = firstCircle;\n if (site && (!circle || site[1] < circle.y || (site[1] === circle.y && site[0] < circle.x))) {\n if (site[0] !== x || site[1] !== y) {\n addBeach(site);\n x = site[0], y = site[1];\n }\n site = sites.pop();\n } else if (circle) {\n removeBeach(circle.arc);\n } else {\n break;\n }\n }\n\n sortCellHalfedges();\n\n if (extent) {\n var x0 = +extent[0][0],\n y0 = +extent[0][1],\n x1 = +extent[1][0],\n y1 = +extent[1][1];\n clipEdges(x0, y0, x1, y1);\n clipCells(x0, y0, x1, y1);\n }\n\n this.edges = edges;\n this.cells = cells;\n\n beaches =\n circles =\n edges =\n cells = null;\n}\n\nDiagram.prototype = {\n constructor: Diagram,\n\n polygons: function() {\n var edges = this.edges;\n\n return this.cells.map(function(cell) {\n var polygon = cell.halfedges.map(function(i) { return cellHalfedgeStart(cell, edges[i]); });\n polygon.data = cell.site.data;\n return polygon;\n });\n },\n\n triangles: function() {\n var triangles = [],\n edges = this.edges;\n\n this.cells.forEach(function(cell, i) {\n if (!(m = (halfedges = cell.halfedges).length)) return;\n var site = cell.site,\n halfedges,\n j = -1,\n m,\n s0,\n e1 = edges[halfedges[m - 1]],\n s1 = e1.left === site ? e1.right : e1.left;\n\n while (++j < m) {\n s0 = s1;\n e1 = edges[halfedges[j]];\n s1 = e1.left === site ? e1.right : e1.left;\n if (s0 && s1 && i < s0.index && i < s1.index && triangleArea(site, s0, s1) < 0) {\n triangles.push([site.data, s0.data, s1.data]);\n }\n }\n });\n\n return triangles;\n },\n\n links: function() {\n return this.edges.filter(function(edge) {\n return edge.right;\n }).map(function(edge) {\n return {\n source: edge.left.data,\n target: edge.right.data\n };\n });\n },\n\n find: function(x, y, radius) {\n var that = this, i0, i1 = that._found || 0, n = that.cells.length, cell;\n\n // Use the previously-found cell, or start with an arbitrary one.\n while (!(cell = that.cells[i1])) if (++i1 >= n) return null;\n var dx = x - cell.site[0], dy = y - cell.site[1], d2 = dx * dx + dy * dy;\n\n // Traverse the half-edges to find a closer cell, if any.\n do {\n cell = that.cells[i0 = i1], i1 = null;\n cell.halfedges.forEach(function(e) {\n var edge = that.edges[e], v = edge.left;\n if ((v === cell.site || !v) && !(v = edge.right)) return;\n var vx = x - v[0], vy = y - v[1], v2 = vx * vx + vy * vy;\n if (v2 < d2) d2 = v2, i1 = v.index;\n });\n } while (i1 !== null);\n\n that._found = i0;\n\n return radius == null || d2 <= radius * radius ? cell.site : null;\n }\n}\n","import {cells, edges, epsilon} from \"./Diagram\";\n\nexport function createEdge(left, right, v0, v1) {\n var edge = [null, null],\n index = edges.push(edge) - 1;\n edge.left = left;\n edge.right = right;\n if (v0) setEdgeEnd(edge, left, right, v0);\n if (v1) setEdgeEnd(edge, right, left, v1);\n cells[left.index].halfedges.push(index);\n cells[right.index].halfedges.push(index);\n return edge;\n}\n\nexport function createBorderEdge(left, v0, v1) {\n var edge = [v0, v1];\n edge.left = left;\n return edge;\n}\n\nexport function setEdgeEnd(edge, left, right, vertex) {\n if (!edge[0] && !edge[1]) {\n edge[0] = vertex;\n edge.left = left;\n edge.right = right;\n } else if (edge.left === right) {\n edge[1] = vertex;\n } else {\n edge[0] = vertex;\n }\n}\n\n// Liang–Barsky line clipping.\nfunction clipEdge(edge, x0, y0, x1, y1) {\n var a = edge[0],\n b = edge[1],\n ax = a[0],\n ay = a[1],\n bx = b[0],\n by = b[1],\n t0 = 0,\n t1 = 1,\n dx = bx - ax,\n dy = by - ay,\n r;\n\n r = x0 - ax;\n if (!dx && r > 0) return;\n r /= dx;\n if (dx < 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n } else if (dx > 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n }\n\n r = x1 - ax;\n if (!dx && r < 0) return;\n r /= dx;\n if (dx < 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n } else if (dx > 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n }\n\n r = y0 - ay;\n if (!dy && r > 0) return;\n r /= dy;\n if (dy < 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n } else if (dy > 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n }\n\n r = y1 - ay;\n if (!dy && r < 0) return;\n r /= dy;\n if (dy < 0) {\n if (r > t1) return;\n if (r > t0) t0 = r;\n } else if (dy > 0) {\n if (r < t0) return;\n if (r < t1) t1 = r;\n }\n\n if (!(t0 > 0) && !(t1 < 1)) return true; // TODO Better check?\n\n if (t0 > 0) edge[0] = [ax + t0 * dx, ay + t0 * dy];\n if (t1 < 1) edge[1] = [ax + t1 * dx, ay + t1 * dy];\n return true;\n}\n\nfunction connectEdge(edge, x0, y0, x1, y1) {\n var v1 = edge[1];\n if (v1) return true;\n\n var v0 = edge[0],\n left = edge.left,\n right = edge.right,\n lx = left[0],\n ly = left[1],\n rx = right[0],\n ry = right[1],\n fx = (lx + rx) / 2,\n fy = (ly + ry) / 2,\n fm,\n fb;\n\n if (ry === ly) {\n if (fx < x0 || fx >= x1) return;\n if (lx > rx) {\n if (!v0) v0 = [fx, y0];\n else if (v0[1] >= y1) return;\n v1 = [fx, y1];\n } else {\n if (!v0) v0 = [fx, y1];\n else if (v0[1] < y0) return;\n v1 = [fx, y0];\n }\n } else {\n fm = (lx - rx) / (ry - ly);\n fb = fy - fm * fx;\n if (fm < -1 || fm > 1) {\n if (lx > rx) {\n if (!v0) v0 = [(y0 - fb) / fm, y0];\n else if (v0[1] >= y1) return;\n v1 = [(y1 - fb) / fm, y1];\n } else {\n if (!v0) v0 = [(y1 - fb) / fm, y1];\n else if (v0[1] < y0) return;\n v1 = [(y0 - fb) / fm, y0];\n }\n } else {\n if (ly < ry) {\n if (!v0) v0 = [x0, fm * x0 + fb];\n else if (v0[0] >= x1) return;\n v1 = [x1, fm * x1 + fb];\n } else {\n if (!v0) v0 = [x1, fm * x1 + fb];\n else if (v0[0] < x0) return;\n v1 = [x0, fm * x0 + fb];\n }\n }\n }\n\n edge[0] = v0;\n edge[1] = v1;\n return true;\n}\n\nexport function clipEdges(x0, y0, x1, y1) {\n var i = edges.length,\n edge;\n\n while (i--) {\n if (!connectEdge(edge = edges[i], x0, y0, x1, y1)\n || !clipEdge(edge, x0, y0, x1, y1)\n || !(Math.abs(edge[0][0] - edge[1][0]) > epsilon\n || Math.abs(edge[0][1] - edge[1][1]) > epsilon)) {\n delete edges[i];\n }\n }\n}\n","function RedBlackTree() {\n this._ = null; // root node\n}\n\nexport function RedBlackNode(node) {\n node.U = // parent node\n node.C = // color - true for red, false for black\n node.L = // left node\n node.R = // right node\n node.P = // previous node\n node.N = null; // next node\n}\n\nRedBlackTree.prototype = {\n constructor: RedBlackTree,\n\n insert: function(after, node) {\n var parent, grandpa, uncle;\n\n if (after) {\n node.P = after;\n node.N = after.N;\n if (after.N) after.N.P = node;\n after.N = node;\n if (after.R) {\n after = after.R;\n while (after.L) after = after.L;\n after.L = node;\n } else {\n after.R = node;\n }\n parent = after;\n } else if (this._) {\n after = RedBlackFirst(this._);\n node.P = null;\n node.N = after;\n after.P = after.L = node;\n parent = after;\n } else {\n node.P = node.N = null;\n this._ = node;\n parent = null;\n }\n node.L = node.R = null;\n node.U = parent;\n node.C = true;\n\n after = node;\n while (parent && parent.C) {\n grandpa = parent.U;\n if (parent === grandpa.L) {\n uncle = grandpa.R;\n if (uncle && uncle.C) {\n parent.C = uncle.C = false;\n grandpa.C = true;\n after = grandpa;\n } else {\n if (after === parent.R) {\n RedBlackRotateLeft(this, parent);\n after = parent;\n parent = after.U;\n }\n parent.C = false;\n grandpa.C = true;\n RedBlackRotateRight(this, grandpa);\n }\n } else {\n uncle = grandpa.L;\n if (uncle && uncle.C) {\n parent.C = uncle.C = false;\n grandpa.C = true;\n after = grandpa;\n } else {\n if (after === parent.L) {\n RedBlackRotateRight(this, parent);\n after = parent;\n parent = after.U;\n }\n parent.C = false;\n grandpa.C = true;\n RedBlackRotateLeft(this, grandpa);\n }\n }\n parent = after.U;\n }\n this._.C = false;\n },\n\n remove: function(node) {\n if (node.N) node.N.P = node.P;\n if (node.P) node.P.N = node.N;\n node.N = node.P = null;\n\n var parent = node.U,\n sibling,\n left = node.L,\n right = node.R,\n next,\n red;\n\n if (!left) next = right;\n else if (!right) next = left;\n else next = RedBlackFirst(right);\n\n if (parent) {\n if (parent.L === node) parent.L = next;\n else parent.R = next;\n } else {\n this._ = next;\n }\n\n if (left && right) {\n red = next.C;\n next.C = node.C;\n next.L = left;\n left.U = next;\n if (next !== right) {\n parent = next.U;\n next.U = node.U;\n node = next.R;\n parent.L = node;\n next.R = right;\n right.U = next;\n } else {\n next.U = parent;\n parent = next;\n node = next.R;\n }\n } else {\n red = node.C;\n node = next;\n }\n\n if (node) node.U = parent;\n if (red) return;\n if (node && node.C) { node.C = false; return; }\n\n do {\n if (node === this._) break;\n if (node === parent.L) {\n sibling = parent.R;\n if (sibling.C) {\n sibling.C = false;\n parent.C = true;\n RedBlackRotateLeft(this, parent);\n sibling = parent.R;\n }\n if ((sibling.L && sibling.L.C)\n || (sibling.R && sibling.R.C)) {\n if (!sibling.R || !sibling.R.C) {\n sibling.L.C = false;\n sibling.C = true;\n RedBlackRotateRight(this, sibling);\n sibling = parent.R;\n }\n sibling.C = parent.C;\n parent.C = sibling.R.C = false;\n RedBlackRotateLeft(this, parent);\n node = this._;\n break;\n }\n } else {\n sibling = parent.L;\n if (sibling.C) {\n sibling.C = false;\n parent.C = true;\n RedBlackRotateRight(this, parent);\n sibling = parent.L;\n }\n if ((sibling.L && sibling.L.C)\n || (sibling.R && sibling.R.C)) {\n if (!sibling.L || !sibling.L.C) {\n sibling.R.C = false;\n sibling.C = true;\n RedBlackRotateLeft(this, sibling);\n sibling = parent.L;\n }\n sibling.C = parent.C;\n parent.C = sibling.L.C = false;\n RedBlackRotateRight(this, parent);\n node = this._;\n break;\n }\n }\n sibling.C = true;\n node = parent;\n parent = parent.U;\n } while (!node.C);\n\n if (node) node.C = false;\n }\n};\n\nfunction RedBlackRotateLeft(tree, node) {\n var p = node,\n q = node.R,\n parent = p.U;\n\n if (parent) {\n if (parent.L === p) parent.L = q;\n else parent.R = q;\n } else {\n tree._ = q;\n }\n\n q.U = parent;\n p.U = q;\n p.R = q.L;\n if (p.R) p.R.U = p;\n q.L = p;\n}\n\nfunction RedBlackRotateRight(tree, node) {\n var p = node,\n q = node.L,\n parent = p.U;\n\n if (parent) {\n if (parent.L === p) parent.L = q;\n else parent.R = q;\n } else {\n tree._ = q;\n }\n\n q.U = parent;\n p.U = q;\n p.L = q.R;\n if (p.L) p.L.U = p;\n q.R = p;\n}\n\nfunction RedBlackFirst(node) {\n while (node.L) node = node.L;\n return node;\n}\n\nexport default RedBlackTree;\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","export {default as voronoi} from \"./voronoi\";\n","export function x(d) {\n return d[0];\n}\n\nexport function y(d) {\n return d[1];\n}\n","import constant from \"./constant\";\nimport {x as pointX, y as pointY} from \"./point\";\nimport Diagram, {epsilon} from \"./Diagram\";\n\nexport default function() {\n var x = pointX,\n y = pointY,\n extent = null;\n\n function voronoi(data) {\n return new Diagram(data.map(function(d, i) {\n var s = [Math.round(x(d, i, data) / epsilon) * epsilon, Math.round(y(d, i, data) / epsilon) * epsilon];\n s.index = i;\n s.data = d;\n return s;\n }), extent);\n }\n\n voronoi.polygons = function(data) {\n return voronoi(data).polygons();\n };\n\n voronoi.links = function(data) {\n return voronoi(data).links();\n };\n\n voronoi.triangles = function(data) {\n return voronoi(data).triangles();\n };\n\n voronoi.x = function(_) {\n return arguments.length ? (x = typeof _ === \"function\" ? _ : constant(+_), voronoi) : x;\n };\n\n voronoi.y = function(_) {\n return arguments.length ? (y = typeof _ === \"function\" ? _ : constant(+_), voronoi) : y;\n };\n\n voronoi.extent = function(_) {\n return arguments.length ? (extent = _ == null ? null : [[+_[0][0], +_[0][1]], [+_[1][0], +_[1][1]]], voronoi) : extent && [[extent[0][0], extent[0][1]], [extent[1][0], extent[1][1]]];\n };\n\n voronoi.size = function(_) {\n return arguments.length ? (extent = _ == null ? null : [[0, 0], [+_[0], +_[1]]], voronoi) : extent && [extent[1][0] - extent[0][0], extent[1][1] - extent[0][1]];\n };\n\n return voronoi;\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","export default function ZoomEvent(target, type, transform) {\n this.target = target;\n this.type = type;\n this.transform = transform;\n}\n","export {default as zoom} from \"./zoom.js\";\nexport {default as zoomTransform, identity as zoomIdentity} from \"./transform.js\";\n","import {event} from \"d3-selection\";\n\nexport function nopropagation() {\n event.stopImmediatePropagation();\n}\n\nexport default function() {\n event.preventDefault();\n event.stopImmediatePropagation();\n}\n","export function Transform(k, x, y) {\n this.k = k;\n this.x = x;\n this.y = y;\n}\n\nTransform.prototype = {\n constructor: Transform,\n scale: function(k) {\n return k === 1 ? this : new Transform(this.k * k, this.x, this.y);\n },\n translate: function(x, y) {\n return x === 0 & y === 0 ? this : new Transform(this.k, this.x + this.k * x, this.y + this.k * y);\n },\n apply: function(point) {\n return [point[0] * this.k + this.x, point[1] * this.k + this.y];\n },\n applyX: function(x) {\n return x * this.k + this.x;\n },\n applyY: function(y) {\n return y * this.k + this.y;\n },\n invert: function(location) {\n return [(location[0] - this.x) / this.k, (location[1] - this.y) / this.k];\n },\n invertX: function(x) {\n return (x - this.x) / this.k;\n },\n invertY: function(y) {\n return (y - this.y) / this.k;\n },\n rescaleX: function(x) {\n return x.copy().domain(x.range().map(this.invertX, this).map(x.invert, x));\n },\n rescaleY: function(y) {\n return y.copy().domain(y.range().map(this.invertY, this).map(y.invert, y));\n },\n toString: function() {\n return \"translate(\" + this.x + \",\" + this.y + \") scale(\" + this.k + \")\";\n }\n};\n\nexport var identity = new Transform(1, 0, 0);\n\ntransform.prototype = Transform.prototype;\n\nexport default function transform(node) {\n while (!node.__zoom) if (!(node = node.parentNode)) return identity;\n return node.__zoom;\n}\n","import {dispatch} from \"d3-dispatch\";\nimport {dragDisable, dragEnable} from \"d3-drag\";\nimport {interpolateZoom} from \"d3-interpolate\";\nimport {event, customEvent, select, mouse, touch} from \"d3-selection\";\nimport {interrupt} from \"d3-transition\";\nimport constant from \"./constant.js\";\nimport ZoomEvent from \"./event.js\";\nimport {Transform, identity} from \"./transform.js\";\nimport noevent, {nopropagation} from \"./noevent.js\";\n\n// Ignore right-click, since that should open the context menu.\nfunction defaultFilter() {\n return !event.ctrlKey && !event.button;\n}\n\nfunction defaultExtent() {\n var e = this;\n if (e instanceof SVGElement) {\n e = e.ownerSVGElement || e;\n if (e.hasAttribute(\"viewBox\")) {\n e = e.viewBox.baseVal;\n return [[e.x, e.y], [e.x + e.width, e.y + e.height]];\n }\n return [[0, 0], [e.width.baseVal.value, e.height.baseVal.value]];\n }\n return [[0, 0], [e.clientWidth, e.clientHeight]];\n}\n\nfunction defaultTransform() {\n return this.__zoom || identity;\n}\n\nfunction defaultWheelDelta() {\n return -event.deltaY * (event.deltaMode === 1 ? 0.05 : event.deltaMode ? 1 : 0.002);\n}\n\nfunction defaultTouchable() {\n return navigator.maxTouchPoints || (\"ontouchstart\" in this);\n}\n\nfunction defaultConstrain(transform, extent, translateExtent) {\n var dx0 = transform.invertX(extent[0][0]) - translateExtent[0][0],\n dx1 = transform.invertX(extent[1][0]) - translateExtent[1][0],\n dy0 = transform.invertY(extent[0][1]) - translateExtent[0][1],\n dy1 = transform.invertY(extent[1][1]) - translateExtent[1][1];\n return transform.translate(\n dx1 > dx0 ? (dx0 + dx1) / 2 : Math.min(0, dx0) || Math.max(0, dx1),\n dy1 > dy0 ? (dy0 + dy1) / 2 : Math.min(0, dy0) || Math.max(0, dy1)\n );\n}\n\nexport default function() {\n var filter = defaultFilter,\n extent = defaultExtent,\n constrain = defaultConstrain,\n wheelDelta = defaultWheelDelta,\n touchable = defaultTouchable,\n scaleExtent = [0, Infinity],\n translateExtent = [[-Infinity, -Infinity], [Infinity, Infinity]],\n duration = 250,\n interpolate = interpolateZoom,\n listeners = dispatch(\"start\", \"zoom\", \"end\"),\n touchstarting,\n touchending,\n touchDelay = 500,\n wheelDelay = 150,\n clickDistance2 = 0;\n\n function zoom(selection) {\n selection\n .property(\"__zoom\", defaultTransform)\n .on(\"wheel.zoom\", wheeled)\n .on(\"mousedown.zoom\", mousedowned)\n .on(\"dblclick.zoom\", dblclicked)\n .filter(touchable)\n .on(\"touchstart.zoom\", touchstarted)\n .on(\"touchmove.zoom\", touchmoved)\n .on(\"touchend.zoom touchcancel.zoom\", touchended)\n .style(\"touch-action\", \"none\")\n .style(\"-webkit-tap-highlight-color\", \"rgba(0,0,0,0)\");\n }\n\n zoom.transform = function(collection, transform, point) {\n var selection = collection.selection ? collection.selection() : collection;\n selection.property(\"__zoom\", defaultTransform);\n if (collection !== selection) {\n schedule(collection, transform, point);\n } else {\n selection.interrupt().each(function() {\n gesture(this, arguments)\n .start()\n .zoom(null, typeof transform === \"function\" ? transform.apply(this, arguments) : transform)\n .end();\n });\n }\n };\n\n zoom.scaleBy = function(selection, k, p) {\n zoom.scaleTo(selection, function() {\n var k0 = this.__zoom.k,\n k1 = typeof k === \"function\" ? k.apply(this, arguments) : k;\n return k0 * k1;\n }, p);\n };\n\n zoom.scaleTo = function(selection, k, p) {\n zoom.transform(selection, function() {\n var e = extent.apply(this, arguments),\n t0 = this.__zoom,\n p0 = p == null ? centroid(e) : typeof p === \"function\" ? p.apply(this, arguments) : p,\n p1 = t0.invert(p0),\n k1 = typeof k === \"function\" ? k.apply(this, arguments) : k;\n return constrain(translate(scale(t0, k1), p0, p1), e, translateExtent);\n }, p);\n };\n\n zoom.translateBy = function(selection, x, y) {\n zoom.transform(selection, function() {\n return constrain(this.__zoom.translate(\n typeof x === \"function\" ? x.apply(this, arguments) : x,\n typeof y === \"function\" ? y.apply(this, arguments) : y\n ), extent.apply(this, arguments), translateExtent);\n });\n };\n\n zoom.translateTo = function(selection, x, y, p) {\n zoom.transform(selection, function() {\n var e = extent.apply(this, arguments),\n t = this.__zoom,\n p0 = p == null ? centroid(e) : typeof p === \"function\" ? p.apply(this, arguments) : p;\n return constrain(identity.translate(p0[0], p0[1]).scale(t.k).translate(\n typeof x === \"function\" ? -x.apply(this, arguments) : -x,\n typeof y === \"function\" ? -y.apply(this, arguments) : -y\n ), e, translateExtent);\n }, p);\n };\n\n function scale(transform, k) {\n k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], k));\n return k === transform.k ? transform : new Transform(k, transform.x, transform.y);\n }\n\n function translate(transform, p0, p1) {\n var x = p0[0] - p1[0] * transform.k, y = p0[1] - p1[1] * transform.k;\n return x === transform.x && y === transform.y ? transform : new Transform(transform.k, x, y);\n }\n\n function centroid(extent) {\n return [(+extent[0][0] + +extent[1][0]) / 2, (+extent[0][1] + +extent[1][1]) / 2];\n }\n\n function schedule(transition, transform, point) {\n transition\n .on(\"start.zoom\", function() { gesture(this, arguments).start(); })\n .on(\"interrupt.zoom end.zoom\", function() { gesture(this, arguments).end(); })\n .tween(\"zoom\", function() {\n var that = this,\n args = arguments,\n g = gesture(that, args),\n e = extent.apply(that, args),\n p = point == null ? centroid(e) : typeof point === \"function\" ? point.apply(that, args) : point,\n w = Math.max(e[1][0] - e[0][0], e[1][1] - e[0][1]),\n a = that.__zoom,\n b = typeof transform === \"function\" ? transform.apply(that, args) : transform,\n i = interpolate(a.invert(p).concat(w / a.k), b.invert(p).concat(w / b.k));\n return function(t) {\n if (t === 1) t = b; // Avoid rounding error on end.\n else { var l = i(t), k = w / l[2]; t = new Transform(k, p[0] - l[0] * k, p[1] - l[1] * k); }\n g.zoom(null, t);\n };\n });\n }\n\n function gesture(that, args, clean) {\n return (!clean && that.__zooming) || new Gesture(that, args);\n }\n\n function Gesture(that, args) {\n this.that = that;\n this.args = args;\n this.active = 0;\n this.extent = extent.apply(that, args);\n this.taps = 0;\n }\n\n Gesture.prototype = {\n start: function() {\n if (++this.active === 1) {\n this.that.__zooming = this;\n this.emit(\"start\");\n }\n return this;\n },\n zoom: function(key, transform) {\n if (this.mouse && key !== \"mouse\") this.mouse[1] = transform.invert(this.mouse[0]);\n if (this.touch0 && key !== \"touch\") this.touch0[1] = transform.invert(this.touch0[0]);\n if (this.touch1 && key !== \"touch\") this.touch1[1] = transform.invert(this.touch1[0]);\n this.that.__zoom = transform;\n this.emit(\"zoom\");\n return this;\n },\n end: function() {\n if (--this.active === 0) {\n delete this.that.__zooming;\n this.emit(\"end\");\n }\n return this;\n },\n emit: function(type) {\n customEvent(new ZoomEvent(zoom, type, this.that.__zoom), listeners.apply, listeners, [type, this.that, this.args]);\n }\n };\n\n function wheeled() {\n if (!filter.apply(this, arguments)) return;\n var g = gesture(this, arguments),\n t = this.__zoom,\n k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], t.k * Math.pow(2, wheelDelta.apply(this, arguments)))),\n p = mouse(this);\n\n // If the mouse is in the same location as before, reuse it.\n // If there were recent wheel events, reset the wheel idle timeout.\n if (g.wheel) {\n if (g.mouse[0][0] !== p[0] || g.mouse[0][1] !== p[1]) {\n g.mouse[1] = t.invert(g.mouse[0] = p);\n }\n clearTimeout(g.wheel);\n }\n\n // If this wheel event won’t trigger a transform change, ignore it.\n else if (t.k === k) return;\n\n // Otherwise, capture the mouse point and location at the start.\n else {\n g.mouse = [p, t.invert(p)];\n interrupt(this);\n g.start();\n }\n\n noevent();\n g.wheel = setTimeout(wheelidled, wheelDelay);\n g.zoom(\"mouse\", constrain(translate(scale(t, k), g.mouse[0], g.mouse[1]), g.extent, translateExtent));\n\n function wheelidled() {\n g.wheel = null;\n g.end();\n }\n }\n\n function mousedowned() {\n if (touchending || !filter.apply(this, arguments)) return;\n var g = gesture(this, arguments, true),\n v = select(event.view).on(\"mousemove.zoom\", mousemoved, true).on(\"mouseup.zoom\", mouseupped, true),\n p = mouse(this),\n x0 = event.clientX,\n y0 = event.clientY;\n\n dragDisable(event.view);\n nopropagation();\n g.mouse = [p, this.__zoom.invert(p)];\n interrupt(this);\n g.start();\n\n function mousemoved() {\n noevent();\n if (!g.moved) {\n var dx = event.clientX - x0, dy = event.clientY - y0;\n g.moved = dx * dx + dy * dy > clickDistance2;\n }\n g.zoom(\"mouse\", constrain(translate(g.that.__zoom, g.mouse[0] = mouse(g.that), g.mouse[1]), g.extent, translateExtent));\n }\n\n function mouseupped() {\n v.on(\"mousemove.zoom mouseup.zoom\", null);\n dragEnable(event.view, g.moved);\n noevent();\n g.end();\n }\n }\n\n function dblclicked() {\n if (!filter.apply(this, arguments)) return;\n var t0 = this.__zoom,\n p0 = mouse(this),\n p1 = t0.invert(p0),\n k1 = t0.k * (event.shiftKey ? 0.5 : 2),\n t1 = constrain(translate(scale(t0, k1), p0, p1), extent.apply(this, arguments), translateExtent);\n\n noevent();\n if (duration > 0) select(this).transition().duration(duration).call(schedule, t1, p0);\n else select(this).call(zoom.transform, t1);\n }\n\n function touchstarted() {\n if (!filter.apply(this, arguments)) return;\n var touches = event.touches,\n n = touches.length,\n g = gesture(this, arguments, event.changedTouches.length === n),\n started, i, t, p;\n\n nopropagation();\n for (i = 0; i < n; ++i) {\n t = touches[i], p = touch(this, touches, t.identifier);\n p = [p, this.__zoom.invert(p), t.identifier];\n if (!g.touch0) g.touch0 = p, started = true, g.taps = 1 + !!touchstarting;\n else if (!g.touch1 && g.touch0[2] !== p[2]) g.touch1 = p, g.taps = 0;\n }\n\n if (touchstarting) touchstarting = clearTimeout(touchstarting);\n\n if (started) {\n if (g.taps < 2) touchstarting = setTimeout(function() { touchstarting = null; }, touchDelay);\n interrupt(this);\n g.start();\n }\n }\n\n function touchmoved() {\n if (!this.__zooming) return;\n var g = gesture(this, arguments),\n touches = event.changedTouches,\n n = touches.length, i, t, p, l;\n\n noevent();\n if (touchstarting) touchstarting = clearTimeout(touchstarting);\n g.taps = 0;\n for (i = 0; i < n; ++i) {\n t = touches[i], p = touch(this, touches, t.identifier);\n if (g.touch0 && g.touch0[2] === t.identifier) g.touch0[0] = p;\n else if (g.touch1 && g.touch1[2] === t.identifier) g.touch1[0] = p;\n }\n t = g.that.__zoom;\n if (g.touch1) {\n var p0 = g.touch0[0], l0 = g.touch0[1],\n p1 = g.touch1[0], l1 = g.touch1[1],\n dp = (dp = p1[0] - p0[0]) * dp + (dp = p1[1] - p0[1]) * dp,\n dl = (dl = l1[0] - l0[0]) * dl + (dl = l1[1] - l0[1]) * dl;\n t = scale(t, Math.sqrt(dp / dl));\n p = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2];\n l = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2];\n }\n else if (g.touch0) p = g.touch0[0], l = g.touch0[1];\n else return;\n g.zoom(\"touch\", constrain(translate(t, p, l), g.extent, translateExtent));\n }\n\n function touchended() {\n if (!this.__zooming) return;\n var g = gesture(this, arguments),\n touches = event.changedTouches,\n n = touches.length, i, t;\n\n nopropagation();\n if (touchending) clearTimeout(touchending);\n touchending = setTimeout(function() { touchending = null; }, touchDelay);\n for (i = 0; i < n; ++i) {\n t = touches[i];\n if (g.touch0 && g.touch0[2] === t.identifier) delete g.touch0;\n else if (g.touch1 && g.touch1[2] === t.identifier) delete g.touch1;\n }\n if (g.touch1 && !g.touch0) g.touch0 = g.touch1, delete g.touch1;\n if (g.touch0) g.touch0[1] = this.__zoom.invert(g.touch0[0]);\n else {\n g.end();\n // If this was a dbltap, reroute to the (optional) dblclick.zoom handler.\n if (g.taps === 2) {\n var p = select(this).on(\"dblclick.zoom\");\n if (p) p.apply(this, arguments);\n }\n }\n }\n\n zoom.wheelDelta = function(_) {\n return arguments.length ? (wheelDelta = typeof _ === \"function\" ? _ : constant(+_), zoom) : wheelDelta;\n };\n\n zoom.filter = function(_) {\n return arguments.length ? (filter = typeof _ === \"function\" ? _ : constant(!!_), zoom) : filter;\n };\n\n zoom.touchable = function(_) {\n return arguments.length ? (touchable = typeof _ === \"function\" ? _ : constant(!!_), zoom) : touchable;\n };\n\n zoom.extent = function(_) {\n return arguments.length ? (extent = typeof _ === \"function\" ? _ : constant([[+_[0][0], +_[0][1]], [+_[1][0], +_[1][1]]]), zoom) : extent;\n };\n\n zoom.scaleExtent = function(_) {\n return arguments.length ? (scaleExtent[0] = +_[0], scaleExtent[1] = +_[1], zoom) : [scaleExtent[0], scaleExtent[1]];\n };\n\n zoom.translateExtent = function(_) {\n return arguments.length ? (translateExtent[0][0] = +_[0][0], translateExtent[1][0] = +_[1][0], translateExtent[0][1] = +_[0][1], translateExtent[1][1] = +_[1][1], zoom) : [[translateExtent[0][0], translateExtent[0][1]], [translateExtent[1][0], translateExtent[1][1]]];\n };\n\n zoom.constrain = function(_) {\n return arguments.length ? (constrain = _, zoom) : constrain;\n };\n\n zoom.duration = function(_) {\n return arguments.length ? (duration = +_, zoom) : duration;\n };\n\n zoom.interpolate = function(_) {\n return arguments.length ? (interpolate = _, zoom) : interpolate;\n };\n\n zoom.on = function() {\n var value = listeners.on.apply(listeners, arguments);\n return value === listeners ? zoom : value;\n };\n\n zoom.clickDistance = function(_) {\n return arguments.length ? (clickDistance2 = (_ = +_) * _, zoom) : Math.sqrt(clickDistance2);\n };\n\n return zoom;\n}\n","export var name = \"d3\";\nexport var version = \"5.16.0\";\nexport var description = \"Data-Driven Documents\";\nexport var keywords = [\"dom\",\"visualization\",\"svg\",\"animation\",\"canvas\"];\nexport var homepage = \"https://d3js.org\";\nexport var license = \"BSD-3-Clause\";\nexport var author = {\"name\":\"Mike Bostock\",\"url\":\"https://bost.ocks.org/mike\"};\nexport var main = \"dist/d3.node.js\";\nexport var unpkg = \"dist/d3.min.js\";\nexport var jsdelivr = \"dist/d3.min.js\";\nexport var module = \"index.js\";\nexport var repository = {\"type\":\"git\",\"url\":\"https://github.com/d3/d3.git\"};\nexport var files = [\"dist/**/*.js\",\"index.js\"];\nexport var scripts = {\"pretest\":\"rimraf dist && mkdir dist && json2module package.json > dist/package.js && rollup -c\",\"test\":\"tape 'test/**/*-test.js'\",\"prepublishOnly\":\"yarn test\",\"postpublish\":\"git push && git push --tags && cd ../d3.github.com && git pull && cp ../d3/dist/d3.js d3.v5.js && cp ../d3/dist/d3.min.js d3.v5.min.js && git add d3.v5.js d3.v5.min.js && git commit -m \\\"d3 ${npm_package_version}\\\" && git push && cd - && cd ../d3-bower && git pull && cp ../d3/LICENSE ../d3/README.md ../d3/dist/d3.js ../d3/dist/d3.min.js . && git add -- LICENSE README.md d3.js d3.min.js && git commit -m \\\"${npm_package_version}\\\" && git tag -am \\\"${npm_package_version}\\\" v${npm_package_version} && git push && git push --tags && cd - && zip -j dist/d3.zip -- LICENSE README.md API.md CHANGES.md dist/d3.js dist/d3.min.js\"};\nexport var devDependencies = {\"json2module\":\"0.0\",\"rimraf\":\"2\",\"rollup\":\"1\",\"rollup-plugin-ascii\":\"0.0\",\"rollup-plugin-node-resolve\":\"3\",\"rollup-plugin-terser\":\"5\",\"tape\":\"4\"};\nexport var dependencies = {\"d3-array\":\"1\",\"d3-axis\":\"1\",\"d3-brush\":\"1\",\"d3-chord\":\"1\",\"d3-collection\":\"1\",\"d3-color\":\"1\",\"d3-contour\":\"1\",\"d3-dispatch\":\"1\",\"d3-drag\":\"1\",\"d3-dsv\":\"1\",\"d3-ease\":\"1\",\"d3-fetch\":\"1\",\"d3-force\":\"1\",\"d3-format\":\"1\",\"d3-geo\":\"1\",\"d3-hierarchy\":\"1\",\"d3-interpolate\":\"1\",\"d3-path\":\"1\",\"d3-polygon\":\"1\",\"d3-quadtree\":\"1\",\"d3-random\":\"1\",\"d3-scale\":\"2\",\"d3-scale-chromatic\":\"1\",\"d3-selection\":\"1\",\"d3-shape\":\"1\",\"d3-time\":\"1\",\"d3-time-format\":\"2\",\"d3-timer\":\"1\",\"d3-transition\":\"1\",\"d3-voronoi\":\"1\",\"d3-zoom\":\"1\"};\n","export {version} from \"./dist/package.js\";\nexport * from \"d3-array\";\nexport * from \"d3-axis\";\nexport * from \"d3-brush\";\nexport * from \"d3-chord\";\nexport * from \"d3-collection\";\nexport * from \"d3-color\";\nexport * from \"d3-contour\";\nexport * from \"d3-dispatch\";\nexport * from \"d3-drag\";\nexport * from \"d3-dsv\";\nexport * from \"d3-ease\";\nexport * from \"d3-fetch\";\nexport * from \"d3-force\";\nexport * from \"d3-format\";\nexport * from \"d3-geo\";\nexport * from \"d3-hierarchy\";\nexport * from \"d3-interpolate\";\nexport * from \"d3-path\";\nexport * from \"d3-polygon\";\nexport * from \"d3-quadtree\";\nexport * from \"d3-random\";\nexport * from \"d3-scale\";\nexport * from \"d3-scale-chromatic\";\nexport * from \"d3-selection\";\nexport * from \"d3-shape\";\nexport * from \"d3-time\";\nexport * from \"d3-time-format\";\nexport * from \"d3-timer\";\nexport * from \"d3-transition\";\nexport * from \"d3-voronoi\";\nexport * from \"d3-zoom\";\n","var array = Array.prototype;\n\nexport var slice = array.slice;\nexport var map = array.map;\n","export default function(a, b) {\n return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;\n}\n","import ascending from \"./ascending\";\nimport bisector from \"./bisector\";\n\nvar ascendingBisect = bisector(ascending);\nexport var bisectRight = ascendingBisect.right;\nexport var bisectLeft = ascendingBisect.left;\nexport default bisectRight;\n","import ascending from \"./ascending\";\n\nexport default function(compare) {\n if (compare.length === 1) compare = ascendingComparator(compare);\n return {\n left: function(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n var mid = lo + hi >>> 1;\n if (compare(a[mid], x) < 0) lo = mid + 1;\n else hi = mid;\n }\n return lo;\n },\n right: function(a, x, lo, hi) {\n if (lo == null) lo = 0;\n if (hi == null) hi = a.length;\n while (lo < hi) {\n var mid = lo + hi >>> 1;\n if (compare(a[mid], x) > 0) hi = mid;\n else lo = mid + 1;\n }\n return lo;\n }\n };\n}\n\nfunction ascendingComparator(f) {\n return function(d, x) {\n return ascending(f(d), x);\n };\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","import {pair} from \"./pairs\";\n\nexport default function(values0, values1, reduce) {\n var n0 = values0.length,\n n1 = values1.length,\n values = new Array(n0 * n1),\n i0,\n i1,\n i,\n value0;\n\n if (reduce == null) reduce = pair;\n\n for (i0 = i = 0; i0 < n0; ++i0) {\n for (value0 = values0[i0], i1 = 0; i1 < n1; ++i1, ++i) {\n values[i] = reduce(value0, values1[i1]);\n }\n }\n\n return values;\n}\n","export default function(a, b) {\n return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;\n}\n","import variance from \"./variance\";\n\nexport default function(array, f) {\n var v = variance(array, f);\n return v ? Math.sqrt(v) : v;\n}\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n min,\n max;\n\n if (valueof == null) {\n while (++i < n) { // Find the first comparable value.\n if ((value = values[i]) != null && value >= value) {\n min = max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = values[i]) != null) {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n }\n }\n\n else {\n while (++i < n) { // Find the first comparable value.\n if ((value = valueof(values[i], i, values)) != null && value >= value) {\n min = max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = valueof(values[i], i, values)) != null) {\n if (min > value) min = value;\n if (max < value) max = value;\n }\n }\n }\n }\n }\n\n return [min, max];\n}\n","import {slice} from \"./array\";\nimport bisect from \"./bisect\";\nimport constant from \"./constant\";\nimport extent from \"./extent\";\nimport identity from \"./identity\";\nimport range from \"./range\";\nimport {tickStep} from \"./ticks\";\nimport sturges from \"./threshold/sturges\";\n\nexport default function() {\n var value = identity,\n domain = extent,\n threshold = sturges;\n\n function histogram(data) {\n var i,\n n = data.length,\n x,\n values = new Array(n);\n\n for (i = 0; i < n; ++i) {\n values[i] = value(data[i], i, data);\n }\n\n var xz = domain(values),\n x0 = xz[0],\n x1 = xz[1],\n tz = threshold(values, x0, x1);\n\n // Convert number of thresholds into uniform thresholds.\n if (!Array.isArray(tz)) {\n tz = tickStep(x0, x1, tz);\n tz = range(Math.ceil(x0 / tz) * tz, x1, tz); // exclusive\n }\n\n // Remove any thresholds outside the domain.\n var m = tz.length;\n while (tz[0] <= x0) tz.shift(), --m;\n while (tz[m - 1] > x1) tz.pop(), --m;\n\n var bins = new Array(m + 1),\n bin;\n\n // Initialize bins.\n for (i = 0; i <= m; ++i) {\n bin = bins[i] = [];\n bin.x0 = i > 0 ? tz[i - 1] : x0;\n bin.x1 = i < m ? tz[i] : x1;\n }\n\n // Assign data to bins by value, ignoring any outside the domain.\n for (i = 0; i < n; ++i) {\n x = values[i];\n if (x0 <= x && x <= x1) {\n bins[bisect(tz, x, 0, m)].push(data[i]);\n }\n }\n\n return bins;\n }\n\n histogram.value = function(_) {\n return arguments.length ? (value = typeof _ === \"function\" ? _ : constant(_), histogram) : value;\n };\n\n histogram.domain = function(_) {\n return arguments.length ? (domain = typeof _ === \"function\" ? _ : constant([_[0], _[1]]), histogram) : domain;\n };\n\n histogram.thresholds = function(_) {\n return arguments.length ? (threshold = typeof _ === \"function\" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), histogram) : threshold;\n };\n\n return histogram;\n}\n","export default function(x) {\n return x;\n}\n","export {default as bisect, bisectRight, bisectLeft} from \"./bisect\";\nexport {default as ascending} from \"./ascending\";\nexport {default as bisector} from \"./bisector\";\nexport {default as cross} from \"./cross\";\nexport {default as descending} from \"./descending\";\nexport {default as deviation} from \"./deviation\";\nexport {default as extent} from \"./extent\";\nexport {default as histogram} from \"./histogram\";\nexport {default as thresholdFreedmanDiaconis} from \"./threshold/freedmanDiaconis\";\nexport {default as thresholdScott} from \"./threshold/scott\";\nexport {default as thresholdSturges} from \"./threshold/sturges\";\nexport {default as max} from \"./max\";\nexport {default as mean} from \"./mean\";\nexport {default as median} from \"./median\";\nexport {default as merge} from \"./merge\";\nexport {default as min} from \"./min\";\nexport {default as pairs} from \"./pairs\";\nexport {default as permute} from \"./permute\";\nexport {default as quantile} from \"./quantile\";\nexport {default as range} from \"./range\";\nexport {default as scan} from \"./scan\";\nexport {default as shuffle} from \"./shuffle\";\nexport {default as sum} from \"./sum\";\nexport {default as ticks, tickIncrement, tickStep} from \"./ticks\";\nexport {default as transpose} from \"./transpose\";\nexport {default as variance} from \"./variance\";\nexport {default as zip} from \"./zip\";\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n max;\n\n if (valueof == null) {\n while (++i < n) { // Find the first comparable value.\n if ((value = values[i]) != null && value >= value) {\n max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = values[i]) != null && value > max) {\n max = value;\n }\n }\n }\n }\n }\n\n else {\n while (++i < n) { // Find the first comparable value.\n if ((value = valueof(values[i], i, values)) != null && value >= value) {\n max = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = valueof(values[i], i, values)) != null && value > max) {\n max = value;\n }\n }\n }\n }\n }\n\n return max;\n}\n","import number from \"./number\";\n\nexport default function(values, valueof) {\n var n = values.length,\n m = n,\n i = -1,\n value,\n sum = 0;\n\n if (valueof == null) {\n while (++i < n) {\n if (!isNaN(value = number(values[i]))) sum += value;\n else --m;\n }\n }\n\n else {\n while (++i < n) {\n if (!isNaN(value = number(valueof(values[i], i, values)))) sum += value;\n else --m;\n }\n }\n\n if (m) return sum / m;\n}\n","import ascending from \"./ascending\";\nimport number from \"./number\";\nimport quantile from \"./quantile\";\n\nexport default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n numbers = [];\n\n if (valueof == null) {\n while (++i < n) {\n if (!isNaN(value = number(values[i]))) {\n numbers.push(value);\n }\n }\n }\n\n else {\n while (++i < n) {\n if (!isNaN(value = number(valueof(values[i], i, values)))) {\n numbers.push(value);\n }\n }\n }\n\n return quantile(numbers.sort(ascending), 0.5);\n}\n","export default function(arrays) {\n var n = arrays.length,\n m,\n i = -1,\n j = 0,\n merged,\n array;\n\n while (++i < n) j += arrays[i].length;\n merged = new Array(j);\n\n while (--n >= 0) {\n array = arrays[n];\n m = array.length;\n while (--m >= 0) {\n merged[--j] = array[m];\n }\n }\n\n return merged;\n}\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n min;\n\n if (valueof == null) {\n while (++i < n) { // Find the first comparable value.\n if ((value = values[i]) != null && value >= value) {\n min = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = values[i]) != null && min > value) {\n min = value;\n }\n }\n }\n }\n }\n\n else {\n while (++i < n) { // Find the first comparable value.\n if ((value = valueof(values[i], i, values)) != null && value >= value) {\n min = value;\n while (++i < n) { // Compare the remaining values.\n if ((value = valueof(values[i], i, values)) != null && min > value) {\n min = value;\n }\n }\n }\n }\n }\n\n return min;\n}\n","export default function(x) {\n return x === null ? NaN : +x;\n}\n","export default function(array, f) {\n if (f == null) f = pair;\n var i = 0, n = array.length - 1, p = array[0], pairs = new Array(n < 0 ? 0 : n);\n while (i < n) pairs[i] = f(p, p = array[++i]);\n return pairs;\n}\n\nexport function pair(a, b) {\n return [a, b];\n}\n","export default function(array, indexes) {\n var i = indexes.length, permutes = new Array(i);\n while (i--) permutes[i] = array[indexes[i]];\n return permutes;\n}\n","import number from \"./number\";\n\nexport default function(values, p, valueof) {\n if (valueof == null) valueof = number;\n if (!(n = values.length)) return;\n if ((p = +p) <= 0 || n < 2) return +valueof(values[0], 0, values);\n if (p >= 1) return +valueof(values[n - 1], n - 1, values);\n var n,\n i = (n - 1) * p,\n i0 = Math.floor(i),\n value0 = +valueof(values[i0], i0, values),\n value1 = +valueof(values[i0 + 1], i0 + 1, values);\n return value0 + (value1 - value0) * (i - i0);\n}\n","export default function(start, stop, step) {\n start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step;\n\n var i = -1,\n n = Math.max(0, Math.ceil((stop - start) / step)) | 0,\n range = new Array(n);\n\n while (++i < n) {\n range[i] = start + i * step;\n }\n\n return range;\n}\n","import ascending from \"./ascending\";\n\nexport default function(values, compare) {\n if (!(n = values.length)) return;\n var n,\n i = 0,\n j = 0,\n xi,\n xj = values[j];\n\n if (compare == null) compare = ascending;\n\n while (++i < n) {\n if (compare(xi = values[i], xj) < 0 || compare(xj, xj) !== 0) {\n xj = xi, j = i;\n }\n }\n\n if (compare(xj, xj) === 0) return j;\n}\n","export default function(array, i0, i1) {\n var m = (i1 == null ? array.length : i1) - (i0 = i0 == null ? 0 : +i0),\n t,\n i;\n\n while (m) {\n i = Math.random() * m-- | 0;\n t = array[m + i0];\n array[m + i0] = array[i + i0];\n array[i + i0] = t;\n }\n\n return array;\n}\n","export default function(values, valueof) {\n var n = values.length,\n i = -1,\n value,\n sum = 0;\n\n if (valueof == null) {\n while (++i < n) {\n if (value = +values[i]) sum += value; // Note: zero and null are equivalent.\n }\n }\n\n else {\n while (++i < n) {\n if (value = +valueof(values[i], i, values)) sum += value;\n }\n }\n\n return sum;\n}\n","import {map} from \"../array\";\nimport ascending from \"../ascending\";\nimport number from \"../number\";\nimport quantile from \"../quantile\";\n\nexport default function(values, min, max) {\n values = map.call(values, number).sort(ascending);\n return Math.ceil((max - min) / (2 * (quantile(values, 0.75) - quantile(values, 0.25)) * Math.pow(values.length, -1 / 3)));\n}\n","import deviation from \"../deviation\";\n\nexport default function(values, min, max) {\n return Math.ceil((max - min) / (3.5 * deviation(values) * Math.pow(values.length, -1 / 3)));\n}\n","export default function(values) {\n return Math.ceil(Math.log(values.length) / Math.LN2) + 1;\n}\n","var e10 = Math.sqrt(50),\n e5 = Math.sqrt(10),\n e2 = Math.sqrt(2);\n\nexport default function(start, stop, count) {\n var reverse,\n i = -1,\n n,\n ticks,\n step;\n\n stop = +stop, start = +start, count = +count;\n if (start === stop && count > 0) return [start];\n if (reverse = stop < start) n = start, start = stop, stop = n;\n if ((step = tickIncrement(start, stop, count)) === 0 || !isFinite(step)) return [];\n\n if (step > 0) {\n start = Math.ceil(start / step);\n stop = Math.floor(stop / step);\n ticks = new Array(n = Math.ceil(stop - start + 1));\n while (++i < n) ticks[i] = (start + i) * step;\n } else {\n start = Math.floor(start * step);\n stop = Math.ceil(stop * step);\n ticks = new Array(n = Math.ceil(start - stop + 1));\n while (++i < n) ticks[i] = (start - i) / step;\n }\n\n if (reverse) ticks.reverse();\n\n return ticks;\n}\n\nexport function tickIncrement(start, stop, count) {\n var step = (stop - start) / Math.max(0, count),\n power = Math.floor(Math.log(step) / Math.LN10),\n error = step / Math.pow(10, power);\n return power >= 0\n ? (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1) * Math.pow(10, power)\n : -Math.pow(10, -power) / (error >= e10 ? 10 : error >= e5 ? 5 : error >= e2 ? 2 : 1);\n}\n\nexport function tickStep(start, stop, count) {\n var step0 = Math.abs(stop - start) / Math.max(0, count),\n step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)),\n error = step0 / step1;\n if (error >= e10) step1 *= 10;\n else if (error >= e5) step1 *= 5;\n else if (error >= e2) step1 *= 2;\n return stop < start ? -step1 : step1;\n}\n","import min from \"./min\";\n\nexport default function(matrix) {\n if (!(n = matrix.length)) return [];\n for (var i = -1, m = min(matrix, length), transpose = new Array(m); ++i < m;) {\n for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n;) {\n row[j] = matrix[j][i];\n }\n }\n return transpose;\n}\n\nfunction length(d) {\n return d.length;\n}\n","import number from \"./number\";\n\nexport default function(values, valueof) {\n var n = values.length,\n m = 0,\n i = -1,\n mean = 0,\n value,\n delta,\n sum = 0;\n\n if (valueof == null) {\n while (++i < n) {\n if (!isNaN(value = number(values[i]))) {\n delta = value - mean;\n mean += delta / ++m;\n sum += delta * (value - mean);\n }\n }\n }\n\n else {\n while (++i < n) {\n if (!isNaN(value = number(valueof(values[i], i, values)))) {\n delta = value - mean;\n mean += delta / ++m;\n sum += delta * (value - mean);\n }\n }\n }\n\n if (m > 1) return sum / (m - 1);\n}\n","import transpose from \"./transpose\";\n\nexport default function() {\n return transpose(arguments);\n}\n","export default function(ring) {\n var i = 0, n = ring.length, area = ring[n - 1][1] * ring[0][0] - ring[n - 1][0] * ring[0][1];\n while (++i < n) area += ring[i - 1][1] * ring[i][0] - ring[i - 1][0] * ring[i][1];\n return area;\n}\n","var array = Array.prototype;\n\nexport var slice = array.slice;\n","export default function(a, b) {\n return a - b;\n}\n","// TODO Optimize edge cases.\n// TODO Optimize index calculation.\n// TODO Optimize arguments.\nexport function blurX(source, target, r) {\n var n = source.width,\n m = source.height,\n w = (r << 1) + 1;\n for (var j = 0; j < m; ++j) {\n for (var i = 0, sr = 0; i < n + r; ++i) {\n if (i < n) {\n sr += source.data[i + j * n];\n }\n if (i >= r) {\n if (i >= w) {\n sr -= source.data[i - w + j * n];\n }\n target.data[i - r + j * n] = sr / Math.min(i + 1, n - 1 + w - i, w);\n }\n }\n }\n}\n\n// TODO Optimize edge cases.\n// TODO Optimize index calculation.\n// TODO Optimize arguments.\nexport function blurY(source, target, r) {\n var n = source.width,\n m = source.height,\n w = (r << 1) + 1;\n for (var i = 0; i < n; ++i) {\n for (var j = 0, sr = 0; j < m + r; ++j) {\n if (j < m) {\n sr += source.data[i + j * n];\n }\n if (j >= r) {\n if (j >= w) {\n sr -= source.data[i + (j - w) * n];\n }\n target.data[i + (j - r) * n] = sr / Math.min(j + 1, m - 1 + w - j, w);\n }\n }\n }\n}\n","export default function(x) {\n return function() {\n return x;\n };\n}\n","export default function(ring, hole) {\n var i = -1, n = hole.length, c;\n while (++i < n) if (c = ringContains(ring, hole[i])) return c;\n return 0;\n}\n\nfunction ringContains(ring, point) {\n var x = point[0], y = point[1], contains = -1;\n for (var i = 0, n = ring.length, j = n - 1; i < n; j = i++) {\n var pi = ring[i], xi = pi[0], yi = pi[1], pj = ring[j], xj = pj[0], yj = pj[1];\n if (segmentContains(pi, pj, point)) return 0;\n if (((yi > y) !== (yj > y)) && ((x < (xj - xi) * (y - yi) / (yj - yi) + xi))) contains = -contains;\n }\n return contains;\n}\n\nfunction segmentContains(a, b, c) {\n var i; return collinear(a, b, c) && within(a[i = +(a[0] === b[0])], c[i], b[i]);\n}\n\nfunction collinear(a, b, c) {\n return (b[0] - a[0]) * (c[1] - a[1]) === (c[0] - a[0]) * (b[1] - a[1]);\n}\n\nfunction within(p, q, r) {\n return p <= q && q <= r || r <= q && q <= p;\n}\n","import {extent, thresholdSturges, tickStep, range} from \"d3-array\";\nimport {slice} from \"./array\";\nimport ascending from \"./ascending\";\nimport area from \"./area\";\nimport constant from \"./constant\";\nimport contains from \"./contains\";\nimport noop from \"./noop\";\n\nvar cases = [\n [],\n [[[1.0, 1.5], [0.5, 1.0]]],\n [[[1.5, 1.0], [1.0, 1.5]]],\n [[[1.5, 1.0], [0.5, 1.0]]],\n [[[1.0, 0.5], [1.5, 1.0]]],\n [[[1.0, 1.5], [0.5, 1.0]], [[1.0, 0.5], [1.5, 1.0]]],\n [[[1.0, 0.5], [1.0, 1.5]]],\n [[[1.0, 0.5], [0.5, 1.0]]],\n [[[0.5, 1.0], [1.0, 0.5]]],\n [[[1.0, 1.5], [1.0, 0.5]]],\n [[[0.5, 1.0], [1.0, 0.5]], [[1.5, 1.0], [1.0, 1.5]]],\n [[[1.5, 1.0], [1.0, 0.5]]],\n [[[0.5, 1.0], [1.5, 1.0]]],\n [[[1.0, 1.5], [1.5, 1.0]]],\n [[[0.5, 1.0], [1.0, 1.5]]],\n []\n];\n\nexport default function() {\n var dx = 1,\n dy = 1,\n threshold = thresholdSturges,\n smooth = smoothLinear;\n\n function contours(values) {\n var tz = threshold(values);\n\n // Convert number of thresholds into uniform thresholds.\n if (!Array.isArray(tz)) {\n var domain = extent(values), start = domain[0], stop = domain[1];\n tz = tickStep(start, stop, tz);\n tz = range(Math.floor(start / tz) * tz, Math.floor(stop / tz) * tz, tz);\n } else {\n tz = tz.slice().sort(ascending);\n }\n\n return tz.map(function(value) {\n return contour(values, value);\n });\n }\n\n // Accumulate, smooth contour rings, assign holes to exterior rings.\n // Based on https://github.com/mbostock/shapefile/blob/v0.6.2/shp/polygon.js\n function contour(values, value) {\n var polygons = [],\n holes = [];\n\n isorings(values, value, function(ring) {\n smooth(ring, values, value);\n if (area(ring) > 0) polygons.push([ring]);\n else holes.push(ring);\n });\n\n holes.forEach(function(hole) {\n for (var i = 0, n = polygons.length, polygon; i < n; ++i) {\n if (contains((polygon = polygons[i])[0], hole) !== -1) {\n polygon.push(hole);\n return;\n }\n }\n });\n\n return {\n type: \"MultiPolygon\",\n value: value,\n coordinates: polygons\n };\n }\n\n // Marching squares with isolines stitched into rings.\n // Based on https://github.com/topojson/topojson-client/blob/v3.0.0/src/stitch.js\n function isorings(values, value, callback) {\n var fragmentByStart = new Array,\n fragmentByEnd = new Array,\n x, y, t0, t1, t2, t3;\n\n // Special case for the first row (y = -1, t2 = t3 = 0).\n x = y = -1;\n t1 = values[0] >= value;\n cases[t1 << 1].forEach(stitch);\n while (++x < dx - 1) {\n t0 = t1, t1 = values[x + 1] >= value;\n cases[t0 | t1 << 1].forEach(stitch);\n }\n cases[t1 << 0].forEach(stitch);\n\n // General case for the intermediate rows.\n while (++y < dy - 1) {\n x = -1;\n t1 = values[y * dx + dx] >= value;\n t2 = values[y * dx] >= value;\n cases[t1 << 1 | t2 << 2].forEach(stitch);\n while (++x < dx - 1) {\n t0 = t1, t1 = values[y * dx + dx + x + 1] >= value;\n t3 = t2, t2 = values[y * dx + x + 1] >= value;\n cases[t0 | t1 << 1 | t2 << 2 | t3 << 3].forEach(stitch);\n }\n cases[t1 | t2 << 3].forEach(stitch);\n }\n\n // Special case for the last row (y = dy - 1, t0 = t1 = 0).\n x = -1;\n t2 = values[y * dx] >= value;\n cases[t2 << 2].forEach(stitch);\n while (++x < dx - 1) {\n t3 = t2, t2 = values[y * dx + x + 1] >= value;\n cases[t2 << 2 | t3 << 3].forEach(stitch);\n }\n cases[t2 << 3].forEach(stitch);\n\n function stitch(line) {\n var start = [line[0][0] + x, line[0][1] + y],\n end = [line[1][0] + x, line[1][1] + y],\n startIndex = index(start),\n endIndex = index(end),\n f, g;\n if (f = fragmentByEnd[startIndex]) {\n if (g = fragmentByStart[endIndex]) {\n delete fragmentByEnd[f.end];\n delete fragmentByStart[g.start];\n if (f === g) {\n f.ring.push(end);\n callback(f.ring);\n } else {\n fragmentByStart[f.start] = fragmentByEnd[g.end] = {start: f.start, end: g.end, ring: f.ring.concat(g.ring)};\n }\n } else {\n delete fragmentByEnd[f.end];\n f.ring.push(end);\n fragmentByEnd[f.end = endIndex] = f;\n }\n } else if (f = fragmentByStart[endIndex]) {\n if (g = fragmentByEnd[startIndex]) {\n delete fragmentByStart[f.start];\n delete fragmentByEnd[g.end];\n if (f === g) {\n f.ring.push(end);\n callback(f.ring);\n } else {\n fragmentByStart[g.start] = fragmentByEnd[f.end] = {start: g.start, end: f.end, ring: g.ring.concat(f.ring)};\n }\n } else {\n delete fragmentByStart[f.start];\n f.ring.unshift(start);\n fragmentByStart[f.start = startIndex] = f;\n }\n } else {\n fragmentByStart[startIndex] = fragmentByEnd[endIndex] = {start: startIndex, end: endIndex, ring: [start, end]};\n }\n }\n }\n\n function index(point) {\n return point[0] * 2 + point[1] * (dx + 1) * 4;\n }\n\n function smoothLinear(ring, values, value) {\n ring.forEach(function(point) {\n var x = point[0],\n y = point[1],\n xt = x | 0,\n yt = y | 0,\n v0,\n v1 = values[yt * dx + xt];\n if (x > 0 && x < dx && xt === x) {\n v0 = values[yt * dx + xt - 1];\n point[0] = x + (value - v0) / (v1 - v0) - 0.5;\n }\n if (y > 0 && y < dy && yt === y) {\n v0 = values[(yt - 1) * dx + xt];\n point[1] = y + (value - v0) / (v1 - v0) - 0.5;\n }\n });\n }\n\n contours.contour = contour;\n\n contours.size = function(_) {\n if (!arguments.length) return [dx, dy];\n var _0 = Math.ceil(_[0]), _1 = Math.ceil(_[1]);\n if (!(_0 > 0) || !(_1 > 0)) throw new Error(\"invalid size\");\n return dx = _0, dy = _1, contours;\n };\n\n contours.thresholds = function(_) {\n return arguments.length ? (threshold = typeof _ === \"function\" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), contours) : threshold;\n };\n\n contours.smooth = function(_) {\n return arguments.length ? (smooth = _ ? smoothLinear : noop, contours) : smooth === smoothLinear;\n };\n\n return contours;\n}\n","import {max, range, tickStep} from \"d3-array\";\nimport {slice} from \"./array\";\nimport {blurX, blurY} from \"./blur\";\nimport constant from \"./constant\";\nimport contours from \"./contours\";\n\nfunction defaultX(d) {\n return d[0];\n}\n\nfunction defaultY(d) {\n return d[1];\n}\n\nfunction defaultWeight() {\n return 1;\n}\n\nexport default function() {\n var x = defaultX,\n y = defaultY,\n weight = defaultWeight,\n dx = 960,\n dy = 500,\n r = 20, // blur radius\n k = 2, // log2(grid cell size)\n o = r * 3, // grid offset, to pad for blur\n n = (dx + o * 2) >> k, // grid width\n m = (dy + o * 2) >> k, // grid height\n threshold = constant(20);\n\n function density(data) {\n var values0 = new Float32Array(n * m),\n values1 = new Float32Array(n * m);\n\n data.forEach(function(d, i, data) {\n var xi = (+x(d, i, data) + o) >> k,\n yi = (+y(d, i, data) + o) >> k,\n wi = +weight(d, i, data);\n if (xi >= 0 && xi < n && yi >= 0 && yi < m) {\n values0[xi + yi * n] += wi;\n }\n });\n\n // TODO Optimize.\n blurX({width: n, height: m, data: values0}, {width: n, height: m, data: values1}, r >> k);\n blurY({width: n, height: m, data: values1}, {width: n, height: m, data: values0}, r >> k);\n blurX({width: n, height: m, data: values0}, {width: n, height: m, data: values1}, r >> k);\n blurY({width: n, height: m, data: values1}, {width: n, height: m, data: values0}, r >> k);\n blurX({width: n, height: m, data: values0}, {width: n, height: m, data: values1}, r >> k);\n blurY({width: n, height: m, data: values1}, {width: n, height: m, data: values0}, r >> k);\n\n var tz = threshold(values0);\n\n // Convert number of thresholds into uniform thresholds.\n if (!Array.isArray(tz)) {\n var stop = max(values0);\n tz = tickStep(0, stop, tz);\n tz = range(0, Math.floor(stop / tz) * tz, tz);\n tz.shift();\n }\n\n return contours()\n .thresholds(tz)\n .size([n, m])\n (values0)\n .map(transform);\n }\n\n function transform(geometry) {\n geometry.value *= Math.pow(2, -2 * k); // Density in points per square pixel.\n geometry.coordinates.forEach(transformPolygon);\n return geometry;\n }\n\n function transformPolygon(coordinates) {\n coordinates.forEach(transformRing);\n }\n\n function transformRing(coordinates) {\n coordinates.forEach(transformPoint);\n }\n\n // TODO Optimize.\n function transformPoint(coordinates) {\n coordinates[0] = coordinates[0] * Math.pow(2, k) - o;\n coordinates[1] = coordinates[1] * Math.pow(2, k) - o;\n }\n\n function resize() {\n o = r * 3;\n n = (dx + o * 2) >> k;\n m = (dy + o * 2) >> k;\n return density;\n }\n\n density.x = function(_) {\n return arguments.length ? (x = typeof _ === \"function\" ? _ : constant(+_), density) : x;\n };\n\n density.y = function(_) {\n return arguments.length ? (y = typeof _ === \"function\" ? _ : constant(+_), density) : y;\n };\n\n density.weight = function(_) {\n return arguments.length ? (weight = typeof _ === \"function\" ? _ : constant(+_), density) : weight;\n };\n\n density.size = function(_) {\n if (!arguments.length) return [dx, dy];\n var _0 = Math.ceil(_[0]), _1 = Math.ceil(_[1]);\n if (!(_0 >= 0) && !(_0 >= 0)) throw new Error(\"invalid size\");\n return dx = _0, dy = _1, resize();\n };\n\n density.cellSize = function(_) {\n if (!arguments.length) return 1 << k;\n if (!((_ = +_) >= 1)) throw new Error(\"invalid cell size\");\n return k = Math.floor(Math.log(_) / Math.LN2), resize();\n };\n\n density.thresholds = function(_) {\n return arguments.length ? (threshold = typeof _ === \"function\" ? _ : Array.isArray(_) ? constant(slice.call(_)) : constant(_), density) : threshold;\n };\n\n density.bandwidth = function(_) {\n if (!arguments.length) return Math.sqrt(r * (r + 1));\n if (!((_ = +_) >= 0)) throw new Error(\"invalid bandwidth\");\n return r = Math.round((Math.sqrt(4 * _ * _ + 1) - 1) / 2), resize();\n };\n\n return density;\n}\n","export {default as contours} from \"./contours\";\nexport {default as contourDensity} from \"./density\";\n","export default function() {}\n","\nconst EPSILON = Math.pow(2, -52);\nconst EDGE_STACK = new Uint32Array(512);\n\nexport default class Delaunator {\n\n static from(points, getX = defaultGetX, getY = defaultGetY) {\n const n = points.length;\n const coords = new Float64Array(n * 2);\n\n for (let i = 0; i < n; i++) {\n const p = points[i];\n coords[2 * i] = getX(p);\n coords[2 * i + 1] = getY(p);\n }\n\n return new Delaunator(coords);\n }\n\n constructor(coords) {\n const n = coords.length >> 1;\n if (n > 0 && typeof coords[0] !== 'number') throw new Error('Expected coords to contain numbers.');\n\n this.coords = coords;\n\n // arrays that will store the triangulation graph\n const maxTriangles = Math.max(2 * n - 5, 0);\n this._triangles = new Uint32Array(maxTriangles * 3);\n this._halfedges = new Int32Array(maxTriangles * 3);\n\n // temporary arrays for tracking the edges of the advancing convex hull\n this._hashSize = Math.ceil(Math.sqrt(n));\n this._hullPrev = new Uint32Array(n); // edge to prev edge\n this._hullNext = new Uint32Array(n); // edge to next edge\n this._hullTri = new Uint32Array(n); // edge to adjacent triangle\n this._hullHash = new Int32Array(this._hashSize).fill(-1); // angular edge hash\n\n // temporary arrays for sorting points\n this._ids = new Uint32Array(n);\n this._dists = new Float64Array(n);\n\n this.update();\n }\n\n update() {\n const {coords, _hullPrev: hullPrev, _hullNext: hullNext, _hullTri: hullTri, _hullHash: hullHash} = this;\n const n = coords.length >> 1;\n\n // populate an array of point indices; calculate input data bbox\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (let i = 0; i < n; i++) {\n const x = coords[2 * i];\n const y = coords[2 * i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n this._ids[i] = i;\n }\n const cx = (minX + maxX) / 2;\n const cy = (minY + maxY) / 2;\n\n let minDist = Infinity;\n let i0, i1, i2;\n\n // pick a seed point close to the center\n for (let i = 0; i < n; i++) {\n const d = dist(cx, cy, coords[2 * i], coords[2 * i + 1]);\n if (d < minDist) {\n i0 = i;\n minDist = d;\n }\n }\n const i0x = coords[2 * i0];\n const i0y = coords[2 * i0 + 1];\n\n minDist = Infinity;\n\n // find the point closest to the seed\n for (let i = 0; i < n; i++) {\n if (i === i0) continue;\n const d = dist(i0x, i0y, coords[2 * i], coords[2 * i + 1]);\n if (d < minDist && d > 0) {\n i1 = i;\n minDist = d;\n }\n }\n let i1x = coords[2 * i1];\n let i1y = coords[2 * i1 + 1];\n\n let minRadius = Infinity;\n\n // find the third point which forms the smallest circumcircle with the first two\n for (let i = 0; i < n; i++) {\n if (i === i0 || i === i1) continue;\n const r = circumradius(i0x, i0y, i1x, i1y, coords[2 * i], coords[2 * i + 1]);\n if (r < minRadius) {\n i2 = i;\n minRadius = r;\n }\n }\n let i2x = coords[2 * i2];\n let i2y = coords[2 * i2 + 1];\n\n if (minRadius === Infinity) {\n // order collinear points by dx (or dy if all x are identical)\n // and return the list as a hull\n for (let i = 0; i < n; i++) {\n this._dists[i] = (coords[2 * i] - coords[0]) || (coords[2 * i + 1] - coords[1]);\n }\n quicksort(this._ids, this._dists, 0, n - 1);\n const hull = new Uint32Array(n);\n let j = 0;\n for (let i = 0, d0 = -Infinity; i < n; i++) {\n const id = this._ids[i];\n if (this._dists[id] > d0) {\n hull[j++] = id;\n d0 = this._dists[id];\n }\n }\n this.hull = hull.subarray(0, j);\n this.triangles = new Uint32Array(0);\n this.halfedges = new Uint32Array(0);\n return;\n }\n\n // swap the order of the seed points for counter-clockwise orientation\n if (orient(i0x, i0y, i1x, i1y, i2x, i2y)) {\n const i = i1;\n const x = i1x;\n const y = i1y;\n i1 = i2;\n i1x = i2x;\n i1y = i2y;\n i2 = i;\n i2x = x;\n i2y = y;\n }\n\n const center = circumcenter(i0x, i0y, i1x, i1y, i2x, i2y);\n this._cx = center.x;\n this._cy = center.y;\n\n for (let i = 0; i < n; i++) {\n this._dists[i] = dist(coords[2 * i], coords[2 * i + 1], center.x, center.y);\n }\n\n // sort the points by distance from the seed triangle circumcenter\n quicksort(this._ids, this._dists, 0, n - 1);\n\n // set up the seed triangle as the starting hull\n this._hullStart = i0;\n let hullSize = 3;\n\n hullNext[i0] = hullPrev[i2] = i1;\n hullNext[i1] = hullPrev[i0] = i2;\n hullNext[i2] = hullPrev[i1] = i0;\n\n hullTri[i0] = 0;\n hullTri[i1] = 1;\n hullTri[i2] = 2;\n\n hullHash.fill(-1);\n hullHash[this._hashKey(i0x, i0y)] = i0;\n hullHash[this._hashKey(i1x, i1y)] = i1;\n hullHash[this._hashKey(i2x, i2y)] = i2;\n\n this.trianglesLen = 0;\n this._addTriangle(i0, i1, i2, -1, -1, -1);\n\n for (let k = 0, xp, yp; k < this._ids.length; k++) {\n const i = this._ids[k];\n const x = coords[2 * i];\n const y = coords[2 * i + 1];\n\n // skip near-duplicate points\n if (k > 0 && Math.abs(x - xp) <= EPSILON && Math.abs(y - yp) <= EPSILON) continue;\n xp = x;\n yp = y;\n\n // skip seed triangle points\n if (i === i0 || i === i1 || i === i2) continue;\n\n // find a visible edge on the convex hull using edge hash\n let start = 0;\n for (let j = 0, key = this._hashKey(x, y); j < this._hashSize; j++) {\n start = hullHash[(key + j) % this._hashSize];\n if (start !== -1 && start !== hullNext[start]) break;\n }\n\n start = hullPrev[start];\n let e = start, q;\n while (q = hullNext[e], !orient(x, y, coords[2 * e], coords[2 * e + 1], coords[2 * q], coords[2 * q + 1])) {\n e = q;\n if (e === start) {\n e = -1;\n break;\n }\n }\n if (e === -1) continue; // likely a near-duplicate point; skip it\n\n // add the first triangle from the point\n let t = this._addTriangle(e, i, hullNext[e], -1, -1, hullTri[e]);\n\n // recursively flip triangles from the point until they satisfy the Delaunay condition\n hullTri[i] = this._legalize(t + 2);\n hullTri[e] = t; // keep track of boundary triangles on the hull\n hullSize++;\n\n // walk forward through the hull, adding more triangles and flipping recursively\n let n = hullNext[e];\n while (q = hullNext[n], orient(x, y, coords[2 * n], coords[2 * n + 1], coords[2 * q], coords[2 * q + 1])) {\n t = this._addTriangle(n, i, q, hullTri[i], -1, hullTri[n]);\n hullTri[i] = this._legalize(t + 2);\n hullNext[n] = n; // mark as removed\n hullSize--;\n n = q;\n }\n\n // walk backward from the other side, adding more triangles and flipping\n if (e === start) {\n while (q = hullPrev[e], orient(x, y, coords[2 * q], coords[2 * q + 1], coords[2 * e], coords[2 * e + 1])) {\n t = this._addTriangle(q, i, e, -1, hullTri[e], hullTri[q]);\n this._legalize(t + 2);\n hullTri[q] = t;\n hullNext[e] = e; // mark as removed\n hullSize--;\n e = q;\n }\n }\n\n // update the hull indices\n this._hullStart = hullPrev[i] = e;\n hullNext[e] = hullPrev[n] = i;\n hullNext[i] = n;\n\n // save the two new edges in the hash table\n hullHash[this._hashKey(x, y)] = i;\n hullHash[this._hashKey(coords[2 * e], coords[2 * e + 1])] = e;\n }\n\n this.hull = new Uint32Array(hullSize);\n for (let i = 0, e = this._hullStart; i < hullSize; i++) {\n this.hull[i] = e;\n e = hullNext[e];\n }\n\n // trim typed triangle mesh arrays\n this.triangles = this._triangles.subarray(0, this.trianglesLen);\n this.halfedges = this._halfedges.subarray(0, this.trianglesLen);\n }\n\n _hashKey(x, y) {\n return Math.floor(pseudoAngle(x - this._cx, y - this._cy) * this._hashSize) % this._hashSize;\n }\n\n _legalize(a) {\n const {_triangles: triangles, _halfedges: halfedges, coords} = this;\n\n let i = 0;\n let ar = 0;\n\n // recursion eliminated with a fixed-size stack\n while (true) {\n const b = halfedges[a];\n\n /* if the pair of triangles doesn't satisfy the Delaunay condition\n * (p1 is inside the circumcircle of [p0, pl, pr]), flip them,\n * then do the same check/flip recursively for the new pair of triangles\n *\n * pl pl\n * /||\\ / \\\n * al/ || \\bl al/ \\a\n * / || \\ / \\\n * / a||b \\ flip /___ar___\\\n * p0\\ || /p1 => p0\\---bl---/p1\n * \\ || / \\ /\n * ar\\ || /br b\\ /br\n * \\||/ \\ /\n * pr pr\n */\n const a0 = a - a % 3;\n ar = a0 + (a + 2) % 3;\n\n if (b === -1) { // convex hull edge\n if (i === 0) break;\n a = EDGE_STACK[--i];\n continue;\n }\n\n const b0 = b - b % 3;\n const al = a0 + (a + 1) % 3;\n const bl = b0 + (b + 2) % 3;\n\n const p0 = triangles[ar];\n const pr = triangles[a];\n const pl = triangles[al];\n const p1 = triangles[bl];\n\n const illegal = inCircle(\n coords[2 * p0], coords[2 * p0 + 1],\n coords[2 * pr], coords[2 * pr + 1],\n coords[2 * pl], coords[2 * pl + 1],\n coords[2 * p1], coords[2 * p1 + 1]);\n\n if (illegal) {\n triangles[a] = p1;\n triangles[b] = p0;\n\n const hbl = halfedges[bl];\n\n // edge swapped on the other side of the hull (rare); fix the halfedge reference\n if (hbl === -1) {\n let e = this._hullStart;\n do {\n if (this._hullTri[e] === bl) {\n this._hullTri[e] = a;\n break;\n }\n e = this._hullPrev[e];\n } while (e !== this._hullStart);\n }\n this._link(a, hbl);\n this._link(b, halfedges[ar]);\n this._link(ar, bl);\n\n const br = b0 + (b + 1) % 3;\n\n // don't worry about hitting the cap: it can only happen on extremely degenerate input\n if (i < EDGE_STACK.length) {\n EDGE_STACK[i++] = br;\n }\n } else {\n if (i === 0) break;\n a = EDGE_STACK[--i];\n }\n }\n\n return ar;\n }\n\n _link(a, b) {\n this._halfedges[a] = b;\n if (b !== -1) this._halfedges[b] = a;\n }\n\n // add a new triangle given vertex indices and adjacent half-edge ids\n _addTriangle(i0, i1, i2, a, b, c) {\n const t = this.trianglesLen;\n\n this._triangles[t] = i0;\n this._triangles[t + 1] = i1;\n this._triangles[t + 2] = i2;\n\n this._link(t, a);\n this._link(t + 1, b);\n this._link(t + 2, c);\n\n this.trianglesLen += 3;\n\n return t;\n }\n}\n\n// monotonically increases with real angle, but doesn't need expensive trigonometry\nfunction pseudoAngle(dx, dy) {\n const p = dx / (Math.abs(dx) + Math.abs(dy));\n return (dy > 0 ? 3 - p : 1 + p) / 4; // [0..1]\n}\n\nfunction dist(ax, ay, bx, by) {\n const dx = ax - bx;\n const dy = ay - by;\n return dx * dx + dy * dy;\n}\n\n// return 2d orientation sign if we're confident in it through J. Shewchuk's error bound check\nfunction orientIfSure(px, py, rx, ry, qx, qy) {\n const l = (ry - py) * (qx - px);\n const r = (rx - px) * (qy - py);\n return Math.abs(l - r) >= 3.3306690738754716e-16 * Math.abs(l + r) ? l - r : 0;\n}\n\n// a more robust orientation test that's stable in a given triangle (to fix robustness issues)\nfunction orient(rx, ry, qx, qy, px, py) {\n const sign = orientIfSure(px, py, rx, ry, qx, qy) ||\n orientIfSure(rx, ry, qx, qy, px, py) ||\n orientIfSure(qx, qy, px, py, rx, ry);\n return sign < 0;\n}\n\nfunction inCircle(ax, ay, bx, by, cx, cy, px, py) {\n const dx = ax - px;\n const dy = ay - py;\n const ex = bx - px;\n const ey = by - py;\n const fx = cx - px;\n const fy = cy - py;\n\n const ap = dx * dx + dy * dy;\n const bp = ex * ex + ey * ey;\n const cp = fx * fx + fy * fy;\n\n return dx * (ey * cp - bp * fy) -\n dy * (ex * cp - bp * fx) +\n ap * (ex * fy - ey * fx) < 0;\n}\n\nfunction circumradius(ax, ay, bx, by, cx, cy) {\n const dx = bx - ax;\n const dy = by - ay;\n const ex = cx - ax;\n const ey = cy - ay;\n\n const bl = dx * dx + dy * dy;\n const cl = ex * ex + ey * ey;\n const d = 0.5 / (dx * ey - dy * ex);\n\n const x = (ey * bl - dy * cl) * d;\n const y = (dx * cl - ex * bl) * d;\n\n return x * x + y * y;\n}\n\nfunction circumcenter(ax, ay, bx, by, cx, cy) {\n const dx = bx - ax;\n const dy = by - ay;\n const ex = cx - ax;\n const ey = cy - ay;\n\n const bl = dx * dx + dy * dy;\n const cl = ex * ex + ey * ey;\n const d = 0.5 / (dx * ey - dy * ex);\n\n const x = ax + (ey * bl - dy * cl) * d;\n const y = ay + (dx * cl - ex * bl) * d;\n\n return {x, y};\n}\n\nfunction quicksort(ids, dists, left, right) {\n if (right - left <= 20) {\n for (let i = left + 1; i <= right; i++) {\n const temp = ids[i];\n const tempDist = dists[temp];\n let j = i - 1;\n while (j >= left && dists[ids[j]] > tempDist) ids[j + 1] = ids[j--];\n ids[j + 1] = temp;\n }\n } else {\n const median = (left + right) >> 1;\n let i = left + 1;\n let j = right;\n swap(ids, median, i);\n if (dists[ids[left]] > dists[ids[right]]) swap(ids, left, right);\n if (dists[ids[i]] > dists[ids[right]]) swap(ids, i, right);\n if (dists[ids[left]] > dists[ids[i]]) swap(ids, left, i);\n\n const temp = ids[i];\n const tempDist = dists[temp];\n while (true) {\n do i++; while (dists[ids[i]] < tempDist);\n do j--; while (dists[ids[j]] > tempDist);\n if (j < i) break;\n swap(ids, i, j);\n }\n ids[left + 1] = ids[j];\n ids[j] = temp;\n\n if (right - i + 1 >= j - left) {\n quicksort(ids, dists, i, right);\n quicksort(ids, dists, left, j - 1);\n } else {\n quicksort(ids, dists, left, j - 1);\n quicksort(ids, dists, i, right);\n }\n }\n}\n\nfunction swap(arr, i, j) {\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\nfunction defaultGetX(p) {\n return p[0];\n}\nfunction defaultGetY(p) {\n return p[1];\n}\n","\"use strict\";\nvar windowOrGlobal = Function('return this')();\n(function (root) {\n /* istanbul ignore next */\n if (typeof exports !== 'undefined') {\n /* istanbul ignore next */\n if (typeof module !== 'undefined' && module && module.exports) {\n exports = module.exports = clone;\n }\n exports.clone = clone;\n }\n else {\n /* istanbul ignore next */\n root.clone = clone;\n }\n function clone(value) {\n var type = typeof value;\n switch (type) {\n case 'object':\n // null and undefined\n if (value == null) {\n return value;\n }\n var result = void 0;\n if (value instanceof Date) {\n result = new Date();\n result.setTime(value.getTime());\n return result;\n }\n else if (value instanceof RegExp) {\n result = newRegExp(value);\n return result;\n }\n result = JSON.parse(JSON.stringify(value));\n fixTypes(value, result);\n return result;\n default:\n return value;\n }\n }\n function fixPropertyValue(original, copy, key) {\n var originalValue = original[key];\n var originalType = typeof originalValue;\n switch (originalType) {\n case 'object':\n if (originalValue instanceof Date) {\n var newValue = new Date();\n newValue.setTime(originalValue.getTime());\n copy[key] = newValue;\n }\n else if (originalValue instanceof RegExp) {\n copy[key] = newRegExp(originalValue);\n }\n else if (originalValue == null) {\n copy[key] = originalValue;\n }\n else {\n fixTypes(originalValue, copy[key]);\n }\n break;\n case 'number':\n if (isNaN(originalValue)) {\n copy[key] = NaN;\n }\n else if (originalValue == Infinity) {\n copy[key] = Infinity;\n }\n break;\n default:\n break;\n }\n }\n function fixTypes(original, copy) {\n if (original instanceof Array) {\n for (var index = 0; index < original.length; index++) {\n fixPropertyValue(original, copy, index);\n }\n }\n else {\n var keys = Object.getOwnPropertyNames(original);\n keys.forEach(function (key) {\n fixPropertyValue(original, copy, key);\n });\n }\n }\n function newRegExp(value) {\n var regexpText = String(value);\n var slashIndex = regexpText.lastIndexOf('/');\n return new RegExp(regexpText.slice(1, slashIndex), regexpText.slice(slashIndex + 1));\n }\n})(windowOrGlobal);\n","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n","'use strict';\n\nmodule.exports = function (data, opts) {\n if (!opts) opts = {};\n if (typeof opts === 'function') opts = { cmp: opts };\n var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;\n\n var cmp = opts.cmp && (function (f) {\n return function (node) {\n return function (a, b) {\n var aobj = { key: a, value: node[a] };\n var bobj = { key: b, value: node[b] };\n return f(aobj, bobj);\n };\n };\n })(opts.cmp);\n\n var seen = [];\n return (function stringify (node) {\n if (node && node.toJSON && typeof node.toJSON === 'function') {\n node = node.toJSON();\n }\n\n if (node === undefined) return;\n if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';\n if (typeof node !== 'object') return JSON.stringify(node);\n\n var i, out;\n if (Array.isArray(node)) {\n out = '[';\n for (i = 0; i < node.length; i++) {\n if (i) out += ',';\n out += stringify(node[i]) || 'null';\n }\n return out + ']';\n }\n\n if (node === null) return 'null';\n\n if (seen.indexOf(node) !== -1) {\n if (cycles) return JSON.stringify('__cycle__');\n throw new TypeError('Converting circular structure to JSON');\n }\n\n var seenIndex = seen.push(node) - 1;\n var keys = Object.keys(node).sort(cmp && cmp(node));\n out = '';\n for (i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = stringify(node[key]);\n\n if (!value) continue;\n if (out) out += ',';\n out += JSON.stringify(key) + ':' + value;\n }\n seen.splice(seenIndex, 1);\n return '{' + out + '}';\n })(data);\n};\n","!function(e,t){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=t():\"function\"==typeof define&&define.amd?define(t):(e=e||self).graphology=t()}(this,(function(){\"use strict\";function e(t){return(e=\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&\"function\"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?\"symbol\":typeof e})(t)}function t(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}function n(e){return(n=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function r(e,t){return(r=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function i(){if(\"undefined\"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if(\"function\"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],(function(){}))),!0}catch(e){return!1}}function o(e,t,n){return(o=i()?Reflect.construct:function(e,t,n){var i=[null];i.push.apply(i,t);var o=new(Function.bind.apply(e,i));return n&&r(o,n.prototype),o}).apply(null,arguments)}function a(e){var t=\"function\"==typeof Map?new Map:void 0;return(a=function(e){if(null===e||(i=e,-1===Function.toString.call(i).indexOf(\"[native code]\")))return e;var i;if(\"function\"!=typeof e)throw new TypeError(\"Super expression must either be null or a function\");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,a)}function a(){return o(e,arguments,n(this).constructor)}return a.prototype=Object.create(e.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),r(a,e)})(e)}function c(e){if(void 0===e)throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");return e}function d(){for(var e=arguments[0]||{},t=1,n=arguments.length;t0&&a.length>i){a.warned=!0;var d=new Error(\"Possible EventEmitter memory leak detected. \"+a.length+\" \"+t+\" listeners added. Use emitter.setMaxListeners() to increase limit\");d.name=\"MaxListenersExceededWarning\",d.emitter=e,d.type=t,d.count=a.length,c=d,\"function\"==typeof console.warn?console.warn(c):console.log(c)}}else a=o[t]=n,++e._eventsCount;return e}function k(e,t,n){var r=!1;function i(){e.removeListener(t,i),r||(r=!0,n.apply(e,arguments))}return i.listener=n,i}function x(e){var t=this._events;if(t){var n=t[e];if(\"function\"==typeof n)return 1;if(n)return n.length}return 0}function S(e,t){for(var n=new Array(t);t--;)n[t]=e[t];return n}function A(e){Object.defineProperty(this,\"_next\",{writable:!1,enumerable:!1,value:e}),this.done=!1}l.prototype=Object.create(null),y.EventEmitter=y,y.usingDomains=!1,y.prototype.domain=void 0,y.prototype._events=void 0,y.prototype._maxListeners=void 0,y.defaultMaxListeners=10,y.init=function(){this.domain=null,y.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new l,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},y.prototype.setMaxListeners=function(e){if(\"number\"!=typeof e||e<0||isNaN(e))throw new TypeError('\"n\" argument must be a positive number');return this._maxListeners=e,this},y.prototype.getMaxListeners=function(){return v(this)},y.prototype.emit=function(e){var t,n,r,i,o,a,c,d=\"error\"===e;if(a=this._events)d=d&&null==a.error;else if(!d)return!1;if(c=this.domain,d){if(t=arguments[1],!c){if(t instanceof Error)throw t;var u=new Error('Uncaught, unspecified \"error\" event. ('+t+\")\");throw u.context=t,u}return t||(t=new Error('Uncaught, unspecified \"error\" event')),t.domainEmitter=this,t.domain=c,t.domainThrown=!1,c.emit(\"error\",t),!1}if(!(n=a[e]))return!1;var s=\"function\"==typeof n;switch(r=arguments.length){case 1:w(n,s,this);break;case 2:b(n,s,this,arguments[1]);break;case 3:m(n,s,this,arguments[1],arguments[2]);break;case 4:_(n,s,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(r-1),o=1;o0;)if(n[o]===t||n[o].listener&&n[o].listener===t){a=n[o].listener,i=o;break}if(i<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new l,this;delete r[e]}else!function(e,t){for(var n=t,r=n+1,i=e.length;r0?Reflect.ownKeys(this._events):[]},A.prototype.next=function(){if(this.done)return{done:!0};var e=this._next();return e.done&&(this.done=!0),e},\"undefined\"!=typeof Symbol&&(A.prototype[Symbol.iterator]=function(){return this}),A.of=function(){var e=arguments,t=e.length,n=0;return new A((function(){return n>=t?{done:!0}:{done:!1,value:e[n++]}}))},A.empty=function(){var e=new A(null);return e.done=!0,e},A.is=function(e){return e instanceof A||\"object\"==typeof e&&null!==e&&\"function\"==typeof e.next};var N=A,D=function(e,t){for(var n,r=arguments.length>1?t:1/0,i=r!==1/0?new Array(r):[],o=0;;){if(o===r)return i;if((n=e.next()).done)return o!==t?i.slice(0,o):i;i[o++]=n.value}},L=function(e){function n(t,n){var r;return(r=e.call(this)||this).name=\"GraphError\",r.message=t||\"\",r.data=n||{},r}return t(n,e),n}(a(Error)),j=function(e){function n(t,r){var i;return(i=e.call(this,t,r)||this).name=\"InvalidArgumentsGraphError\",\"function\"==typeof Error.captureStackTrace&&Error.captureStackTrace(c(i),n.prototype.constructor),i}return t(n,e),n}(L),U=function(e){function n(t,r){var i;return(i=e.call(this,t,r)||this).name=\"NotFoundGraphError\",\"function\"==typeof Error.captureStackTrace&&Error.captureStackTrace(c(i),n.prototype.constructor),i}return t(n,e),n}(L),z=function(e){function n(t,r){var i;return(i=e.call(this,t,r)||this).name=\"UsageGraphError\",\"function\"==typeof Error.captureStackTrace&&Error.captureStackTrace(c(i),n.prototype.constructor),i}return t(n,e),n}(L);function O(e,t){this.key=e,this.attributes=t,this.inDegree=0,this.outDegree=0,this.undirectedDegree=0,this.directedSelfLoops=0,this.undirectedSelfLoops=0,this.in={},this.out={},this.undirected={}}function K(e,t){this.key=e,this.attributes=t||{},this.inDegree=0,this.outDegree=0,this.directedSelfLoops=0,this.in={},this.out={}}function M(e,t){this.key=e,this.attributes=t||{},this.undirectedDegree=0,this.undirectedSelfLoops=0,this.undirected={}}function C(e,t,n,r,i){this.key=e,this.attributes=i,this.source=n,this.target=r,this.generatedKey=t}function T(e,t,n,r,i){this.key=e,this.attributes=i,this.source=n,this.target=r,this.generatedKey=t}function P(e,t,n,r,i,o,a){var c=e.multi,d=t?\"undirected\":\"out\",u=t?\"undirected\":\"in\",s=o[d][i];void 0===s&&(s=c?new Set:n,o[d][i]=s),c&&s.add(n),r!==i&&void 0===a[u][r]&&(a[u][r]=s)}function W(e,t,n){var r=e.multi,i=n.source,o=n.target,a=i.key,c=o.key,d=i[t?\"undirected\":\"out\"],u=t?\"undirected\":\"in\";if(c in d)if(r){var s=d[c];1===s.size?(delete d[c],delete o[u][a]):s.delete(n)}else delete d[c];r||delete o[u][a]}K.prototype.upgradeToMixed=function(){this.undirectedDegree=0,this.undirectedSelfLoops=0,this.undirected={}},M.prototype.upgradeToMixed=function(){this.inDegree=0,this.outDegree=0,this.directedSelfLoops=0,this.in={},this.out={}};var R=[{name:function(e){return\"get\".concat(e,\"Attribute\")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i){var o;if(\"mixed\"!==this.type&&\"mixed\"!==n&&n!==this.type)throw new z(\"Graph.\".concat(t,\": cannot find this type of edges in your \").concat(this.type,\" graph.\"));if(arguments.length>2){if(this.multi)throw new z(\"Graph.\".concat(t,\": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.\"));var a=\"\"+e,c=\"\"+i;if(i=arguments[2],!(o=u(this,a,c,n)))throw new U(\"Graph.\".concat(t,': could not find an edge for the given path (\"').concat(a,'\" - \"').concat(c,'\").'))}else if(e=\"\"+e,!(o=this._edges.get(e)))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" edge in the graph.'));if(\"mixed\"!==n&&!(o instanceof r))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" ').concat(n,\" edge in the graph.\"));return o.attributes[i]}}},{name:function(e){return\"get\".concat(e,\"Attributes\")},attacher:function(e,t,n,r){e.prototype[t]=function(e){var i;if(\"mixed\"!==this.type&&\"mixed\"!==n&&n!==this.type)throw new z(\"Graph.\".concat(t,\": cannot find this type of edges in your \").concat(this.type,\" graph.\"));if(arguments.length>1){if(this.multi)throw new z(\"Graph.\".concat(t,\": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.\"));var o=\"\"+e,a=\"\"+arguments[1];if(!(i=u(this,o,a,n)))throw new U(\"Graph.\".concat(t,': could not find an edge for the given path (\"').concat(o,'\" - \"').concat(a,'\").'))}else if(e=\"\"+e,!(i=this._edges.get(e)))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" edge in the graph.'));if(\"mixed\"!==n&&!(i instanceof r))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" ').concat(n,\" edge in the graph.\"));return i.attributes}}},{name:function(e){return\"has\".concat(e,\"Attribute\")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i){var o;if(\"mixed\"!==this.type&&\"mixed\"!==n&&n!==this.type)throw new z(\"Graph.\".concat(t,\": cannot find this type of edges in your \").concat(this.type,\" graph.\"));if(arguments.length>2){if(this.multi)throw new z(\"Graph.\".concat(t,\": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.\"));var a=\"\"+e,c=\"\"+i;if(i=arguments[2],!(o=u(this,a,c,n)))throw new U(\"Graph.\".concat(t,': could not find an edge for the given path (\"').concat(a,'\" - \"').concat(c,'\").'))}else if(e=\"\"+e,!(o=this._edges.get(e)))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" edge in the graph.'));if(\"mixed\"!==n&&!(o instanceof r))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" ').concat(n,\" edge in the graph.\"));return o.attributes.hasOwnProperty(i)}}},{name:function(e){return\"set\".concat(e,\"Attribute\")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i,o){var a;if(\"mixed\"!==this.type&&\"mixed\"!==n&&n!==this.type)throw new z(\"Graph.\".concat(t,\": cannot find this type of edges in your \").concat(this.type,\" graph.\"));if(arguments.length>3){if(this.multi)throw new z(\"Graph.\".concat(t,\": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.\"));var c=\"\"+e,d=\"\"+i;if(i=arguments[2],o=arguments[3],!(a=u(this,c,d,n)))throw new U(\"Graph.\".concat(t,': could not find an edge for the given path (\"').concat(c,'\" - \"').concat(d,'\").'))}else if(e=\"\"+e,!(a=this._edges.get(e)))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" edge in the graph.'));if(\"mixed\"!==n&&!(a instanceof r))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" ').concat(n,\" edge in the graph.\"));return a.attributes[i]=o,this.emit(\"edgeAttributesUpdated\",{key:a.key,type:\"set\",meta:{name:i,value:o}}),this}}},{name:function(e){return\"update\".concat(e,\"Attribute\")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i,o){var a;if(\"mixed\"!==this.type&&\"mixed\"!==n&&n!==this.type)throw new z(\"Graph.\".concat(t,\": cannot find this type of edges in your \").concat(this.type,\" graph.\"));if(arguments.length>3){if(this.multi)throw new z(\"Graph.\".concat(t,\": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.\"));var c=\"\"+e,d=\"\"+i;if(i=arguments[2],o=arguments[3],!(a=u(this,c,d,n)))throw new U(\"Graph.\".concat(t,': could not find an edge for the given path (\"').concat(c,'\" - \"').concat(d,'\").'))}else if(e=\"\"+e,!(a=this._edges.get(e)))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" edge in the graph.'));if(\"function\"!=typeof o)throw new j(\"Graph.\".concat(t,\": updater should be a function.\"));if(\"mixed\"!==n&&!(a instanceof r))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" ').concat(n,\" edge in the graph.\"));return a.attributes[i]=o(a.attributes[i]),this.emit(\"edgeAttributesUpdated\",{key:a.key,type:\"set\",meta:{name:i,value:a.attributes[i]}}),this}}},{name:function(e){return\"remove\".concat(e,\"Attribute\")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i){var o;if(\"mixed\"!==this.type&&\"mixed\"!==n&&n!==this.type)throw new z(\"Graph.\".concat(t,\": cannot find this type of edges in your \").concat(this.type,\" graph.\"));if(arguments.length>2){if(this.multi)throw new z(\"Graph.\".concat(t,\": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.\"));var a=\"\"+e,c=\"\"+i;if(i=arguments[2],!(o=u(this,a,c,n)))throw new U(\"Graph.\".concat(t,': could not find an edge for the given path (\"').concat(a,'\" - \"').concat(c,'\").'))}else if(e=\"\"+e,!(o=this._edges.get(e)))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" edge in the graph.'));if(\"mixed\"!==n&&!(o instanceof r))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" ').concat(n,\" edge in the graph.\"));return delete o.attributes[i],this.emit(\"edgeAttributesUpdated\",{key:o.key,type:\"remove\",meta:{name:i}}),this}}},{name:function(e){return\"replace\".concat(e,\"Attributes\")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i){var o;if(\"mixed\"!==this.type&&\"mixed\"!==n&&n!==this.type)throw new z(\"Graph.\".concat(t,\": cannot find this type of edges in your \").concat(this.type,\" graph.\"));if(arguments.length>2){if(this.multi)throw new z(\"Graph.\".concat(t,\": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.\"));var a=\"\"+e,c=\"\"+i;if(i=arguments[2],!(o=u(this,a,c,n)))throw new U(\"Graph.\".concat(t,': could not find an edge for the given path (\"').concat(a,'\" - \"').concat(c,'\").'))}else if(e=\"\"+e,!(o=this._edges.get(e)))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" edge in the graph.'));if(!h(i))throw new j(\"Graph.\".concat(t,\": provided attributes are not a plain object.\"));if(\"mixed\"!==n&&!(o instanceof r))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" ').concat(n,\" edge in the graph.\"));var d=o.attributes;return o.attributes=i,this.emit(\"edgeAttributesUpdated\",{key:o.key,type:\"replace\",meta:{before:d,after:i}}),this}}},{name:function(e){return\"merge\".concat(e,\"Attributes\")},attacher:function(e,t,n,r){e.prototype[t]=function(e,i){var o;if(\"mixed\"!==this.type&&\"mixed\"!==n&&n!==this.type)throw new z(\"Graph.\".concat(t,\": cannot find this type of edges in your \").concat(this.type,\" graph.\"));if(arguments.length>2){if(this.multi)throw new z(\"Graph.\".concat(t,\": cannot use a {source,target} combo when asking about an edge's attributes in a MultiGraph since we cannot infer the one you want information about.\"));var a=\"\"+e,c=\"\"+i;if(i=arguments[2],!(o=u(this,a,c,n)))throw new U(\"Graph.\".concat(t,': could not find an edge for the given path (\"').concat(a,'\" - \"').concat(c,'\").'))}else if(e=\"\"+e,!(o=this._edges.get(e)))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" edge in the graph.'));if(!h(i))throw new j(\"Graph.\".concat(t,\": provided attributes are not a plain object.\"));if(\"mixed\"!==n&&!(o instanceof r))throw new U(\"Graph.\".concat(t,': could not find the \"').concat(e,'\" ').concat(n,\" edge in the graph.\"));return d(o.attributes,i),this.emit(\"edgeAttributesUpdated\",{key:o.key,type:\"merge\",meta:{data:i}}),this}}}];var I=function(){var e,t=arguments,n=-1;return new N((function r(){if(!e){if(++n>=t.length)return{done:!0};e=t[n]}var i=e.next();return i.done?(e=null,r()):i}))},F=[{name:\"edges\",type:\"mixed\"},{name:\"inEdges\",type:\"directed\",direction:\"in\"},{name:\"outEdges\",type:\"directed\",direction:\"out\"},{name:\"inboundEdges\",type:\"mixed\",direction:\"in\"},{name:\"outboundEdges\",type:\"mixed\",direction:\"out\"},{name:\"directedEdges\",type:\"directed\"},{name:\"undirectedEdges\",type:\"undirected\"}];function Y(e,t){for(var n in t)t[n]instanceof Set?t[n].forEach((function(t){return e.push(t.key)})):e.push(t[n].key)}function J(e,t){for(var n in e){var r=e[n];t(r.key,r.attributes,r.source.key,r.target.key,r.source.attributes,r.target.attributes)}}function q(e,t){for(var n in e)e[n].forEach((function(e){return t(e.key,e.attributes,e.source.key,e.target.key,e.source.attributes,e.target.attributes)}))}function B(e){var t=Object.keys(e),n=t.length,r=null,i=0;return new N((function o(){var a;if(r){var c=r.next();if(c.done)return r=null,i++,o();a=c.value}else{if(i>=n)return{done:!0};var d=t[i];if((a=e[d])instanceof Set)return r=a.values(),o();i++}return{done:!1,value:[a.key,a.attributes,a.source.key,a.target.key,a.source.attributes,a.target.attributes]}}))}function H(e,t,n){n in t&&(t[n]instanceof Set?t[n].forEach((function(t){return e.push(t.key)})):e.push(t[n].key))}function Q(e,t,n){if(t in e)if(e[t]instanceof Set)e[t].forEach((function(e){return n(e.key,e.attributes,e.source.key,e.target.key,e.source.attributes,e.target.attributes)}));else{var r=e[t];n(r.key,r.attributes,r.source.key,r.target.key,r.source.attributes,r.target.attributes)}}function V(e,t){var n=e[t];if(n instanceof Set){var r=n.values();return new N((function(){var e=r.next();if(e.done)return e;var t=e.value;return{done:!1,value:[t.key,t.attributes,t.source.key,t.target.key,t.source.attributes,t.target.attributes]}}))}return N.of([n.key,n.attributes,n.source.key,n.target.key,n.source.attributes,n.target.attributes])}function X(e,t){if(0===e.size)return[];if(\"mixed\"===t||t===e.type)return D(e._edges.keys(),e._edges.size);var n=\"undirected\"===t?e.undirectedSize:e.directedSize,r=new Array(n),i=\"undirected\"===t,o=0;return e._edges.forEach((function(e,t){e instanceof T===i&&(r[o++]=t)})),r}function Z(e,t,n){if(0!==e.size)if(\"mixed\"===t||t===e.type)e._edges.forEach((function(e,t){var r=e.attributes,i=e.source,o=e.target;n(t,r,i.key,o.key,i.attributes,o.attributes)}));else{var r=\"undirected\"===t;e._edges.forEach((function(e,t){if(e instanceof T===r){var i=e.attributes,o=e.source,a=e.target;n(t,i,o.key,a.key,o.attributes,a.attributes)}}))}}function $(e,t){return 0===e.size?N.empty():\"mixed\"===t?(n=e._edges.values(),new N((function(){var e=n.next();if(e.done)return e;var t=e.value;return{value:[t.key,t.attributes,t.source.key,t.target.key,t.source.attributes,t.target.attributes],done:!1}}))):(n=e._edges.values(),new N((function e(){var r=n.next();if(r.done)return r;var i=r.value;return i instanceof T==(\"undirected\"===t)?{value:[i.key,i.attributes,i.source.key,i.target.key,i.source.attributes,i.target.attributes],done:!1}:e()})));var n}function ee(e,t,n){var r=[];return\"undirected\"!==e&&(\"out\"!==t&&Y(r,n.in),\"in\"!==t&&Y(r,n.out)),\"directed\"!==e&&Y(r,n.undirected),r}function te(e,t,n,r,i){var o=e?q:J;\"undirected\"!==t&&(\"out\"!==n&&o(r.in,i),\"in\"!==n&&o(r.out,i)),\"directed\"!==t&&o(r.undirected,i)}function ne(e,t,n){var r=N.empty();return\"undirected\"!==e&&(\"out\"!==t&&void 0!==n.in&&(r=I(r,B(n.in))),\"in\"!==t&&void 0!==n.out&&(r=I(r,B(n.out)))),\"directed\"!==e&&void 0!==n.undirected&&(r=I(r,B(n.undirected))),r}function re(e,t,n,r){var i=[];return\"undirected\"!==e&&(void 0!==n.in&&\"out\"!==t&&H(i,n.in,r),void 0!==n.out&&\"in\"!==t&&H(i,n.out,r)),\"directed\"!==e&&void 0!==n.undirected&&H(i,n.undirected,r),i}function ie(e,t,n,r,i){\"undirected\"!==e&&(void 0!==n.in&&\"out\"!==t&&Q(n.in,r,i),void 0!==n.out&&\"in\"!==t&&Q(n.out,r,i)),\"directed\"!==e&&void 0!==n.undirected&&Q(n.undirected,r,i)}function oe(e,t,n,r){var i=N.empty();return\"undirected\"!==e&&(void 0!==n.in&&\"out\"!==t&&r in n.in&&(i=I(i,V(n.in,r))),void 0!==n.out&&\"in\"!==t&&r in n.out&&(i=I(i,V(n.out,r)))),\"directed\"!==e&&void 0!==n.undirected&&r in n.undirected&&(i=I(i,V(n.undirected,r))),i}var ae=[{name:\"neighbors\",type:\"mixed\"},{name:\"inNeighbors\",type:\"directed\",direction:\"in\"},{name:\"outNeighbors\",type:\"directed\",direction:\"out\"},{name:\"inboundNeighbors\",type:\"mixed\",direction:\"in\"},{name:\"outboundNeighbors\",type:\"mixed\",direction:\"out\"},{name:\"directedNeighbors\",type:\"directed\"},{name:\"undirectedNeighbors\",type:\"undirected\"}];function ce(e,t){if(void 0!==t)for(var n in t)e.add(n)}function de(e,t,n){if(\"mixed\"!==e){if(\"undirected\"===e)return Object.keys(n.undirected);if(\"string\"==typeof t)return Object.keys(n[t])}var r=new Set;return\"undirected\"!==e&&(\"out\"!==t&&ce(r,n.in),\"in\"!==t&&ce(r,n.out)),\"directed\"!==e&&ce(r,n.undirected),D(r.values(),r.size)}function ue(e,t,n){for(var r in t){var i=t[r];i instanceof Set&&(i=i.values().next().value);var o=i.source,a=i.target,c=o===e?a:o;n(c.key,c.attributes)}}function se(e,t,n,r){for(var i in n){var o=n[i];o instanceof Set&&(o=o.values().next().value);var a=o.source,c=o.target,d=a===t?c:a;e.has(d.key)||(e.add(d.key),r(d.key,d.attributes))}}function he(e,t){var n=Object.keys(t),r=n.length,i=0;return new N((function(){if(i>=r)return{done:!0};var o=t[n[i++]];o instanceof Set&&(o=o.values().next().value);var a=o.source,c=o.target,d=a===e?c:a;return{done:!1,value:[d.key,d.attributes]}}))}function fe(e,t,n){var r=Object.keys(n),i=r.length,o=0;return new N((function a(){if(o>=i)return{done:!0};var c=n[r[o++]];c instanceof Set&&(c=c.values().next().value);var d=c.source,u=c.target,s=d===t?u:d;return e.has(s.key)?a():(e.add(s.key),{done:!1,value:[s.key,s.attributes]})}))}function pe(e,t,n,r,i){var o=e._nodes.get(r);if(\"undirected\"!==t){if(\"out\"!==n&&void 0!==o.in)for(var a in o.in)if(a===i)return!0;if(\"in\"!==n&&void 0!==o.out)for(var c in o.out)if(c===i)return!0}if(\"directed\"!==t&&void 0!==o.undirected)for(var d in o.undirected)if(d===i)return!0;return!1}function ge(e,t){var n=t.name,r=t.type,i=t.direction,o=\"forEach\"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[o]=function(e,t){if(\"mixed\"===r||\"mixed\"===this.type||r===this.type){e=\"\"+e;var n=this._nodes.get(e);if(void 0===n)throw new U(\"Graph.\".concat(o,': could not find the \"').concat(e,'\" node in the graph.'));!function(e,t,n,r){if(\"mixed\"!==e){if(\"undirected\"===e)return ue(n,n.undirected,r);if(\"string\"==typeof t)return ue(n,n[t],r)}var i=new Set;\"undirected\"!==e&&(\"out\"!==t&&se(i,n,n.in,r),\"in\"!==t&&se(i,n,n.out,r)),\"directed\"!==e&&se(i,n,n.undirected,r)}(\"mixed\"===r?this.type:r,i,n,t)}}}function le(e,t){var n=t.name,r=t.type,i=t.direction,o=n.slice(0,-1)+\"Entries\";e.prototype[o]=function(e){if(\"mixed\"!==r&&\"mixed\"!==this.type&&r!==this.type)return N.empty();e=\"\"+e;var t=this._nodes.get(e);if(void 0===t)throw new U(\"Graph.\".concat(o,': could not find the \"').concat(e,'\" node in the graph.'));return function(e,t,n){if(\"mixed\"!==e){if(\"undirected\"===e)return he(n,n.undirected);if(\"string\"==typeof t)return he(n,n[t])}var r=N.empty(),i=new Set;return\"undirected\"!==e&&(\"out\"!==t&&(r=I(r,fe(i,n,n.in))),\"in\"!==t&&(r=I(r,fe(i,n,n.out)))),\"directed\"!==e&&(r=I(r,fe(i,n,n.undirected))),r}(\"mixed\"===r?this.type:r,i,t)}}function ye(e,t){var n={key:e};return Object.keys(t.attributes).length&&(n.attributes=d({},t.attributes)),n}function ve(e,t){var n={source:t.source.key,target:t.target.key};return t.generatedKey||(n.key=e),Object.keys(t.attributes).length&&(n.attributes=d({},t.attributes)),t instanceof T&&(n.undirected=!0),n}function we(e){return h(e)?\"key\"in e?!(\"attributes\"in e)||h(e.attributes)&&null!==e.attributes?null:\"invalid-attributes\":\"no-key\":\"not-object\"}function be(e){return h(e)?\"source\"in e?\"target\"in e?!(\"attributes\"in e)||h(e.attributes)&&null!==e.attributes?\"undirected\"in e&&\"boolean\"!=typeof e.undirected?\"invalid-undirected\":null:\"invalid-attributes\":\"no-target\":\"no-source\":\"not-object\"}var me=new Set([\"directed\",\"undirected\",\"mixed\"]),_e=new Set([\"domain\",\"_events\",\"_eventsCount\",\"_maxListeners\"]),Ge={allowSelfLoops:!0,edgeKeyGenerator:null,multi:!1,type:\"mixed\"};function Ee(e,t,n,r,i,o,a,c){if(!r&&\"undirected\"===e.type)throw new z(\"Graph.\".concat(t,\": you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead.\"));if(r&&\"directed\"===e.type)throw new z(\"Graph.\".concat(t,\": you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.\"));if(c&&!h(c))throw new j(\"Graph.\".concat(t,': invalid attributes. Expecting an object but got \"').concat(c,'\"'));if(o=\"\"+o,a=\"\"+a,c=c||{},!e.allowSelfLoops&&o===a)throw new z(\"Graph.\".concat(t,': source & target are the same (\"').concat(o,\"\\\"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.\"));var d=e._nodes.get(o),u=e._nodes.get(a);if(!d)throw new U(\"Graph.\".concat(t,': source node \"').concat(o,'\" not found.'));if(!u)throw new U(\"Graph.\".concat(t,': target node \"').concat(a,'\" not found.'));var s={key:null,undirected:r,source:o,target:a,attributes:c};if(n&&(i=e._edgeKeyGenerator(s)),i=\"\"+i,e._edges.has(i))throw new z(\"Graph.\".concat(t,': the \"').concat(i,'\" edge already exists in the graph.'));if(!e.multi&&(r?void 0!==d.undirected[a]:void 0!==d.out[a]))throw new z(\"Graph.\".concat(t,': an edge linking \"').concat(o,'\" to \"').concat(a,\"\\\" already exists. If you really want to add multiple edges linking those nodes, you should create a multi graph by using the 'multi' option.\"));var f=new(r?T:C)(i,n,d,u,c);return e._edges.set(i,f),o===a?r?d.undirectedSelfLoops++:d.directedSelfLoops++:r?(d.undirectedDegree++,u.undirectedDegree++):(d.outDegree++,u.inDegree++),P(e,r,f,o,a,d,u),r?e._undirectedSize++:e._directedSize++,s.key=i,e.emit(\"edgeAdded\",s),i}function ke(e,t,n,r,i,o,a,c){if(!r&&\"undirected\"===e.type)throw new z(\"Graph.\".concat(t,\": you cannot add a directed edge to an undirected graph. Use the #.addEdge or #.addUndirectedEdge instead.\"));if(r&&\"directed\"===e.type)throw new z(\"Graph.\".concat(t,\": you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.\"));if(c&&!h(c))throw new j(\"Graph.\".concat(t,': invalid attributes. Expecting an object but got \"').concat(c,'\"'));if(o=\"\"+o,a=\"\"+a,c=c||{},!e.allowSelfLoops&&o===a)throw new z(\"Graph.\".concat(t,': source & target are the same (\"').concat(o,\"\\\"), thus creating a loop explicitly forbidden by this graph 'allowSelfLoops' option set to false.\"));var s,f,p=e._nodes.get(o),g=e._nodes.get(a),l=null;if(!n&&(s=e._edges.get(i))){if(s.source!==o||s.target!==a||r&&(s.source!==a||s.target!==o))throw new z(\"Graph.\".concat(t,': inconsistency detected when attempting to merge the \"').concat(i,'\" edge with \"').concat(o,'\" source & \"').concat(a,'\" target vs. (').concat(s.source,\", \").concat(s.target,\").\"));l=i}if(l||e.multi||!p||(r?void 0===p.undirected[a]:void 0===p.out[a])||(f=u(e,o,a,r?\"undirected\":\"directed\")),f)return c?(d(f.attributes,c),l):l;var y={key:null,undirected:r,source:o,target:a,attributes:c};if(n&&(i=e._edgeKeyGenerator(y)),i=\"\"+i,e._edges.has(i))throw new z(\"Graph.\".concat(t,': the \"').concat(i,'\" edge already exists in the graph.'));return p||(e.addNode(o),p=e._nodes.get(o),o===a&&(g=p)),g||(e.addNode(a),g=e._nodes.get(a)),s=new(r?T:C)(i,n,p,g,c),e._edges.set(i,s),o===a?r?p.undirectedSelfLoops++:p.directedSelfLoops++:r?(p.undirectedDegree++,g.undirectedDegree++):(p.outDegree++,g.inDegree++),P(e,r,s,o,a,p,g),r?e._undirectedSize++:e._directedSize++,y.key=i,e.emit(\"edgeAdded\",y),i}var xe=function(e){function n(t){var n;if(n=e.call(this)||this,(t=d({},Ge,t)).edgeKeyGenerator&&\"function\"!=typeof t.edgeKeyGenerator)throw new j(\"Graph.constructor: invalid 'edgeKeyGenerator' option. Expecting a function but got \\\"\".concat(t.edgeKeyGenerator,'\".'));if(\"boolean\"!=typeof t.multi)throw new j(\"Graph.constructor: invalid 'multi' option. Expecting a boolean but got \\\"\".concat(t.multi,'\".'));if(!me.has(t.type))throw new j('Graph.constructor: invalid \\'type\\' option. Should be one of \"mixed\", \"directed\" or \"undirected\" but got \"'.concat(t.type,'\".'));if(\"boolean\"!=typeof t.allowSelfLoops)throw new j(\"Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got \\\"\".concat(t.allowSelfLoops,'\".'));var r,i=\"mixed\"===t.type?O:\"directed\"===t.type?K:M;return p(c(n),\"NodeDataClass\",i),p(c(n),\"_attributes\",{}),p(c(n),\"_nodes\",new Map),p(c(n),\"_edges\",new Map),p(c(n),\"_directedSize\",0),p(c(n),\"_undirectedSize\",0),p(c(n),\"_edgeKeyGenerator\",t.edgeKeyGenerator||(r=0,function(){return\"_geid\".concat(r++,\"_\")})),p(c(n),\"_options\",t),_e.forEach((function(e){return p(c(n),e,n[e])})),g(c(n),\"order\",(function(){return n._nodes.size})),g(c(n),\"size\",(function(){return n._edges.size})),g(c(n),\"directedSize\",(function(){return n._directedSize})),g(c(n),\"undirectedSize\",(function(){return n._undirectedSize})),g(c(n),\"multi\",n._options.multi),g(c(n),\"type\",n._options.type),g(c(n),\"allowSelfLoops\",n._options.allowSelfLoops),n}t(n,e);var r=n.prototype;return r.hasNode=function(e){return this._nodes.has(\"\"+e)},r.hasDirectedEdge=function(e,t){if(\"undirected\"===this.type)return!1;if(1===arguments.length){var n=\"\"+e,r=this._edges.get(n);return!!r&&r instanceof C}if(2===arguments.length){e=\"\"+e,t=\"\"+t;var i=this._nodes.get(e);if(!i)return!1;var o=i.out[t];return!!o&&(!this.multi||!!o.size)}throw new j(\"Graph.hasDirectedEdge: invalid arity (\".concat(arguments.length,\", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.\"))},r.hasUndirectedEdge=function(e,t){if(\"directed\"===this.type)return!1;if(1===arguments.length){var n=\"\"+e,r=this._edges.get(n);return!!r&&r instanceof T}if(2===arguments.length){e=\"\"+e,t=\"\"+t;var i=this._nodes.get(e);if(!i)return!1;var o=i.undirected[t];return!!o&&(!this.multi||!!o.size)}throw new j(\"Graph.hasDirectedEdge: invalid arity (\".concat(arguments.length,\", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.\"))},r.hasEdge=function(e,t){if(1===arguments.length){var n=\"\"+e;return this._edges.has(n)}if(2===arguments.length){e=\"\"+e,t=\"\"+t;var r=this._nodes.get(e);if(!r)return!1;var i=void 0!==r.out&&r.out[t];return i||(i=void 0!==r.undirected&&r.undirected[t]),!!i&&(!this.multi||!!i.size)}throw new j(\"Graph.hasEdge: invalid arity (\".concat(arguments.length,\", instead of 1 or 2). You can either ask for an edge id or for the existence of an edge between a source & a target.\"))},r.directedEdge=function(e,t){if(\"undirected\"!==this.type){if(e=\"\"+e,t=\"\"+t,this.multi)throw new z(\"Graph.directedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.directedEdges instead.\");var n=this._nodes.get(e);if(!n)throw new U('Graph.directedEdge: could not find the \"'.concat(e,'\" source node in the graph.'));if(!this._nodes.has(t))throw new U('Graph.directedEdge: could not find the \"'.concat(t,'\" target node in the graph.'));var r=n.out&&n.out[t]||void 0;return r?r.key:void 0}},r.undirectedEdge=function(e,t){if(\"directed\"!==this.type){if(e=\"\"+e,t=\"\"+t,this.multi)throw new z(\"Graph.undirectedEdge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.undirectedEdges instead.\");var n=this._nodes.get(e);if(!n)throw new U('Graph.undirectedEdge: could not find the \"'.concat(e,'\" source node in the graph.'));if(!this._nodes.has(t))throw new U('Graph.undirectedEdge: could not find the \"'.concat(t,'\" target node in the graph.'));var r=n.undirected&&n.undirected[t]||void 0;return r?r.key:void 0}},r.edge=function(e,t){if(this.multi)throw new z(\"Graph.edge: this method is irrelevant with multigraphs since there might be multiple edges between source & target. See #.edges instead.\");e=\"\"+e,t=\"\"+t;var n=this._nodes.get(e);if(!n)throw new U('Graph.edge: could not find the \"'.concat(e,'\" source node in the graph.'));if(!this._nodes.has(t))throw new U('Graph.edge: could not find the \"'.concat(t,'\" target node in the graph.'));var r=n.out&&n.out[t]||n.undirected&&n.undirected[t]||void 0;if(r)return r.key},r.inDegree=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(\"boolean\"!=typeof t)throw new j('Graph.inDegree: Expecting a boolean but got \"'.concat(t,'\" for the second parameter (allowing self-loops to be counted).'));e=\"\"+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.inDegree: could not find the \"'.concat(e,'\" node in the graph.'));if(\"undirected\"===this.type)return 0;var r=t?n.directedSelfLoops:0;return n.inDegree+r},r.outDegree=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(\"boolean\"!=typeof t)throw new j('Graph.outDegree: Expecting a boolean but got \"'.concat(t,'\" for the second parameter (allowing self-loops to be counted).'));e=\"\"+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.outDegree: could not find the \"'.concat(e,'\" node in the graph.'));if(\"undirected\"===this.type)return 0;var r=t?n.directedSelfLoops:0;return n.outDegree+r},r.directedDegree=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(\"boolean\"!=typeof t)throw new j('Graph.directedDegree: Expecting a boolean but got \"'.concat(t,'\" for the second parameter (allowing self-loops to be counted).'));if(e=\"\"+e,!this.hasNode(e))throw new U('Graph.directedDegree: could not find the \"'.concat(e,'\" node in the graph.'));return\"undirected\"===this.type?0:this.inDegree(e,t)+this.outDegree(e,t)},r.undirectedDegree=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(\"boolean\"!=typeof t)throw new j('Graph.undirectedDegree: Expecting a boolean but got \"'.concat(t,'\" for the second parameter (allowing self-loops to be counted).'));if(e=\"\"+e,!this.hasNode(e))throw new U('Graph.undirectedDegree: could not find the \"'.concat(e,'\" node in the graph.'));if(\"directed\"===this.type)return 0;var n=this._nodes.get(e),r=t?2*n.undirectedSelfLoops:0;return n.undirectedDegree+r},r.degree=function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(\"boolean\"!=typeof t)throw new j('Graph.degree: Expecting a boolean but got \"'.concat(t,'\" for the second parameter (allowing self-loops to be counted).'));if(e=\"\"+e,!this.hasNode(e))throw new U('Graph.degree: could not find the \"'.concat(e,'\" node in the graph.'));var n=0;return\"undirected\"!==this.type&&(n+=this.directedDegree(e,t)),\"directed\"!==this.type&&(n+=this.undirectedDegree(e,t)),n},r.source=function(e){e=\"\"+e;var t=this._edges.get(e);if(!t)throw new U('Graph.source: could not find the \"'.concat(e,'\" edge in the graph.'));return t.source.key},r.target=function(e){e=\"\"+e;var t=this._edges.get(e);if(!t)throw new U('Graph.target: could not find the \"'.concat(e,'\" edge in the graph.'));return t.target.key},r.extremities=function(e){e=\"\"+e;var t=this._edges.get(e);if(!t)throw new U('Graph.extremities: could not find the \"'.concat(e,'\" edge in the graph.'));return[t.source.key,t.target.key]},r.opposite=function(e,t){if(e=\"\"+e,t=\"\"+t,!this._nodes.has(e))throw new U('Graph.opposite: could not find the \"'.concat(e,'\" node in the graph.'));var n=this._edges.get(t);if(!n)throw new U('Graph.opposite: could not find the \"'.concat(t,'\" edge in the graph.'));var r=n.source,i=n.target,o=r.key,a=i.key;if(e!==o&&e!==a)throw new U('Graph.opposite: the \"'.concat(e,'\" node is not attached to the \"').concat(t,'\" edge (').concat(o,\", \").concat(a,\").\"));return e===o?a:o},r.undirected=function(e){e=\"\"+e;var t=this._edges.get(e);if(!t)throw new U('Graph.undirected: could not find the \"'.concat(e,'\" edge in the graph.'));return t instanceof T},r.directed=function(e){e=\"\"+e;var t=this._edges.get(e);if(!t)throw new U('Graph.directed: could not find the \"'.concat(e,'\" edge in the graph.'));return t instanceof C},r.selfLoop=function(e){e=\"\"+e;var t=this._edges.get(e);if(!t)throw new U('Graph.selfLoop: could not find the \"'.concat(e,'\" edge in the graph.'));return t.source===t.target},r.addNode=function(e,t){if(t&&!h(t))throw new j('Graph.addNode: invalid attributes. Expecting an object but got \"'.concat(t,'\"'));if(e=\"\"+e,t=t||{},this._nodes.has(e))throw new z('Graph.addNode: the \"'.concat(e,'\" node already exist in the graph.'));var n=new this.NodeDataClass(e,t);return this._nodes.set(e,n),this.emit(\"nodeAdded\",{key:e,attributes:t}),e},r.mergeNode=function(e,t){if(t&&!h(t))throw new j('Graph.mergeNode: invalid attributes. Expecting an object but got \"'.concat(t,'\"'));e=\"\"+e,t=t||{};var n=this._nodes.get(e);return n?(t&&d(n.attributes,t),e):(n=new this.NodeDataClass(e,t),this._nodes.set(e,n),this.emit(\"nodeAdded\",{key:e,attributes:t}),e)},r.dropNode=function(e){if(e=\"\"+e,!this.hasNode(e))throw new U('Graph.dropNode: could not find the \"'.concat(e,'\" node in the graph.'));for(var t=this.edges(e),n=0,r=t.length;n1){var n=\"\"+arguments[0],r=\"\"+arguments[1];if(!(t=u(this,n,r,this.type)))throw new U('Graph.dropEdge: could not find the \"'.concat(n,'\" -> \"').concat(r,'\" edge in the graph.'))}else if(e=\"\"+e,!(t=this._edges.get(e)))throw new U('Graph.dropEdge: could not find the \"'.concat(e,'\" edge in the graph.'));this._edges.delete(t.key);var i=t,o=i.source,a=i.target,c=i.attributes,d=t instanceof T;return o===a?o.selfLoops--:d?(o.undirectedDegree--,a.undirectedDegree--):(o.outDegree--,a.inDegree--),W(this,d,t),d?this._undirectedSize--:this._directedSize--,this.emit(\"edgeDropped\",{key:e,attributes:c,source:o.key,target:a.key,undirected:d}),this},r.clear=function(){this._edges.clear(),this._nodes.clear(),this.emit(\"cleared\")},r.clearEdges=function(){this._edges.clear(),this.clearIndex(),this.emit(\"edgesCleared\")},r.getAttribute=function(e){return this._attributes[e]},r.getAttributes=function(){return this._attributes},r.hasAttribute=function(e){return this._attributes.hasOwnProperty(e)},r.setAttribute=function(e,t){return this._attributes[e]=t,this.emit(\"attributesUpdated\",{type:\"set\",meta:{name:e,value:t}}),this},r.updateAttribute=function(e,t){if(\"function\"!=typeof t)throw new j(\"Graph.updateAttribute: updater should be a function.\");return this._attributes[e]=t(this._attributes[e]),this.emit(\"attributesUpdated\",{type:\"set\",meta:{name:e,value:this._attributes[e]}}),this},r.removeAttribute=function(e){return delete this._attributes[e],this.emit(\"attributesUpdated\",{type:\"remove\",meta:{name:e}}),this},r.replaceAttributes=function(e){if(!h(e))throw new j(\"Graph.replaceAttributes: provided attributes are not a plain object.\");var t=this._attributes;return this._attributes=e,this.emit(\"attributesUpdated\",{type:\"replace\",meta:{before:t,after:e}}),this},r.mergeAttributes=function(e){if(!h(e))throw new j(\"Graph.mergeAttributes: provided attributes are not a plain object.\");return this._attributes=d(this._attributes,e),this.emit(\"attributesUpdated\",{type:\"merge\",meta:{data:this._attributes}}),this},r.getNodeAttribute=function(e,t){e=\"\"+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.getNodeAttribute: could not find the \"'.concat(e,'\" node in the graph.'));return n.attributes[t]},r.getNodeAttributes=function(e){e=\"\"+e;var t=this._nodes.get(e);if(!t)throw new U('Graph.getNodeAttributes: could not find the \"'.concat(e,'\" node in the graph.'));return t.attributes},r.hasNodeAttribute=function(e,t){e=\"\"+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.hasNodeAttribute: could not find the \"'.concat(e,'\" node in the graph.'));return n.attributes.hasOwnProperty(t)},r.setNodeAttribute=function(e,t,n){e=\"\"+e;var r=this._nodes.get(e);if(!r)throw new U('Graph.setNodeAttribute: could not find the \"'.concat(e,'\" node in the graph.'));if(arguments.length<3)throw new j(\"Graph.setNodeAttribute: not enough arguments. Either you forgot to pass the attribute's name or value, or you meant to use #.replaceNodeAttributes / #.mergeNodeAttributes instead.\");return r.attributes[t]=n,this.emit(\"nodeAttributesUpdated\",{key:e,type:\"set\",meta:{name:t,value:n}}),this},r.updateNodeAttribute=function(e,t,n){e=\"\"+e;var r=this._nodes.get(e);if(!r)throw new U('Graph.updateNodeAttribute: could not find the \"'.concat(e,'\" node in the graph.'));if(arguments.length<3)throw new j(\"Graph.updateNodeAttribute: not enough arguments. Either you forgot to pass the attribute's name or updater, or you meant to use #.replaceNodeAttributes / #.mergeNodeAttributes instead.\");if(\"function\"!=typeof n)throw new j(\"Graph.updateAttribute: updater should be a function.\");var i=r.attributes;return i[t]=n(i[t]),this.emit(\"nodeAttributesUpdated\",{key:e,type:\"set\",meta:{name:t,value:i[t]}}),this},r.removeNodeAttribute=function(e,t){e=\"\"+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.hasNodeAttribute: could not find the \"'.concat(e,'\" node in the graph.'));return delete n.attributes[t],this.emit(\"nodeAttributesUpdated\",{key:e,type:\"remove\",meta:{name:t}}),this},r.replaceNodeAttributes=function(e,t){e=\"\"+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.replaceNodeAttributes: could not find the \"'.concat(e,'\" node in the graph.'));if(!h(t))throw new j(\"Graph.replaceNodeAttributes: provided attributes are not a plain object.\");var r=n.attributes;return n.attributes=t,this.emit(\"nodeAttributesUpdated\",{key:e,type:\"replace\",meta:{before:r,after:t}}),this},r.mergeNodeAttributes=function(e,t){e=\"\"+e;var n=this._nodes.get(e);if(!n)throw new U('Graph.mergeNodeAttributes: could not find the \"'.concat(e,'\" node in the graph.'));if(!h(t))throw new j(\"Graph.mergeNodeAttributes: provided attributes are not a plain object.\");return d(n.attributes,t),this.emit(\"nodeAttributesUpdated\",{key:e,type:\"merge\",meta:{data:t}}),this},r.forEach=function(e){if(\"function\"!=typeof e)throw new j(\"Graph.forEach: expecting a callback.\");this._edges.forEach((function(t,n){var r=t.source,i=t.target;e(r.key,i.key,r.attributes,i.attributes,n,t.attributes)}))},r.adjacency=function(){var e=this._edges.values();return new N((function(){var t=e.next();if(t.done)return t;var n=t.value,r=n.source,i=n.target;return{done:!1,value:[r.key,i.key,r.attributes,i.attributes,n.key,n.attributes]}}))},r.nodes=function(){return D(this._nodes.keys(),this._nodes.size)},r.forEachNode=function(e){if(\"function\"!=typeof e)throw new j(\"Graph.forEachNode: expecting a callback.\");this._nodes.forEach((function(t,n){e(n,t.attributes)}))},r.nodeEntries=function(){var e=this._nodes.values();return new N((function(){var t=e.next();if(t.done)return t;var n=t.value;return{value:[n.key,n.attributes],done:!1}}))},r.exportNode=function(e){e=\"\"+e;var t=this._nodes.get(e);if(!t)throw new U('Graph.exportNode: could not find the \"'.concat(e,'\" node in the graph.'));return ye(e,t)},r.exportEdge=function(e){e=\"\"+e;var t=this._edges.get(e);if(!t)throw new U('Graph.exportEdge: could not find the \"'.concat(e,'\" edge in the graph.'));return ve(e,t)},r.export=function(){var e=new Array(this._nodes.size),t=0;this._nodes.forEach((function(n,r){e[t++]=ye(r,n)}));var n=new Array(this._edges.size);return t=0,this._edges.forEach((function(e,r){n[t++]=ve(r,e)})),{attributes:this.getAttributes(),nodes:e,edges:n}},r.importNode=function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=we(e);if(n){if(\"not-object\"===n)throw new j('Graph.importNode: invalid serialized node. A serialized node should be a plain object with at least a \"key\" property.');if(\"no-key\"===n)throw new j(\"Graph.importNode: no key provided.\");if(\"invalid-attributes\"===n)throw new j(\"Graph.importNode: invalid attributes. Attributes should be a plain object, null or omitted.\")}var r=e.key,i=e.attributes,o=void 0===i?{}:i;return t?this.mergeNode(r,o):this.addNode(r,o),this},r.importEdge=function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=be(e);if(n){if(\"not-object\"===n)throw new j('Graph.importEdge: invalid serialized edge. A serialized edge should be a plain object with at least a \"source\" & \"target\" property.');if(\"no-source\"===n)throw new j(\"Graph.importEdge: missing souce.\");if(\"no-target\"===n)throw new j(\"Graph.importEdge: missing target.\");if(\"invalid-attributes\"===n)throw new j(\"Graph.importEdge: invalid attributes. Attributes should be a plain object, null or omitted.\");if(\"invalid-undirected\"===n)throw new j(\"Graph.importEdge: invalid undirected. Undirected should be boolean or omitted.\")}var r=e.source,i=e.target,o=e.attributes,a=void 0===o?{}:o,c=e.undirected,d=void 0!==c&&c;return\"key\"in e?(t?d?this.mergeUndirectedEdgeWithKey:this.mergeDirectedEdgeWithKey:d?this.addUndirectedEdgeWithKey:this.addDirectedEdgeWithKey).call(this,e.key,r,i,a):(t?d?this.mergeUndirectedEdge:this.mergeDirectedEdge:d?this.addUndirectedEdge:this.addDirectedEdge).call(this,r,i,a),this},r.import=function(e){var t=this,n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(s(e))return this.import(e.export(),n),this;if(!h(e))throw new j(\"Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.\");if(e.attributes){if(!h(e.attributes))throw new j(\"Graph.import: invalid attributes. Expecting a plain object.\");n?this.mergeAttributes(e.attributes):this.replaceAttributes(e.attributes)}return e.nodes&&e.nodes.forEach((function(e){return t.importNode(e,n)})),e.edges&&e.edges.forEach((function(e){return t.importEdge(e,n)})),this},r.nullCopy=function(e){return new n(d({},this._options,e))},r.emptyCopy=function(e){var t=new n(d({},this._options,e));return this._nodes.forEach((function(e,n){e=new t.NodeDataClass(n,d({},e.attributes)),t._nodes.set(n,e)})),t},r.copy=function(){var e=new n(this._options);return e.import(this),e},r.upgradeToMixed=function(){return\"mixed\"===this.type||(this._nodes.forEach((function(e){return e.upgradeToMixed()})),this._options.type=\"mixed\",g(this,\"type\",this._options.type),p(this,\"NodeDataClass\",O)),this},r.upgradeToMulti=function(){return this.multi||(this._options.multi=!0,g(this,\"multi\",!0),(e=this)._nodes.forEach((function(t,n){if(t.out)for(var r in t.out){var i=new Set;i.add(t.out[r]),t.out[r]=i,e._nodes.get(r).in[n]=i}if(t.undirected)for(var o in t.undirected)if(!(o>n)){var a=new Set;a.add(t.undirected[o]),t.undirected[o]=a,e._nodes.get(o).undirected[n]=a}}))),this;var e},r.clearIndex=function(){return this._nodes.forEach((function(e){void 0!==e.in&&(e.in={},e.out={}),void 0!==e.undirected&&(e.undirected={})})),this},r.toJSON=function(){return this.export()},r.toString=function(){var e=this.order>1||0===this.order,t=this.size>1||0===this.size;return\"Graph<\".concat(f(this.order),\" node\").concat(e?\"s\":\"\",\", \").concat(f(this.size),\" edge\").concat(t?\"s\":\"\",\">\")},r.inspect=function(){var e=this,t={};this._nodes.forEach((function(e,n){t[n]=e.attributes}));var n={},r={};this._edges.forEach((function(t,i){var o=t instanceof T?\"--\":\"->\",a=\"\",c=\"(\".concat(t.source.key,\")\").concat(o,\"(\").concat(t.target.key,\")\");t.generatedKey?e.multi&&(void 0===r[c]?r[c]=0:r[c]++,a+=\"\".concat(r[c],\". \")):a+=\"[\".concat(i,\"]: \"),n[a+=c]=t.attributes}));var i={};for(var o in this)this.hasOwnProperty(o)&&!_e.has(o)&&\"function\"!=typeof this[o]&&(i[o]=this[o]);return i.attributes=this._attributes,i.nodes=t,i.edges=n,p(i,\"constructor\",this.constructor),i},n}(y);\"undefined\"!=typeof Symbol&&(xe.prototype[Symbol.for(\"nodejs.util.inspect.custom\")]=xe.prototype.inspect),[{name:function(e){return\"\".concat(e,\"Edge\")},generateKey:!0},{name:function(e){return\"\".concat(e,\"DirectedEdge\")},generateKey:!0,type:\"directed\"},{name:function(e){return\"\".concat(e,\"UndirectedEdge\")},generateKey:!0,type:\"undirected\"},{name:function(e){return\"\".concat(e,\"EdgeWithKey\")}},{name:function(e){return\"\".concat(e,\"DirectedEdgeWithKey\")},type:\"directed\"},{name:function(e){return\"\".concat(e,\"UndirectedEdgeWithKey\")},type:\"undirected\"}].forEach((function(e){[\"add\",\"merge\"].forEach((function(t){var n=e.name(t),r=\"add\"===t?Ee:ke;e.generateKey?xe.prototype[n]=function(t,i,o){return r(this,n,!0,\"undirected\"===(e.type||this.type),null,t,i,o)}:xe.prototype[n]=function(t,i,o,a){return r(this,n,!1,\"undirected\"===(e.type||this.type),t,i,o,a)}}))})),\"undefined\"!=typeof Symbol&&(xe.prototype[Symbol.iterator]=xe.prototype.adjacency),function(e){R.forEach((function(t){var n=t.name,r=t.attacher;r(e,n(\"Edge\"),\"mixed\",C),r(e,n(\"DirectedEdge\"),\"directed\",C),r(e,n(\"UndirectedEdge\"),\"undirected\",T)}))}(xe),function(e){F.forEach((function(t){!function(e,t){var n=t.name,r=t.type,i=t.direction;e.prototype[n]=function(e,t){if(\"mixed\"!==r&&\"mixed\"!==this.type&&r!==this.type)return[];if(!arguments.length)return X(this,r);if(1===arguments.length){e=\"\"+e;var o=this._nodes.get(e);if(void 0===o)throw new U(\"Graph.\".concat(n,': could not find the \"').concat(e,'\" node in the graph.'));return ee(\"mixed\"===r?this.type:r,i,o)}if(2===arguments.length){e=\"\"+e,t=\"\"+t;var a=this._nodes.get(e);if(!a)throw new U(\"Graph.\".concat(n,': could not find the \"').concat(e,'\" source node in the graph.'));if(!this._nodes.has(t))throw new U(\"Graph.\".concat(n,': could not find the \"').concat(t,'\" target node in the graph.'));return re(r,i,a,t)}throw new j(\"Graph.\".concat(n,\": too many arguments (expecting 0, 1 or 2 and got \").concat(arguments.length,\").\"))}}(e,t),function(e,t){var n=t.name,r=t.type,i=t.direction,o=\"forEach\"+n[0].toUpperCase()+n.slice(1,-1);e.prototype[o]=function(e,t,n){if(\"mixed\"===r||\"mixed\"===this.type||r===this.type){if(1===arguments.length)return Z(this,r,n=e);if(2===arguments.length){e=\"\"+e,n=t;var a=this._nodes.get(e);if(void 0===a)throw new U(\"Graph.\".concat(o,': could not find the \"').concat(e,'\" node in the graph.'));return te(this.multi,\"mixed\"===r?this.type:r,i,a,n)}if(3===arguments.length){e=\"\"+e,t=\"\"+t;var c=this._nodes.get(e);if(!c)throw new U(\"Graph.\".concat(o,': could not find the \"').concat(e,'\" source node in the graph.'));if(!this._nodes.has(t))throw new U(\"Graph.\".concat(o,': could not find the \"').concat(t,'\" target node in the graph.'));return ie(r,i,c,t,n)}throw new j(\"Graph.\".concat(o,\": too many arguments (expecting 1, 2 or 3 and got \").concat(arguments.length,\").\"))}}}(e,t),function(e,t){var n=t.name,r=t.type,i=t.direction,o=n.slice(0,-1)+\"Entries\";e.prototype[o]=function(e,t){if(\"mixed\"!==r&&\"mixed\"!==this.type&&r!==this.type)return N.empty();if(!arguments.length)return $(this,r);if(1===arguments.length){e=\"\"+e;var n=this._nodes.get(e);if(!n)throw new U(\"Graph.\".concat(o,': could not find the \"').concat(e,'\" node in the graph.'));return ne(r,i,n)}if(2===arguments.length){e=\"\"+e,t=\"\"+t;var a=this._nodes.get(e);if(!a)throw new U(\"Graph.\".concat(o,': could not find the \"').concat(e,'\" source node in the graph.'));if(!this._nodes.has(t))throw new U(\"Graph.\".concat(o,': could not find the \"').concat(t,'\" target node in the graph.'));return oe(r,i,a,t)}throw new j(\"Graph.\".concat(o,\": too many arguments (expecting 0, 1 or 2 and got \").concat(arguments.length,\").\"))}}(e,t)}))}(xe),function(e){ae.forEach((function(t){!function(e,t){var n=t.name,r=t.type,i=t.direction;e.prototype[n]=function(e){if(\"mixed\"!==r&&\"mixed\"!==this.type&&r!==this.type)return[];if(2===arguments.length){var t=\"\"+arguments[0],o=\"\"+arguments[1];if(!this._nodes.has(t))throw new U(\"Graph.\".concat(n,': could not find the \"').concat(t,'\" node in the graph.'));if(!this._nodes.has(o))throw new U(\"Graph.\".concat(n,': could not find the \"').concat(o,'\" node in the graph.'));return pe(this,r,i,t,o)}if(1===arguments.length){e=\"\"+e;var a=this._nodes.get(e);if(void 0===a)throw new U(\"Graph.\".concat(n,': could not find the \"').concat(e,'\" node in the graph.'));var c=de(\"mixed\"===r?this.type:r,i,a);return c}throw new j(\"Graph.\".concat(n,\": invalid number of arguments (expecting 1 or 2 and got \").concat(arguments.length,\").\"))}}(e,t),ge(e,t),le(e,t)}))}(xe);var Se=function(e){function n(t){return e.call(this,d({type:\"directed\"},t))||this}return t(n,e),n}(xe),Ae=function(e){function n(t){return e.call(this,d({type:\"undirected\"},t))||this}return t(n,e),n}(xe),Ne=function(e){function n(t){return e.call(this,d({multi:!0},t))||this}return t(n,e),n}(xe),De=function(e){function n(t){return e.call(this,d({multi:!0,type:\"directed\"},t))||this}return t(n,e),n}(xe),Le=function(e){function n(t){return e.call(this,d({multi:!0,type:\"undirected\"},t))||this}return t(n,e),n}(xe);function je(e){e.from=function(t,n){var r=new e(n);return r.import(t),r}}return je(xe),je(Se),je(Ae),je(Ne),je(De),je(Le),xe.Graph=xe,xe.DirectedGraph=Se,xe.UndirectedGraph=Ae,xe.MultiGraph=Ne,xe.MultiDirectedGraph=De,xe.MultiUndirectedGraph=Le,xe.InvalidArgumentsGraphError=j,xe.NotFoundGraphError=U,xe.UsageGraphError=z,xe}));\n//# sourceMappingURL=graphology.umd.min.js.map\n","export class InternMap extends Map {\n constructor(entries, key = keyof) {\n super();\n Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});\n if (entries != null) for (const [key, value] of entries) this.set(key, value);\n }\n get(key) {\n return super.get(intern_get(this, key));\n }\n has(key) {\n return super.has(intern_get(this, key));\n }\n set(key, value) {\n return super.set(intern_set(this, key), value);\n }\n delete(key) {\n return super.delete(intern_delete(this, key));\n }\n}\n\nexport class InternSet extends Set {\n constructor(values, key = keyof) {\n super();\n Object.defineProperties(this, {_intern: {value: new Map()}, _key: {value: key}});\n if (values != null) for (const value of values) this.add(value);\n }\n has(value) {\n return super.has(intern_get(this, value));\n }\n add(value) {\n return super.add(intern_set(this, value));\n }\n delete(value) {\n return super.delete(intern_delete(this, value));\n }\n}\n\nfunction intern_get({_intern, _key}, value) {\n const key = _key(value);\n return _intern.has(key) ? _intern.get(key) : value;\n}\n\nfunction intern_set({_intern, _key}, value) {\n const key = _key(value);\n if (_intern.has(key)) return _intern.get(key);\n _intern.set(key, value);\n return value;\n}\n\nfunction intern_delete({_intern, _key}, value) {\n const key = _key(value);\n if (_intern.has(key)) {\n value = _intern.get(value);\n _intern.delete(key);\n }\n return value;\n}\n\nfunction keyof(value) {\n return value !== null && typeof value === \"object\" ? value.valueOf() : value;\n}\n","const toString = Object.prototype.toString;\n\nexport default function isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n","/*\n * jaccard\n * \n */\n\nvar async = require('async');\n\n/*\n * Return mutual elements in the input sets\n */\nvar intersection = function (a, b, c) {\n var x = [];\n var check = function (e, cb) {\n if (~b.indexOf(e)) x.push(e);\n if (cb && typeof cb == 'function') cb(null);\n };\n\n if (c) {\n async.forEach(a, check, function () {\n c(null, x);\n });\n } else {\n a.forEach(check);\n return x;\n }\n}\n\n/*\n * Return distinct elements from both input sets\n */\nvar union = function (a, b, c) {\n var x = [];\n var check = function (e, cb) {\n if (!~x.indexOf(e)) x.push(e);\n if (cb && typeof cb == 'function') cb(null);\n }\n\n if (c) {\n var waiting = 2;\n var asyncCheck = function () {\n if (--waiting == 0) {\n c(null, x);\n }\n }\n async.forEach(a, check, asyncCheck);\n async.forEach(b, check, asyncCheck);\n } else {\n a.forEach(check);\n b.forEach(check);\n return x;\n }\n}\n\n/*\n * Similarity\n */\nvar index = function (a, b, c) {\n if (c) {\n async.parallel({\n intersection: function (cb) {\n intersection(a, b, cb);\n },\n union: function (cb) {\n union(a, b, cb);\n }\n }, function (err, results) {\n c(results.intersection.length / results.union.length);\n });\n } else {\n return intersection(a, b).length / union(a, b).length;\n }\n}\n\n/*\n * Dissimilarity\n */\nvar distance = function (a, b, c) {\n if (c) {\n c(1 - index(a, b));\n } else {\n return 1 - index(a, b);\n }\n}\n\n/*\n * Say cheese\n */\nmodule.exports = {\n index: index,\n distance: distance\n}\n","(function (window, factory) {\n if (typeof exports === 'object') {\n module.exports = factory();\n } else if (typeof define === 'function' && define.amd) {\n define(factory);\n } else {\n window.jStat = factory();\n }\n})(this, function () {\nvar jStat = (function(Math, undefined) {\n\n// For quick reference.\nvar concat = Array.prototype.concat;\nvar slice = Array.prototype.slice;\nvar toString = Object.prototype.toString;\n\n// Calculate correction for IEEE error\n// TODO: This calculation can be improved.\nfunction calcRdx(n, m) {\n var val = n > m ? n : m;\n return Math.pow(10,\n 17 - ~~(Math.log(((val > 0) ? val : -val)) * Math.LOG10E));\n}\n\n\nvar isArray = Array.isArray || function isArray(arg) {\n return toString.call(arg) === '[object Array]';\n};\n\n\nfunction isFunction(arg) {\n return toString.call(arg) === '[object Function]';\n}\n\n\nfunction isNumber(num) {\n return (typeof num === 'number') ? num - num === 0 : false;\n}\n\n\n// Converts the jStat matrix to vector.\nfunction toVector(arr) {\n return concat.apply([], arr);\n}\n\n\n// The one and only jStat constructor.\nfunction jStat() {\n return new jStat._init(arguments);\n}\n\n\n// TODO: Remove after all references in src files have been removed.\njStat.fn = jStat.prototype;\n\n\n// By separating the initializer from the constructor it's easier to handle\n// always returning a new instance whether \"new\" was used or not.\njStat._init = function _init(args) {\n // If first argument is an array, must be vector or matrix.\n if (isArray(args[0])) {\n // Check if matrix.\n if (isArray(args[0][0])) {\n // See if a mapping function was also passed.\n if (isFunction(args[1]))\n args[0] = jStat.map(args[0], args[1]);\n // Iterate over each is faster than this.push.apply(this, args[0].\n for (var i = 0; i < args[0].length; i++)\n this[i] = args[0][i];\n this.length = args[0].length;\n\n // Otherwise must be a vector.\n } else {\n this[0] = isFunction(args[1]) ? jStat.map(args[0], args[1]) : args[0];\n this.length = 1;\n }\n\n // If first argument is number, assume creation of sequence.\n } else if (isNumber(args[0])) {\n this[0] = jStat.seq.apply(null, args);\n this.length = 1;\n\n // Handle case when jStat object is passed to jStat.\n } else if (args[0] instanceof jStat) {\n // Duplicate the object and pass it back.\n return jStat(args[0].toArray());\n\n // Unexpected argument value, return empty jStat object.\n // TODO: This is strange behavior. Shouldn't this throw or some such to let\n // the user know they had bad arguments?\n } else {\n this[0] = [];\n this.length = 1;\n }\n\n return this;\n};\njStat._init.prototype = jStat.prototype;\njStat._init.constructor = jStat;\n\n\n// Utility functions.\n// TODO: for internal use only?\njStat.utils = {\n calcRdx: calcRdx,\n isArray: isArray,\n isFunction: isFunction,\n isNumber: isNumber,\n toVector: toVector\n};\n\n\njStat._random_fn = Math.random;\njStat.setRandom = function setRandom(fn) {\n if (typeof fn !== 'function')\n throw new TypeError('fn is not a function');\n jStat._random_fn = fn;\n};\n\n\n// Easily extend the jStat object.\n// TODO: is this seriously necessary?\njStat.extend = function extend(obj) {\n var i, j;\n\n if (arguments.length === 1) {\n for (j in obj)\n jStat[j] = obj[j];\n return this;\n }\n\n for (i = 1; i < arguments.length; i++) {\n for (j in arguments[i])\n obj[j] = arguments[i][j];\n }\n\n return obj;\n};\n\n\n// Returns the number of rows in the matrix.\njStat.rows = function rows(arr) {\n return arr.length || 1;\n};\n\n\n// Returns the number of columns in the matrix.\njStat.cols = function cols(arr) {\n return arr[0].length || 1;\n};\n\n\n// Returns the dimensions of the object { rows: i, cols: j }\njStat.dimensions = function dimensions(arr) {\n return {\n rows: jStat.rows(arr),\n cols: jStat.cols(arr)\n };\n};\n\n\n// Returns a specified row as a vector or return a sub matrix by pick some rows\njStat.row = function row(arr, index) {\n if (isArray(index)) {\n return index.map(function(i) {\n return jStat.row(arr, i);\n })\n }\n return arr[index];\n};\n\n\n// return row as array\n// rowa([[1,2],[3,4]],0) -> [1,2]\njStat.rowa = function rowa(arr, i) {\n return jStat.row(arr, i);\n};\n\n\n// Returns the specified column as a vector or return a sub matrix by pick some\n// columns\njStat.col = function col(arr, index) {\n if (isArray(index)) {\n var submat = jStat.arange(arr.length).map(function() {\n return new Array(index.length);\n });\n index.forEach(function(ind, i){\n jStat.arange(arr.length).forEach(function(j) {\n submat[j][i] = arr[j][ind];\n });\n });\n return submat;\n }\n var column = new Array(arr.length);\n for (var i = 0; i < arr.length; i++)\n column[i] = [arr[i][index]];\n return column;\n};\n\n\n// return column as array\n// cola([[1,2],[3,4]],0) -> [1,3]\njStat.cola = function cola(arr, i) {\n return jStat.col(arr, i).map(function(a){ return a[0] });\n};\n\n\n// Returns the diagonal of the matrix\njStat.diag = function diag(arr) {\n var nrow = jStat.rows(arr);\n var res = new Array(nrow);\n for (var row = 0; row < nrow; row++)\n res[row] = [arr[row][row]];\n return res;\n};\n\n\n// Returns the anti-diagonal of the matrix\njStat.antidiag = function antidiag(arr) {\n var nrow = jStat.rows(arr) - 1;\n var res = new Array(nrow);\n for (var i = 0; nrow >= 0; nrow--, i++)\n res[i] = [arr[i][nrow]];\n return res;\n};\n\n// Transpose a matrix or array.\njStat.transpose = function transpose(arr) {\n var obj = [];\n var objArr, rows, cols, j, i;\n\n // Make sure arr is in matrix format.\n if (!isArray(arr[0]))\n arr = [arr];\n\n rows = arr.length;\n cols = arr[0].length;\n\n for (i = 0; i < cols; i++) {\n objArr = new Array(rows);\n for (j = 0; j < rows; j++)\n objArr[j] = arr[j][i];\n obj.push(objArr);\n }\n\n // If obj is vector, return only single array.\n return obj.length === 1 ? obj[0] : obj;\n};\n\n\n// Map a function to an array or array of arrays.\n// \"toAlter\" is an internal variable.\njStat.map = function map(arr, func, toAlter) {\n var row, nrow, ncol, res, col;\n\n if (!isArray(arr[0]))\n arr = [arr];\n\n nrow = arr.length;\n ncol = arr[0].length;\n res = toAlter ? arr : new Array(nrow);\n\n for (row = 0; row < nrow; row++) {\n // if the row doesn't exist, create it\n if (!res[row])\n res[row] = new Array(ncol);\n for (col = 0; col < ncol; col++)\n res[row][col] = func(arr[row][col], row, col);\n }\n\n return res.length === 1 ? res[0] : res;\n};\n\n\n// Cumulatively combine the elements of an array or array of arrays using a function.\njStat.cumreduce = function cumreduce(arr, func, toAlter) {\n var row, nrow, ncol, res, col;\n\n if (!isArray(arr[0]))\n arr = [arr];\n\n nrow = arr.length;\n ncol = arr[0].length;\n res = toAlter ? arr : new Array(nrow);\n\n for (row = 0; row < nrow; row++) {\n // if the row doesn't exist, create it\n if (!res[row])\n res[row] = new Array(ncol);\n if (ncol > 0)\n res[row][0] = arr[row][0];\n for (col = 1; col < ncol; col++)\n res[row][col] = func(res[row][col-1], arr[row][col]);\n }\n return res.length === 1 ? res[0] : res;\n};\n\n\n// Destructively alter an array.\njStat.alter = function alter(arr, func) {\n return jStat.map(arr, func, true);\n};\n\n\n// Generate a rows x cols matrix according to the supplied function.\njStat.create = function create(rows, cols, func) {\n var res = new Array(rows);\n var i, j;\n\n if (isFunction(cols)) {\n func = cols;\n cols = rows;\n }\n\n for (i = 0; i < rows; i++) {\n res[i] = new Array(cols);\n for (j = 0; j < cols; j++)\n res[i][j] = func(i, j);\n }\n\n return res;\n};\n\n\nfunction retZero() { return 0; }\n\n\n// Generate a rows x cols matrix of zeros.\njStat.zeros = function zeros(rows, cols) {\n if (!isNumber(cols))\n cols = rows;\n return jStat.create(rows, cols, retZero);\n};\n\n\nfunction retOne() { return 1; }\n\n\n// Generate a rows x cols matrix of ones.\njStat.ones = function ones(rows, cols) {\n if (!isNumber(cols))\n cols = rows;\n return jStat.create(rows, cols, retOne);\n};\n\n\n// Generate a rows x cols matrix of uniformly random numbers.\njStat.rand = function rand(rows, cols) {\n if (!isNumber(cols))\n cols = rows;\n return jStat.create(rows, cols, jStat._random_fn);\n};\n\n\nfunction retIdent(i, j) { return i === j ? 1 : 0; }\n\n\n// Generate an identity matrix of size row x cols.\njStat.identity = function identity(rows, cols) {\n if (!isNumber(cols))\n cols = rows;\n return jStat.create(rows, cols, retIdent);\n};\n\n\n// Tests whether a matrix is symmetric\njStat.symmetric = function symmetric(arr) {\n var size = arr.length;\n var row, col;\n\n if (arr.length !== arr[0].length)\n return false;\n\n for (row = 0; row < size; row++) {\n for (col = 0; col < size; col++)\n if (arr[col][row] !== arr[row][col])\n return false;\n }\n\n return true;\n};\n\n\n// Set all values to zero.\njStat.clear = function clear(arr) {\n return jStat.alter(arr, retZero);\n};\n\n\n// Generate sequence.\njStat.seq = function seq(min, max, length, func) {\n if (!isFunction(func))\n func = false;\n\n var arr = [];\n var hival = calcRdx(min, max);\n var step = (max * hival - min * hival) / ((length - 1) * hival);\n var current = min;\n var cnt;\n\n // Current is assigned using a technique to compensate for IEEE error.\n // TODO: Needs better implementation.\n for (cnt = 0;\n current <= max && cnt < length;\n cnt++, current = (min * hival + step * hival * cnt) / hival) {\n arr.push((func ? func(current, cnt) : current));\n }\n\n return arr;\n};\n\n\n// arange(5) -> [0,1,2,3,4]\n// arange(1,5) -> [1,2,3,4]\n// arange(5,1,-1) -> [5,4,3,2]\njStat.arange = function arange(start, end, step) {\n var rl = [];\n var i;\n step = step || 1;\n if (end === undefined) {\n end = start;\n start = 0;\n }\n if (start === end || step === 0) {\n return [];\n }\n if (start < end && step < 0) {\n return [];\n }\n if (start > end && step > 0) {\n return [];\n }\n if (step > 0) {\n for (i = start; i < end; i += step) {\n rl.push(i);\n }\n } else {\n for (i = start; i > end; i += step) {\n rl.push(i);\n }\n }\n return rl;\n};\n\n\n// A=[[1,2,3],[4,5,6],[7,8,9]]\n// slice(A,{row:{end:2},col:{start:1}}) -> [[2,3],[5,6]]\n// slice(A,1,{start:1}) -> [5,6]\n// as numpy code A[:2,1:]\njStat.slice = (function(){\n function _slice(list, start, end, step) {\n // note it's not equal to range.map mode it's a bug\n var i;\n var rl = [];\n var length = list.length;\n if (start === undefined && end === undefined && step === undefined) {\n return jStat.copy(list);\n }\n\n start = start || 0;\n end = end || list.length;\n start = start >= 0 ? start : length + start;\n end = end >= 0 ? end : length + end;\n step = step || 1;\n if (start === end || step === 0) {\n return [];\n }\n if (start < end && step < 0) {\n return [];\n }\n if (start > end && step > 0) {\n return [];\n }\n if (step > 0) {\n for (i = start; i < end; i += step) {\n rl.push(list[i]);\n }\n } else {\n for (i = start; i > end;i += step) {\n rl.push(list[i]);\n }\n }\n return rl;\n }\n\n function slice(list, rcSlice) {\n var colSlice, rowSlice;\n rcSlice = rcSlice || {};\n if (isNumber(rcSlice.row)) {\n if (isNumber(rcSlice.col))\n return list[rcSlice.row][rcSlice.col];\n var row = jStat.rowa(list, rcSlice.row);\n colSlice = rcSlice.col || {};\n return _slice(row, colSlice.start, colSlice.end, colSlice.step);\n }\n\n if (isNumber(rcSlice.col)) {\n var col = jStat.cola(list, rcSlice.col);\n rowSlice = rcSlice.row || {};\n return _slice(col, rowSlice.start, rowSlice.end, rowSlice.step);\n }\n\n rowSlice = rcSlice.row || {};\n colSlice = rcSlice.col || {};\n var rows = _slice(list, rowSlice.start, rowSlice.end, rowSlice.step);\n return rows.map(function(row) {\n return _slice(row, colSlice.start, colSlice.end, colSlice.step);\n });\n }\n\n return slice;\n}());\n\n\n// A=[[1,2,3],[4,5,6],[7,8,9]]\n// sliceAssign(A,{row:{start:1},col:{start:1}},[[0,0],[0,0]])\n// A=[[1,2,3],[4,0,0],[7,0,0]]\njStat.sliceAssign = function sliceAssign(A, rcSlice, B) {\n var nl, ml;\n if (isNumber(rcSlice.row)) {\n if (isNumber(rcSlice.col))\n return A[rcSlice.row][rcSlice.col] = B;\n rcSlice.col = rcSlice.col || {};\n rcSlice.col.start = rcSlice.col.start || 0;\n rcSlice.col.end = rcSlice.col.end || A[0].length;\n rcSlice.col.step = rcSlice.col.step || 1;\n nl = jStat.arange(rcSlice.col.start,\n Math.min(A.length, rcSlice.col.end),\n rcSlice.col.step);\n var m = rcSlice.row;\n nl.forEach(function(n, i) {\n A[m][n] = B[i];\n });\n return A;\n }\n\n if (isNumber(rcSlice.col)) {\n rcSlice.row = rcSlice.row || {};\n rcSlice.row.start = rcSlice.row.start || 0;\n rcSlice.row.end = rcSlice.row.end || A.length;\n rcSlice.row.step = rcSlice.row.step || 1;\n ml = jStat.arange(rcSlice.row.start,\n Math.min(A[0].length, rcSlice.row.end),\n rcSlice.row.step);\n var n = rcSlice.col;\n ml.forEach(function(m, j) {\n A[m][n] = B[j];\n });\n return A;\n }\n\n if (B[0].length === undefined) {\n B = [B];\n }\n rcSlice.row.start = rcSlice.row.start || 0;\n rcSlice.row.end = rcSlice.row.end || A.length;\n rcSlice.row.step = rcSlice.row.step || 1;\n rcSlice.col.start = rcSlice.col.start || 0;\n rcSlice.col.end = rcSlice.col.end || A[0].length;\n rcSlice.col.step = rcSlice.col.step || 1;\n ml = jStat.arange(rcSlice.row.start,\n Math.min(A.length, rcSlice.row.end),\n rcSlice.row.step);\n nl = jStat.arange(rcSlice.col.start,\n Math.min(A[0].length, rcSlice.col.end),\n rcSlice.col.step);\n ml.forEach(function(m, i) {\n nl.forEach(function(n, j) {\n A[m][n] = B[i][j];\n });\n });\n return A;\n};\n\n\n// [1,2,3] ->\n// [[1,0,0],[0,2,0],[0,0,3]]\njStat.diagonal = function diagonal(diagArray) {\n var mat = jStat.zeros(diagArray.length, diagArray.length);\n diagArray.forEach(function(t, i) {\n mat[i][i] = t;\n });\n return mat;\n};\n\n\n// return copy of A\njStat.copy = function copy(A) {\n return A.map(function(row) {\n if (isNumber(row))\n return row;\n return row.map(function(t) {\n return t;\n });\n });\n};\n\n\n// TODO: Go over this entire implementation. Seems a tragic waste of resources\n// doing all this work. Instead, and while ugly, use new Function() to generate\n// a custom function for each static method.\n\n// Quick reference.\nvar jProto = jStat.prototype;\n\n// Default length.\njProto.length = 0;\n\n// For internal use only.\n// TODO: Check if they're actually used, and if they are then rename them\n// to _*\njProto.push = Array.prototype.push;\njProto.sort = Array.prototype.sort;\njProto.splice = Array.prototype.splice;\njProto.slice = Array.prototype.slice;\n\n\n// Return a clean array.\njProto.toArray = function toArray() {\n return this.length > 1 ? slice.call(this) : slice.call(this)[0];\n};\n\n\n// Map a function to a matrix or vector.\njProto.map = function map(func, toAlter) {\n return jStat(jStat.map(this, func, toAlter));\n};\n\n\n// Cumulatively combine the elements of a matrix or vector using a function.\njProto.cumreduce = function cumreduce(func, toAlter) {\n return jStat(jStat.cumreduce(this, func, toAlter));\n};\n\n\n// Destructively alter an array.\njProto.alter = function alter(func) {\n jStat.alter(this, func);\n return this;\n};\n\n\n// Extend prototype with methods that have no argument.\n(function(funcs) {\n for (var i = 0; i < funcs.length; i++) (function(passfunc) {\n jProto[passfunc] = function(func) {\n var self = this,\n results;\n // Check for callback.\n if (func) {\n setTimeout(function() {\n func.call(self, jProto[passfunc].call(self));\n });\n return this;\n }\n results = jStat[passfunc](this);\n return isArray(results) ? jStat(results) : results;\n };\n })(funcs[i]);\n})('transpose clear symmetric rows cols dimensions diag antidiag'.split(' '));\n\n\n// Extend prototype with methods that have one argument.\n(function(funcs) {\n for (var i = 0; i < funcs.length; i++) (function(passfunc) {\n jProto[passfunc] = function(index, func) {\n var self = this;\n // check for callback\n if (func) {\n setTimeout(function() {\n func.call(self, jProto[passfunc].call(self, index));\n });\n return this;\n }\n return jStat(jStat[passfunc](this, index));\n };\n })(funcs[i]);\n})('row col'.split(' '));\n\n\n// Extend prototype with simple shortcut methods.\n(function(funcs) {\n for (var i = 0; i < funcs.length; i++) (function(passfunc) {\n jProto[passfunc] = function() {\n return jStat(jStat[passfunc].apply(null, arguments));\n };\n })(funcs[i]);\n})('create zeros ones rand identity'.split(' '));\n\n\n// Exposing jStat.\nreturn jStat;\n\n}(Math));\n(function(jStat, Math) {\n\nvar isFunction = jStat.utils.isFunction;\n\n// Ascending functions for sort\nfunction ascNum(a, b) { return a - b; }\n\nfunction clip(arg, min, max) {\n return Math.max(min, Math.min(arg, max));\n}\n\n\n// sum of an array\njStat.sum = function sum(arr) {\n var sum = 0;\n var i = arr.length;\n while (--i >= 0)\n sum += arr[i];\n return sum;\n};\n\n\n// sum squared\njStat.sumsqrd = function sumsqrd(arr) {\n var sum = 0;\n var i = arr.length;\n while (--i >= 0)\n sum += arr[i] * arr[i];\n return sum;\n};\n\n\n// sum of squared errors of prediction (SSE)\njStat.sumsqerr = function sumsqerr(arr) {\n var mean = jStat.mean(arr);\n var sum = 0;\n var i = arr.length;\n var tmp;\n while (--i >= 0) {\n tmp = arr[i] - mean;\n sum += tmp * tmp;\n }\n return sum;\n};\n\n// sum of an array in each row\njStat.sumrow = function sumrow(arr) {\n var sum = 0;\n var i = arr.length;\n while (--i >= 0)\n sum += arr[i];\n return sum;\n};\n\n// product of an array\njStat.product = function product(arr) {\n var prod = 1;\n var i = arr.length;\n while (--i >= 0)\n prod *= arr[i];\n return prod;\n};\n\n\n// minimum value of an array\njStat.min = function min(arr) {\n var low = arr[0];\n var i = 0;\n while (++i < arr.length)\n if (arr[i] < low)\n low = arr[i];\n return low;\n};\n\n\n// maximum value of an array\njStat.max = function max(arr) {\n var high = arr[0];\n var i = 0;\n while (++i < arr.length)\n if (arr[i] > high)\n high = arr[i];\n return high;\n};\n\n\n// unique values of an array\njStat.unique = function unique(arr) {\n var hash = {}, _arr = [];\n for(var i = 0; i < arr.length; i++) {\n if (!hash[arr[i]]) {\n hash[arr[i]] = true;\n _arr.push(arr[i]);\n }\n }\n return _arr;\n};\n\n\n// mean value of an array\njStat.mean = function mean(arr) {\n return jStat.sum(arr) / arr.length;\n};\n\n\n// mean squared error (MSE)\njStat.meansqerr = function meansqerr(arr) {\n return jStat.sumsqerr(arr) / arr.length;\n};\n\n\n// geometric mean of an array\njStat.geomean = function geomean(arr) {\n var logs = arr.map(Math.log)\n var meanOfLogs = jStat.mean(logs)\n return Math.exp(meanOfLogs)\n};\n\n\n// median of an array\njStat.median = function median(arr) {\n var arrlen = arr.length;\n var _arr = arr.slice().sort(ascNum);\n // check if array is even or odd, then return the appropriate\n return !(arrlen & 1)\n ? (_arr[(arrlen / 2) - 1 ] + _arr[(arrlen / 2)]) / 2\n : _arr[(arrlen / 2) | 0 ];\n};\n\n\n// cumulative sum of an array\njStat.cumsum = function cumsum(arr) {\n return jStat.cumreduce(arr, function (a, b) { return a + b; });\n};\n\n\n// cumulative product of an array\njStat.cumprod = function cumprod(arr) {\n return jStat.cumreduce(arr, function (a, b) { return a * b; });\n};\n\n\n// successive differences of a sequence\njStat.diff = function diff(arr) {\n var diffs = [];\n var arrLen = arr.length;\n var i;\n for (i = 1; i < arrLen; i++)\n diffs.push(arr[i] - arr[i - 1]);\n return diffs;\n};\n\n\n// ranks of an array\njStat.rank = function (arr) {\n var i;\n var distinctNumbers = [];\n var numberCounts = {};\n for (i = 0; i < arr.length; i++) {\n var number = arr[i];\n if (numberCounts[number]) {\n numberCounts[number]++;\n } else {\n numberCounts[number] = 1;\n distinctNumbers.push(number);\n }\n }\n\n var sortedDistinctNumbers = distinctNumbers.sort(ascNum);\n var numberRanks = {};\n var currentRank = 1;\n for (i = 0; i < sortedDistinctNumbers.length; i++) {\n var number = sortedDistinctNumbers[i];\n var count = numberCounts[number];\n var first = currentRank;\n var last = currentRank + count - 1;\n var rank = (first + last) / 2;\n numberRanks[number] = rank;\n currentRank += count;\n }\n\n return arr.map(function (number) {\n return numberRanks[number];\n });\n};\n\n\n// mode of an array\n// if there are multiple modes of an array, return all of them\n// is this the appropriate way of handling it?\njStat.mode = function mode(arr) {\n var arrLen = arr.length;\n var _arr = arr.slice().sort(ascNum);\n var count = 1;\n var maxCount = 0;\n var numMaxCount = 0;\n var mode_arr = [];\n var i;\n\n for (i = 0; i < arrLen; i++) {\n if (_arr[i] === _arr[i + 1]) {\n count++;\n } else {\n if (count > maxCount) {\n mode_arr = [_arr[i]];\n maxCount = count;\n numMaxCount = 0;\n }\n // are there multiple max counts\n else if (count === maxCount) {\n mode_arr.push(_arr[i]);\n numMaxCount++;\n }\n // resetting count for new value in array\n count = 1;\n }\n }\n\n return numMaxCount === 0 ? mode_arr[0] : mode_arr;\n};\n\n\n// range of an array\njStat.range = function range(arr) {\n return jStat.max(arr) - jStat.min(arr);\n};\n\n// variance of an array\n// flag = true indicates sample instead of population\njStat.variance = function variance(arr, flag) {\n return jStat.sumsqerr(arr) / (arr.length - (flag ? 1 : 0));\n};\n\n// pooled variance of an array of arrays\njStat.pooledvariance = function pooledvariance(arr) {\n var sumsqerr = arr.reduce(function (a, samples) {return a + jStat.sumsqerr(samples);}, 0);\n var count = arr.reduce(function (a, samples) {return a + samples.length;}, 0);\n return sumsqerr / (count - arr.length);\n};\n\n// deviation of an array\njStat.deviation = function (arr) {\n var mean = jStat.mean(arr);\n var arrlen = arr.length;\n var dev = new Array(arrlen);\n for (var i = 0; i < arrlen; i++) {\n dev[i] = arr[i] - mean;\n }\n return dev;\n};\n\n// standard deviation of an array\n// flag = true indicates sample instead of population\njStat.stdev = function stdev(arr, flag) {\n return Math.sqrt(jStat.variance(arr, flag));\n};\n\n// pooled standard deviation of an array of arrays\njStat.pooledstdev = function pooledstdev(arr) {\n return Math.sqrt(jStat.pooledvariance(arr));\n};\n\n// mean deviation (mean absolute deviation) of an array\njStat.meandev = function meandev(arr) {\n var mean = jStat.mean(arr);\n var a = [];\n for (var i = arr.length - 1; i >= 0; i--) {\n a.push(Math.abs(arr[i] - mean));\n }\n return jStat.mean(a);\n};\n\n\n// median deviation (median absolute deviation) of an array\njStat.meddev = function meddev(arr) {\n var median = jStat.median(arr);\n var a = [];\n for (var i = arr.length - 1; i >= 0; i--) {\n a.push(Math.abs(arr[i] - median));\n }\n return jStat.median(a);\n};\n\n\n// coefficient of variation\njStat.coeffvar = function coeffvar(arr) {\n return jStat.stdev(arr) / jStat.mean(arr);\n};\n\n\n// quartiles of an array\njStat.quartiles = function quartiles(arr) {\n var arrlen = arr.length;\n var _arr = arr.slice().sort(ascNum);\n return [\n _arr[ Math.round((arrlen) / 4) - 1 ],\n _arr[ Math.round((arrlen) / 2) - 1 ],\n _arr[ Math.round((arrlen) * 3 / 4) - 1 ]\n ];\n};\n\n\n// Arbitary quantiles of an array. Direct port of the scipy.stats\n// implementation by Pierre GF Gerard-Marchant.\njStat.quantiles = function quantiles(arr, quantilesArray, alphap, betap) {\n var sortedArray = arr.slice().sort(ascNum);\n var quantileVals = [quantilesArray.length];\n var n = arr.length;\n var i, p, m, aleph, k, gamma;\n\n if (typeof alphap === 'undefined')\n alphap = 3 / 8;\n if (typeof betap === 'undefined')\n betap = 3 / 8;\n\n for (i = 0; i < quantilesArray.length; i++) {\n p = quantilesArray[i];\n m = alphap + p * (1 - alphap - betap);\n aleph = n * p + m;\n k = Math.floor(clip(aleph, 1, n - 1));\n gamma = clip(aleph - k, 0, 1);\n quantileVals[i] = (1 - gamma) * sortedArray[k - 1] + gamma * sortedArray[k];\n }\n\n return quantileVals;\n};\n\n// Return the k-th percentile of values in a range, where k is in the range 0..1, inclusive.\n// Passing true for the exclusive parameter excludes both endpoints of the range.\njStat.percentile = function percentile(arr, k, exclusive) {\n var _arr = arr.slice().sort(ascNum);\n var realIndex = k * (_arr.length + (exclusive ? 1 : -1)) + (exclusive ? 0 : 1);\n var index = parseInt(realIndex);\n var frac = realIndex - index;\n if (index + 1 < _arr.length) {\n return _arr[index - 1] + frac * (_arr[index] - _arr[index - 1]);\n } else {\n return _arr[index - 1];\n }\n}\n\n// The percentile rank of score in a given array. Returns the percentage\n// of all values in the input array that are less than (kind='strict') or\n// less or equal than (kind='weak') score. Default is weak.\njStat.percentileOfScore = function percentileOfScore(arr, score, kind) {\n var counter = 0;\n var len = arr.length;\n var strict = false;\n var value, i;\n\n if (kind === 'strict')\n strict = true;\n\n for (i = 0; i < len; i++) {\n value = arr[i];\n if ((strict && value < score) ||\n (!strict && value <= score)) {\n counter++;\n }\n }\n\n return counter / len;\n};\n\n\n// Histogram (bin count) data\njStat.histogram = function histogram(arr, binCnt) {\n binCnt = binCnt || 4;\n var first = jStat.min(arr);\n var binWidth = (jStat.max(arr) - first) / binCnt;\n var len = arr.length;\n var bins = [];\n var i;\n\n for (i = 0; i < binCnt; i++)\n bins[i] = 0;\n for (i = 0; i < len; i++)\n bins[Math.min(Math.floor(((arr[i] - first) / binWidth)), binCnt - 1)] += 1;\n\n return bins;\n};\n\n\n// covariance of two arrays\njStat.covariance = function covariance(arr1, arr2) {\n var u = jStat.mean(arr1);\n var v = jStat.mean(arr2);\n var arr1Len = arr1.length;\n var sq_dev = new Array(arr1Len);\n var i;\n\n for (i = 0; i < arr1Len; i++)\n sq_dev[i] = (arr1[i] - u) * (arr2[i] - v);\n\n return jStat.sum(sq_dev) / (arr1Len - 1);\n};\n\n\n// (pearson's) population correlation coefficient, rho\njStat.corrcoeff = function corrcoeff(arr1, arr2) {\n return jStat.covariance(arr1, arr2) /\n jStat.stdev(arr1, 1) /\n jStat.stdev(arr2, 1);\n};\n\n // (spearman's) rank correlation coefficient, sp\njStat.spearmancoeff = function (arr1, arr2) {\n arr1 = jStat.rank(arr1);\n arr2 = jStat.rank(arr2);\n //return pearson's correlation of the ranks:\n return jStat.corrcoeff(arr1, arr2);\n}\n\n\n// statistical standardized moments (general form of skew/kurt)\njStat.stanMoment = function stanMoment(arr, n) {\n var mu = jStat.mean(arr);\n var sigma = jStat.stdev(arr);\n var len = arr.length;\n var skewSum = 0;\n\n for (var i = 0; i < len; i++)\n skewSum += Math.pow((arr[i] - mu) / sigma, n);\n\n return skewSum / arr.length;\n};\n\n// (pearson's) moment coefficient of skewness\njStat.skewness = function skewness(arr) {\n return jStat.stanMoment(arr, 3);\n};\n\n// (pearson's) (excess) kurtosis\njStat.kurtosis = function kurtosis(arr) {\n return jStat.stanMoment(arr, 4) - 3;\n};\n\n\nvar jProto = jStat.prototype;\n\n\n// Extend jProto with method for calculating cumulative sums and products.\n// This differs from the similar extension below as cumsum and cumprod should\n// not be run again in the case fullbool === true.\n// If a matrix is passed, automatically assume operation should be done on the\n// columns.\n(function(funcs) {\n for (var i = 0; i < funcs.length; i++) (function(passfunc) {\n // If a matrix is passed, automatically assume operation should be done on\n // the columns.\n jProto[passfunc] = function(fullbool, func) {\n var arr = [];\n var i = 0;\n var tmpthis = this;\n // Assignment reassignation depending on how parameters were passed in.\n if (isFunction(fullbool)) {\n func = fullbool;\n fullbool = false;\n }\n // Check if a callback was passed with the function.\n if (func) {\n setTimeout(function() {\n func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool));\n });\n return this;\n }\n // Check if matrix and run calculations.\n if (this.length > 1) {\n tmpthis = fullbool === true ? this : this.transpose();\n for (; i < tmpthis.length; i++)\n arr[i] = jStat[passfunc](tmpthis[i]);\n return arr;\n }\n // Pass fullbool if only vector, not a matrix. for variance and stdev.\n return jStat[passfunc](this[0], fullbool);\n };\n })(funcs[i]);\n})(('cumsum cumprod').split(' '));\n\n\n// Extend jProto with methods which don't require arguments and work on columns.\n(function(funcs) {\n for (var i = 0; i < funcs.length; i++) (function(passfunc) {\n // If a matrix is passed, automatically assume operation should be done on\n // the columns.\n jProto[passfunc] = function(fullbool, func) {\n var arr = [];\n var i = 0;\n var tmpthis = this;\n // Assignment reassignation depending on how parameters were passed in.\n if (isFunction(fullbool)) {\n func = fullbool;\n fullbool = false;\n }\n // Check if a callback was passed with the function.\n if (func) {\n setTimeout(function() {\n func.call(tmpthis, jProto[passfunc].call(tmpthis, fullbool));\n });\n return this;\n }\n // Check if matrix and run calculations.\n if (this.length > 1) {\n if (passfunc !== 'sumrow')\n tmpthis = fullbool === true ? this : this.transpose();\n for (; i < tmpthis.length; i++)\n arr[i] = jStat[passfunc](tmpthis[i]);\n return fullbool === true\n ? jStat[passfunc](jStat.utils.toVector(arr))\n : arr;\n }\n // Pass fullbool if only vector, not a matrix. for variance and stdev.\n return jStat[passfunc](this[0], fullbool);\n };\n })(funcs[i]);\n})(('sum sumsqrd sumsqerr sumrow product min max unique mean meansqerr ' +\n 'geomean median diff rank mode range variance deviation stdev meandev ' +\n 'meddev coeffvar quartiles histogram skewness kurtosis').split(' '));\n\n\n// Extend jProto with functions that take arguments. Operations on matrices are\n// done on columns.\n(function(funcs) {\n for (var i = 0; i < funcs.length; i++) (function(passfunc) {\n jProto[passfunc] = function() {\n var arr = [];\n var i = 0;\n var tmpthis = this;\n var args = Array.prototype.slice.call(arguments);\n var callbackFunction;\n\n // If the last argument is a function, we assume it's a callback; we\n // strip the callback out and call the function again.\n if (isFunction(args[args.length - 1])) {\n callbackFunction = args[args.length - 1];\n var argsToPass = args.slice(0, args.length - 1);\n\n setTimeout(function() {\n callbackFunction.call(tmpthis,\n jProto[passfunc].apply(tmpthis, argsToPass));\n });\n return this;\n\n // Otherwise we curry the function args and call normally.\n } else {\n callbackFunction = undefined;\n var curriedFunction = function curriedFunction(vector) {\n return jStat[passfunc].apply(tmpthis, [vector].concat(args));\n }\n }\n\n // If this is a matrix, run column-by-column.\n if (this.length > 1) {\n tmpthis = tmpthis.transpose();\n for (; i < tmpthis.length; i++)\n arr[i] = curriedFunction(tmpthis[i]);\n return arr;\n }\n\n // Otherwise run on the vector.\n return curriedFunction(this[0]);\n };\n })(funcs[i]);\n})('quantiles percentileOfScore'.split(' '));\n\n}(jStat, Math));\n// Special functions //\n(function(jStat, Math) {\n\n// Log-gamma function\njStat.gammaln = function gammaln(x) {\n var j = 0;\n var cof = [\n 76.18009172947146, -86.50532032941677, 24.01409824083091,\n -1.231739572450155, 0.1208650973866179e-2, -0.5395239384953e-5\n ];\n var ser = 1.000000000190015;\n var xx, y, tmp;\n tmp = (y = xx = x) + 5.5;\n tmp -= (xx + 0.5) * Math.log(tmp);\n for (; j < 6; j++)\n ser += cof[j] / ++y;\n return Math.log(2.5066282746310005 * ser / xx) - tmp;\n};\n\n/*\n * log-gamma function to support poisson distribution sampling. The\n * algorithm comes from SPECFUN by Shanjie Zhang and Jianming Jin and their\n * book \"Computation of Special Functions\", 1996, John Wiley & Sons, Inc.\n */\njStat.loggam = function loggam(x) {\n var x0, x2, xp, gl, gl0;\n var k, n;\n\n var a = [8.333333333333333e-02, -2.777777777777778e-03,\n 7.936507936507937e-04, -5.952380952380952e-04,\n 8.417508417508418e-04, -1.917526917526918e-03,\n 6.410256410256410e-03, -2.955065359477124e-02,\n 1.796443723688307e-01, -1.39243221690590e+00];\n x0 = x;\n n = 0;\n if ((x == 1.0) || (x == 2.0)) {\n return 0.0;\n }\n if (x <= 7.0) {\n n = Math.floor(7 - x);\n x0 = x + n;\n }\n x2 = 1.0 / (x0 * x0);\n xp = 2 * Math.PI;\n gl0 = a[9];\n for (k = 8; k >= 0; k--) {\n gl0 *= x2;\n gl0 += a[k];\n }\n gl = gl0 / x0 + 0.5 * Math.log(xp) + (x0 - 0.5) * Math.log(x0) - x0;\n if (x <= 7.0) {\n for (k = 1; k <= n; k++) {\n gl -= Math.log(x0 - 1.0);\n x0 -= 1.0;\n }\n }\n return gl;\n}\n\n// gamma of x\njStat.gammafn = function gammafn(x) {\n var p = [-1.716185138865495, 24.76565080557592, -379.80425647094563,\n 629.3311553128184, 866.9662027904133, -31451.272968848367,\n -36144.413418691176, 66456.14382024054\n ];\n var q = [-30.8402300119739, 315.35062697960416, -1015.1563674902192,\n -3107.771671572311, 22538.118420980151, 4755.8462775278811,\n -134659.9598649693, -115132.2596755535];\n var fact = false;\n var n = 0;\n var xden = 0;\n var xnum = 0;\n var y = x;\n var i, z, yi, res;\n if (x > 171.6243769536076) {\n return Infinity;\n }\n if (y <= 0) {\n res = y % 1 + 3.6e-16;\n if (res) {\n fact = (!(y & 1) ? 1 : -1) * Math.PI / Math.sin(Math.PI * res);\n y = 1 - y;\n } else {\n return Infinity;\n }\n }\n yi = y;\n if (y < 1) {\n z = y++;\n } else {\n z = (y -= n = (y | 0) - 1) - 1;\n }\n for (i = 0; i < 8; ++i) {\n xnum = (xnum + p[i]) * z;\n xden = xden * z + q[i];\n }\n res = xnum / xden + 1;\n if (yi < y) {\n res /= yi;\n } else if (yi > y) {\n for (i = 0; i < n; ++i) {\n res *= y;\n y++;\n }\n }\n if (fact) {\n res = fact / res;\n }\n return res;\n};\n\n\n// lower incomplete gamma function, which is usually typeset with a\n// lower-case greek gamma as the function symbol\njStat.gammap = function gammap(a, x) {\n return jStat.lowRegGamma(a, x) * jStat.gammafn(a);\n};\n\n\n// The lower regularized incomplete gamma function, usually written P(a,x)\njStat.lowRegGamma = function lowRegGamma(a, x) {\n var aln = jStat.gammaln(a);\n var ap = a;\n var sum = 1 / a;\n var del = sum;\n var b = x + 1 - a;\n var c = 1 / 1.0e-30;\n var d = 1 / b;\n var h = d;\n var i = 1;\n // calculate maximum number of itterations required for a\n var ITMAX = -~(Math.log((a >= 1) ? a : 1 / a) * 8.5 + a * 0.4 + 17);\n var an;\n\n if (x < 0 || a <= 0) {\n return NaN;\n } else if (x < a + 1) {\n for (; i <= ITMAX; i++) {\n sum += del *= x / ++ap;\n }\n return (sum * Math.exp(-x + a * Math.log(x) - (aln)));\n }\n\n for (; i <= ITMAX; i++) {\n an = -i * (i - a);\n b += 2;\n d = an * d + b;\n c = b + an / c;\n d = 1 / d;\n h *= d * c;\n }\n\n return (1 - h * Math.exp(-x + a * Math.log(x) - (aln)));\n};\n\n// natural log factorial of n\njStat.factorialln = function factorialln(n) {\n return n < 0 ? NaN : jStat.gammaln(n + 1);\n};\n\n// factorial of n\njStat.factorial = function factorial(n) {\n return n < 0 ? NaN : jStat.gammafn(n + 1);\n};\n\n// combinations of n, m\njStat.combination = function combination(n, m) {\n // make sure n or m don't exceed the upper limit of usable values\n return (n > 170 || m > 170)\n ? Math.exp(jStat.combinationln(n, m))\n : (jStat.factorial(n) / jStat.factorial(m)) / jStat.factorial(n - m);\n};\n\n\njStat.combinationln = function combinationln(n, m){\n return jStat.factorialln(n) - jStat.factorialln(m) - jStat.factorialln(n - m);\n};\n\n\n// permutations of n, m\njStat.permutation = function permutation(n, m) {\n return jStat.factorial(n) / jStat.factorial(n - m);\n};\n\n\n// beta function\njStat.betafn = function betafn(x, y) {\n // ensure arguments are positive\n if (x <= 0 || y <= 0)\n return undefined;\n // make sure x + y doesn't exceed the upper limit of usable values\n return (x + y > 170)\n ? Math.exp(jStat.betaln(x, y))\n : jStat.gammafn(x) * jStat.gammafn(y) / jStat.gammafn(x + y);\n};\n\n\n// natural logarithm of beta function\njStat.betaln = function betaln(x, y) {\n return jStat.gammaln(x) + jStat.gammaln(y) - jStat.gammaln(x + y);\n};\n\n\n// Evaluates the continued fraction for incomplete beta function by modified\n// Lentz's method.\njStat.betacf = function betacf(x, a, b) {\n var fpmin = 1e-30;\n var m = 1;\n var qab = a + b;\n var qap = a + 1;\n var qam = a - 1;\n var c = 1;\n var d = 1 - qab * x / qap;\n var m2, aa, del, h;\n\n // These q's will be used in factors that occur in the coefficients\n if (Math.abs(d) < fpmin)\n d = fpmin;\n d = 1 / d;\n h = d;\n\n for (; m <= 100; m++) {\n m2 = 2 * m;\n aa = m * (b - m) * x / ((qam + m2) * (a + m2));\n // One step (the even one) of the recurrence\n d = 1 + aa * d;\n if (Math.abs(d) < fpmin)\n d = fpmin;\n c = 1 + aa / c;\n if (Math.abs(c) < fpmin)\n c = fpmin;\n d = 1 / d;\n h *= d * c;\n aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2));\n // Next step of the recurrence (the odd one)\n d = 1 + aa * d;\n if (Math.abs(d) < fpmin)\n d = fpmin;\n c = 1 + aa / c;\n if (Math.abs(c) < fpmin)\n c = fpmin;\n d = 1 / d;\n del = d * c;\n h *= del;\n if (Math.abs(del - 1.0) < 3e-7)\n break;\n }\n\n return h;\n};\n\n\n// Returns the inverse of the lower regularized inomplete gamma function\njStat.gammapinv = function gammapinv(p, a) {\n var j = 0;\n var a1 = a - 1;\n var EPS = 1e-8;\n var gln = jStat.gammaln(a);\n var x, err, t, u, pp, lna1, afac;\n\n if (p >= 1)\n return Math.max(100, a + 100 * Math.sqrt(a));\n if (p <= 0)\n return 0;\n if (a > 1) {\n lna1 = Math.log(a1);\n afac = Math.exp(a1 * (lna1 - 1) - gln);\n pp = (p < 0.5) ? p : 1 - p;\n t = Math.sqrt(-2 * Math.log(pp));\n x = (2.30753 + t * 0.27061) / (1 + t * (0.99229 + t * 0.04481)) - t;\n if (p < 0.5)\n x = -x;\n x = Math.max(1e-3,\n a * Math.pow(1 - 1 / (9 * a) - x / (3 * Math.sqrt(a)), 3));\n } else {\n t = 1 - a * (0.253 + a * 0.12);\n if (p < t)\n x = Math.pow(p / t, 1 / a);\n else\n x = 1 - Math.log(1 - (p - t) / (1 - t));\n }\n\n for(; j < 12; j++) {\n if (x <= 0)\n return 0;\n err = jStat.lowRegGamma(a, x) - p;\n if (a > 1)\n t = afac * Math.exp(-(x - a1) + a1 * (Math.log(x) - lna1));\n else\n t = Math.exp(-x + a1 * Math.log(x) - gln);\n u = err / t;\n x -= (t = u / (1 - 0.5 * Math.min(1, u * ((a - 1) / x - 1))));\n if (x <= 0)\n x = 0.5 * (x + t);\n if (Math.abs(t) < EPS * x)\n break;\n }\n\n return x;\n};\n\n\n// Returns the error function erf(x)\njStat.erf = function erf(x) {\n var cof = [-1.3026537197817094, 6.4196979235649026e-1, 1.9476473204185836e-2,\n -9.561514786808631e-3, -9.46595344482036e-4, 3.66839497852761e-4,\n 4.2523324806907e-5, -2.0278578112534e-5, -1.624290004647e-6,\n 1.303655835580e-6, 1.5626441722e-8, -8.5238095915e-8,\n 6.529054439e-9, 5.059343495e-9, -9.91364156e-10,\n -2.27365122e-10, 9.6467911e-11, 2.394038e-12,\n -6.886027e-12, 8.94487e-13, 3.13092e-13,\n -1.12708e-13, 3.81e-16, 7.106e-15,\n -1.523e-15, -9.4e-17, 1.21e-16,\n -2.8e-17];\n var j = cof.length - 1;\n var isneg = false;\n var d = 0;\n var dd = 0;\n var t, ty, tmp, res;\n\n if (x < 0) {\n x = -x;\n isneg = true;\n }\n\n t = 2 / (2 + x);\n ty = 4 * t - 2;\n\n for(; j > 0; j--) {\n tmp = d;\n d = ty * d - dd + cof[j];\n dd = tmp;\n }\n\n res = t * Math.exp(-x * x + 0.5 * (cof[0] + ty * d) - dd);\n return isneg ? res - 1 : 1 - res;\n};\n\n\n// Returns the complmentary error function erfc(x)\njStat.erfc = function erfc(x) {\n return 1 - jStat.erf(x);\n};\n\n\n// Returns the inverse of the complementary error function\njStat.erfcinv = function erfcinv(p) {\n var j = 0;\n var x, err, t, pp;\n if (p >= 2)\n return -100;\n if (p <= 0)\n return 100;\n pp = (p < 1) ? p : 2 - p;\n t = Math.sqrt(-2 * Math.log(pp / 2));\n x = -0.70711 * ((2.30753 + t * 0.27061) /\n (1 + t * (0.99229 + t * 0.04481)) - t);\n for (; j < 2; j++) {\n err = jStat.erfc(x) - pp;\n x += err / (1.12837916709551257 * Math.exp(-x * x) - x * err);\n }\n return (p < 1) ? x : -x;\n};\n\n\n// Returns the inverse of the incomplete beta function\njStat.ibetainv = function ibetainv(p, a, b) {\n var EPS = 1e-8;\n var a1 = a - 1;\n var b1 = b - 1;\n var j = 0;\n var lna, lnb, pp, t, u, err, x, al, h, w, afac;\n if (p <= 0)\n return 0;\n if (p >= 1)\n return 1;\n if (a >= 1 && b >= 1) {\n pp = (p < 0.5) ? p : 1 - p;\n t = Math.sqrt(-2 * Math.log(pp));\n x = (2.30753 + t * 0.27061) / (1 + t* (0.99229 + t * 0.04481)) - t;\n if (p < 0.5)\n x = -x;\n al = (x * x - 3) / 6;\n h = 2 / (1 / (2 * a - 1) + 1 / (2 * b - 1));\n w = (x * Math.sqrt(al + h) / h) - (1 / (2 * b - 1) - 1 / (2 * a - 1)) *\n (al + 5 / 6 - 2 / (3 * h));\n x = a / (a + b * Math.exp(2 * w));\n } else {\n lna = Math.log(a / (a + b));\n lnb = Math.log(b / (a + b));\n t = Math.exp(a * lna) / a;\n u = Math.exp(b * lnb) / b;\n w = t + u;\n if (p < t / w)\n x = Math.pow(a * w * p, 1 / a);\n else\n x = 1 - Math.pow(b * w * (1 - p), 1 / b);\n }\n afac = -jStat.gammaln(a) - jStat.gammaln(b) + jStat.gammaln(a + b);\n for(; j < 10; j++) {\n if (x === 0 || x === 1)\n return x;\n err = jStat.ibeta(x, a, b) - p;\n t = Math.exp(a1 * Math.log(x) + b1 * Math.log(1 - x) + afac);\n u = err / t;\n x -= (t = u / (1 - 0.5 * Math.min(1, u * (a1 / x - b1 / (1 - x)))));\n if (x <= 0)\n x = 0.5 * (x + t);\n if (x >= 1)\n x = 0.5 * (x + t + 1);\n if (Math.abs(t) < EPS * x && j > 0)\n break;\n }\n return x;\n};\n\n\n// Returns the incomplete beta function I_x(a,b)\njStat.ibeta = function ibeta(x, a, b) {\n // Factors in front of the continued fraction.\n var bt = (x === 0 || x === 1) ? 0 :\n Math.exp(jStat.gammaln(a + b) - jStat.gammaln(a) -\n jStat.gammaln(b) + a * Math.log(x) + b *\n Math.log(1 - x));\n if (x < 0 || x > 1)\n return false;\n if (x < (a + 1) / (a + b + 2))\n // Use continued fraction directly.\n return bt * jStat.betacf(x, a, b) / a;\n // else use continued fraction after making the symmetry transformation.\n return 1 - bt * jStat.betacf(1 - x, b, a) / b;\n};\n\n\n// Returns a normal deviate (mu=0, sigma=1).\n// If n and m are specified it returns a object of normal deviates.\njStat.randn = function randn(n, m) {\n var u, v, x, y, q;\n if (!m)\n m = n;\n if (n)\n return jStat.create(n, m, function() { return jStat.randn(); });\n do {\n u = jStat._random_fn();\n v = 1.7156 * (jStat._random_fn() - 0.5);\n x = u - 0.449871;\n y = Math.abs(v) + 0.386595;\n q = x * x + y * (0.19600 * y - 0.25472 * x);\n } while (q > 0.27597 && (q > 0.27846 || v * v > -4 * Math.log(u) * u * u));\n return v / u;\n};\n\n\n// Returns a gamma deviate by the method of Marsaglia and Tsang.\njStat.randg = function randg(shape, n, m) {\n var oalph = shape;\n var a1, a2, u, v, x, mat;\n if (!m)\n m = n;\n if (!shape)\n shape = 1;\n if (n) {\n mat = jStat.zeros(n,m);\n mat.alter(function() { return jStat.randg(shape); });\n return mat;\n }\n if (shape < 1)\n shape += 1;\n a1 = shape - 1 / 3;\n a2 = 1 / Math.sqrt(9 * a1);\n do {\n do {\n x = jStat.randn();\n v = 1 + a2 * x;\n } while(v <= 0);\n v = v * v * v;\n u = jStat._random_fn();\n } while(u > 1 - 0.331 * Math.pow(x, 4) &&\n Math.log(u) > 0.5 * x*x + a1 * (1 - v + Math.log(v)));\n // alpha > 1\n if (shape == oalph)\n return a1 * v;\n // alpha < 1\n do {\n u = jStat._random_fn();\n } while(u === 0);\n return Math.pow(u, 1 / oalph) * a1 * v;\n};\n\n\n// making use of static methods on the instance\n(function(funcs) {\n for (var i = 0; i < funcs.length; i++) (function(passfunc) {\n jStat.fn[passfunc] = function() {\n return jStat(\n jStat.map(this, function(value) { return jStat[passfunc](value); }));\n }\n })(funcs[i]);\n})('gammaln gammafn factorial factorialln'.split(' '));\n\n\n(function(funcs) {\n for (var i = 0; i < funcs.length; i++) (function(passfunc) {\n jStat.fn[passfunc] = function() {\n return jStat(jStat[passfunc].apply(null, arguments));\n };\n })(funcs[i]);\n})('randn'.split(' '));\n\n}(jStat, Math));\n(function(jStat, Math) {\n\n// generate all distribution instance methods\n(function(list) {\n for (var i = 0; i < list.length; i++) (function(func) {\n // distribution instance method\n jStat[func] = function f(a, b, c) {\n if (!(this instanceof f))\n return new f(a, b, c);\n this._a = a;\n this._b = b;\n this._c = c;\n return this;\n };\n // distribution method to be used on a jStat instance\n jStat.fn[func] = function(a, b, c) {\n var newthis = jStat[func](a, b, c);\n newthis.data = this;\n return newthis;\n };\n // sample instance method\n jStat[func].prototype.sample = function(arr) {\n var a = this._a;\n var b = this._b;\n var c = this._c;\n if (arr)\n return jStat.alter(arr, function() {\n return jStat[func].sample(a, b, c);\n });\n else\n return jStat[func].sample(a, b, c);\n };\n // generate the pdf, cdf and inv instance methods\n (function(vals) {\n for (var i = 0; i < vals.length; i++) (function(fnfunc) {\n jStat[func].prototype[fnfunc] = function(x) {\n var a = this._a;\n var b = this._b;\n var c = this._c;\n if (!x && x !== 0)\n x = this.data;\n if (typeof x !== 'number') {\n return jStat.fn.map.call(x, function(x) {\n return jStat[func][fnfunc](x, a, b, c);\n });\n }\n return jStat[func][fnfunc](x, a, b, c);\n };\n })(vals[i]);\n })('pdf cdf inv'.split(' '));\n // generate the mean, median, mode and variance instance methods\n (function(vals) {\n for (var i = 0; i < vals.length; i++) (function(fnfunc) {\n jStat[func].prototype[fnfunc] = function() {\n return jStat[func][fnfunc](this._a, this._b, this._c);\n };\n })(vals[i]);\n })('mean median mode variance'.split(' '));\n })(list[i]);\n})((\n 'beta centralF cauchy chisquare exponential gamma invgamma kumaraswamy ' +\n 'laplace lognormal noncentralt normal pareto studentt weibull uniform ' +\n 'binomial negbin hypgeom poisson triangular tukey arcsine'\n).split(' '));\n\n\n\n// extend beta function with static methods\njStat.extend(jStat.beta, {\n pdf: function pdf(x, alpha, beta) {\n // PDF is zero outside the support\n if (x > 1 || x < 0)\n return 0;\n // PDF is one for the uniform case\n if (alpha == 1 && beta == 1)\n return 1;\n\n if (alpha < 512 && beta < 512) {\n return (Math.pow(x, alpha - 1) * Math.pow(1 - x, beta - 1)) /\n jStat.betafn(alpha, beta);\n } else {\n return Math.exp((alpha - 1) * Math.log(x) +\n (beta - 1) * Math.log(1 - x) -\n jStat.betaln(alpha, beta));\n }\n },\n\n cdf: function cdf(x, alpha, beta) {\n return (x > 1 || x < 0) ? (x > 1) * 1 : jStat.ibeta(x, alpha, beta);\n },\n\n inv: function inv(x, alpha, beta) {\n return jStat.ibetainv(x, alpha, beta);\n },\n\n mean: function mean(alpha, beta) {\n return alpha / (alpha + beta);\n },\n\n median: function median(alpha, beta) {\n return jStat.ibetainv(0.5, alpha, beta);\n },\n\n mode: function mode(alpha, beta) {\n return (alpha - 1 ) / ( alpha + beta - 2);\n },\n\n // return a random sample\n sample: function sample(alpha, beta) {\n var u = jStat.randg(alpha);\n return u / (u + jStat.randg(beta));\n },\n\n variance: function variance(alpha, beta) {\n return (alpha * beta) / (Math.pow(alpha + beta, 2) * (alpha + beta + 1));\n }\n});\n\n// extend F function with static methods\njStat.extend(jStat.centralF, {\n // This implementation of the pdf function avoids float overflow\n // See the way that R calculates this value:\n // https://svn.r-project.org/R/trunk/src/nmath/df.c\n pdf: function pdf(x, df1, df2) {\n var p, q, f;\n\n if (x < 0)\n return 0;\n\n if (df1 <= 2) {\n if (x === 0 && df1 < 2) {\n return Infinity;\n }\n if (x === 0 && df1 === 2) {\n return 1;\n }\n return (1 / jStat.betafn(df1 / 2, df2 / 2)) *\n Math.pow(df1 / df2, df1 / 2) *\n Math.pow(x, (df1/2) - 1) *\n Math.pow((1 + (df1 / df2) * x), -(df1 + df2) / 2);\n }\n\n p = (df1 * x) / (df2 + x * df1);\n q = df2 / (df2 + x * df1);\n f = df1 * q / 2.0;\n return f * jStat.binomial.pdf((df1 - 2) / 2, (df1 + df2 - 2) / 2, p);\n },\n\n cdf: function cdf(x, df1, df2) {\n if (x < 0)\n return 0;\n return jStat.ibeta((df1 * x) / (df1 * x + df2), df1 / 2, df2 / 2);\n },\n\n inv: function inv(x, df1, df2) {\n return df2 / (df1 * (1 / jStat.ibetainv(x, df1 / 2, df2 / 2) - 1));\n },\n\n mean: function mean(df1, df2) {\n return (df2 > 2) ? df2 / (df2 - 2) : undefined;\n },\n\n mode: function mode(df1, df2) {\n return (df1 > 2) ? (df2 * (df1 - 2)) / (df1 * (df2 + 2)) : undefined;\n },\n\n // return a random sample\n sample: function sample(df1, df2) {\n var x1 = jStat.randg(df1 / 2) * 2;\n var x2 = jStat.randg(df2 / 2) * 2;\n return (x1 / df1) / (x2 / df2);\n },\n\n variance: function variance(df1, df2) {\n if (df2 <= 4)\n return undefined;\n return 2 * df2 * df2 * (df1 + df2 - 2) /\n (df1 * (df2 - 2) * (df2 - 2) * (df2 - 4));\n }\n});\n\n\n// extend cauchy function with static methods\njStat.extend(jStat.cauchy, {\n pdf: function pdf(x, local, scale) {\n if (scale < 0) { return 0; }\n\n return (scale / (Math.pow(x - local, 2) + Math.pow(scale, 2))) / Math.PI;\n },\n\n cdf: function cdf(x, local, scale) {\n return Math.atan((x - local) / scale) / Math.PI + 0.5;\n },\n\n inv: function(p, local, scale) {\n return local + scale * Math.tan(Math.PI * (p - 0.5));\n },\n\n median: function median(local/*, scale*/) {\n return local;\n },\n\n mode: function mode(local/*, scale*/) {\n return local;\n },\n\n sample: function sample(local, scale) {\n return jStat.randn() *\n Math.sqrt(1 / (2 * jStat.randg(0.5))) * scale + local;\n }\n});\n\n\n\n// extend chisquare function with static methods\njStat.extend(jStat.chisquare, {\n pdf: function pdf(x, dof) {\n if (x < 0)\n return 0;\n return (x === 0 && dof === 2) ? 0.5 :\n Math.exp((dof / 2 - 1) * Math.log(x) - x / 2 - (dof / 2) *\n Math.log(2) - jStat.gammaln(dof / 2));\n },\n\n cdf: function cdf(x, dof) {\n if (x < 0)\n return 0;\n return jStat.lowRegGamma(dof / 2, x / 2);\n },\n\n inv: function(p, dof) {\n return 2 * jStat.gammapinv(p, 0.5 * dof);\n },\n\n mean : function(dof) {\n return dof;\n },\n\n // TODO: this is an approximation (is there a better way?)\n median: function median(dof) {\n return dof * Math.pow(1 - (2 / (9 * dof)), 3);\n },\n\n mode: function mode(dof) {\n return (dof - 2 > 0) ? dof - 2 : 0;\n },\n\n sample: function sample(dof) {\n return jStat.randg(dof / 2) * 2;\n },\n\n variance: function variance(dof) {\n return 2 * dof;\n }\n});\n\n\n\n// extend exponential function with static methods\njStat.extend(jStat.exponential, {\n pdf: function pdf(x, rate) {\n return x < 0 ? 0 : rate * Math.exp(-rate * x);\n },\n\n cdf: function cdf(x, rate) {\n return x < 0 ? 0 : 1 - Math.exp(-rate * x);\n },\n\n inv: function(p, rate) {\n return -Math.log(1 - p) / rate;\n },\n\n mean : function(rate) {\n return 1 / rate;\n },\n\n median: function (rate) {\n return (1 / rate) * Math.log(2);\n },\n\n mode: function mode(/*rate*/) {\n return 0;\n },\n\n sample: function sample(rate) {\n return -1 / rate * Math.log(jStat._random_fn());\n },\n\n variance : function(rate) {\n return Math.pow(rate, -2);\n }\n});\n\n\n\n// extend gamma function with static methods\njStat.extend(jStat.gamma, {\n pdf: function pdf(x, shape, scale) {\n if (x < 0)\n return 0;\n return (x === 0 && shape === 1) ? 1 / scale :\n Math.exp((shape - 1) * Math.log(x) - x / scale -\n jStat.gammaln(shape) - shape * Math.log(scale));\n },\n\n cdf: function cdf(x, shape, scale) {\n if (x < 0)\n return 0;\n return jStat.lowRegGamma(shape, x / scale);\n },\n\n inv: function(p, shape, scale) {\n return jStat.gammapinv(p, shape) * scale;\n },\n\n mean : function(shape, scale) {\n return shape * scale;\n },\n\n mode: function mode(shape, scale) {\n if(shape > 1) return (shape - 1) * scale;\n return undefined;\n },\n\n sample: function sample(shape, scale) {\n return jStat.randg(shape) * scale;\n },\n\n variance: function variance(shape, scale) {\n return shape * scale * scale;\n }\n});\n\n// extend inverse gamma function with static methods\njStat.extend(jStat.invgamma, {\n pdf: function pdf(x, shape, scale) {\n if (x <= 0)\n return 0;\n return Math.exp(-(shape + 1) * Math.log(x) - scale / x -\n jStat.gammaln(shape) + shape * Math.log(scale));\n },\n\n cdf: function cdf(x, shape, scale) {\n if (x <= 0)\n return 0;\n return 1 - jStat.lowRegGamma(shape, scale / x);\n },\n\n inv: function(p, shape, scale) {\n return scale / jStat.gammapinv(1 - p, shape);\n },\n\n mean : function(shape, scale) {\n return (shape > 1) ? scale / (shape - 1) : undefined;\n },\n\n mode: function mode(shape, scale) {\n return scale / (shape + 1);\n },\n\n sample: function sample(shape, scale) {\n return scale / jStat.randg(shape);\n },\n\n variance: function variance(shape, scale) {\n if (shape <= 2)\n return undefined;\n return scale * scale / ((shape - 1) * (shape - 1) * (shape - 2));\n }\n});\n\n\n// extend kumaraswamy function with static methods\njStat.extend(jStat.kumaraswamy, {\n pdf: function pdf(x, alpha, beta) {\n if (x === 0 && alpha === 1)\n return beta;\n else if (x === 1 && beta === 1)\n return alpha;\n return Math.exp(Math.log(alpha) + Math.log(beta) + (alpha - 1) *\n Math.log(x) + (beta - 1) *\n Math.log(1 - Math.pow(x, alpha)));\n },\n\n cdf: function cdf(x, alpha, beta) {\n if (x < 0)\n return 0;\n else if (x > 1)\n return 1;\n return (1 - Math.pow(1 - Math.pow(x, alpha), beta));\n },\n\n inv: function inv(p, alpha, beta) {\n return Math.pow(1 - Math.pow(1 - p, 1 / beta), 1 / alpha);\n },\n\n mean : function(alpha, beta) {\n return (beta * jStat.gammafn(1 + 1 / alpha) *\n jStat.gammafn(beta)) / (jStat.gammafn(1 + 1 / alpha + beta));\n },\n\n median: function median(alpha, beta) {\n return Math.pow(1 - Math.pow(2, -1 / beta), 1 / alpha);\n },\n\n mode: function mode(alpha, beta) {\n if (!(alpha >= 1 && beta >= 1 && (alpha !== 1 && beta !== 1)))\n return undefined;\n return Math.pow((alpha - 1) / (alpha * beta - 1), 1 / alpha);\n },\n\n variance: function variance(/*alpha, beta*/) {\n throw new Error('variance not yet implemented');\n // TODO: complete this\n }\n});\n\n\n\n// extend lognormal function with static methods\njStat.extend(jStat.lognormal, {\n pdf: function pdf(x, mu, sigma) {\n if (x <= 0)\n return 0;\n return Math.exp(-Math.log(x) - 0.5 * Math.log(2 * Math.PI) -\n Math.log(sigma) - Math.pow(Math.log(x) - mu, 2) /\n (2 * sigma * sigma));\n },\n\n cdf: function cdf(x, mu, sigma) {\n if (x < 0)\n return 0;\n return 0.5 +\n (0.5 * jStat.erf((Math.log(x) - mu) / Math.sqrt(2 * sigma * sigma)));\n },\n\n inv: function(p, mu, sigma) {\n return Math.exp(-1.41421356237309505 * sigma * jStat.erfcinv(2 * p) + mu);\n },\n\n mean: function mean(mu, sigma) {\n return Math.exp(mu + sigma * sigma / 2);\n },\n\n median: function median(mu/*, sigma*/) {\n return Math.exp(mu);\n },\n\n mode: function mode(mu, sigma) {\n return Math.exp(mu - sigma * sigma);\n },\n\n sample: function sample(mu, sigma) {\n return Math.exp(jStat.randn() * sigma + mu);\n },\n\n variance: function variance(mu, sigma) {\n return (Math.exp(sigma * sigma) - 1) * Math.exp(2 * mu + sigma * sigma);\n }\n});\n\n\n\n// extend noncentralt function with static methods\njStat.extend(jStat.noncentralt, {\n pdf: function pdf(x, dof, ncp) {\n var tol = 1e-14;\n if (Math.abs(ncp) < tol) // ncp approx 0; use student-t\n return jStat.studentt.pdf(x, dof)\n\n if (Math.abs(x) < tol) { // different formula for x == 0\n return Math.exp(jStat.gammaln((dof + 1) / 2) - ncp * ncp / 2 -\n 0.5 * Math.log(Math.PI * dof) - jStat.gammaln(dof / 2));\n }\n\n // formula for x != 0\n return dof / x *\n (jStat.noncentralt.cdf(x * Math.sqrt(1 + 2 / dof), dof+2, ncp) -\n jStat.noncentralt.cdf(x, dof, ncp));\n },\n\n cdf: function cdf(x, dof, ncp) {\n var tol = 1e-14;\n var min_iterations = 200;\n\n if (Math.abs(ncp) < tol) // ncp approx 0; use student-t\n return jStat.studentt.cdf(x, dof);\n\n // turn negative x into positive and flip result afterwards\n var flip = false;\n if (x < 0) {\n flip = true;\n ncp = -ncp;\n }\n\n var prob = jStat.normal.cdf(-ncp, 0, 1);\n var value = tol + 1;\n // use value at last two steps to determine convergence\n var lastvalue = value;\n var y = x * x / (x * x + dof);\n var j = 0;\n var p = Math.exp(-ncp * ncp / 2);\n var q = Math.exp(-ncp * ncp / 2 - 0.5 * Math.log(2) -\n jStat.gammaln(3 / 2)) * ncp;\n while (j < min_iterations || lastvalue > tol || value > tol) {\n lastvalue = value;\n if (j > 0) {\n p *= (ncp * ncp) / (2 * j);\n q *= (ncp * ncp) / (2 * (j + 1 / 2));\n }\n value = p * jStat.beta.cdf(y, j + 0.5, dof / 2) +\n q * jStat.beta.cdf(y, j+1, dof/2);\n prob += 0.5 * value;\n j++;\n }\n\n return flip ? (1 - prob) : prob;\n }\n});\n\n\n// extend normal function with static methods\njStat.extend(jStat.normal, {\n pdf: function pdf(x, mean, std) {\n return Math.exp(-0.5 * Math.log(2 * Math.PI) -\n Math.log(std) - Math.pow(x - mean, 2) / (2 * std * std));\n },\n\n cdf: function cdf(x, mean, std) {\n return 0.5 * (1 + jStat.erf((x - mean) / Math.sqrt(2 * std * std)));\n },\n\n inv: function(p, mean, std) {\n return -1.41421356237309505 * std * jStat.erfcinv(2 * p) + mean;\n },\n\n mean : function(mean/*, std*/) {\n return mean;\n },\n\n median: function median(mean/*, std*/) {\n return mean;\n },\n\n mode: function (mean/*, std*/) {\n return mean;\n },\n\n sample: function sample(mean, std) {\n return jStat.randn() * std + mean;\n },\n\n variance : function(mean, std) {\n return std * std;\n }\n});\n\n\n\n// extend pareto function with static methods\njStat.extend(jStat.pareto, {\n pdf: function pdf(x, scale, shape) {\n if (x < scale)\n return 0;\n return (shape * Math.pow(scale, shape)) / Math.pow(x, shape + 1);\n },\n\n cdf: function cdf(x, scale, shape) {\n if (x < scale)\n return 0;\n return 1 - Math.pow(scale / x, shape);\n },\n\n inv: function inv(p, scale, shape) {\n return scale / Math.pow(1 - p, 1 / shape);\n },\n\n mean: function mean(scale, shape) {\n if (shape <= 1)\n return undefined;\n return (shape * Math.pow(scale, shape)) / (shape - 1);\n },\n\n median: function median(scale, shape) {\n return scale * (shape * Math.SQRT2);\n },\n\n mode: function mode(scale/*, shape*/) {\n return scale;\n },\n\n variance : function(scale, shape) {\n if (shape <= 2)\n return undefined;\n return (scale*scale * shape) / (Math.pow(shape - 1, 2) * (shape - 2));\n }\n});\n\n\n\n// extend studentt function with static methods\njStat.extend(jStat.studentt, {\n pdf: function pdf(x, dof) {\n dof = dof > 1e100 ? 1e100 : dof;\n return (1/(Math.sqrt(dof) * jStat.betafn(0.5, dof/2))) *\n Math.pow(1 + ((x * x) / dof), -((dof + 1) / 2));\n },\n\n cdf: function cdf(x, dof) {\n var dof2 = dof / 2;\n return jStat.ibeta((x + Math.sqrt(x * x + dof)) /\n (2 * Math.sqrt(x * x + dof)), dof2, dof2);\n },\n\n inv: function(p, dof) {\n var x = jStat.ibetainv(2 * Math.min(p, 1 - p), 0.5 * dof, 0.5);\n x = Math.sqrt(dof * (1 - x) / x);\n return (p > 0.5) ? x : -x;\n },\n\n mean: function mean(dof) {\n return (dof > 1) ? 0 : undefined;\n },\n\n median: function median(/*dof*/) {\n return 0;\n },\n\n mode: function mode(/*dof*/) {\n return 0;\n },\n\n sample: function sample(dof) {\n return jStat.randn() * Math.sqrt(dof / (2 * jStat.randg(dof / 2)));\n },\n\n variance: function variance(dof) {\n return (dof > 2) ? dof / (dof - 2) : (dof > 1) ? Infinity : undefined;\n }\n});\n\n\n\n// extend weibull function with static methods\njStat.extend(jStat.weibull, {\n pdf: function pdf(x, scale, shape) {\n if (x < 0 || scale < 0 || shape < 0)\n return 0;\n return (shape / scale) * Math.pow((x / scale), (shape - 1)) *\n Math.exp(-(Math.pow((x / scale), shape)));\n },\n\n cdf: function cdf(x, scale, shape) {\n return x < 0 ? 0 : 1 - Math.exp(-Math.pow((x / scale), shape));\n },\n\n inv: function(p, scale, shape) {\n return scale * Math.pow(-Math.log(1 - p), 1 / shape);\n },\n\n mean : function(scale, shape) {\n return scale * jStat.gammafn(1 + 1 / shape);\n },\n\n median: function median(scale, shape) {\n return scale * Math.pow(Math.log(2), 1 / shape);\n },\n\n mode: function mode(scale, shape) {\n if (shape <= 1)\n return 0;\n return scale * Math.pow((shape - 1) / shape, 1 / shape);\n },\n\n sample: function sample(scale, shape) {\n return scale * Math.pow(-Math.log(jStat._random_fn()), 1 / shape);\n },\n\n variance: function variance(scale, shape) {\n return scale * scale * jStat.gammafn(1 + 2 / shape) -\n Math.pow(jStat.weibull.mean(scale, shape), 2);\n }\n});\n\n\n\n// extend uniform function with static methods\njStat.extend(jStat.uniform, {\n pdf: function pdf(x, a, b) {\n return (x < a || x > b) ? 0 : 1 / (b - a);\n },\n\n cdf: function cdf(x, a, b) {\n if (x < a)\n return 0;\n else if (x < b)\n return (x - a) / (b - a);\n return 1;\n },\n\n inv: function(p, a, b) {\n return a + (p * (b - a));\n },\n\n mean: function mean(a, b) {\n return 0.5 * (a + b);\n },\n\n median: function median(a, b) {\n return jStat.mean(a, b);\n },\n\n mode: function mode(/*a, b*/) {\n throw new Error('mode is not yet implemented');\n },\n\n sample: function sample(a, b) {\n return (a / 2 + b / 2) + (b / 2 - a / 2) * (2 * jStat._random_fn() - 1);\n },\n\n variance: function variance(a, b) {\n return Math.pow(b - a, 2) / 12;\n }\n});\n\n\n// Got this from http://www.math.ucla.edu/~tom/distributions/binomial.html\nfunction betinc(x, a, b, eps) {\n var a0 = 0;\n var b0 = 1;\n var a1 = 1;\n var b1 = 1;\n var m9 = 0;\n var a2 = 0;\n var c9;\n\n while (Math.abs((a1 - a2) / a1) > eps) {\n a2 = a1;\n c9 = -(a + m9) * (a + b + m9) * x / (a + 2 * m9) / (a + 2 * m9 + 1);\n a0 = a1 + c9 * a0;\n b0 = b1 + c9 * b0;\n m9 = m9 + 1;\n c9 = m9 * (b - m9) * x / (a + 2 * m9 - 1) / (a + 2 * m9);\n a1 = a0 + c9 * a1;\n b1 = b0 + c9 * b1;\n a0 = a0 / b1;\n b0 = b0 / b1;\n a1 = a1 / b1;\n b1 = 1;\n }\n\n return a1 / a;\n}\n\n\n// extend uniform function with static methods\njStat.extend(jStat.binomial, {\n pdf: function pdf(k, n, p) {\n return (p === 0 || p === 1) ?\n ((n * p) === k ? 1 : 0) :\n jStat.combination(n, k) * Math.pow(p, k) * Math.pow(1 - p, n - k);\n },\n\n cdf: function cdf(x, n, p) {\n var betacdf;\n var eps = 1e-10;\n\n if (x < 0)\n return 0;\n if (x >= n)\n return 1;\n if (p < 0 || p > 1 || n <= 0)\n return NaN;\n\n x = Math.floor(x);\n var z = p;\n var a = x + 1;\n var b = n - x;\n var s = a + b;\n var bt = Math.exp(jStat.gammaln(s) - jStat.gammaln(b) -\n jStat.gammaln(a) + a * Math.log(z) + b * Math.log(1 - z));\n\n if (z < (a + 1) / (s + 2))\n betacdf = bt * betinc(z, a, b, eps);\n else\n betacdf = 1 - bt * betinc(1 - z, b, a, eps);\n\n return Math.round((1 - betacdf) * (1 / eps)) / (1 / eps);\n }\n});\n\n\n\n// extend uniform function with static methods\njStat.extend(jStat.negbin, {\n pdf: function pdf(k, r, p) {\n if (k !== k >>> 0)\n return false;\n if (k < 0)\n return 0;\n return jStat.combination(k + r - 1, r - 1) *\n Math.pow(1 - p, k) * Math.pow(p, r);\n },\n\n cdf: function cdf(x, r, p) {\n var sum = 0,\n k = 0;\n if (x < 0) return 0;\n for (; k <= x; k++) {\n sum += jStat.negbin.pdf(k, r, p);\n }\n return sum;\n }\n});\n\n\n\n// extend uniform function with static methods\njStat.extend(jStat.hypgeom, {\n pdf: function pdf(k, N, m, n) {\n // Hypergeometric PDF.\n\n // A simplification of the CDF algorithm below.\n\n // k = number of successes drawn\n // N = population size\n // m = number of successes in population\n // n = number of items drawn from population\n\n if(k !== k | 0) {\n return false;\n } else if(k < 0 || k < m - (N - n)) {\n // It's impossible to have this few successes drawn.\n return 0;\n } else if(k > n || k > m) {\n // It's impossible to have this many successes drawn.\n return 0;\n } else if (m * 2 > N) {\n // More than half the population is successes.\n\n if(n * 2 > N) {\n // More than half the population is sampled.\n\n return jStat.hypgeom.pdf(N - m - n + k, N, N - m, N - n)\n } else {\n // Half or less of the population is sampled.\n\n return jStat.hypgeom.pdf(n - k, N, N - m, n);\n }\n\n } else if(n * 2 > N) {\n // Half or less is successes.\n\n return jStat.hypgeom.pdf(m - k, N, m, N - n);\n\n } else if(m < n) {\n // We want to have the number of things sampled to be less than the\n // successes available. So swap the definitions of successful and sampled.\n return jStat.hypgeom.pdf(k, N, n, m);\n } else {\n // If we get here, half or less of the population was sampled, half or\n // less of it was successes, and we had fewer sampled things than\n // successes. Now we can do this complicated iterative algorithm in an\n // efficient way.\n\n // The basic premise of the algorithm is that we partially normalize our\n // intermediate product to keep it in a numerically good region, and then\n // finish the normalization at the end.\n\n // This variable holds the scaled probability of the current number of\n // successes.\n var scaledPDF = 1;\n\n // This keeps track of how much we have normalized.\n var samplesDone = 0;\n\n for(var i = 0; i < k; i++) {\n // For every possible number of successes up to that observed...\n\n while(scaledPDF > 1 && samplesDone < n) {\n // Intermediate result is growing too big. Apply some of the\n // normalization to shrink everything.\n\n scaledPDF *= 1 - (m / (N - samplesDone));\n\n // Say we've normalized by this sample already.\n samplesDone++;\n }\n\n // Work out the partially-normalized hypergeometric PDF for the next\n // number of successes\n scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1));\n }\n\n for(; samplesDone < n; samplesDone++) {\n // Apply all the rest of the normalization\n scaledPDF *= 1 - (m / (N - samplesDone));\n }\n\n // Bound answer sanely before returning.\n return Math.min(1, Math.max(0, scaledPDF));\n }\n },\n\n cdf: function cdf(x, N, m, n) {\n // Hypergeometric CDF.\n\n // This algorithm is due to Prof. Thomas S. Ferguson, ,\n // and comes from his hypergeometric test calculator at\n // .\n\n // x = number of successes drawn\n // N = population size\n // m = number of successes in population\n // n = number of items drawn from population\n\n if(x < 0 || x < m - (N - n)) {\n // It's impossible to have this few successes drawn or fewer.\n return 0;\n } else if(x >= n || x >= m) {\n // We will always have this many successes or fewer.\n return 1;\n } else if (m * 2 > N) {\n // More than half the population is successes.\n\n if(n * 2 > N) {\n // More than half the population is sampled.\n\n return jStat.hypgeom.cdf(N - m - n + x, N, N - m, N - n)\n } else {\n // Half or less of the population is sampled.\n\n return 1 - jStat.hypgeom.cdf(n - x - 1, N, N - m, n);\n }\n\n } else if(n * 2 > N) {\n // Half or less is successes.\n\n return 1 - jStat.hypgeom.cdf(m - x - 1, N, m, N - n);\n\n } else if(m < n) {\n // We want to have the number of things sampled to be less than the\n // successes available. So swap the definitions of successful and sampled.\n return jStat.hypgeom.cdf(x, N, n, m);\n } else {\n // If we get here, half or less of the population was sampled, half or\n // less of it was successes, and we had fewer sampled things than\n // successes. Now we can do this complicated iterative algorithm in an\n // efficient way.\n\n // The basic premise of the algorithm is that we partially normalize our\n // intermediate sum to keep it in a numerically good region, and then\n // finish the normalization at the end.\n\n // Holds the intermediate, scaled total CDF.\n var scaledCDF = 1;\n\n // This variable holds the scaled probability of the current number of\n // successes.\n var scaledPDF = 1;\n\n // This keeps track of how much we have normalized.\n var samplesDone = 0;\n\n for(var i = 0; i < x; i++) {\n // For every possible number of successes up to that observed...\n\n while(scaledCDF > 1 && samplesDone < n) {\n // Intermediate result is growing too big. Apply some of the\n // normalization to shrink everything.\n\n var factor = 1 - (m / (N - samplesDone));\n\n scaledPDF *= factor;\n scaledCDF *= factor;\n\n // Say we've normalized by this sample already.\n samplesDone++;\n }\n\n // Work out the partially-normalized hypergeometric PDF for the next\n // number of successes\n scaledPDF *= (n - i) * (m - i) / ((i + 1) * (N - m - n + i + 1));\n\n // Add to the CDF answer.\n scaledCDF += scaledPDF;\n }\n\n for(; samplesDone < n; samplesDone++) {\n // Apply all the rest of the normalization\n scaledCDF *= 1 - (m / (N - samplesDone));\n }\n\n // Bound answer sanely before returning.\n return Math.min(1, Math.max(0, scaledCDF));\n }\n }\n});\n\n\n\n// extend uniform function with static methods\njStat.extend(jStat.poisson, {\n pdf: function pdf(k, l) {\n if (l < 0 || (k % 1) !== 0 || k < 0) {\n return 0;\n }\n\n return Math.pow(l, k) * Math.exp(-l) / jStat.factorial(k);\n },\n\n cdf: function cdf(x, l) {\n var sumarr = [],\n k = 0;\n if (x < 0) return 0;\n for (; k <= x; k++) {\n sumarr.push(jStat.poisson.pdf(k, l));\n }\n return jStat.sum(sumarr);\n },\n\n mean : function(l) {\n return l;\n },\n\n variance : function(l) {\n return l;\n },\n\n sampleSmall: function sampleSmall(l) {\n var p = 1, k = 0, L = Math.exp(-l);\n do {\n k++;\n p *= jStat._random_fn();\n } while (p > L);\n return k - 1;\n },\n\n sampleLarge: function sampleLarge(l) {\n var lam = l;\n var k;\n var U, V, slam, loglam, a, b, invalpha, vr, us;\n\n slam = Math.sqrt(lam);\n loglam = Math.log(lam);\n b = 0.931 + 2.53 * slam;\n a = -0.059 + 0.02483 * b;\n invalpha = 1.1239 + 1.1328 / (b - 3.4);\n vr = 0.9277 - 3.6224 / (b - 2);\n\n while (1) {\n U = Math.random() - 0.5;\n V = Math.random();\n us = 0.5 - Math.abs(U);\n k = Math.floor((2 * a / us + b) * U + lam + 0.43);\n if ((us >= 0.07) && (V <= vr)) {\n return k;\n }\n if ((k < 0) || ((us < 0.013) && (V > us))) {\n continue;\n }\n /* log(V) == log(0.0) ok here */\n /* if U==0.0 so that us==0.0, log is ok since always returns */\n if ((Math.log(V) + Math.log(invalpha) - Math.log(a / (us * us) + b)) <= (-lam + k * loglam - jStat.loggam(k + 1))) {\n return k;\n }\n }\n },\n\n sample: function sample(l) {\n if (l < 10)\n return this.sampleSmall(l);\n else\n return this.sampleLarge(l);\n }\n});\n\n// extend triangular function with static methods\njStat.extend(jStat.triangular, {\n pdf: function pdf(x, a, b, c) {\n if (b <= a || c < a || c > b) {\n return NaN;\n } else {\n if (x < a || x > b) {\n return 0;\n } else if (x < c) {\n return (2 * (x - a)) / ((b - a) * (c - a));\n } else if (x === c) {\n return (2 / (b - a));\n } else { // x > c\n return (2 * (b - x)) / ((b - a) * (b - c));\n }\n }\n },\n\n cdf: function cdf(x, a, b, c) {\n if (b <= a || c < a || c > b)\n return NaN;\n if (x <= a)\n return 0;\n else if (x >= b)\n return 1;\n if (x <= c)\n return Math.pow(x - a, 2) / ((b - a) * (c - a));\n else // x > c\n return 1 - Math.pow(b - x, 2) / ((b - a) * (b - c));\n },\n\n inv: function inv(p, a, b, c) {\n if (b <= a || c < a || c > b) {\n return NaN;\n } else {\n if (p <= ((c - a) / (b - a))) {\n return a + (b - a) * Math.sqrt(p * ((c - a) / (b - a)));\n } else { // p > ((c - a) / (b - a))\n return a + (b - a) * (1 - Math.sqrt((1 - p) * (1 - ((c - a) / (b - a)))));\n }\n }\n },\n\n mean: function mean(a, b, c) {\n return (a + b + c) / 3;\n },\n\n median: function median(a, b, c) {\n if (c <= (a + b) / 2) {\n return b - Math.sqrt((b - a) * (b - c)) / Math.sqrt(2);\n } else if (c > (a + b) / 2) {\n return a + Math.sqrt((b - a) * (c - a)) / Math.sqrt(2);\n }\n },\n\n mode: function mode(a, b, c) {\n return c;\n },\n\n sample: function sample(a, b, c) {\n var u = jStat._random_fn();\n if (u < ((c - a) / (b - a)))\n return a + Math.sqrt(u * (b - a) * (c - a))\n return b - Math.sqrt((1 - u) * (b - a) * (b - c));\n },\n\n variance: function variance(a, b, c) {\n return (a * a + b * b + c * c - a * b - a * c - b * c) / 18;\n }\n});\n\n\n// extend arcsine function with static methods\njStat.extend(jStat.arcsine, {\n pdf: function pdf(x, a, b) {\n if (b <= a) return NaN;\n\n return (x <= a || x >= b) ? 0 :\n (2 / Math.PI) *\n Math.pow(Math.pow(b - a, 2) -\n Math.pow(2 * x - a - b, 2), -0.5);\n },\n\n cdf: function cdf(x, a, b) {\n if (x < a)\n return 0;\n else if (x < b)\n return (2 / Math.PI) * Math.asin(Math.sqrt((x - a)/(b - a)));\n return 1;\n },\n\n inv: function(p, a, b) {\n return a + (0.5 - 0.5 * Math.cos(Math.PI * p)) * (b - a);\n },\n\n mean: function mean(a, b) {\n if (b <= a) return NaN;\n return (a + b) / 2;\n },\n\n median: function median(a, b) {\n if (b <= a) return NaN;\n return (a + b) / 2;\n },\n\n mode: function mode(/*a, b*/) {\n throw new Error('mode is not yet implemented');\n },\n\n sample: function sample(a, b) {\n return ((a + b) / 2) + ((b - a) / 2) *\n Math.sin(2 * Math.PI * jStat.uniform.sample(0, 1));\n },\n\n variance: function variance(a, b) {\n if (b <= a) return NaN;\n return Math.pow(b - a, 2) / 8;\n }\n});\n\n\nfunction laplaceSign(x) { return x / Math.abs(x); }\n\njStat.extend(jStat.laplace, {\n pdf: function pdf(x, mu, b) {\n return (b <= 0) ? 0 : (Math.exp(-Math.abs(x - mu) / b)) / (2 * b);\n },\n\n cdf: function cdf(x, mu, b) {\n if (b <= 0) { return 0; }\n\n if(x < mu) {\n return 0.5 * Math.exp((x - mu) / b);\n } else {\n return 1 - 0.5 * Math.exp(- (x - mu) / b);\n }\n },\n\n mean: function(mu/*, b*/) {\n return mu;\n },\n\n median: function(mu/*, b*/) {\n return mu;\n },\n\n mode: function(mu/*, b*/) {\n return mu;\n },\n\n variance: function(mu, b) {\n return 2 * b * b;\n },\n\n sample: function sample(mu, b) {\n var u = jStat._random_fn() - 0.5;\n\n return mu - (b * laplaceSign(u) * Math.log(1 - (2 * Math.abs(u))));\n }\n});\n\nfunction tukeyWprob(w, rr, cc) {\n var nleg = 12;\n var ihalf = 6;\n\n var C1 = -30;\n var C2 = -50;\n var C3 = 60;\n var bb = 8;\n var wlar = 3;\n var wincr1 = 2;\n var wincr2 = 3;\n var xleg = [\n 0.981560634246719250690549090149,\n 0.904117256370474856678465866119,\n 0.769902674194304687036893833213,\n 0.587317954286617447296702418941,\n 0.367831498998180193752691536644,\n 0.125233408511468915472441369464\n ];\n var aleg = [\n 0.047175336386511827194615961485,\n 0.106939325995318430960254718194,\n 0.160078328543346226334652529543,\n 0.203167426723065921749064455810,\n 0.233492536538354808760849898925,\n 0.249147045813402785000562436043\n ];\n\n var qsqz = w * 0.5;\n\n // if w >= 16 then the integral lower bound (occurs for c=20)\n // is 0.99999999999995 so return a value of 1.\n\n if (qsqz >= bb)\n return 1.0;\n\n // find (f(w/2) - 1) ^ cc\n // (first term in integral of hartley's form).\n\n var pr_w = 2 * jStat.normal.cdf(qsqz, 0, 1, 1, 0) - 1; // erf(qsqz / M_SQRT2)\n // if pr_w ^ cc < 2e-22 then set pr_w = 0\n if (pr_w >= Math.exp(C2 / cc))\n pr_w = Math.pow(pr_w, cc);\n else\n pr_w = 0.0;\n\n // if w is large then the second component of the\n // integral is small, so fewer intervals are needed.\n\n var wincr;\n if (w > wlar)\n wincr = wincr1;\n else\n wincr = wincr2;\n\n // find the integral of second term of hartley's form\n // for the integral of the range for equal-length\n // intervals using legendre quadrature. limits of\n // integration are from (w/2, 8). two or three\n // equal-length intervals are used.\n\n // blb and bub are lower and upper limits of integration.\n\n var blb = qsqz;\n var binc = (bb - qsqz) / wincr;\n var bub = blb + binc;\n var einsum = 0.0;\n\n // integrate over each interval\n\n var cc1 = cc - 1.0;\n for (var wi = 1; wi <= wincr; wi++) {\n var elsum = 0.0;\n var a = 0.5 * (bub + blb);\n\n // legendre quadrature with order = nleg\n\n var b = 0.5 * (bub - blb);\n\n for (var jj = 1; jj <= nleg; jj++) {\n var j, xx;\n if (ihalf < jj) {\n j = (nleg - jj) + 1;\n xx = xleg[j-1];\n } else {\n j = jj;\n xx = -xleg[j-1];\n }\n var c = b * xx;\n var ac = a + c;\n\n // if exp(-qexpo/2) < 9e-14,\n // then doesn't contribute to integral\n\n var qexpo = ac * ac;\n if (qexpo > C3)\n break;\n\n var pplus = 2 * jStat.normal.cdf(ac, 0, 1, 1, 0);\n var pminus= 2 * jStat.normal.cdf(ac, w, 1, 1, 0);\n\n // if rinsum ^ (cc-1) < 9e-14,\n // then doesn't contribute to integral\n\n var rinsum = (pplus * 0.5) - (pminus * 0.5);\n if (rinsum >= Math.exp(C1 / cc1)) {\n rinsum = (aleg[j-1] * Math.exp(-(0.5 * qexpo))) * Math.pow(rinsum, cc1);\n elsum += rinsum;\n }\n }\n elsum *= (((2.0 * b) * cc) / Math.sqrt(2 * Math.PI));\n einsum += elsum;\n blb = bub;\n bub += binc;\n }\n\n // if pr_w ^ rr < 9e-14, then return 0\n pr_w += einsum;\n if (pr_w <= Math.exp(C1 / rr))\n return 0;\n\n pr_w = Math.pow(pr_w, rr);\n if (pr_w >= 1) // 1 was iMax was eps\n return 1;\n return pr_w;\n}\n\nfunction tukeyQinv(p, c, v) {\n var p0 = 0.322232421088;\n var q0 = 0.993484626060e-01;\n var p1 = -1.0;\n var q1 = 0.588581570495;\n var p2 = -0.342242088547;\n var q2 = 0.531103462366;\n var p3 = -0.204231210125;\n var q3 = 0.103537752850;\n var p4 = -0.453642210148e-04;\n var q4 = 0.38560700634e-02;\n var c1 = 0.8832;\n var c2 = 0.2368;\n var c3 = 1.214;\n var c4 = 1.208;\n var c5 = 1.4142;\n var vmax = 120.0;\n\n var ps = 0.5 - 0.5 * p;\n var yi = Math.sqrt(Math.log(1.0 / (ps * ps)));\n var t = yi + (((( yi * p4 + p3) * yi + p2) * yi + p1) * yi + p0)\n / (((( yi * q4 + q3) * yi + q2) * yi + q1) * yi + q0);\n if (v < vmax) t += (t * t * t + t) / v / 4.0;\n var q = c1 - c2 * t;\n if (v < vmax) q += -c3 / v + c4 * t / v;\n return t * (q * Math.log(c - 1.0) + c5);\n}\n\njStat.extend(jStat.tukey, {\n cdf: function cdf(q, nmeans, df) {\n // Identical implementation as the R ptukey() function as of commit 68947\n var rr = 1;\n var cc = nmeans;\n\n var nlegq = 16;\n var ihalfq = 8;\n\n var eps1 = -30.0;\n var eps2 = 1.0e-14;\n var dhaf = 100.0;\n var dquar = 800.0;\n var deigh = 5000.0;\n var dlarg = 25000.0;\n var ulen1 = 1.0;\n var ulen2 = 0.5;\n var ulen3 = 0.25;\n var ulen4 = 0.125;\n var xlegq = [\n 0.989400934991649932596154173450,\n 0.944575023073232576077988415535,\n 0.865631202387831743880467897712,\n 0.755404408355003033895101194847,\n 0.617876244402643748446671764049,\n 0.458016777657227386342419442984,\n 0.281603550779258913230460501460,\n 0.950125098376374401853193354250e-1\n ];\n var alegq = [\n 0.271524594117540948517805724560e-1,\n 0.622535239386478928628438369944e-1,\n 0.951585116824927848099251076022e-1,\n 0.124628971255533872052476282192,\n 0.149595988816576732081501730547,\n 0.169156519395002538189312079030,\n 0.182603415044923588866763667969,\n 0.189450610455068496285396723208\n ];\n\n if (q <= 0)\n return 0;\n\n // df must be > 1\n // there must be at least two values\n\n if (df < 2 || rr < 1 || cc < 2) return NaN;\n\n if (!Number.isFinite(q))\n return 1;\n\n if (df > dlarg)\n return tukeyWprob(q, rr, cc);\n\n // calculate leading constant\n\n var f2 = df * 0.5;\n var f2lf = ((f2 * Math.log(df)) - (df * Math.log(2))) - jStat.gammaln(f2);\n var f21 = f2 - 1.0;\n\n // integral is divided into unit, half-unit, quarter-unit, or\n // eighth-unit length intervals depending on the value of the\n // degrees of freedom.\n\n var ff4 = df * 0.25;\n var ulen;\n if (df <= dhaf) ulen = ulen1;\n else if (df <= dquar) ulen = ulen2;\n else if (df <= deigh) ulen = ulen3;\n else ulen = ulen4;\n\n f2lf += Math.log(ulen);\n\n // integrate over each subinterval\n\n var ans = 0.0;\n\n for (var i = 1; i <= 50; i++) {\n var otsum = 0.0;\n\n // legendre quadrature with order = nlegq\n // nodes (stored in xlegq) are symmetric around zero.\n\n var twa1 = (2 * i - 1) * ulen;\n\n for (var jj = 1; jj <= nlegq; jj++) {\n var j, t1;\n if (ihalfq < jj) {\n j = jj - ihalfq - 1;\n t1 = (f2lf + (f21 * Math.log(twa1 + (xlegq[j] * ulen))))\n - (((xlegq[j] * ulen) + twa1) * ff4);\n } else {\n j = jj - 1;\n t1 = (f2lf + (f21 * Math.log(twa1 - (xlegq[j] * ulen))))\n + (((xlegq[j] * ulen) - twa1) * ff4);\n }\n\n // if exp(t1) < 9e-14, then doesn't contribute to integral\n var qsqz;\n if (t1 >= eps1) {\n if (ihalfq < jj) {\n qsqz = q * Math.sqrt(((xlegq[j] * ulen) + twa1) * 0.5);\n } else {\n qsqz = q * Math.sqrt(((-(xlegq[j] * ulen)) + twa1) * 0.5);\n }\n\n // call wprob to find integral of range portion\n\n var wprb = tukeyWprob(qsqz, rr, cc);\n var rotsum = (wprb * alegq[j]) * Math.exp(t1);\n otsum += rotsum;\n }\n // end legendre integral for interval i\n // L200:\n }\n\n // if integral for interval i < 1e-14, then stop.\n // However, in order to avoid small area under left tail,\n // at least 1 / ulen intervals are calculated.\n if (i * ulen >= 1.0 && otsum <= eps2)\n break;\n\n // end of interval i\n // L330:\n\n ans += otsum;\n }\n\n if (otsum > eps2) { // not converged\n throw new Error('tukey.cdf failed to converge');\n }\n if (ans > 1)\n ans = 1;\n return ans;\n },\n\n inv: function(p, nmeans, df) {\n // Identical implementation as the R qtukey() function as of commit 68947\n var rr = 1;\n var cc = nmeans;\n\n var eps = 0.0001;\n var maxiter = 50;\n\n // df must be > 1 ; there must be at least two values\n if (df < 2 || rr < 1 || cc < 2) return NaN;\n\n if (p < 0 || p > 1) return NaN;\n if (p === 0) return 0;\n if (p === 1) return Infinity;\n\n // Initial value\n\n var x0 = tukeyQinv(p, cc, df);\n\n // Find prob(value < x0)\n\n var valx0 = jStat.tukey.cdf(x0, nmeans, df) - p;\n\n // Find the second iterate and prob(value < x1).\n // If the first iterate has probability value\n // exceeding p then second iterate is 1 less than\n // first iterate; otherwise it is 1 greater.\n\n var x1;\n if (valx0 > 0.0)\n x1 = Math.max(0.0, x0 - 1.0);\n else\n x1 = x0 + 1.0;\n var valx1 = jStat.tukey.cdf(x1, nmeans, df) - p;\n\n // Find new iterate\n\n var ans;\n for(var iter = 1; iter < maxiter; iter++) {\n ans = x1 - ((valx1 * (x1 - x0)) / (valx1 - valx0));\n valx0 = valx1;\n\n // New iterate must be >= 0\n\n x0 = x1;\n if (ans < 0.0) {\n ans = 0.0;\n valx1 = -p;\n }\n // Find prob(value < new iterate)\n\n valx1 = jStat.tukey.cdf(ans, nmeans, df) - p;\n x1 = ans;\n\n // If the difference between two successive\n // iterates is less than eps, stop\n\n var xabs = Math.abs(x1 - x0);\n if (xabs < eps)\n return ans;\n }\n\n throw new Error('tukey.inv failed to converge');\n }\n});\n\n}(jStat, Math));\n/* Provides functions for the solution of linear system of equations, integration, extrapolation,\n * interpolation, eigenvalue problems, differential equations and PCA analysis. */\n\n(function(jStat, Math) {\n\nvar push = Array.prototype.push;\nvar isArray = jStat.utils.isArray;\n\nfunction isUsable(arg) {\n return isArray(arg) || arg instanceof jStat;\n}\n\njStat.extend({\n\n // add a vector/matrix to a vector/matrix or scalar\n add: function add(arr, arg) {\n // check if arg is a vector or scalar\n if (isUsable(arg)) {\n if (!isUsable(arg[0])) arg = [ arg ];\n return jStat.map(arr, function(value, row, col) {\n return value + arg[row][col];\n });\n }\n return jStat.map(arr, function(value) { return value + arg; });\n },\n\n // subtract a vector or scalar from the vector\n subtract: function subtract(arr, arg) {\n // check if arg is a vector or scalar\n if (isUsable(arg)) {\n if (!isUsable(arg[0])) arg = [ arg ];\n return jStat.map(arr, function(value, row, col) {\n return value - arg[row][col] || 0;\n });\n }\n return jStat.map(arr, function(value) { return value - arg; });\n },\n\n // matrix division\n divide: function divide(arr, arg) {\n if (isUsable(arg)) {\n if (!isUsable(arg[0])) arg = [ arg ];\n return jStat.multiply(arr, jStat.inv(arg));\n }\n return jStat.map(arr, function(value) { return value / arg; });\n },\n\n // matrix multiplication\n multiply: function multiply(arr, arg) {\n var row, col, nrescols, sum, nrow, ncol, res, rescols;\n // eg: arr = 2 arg = 3 -> 6 for res[0][0] statement closure\n if (arr.length === undefined && arg.length === undefined) {\n return arr * arg;\n }\n nrow = arr.length,\n ncol = arr[0].length,\n res = jStat.zeros(nrow, nrescols = (isUsable(arg)) ? arg[0].length : ncol),\n rescols = 0;\n if (isUsable(arg)) {\n for (; rescols < nrescols; rescols++) {\n for (row = 0; row < nrow; row++) {\n sum = 0;\n for (col = 0; col < ncol; col++)\n sum += arr[row][col] * arg[col][rescols];\n res[row][rescols] = sum;\n }\n }\n return (nrow === 1 && rescols === 1) ? res[0][0] : res;\n }\n return jStat.map(arr, function(value) { return value * arg; });\n },\n\n // outer([1,2,3],[4,5,6])\n // ===\n // [[1],[2],[3]] times [[4,5,6]]\n // ->\n // [[4,5,6],[8,10,12],[12,15,18]]\n outer:function outer(A, B) {\n return jStat.multiply(A.map(function(t){ return [t] }), [B]);\n },\n\n\n // Returns the dot product of two matricies\n dot: function dot(arr, arg) {\n if (!isUsable(arr[0])) arr = [ arr ];\n if (!isUsable(arg[0])) arg = [ arg ];\n // convert column to row vector\n var left = (arr[0].length === 1 && arr.length !== 1) ? jStat.transpose(arr) : arr,\n right = (arg[0].length === 1 && arg.length !== 1) ? jStat.transpose(arg) : arg,\n res = [],\n row = 0,\n nrow = left.length,\n ncol = left[0].length,\n sum, col;\n for (; row < nrow; row++) {\n res[row] = [];\n sum = 0;\n for (col = 0; col < ncol; col++)\n sum += left[row][col] * right[row][col];\n res[row] = sum;\n }\n return (res.length === 1) ? res[0] : res;\n },\n\n // raise every element by a scalar\n pow: function pow(arr, arg) {\n return jStat.map(arr, function(value) { return Math.pow(value, arg); });\n },\n\n // exponentiate every element\n exp: function exp(arr) {\n return jStat.map(arr, function(value) { return Math.exp(value); });\n },\n\n // generate the natural log of every element\n log: function exp(arr) {\n return jStat.map(arr, function(value) { return Math.log(value); });\n },\n\n // generate the absolute values of the vector\n abs: function abs(arr) {\n return jStat.map(arr, function(value) { return Math.abs(value); });\n },\n\n // computes the p-norm of the vector\n // In the case that a matrix is passed, uses the first row as the vector\n norm: function norm(arr, p) {\n var nnorm = 0,\n i = 0;\n // check the p-value of the norm, and set for most common case\n if (isNaN(p)) p = 2;\n // check if multi-dimensional array, and make vector correction\n if (isUsable(arr[0])) arr = arr[0];\n // vector norm\n for (; i < arr.length; i++) {\n nnorm += Math.pow(Math.abs(arr[i]), p);\n }\n return Math.pow(nnorm, 1 / p);\n },\n\n // computes the angle between two vectors in rads\n // In case a matrix is passed, this uses the first row as the vector\n angle: function angle(arr, arg) {\n return Math.acos(jStat.dot(arr, arg) / (jStat.norm(arr) * jStat.norm(arg)));\n },\n\n // augment one matrix by another\n // Note: this function returns a matrix, not a jStat object\n aug: function aug(a, b) {\n var newarr = [];\n var i;\n for (i = 0; i < a.length; i++) {\n newarr.push(a[i].slice());\n }\n for (i = 0; i < newarr.length; i++) {\n push.apply(newarr[i], b[i]);\n }\n return newarr;\n },\n\n // The inv() function calculates the inverse of a matrix\n // Create the inverse by augmenting the matrix by the identity matrix of the\n // appropriate size, and then use G-J elimination on the augmented matrix.\n inv: function inv(a) {\n var rows = a.length;\n var cols = a[0].length;\n var b = jStat.identity(rows, cols);\n var c = jStat.gauss_jordan(a, b);\n var result = [];\n var i = 0;\n var j;\n\n //We need to copy the inverse portion to a new matrix to rid G-J artifacts\n for (; i < rows; i++) {\n result[i] = [];\n for (j = cols; j < c[0].length; j++)\n result[i][j - cols] = c[i][j];\n }\n return result;\n },\n\n // calculate the determinant of a matrix\n det: function det(a) {\n if (a.length === 2) {\n return a[0][0] * a[1][1] - a[0][1] * a[1][0];\n }\n\n var determinant = 0;\n for (var i = 0; i < a.length; i++) {\n // build a sub matrix without column `i`\n var submatrix = [];\n for (var row = 1; row < a.length; row++) {\n submatrix[row - 1] = [];\n for (var col = 0; col < a.length; col++) {\n if (col < i) {\n submatrix[row - 1][col] = a[row][col];\n } else if (col > i) {\n submatrix[row - 1][col - 1] = a[row][col];\n }\n }\n }\n\n // alternate between + and - between determinants\n var sign = i % 2 ? -1 : 1;\n determinant += det(submatrix) * a[0][i] * sign;\n }\n\n return determinant\n },\n\n gauss_elimination: function gauss_elimination(a, b) {\n var i = 0,\n j = 0,\n n = a.length,\n m = a[0].length,\n factor = 1,\n sum = 0,\n x = [],\n maug, pivot, temp, k;\n a = jStat.aug(a, b);\n maug = a[0].length;\n for(i = 0; i < n; i++) {\n pivot = a[i][i];\n j = i;\n for (k = i + 1; k < m; k++) {\n if (pivot < Math.abs(a[k][i])) {\n pivot = a[k][i];\n j = k;\n }\n }\n if (j != i) {\n for(k = 0; k < maug; k++) {\n temp = a[i][k];\n a[i][k] = a[j][k];\n a[j][k] = temp;\n }\n }\n for (j = i + 1; j < n; j++) {\n factor = a[j][i] / a[i][i];\n for(k = i; k < maug; k++) {\n a[j][k] = a[j][k] - factor * a[i][k];\n }\n }\n }\n for (i = n - 1; i >= 0; i--) {\n sum = 0;\n for (j = i + 1; j<= n - 1; j++) {\n sum = sum + x[j] * a[i][j];\n }\n x[i] =(a[i][maug - 1] - sum) / a[i][i];\n }\n return x;\n },\n\n gauss_jordan: function gauss_jordan(a, b) {\n var m = jStat.aug(a, b);\n var h = m.length;\n var w = m[0].length;\n var c = 0;\n var x, y, y2;\n // find max pivot\n for (y = 0; y < h; y++) {\n var maxrow = y;\n for (y2 = y+1; y2 < h; y2++) {\n if (Math.abs(m[y2][y]) > Math.abs(m[maxrow][y]))\n maxrow = y2;\n }\n var tmp = m[y];\n m[y] = m[maxrow];\n m[maxrow] = tmp\n for (y2 = y+1; y2 < h; y2++) {\n c = m[y2][y] / m[y][y];\n for (x = y; x < w; x++) {\n m[y2][x] -= m[y][x] * c;\n }\n }\n }\n // backsubstitute\n for (y = h-1; y >= 0; y--) {\n c = m[y][y];\n for (y2 = 0; y2 < y; y2++) {\n for (x = w-1; x > y-1; x--) {\n m[y2][x] -= m[y][x] * m[y2][y] / c;\n }\n }\n m[y][y] /= c;\n for (x = h; x < w; x++) {\n m[y][x] /= c;\n }\n }\n return m;\n },\n\n // solve equation\n // Ax=b\n // A is upper triangular matrix\n // A=[[1,2,3],[0,4,5],[0,6,7]]\n // b=[1,2,3]\n // triaUpSolve(A,b) // -> [2.666,0.1666,1.666]\n // if you use matrix style\n // A=[[1,2,3],[0,4,5],[0,6,7]]\n // b=[[1],[2],[3]]\n // will return [[2.666],[0.1666],[1.666]]\n triaUpSolve: function triaUpSolve(A, b) {\n var size = A[0].length;\n var x = jStat.zeros(1, size)[0];\n var parts;\n var matrix_mode = false;\n\n if (b[0].length != undefined) {\n b = b.map(function(i){ return i[0] });\n matrix_mode = true;\n }\n\n jStat.arange(size - 1, -1, -1).forEach(function(i) {\n parts = jStat.arange(i + 1, size).map(function(j) {\n return x[j] * A[i][j];\n });\n x[i] = (b[i] - jStat.sum(parts)) / A[i][i];\n });\n\n if (matrix_mode)\n return x.map(function(i){ return [i] });\n return x;\n },\n\n triaLowSolve: function triaLowSolve(A, b) {\n // like to triaUpSolve but A is lower triangular matrix\n var size = A[0].length;\n var x = jStat.zeros(1, size)[0];\n var parts;\n\n var matrix_mode=false;\n if (b[0].length != undefined) {\n b = b.map(function(i){ return i[0] });\n matrix_mode = true;\n }\n\n jStat.arange(size).forEach(function(i) {\n parts = jStat.arange(i).map(function(j) {\n return A[i][j] * x[j];\n });\n x[i] = (b[i] - jStat.sum(parts)) / A[i][i];\n })\n\n if (matrix_mode)\n return x.map(function(i){ return [i] });\n return x;\n },\n\n\n // A -> [L,U]\n // A=LU\n // L is lower triangular matrix\n // U is upper triangular matrix\n lu: function lu(A) {\n var size = A.length;\n //var L=jStat.diagonal(jStat.ones(1,size)[0]);\n var L = jStat.identity(size);\n var R = jStat.zeros(A.length, A[0].length);\n var parts;\n jStat.arange(size).forEach(function(t) {\n R[0][t] = A[0][t];\n });\n jStat.arange(1, size).forEach(function(l) {\n jStat.arange(l).forEach(function(i) {\n parts = jStat.arange(i).map(function(jj) {\n return L[l][jj] * R[jj][i];\n });\n L[l][i] = (A[l][i] - jStat.sum(parts)) / R[i][i];\n });\n jStat.arange(l, size).forEach(function(j) {\n parts = jStat.arange(l).map(function(jj) {\n return L[l][jj] * R[jj][j];\n });\n R[l][j] = A[parts.length][j] - jStat.sum(parts);\n });\n });\n return [L, R];\n },\n\n // A -> T\n // A=TT'\n // T is lower triangular matrix\n cholesky: function cholesky(A) {\n var size = A.length;\n var T = jStat.zeros(A.length, A[0].length);\n var parts;\n jStat.arange(size).forEach(function(i) {\n parts = jStat.arange(i).map(function(t) {\n return Math.pow(T[i][t],2);\n });\n T[i][i] = Math.sqrt(A[i][i] - jStat.sum(parts));\n jStat.arange(i + 1, size).forEach(function(j) {\n parts = jStat.arange(i).map(function(t) {\n return T[i][t] * T[j][t];\n });\n T[j][i] = (A[i][j] - jStat.sum(parts)) / T[i][i];\n });\n });\n return T;\n },\n\n\n gauss_jacobi: function gauss_jacobi(a, b, x, r) {\n var i = 0;\n var j = 0;\n var n = a.length;\n var l = [];\n var u = [];\n var d = [];\n var xv, c, h, xk;\n for (; i < n; i++) {\n l[i] = [];\n u[i] = [];\n d[i] = [];\n for (j = 0; j < n; j++) {\n if (i > j) {\n l[i][j] = a[i][j];\n u[i][j] = d[i][j] = 0;\n } else if (i < j) {\n u[i][j] = a[i][j];\n l[i][j] = d[i][j] = 0;\n } else {\n d[i][j] = a[i][j];\n l[i][j] = u[i][j] = 0;\n }\n }\n }\n h = jStat.multiply(jStat.multiply(jStat.inv(d), jStat.add(l, u)), -1);\n c = jStat.multiply(jStat.inv(d), b);\n xv = x;\n xk = jStat.add(jStat.multiply(h, x), c);\n i = 2;\n while (Math.abs(jStat.norm(jStat.subtract(xk,xv))) > r) {\n xv = xk;\n xk = jStat.add(jStat.multiply(h, xv), c);\n i++;\n }\n return xk;\n },\n\n gauss_seidel: function gauss_seidel(a, b, x, r) {\n var i = 0;\n var n = a.length;\n var l = [];\n var u = [];\n var d = [];\n var j, xv, c, h, xk;\n for (; i < n; i++) {\n l[i] = [];\n u[i] = [];\n d[i] = [];\n for (j = 0; j < n; j++) {\n if (i > j) {\n l[i][j] = a[i][j];\n u[i][j] = d[i][j] = 0;\n } else if (i < j) {\n u[i][j] = a[i][j];\n l[i][j] = d[i][j] = 0;\n } else {\n d[i][j] = a[i][j];\n l[i][j] = u[i][j] = 0;\n }\n }\n }\n h = jStat.multiply(jStat.multiply(jStat.inv(jStat.add(d, l)), u), -1);\n c = jStat.multiply(jStat.inv(jStat.add(d, l)), b);\n xv = x;\n xk = jStat.add(jStat.multiply(h, x), c);\n i = 2;\n while (Math.abs(jStat.norm(jStat.subtract(xk, xv))) > r) {\n xv = xk;\n xk = jStat.add(jStat.multiply(h, xv), c);\n i = i + 1;\n }\n return xk;\n },\n\n SOR: function SOR(a, b, x, r, w) {\n var i = 0;\n var n = a.length;\n var l = [];\n var u = [];\n var d = [];\n var j, xv, c, h, xk;\n for (; i < n; i++) {\n l[i] = [];\n u[i] = [];\n d[i] = [];\n for (j = 0; j < n; j++) {\n if (i > j) {\n l[i][j] = a[i][j];\n u[i][j] = d[i][j] = 0;\n } else if (i < j) {\n u[i][j] = a[i][j];\n l[i][j] = d[i][j] = 0;\n } else {\n d[i][j] = a[i][j];\n l[i][j] = u[i][j] = 0;\n }\n }\n }\n h = jStat.multiply(jStat.inv(jStat.add(d, jStat.multiply(l, w))),\n jStat.subtract(jStat.multiply(d, 1 - w),\n jStat.multiply(u, w)));\n c = jStat.multiply(jStat.multiply(jStat.inv(jStat.add(d,\n jStat.multiply(l, w))), b), w);\n xv = x;\n xk = jStat.add(jStat.multiply(h, x), c);\n i = 2;\n while (Math.abs(jStat.norm(jStat.subtract(xk, xv))) > r) {\n xv = xk;\n xk = jStat.add(jStat.multiply(h, xv), c);\n i++;\n }\n return xk;\n },\n\n householder: function householder(a) {\n var m = a.length;\n var n = a[0].length;\n var i = 0;\n var w = [];\n var p = [];\n var alpha, r, k, j, factor;\n for (; i < m - 1; i++) {\n alpha = 0;\n for (j = i + 1; j < n; j++)\n alpha += (a[j][i] * a[j][i]);\n factor = (a[i + 1][i] > 0) ? -1 : 1;\n alpha = factor * Math.sqrt(alpha);\n r = Math.sqrt((((alpha * alpha) - a[i + 1][i] * alpha) / 2));\n w = jStat.zeros(m, 1);\n w[i + 1][0] = (a[i + 1][i] - alpha) / (2 * r);\n for (k = i + 2; k < m; k++) w[k][0] = a[k][i] / (2 * r);\n p = jStat.subtract(jStat.identity(m, n),\n jStat.multiply(jStat.multiply(w, jStat.transpose(w)), 2));\n a = jStat.multiply(p, jStat.multiply(a, p));\n }\n return a;\n },\n\n // A -> [Q,R]\n // Q is orthogonal matrix\n // R is upper triangular\n QR: (function() {\n // x -> Q\n // find a orthogonal matrix Q st.\n // Qx=y\n // y is [||x||,0,0,...]\n\n // quick ref\n var sum = jStat.sum;\n var range = jStat.arange;\n\n function qr2(x) {\n // quick impletation\n // https://www.stat.wisc.edu/~larget/math496/qr.html\n\n var n = x.length;\n var p = x[0].length;\n\n var r = jStat.zeros(p, p);\n x = jStat.copy(x);\n\n var i,j,k;\n for(j = 0; j < p; j++){\n r[j][j] = Math.sqrt(sum(range(n).map(function(i){\n return x[i][j] * x[i][j];\n })));\n for(i = 0; i < n; i++){\n x[i][j] = x[i][j] / r[j][j];\n }\n for(k = j+1; k < p; k++){\n r[j][k] = sum(range(n).map(function(i){\n return x[i][j] * x[i][k];\n }));\n for(i = 0; i < n; i++){\n x[i][k] = x[i][k] - x[i][j]*r[j][k];\n }\n }\n }\n return [x, r];\n }\n\n return qr2;\n }()),\n\n lstsq: (function() {\n // solve least squard problem for Ax=b as QR decomposition way if b is\n // [[b1],[b2],[b3]] form will return [[x1],[x2],[x3]] array form solution\n // else b is [b1,b2,b3] form will return [x1,x2,x3] array form solution\n function R_I(A) {\n A = jStat.copy(A);\n var size = A.length;\n var I = jStat.identity(size);\n jStat.arange(size - 1, -1, -1).forEach(function(i) {\n jStat.sliceAssign(\n I, { row: i }, jStat.divide(jStat.slice(I, { row: i }), A[i][i]));\n jStat.sliceAssign(\n A, { row: i }, jStat.divide(jStat.slice(A, { row: i }), A[i][i]));\n jStat.arange(i).forEach(function(j) {\n var c = jStat.multiply(A[j][i], -1);\n var Aj = jStat.slice(A, { row: j });\n var cAi = jStat.multiply(jStat.slice(A, { row: i }), c);\n jStat.sliceAssign(A, { row: j }, jStat.add(Aj, cAi));\n var Ij = jStat.slice(I, { row: j });\n var cIi = jStat.multiply(jStat.slice(I, { row: i }), c);\n jStat.sliceAssign(I, { row: j }, jStat.add(Ij, cIi));\n })\n });\n return I;\n }\n\n function qr_solve(A, b){\n var array_mode = false;\n if (b[0].length === undefined) {\n // [c1,c2,c3] mode\n b = b.map(function(x){ return [x] });\n array_mode = true;\n }\n var QR = jStat.QR(A);\n var Q = QR[0];\n var R = QR[1];\n var attrs = A[0].length;\n var Q1 = jStat.slice(Q,{col:{end:attrs}});\n var R1 = jStat.slice(R,{row:{end:attrs}});\n var RI = R_I(R1);\n var Q2 = jStat.transpose(Q1);\n\n if(Q2[0].length === undefined){\n Q2 = [Q2]; // The confusing jStat.multifly implementation threat nature process again.\n }\n\n var x = jStat.multiply(jStat.multiply(RI, Q2), b);\n\n if(x.length === undefined){\n x = [[x]]; // The confusing jStat.multifly implementation threat nature process again.\n }\n\n\n if (array_mode)\n return x.map(function(i){ return i[0] });\n return x;\n }\n\n return qr_solve;\n }()),\n\n jacobi: function jacobi(a) {\n var condition = 1;\n var n = a.length;\n var e = jStat.identity(n, n);\n var ev = [];\n var b, i, j, p, q, maxim, theta, s;\n // condition === 1 only if tolerance is not reached\n while (condition === 1) {\n maxim = a[0][1];\n p = 0;\n q = 1;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i != j) {\n if (maxim < Math.abs(a[i][j])) {\n maxim = Math.abs(a[i][j]);\n p = i;\n q = j;\n }\n }\n }\n }\n if (a[p][p] === a[q][q])\n theta = (a[p][q] > 0) ? Math.PI / 4 : -Math.PI / 4;\n else\n theta = Math.atan(2 * a[p][q] / (a[p][p] - a[q][q])) / 2;\n s = jStat.identity(n, n);\n s[p][p] = Math.cos(theta);\n s[p][q] = -Math.sin(theta);\n s[q][p] = Math.sin(theta);\n s[q][q] = Math.cos(theta);\n // eigen vector matrix\n e = jStat.multiply(e, s);\n b = jStat.multiply(jStat.multiply(jStat.inv(s), a), s);\n a = b;\n condition = 0;\n for (i = 1; i < n; i++) {\n for (j = 1; j < n; j++) {\n if (i != j && Math.abs(a[i][j]) > 0.001) {\n condition = 1;\n }\n }\n }\n }\n for (i = 0; i < n; i++) ev.push(a[i][i]);\n //returns both the eigenvalue and eigenmatrix\n return [e, ev];\n },\n\n rungekutta: function rungekutta(f, h, p, t_j, u_j, order) {\n var k1, k2, u_j1, k3, k4;\n if (order === 2) {\n while (t_j <= p) {\n k1 = h * f(t_j, u_j);\n k2 = h * f(t_j + h, u_j + k1);\n u_j1 = u_j + (k1 + k2) / 2;\n u_j = u_j1;\n t_j = t_j + h;\n }\n }\n if (order === 4) {\n while (t_j <= p) {\n k1 = h * f(t_j, u_j);\n k2 = h * f(t_j + h / 2, u_j + k1 / 2);\n k3 = h * f(t_j + h / 2, u_j + k2 / 2);\n k4 = h * f(t_j +h, u_j + k3);\n u_j1 = u_j + (k1 + 2 * k2 + 2 * k3 + k4) / 6;\n u_j = u_j1;\n t_j = t_j + h;\n }\n }\n return u_j;\n },\n\n romberg: function romberg(f, a, b, order) {\n var i = 0;\n var h = (b - a) / 2;\n var x = [];\n var h1 = [];\n var g = [];\n var m, a1, j, k, I;\n while (i < order / 2) {\n I = f(a);\n for (j = a, k = 0; j <= b; j = j + h, k++) x[k] = j;\n m = x.length;\n for (j = 1; j < m - 1; j++) {\n I += (((j % 2) !== 0) ? 4 : 2) * f(x[j]);\n }\n I = (h / 3) * (I + f(b));\n g[i] = I;\n h /= 2;\n i++;\n }\n a1 = g.length;\n m = 1;\n while (a1 !== 1) {\n for (j = 0; j < a1 - 1; j++)\n h1[j] = ((Math.pow(4, m)) * g[j + 1] - g[j]) / (Math.pow(4, m) - 1);\n a1 = h1.length;\n g = h1;\n h1 = [];\n m++;\n }\n return g;\n },\n\n richardson: function richardson(X, f, x, h) {\n function pos(X, x) {\n var i = 0;\n var n = X.length;\n var p;\n for (; i < n; i++)\n if (X[i] === x) p = i;\n return p;\n }\n var h_min = Math.abs(x - X[pos(X, x) + 1]);\n var i = 0;\n var g = [];\n var h1 = [];\n var y1, y2, m, a, j;\n while (h >= h_min) {\n y1 = pos(X, x + h);\n y2 = pos(X, x);\n g[i] = (f[y1] - 2 * f[y2] + f[2 * y2 - y1]) / (h * h);\n h /= 2;\n i++;\n }\n a = g.length;\n m = 1;\n while (a != 1) {\n for (j = 0; j < a - 1; j++)\n h1[j] = ((Math.pow(4, m)) * g[j + 1] - g[j]) / (Math.pow(4, m) - 1);\n a = h1.length;\n g = h1;\n h1 = [];\n m++;\n }\n return g;\n },\n\n simpson: function simpson(f, a, b, n) {\n var h = (b - a) / n;\n var I = f(a);\n var x = [];\n var j = a;\n var k = 0;\n var i = 1;\n var m;\n for (; j <= b; j = j + h, k++)\n x[k] = j;\n m = x.length;\n for (; i < m - 1; i++) {\n I += ((i % 2 !== 0) ? 4 : 2) * f(x[i]);\n }\n return (h / 3) * (I + f(b));\n },\n\n hermite: function hermite(X, F, dF, value) {\n var n = X.length;\n var p = 0;\n var i = 0;\n var l = [];\n var dl = [];\n var A = [];\n var B = [];\n var j;\n for (; i < n; i++) {\n l[i] = 1;\n for (j = 0; j < n; j++) {\n if (i != j) l[i] *= (value - X[j]) / (X[i] - X[j]);\n }\n dl[i] = 0;\n for (j = 0; j < n; j++) {\n if (i != j) dl[i] += 1 / (X [i] - X[j]);\n }\n A[i] = (1 - 2 * (value - X[i]) * dl[i]) * (l[i] * l[i]);\n B[i] = (value - X[i]) * (l[i] * l[i]);\n p += (A[i] * F[i] + B[i] * dF[i]);\n }\n return p;\n },\n\n lagrange: function lagrange(X, F, value) {\n var p = 0;\n var i = 0;\n var j, l;\n var n = X.length;\n for (; i < n; i++) {\n l = F[i];\n for (j = 0; j < n; j++) {\n // calculating the lagrange polynomial L_i\n if (i != j) l *= (value - X[j]) / (X[i] - X[j]);\n }\n // adding the lagrange polynomials found above\n p += l;\n }\n return p;\n },\n\n cubic_spline: function cubic_spline(X, F, value) {\n var n = X.length;\n var i = 0, j;\n var A = [];\n var B = [];\n var alpha = [];\n var c = [];\n var h = [];\n var b = [];\n var d = [];\n for (; i < n - 1; i++)\n h[i] = X[i + 1] - X[i];\n alpha[0] = 0;\n for (i = 1; i < n - 1; i++) {\n alpha[i] = (3 / h[i]) * (F[i + 1] - F[i]) -\n (3 / h[i-1]) * (F[i] - F[i-1]);\n }\n for (i = 1; i < n - 1; i++) {\n A[i] = [];\n B[i] = [];\n A[i][i-1] = h[i-1];\n A[i][i] = 2 * (h[i - 1] + h[i]);\n A[i][i+1] = h[i];\n B[i][0] = alpha[i];\n }\n c = jStat.multiply(jStat.inv(A), B);\n for (j = 0; j < n - 1; j++) {\n b[j] = (F[j + 1] - F[j]) / h[j] - h[j] * (c[j + 1][0] + 2 * c[j][0]) / 3;\n d[j] = (c[j + 1][0] - c[j][0]) / (3 * h[j]);\n }\n for (j = 0; j < n; j++) {\n if (X[j] > value) break;\n }\n j -= 1;\n return F[j] + (value - X[j]) * b[j] + jStat.sq(value-X[j]) *\n c[j] + (value - X[j]) * jStat.sq(value - X[j]) * d[j];\n },\n\n gauss_quadrature: function gauss_quadrature() {\n throw new Error('gauss_quadrature not yet implemented');\n },\n\n PCA: function PCA(X) {\n var m = X.length;\n var n = X[0].length;\n var i = 0;\n var j, temp1;\n var u = [];\n var D = [];\n var result = [];\n var temp2 = [];\n var Y = [];\n var Bt = [];\n var B = [];\n var C = [];\n var V = [];\n var Vt = [];\n for (i = 0; i < m; i++) {\n u[i] = jStat.sum(X[i]) / n;\n }\n for (i = 0; i < n; i++) {\n B[i] = [];\n for(j = 0; j < m; j++) {\n B[i][j] = X[j][i] - u[j];\n }\n }\n B = jStat.transpose(B);\n for (i = 0; i < m; i++) {\n C[i] = [];\n for (j = 0; j < m; j++) {\n C[i][j] = (jStat.dot([B[i]], [B[j]])) / (n - 1);\n }\n }\n result = jStat.jacobi(C);\n V = result[0];\n D = result[1];\n Vt = jStat.transpose(V);\n for (i = 0; i < D.length; i++) {\n for (j = i; j < D.length; j++) {\n if(D[i] < D[j]) {\n temp1 = D[i];\n D[i] = D[j];\n D[j] = temp1;\n temp2 = Vt[i];\n Vt[i] = Vt[j];\n Vt[j] = temp2;\n }\n }\n }\n Bt = jStat.transpose(B);\n for (i = 0; i < m; i++) {\n Y[i] = [];\n for (j = 0; j < Bt.length; j++) {\n Y[i][j] = jStat.dot([Vt[i]], [Bt[j]]);\n }\n }\n return [X, D, Vt, Y];\n }\n});\n\n// extend jStat.fn with methods that require one argument\n(function(funcs) {\n for (var i = 0; i < funcs.length; i++) (function(passfunc) {\n jStat.fn[passfunc] = function(arg, func) {\n var tmpthis = this;\n // check for callback\n if (func) {\n setTimeout(function() {\n func.call(tmpthis, jStat.fn[passfunc].call(tmpthis, arg));\n }, 15);\n return this;\n }\n if (typeof jStat[passfunc](this, arg) === 'number')\n return jStat[passfunc](this, arg);\n else\n return jStat(jStat[passfunc](this, arg));\n };\n }(funcs[i]));\n}('add divide multiply subtract dot pow exp log abs norm angle'.split(' ')));\n\n}(jStat, Math));\n(function(jStat, Math) {\n\nvar slice = [].slice;\nvar isNumber = jStat.utils.isNumber;\nvar isArray = jStat.utils.isArray;\n\n// flag==true denotes use of sample standard deviation\n// Z Statistics\njStat.extend({\n // 2 different parameter lists:\n // (value, mean, sd)\n // (value, array, flag)\n zscore: function zscore() {\n var args = slice.call(arguments);\n if (isNumber(args[1])) {\n return (args[0] - args[1]) / args[2];\n }\n return (args[0] - jStat.mean(args[1])) / jStat.stdev(args[1], args[2]);\n },\n\n // 3 different paramter lists:\n // (value, mean, sd, sides)\n // (zscore, sides)\n // (value, array, sides, flag)\n ztest: function ztest() {\n var args = slice.call(arguments);\n var z;\n if (isArray(args[1])) {\n // (value, array, sides, flag)\n z = jStat.zscore(args[0],args[1],args[3]);\n return (args[2] === 1) ?\n (jStat.normal.cdf(-Math.abs(z), 0, 1)) :\n (jStat.normal.cdf(-Math.abs(z), 0, 1)*2);\n } else {\n if (args.length > 2) {\n // (value, mean, sd, sides)\n z = jStat.zscore(args[0],args[1],args[2]);\n return (args[3] === 1) ?\n (jStat.normal.cdf(-Math.abs(z),0,1)) :\n (jStat.normal.cdf(-Math.abs(z),0,1)* 2);\n } else {\n // (zscore, sides)\n z = args[0];\n return (args[1] === 1) ?\n (jStat.normal.cdf(-Math.abs(z),0,1)) :\n (jStat.normal.cdf(-Math.abs(z),0,1)*2);\n }\n }\n }\n});\n\njStat.extend(jStat.fn, {\n zscore: function zscore(value, flag) {\n return (value - this.mean()) / this.stdev(flag);\n },\n\n ztest: function ztest(value, sides, flag) {\n var zscore = Math.abs(this.zscore(value, flag));\n return (sides === 1) ?\n (jStat.normal.cdf(-zscore, 0, 1)) :\n (jStat.normal.cdf(-zscore, 0, 1) * 2);\n }\n});\n\n// T Statistics\njStat.extend({\n // 2 parameter lists\n // (value, mean, sd, n)\n // (value, array)\n tscore: function tscore() {\n var args = slice.call(arguments);\n return (args.length === 4) ?\n ((args[0] - args[1]) / (args[2] / Math.sqrt(args[3]))) :\n ((args[0] - jStat.mean(args[1])) /\n (jStat.stdev(args[1], true) / Math.sqrt(args[1].length)));\n },\n\n // 3 different paramter lists:\n // (value, mean, sd, n, sides)\n // (tscore, n, sides)\n // (value, array, sides)\n ttest: function ttest() {\n var args = slice.call(arguments);\n var tscore;\n if (args.length === 5) {\n tscore = Math.abs(jStat.tscore(args[0], args[1], args[2], args[3]));\n return (args[4] === 1) ?\n (jStat.studentt.cdf(-tscore, args[3]-1)) :\n (jStat.studentt.cdf(-tscore, args[3]-1)*2);\n }\n if (isNumber(args[1])) {\n tscore = Math.abs(args[0])\n return (args[2] == 1) ?\n (jStat.studentt.cdf(-tscore, args[1]-1)) :\n (jStat.studentt.cdf(-tscore, args[1]-1) * 2);\n }\n tscore = Math.abs(jStat.tscore(args[0], args[1]))\n return (args[2] == 1) ?\n (jStat.studentt.cdf(-tscore, args[1].length-1)) :\n (jStat.studentt.cdf(-tscore, args[1].length-1) * 2);\n }\n});\n\njStat.extend(jStat.fn, {\n tscore: function tscore(value) {\n return (value - this.mean()) / (this.stdev(true) / Math.sqrt(this.cols()));\n },\n\n ttest: function ttest(value, sides) {\n return (sides === 1) ?\n (1 - jStat.studentt.cdf(Math.abs(this.tscore(value)), this.cols()-1)) :\n (jStat.studentt.cdf(-Math.abs(this.tscore(value)), this.cols()-1)*2);\n }\n});\n\n// F Statistics\njStat.extend({\n // Paramter list is as follows:\n // (array1, array2, array3, ...)\n // or it is an array of arrays\n // array of arrays conversion\n anovafscore: function anovafscore() {\n var args = slice.call(arguments),\n expVar, sample, sampMean, sampSampMean, tmpargs, unexpVar, i, j;\n if (args.length === 1) {\n tmpargs = new Array(args[0].length);\n for (i = 0; i < args[0].length; i++) {\n tmpargs[i] = args[0][i];\n }\n args = tmpargs;\n }\n // Builds sample array\n sample = new Array();\n for (i = 0; i < args.length; i++) {\n sample = sample.concat(args[i]);\n }\n sampMean = jStat.mean(sample);\n // Computes the explained variance\n expVar = 0;\n for (i = 0; i < args.length; i++) {\n expVar = expVar + args[i].length * Math.pow(jStat.mean(args[i]) - sampMean, 2);\n }\n expVar /= (args.length - 1);\n // Computes unexplained variance\n unexpVar = 0;\n for (i = 0; i < args.length; i++) {\n sampSampMean = jStat.mean(args[i]);\n for (j = 0; j < args[i].length; j++) {\n unexpVar += Math.pow(args[i][j] - sampSampMean, 2);\n }\n }\n unexpVar /= (sample.length - args.length);\n return expVar / unexpVar;\n },\n\n // 2 different paramter setups\n // (array1, array2, array3, ...)\n // (anovafscore, df1, df2)\n anovaftest: function anovaftest() {\n var args = slice.call(arguments),\n df1, df2, n, i;\n if (isNumber(args[0])) {\n return 1 - jStat.centralF.cdf(args[0], args[1], args[2]);\n }\n var anovafscore = jStat.anovafscore(args);\n df1 = args.length - 1;\n n = 0;\n for (i = 0; i < args.length; i++) {\n n = n + args[i].length;\n }\n df2 = n - df1 - 1;\n return 1 - jStat.centralF.cdf(anovafscore, df1, df2);\n },\n\n ftest: function ftest(fscore, df1, df2) {\n return 1 - jStat.centralF.cdf(fscore, df1, df2);\n }\n});\n\njStat.extend(jStat.fn, {\n anovafscore: function anovafscore() {\n return jStat.anovafscore(this.toArray());\n },\n\n anovaftes: function anovaftes() {\n var n = 0;\n var i;\n for (i = 0; i < this.length; i++) {\n n = n + this[i].length;\n }\n return jStat.ftest(this.anovafscore(), this.length - 1, n - this.length);\n }\n});\n\n// Tukey's range test\njStat.extend({\n // 2 parameter lists\n // (mean1, mean2, n1, n2, sd)\n // (array1, array2, sd)\n qscore: function qscore() {\n var args = slice.call(arguments);\n var mean1, mean2, n1, n2, sd;\n if (isNumber(args[0])) {\n mean1 = args[0];\n mean2 = args[1];\n n1 = args[2];\n n2 = args[3];\n sd = args[4];\n } else {\n mean1 = jStat.mean(args[0]);\n mean2 = jStat.mean(args[1]);\n n1 = args[0].length;\n n2 = args[1].length;\n sd = args[2];\n }\n return Math.abs(mean1 - mean2) / (sd * Math.sqrt((1 / n1 + 1 / n2) / 2));\n },\n\n // 3 different parameter lists:\n // (qscore, n, k)\n // (mean1, mean2, n1, n2, sd, n, k)\n // (array1, array2, sd, n, k)\n qtest: function qtest() {\n var args = slice.call(arguments);\n\n var qscore;\n if (args.length === 3) {\n qscore = args[0];\n args = args.slice(1);\n } else if (args.length === 7) {\n qscore = jStat.qscore(args[0], args[1], args[2], args[3], args[4]);\n args = args.slice(5);\n } else {\n qscore = jStat.qscore(args[0], args[1], args[2]);\n args = args.slice(3);\n }\n\n var n = args[0];\n var k = args[1];\n\n return 1 - jStat.tukey.cdf(qscore, k, n - k);\n },\n\n tukeyhsd: function tukeyhsd(arrays) {\n var sd = jStat.pooledstdev(arrays);\n var means = arrays.map(function (arr) {return jStat.mean(arr);});\n var n = arrays.reduce(function (n, arr) {return n + arr.length;}, 0);\n\n var results = [];\n for (var i = 0; i < arrays.length; ++i) {\n for (var j = i + 1; j < arrays.length; ++j) {\n var p = jStat.qtest(means[i], means[j], arrays[i].length, arrays[j].length, sd, n, arrays.length);\n results.push([[i, j], p]);\n }\n }\n\n return results;\n }\n});\n\n// Error Bounds\njStat.extend({\n // 2 different parameter setups\n // (value, alpha, sd, n)\n // (value, alpha, array)\n normalci: function normalci() {\n var args = slice.call(arguments),\n ans = new Array(2),\n change;\n if (args.length === 4) {\n change = Math.abs(jStat.normal.inv(args[1] / 2, 0, 1) *\n args[2] / Math.sqrt(args[3]));\n } else {\n change = Math.abs(jStat.normal.inv(args[1] / 2, 0, 1) *\n jStat.stdev(args[2]) / Math.sqrt(args[2].length));\n }\n ans[0] = args[0] - change;\n ans[1] = args[0] + change;\n return ans;\n },\n\n // 2 different parameter setups\n // (value, alpha, sd, n)\n // (value, alpha, array)\n tci: function tci() {\n var args = slice.call(arguments),\n ans = new Array(2),\n change;\n if (args.length === 4) {\n change = Math.abs(jStat.studentt.inv(args[1] / 2, args[3] - 1) *\n args[2] / Math.sqrt(args[3]));\n } else {\n change = Math.abs(jStat.studentt.inv(args[1] / 2, args[2].length - 1) *\n jStat.stdev(args[2], true) / Math.sqrt(args[2].length));\n }\n ans[0] = args[0] - change;\n ans[1] = args[0] + change;\n return ans;\n },\n\n significant: function significant(pvalue, alpha) {\n return pvalue < alpha;\n }\n});\n\njStat.extend(jStat.fn, {\n normalci: function normalci(value, alpha) {\n return jStat.normalci(value, alpha, this.toArray());\n },\n\n tci: function tci(value, alpha) {\n return jStat.tci(value, alpha, this.toArray());\n }\n});\n\n// internal method for calculating the z-score for a difference of proportions test\nfunction differenceOfProportions(p1, n1, p2, n2) {\n if (p1 > 1 || p2 > 1 || p1 <= 0 || p2 <= 0) {\n throw new Error(\"Proportions should be greater than 0 and less than 1\")\n }\n var pooled = (p1 * n1 + p2 * n2) / (n1 + n2);\n var se = Math.sqrt(pooled * (1 - pooled) * ((1/n1) + (1/n2)));\n return (p1 - p2) / se;\n}\n\n// Difference of Proportions\njStat.extend(jStat.fn, {\n oneSidedDifferenceOfProportions: function oneSidedDifferenceOfProportions(p1, n1, p2, n2) {\n var z = differenceOfProportions(p1, n1, p2, n2);\n return jStat.ztest(z, 1);\n },\n\n twoSidedDifferenceOfProportions: function twoSidedDifferenceOfProportions(p1, n1, p2, n2) {\n var z = differenceOfProportions(p1, n1, p2, n2);\n return jStat.ztest(z, 2);\n }\n});\n\n}(jStat, Math));\njStat.models = (function(){\n function sub_regress(exog) {\n var var_count = exog[0].length;\n var modelList = jStat.arange(var_count).map(function(endog_index) {\n var exog_index =\n jStat.arange(var_count).filter(function(i){return i!==endog_index});\n return ols(jStat.col(exog, endog_index).map(function(x){ return x[0] }),\n jStat.col(exog, exog_index))\n });\n return modelList;\n }\n\n // do OLS model regress\n // exog have include const columns ,it will not generate it .In fact, exog is\n // \"design matrix\" look at\n //https://en.wikipedia.org/wiki/Design_matrix\n function ols(endog, exog) {\n var nobs = endog.length;\n var df_model = exog[0].length - 1;\n var df_resid = nobs-df_model - 1;\n var coef = jStat.lstsq(exog, endog);\n var predict =\n jStat.multiply(exog, coef.map(function(x) { return [x] }))\n .map(function(p) { return p[0] });\n var resid = jStat.subtract(endog, predict);\n var ybar = jStat.mean(endog);\n // constant cause problem\n // var SST = jStat.sum(endog.map(function(y) {\n // return Math.pow(y-ybar,2);\n // }));\n var SSE = jStat.sum(predict.map(function(f) {\n return Math.pow(f - ybar, 2);\n }));\n var SSR = jStat.sum(endog.map(function(y, i) {\n return Math.pow(y - predict[i], 2);\n }));\n var SST = SSE + SSR;\n var R2 = (SSE / SST);\n return {\n exog:exog,\n endog:endog,\n nobs:nobs,\n df_model:df_model,\n df_resid:df_resid,\n coef:coef,\n predict:predict,\n resid:resid,\n ybar:ybar,\n SST:SST,\n SSE:SSE,\n SSR:SSR,\n R2:R2\n };\n }\n\n // H0: b_I=0\n // H1: b_I!=0\n function t_test(model) {\n var subModelList = sub_regress(model.exog);\n //var sigmaHat=jStat.stdev(model.resid);\n var sigmaHat = Math.sqrt(model.SSR / (model.df_resid));\n var seBetaHat = subModelList.map(function(mod) {\n var SST = mod.SST;\n var R2 = mod.R2;\n return sigmaHat / Math.sqrt(SST * (1 - R2));\n });\n var tStatistic = model.coef.map(function(coef, i) {\n return (coef - 0) / seBetaHat[i];\n });\n var pValue = tStatistic.map(function(t) {\n var leftppf = jStat.studentt.cdf(t, model.df_resid);\n return (leftppf > 0.5 ? 1 - leftppf : leftppf) * 2;\n });\n var c = jStat.studentt.inv(0.975, model.df_resid);\n var interval95 = model.coef.map(function(coef, i) {\n var d = c * seBetaHat[i];\n return [coef - d, coef + d];\n })\n return {\n se: seBetaHat,\n t: tStatistic,\n p: pValue,\n sigmaHat: sigmaHat,\n interval95: interval95\n };\n }\n\n function F_test(model) {\n var F_statistic =\n (model.R2 / model.df_model) / ((1 - model.R2) / model.df_resid);\n var fcdf = function(x, n1, n2) {\n return jStat.beta.cdf(x / (n2 / n1 + x), n1 / 2, n2 / 2)\n }\n var pvalue = 1 - fcdf(F_statistic, model.df_model, model.df_resid);\n return { F_statistic: F_statistic, pvalue: pvalue };\n }\n\n function ols_wrap(endog, exog) {\n var model = ols(endog,exog);\n var ttest = t_test(model);\n var ftest = F_test(model);\n // Provide the Wherry / Ezekiel / McNemar / Cohen Adjusted R^2\n // Which matches the 'adjusted R^2' provided by R's lm package\n var adjust_R2 =\n 1 - (1 - model.R2) * ((model.nobs - 1) / (model.df_resid));\n model.t = ttest;\n model.f = ftest;\n model.adjust_R2 = adjust_R2;\n return model;\n }\n\n return { ols: ols_wrap };\n})();\n//To regress, simply build X matrix\n//(append column of 1's) using\n//buildxmatrix and build the Y\n//matrix using buildymatrix\n//(simply the transpose)\n//and run regress.\n\n\n\n//Regressions\n\njStat.extend({\n buildxmatrix: function buildxmatrix(){\n //Parameters will be passed in as such\n //(array1,array2,array3,...)\n //as (x1,x2,x3,...)\n //needs to be (1,x1,x2,x3,...)\n var matrixRows = new Array(arguments.length);\n for(var i=0;i1){\n result = [];\n for (i = 0; i < A.rows(); i++) {\n result[i] = [];\n for (j = 0; j < B.cols(); j++) {\n sum = 0;\n for (k = 0; k < A.cols(); k++) {\n sum += A.toArray()[i][k] * B.toArray()[k][j];\n }\n result[i][j] = sum;\n }\n }\n return jStat(result);\n }\n result = [];\n for (i = 0; i < A.rows(); i++) {\n result[i] = [];\n for (j = 0; j < B.cols(); j++) {\n sum = 0;\n for (k = 0; k < A.cols(); k++) {\n sum += A.toArray()[i][k] * B.toArray()[j];\n }\n result[i][j] = sum;\n }\n }\n return jStat(result);\n }\n },\n\n //regress and regresst to be fixed\n\n regress: function regress(jMatX,jMatY){\n //print(\"regressin!\");\n //print(jMatX.toArray());\n var innerinv = jStat.xtranspxinv(jMatX);\n //print(innerinv);\n var xtransp = jMatX.transpose();\n var next = jStat.matrixmult(jStat(innerinv),xtransp);\n return jStat.matrixmult(next,jMatY);\n\n },\n\n regresst: function regresst(jMatX,jMatY,sides){\n var beta = jStat.regress(jMatX,jMatY);\n\n var compile = {};\n compile.anova = {};\n var jMatYBar = jStat.jMatYBar(jMatX, beta);\n compile.yBar = jMatYBar;\n var yAverage = jMatY.mean();\n compile.anova.residuals = jStat.residuals(jMatY, jMatYBar);\n\n compile.anova.ssr = jStat.ssr(jMatYBar, yAverage);\n compile.anova.msr = compile.anova.ssr / (jMatX[0].length - 1);\n\n compile.anova.sse = jStat.sse(jMatY, jMatYBar);\n compile.anova.mse =\n compile.anova.sse / (jMatY.length - (jMatX[0].length - 1) - 1);\n\n compile.anova.sst = jStat.sst(jMatY, yAverage);\n compile.anova.mst = compile.anova.sst / (jMatY.length - 1);\n\n compile.anova.r2 = 1 - (compile.anova.sse / compile.anova.sst);\n if (compile.anova.r2 < 0) compile.anova.r2 = 0;\n\n compile.anova.fratio = compile.anova.msr / compile.anova.mse;\n compile.anova.pvalue =\n jStat.anovaftest(compile.anova.fratio,\n jMatX[0].length - 1,\n jMatY.length - (jMatX[0].length - 1) - 1);\n\n compile.anova.rmse = Math.sqrt(compile.anova.mse);\n\n compile.anova.r2adj = 1 - (compile.anova.mse / compile.anova.mst);\n if (compile.anova.r2adj < 0) compile.anova.r2adj = 0;\n\n compile.stats = new Array(jMatX[0].length);\n var covar = jStat.xtranspxinv(jMatX);\n var sds, ts, ps;\n\n for(var i=0; i\n * Copyright OpenJS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n;(function() {\n\n /** Used as a safe reference for `undefined` in pre-ES5 environments. */\n var undefined;\n\n /** Used as the semantic version number. */\n var VERSION = '4.17.21';\n\n /** Used as the size to enable large array optimizations. */\n var LARGE_ARRAY_SIZE = 200;\n\n /** Error message constants. */\n var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',\n FUNC_ERROR_TEXT = 'Expected a function',\n INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`';\n\n /** Used to stand-in for `undefined` hash values. */\n var HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n /** Used as the maximum memoize cache size. */\n var MAX_MEMOIZE_SIZE = 500;\n\n /** Used as the internal argument placeholder. */\n var PLACEHOLDER = '__lodash_placeholder__';\n\n /** Used to compose bitmasks for cloning. */\n var CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n /** Used to compose bitmasks for value comparisons. */\n var COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n /** Used to compose bitmasks for function metadata. */\n var WRAP_BIND_FLAG = 1,\n WRAP_BIND_KEY_FLAG = 2,\n WRAP_CURRY_BOUND_FLAG = 4,\n WRAP_CURRY_FLAG = 8,\n WRAP_CURRY_RIGHT_FLAG = 16,\n WRAP_PARTIAL_FLAG = 32,\n WRAP_PARTIAL_RIGHT_FLAG = 64,\n WRAP_ARY_FLAG = 128,\n WRAP_REARG_FLAG = 256,\n WRAP_FLIP_FLAG = 512;\n\n /** Used as default options for `_.truncate`. */\n var DEFAULT_TRUNC_LENGTH = 30,\n DEFAULT_TRUNC_OMISSION = '...';\n\n /** Used to detect hot functions by number of calls within a span of milliseconds. */\n var HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n /** Used to indicate the type of lazy iteratees. */\n var LAZY_FILTER_FLAG = 1,\n LAZY_MAP_FLAG = 2,\n LAZY_WHILE_FLAG = 3;\n\n /** Used as references for various `Number` constants. */\n var INFINITY = 1 / 0,\n MAX_SAFE_INTEGER = 9007199254740991,\n MAX_INTEGER = 1.7976931348623157e+308,\n NAN = 0 / 0;\n\n /** Used as references for the maximum length and index of an array. */\n var MAX_ARRAY_LENGTH = 4294967295,\n MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,\n HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;\n\n /** Used to associate wrap methods with their bit flags. */\n var wrapFlags = [\n ['ary', WRAP_ARY_FLAG],\n ['bind', WRAP_BIND_FLAG],\n ['bindKey', WRAP_BIND_KEY_FLAG],\n ['curry', WRAP_CURRY_FLAG],\n ['curryRight', WRAP_CURRY_RIGHT_FLAG],\n ['flip', WRAP_FLIP_FLAG],\n ['partial', WRAP_PARTIAL_FLAG],\n ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],\n ['rearg', WRAP_REARG_FLAG]\n ];\n\n /** `Object#toString` result references. */\n var argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n domExcTag = '[object DOMException]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]',\n weakSetTag = '[object WeakSet]';\n\n var arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n /** Used to match empty string literals in compiled template source. */\n var reEmptyStringLeading = /\\b__p \\+= '';/g,\n reEmptyStringMiddle = /\\b(__p \\+=) '' \\+/g,\n reEmptyStringTrailing = /(__e\\(.*?\\)|\\b__t\\)) \\+\\n'';/g;\n\n /** Used to match HTML entities and HTML characters. */\n var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,\n reUnescapedHtml = /[&<>\"']/g,\n reHasEscapedHtml = RegExp(reEscapedHtml.source),\n reHasUnescapedHtml = RegExp(reUnescapedHtml.source);\n\n /** Used to match template delimiters. */\n var reEscape = /<%-([\\s\\S]+?)%>/g,\n reEvaluate = /<%([\\s\\S]+?)%>/g,\n reInterpolate = /<%=([\\s\\S]+?)%>/g;\n\n /** Used to match property names within property paths. */\n var reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/,\n rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n /**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\n var reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g,\n reHasRegExpChar = RegExp(reRegExpChar.source);\n\n /** Used to match leading whitespace. */\n var reTrimStart = /^\\s+/;\n\n /** Used to match a single whitespace character. */\n var reWhitespace = /\\s/;\n\n /** Used to match wrap detail comments. */\n var reWrapComment = /\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,\n reWrapDetails = /\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,\n reSplitDetails = /,? & /;\n\n /** Used to match words composed of alphanumeric characters. */\n var reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n /**\n * Used to validate the `validate` option in `_.template` variable.\n *\n * Forbids characters which could potentially change the meaning of the function argument definition:\n * - \"(),\" (modification of function parameters)\n * - \"=\" (default value)\n * - \"[]{}\" (destructuring of function parameters)\n * - \"/\" (beginning of a comment)\n * - whitespace\n */\n var reForbiddenIdentifierChars = /[()=,{}\\[\\]\\/\\s]/;\n\n /** Used to match backslashes in property paths. */\n var reEscapeChar = /\\\\(\\\\)?/g;\n\n /**\n * Used to match\n * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).\n */\n var reEsTemplate = /\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g;\n\n /** Used to match `RegExp` flags from their coerced string values. */\n var reFlags = /\\w*$/;\n\n /** Used to detect bad signed hexadecimal string values. */\n var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n /** Used to detect binary string values. */\n var reIsBinary = /^0b[01]+$/i;\n\n /** Used to detect host constructors (Safari). */\n var reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n /** Used to detect octal string values. */\n var reIsOctal = /^0o[0-7]+$/i;\n\n /** Used to detect unsigned integer values. */\n var reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n /** Used to match Latin Unicode letters (excluding mathematical operators). */\n var reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n /** Used to ensure capturing order of template delimiters. */\n var reNoMatch = /($^)/;\n\n /** Used to match unescaped characters in compiled string literals. */\n var reUnescapedString = /['\\n\\r\\u2028\\u2029\\\\]/g;\n\n /** Used to compose unicode character classes. */\n var rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsDingbatRange = '\\\\u2700-\\\\u27bf',\n rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n rsPunctuationRange = '\\\\u2000-\\\\u206f',\n rsSpaceRange = ' \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000',\n rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n rsVarRange = '\\\\ufe0e\\\\ufe0f',\n rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n /** Used to compose unicode capture groups. */\n var rsApos = \"['\\u2019]\",\n rsAstral = '[' + rsAstralRange + ']',\n rsBreak = '[' + rsBreakRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsDigits = '\\\\d+',\n rsDingbat = '[' + rsDingbatRange + ']',\n rsLower = '[' + rsLowerRange + ']',\n rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsUpper = '[' + rsUpperRange + ']',\n rsZWJ = '\\\\u200d';\n\n /** Used to compose unicode regexes. */\n var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n /** Used to match apostrophes. */\n var reApos = RegExp(rsApos, 'g');\n\n /**\n * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n */\n var reComboMark = RegExp(rsCombo, 'g');\n\n /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\n var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n /** Used to match complex or compound words. */\n var reUnicodeWord = RegExp([\n rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n rsUpper + '+' + rsOptContrUpper,\n rsOrdUpper,\n rsOrdLower,\n rsDigits,\n rsEmoji\n ].join('|'), 'g');\n\n /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\n var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n /** Used to detect strings that need a more robust regexp to match words. */\n var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n /** Used to assign default `context` object properties. */\n var contextProps = [\n 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',\n 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',\n 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',\n 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',\n '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'\n ];\n\n /** Used to make template sourceURLs easier to identify. */\n var templateCounter = -1;\n\n /** Used to identify `toStringTag` values of typed arrays. */\n var typedArrayTags = {};\n typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\n typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\n typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\n typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\n typedArrayTags[uint32Tag] = true;\n typedArrayTags[argsTag] = typedArrayTags[arrayTag] =\n typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\n typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\n typedArrayTags[errorTag] = typedArrayTags[funcTag] =\n typedArrayTags[mapTag] = typedArrayTags[numberTag] =\n typedArrayTags[objectTag] = typedArrayTags[regexpTag] =\n typedArrayTags[setTag] = typedArrayTags[stringTag] =\n typedArrayTags[weakMapTag] = false;\n\n /** Used to identify `toStringTag` values supported by `_.clone`. */\n var cloneableTags = {};\n cloneableTags[argsTag] = cloneableTags[arrayTag] =\n cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\n cloneableTags[boolTag] = cloneableTags[dateTag] =\n cloneableTags[float32Tag] = cloneableTags[float64Tag] =\n cloneableTags[int8Tag] = cloneableTags[int16Tag] =\n cloneableTags[int32Tag] = cloneableTags[mapTag] =\n cloneableTags[numberTag] = cloneableTags[objectTag] =\n cloneableTags[regexpTag] = cloneableTags[setTag] =\n cloneableTags[stringTag] = cloneableTags[symbolTag] =\n cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\n cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\n cloneableTags[errorTag] = cloneableTags[funcTag] =\n cloneableTags[weakMapTag] = false;\n\n /** Used to map Latin Unicode letters to basic Latin letters. */\n var deburredLetters = {\n // Latin-1 Supplement block.\n '\\xc0': 'A', '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n '\\xe0': 'a', '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n '\\xc7': 'C', '\\xe7': 'c',\n '\\xd0': 'D', '\\xf0': 'd',\n '\\xc8': 'E', '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n '\\xe8': 'e', '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n '\\xcc': 'I', '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n '\\xec': 'i', '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n '\\xd1': 'N', '\\xf1': 'n',\n '\\xd2': 'O', '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n '\\xf2': 'o', '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n '\\xd9': 'U', '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n '\\xf9': 'u', '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n '\\xdd': 'Y', '\\xfd': 'y', '\\xff': 'y',\n '\\xc6': 'Ae', '\\xe6': 'ae',\n '\\xde': 'Th', '\\xfe': 'th',\n '\\xdf': 'ss',\n // Latin Extended-A block.\n '\\u0100': 'A', '\\u0102': 'A', '\\u0104': 'A',\n '\\u0101': 'a', '\\u0103': 'a', '\\u0105': 'a',\n '\\u0106': 'C', '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n '\\u0107': 'c', '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n '\\u010e': 'D', '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n '\\u0112': 'E', '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n '\\u0113': 'e', '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n '\\u011c': 'G', '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n '\\u011d': 'g', '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n '\\u0124': 'H', '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n '\\u0128': 'I', '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n '\\u0129': 'i', '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n '\\u0134': 'J', '\\u0135': 'j',\n '\\u0136': 'K', '\\u0137': 'k', '\\u0138': 'k',\n '\\u0139': 'L', '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n '\\u013a': 'l', '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n '\\u0143': 'N', '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n '\\u0144': 'n', '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n '\\u014c': 'O', '\\u014e': 'O', '\\u0150': 'O',\n '\\u014d': 'o', '\\u014f': 'o', '\\u0151': 'o',\n '\\u0154': 'R', '\\u0156': 'R', '\\u0158': 'R',\n '\\u0155': 'r', '\\u0157': 'r', '\\u0159': 'r',\n '\\u015a': 'S', '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n '\\u015b': 's', '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n '\\u0162': 'T', '\\u0164': 'T', '\\u0166': 'T',\n '\\u0163': 't', '\\u0165': 't', '\\u0167': 't',\n '\\u0168': 'U', '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n '\\u0169': 'u', '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n '\\u0174': 'W', '\\u0175': 'w',\n '\\u0176': 'Y', '\\u0177': 'y', '\\u0178': 'Y',\n '\\u0179': 'Z', '\\u017b': 'Z', '\\u017d': 'Z',\n '\\u017a': 'z', '\\u017c': 'z', '\\u017e': 'z',\n '\\u0132': 'IJ', '\\u0133': 'ij',\n '\\u0152': 'Oe', '\\u0153': 'oe',\n '\\u0149': \"'n\", '\\u017f': 's'\n };\n\n /** Used to map characters to HTML entities. */\n var htmlEscapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''\n };\n\n /** Used to map HTML entities to characters. */\n var htmlUnescapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '"': '\"',\n ''': \"'\"\n };\n\n /** Used to escape characters for inclusion in compiled string literals. */\n var stringEscapes = {\n '\\\\': '\\\\',\n \"'\": \"'\",\n '\\n': 'n',\n '\\r': 'r',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n /** Built-in method references without a dependency on `root`. */\n var freeParseFloat = parseFloat,\n freeParseInt = parseInt;\n\n /** Detect free variable `global` from Node.js. */\n var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n /** Detect free variable `self`. */\n var freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n /** Used as a reference to the global object. */\n var root = freeGlobal || freeSelf || Function('return this')();\n\n /** Detect free variable `exports`. */\n var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n /** Detect free variable `module`. */\n var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n /** Detect the popular CommonJS extension `module.exports`. */\n var moduleExports = freeModule && freeModule.exports === freeExports;\n\n /** Detect free variable `process` from Node.js. */\n var freeProcess = moduleExports && freeGlobal.process;\n\n /** Used to access faster Node.js helpers. */\n var nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n }());\n\n /* Node.js helper references. */\n var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,\n nodeIsDate = nodeUtil && nodeUtil.isDate,\n nodeIsMap = nodeUtil && nodeUtil.isMap,\n nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,\n nodeIsSet = nodeUtil && nodeUtil.isSet,\n nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\n function apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n }\n\n /**\n * A specialized version of `baseAggregator` for arrays.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function arrayAggregator(array, setter, iteratee, accumulator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n var value = array[index];\n setter(accumulator, value, iteratee(value), array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.forEachRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEachRight(array, iteratee) {\n var length = array == null ? 0 : array.length;\n\n while (length--) {\n if (iteratee(array[length], length, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.every` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n */\n function arrayEvery(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (!predicate(array[index], index, array)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\n function arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n }\n\n /**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\n function arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n }\n\n /**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\n function arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n }\n\n /**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.reduceRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the last element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduceRight(array, iteratee, accumulator, initAccum) {\n var length = array == null ? 0 : array.length;\n if (initAccum && length) {\n accumulator = array[--length];\n }\n while (length--) {\n accumulator = iteratee(accumulator, array[length], length, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Gets the size of an ASCII `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n var asciiSize = baseProperty('length');\n\n /**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function asciiToArray(string) {\n return string.split('');\n }\n\n /**\n * Splits an ASCII `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function asciiWords(string) {\n return string.match(reAsciiWord) || [];\n }\n\n /**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\n function baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n }\n\n /**\n * This function is like `baseIndexOf` except that it accepts a comparator.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOfWith(array, value, fromIndex, comparator) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (comparator(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\n function baseIsNaN(value) {\n return value !== value;\n }\n\n /**\n * The base implementation of `_.mean` and `_.meanBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the mean.\n */\n function baseMean(array, iteratee) {\n var length = array == null ? 0 : array.length;\n return length ? (baseSum(array, iteratee) / length) : NAN;\n }\n\n /**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\n function baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.propertyOf` without support for deep paths.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyOf(object) {\n return function(key) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.reduce` and `_.reduceRight`, without support\n * for iteratee shorthands, which iterates over `collection` using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} accumulator The initial value.\n * @param {boolean} initAccum Specify using the first or last element of\n * `collection` as the initial value.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the accumulated value.\n */\n function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {\n eachFunc(collection, function(value, index, collection) {\n accumulator = initAccum\n ? (initAccum = false, value)\n : iteratee(accumulator, value, index, collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.sortBy` which uses `comparer` to define the\n * sort order of `array` and replaces criteria objects with their corresponding\n * values.\n *\n * @private\n * @param {Array} array The array to sort.\n * @param {Function} comparer The function to define sort order.\n * @returns {Array} Returns `array`.\n */\n function baseSortBy(array, comparer) {\n var length = array.length;\n\n array.sort(comparer);\n while (length--) {\n array[length] = array[length].value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.sum` and `_.sumBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the sum.\n */\n function baseSum(array, iteratee) {\n var result,\n index = -1,\n length = array.length;\n\n while (++index < length) {\n var current = iteratee(array[index]);\n if (current !== undefined) {\n result = result === undefined ? current : (result + current);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\n function baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array\n * of key-value pairs for `object` corresponding to the property names of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the key-value pairs.\n */\n function baseToPairs(object, props) {\n return arrayMap(props, function(key) {\n return [key, object[key]];\n });\n }\n\n /**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\n function baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n }\n\n /**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\n function baseUnary(func) {\n return function(value) {\n return func(value);\n };\n }\n\n /**\n * The base implementation of `_.values` and `_.valuesIn` which creates an\n * array of `object` property values corresponding to the property names\n * of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the array of property values.\n */\n function baseValues(object, props) {\n return arrayMap(props, function(key) {\n return object[key];\n });\n }\n\n /**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function cacheHas(cache, key) {\n return cache.has(key);\n }\n\n /**\n * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the first unmatched string symbol.\n */\n function charsStartIndex(strSymbols, chrSymbols) {\n var index = -1,\n length = strSymbols.length;\n\n while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the last unmatched string symbol.\n */\n function charsEndIndex(strSymbols, chrSymbols) {\n var index = strSymbols.length;\n\n while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Gets the number of `placeholder` occurrences in `array`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} placeholder The placeholder to search for.\n * @returns {number} Returns the placeholder count.\n */\n function countHolders(array, placeholder) {\n var length = array.length,\n result = 0;\n\n while (length--) {\n if (array[length] === placeholder) {\n ++result;\n }\n }\n return result;\n }\n\n /**\n * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n * letters to basic Latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\n var deburrLetter = basePropertyOf(deburredLetters);\n\n /**\n * Used by `_.escape` to convert characters to HTML entities.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n var escapeHtmlChar = basePropertyOf(htmlEscapes);\n\n /**\n * Used by `_.template` to escape characters for inclusion in compiled string literals.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n function escapeStringChar(chr) {\n return '\\\\' + stringEscapes[chr];\n }\n\n /**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function getValue(object, key) {\n return object == null ? undefined : object[key];\n }\n\n /**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\n function hasUnicode(string) {\n return reHasUnicode.test(string);\n }\n\n /**\n * Checks if `string` contains a word composed of Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a word is found, else `false`.\n */\n function hasUnicodeWord(string) {\n return reHasUnicodeWord.test(string);\n }\n\n /**\n * Converts `iterator` to an array.\n *\n * @private\n * @param {Object} iterator The iterator to convert.\n * @returns {Array} Returns the converted array.\n */\n function iteratorToArray(iterator) {\n var data,\n result = [];\n\n while (!(data = iterator.next()).done) {\n result.push(data.value);\n }\n return result;\n }\n\n /**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\n function mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n }\n\n /**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\n function overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n }\n\n /**\n * Replaces all `placeholder` elements in `array` with an internal placeholder\n * and returns an array of their indexes.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {*} placeholder The placeholder to replace.\n * @returns {Array} Returns the new array of placeholder indexes.\n */\n function replaceHolders(array, placeholder) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value === placeholder || value === PLACEHOLDER) {\n array[index] = PLACEHOLDER;\n result[resIndex++] = index;\n }\n }\n return result;\n }\n\n /**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\n function setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n }\n\n /**\n * Converts `set` to its value-value pairs.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the value-value pairs.\n */\n function setToPairs(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = [value, value];\n });\n return result;\n }\n\n /**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * A specialized version of `_.lastIndexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function strictLastIndexOf(array, value, fromIndex) {\n var index = fromIndex + 1;\n while (index--) {\n if (array[index] === value) {\n return index;\n }\n }\n return index;\n }\n\n /**\n * Gets the number of symbols in `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the string size.\n */\n function stringSize(string) {\n return hasUnicode(string)\n ? unicodeSize(string)\n : asciiSize(string);\n }\n\n /**\n * Converts `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function stringToArray(string) {\n return hasUnicode(string)\n ? unicodeToArray(string)\n : asciiToArray(string);\n }\n\n /**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\n function trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n }\n\n /**\n * Used by `_.unescape` to convert HTML entities to characters.\n *\n * @private\n * @param {string} chr The matched character to unescape.\n * @returns {string} Returns the unescaped character.\n */\n var unescapeHtmlChar = basePropertyOf(htmlUnescapes);\n\n /**\n * Gets the size of a Unicode `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n function unicodeSize(string) {\n var result = reUnicode.lastIndex = 0;\n while (reUnicode.test(string)) {\n ++result;\n }\n return result;\n }\n\n /**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function unicodeToArray(string) {\n return string.match(reUnicode) || [];\n }\n\n /**\n * Splits a Unicode `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function unicodeWords(string) {\n return string.match(reUnicodeWord) || [];\n }\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * Create a new pristine `lodash` function using the `context` object.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Util\n * @param {Object} [context=root] The context object.\n * @returns {Function} Returns a new `lodash` function.\n * @example\n *\n * _.mixin({ 'foo': _.constant('foo') });\n *\n * var lodash = _.runInContext();\n * lodash.mixin({ 'bar': lodash.constant('bar') });\n *\n * _.isFunction(_.foo);\n * // => true\n * _.isFunction(_.bar);\n * // => false\n *\n * lodash.isFunction(lodash.foo);\n * // => false\n * lodash.isFunction(lodash.bar);\n * // => true\n *\n * // Create a suped-up `defer` in Node.js.\n * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;\n */\n var runInContext = (function runInContext(context) {\n context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));\n\n /** Built-in constructor references. */\n var Array = context.Array,\n Date = context.Date,\n Error = context.Error,\n Function = context.Function,\n Math = context.Math,\n Object = context.Object,\n RegExp = context.RegExp,\n String = context.String,\n TypeError = context.TypeError;\n\n /** Used for built-in method references. */\n var arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n /** Used to detect overreaching core-js shims. */\n var coreJsData = context['__core-js_shared__'];\n\n /** Used to resolve the decompiled source of functions. */\n var funcToString = funcProto.toString;\n\n /** Used to check objects for own properties. */\n var hasOwnProperty = objectProto.hasOwnProperty;\n\n /** Used to generate unique IDs. */\n var idCounter = 0;\n\n /** Used to detect methods masquerading as native. */\n var maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n }());\n\n /**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\n var nativeObjectToString = objectProto.toString;\n\n /** Used to infer the `Object` constructor. */\n var objectCtorString = funcToString.call(Object);\n\n /** Used to restore the original `_` reference in `_.noConflict`. */\n var oldDash = root._;\n\n /** Used to detect if a method is native. */\n var reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n );\n\n /** Built-in value references. */\n var Buffer = moduleExports ? context.Buffer : undefined,\n Symbol = context.Symbol,\n Uint8Array = context.Uint8Array,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,\n getPrototype = overArg(Object.getPrototypeOf, Object),\n objectCreate = Object.create,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,\n symIterator = Symbol ? Symbol.iterator : undefined,\n symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n var defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n }());\n\n /** Mocked built-ins. */\n var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,\n ctxNow = Date && Date.now !== root.Date.now && Date.now,\n ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;\n\n /* Built-in method references for those with the same name as other `lodash` methods. */\n var nativeCeil = Math.ceil,\n nativeFloor = Math.floor,\n nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeIsFinite = context.isFinite,\n nativeJoin = arrayProto.join,\n nativeKeys = overArg(Object.keys, Object),\n nativeMax = Math.max,\n nativeMin = Math.min,\n nativeNow = Date.now,\n nativeParseInt = context.parseInt,\n nativeRandom = Math.random,\n nativeReverse = arrayProto.reverse;\n\n /* Built-in method references that are verified to be native. */\n var DataView = getNative(context, 'DataView'),\n Map = getNative(context, 'Map'),\n Promise = getNative(context, 'Promise'),\n Set = getNative(context, 'Set'),\n WeakMap = getNative(context, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n /** Used to store function metadata. */\n var metaMap = WeakMap && new WeakMap;\n\n /** Used to lookup unminified function names. */\n var realNames = {};\n\n /** Used to detect maps, sets, and weakmaps. */\n var dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n /** Used to convert symbols to primitives and strings. */\n var symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` object which wraps `value` to enable implicit method\n * chain sequences. Methods that operate on and return arrays, collections,\n * and functions can be chained together. Methods that retrieve a single value\n * or may return a primitive value will automatically end the chain sequence\n * and return the unwrapped value. Otherwise, the value must be unwrapped\n * with `_#value`.\n *\n * Explicit chain sequences, which must be unwrapped with `_#value`, may be\n * enabled using `_.chain`.\n *\n * The execution of chained methods is lazy, that is, it's deferred until\n * `_#value` is implicitly or explicitly called.\n *\n * Lazy evaluation allows several methods to support shortcut fusion.\n * Shortcut fusion is an optimization to merge iteratee calls; this avoids\n * the creation of intermediate arrays and can greatly reduce the number of\n * iteratee executions. Sections of a chain sequence qualify for shortcut\n * fusion if the section is applied to an array and iteratees accept only\n * one argument. The heuristic for whether a section qualifies for shortcut\n * fusion is subject to change.\n *\n * Chaining is supported in custom builds as long as the `_#value` method is\n * directly or indirectly included in the build.\n *\n * In addition to lodash methods, wrappers have `Array` and `String` methods.\n *\n * The wrapper `Array` methods are:\n * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`\n *\n * The wrapper `String` methods are:\n * `replace` and `split`\n *\n * The wrapper methods that support shortcut fusion are:\n * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,\n * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,\n * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`\n *\n * The chainable wrapper methods are:\n * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,\n * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,\n * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,\n * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,\n * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,\n * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,\n * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,\n * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,\n * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,\n * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,\n * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,\n * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,\n * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,\n * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,\n * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,\n * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,\n * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,\n * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,\n * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,\n * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,\n * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,\n * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,\n * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,\n * `zipObject`, `zipObjectDeep`, and `zipWith`\n *\n * The wrapper methods that are **not** chainable by default are:\n * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,\n * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,\n * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,\n * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,\n * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,\n * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,\n * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,\n * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,\n * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,\n * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,\n * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,\n * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,\n * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,\n * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,\n * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,\n * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,\n * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,\n * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,\n * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,\n * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,\n * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,\n * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,\n * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,\n * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,\n * `upperFirst`, `value`, and `words`\n *\n * @name _\n * @constructor\n * @category Seq\n * @param {*} value The value to wrap in a `lodash` instance.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2, 3]);\n *\n * // Returns an unwrapped value.\n * wrapped.reduce(_.add);\n * // => 6\n *\n * // Returns a wrapped value.\n * var squares = wrapped.map(square);\n *\n * _.isArray(squares);\n * // => false\n *\n * _.isArray(squares.value());\n * // => true\n */\n function lodash(value) {\n if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {\n if (value instanceof LodashWrapper) {\n return value;\n }\n if (hasOwnProperty.call(value, '__wrapped__')) {\n return wrapperClone(value);\n }\n }\n return new LodashWrapper(value);\n }\n\n /**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\n var baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n }());\n\n /**\n * The function whose prototype chain sequence wrappers inherit from.\n *\n * @private\n */\n function baseLodash() {\n // No operation performed.\n }\n\n /**\n * The base constructor for creating `lodash` wrapper objects.\n *\n * @private\n * @param {*} value The value to wrap.\n * @param {boolean} [chainAll] Enable explicit method chain sequences.\n */\n function LodashWrapper(value, chainAll) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__chain__ = !!chainAll;\n this.__index__ = 0;\n this.__values__ = undefined;\n }\n\n /**\n * By default, the template delimiters used by lodash are like those in\n * embedded Ruby (ERB) as well as ES2015 template strings. Change the\n * following template settings to use alternative delimiters.\n *\n * @static\n * @memberOf _\n * @type {Object}\n */\n lodash.templateSettings = {\n\n /**\n * Used to detect `data` property values to be HTML-escaped.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'escape': reEscape,\n\n /**\n * Used to detect code to be evaluated.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'evaluate': reEvaluate,\n\n /**\n * Used to detect `data` property values to inject.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'interpolate': reInterpolate,\n\n /**\n * Used to reference the data object in the template text.\n *\n * @memberOf _.templateSettings\n * @type {string}\n */\n 'variable': '',\n\n /**\n * Used to import variables into the compiled template.\n *\n * @memberOf _.templateSettings\n * @type {Object}\n */\n 'imports': {\n\n /**\n * A reference to the `lodash` function.\n *\n * @memberOf _.templateSettings.imports\n * @type {Function}\n */\n '_': lodash\n }\n };\n\n // Ensure wrappers are instances of `baseLodash`.\n lodash.prototype = baseLodash.prototype;\n lodash.prototype.constructor = lodash;\n\n LodashWrapper.prototype = baseCreate(baseLodash.prototype);\n LodashWrapper.prototype.constructor = LodashWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.\n *\n * @private\n * @constructor\n * @param {*} value The value to wrap.\n */\n function LazyWrapper(value) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__dir__ = 1;\n this.__filtered__ = false;\n this.__iteratees__ = [];\n this.__takeCount__ = MAX_ARRAY_LENGTH;\n this.__views__ = [];\n }\n\n /**\n * Creates a clone of the lazy wrapper object.\n *\n * @private\n * @name clone\n * @memberOf LazyWrapper\n * @returns {Object} Returns the cloned `LazyWrapper` object.\n */\n function lazyClone() {\n var result = new LazyWrapper(this.__wrapped__);\n result.__actions__ = copyArray(this.__actions__);\n result.__dir__ = this.__dir__;\n result.__filtered__ = this.__filtered__;\n result.__iteratees__ = copyArray(this.__iteratees__);\n result.__takeCount__ = this.__takeCount__;\n result.__views__ = copyArray(this.__views__);\n return result;\n }\n\n /**\n * Reverses the direction of lazy iteration.\n *\n * @private\n * @name reverse\n * @memberOf LazyWrapper\n * @returns {Object} Returns the new reversed `LazyWrapper` object.\n */\n function lazyReverse() {\n if (this.__filtered__) {\n var result = new LazyWrapper(this);\n result.__dir__ = -1;\n result.__filtered__ = true;\n } else {\n result = this.clone();\n result.__dir__ *= -1;\n }\n return result;\n }\n\n /**\n * Extracts the unwrapped value from its lazy wrapper.\n *\n * @private\n * @name value\n * @memberOf LazyWrapper\n * @returns {*} Returns the unwrapped value.\n */\n function lazyValue() {\n var array = this.__wrapped__.value(),\n dir = this.__dir__,\n isArr = isArray(array),\n isRight = dir < 0,\n arrLength = isArr ? array.length : 0,\n view = getView(0, arrLength, this.__views__),\n start = view.start,\n end = view.end,\n length = end - start,\n index = isRight ? end : (start - 1),\n iteratees = this.__iteratees__,\n iterLength = iteratees.length,\n resIndex = 0,\n takeCount = nativeMin(length, this.__takeCount__);\n\n if (!isArr || (!isRight && arrLength == length && takeCount == length)) {\n return baseWrapperValue(array, this.__actions__);\n }\n var result = [];\n\n outer:\n while (length-- && resIndex < takeCount) {\n index += dir;\n\n var iterIndex = -1,\n value = array[index];\n\n while (++iterIndex < iterLength) {\n var data = iteratees[iterIndex],\n iteratee = data.iteratee,\n type = data.type,\n computed = iteratee(value);\n\n if (type == LAZY_MAP_FLAG) {\n value = computed;\n } else if (!computed) {\n if (type == LAZY_FILTER_FLAG) {\n continue outer;\n } else {\n break outer;\n }\n }\n }\n result[resIndex++] = value;\n }\n return result;\n }\n\n // Ensure `LazyWrapper` is an instance of `baseLodash`.\n LazyWrapper.prototype = baseCreate(baseLodash.prototype);\n LazyWrapper.prototype.constructor = LazyWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\n function hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n }\n\n /**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n }\n\n /**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n }\n\n /**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\n function hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n }\n\n // Add methods to `Hash`.\n Hash.prototype.clear = hashClear;\n Hash.prototype['delete'] = hashDelete;\n Hash.prototype.get = hashGet;\n Hash.prototype.has = hashHas;\n Hash.prototype.set = hashSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\n function listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n }\n\n /**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n }\n\n /**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n }\n\n /**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\n function listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n }\n\n // Add methods to `ListCache`.\n ListCache.prototype.clear = listCacheClear;\n ListCache.prototype['delete'] = listCacheDelete;\n ListCache.prototype.get = listCacheGet;\n ListCache.prototype.has = listCacheHas;\n ListCache.prototype.set = listCacheSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\n function mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n }\n\n /**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n }\n\n /**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function mapCacheGet(key) {\n return getMapData(this, key).get(key);\n }\n\n /**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function mapCacheHas(key) {\n return getMapData(this, key).has(key);\n }\n\n /**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\n function mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n }\n\n // Add methods to `MapCache`.\n MapCache.prototype.clear = mapCacheClear;\n MapCache.prototype['delete'] = mapCacheDelete;\n MapCache.prototype.get = mapCacheGet;\n MapCache.prototype.has = mapCacheHas;\n MapCache.prototype.set = mapCacheSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\n function SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n }\n\n /**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\n function setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n }\n\n /**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\n function setCacheHas(value) {\n return this.__data__.has(value);\n }\n\n // Add methods to `SetCache`.\n SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\n SetCache.prototype.has = setCacheHas;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n }\n\n /**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\n function stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n }\n\n /**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function stackGet(key) {\n return this.__data__.get(key);\n }\n\n /**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function stackHas(key) {\n return this.__data__.has(key);\n }\n\n /**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\n function stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n }\n\n // Add methods to `Stack`.\n Stack.prototype.clear = stackClear;\n Stack.prototype['delete'] = stackDelete;\n Stack.prototype.get = stackGet;\n Stack.prototype.has = stackHas;\n Stack.prototype.set = stackSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\n function arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.sample` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @returns {*} Returns the random element.\n */\n function arraySample(array) {\n var length = array.length;\n return length ? array[baseRandom(0, length - 1)] : undefined;\n }\n\n /**\n * A specialized version of `_.sampleSize` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function arraySampleSize(array, n) {\n return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));\n }\n\n /**\n * A specialized version of `_.shuffle` for arrays.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function arrayShuffle(array) {\n return shuffleSelf(copyArray(array));\n }\n\n /**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n }\n\n /**\n * Aggregates elements of `collection` on `accumulator` with keys transformed\n * by `iteratee` and values set by `setter`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseAggregator(collection, setter, iteratee, accumulator) {\n baseEach(collection, function(value, key, collection) {\n setter(accumulator, value, iteratee(value), collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n }\n\n /**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n }\n\n /**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n }\n\n /**\n * The base implementation of `_.at` without support for individual paths.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {string[]} paths The property paths to pick.\n * @returns {Array} Returns the picked elements.\n */\n function baseAt(object, paths) {\n var index = -1,\n length = paths.length,\n result = Array(length),\n skip = object == null;\n\n while (++index < length) {\n result[index] = skip ? undefined : get(object, paths[index]);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.clamp` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n */\n function baseClamp(number, lower, upper) {\n if (number === number) {\n if (upper !== undefined) {\n number = number <= upper ? number : upper;\n }\n if (lower !== undefined) {\n number = number >= lower ? number : lower;\n }\n }\n return number;\n }\n\n /**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\n function baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n }\n\n /**\n * The base implementation of `_.conforms` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property predicates to conform to.\n * @returns {Function} Returns the new spec function.\n */\n function baseConforms(source) {\n var props = keys(source);\n return function(object) {\n return baseConformsTo(object, source, props);\n };\n }\n\n /**\n * The base implementation of `_.conformsTo` which accepts `props` to check.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n */\n function baseConformsTo(object, source, props) {\n var length = props.length;\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (length--) {\n var key = props[length],\n predicate = source[key],\n value = object[key];\n\n if ((value === undefined && !(key in object)) || !predicate(value)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.delay` and `_.defer` which accepts `args`\n * to provide to `func`.\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {Array} args The arguments to provide to `func`.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n function baseDelay(func, wait, args) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return setTimeout(function() { func.apply(undefined, args); }, wait);\n }\n\n /**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\n function baseDifference(array, values, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n isCommon = true,\n length = array.length,\n result = [],\n valuesLength = values.length;\n\n if (!length) {\n return result;\n }\n if (iteratee) {\n values = arrayMap(values, baseUnary(iteratee));\n }\n if (comparator) {\n includes = arrayIncludesWith;\n isCommon = false;\n }\n else if (values.length >= LARGE_ARRAY_SIZE) {\n includes = cacheHas;\n isCommon = false;\n values = new SetCache(values);\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee == null ? value : iteratee(value);\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === computed) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (!includes(values, computed, comparator)) {\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.forEach` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\n var baseEach = createBaseEach(baseForOwn);\n\n /**\n * The base implementation of `_.forEachRight` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\n var baseEachRight = createBaseEach(baseForOwnRight, true);\n\n /**\n * The base implementation of `_.every` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`\n */\n function baseEvery(collection, predicate) {\n var result = true;\n baseEach(collection, function(value, index, collection) {\n result = !!predicate(value, index, collection);\n return result;\n });\n return result;\n }\n\n /**\n * The base implementation of methods like `_.max` and `_.min` which accepts a\n * `comparator` to determine the extremum value.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The iteratee invoked per iteration.\n * @param {Function} comparator The comparator used to compare values.\n * @returns {*} Returns the extremum value.\n */\n function baseExtremum(array, iteratee, comparator) {\n var index = -1,\n length = array.length;\n\n while (++index < length) {\n var value = array[index],\n current = iteratee(value);\n\n if (current != null && (computed === undefined\n ? (current === current && !isSymbol(current))\n : comparator(current, computed)\n )) {\n var computed = current,\n result = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.fill` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n */\n function baseFill(array, value, start, end) {\n var length = array.length;\n\n start = toInteger(start);\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = (end === undefined || end > length) ? length : toInteger(end);\n if (end < 0) {\n end += length;\n }\n end = start > end ? 0 : toLength(end);\n while (start < end) {\n array[start++] = value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.filter` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function baseFilter(collection, predicate) {\n var result = [];\n baseEach(collection, function(value, index, collection) {\n if (predicate(value, index, collection)) {\n result.push(value);\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\n function baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n var baseFor = createBaseFor();\n\n /**\n * This function is like `baseFor` except that it iterates over properties\n * in the opposite order.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n var baseForRight = createBaseFor(true);\n\n /**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.forOwnRight` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwnRight(object, iteratee) {\n return object && baseForRight(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.functions` which creates an array of\n * `object` function property names filtered from `props`.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Array} props The property names to filter.\n * @returns {Array} Returns the function names.\n */\n function baseFunctions(object, props) {\n return arrayFilter(props, function(key) {\n return isFunction(object[key]);\n });\n }\n\n /**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\n function baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n }\n\n /**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n }\n\n /**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n function baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n }\n\n /**\n * The base implementation of `_.gt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n */\n function baseGt(value, other) {\n return value > other;\n }\n\n /**\n * The base implementation of `_.has` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\n function baseHas(object, key) {\n return object != null && hasOwnProperty.call(object, key);\n }\n\n /**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\n function baseHasIn(object, key) {\n return object != null && key in Object(object);\n }\n\n /**\n * The base implementation of `_.inRange` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to check.\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n */\n function baseInRange(number, start, end) {\n return number >= nativeMin(start, end) && number < nativeMax(start, end);\n }\n\n /**\n * The base implementation of methods like `_.intersection`, without support\n * for iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of shared values.\n */\n function baseIntersection(arrays, iteratee, comparator) {\n var includes = comparator ? arrayIncludesWith : arrayIncludes,\n length = arrays[0].length,\n othLength = arrays.length,\n othIndex = othLength,\n caches = Array(othLength),\n maxLength = Infinity,\n result = [];\n\n while (othIndex--) {\n var array = arrays[othIndex];\n if (othIndex && iteratee) {\n array = arrayMap(array, baseUnary(iteratee));\n }\n maxLength = nativeMin(array.length, maxLength);\n caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))\n ? new SetCache(othIndex && array)\n : undefined;\n }\n array = arrays[0];\n\n var index = -1,\n seen = caches[0];\n\n outer:\n while (++index < length && result.length < maxLength) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (!(seen\n ? cacheHas(seen, computed)\n : includes(result, computed, comparator)\n )) {\n othIndex = othLength;\n while (--othIndex) {\n var cache = caches[othIndex];\n if (!(cache\n ? cacheHas(cache, computed)\n : includes(arrays[othIndex], computed, comparator))\n ) {\n continue outer;\n }\n }\n if (seen) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.invert` and `_.invertBy` which inverts\n * `object` with values transformed by `iteratee` and set by `setter`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform values.\n * @param {Object} accumulator The initial inverted object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseInverter(object, setter, iteratee, accumulator) {\n baseForOwn(object, function(value, key, object) {\n setter(accumulator, iteratee(value), key, object);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.invoke` without support for individual\n * method arguments.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {Array} args The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n */\n function baseInvoke(object, path, args) {\n path = castPath(path, object);\n object = parent(object, path);\n var func = object == null ? object : object[toKey(last(path))];\n return func == null ? undefined : apply(func, object, args);\n }\n\n /**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\n function baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n }\n\n /**\n * The base implementation of `_.isArrayBuffer` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n */\n function baseIsArrayBuffer(value) {\n return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;\n }\n\n /**\n * The base implementation of `_.isDate` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n */\n function baseIsDate(value) {\n return isObjectLike(value) && baseGetTag(value) == dateTag;\n }\n\n /**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\n function baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n }\n\n /**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n }\n\n /**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\n function baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n }\n\n /**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\n function baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\n function baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n }\n\n /**\n * The base implementation of `_.isRegExp` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n */\n function baseIsRegExp(value) {\n return isObjectLike(value) && baseGetTag(value) == regexpTag;\n }\n\n /**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\n function baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n }\n\n /**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\n function baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n }\n\n /**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\n function baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n }\n\n /**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.lt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n */\n function baseLt(value, other) {\n return value < other;\n }\n\n /**\n * The base implementation of `_.map` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function baseMap(collection, iteratee) {\n var index = -1,\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value, key, collection) {\n result[++index] = iteratee(value, key, collection);\n });\n return result;\n }\n\n /**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\n function baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n }\n\n /**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\n function baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n }\n\n /**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n }\n\n /**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n }\n\n /**\n * The base implementation of `_.nth` which doesn't coerce arguments.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {number} n The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n */\n function baseNth(array, n) {\n var length = array.length;\n if (!length) {\n return;\n }\n n += n < 0 ? length : 0;\n return isIndex(n, length) ? array[n] : undefined;\n }\n\n /**\n * The base implementation of `_.orderBy` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.\n * @param {string[]} orders The sort orders of `iteratees`.\n * @returns {Array} Returns the new sorted array.\n */\n function baseOrderBy(collection, iteratees, orders) {\n if (iteratees.length) {\n iteratees = arrayMap(iteratees, function(iteratee) {\n if (isArray(iteratee)) {\n return function(value) {\n return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);\n }\n }\n return iteratee;\n });\n } else {\n iteratees = [identity];\n }\n\n var index = -1;\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n\n var result = baseMap(collection, function(value, key, collection) {\n var criteria = arrayMap(iteratees, function(iteratee) {\n return iteratee(value);\n });\n return { 'criteria': criteria, 'index': ++index, 'value': value };\n });\n\n return baseSortBy(result, function(object, other) {\n return compareMultiple(object, other, orders);\n });\n }\n\n /**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @returns {Object} Returns the new object.\n */\n function basePick(object, paths) {\n return basePickBy(object, paths, function(value, path) {\n return hasIn(object, path);\n });\n }\n\n /**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\n function basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n }\n\n /**\n * The base implementation of `_.pullAllBy` without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n */\n function basePullAll(array, values, iteratee, comparator) {\n var indexOf = comparator ? baseIndexOfWith : baseIndexOf,\n index = -1,\n length = values.length,\n seen = array;\n\n if (array === values) {\n values = copyArray(values);\n }\n if (iteratee) {\n seen = arrayMap(array, baseUnary(iteratee));\n }\n while (++index < length) {\n var fromIndex = 0,\n value = values[index],\n computed = iteratee ? iteratee(value) : value;\n\n while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {\n if (seen !== array) {\n splice.call(seen, fromIndex, 1);\n }\n splice.call(array, fromIndex, 1);\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.pullAt` without support for individual\n * indexes or capturing the removed elements.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {number[]} indexes The indexes of elements to remove.\n * @returns {Array} Returns `array`.\n */\n function basePullAt(array, indexes) {\n var length = array ? indexes.length : 0,\n lastIndex = length - 1;\n\n while (length--) {\n var index = indexes[length];\n if (length == lastIndex || index !== previous) {\n var previous = index;\n if (isIndex(index)) {\n splice.call(array, index, 1);\n } else {\n baseUnset(array, index);\n }\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.random` without support for returning\n * floating-point numbers.\n *\n * @private\n * @param {number} lower The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the random number.\n */\n function baseRandom(lower, upper) {\n return lower + nativeFloor(nativeRandom() * (upper - lower + 1));\n }\n\n /**\n * The base implementation of `_.range` and `_.rangeRight` which doesn't\n * coerce arguments.\n *\n * @private\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @param {number} step The value to increment or decrement by.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the range of numbers.\n */\n function baseRange(start, end, step, fromRight) {\n var index = -1,\n length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),\n result = Array(length);\n\n while (length--) {\n result[fromRight ? length : ++index] = start;\n start += step;\n }\n return result;\n }\n\n /**\n * The base implementation of `_.repeat` which doesn't coerce arguments.\n *\n * @private\n * @param {string} string The string to repeat.\n * @param {number} n The number of times to repeat the string.\n * @returns {string} Returns the repeated string.\n */\n function baseRepeat(string, n) {\n var result = '';\n if (!string || n < 1 || n > MAX_SAFE_INTEGER) {\n return result;\n }\n // Leverage the exponentiation by squaring algorithm for a faster repeat.\n // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.\n do {\n if (n % 2) {\n result += string;\n }\n n = nativeFloor(n / 2);\n if (n) {\n string += string;\n }\n } while (n);\n\n return result;\n }\n\n /**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\n function baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n }\n\n /**\n * The base implementation of `_.sample`.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n */\n function baseSample(collection) {\n return arraySample(values(collection));\n }\n\n /**\n * The base implementation of `_.sampleSize` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function baseSampleSize(collection, n) {\n var array = values(collection);\n return shuffleSelf(array, baseClamp(n, 0, array.length));\n }\n\n /**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n }\n\n /**\n * The base implementation of `setData` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var baseSetData = !metaMap ? identity : function(func, data) {\n metaMap.set(func, data);\n return func;\n };\n\n /**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\n var baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n };\n\n /**\n * The base implementation of `_.shuffle`.\n *\n * @private\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function baseShuffle(collection) {\n return shuffleSelf(values(collection));\n }\n\n /**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n }\n\n /**\n * The base implementation of `_.some` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function baseSome(collection, predicate) {\n var result;\n\n baseEach(collection, function(value, index, collection) {\n result = predicate(value, index, collection);\n return !result;\n });\n return !!result;\n }\n\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which\n * performs a binary search of `array` to determine the index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, retHighest) {\n var low = 0,\n high = array == null ? low : array.length;\n\n if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = array[mid];\n\n if (computed !== null && !isSymbol(computed) &&\n (retHighest ? (computed <= value) : (computed < value))) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n return baseSortedIndexBy(array, value, identity, retHighest);\n }\n\n /**\n * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`\n * which invokes `iteratee` for `value` and each element of `array` to compute\n * their sort ranking. The iteratee is invoked with one argument; (value).\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iteratee The iteratee invoked per element.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndexBy(array, value, iteratee, retHighest) {\n var low = 0,\n high = array == null ? 0 : array.length;\n if (high === 0) {\n return 0;\n }\n\n value = iteratee(value);\n var valIsNaN = value !== value,\n valIsNull = value === null,\n valIsSymbol = isSymbol(value),\n valIsUndefined = value === undefined;\n\n while (low < high) {\n var mid = nativeFloor((low + high) / 2),\n computed = iteratee(array[mid]),\n othIsDefined = computed !== undefined,\n othIsNull = computed === null,\n othIsReflexive = computed === computed,\n othIsSymbol = isSymbol(computed);\n\n if (valIsNaN) {\n var setLow = retHighest || othIsReflexive;\n } else if (valIsUndefined) {\n setLow = othIsReflexive && (retHighest || othIsDefined);\n } else if (valIsNull) {\n setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);\n } else if (valIsSymbol) {\n setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);\n } else if (othIsNull || othIsSymbol) {\n setLow = false;\n } else {\n setLow = retHighest ? (computed <= value) : (computed < value);\n }\n if (setLow) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return nativeMin(high, MAX_ARRAY_INDEX);\n }\n\n /**\n * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\n function baseSortedUniq(array, iteratee) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n if (!index || !eq(computed, seen)) {\n var seen = computed;\n result[resIndex++] = value === 0 ? 0 : value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toNumber` which doesn't ensure correct\n * conversions of binary, hexadecimal, or octal string values.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n */\n function baseToNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n return +value;\n }\n\n /**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\n function baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n }\n\n /**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\n function baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.unset`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The property path to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n */\n function baseUnset(object, path) {\n path = castPath(path, object);\n object = parent(object, path);\n return object == null || delete object[toKey(last(path))];\n }\n\n /**\n * The base implementation of `_.update`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to update.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseUpdate(object, path, updater, customizer) {\n return baseSet(object, path, updater(baseGet(object, path)), customizer);\n }\n\n /**\n * The base implementation of methods like `_.dropWhile` and `_.takeWhile`\n * without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {Function} predicate The function invoked per iteration.\n * @param {boolean} [isDrop] Specify dropping elements instead of taking them.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseWhile(array, predicate, isDrop, fromRight) {\n var length = array.length,\n index = fromRight ? length : -1;\n\n while ((fromRight ? index-- : ++index < length) &&\n predicate(array[index], index, array)) {}\n\n return isDrop\n ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))\n : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));\n }\n\n /**\n * The base implementation of `wrapperValue` which returns the result of\n * performing a sequence of actions on the unwrapped `value`, where each\n * successive action is supplied the return value of the previous.\n *\n * @private\n * @param {*} value The unwrapped value.\n * @param {Array} actions Actions to perform to resolve the unwrapped value.\n * @returns {*} Returns the resolved value.\n */\n function baseWrapperValue(value, actions) {\n var result = value;\n if (result instanceof LazyWrapper) {\n result = result.value();\n }\n return arrayReduce(actions, function(result, action) {\n return action.func.apply(action.thisArg, arrayPush([result], action.args));\n }, result);\n }\n\n /**\n * The base implementation of methods like `_.xor`, without support for\n * iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of values.\n */\n function baseXor(arrays, iteratee, comparator) {\n var length = arrays.length;\n if (length < 2) {\n return length ? baseUniq(arrays[0]) : [];\n }\n var index = -1,\n result = Array(length);\n\n while (++index < length) {\n var array = arrays[index],\n othIndex = -1;\n\n while (++othIndex < length) {\n if (othIndex != index) {\n result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);\n }\n }\n }\n return baseUniq(baseFlatten(result, 1), iteratee, comparator);\n }\n\n /**\n * This base implementation of `_.zipObject` which assigns values using `assignFunc`.\n *\n * @private\n * @param {Array} props The property identifiers.\n * @param {Array} values The property values.\n * @param {Function} assignFunc The function to assign values.\n * @returns {Object} Returns the new object.\n */\n function baseZipObject(props, values, assignFunc) {\n var index = -1,\n length = props.length,\n valsLength = values.length,\n result = {};\n\n while (++index < length) {\n var value = index < valsLength ? values[index] : undefined;\n assignFunc(result, props[index], value);\n }\n return result;\n }\n\n /**\n * Casts `value` to an empty array if it's not an array like object.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Array|Object} Returns the cast array-like object.\n */\n function castArrayLikeObject(value) {\n return isArrayLikeObject(value) ? value : [];\n }\n\n /**\n * Casts `value` to `identity` if it's not a function.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Function} Returns cast function.\n */\n function castFunction(value) {\n return typeof value == 'function' ? value : identity;\n }\n\n /**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\n function castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n }\n\n /**\n * A `baseRest` alias which can be replaced with `identity` by module\n * replacement plugins.\n *\n * @private\n * @type {Function}\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n var castRest = baseRest;\n\n /**\n * Casts `array` to a slice if it's needed.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {number} start The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the cast slice.\n */\n function castSlice(array, start, end) {\n var length = array.length;\n end = end === undefined ? length : end;\n return (!start && end >= length) ? array : baseSlice(array, start, end);\n }\n\n /**\n * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).\n *\n * @private\n * @param {number|Object} id The timer id or timeout object of the timer to clear.\n */\n var clearTimeout = ctxClearTimeout || function(id) {\n return root.clearTimeout(id);\n };\n\n /**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\n function cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n }\n\n /**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\n function cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n }\n\n /**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\n function cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n }\n\n /**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\n function cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n }\n\n /**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\n function cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n }\n\n /**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\n function cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n }\n\n /**\n * Compares values to sort them in ascending order.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {number} Returns the sort order indicator for `value`.\n */\n function compareAscending(value, other) {\n if (value !== other) {\n var valIsDefined = value !== undefined,\n valIsNull = value === null,\n valIsReflexive = value === value,\n valIsSymbol = isSymbol(value);\n\n var othIsDefined = other !== undefined,\n othIsNull = other === null,\n othIsReflexive = other === other,\n othIsSymbol = isSymbol(other);\n\n if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||\n (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||\n (valIsNull && othIsDefined && othIsReflexive) ||\n (!valIsDefined && othIsReflexive) ||\n !valIsReflexive) {\n return 1;\n }\n if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||\n (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||\n (othIsNull && valIsDefined && valIsReflexive) ||\n (!othIsDefined && valIsReflexive) ||\n !othIsReflexive) {\n return -1;\n }\n }\n return 0;\n }\n\n /**\n * Used by `_.orderBy` to compare multiple properties of a value to another\n * and stable sort them.\n *\n * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,\n * specify an order of \"desc\" for descending or \"asc\" for ascending sort order\n * of corresponding values.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {boolean[]|string[]} orders The order to sort by for each property.\n * @returns {number} Returns the sort order indicator for `object`.\n */\n function compareMultiple(object, other, orders) {\n var index = -1,\n objCriteria = object.criteria,\n othCriteria = other.criteria,\n length = objCriteria.length,\n ordersLength = orders.length;\n\n while (++index < length) {\n var result = compareAscending(objCriteria[index], othCriteria[index]);\n if (result) {\n if (index >= ordersLength) {\n return result;\n }\n var order = orders[index];\n return result * (order == 'desc' ? -1 : 1);\n }\n }\n // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications\n // that causes it, under certain circumstances, to provide the same value for\n // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247\n // for more details.\n //\n // This also ensures a stable sort in V8 and other engines.\n // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.\n return object.index - other.index;\n }\n\n /**\n * Creates an array that is the composition of partially applied arguments,\n * placeholders, and provided arguments into a single array of arguments.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to prepend to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgs(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersLength = holders.length,\n leftIndex = -1,\n leftLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(leftLength + rangeLength),\n isUncurried = !isCurried;\n\n while (++leftIndex < leftLength) {\n result[leftIndex] = partials[leftIndex];\n }\n while (++argsIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[holders[argsIndex]] = args[argsIndex];\n }\n }\n while (rangeLength--) {\n result[leftIndex++] = args[argsIndex++];\n }\n return result;\n }\n\n /**\n * This function is like `composeArgs` except that the arguments composition\n * is tailored for `_.partialRight`.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to append to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgsRight(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersIndex = -1,\n holdersLength = holders.length,\n rightIndex = -1,\n rightLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(rangeLength + rightLength),\n isUncurried = !isCurried;\n\n while (++argsIndex < rangeLength) {\n result[argsIndex] = args[argsIndex];\n }\n var offset = argsIndex;\n while (++rightIndex < rightLength) {\n result[offset + rightIndex] = partials[rightIndex];\n }\n while (++holdersIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[offset + holders[holdersIndex]] = args[argsIndex++];\n }\n }\n return result;\n }\n\n /**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\n function copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n }\n\n /**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\n function copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n }\n\n /**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n }\n\n /**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n }\n\n /**\n * Creates a function like `_.groupBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} [initializer] The accumulator object initializer.\n * @returns {Function} Returns the new aggregator function.\n */\n function createAggregator(setter, initializer) {\n return function(collection, iteratee) {\n var func = isArray(collection) ? arrayAggregator : baseAggregator,\n accumulator = initializer ? initializer() : {};\n\n return func(collection, setter, getIteratee(iteratee, 2), accumulator);\n };\n }\n\n /**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\n function createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n }\n\n /**\n * Creates a `baseEach` or `baseEachRight` function.\n *\n * @private\n * @param {Function} eachFunc The function to iterate over a collection.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\n function createBaseEach(eachFunc, fromRight) {\n return function(collection, iteratee) {\n if (collection == null) {\n return collection;\n }\n if (!isArrayLike(collection)) {\n return eachFunc(collection, iteratee);\n }\n var length = collection.length,\n index = fromRight ? length : -1,\n iterable = Object(collection);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (iteratee(iterable[index], index, iterable) === false) {\n break;\n }\n }\n return collection;\n };\n }\n\n /**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\n function createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the optional `this`\n * binding of `thisArg`.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createBind(func, bitmask, thisArg) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return fn.apply(isBind ? thisArg : this, arguments);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.lowerFirst`.\n *\n * @private\n * @param {string} methodName The name of the `String` case method to use.\n * @returns {Function} Returns the new case function.\n */\n function createCaseFirst(methodName) {\n return function(string) {\n string = toString(string);\n\n var strSymbols = hasUnicode(string)\n ? stringToArray(string)\n : undefined;\n\n var chr = strSymbols\n ? strSymbols[0]\n : string.charAt(0);\n\n var trailing = strSymbols\n ? castSlice(strSymbols, 1).join('')\n : string.slice(1);\n\n return chr[methodName]() + trailing;\n };\n }\n\n /**\n * Creates a function like `_.camelCase`.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\n function createCompounder(callback) {\n return function(string) {\n return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n };\n }\n\n /**\n * Creates a function that produces an instance of `Ctor` regardless of\n * whether it was invoked as part of a `new` expression or by `call` or `apply`.\n *\n * @private\n * @param {Function} Ctor The constructor to wrap.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCtor(Ctor) {\n return function() {\n // Use a `switch` statement to work with class constructors. See\n // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist\n // for more details.\n var args = arguments;\n switch (args.length) {\n case 0: return new Ctor;\n case 1: return new Ctor(args[0]);\n case 2: return new Ctor(args[0], args[1]);\n case 3: return new Ctor(args[0], args[1], args[2]);\n case 4: return new Ctor(args[0], args[1], args[2], args[3]);\n case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);\n case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);\n case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);\n }\n var thisBinding = baseCreate(Ctor.prototype),\n result = Ctor.apply(thisBinding, args);\n\n // Mimic the constructor's `return` behavior.\n // See https://es5.github.io/#x13.2.2 for more details.\n return isObject(result) ? result : thisBinding;\n };\n }\n\n /**\n * Creates a function that wraps `func` to enable currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {number} arity The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCurry(func, bitmask, arity) {\n var Ctor = createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length,\n placeholder = getHolder(wrapper);\n\n while (index--) {\n args[index] = arguments[index];\n }\n var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)\n ? []\n : replaceHolders(args, placeholder);\n\n length -= holders.length;\n if (length < arity) {\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, undefined,\n args, holders, undefined, undefined, arity - length);\n }\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return apply(fn, this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a `_.find` or `_.findLast` function.\n *\n * @private\n * @param {Function} findIndexFunc The function to find the collection index.\n * @returns {Function} Returns the new find function.\n */\n function createFind(findIndexFunc) {\n return function(collection, predicate, fromIndex) {\n var iterable = Object(collection);\n if (!isArrayLike(collection)) {\n var iteratee = getIteratee(predicate, 3);\n collection = keys(collection);\n predicate = function(key) { return iteratee(iterable[key], key, iterable); };\n }\n var index = findIndexFunc(collection, predicate, fromIndex);\n return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;\n };\n }\n\n /**\n * Creates a `_.flow` or `_.flowRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new flow function.\n */\n function createFlow(fromRight) {\n return flatRest(function(funcs) {\n var length = funcs.length,\n index = length,\n prereq = LodashWrapper.prototype.thru;\n\n if (fromRight) {\n funcs.reverse();\n }\n while (index--) {\n var func = funcs[index];\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (prereq && !wrapper && getFuncName(func) == 'wrapper') {\n var wrapper = new LodashWrapper([], true);\n }\n }\n index = wrapper ? index : length;\n while (++index < length) {\n func = funcs[index];\n\n var funcName = getFuncName(func),\n data = funcName == 'wrapper' ? getData(func) : undefined;\n\n if (data && isLaziable(data[0]) &&\n data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&\n !data[4].length && data[9] == 1\n ) {\n wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);\n } else {\n wrapper = (func.length == 1 && isLaziable(func))\n ? wrapper[funcName]()\n : wrapper.thru(func);\n }\n }\n return function() {\n var args = arguments,\n value = args[0];\n\n if (wrapper && args.length == 1 && isArray(value)) {\n return wrapper.plant(value).value();\n }\n var index = 0,\n result = length ? funcs[index].apply(this, args) : value;\n\n while (++index < length) {\n result = funcs[index].call(this, result);\n }\n return result;\n };\n });\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with optional `this`\n * binding of `thisArg`, partial application, and currying.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [partialsRight] The arguments to append to those provided\n * to the new function.\n * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {\n var isAry = bitmask & WRAP_ARY_FLAG,\n isBind = bitmask & WRAP_BIND_FLAG,\n isBindKey = bitmask & WRAP_BIND_KEY_FLAG,\n isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),\n isFlip = bitmask & WRAP_FLIP_FLAG,\n Ctor = isBindKey ? undefined : createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length;\n\n while (index--) {\n args[index] = arguments[index];\n }\n if (isCurried) {\n var placeholder = getHolder(wrapper),\n holdersCount = countHolders(args, placeholder);\n }\n if (partials) {\n args = composeArgs(args, partials, holders, isCurried);\n }\n if (partialsRight) {\n args = composeArgsRight(args, partialsRight, holdersRight, isCurried);\n }\n length -= holdersCount;\n if (isCurried && length < arity) {\n var newHolders = replaceHolders(args, placeholder);\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, thisArg,\n args, newHolders, argPos, ary, arity - length\n );\n }\n var thisBinding = isBind ? thisArg : this,\n fn = isBindKey ? thisBinding[func] : func;\n\n length = args.length;\n if (argPos) {\n args = reorder(args, argPos);\n } else if (isFlip && length > 1) {\n args.reverse();\n }\n if (isAry && ary < length) {\n args.length = ary;\n }\n if (this && this !== root && this instanceof wrapper) {\n fn = Ctor || createCtor(fn);\n }\n return fn.apply(thisBinding, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.invertBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} toIteratee The function to resolve iteratees.\n * @returns {Function} Returns the new inverter function.\n */\n function createInverter(setter, toIteratee) {\n return function(object, iteratee) {\n return baseInverter(object, setter, toIteratee(iteratee), {});\n };\n }\n\n /**\n * Creates a function that performs a mathematical operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @param {number} [defaultValue] The value used for `undefined` arguments.\n * @returns {Function} Returns the new mathematical operation function.\n */\n function createMathOperation(operator, defaultValue) {\n return function(value, other) {\n var result;\n if (value === undefined && other === undefined) {\n return defaultValue;\n }\n if (value !== undefined) {\n result = value;\n }\n if (other !== undefined) {\n if (result === undefined) {\n return other;\n }\n if (typeof value == 'string' || typeof other == 'string') {\n value = baseToString(value);\n other = baseToString(other);\n } else {\n value = baseToNumber(value);\n other = baseToNumber(other);\n }\n result = operator(value, other);\n }\n return result;\n };\n }\n\n /**\n * Creates a function like `_.over`.\n *\n * @private\n * @param {Function} arrayFunc The function to iterate over iteratees.\n * @returns {Function} Returns the new over function.\n */\n function createOver(arrayFunc) {\n return flatRest(function(iteratees) {\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n return baseRest(function(args) {\n var thisArg = this;\n return arrayFunc(iteratees, function(iteratee) {\n return apply(iteratee, thisArg, args);\n });\n });\n });\n }\n\n /**\n * Creates the padding for `string` based on `length`. The `chars` string\n * is truncated if the number of characters exceeds `length`.\n *\n * @private\n * @param {number} length The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padding for `string`.\n */\n function createPadding(length, chars) {\n chars = chars === undefined ? ' ' : baseToString(chars);\n\n var charsLength = chars.length;\n if (charsLength < 2) {\n return charsLength ? baseRepeat(chars, length) : chars;\n }\n var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));\n return hasUnicode(chars)\n ? castSlice(stringToArray(result), 0, length).join('')\n : result.slice(0, length);\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the `this` binding\n * of `thisArg` and `partials` prepended to the arguments it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} partials The arguments to prepend to those provided to\n * the new function.\n * @returns {Function} Returns the new wrapped function.\n */\n function createPartial(func, bitmask, thisArg, partials) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var argsIndex = -1,\n argsLength = arguments.length,\n leftIndex = -1,\n leftLength = partials.length,\n args = Array(leftLength + argsLength),\n fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n\n while (++leftIndex < leftLength) {\n args[leftIndex] = partials[leftIndex];\n }\n while (argsLength--) {\n args[leftIndex++] = arguments[++argsIndex];\n }\n return apply(fn, isBind ? thisArg : this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a `_.range` or `_.rangeRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new range function.\n */\n function createRange(fromRight) {\n return function(start, end, step) {\n if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {\n end = step = undefined;\n }\n // Ensure the sign of `-0` is preserved.\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);\n return baseRange(start, end, step, fromRight);\n };\n }\n\n /**\n * Creates a function that performs a relational operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @returns {Function} Returns the new relational operation function.\n */\n function createRelationalOperation(operator) {\n return function(value, other) {\n if (!(typeof value == 'string' && typeof other == 'string')) {\n value = toNumber(value);\n other = toNumber(other);\n }\n return operator(value, other);\n };\n }\n\n /**\n * Creates a function that wraps `func` to continue currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {Function} wrapFunc The function to create the `func` wrapper.\n * @param {*} placeholder The placeholder value.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {\n var isCurry = bitmask & WRAP_CURRY_FLAG,\n newHolders = isCurry ? holders : undefined,\n newHoldersRight = isCurry ? undefined : holders,\n newPartials = isCurry ? partials : undefined,\n newPartialsRight = isCurry ? undefined : partials;\n\n bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);\n bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);\n\n if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {\n bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);\n }\n var newData = [\n func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,\n newHoldersRight, argPos, ary, arity\n ];\n\n var result = wrapFunc.apply(undefined, newData);\n if (isLaziable(func)) {\n setData(result, newData);\n }\n result.placeholder = placeholder;\n return setWrapToString(result, func, bitmask);\n }\n\n /**\n * Creates a function like `_.round`.\n *\n * @private\n * @param {string} methodName The name of the `Math` method to use when rounding.\n * @returns {Function} Returns the new round function.\n */\n function createRound(methodName) {\n var func = Math[methodName];\n return function(number, precision) {\n number = toNumber(number);\n precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);\n if (precision && nativeIsFinite(number)) {\n // Shift with exponential notation to avoid floating-point issues.\n // See [MDN](https://mdn.io/round#Examples) for more details.\n var pair = (toString(number) + 'e').split('e'),\n value = func(pair[0] + 'e' + (+pair[1] + precision));\n\n pair = (toString(value) + 'e').split('e');\n return +(pair[0] + 'e' + (+pair[1] - precision));\n }\n return func(number);\n };\n }\n\n /**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\n var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n };\n\n /**\n * Creates a `_.toPairs` or `_.toPairsIn` function.\n *\n * @private\n * @param {Function} keysFunc The function to get the keys of a given object.\n * @returns {Function} Returns the new pairs function.\n */\n function createToPairs(keysFunc) {\n return function(object) {\n var tag = getTag(object);\n if (tag == mapTag) {\n return mapToArray(object);\n }\n if (tag == setTag) {\n return setToPairs(object);\n }\n return baseToPairs(object, keysFunc(object));\n };\n }\n\n /**\n * Creates a function that either curries or invokes `func` with optional\n * `this` binding and partially applied arguments.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags.\n * 1 - `_.bind`\n * 2 - `_.bindKey`\n * 4 - `_.curry` or `_.curryRight` of a bound function\n * 8 - `_.curry`\n * 16 - `_.curryRight`\n * 32 - `_.partial`\n * 64 - `_.partialRight`\n * 128 - `_.rearg`\n * 256 - `_.ary`\n * 512 - `_.flip`\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to be partially applied.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {\n var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;\n if (!isBindKey && typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var length = partials ? partials.length : 0;\n if (!length) {\n bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);\n partials = holders = undefined;\n }\n ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);\n arity = arity === undefined ? arity : toInteger(arity);\n length -= holders ? holders.length : 0;\n\n if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {\n var partialsRight = partials,\n holdersRight = holders;\n\n partials = holders = undefined;\n }\n var data = isBindKey ? undefined : getData(func);\n\n var newData = [\n func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,\n argPos, ary, arity\n ];\n\n if (data) {\n mergeData(newData, data);\n }\n func = newData[0];\n bitmask = newData[1];\n thisArg = newData[2];\n partials = newData[3];\n holders = newData[4];\n arity = newData[9] = newData[9] === undefined\n ? (isBindKey ? 0 : func.length)\n : nativeMax(newData[9] - length, 0);\n\n if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {\n bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);\n }\n if (!bitmask || bitmask == WRAP_BIND_FLAG) {\n var result = createBind(func, bitmask, thisArg);\n } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {\n result = createCurry(func, bitmask, arity);\n } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {\n result = createPartial(func, bitmask, thisArg, partials);\n } else {\n result = createHybrid.apply(undefined, newData);\n }\n var setter = data ? baseSetData : setData;\n return setWrapToString(setter(result, newData), func, bitmask);\n }\n\n /**\n * Used by `_.defaults` to customize its `_.assignIn` use to assign properties\n * of source objects to the destination object for all destination properties\n * that resolve to `undefined`.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to assign.\n * @param {Object} object The parent object of `objValue`.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsAssignIn(objValue, srcValue, key, object) {\n if (objValue === undefined ||\n (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n return srcValue;\n }\n return objValue;\n }\n\n /**\n * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source\n * objects into destination objects that are passed thru.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to merge.\n * @param {Object} object The parent object of `objValue`.\n * @param {Object} source The parent object of `srcValue`.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {\n if (isObject(objValue) && isObject(srcValue)) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, objValue);\n baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);\n stack['delete'](srcValue);\n }\n return objValue;\n }\n\n /**\n * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain\n * objects.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {string} key The key of the property to inspect.\n * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.\n */\n function customOmitClone(value) {\n return isPlainObject(value) ? undefined : value;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\n function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n }\n\n /**\n * A specialized version of `baseRest` which flattens the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n function flatRest(func) {\n return setToString(overRest(func, undefined, flatten), func + '');\n }\n\n /**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n }\n\n /**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n }\n\n /**\n * Gets metadata for `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {*} Returns the metadata for `func`.\n */\n var getData = !metaMap ? noop : function(func) {\n return metaMap.get(func);\n };\n\n /**\n * Gets the name of `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {string} Returns the function name.\n */\n function getFuncName(func) {\n var result = (func.name + ''),\n array = realNames[result],\n length = hasOwnProperty.call(realNames, result) ? array.length : 0;\n\n while (length--) {\n var data = array[length],\n otherFunc = data.func;\n if (otherFunc == null || otherFunc == func) {\n return data.name;\n }\n }\n return result;\n }\n\n /**\n * Gets the argument placeholder value for `func`.\n *\n * @private\n * @param {Function} func The function to inspect.\n * @returns {*} Returns the placeholder value.\n */\n function getHolder(func) {\n var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;\n return object.placeholder;\n }\n\n /**\n * Gets the appropriate \"iteratee\" function. If `_.iteratee` is customized,\n * this function returns the custom method, otherwise it returns `baseIteratee`.\n * If arguments are provided, the chosen function is invoked with them and\n * its result is returned.\n *\n * @private\n * @param {*} [value] The value to convert to an iteratee.\n * @param {number} [arity] The arity of the created iteratee.\n * @returns {Function} Returns the chosen function or its result.\n */\n function getIteratee() {\n var result = lodash.iteratee || iteratee;\n result = result === iteratee ? baseIteratee : result;\n return arguments.length ? result(arguments[0], arguments[1]) : result;\n }\n\n /**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\n function getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n }\n\n /**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\n function getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n }\n\n /**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\n function getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n }\n\n /**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\n function getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n }\n\n /**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n };\n\n /**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n };\n\n /**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n var getTag = baseGetTag;\n\n // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\n if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n }\n\n /**\n * Gets the view, applying any `transforms` to the `start` and `end` positions.\n *\n * @private\n * @param {number} start The start of the view.\n * @param {number} end The end of the view.\n * @param {Array} transforms The transformations to apply to the view.\n * @returns {Object} Returns an object containing the `start` and `end`\n * positions of the view.\n */\n function getView(start, end, transforms) {\n var index = -1,\n length = transforms.length;\n\n while (++index < length) {\n var data = transforms[index],\n size = data.size;\n\n switch (data.type) {\n case 'drop': start += size; break;\n case 'dropRight': end -= size; break;\n case 'take': end = nativeMin(end, start + size); break;\n case 'takeRight': start = nativeMax(start, end - size); break;\n }\n }\n return { 'start': start, 'end': end };\n }\n\n /**\n * Extracts wrapper details from the `source` body comment.\n *\n * @private\n * @param {string} source The source to inspect.\n * @returns {Array} Returns the wrapper details.\n */\n function getWrapDetails(source) {\n var match = source.match(reWrapDetails);\n return match ? match[1].split(reSplitDetails) : [];\n }\n\n /**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\n function hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n }\n\n /**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\n function initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n }\n\n /**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n }\n\n /**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n }\n\n /**\n * Inserts wrapper `details` in a comment at the top of the `source` body.\n *\n * @private\n * @param {string} source The source to modify.\n * @returns {Array} details The details to insert.\n * @returns {string} Returns the modified source.\n */\n function insertWrapDetails(source, details) {\n var length = details.length;\n if (!length) {\n return source;\n }\n var lastIndex = length - 1;\n details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];\n details = details.join(length > 2 ? ', ' : ' ');\n return source.replace(reWrapComment, '{\\n/* [wrapped with ' + details + '] */\\n');\n }\n\n /**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\n function isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n }\n\n /**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\n function isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n }\n\n /**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\n function isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n }\n\n /**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\n function isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n }\n\n /**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\n function isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n }\n\n /**\n * Checks if `func` has a lazy counterpart.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` has a lazy counterpart,\n * else `false`.\n */\n function isLaziable(func) {\n var funcName = getFuncName(func),\n other = lodash[funcName];\n\n if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {\n return false;\n }\n if (func === other) {\n return true;\n }\n var data = getData(other);\n return !!data && func === data[0];\n }\n\n /**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\n function isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n }\n\n /**\n * Checks if `func` is capable of being masked.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `func` is maskable, else `false`.\n */\n var isMaskable = coreJsData ? isFunction : stubFalse;\n\n /**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\n function isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n }\n\n /**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\n function isStrictComparable(value) {\n return value === value && !isObject(value);\n }\n\n /**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\n function matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n }\n\n /**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\n function memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n }\n\n /**\n * Merges the function metadata of `source` into `data`.\n *\n * Merging metadata reduces the number of wrappers used to invoke a function.\n * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`\n * may be applied regardless of execution order. Methods like `_.ary` and\n * `_.rearg` modify function arguments, making the order in which they are\n * executed important, preventing the merging of metadata. However, we make\n * an exception for a safe combined case where curried functions have `_.ary`\n * and or `_.rearg` applied.\n *\n * @private\n * @param {Array} data The destination metadata.\n * @param {Array} source The source metadata.\n * @returns {Array} Returns `data`.\n */\n function mergeData(data, source) {\n var bitmask = data[1],\n srcBitmask = source[1],\n newBitmask = bitmask | srcBitmask,\n isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);\n\n var isCombo =\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||\n ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));\n\n // Exit early if metadata can't be merged.\n if (!(isCommon || isCombo)) {\n return data;\n }\n // Use source `thisArg` if available.\n if (srcBitmask & WRAP_BIND_FLAG) {\n data[2] = source[2];\n // Set when currying a bound function.\n newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;\n }\n // Compose partial arguments.\n var value = source[3];\n if (value) {\n var partials = data[3];\n data[3] = partials ? composeArgs(partials, value, source[4]) : value;\n data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];\n }\n // Compose partial right arguments.\n value = source[5];\n if (value) {\n partials = data[5];\n data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;\n data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];\n }\n // Use source `argPos` if available.\n value = source[7];\n if (value) {\n data[7] = value;\n }\n // Use source `ary` if it's smaller.\n if (srcBitmask & WRAP_ARY_FLAG) {\n data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);\n }\n // Use source `arity` if one is not provided.\n if (data[9] == null) {\n data[9] = source[9];\n }\n // Use source `func` and merge bitmasks.\n data[0] = source[0];\n data[1] = newBitmask;\n\n return data;\n }\n\n /**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\n function objectToString(value) {\n return nativeObjectToString.call(value);\n }\n\n /**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\n function overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n }\n\n /**\n * Gets the parent value at `path` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} path The path to get the parent value of.\n * @returns {*} Returns the parent value.\n */\n function parent(object, path) {\n return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));\n }\n\n /**\n * Reorder `array` according to the specified indexes where the element at\n * the first index is assigned as the first element, the element at\n * the second index is assigned as the second element, and so on.\n *\n * @private\n * @param {Array} array The array to reorder.\n * @param {Array} indexes The arranged array indexes.\n * @returns {Array} Returns `array`.\n */\n function reorder(array, indexes) {\n var arrLength = array.length,\n length = nativeMin(indexes.length, arrLength),\n oldArray = copyArray(array);\n\n while (length--) {\n var index = indexes[length];\n array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;\n }\n return array;\n }\n\n /**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n }\n\n /**\n * Sets metadata for `func`.\n *\n * **Note:** If this function becomes hot, i.e. is invoked a lot in a short\n * period of time, it will trip its breaker and transition to an identity\n * function to avoid garbage collection pauses in V8. See\n * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)\n * for more details.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var setData = shortOut(baseSetData);\n\n /**\n * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n var setTimeout = ctxSetTimeout || function(func, wait) {\n return root.setTimeout(func, wait);\n };\n\n /**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\n var setToString = shortOut(baseSetToString);\n\n /**\n * Sets the `toString` method of `wrapper` to mimic the source of `reference`\n * with wrapper details in a comment at the top of the source body.\n *\n * @private\n * @param {Function} wrapper The function to modify.\n * @param {Function} reference The reference function.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Function} Returns `wrapper`.\n */\n function setWrapToString(wrapper, reference, bitmask) {\n var source = (reference + '');\n return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));\n }\n\n /**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\n function shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n }\n\n /**\n * A specialized version of `_.shuffle` which mutates and sets the size of `array`.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @param {number} [size=array.length] The size of `array`.\n * @returns {Array} Returns `array`.\n */\n function shuffleSelf(array, size) {\n var index = -1,\n length = array.length,\n lastIndex = length - 1;\n\n size = size === undefined ? length : size;\n while (++index < size) {\n var rand = baseRandom(index, lastIndex),\n value = array[rand];\n\n array[rand] = array[index];\n array[index] = value;\n }\n array.length = size;\n return array;\n }\n\n /**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\n var stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n });\n\n /**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\n function toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n }\n\n /**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\n function toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n }\n\n /**\n * Updates wrapper `details` based on `bitmask` flags.\n *\n * @private\n * @returns {Array} details The details to modify.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Array} Returns `details`.\n */\n function updateWrapDetails(details, bitmask) {\n arrayEach(wrapFlags, function(pair) {\n var value = '_.' + pair[0];\n if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {\n details.push(value);\n }\n });\n return details.sort();\n }\n\n /**\n * Creates a clone of `wrapper`.\n *\n * @private\n * @param {Object} wrapper The wrapper to clone.\n * @returns {Object} Returns the cloned wrapper.\n */\n function wrapperClone(wrapper) {\n if (wrapper instanceof LazyWrapper) {\n return wrapper.clone();\n }\n var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);\n result.__actions__ = copyArray(wrapper.__actions__);\n result.__index__ = wrapper.__index__;\n result.__values__ = wrapper.__values__;\n return result;\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of elements split into groups the length of `size`.\n * If `array` can't be split evenly, the final chunk will be the remaining\n * elements.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to process.\n * @param {number} [size=1] The length of each chunk\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the new array of chunks.\n * @example\n *\n * _.chunk(['a', 'b', 'c', 'd'], 2);\n * // => [['a', 'b'], ['c', 'd']]\n *\n * _.chunk(['a', 'b', 'c', 'd'], 3);\n * // => [['a', 'b', 'c'], ['d']]\n */\n function chunk(array, size, guard) {\n if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {\n size = 1;\n } else {\n size = nativeMax(toInteger(size), 0);\n }\n var length = array == null ? 0 : array.length;\n if (!length || size < 1) {\n return [];\n }\n var index = 0,\n resIndex = 0,\n result = Array(nativeCeil(length / size));\n\n while (index < length) {\n result[resIndex++] = baseSlice(array, index, (index += size));\n }\n return result;\n }\n\n /**\n * Creates an array with all falsey values removed. The values `false`, `null`,\n * `0`, `\"\"`, `undefined`, and `NaN` are falsey.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to compact.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.compact([0, 1, false, 2, '', 3]);\n * // => [1, 2, 3]\n */\n function compact(array) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * Creates a new array concatenating `array` with any additional arrays\n * and/or values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to concatenate.\n * @param {...*} [values] The values to concatenate.\n * @returns {Array} Returns the new concatenated array.\n * @example\n *\n * var array = [1];\n * var other = _.concat(array, 2, [3], [[4]]);\n *\n * console.log(other);\n * // => [1, 2, 3, [4]]\n *\n * console.log(array);\n * // => [1]\n */\n function concat() {\n var length = arguments.length;\n if (!length) {\n return [];\n }\n var args = Array(length - 1),\n array = arguments[0],\n index = length;\n\n while (index--) {\n args[index - 1] = arguments[index];\n }\n return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));\n }\n\n /**\n * Creates an array of `array` values not included in the other given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * **Note:** Unlike `_.pullAll`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.without, _.xor\n * @example\n *\n * _.difference([2, 1], [2, 3]);\n * // => [1]\n */\n var difference = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `iteratee` which\n * is invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * **Note:** Unlike `_.pullAllBy`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var differenceBy = baseRest(function(array, values) {\n var iteratee = last(values);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `comparator`\n * which is invoked to compare elements of `array` to `values`. The order and\n * references of result values are determined by the first array. The comparator\n * is invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.pullAllWith`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n *\n * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }]\n */\n var differenceWith = baseRest(function(array, values) {\n var comparator = last(values);\n if (isArrayLikeObject(comparator)) {\n comparator = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)\n : [];\n });\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.drop([1, 2, 3]);\n * // => [2, 3]\n *\n * _.drop([1, 2, 3], 2);\n * // => [3]\n *\n * _.drop([1, 2, 3], 5);\n * // => []\n *\n * _.drop([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function drop(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.dropRight([1, 2, 3]);\n * // => [1, 2]\n *\n * _.dropRight([1, 2, 3], 2);\n * // => [1]\n *\n * _.dropRight([1, 2, 3], 5);\n * // => []\n *\n * _.dropRight([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function dropRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the end.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.dropRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropRightWhile(users, ['active', false]);\n * // => objects for ['barney']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropRightWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the beginning.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.dropWhile(users, function(o) { return !o.active; });\n * // => objects for ['pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropWhile(users, ['active', false]);\n * // => objects for ['pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true)\n : [];\n }\n\n /**\n * Fills elements of `array` with `value` from `start` up to, but not\n * including, `end`.\n *\n * **Note:** This method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Array\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.fill(array, 'a');\n * console.log(array);\n * // => ['a', 'a', 'a']\n *\n * _.fill(Array(3), 2);\n * // => [2, 2, 2]\n *\n * _.fill([4, 6, 8, 10], '*', 1, 3);\n * // => [4, '*', '*', 10]\n */\n function fill(array, value, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {\n start = 0;\n end = length;\n }\n return baseFill(array, value, start, end);\n }\n\n /**\n * This method is like `_.find` except that it returns the index of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.findIndex(users, function(o) { return o.user == 'barney'; });\n * // => 0\n *\n * // The `_.matches` iteratee shorthand.\n * _.findIndex(users, { 'user': 'fred', 'active': false });\n * // => 1\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findIndex(users, ['active', false]);\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.findIndex(users, 'active');\n * // => 2\n */\n function findIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index);\n }\n\n /**\n * This method is like `_.findIndex` except that it iterates over elements\n * of `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });\n * // => 2\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastIndex(users, { 'user': 'barney', 'active': true });\n * // => 0\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastIndex(users, ['active', false]);\n * // => 2\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastIndex(users, 'active');\n * // => 0\n */\n function findLastIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length - 1;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = fromIndex < 0\n ? nativeMax(length + index, 0)\n : nativeMin(index, length - 1);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index, true);\n }\n\n /**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\n function flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n }\n\n /**\n * Recursively flattens `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flattenDeep([1, [2, [3, [4]], 5]]);\n * // => [1, 2, 3, 4, 5]\n */\n function flattenDeep(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, INFINITY) : [];\n }\n\n /**\n * Recursively flatten `array` up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * var array = [1, [2, [3, [4]], 5]];\n *\n * _.flattenDepth(array, 1);\n * // => [1, 2, [3, [4]], 5]\n *\n * _.flattenDepth(array, 2);\n * // => [1, 2, 3, [4], 5]\n */\n function flattenDepth(array, depth) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(array, depth);\n }\n\n /**\n * The inverse of `_.toPairs`; this method returns an object composed\n * from key-value `pairs`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} pairs The key-value pairs.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.fromPairs([['a', 1], ['b', 2]]);\n * // => { 'a': 1, 'b': 2 }\n */\n function fromPairs(pairs) {\n var index = -1,\n length = pairs == null ? 0 : pairs.length,\n result = {};\n\n while (++index < length) {\n var pair = pairs[index];\n result[pair[0]] = pair[1];\n }\n return result;\n }\n\n /**\n * Gets the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias first\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the first element of `array`.\n * @example\n *\n * _.head([1, 2, 3]);\n * // => 1\n *\n * _.head([]);\n * // => undefined\n */\n function head(array) {\n return (array && array.length) ? array[0] : undefined;\n }\n\n /**\n * Gets the index at which the first occurrence of `value` is found in `array`\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. If `fromIndex` is negative, it's used as the\n * offset from the end of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.indexOf([1, 2, 1, 2], 2);\n * // => 1\n *\n * // Search from the `fromIndex`.\n * _.indexOf([1, 2, 1, 2], 2, 2);\n * // => 3\n */\n function indexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseIndexOf(array, value, index);\n }\n\n /**\n * Gets all but the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.initial([1, 2, 3]);\n * // => [1, 2]\n */\n function initial(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 0, -1) : [];\n }\n\n /**\n * Creates an array of unique values that are included in all given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersection([2, 1], [2, 3]);\n * // => [2]\n */\n var intersection = baseRest(function(arrays) {\n var mapped = arrayMap(arrays, castArrayLikeObject);\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped)\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `iteratee`\n * which is invoked for each element of each `arrays` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [2.1]\n *\n * // The `_.property` iteratee shorthand.\n * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }]\n */\n var intersectionBy = baseRest(function(arrays) {\n var iteratee = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n if (iteratee === last(mapped)) {\n iteratee = undefined;\n } else {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `comparator`\n * which is invoked to compare elements of `arrays`. The order and references\n * of result values are determined by the first array. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.intersectionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }]\n */\n var intersectionWith = baseRest(function(arrays) {\n var comparator = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n comparator = typeof comparator == 'function' ? comparator : undefined;\n if (comparator) {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, undefined, comparator)\n : [];\n });\n\n /**\n * Converts all elements in `array` into a string separated by `separator`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to convert.\n * @param {string} [separator=','] The element separator.\n * @returns {string} Returns the joined string.\n * @example\n *\n * _.join(['a', 'b', 'c'], '~');\n * // => 'a~b~c'\n */\n function join(array, separator) {\n return array == null ? '' : nativeJoin.call(array, separator);\n }\n\n /**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\n function last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n }\n\n /**\n * This method is like `_.indexOf` except that it iterates over elements of\n * `array` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.lastIndexOf([1, 2, 1, 2], 2);\n * // => 3\n *\n * // Search from the `fromIndex`.\n * _.lastIndexOf([1, 2, 1, 2], 2, 2);\n * // => 1\n */\n function lastIndexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);\n }\n return value === value\n ? strictLastIndexOf(array, value, index)\n : baseFindIndex(array, baseIsNaN, index, true);\n }\n\n /**\n * Gets the element at index `n` of `array`. If `n` is negative, the nth\n * element from the end is returned.\n *\n * @static\n * @memberOf _\n * @since 4.11.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=0] The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n *\n * _.nth(array, 1);\n * // => 'b'\n *\n * _.nth(array, -2);\n * // => 'c';\n */\n function nth(array, n) {\n return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;\n }\n\n /**\n * Removes all given values from `array` using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`\n * to remove elements from an array by predicate.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...*} [values] The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pull(array, 'a', 'c');\n * console.log(array);\n * // => ['b', 'b']\n */\n var pull = baseRest(pullAll);\n\n /**\n * This method is like `_.pull` except that it accepts an array of values to remove.\n *\n * **Note:** Unlike `_.difference`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pullAll(array, ['a', 'c']);\n * console.log(array);\n * // => ['b', 'b']\n */\n function pullAll(array, values) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values)\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `iteratee` which is\n * invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The iteratee is invoked with one argument: (value).\n *\n * **Note:** Unlike `_.differenceBy`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];\n *\n * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');\n * console.log(array);\n * // => [{ 'x': 2 }]\n */\n function pullAllBy(array, values, iteratee) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, getIteratee(iteratee, 2))\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `comparator` which\n * is invoked to compare elements of `array` to `values`. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.differenceWith`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];\n *\n * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);\n * console.log(array);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]\n */\n function pullAllWith(array, values, comparator) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, undefined, comparator)\n : array;\n }\n\n /**\n * Removes elements from `array` corresponding to `indexes` and returns an\n * array of removed elements.\n *\n * **Note:** Unlike `_.at`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...(number|number[])} [indexes] The indexes of elements to remove.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n * var pulled = _.pullAt(array, [1, 3]);\n *\n * console.log(array);\n * // => ['a', 'c']\n *\n * console.log(pulled);\n * // => ['b', 'd']\n */\n var pullAt = flatRest(function(array, indexes) {\n var length = array == null ? 0 : array.length,\n result = baseAt(array, indexes);\n\n basePullAt(array, arrayMap(indexes, function(index) {\n return isIndex(index, length) ? +index : index;\n }).sort(compareAscending));\n\n return result;\n });\n\n /**\n * Removes all elements from `array` that `predicate` returns truthy for\n * and returns an array of the removed elements. The predicate is invoked\n * with three arguments: (value, index, array).\n *\n * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`\n * to pull elements from an array by value.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = [1, 2, 3, 4];\n * var evens = _.remove(array, function(n) {\n * return n % 2 == 0;\n * });\n *\n * console.log(array);\n * // => [1, 3]\n *\n * console.log(evens);\n * // => [2, 4]\n */\n function remove(array, predicate) {\n var result = [];\n if (!(array && array.length)) {\n return result;\n }\n var index = -1,\n indexes = [],\n length = array.length;\n\n predicate = getIteratee(predicate, 3);\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result.push(value);\n indexes.push(index);\n }\n }\n basePullAt(array, indexes);\n return result;\n }\n\n /**\n * Reverses `array` so that the first element becomes the last, the second\n * element becomes the second to last, and so on.\n *\n * **Note:** This method mutates `array` and is based on\n * [`Array#reverse`](https://mdn.io/Array/reverse).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.reverse(array);\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function reverse(array) {\n return array == null ? array : nativeReverse.call(array);\n }\n\n /**\n * Creates a slice of `array` from `start` up to, but not including, `end`.\n *\n * **Note:** This method is used instead of\n * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are\n * returned.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function slice(array, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {\n start = 0;\n end = length;\n }\n else {\n start = start == null ? 0 : toInteger(start);\n end = end === undefined ? length : toInteger(end);\n }\n return baseSlice(array, start, end);\n }\n\n /**\n * Uses a binary search to determine the lowest index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedIndex([30, 50], 40);\n * // => 1\n */\n function sortedIndex(array, value) {\n return baseSortedIndex(array, value);\n }\n\n /**\n * This method is like `_.sortedIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedIndexBy(objects, { 'x': 4 }, 'x');\n * // => 0\n */\n function sortedIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));\n }\n\n /**\n * This method is like `_.indexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedIndexOf([4, 5, 5, 5, 6], 5);\n * // => 1\n */\n function sortedIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value);\n if (index < length && eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.sortedIndex` except that it returns the highest\n * index at which `value` should be inserted into `array` in order to\n * maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedLastIndex([4, 5, 5, 5, 6], 5);\n * // => 4\n */\n function sortedLastIndex(array, value) {\n return baseSortedIndex(array, value, true);\n }\n\n /**\n * This method is like `_.sortedLastIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 1\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');\n * // => 1\n */\n function sortedLastIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);\n }\n\n /**\n * This method is like `_.lastIndexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);\n * // => 3\n */\n function sortedLastIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value, true) - 1;\n if (eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.uniq` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniq([1, 1, 2]);\n * // => [1, 2]\n */\n function sortedUniq(array) {\n return (array && array.length)\n ? baseSortedUniq(array)\n : [];\n }\n\n /**\n * This method is like `_.uniqBy` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);\n * // => [1.1, 2.3]\n */\n function sortedUniqBy(array, iteratee) {\n return (array && array.length)\n ? baseSortedUniq(array, getIteratee(iteratee, 2))\n : [];\n }\n\n /**\n * Gets all but the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.tail([1, 2, 3]);\n * // => [2, 3]\n */\n function tail(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 1, length) : [];\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.take([1, 2, 3]);\n * // => [1]\n *\n * _.take([1, 2, 3], 2);\n * // => [1, 2]\n *\n * _.take([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.take([1, 2, 3], 0);\n * // => []\n */\n function take(array, n, guard) {\n if (!(array && array.length)) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.takeRight([1, 2, 3]);\n * // => [3]\n *\n * _.takeRight([1, 2, 3], 2);\n * // => [2, 3]\n *\n * _.takeRight([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.takeRight([1, 2, 3], 0);\n * // => []\n */\n function takeRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with elements taken from the end. Elements are\n * taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.takeRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeRightWhile(users, ['active', false]);\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeRightWhile(users, 'active');\n * // => []\n */\n function takeRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), false, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` with elements taken from the beginning. Elements\n * are taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.takeWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeWhile(users, ['active', false]);\n * // => objects for ['barney', 'fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeWhile(users, 'active');\n * // => []\n */\n function takeWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3))\n : [];\n }\n\n /**\n * Creates an array of unique values, in order, from all given arrays using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.union([2], [1, 2]);\n * // => [2, 1]\n */\n var union = baseRest(function(arrays) {\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));\n });\n\n /**\n * This method is like `_.union` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which uniqueness is computed. Result values are chosen from the first\n * array in which the value occurs. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.unionBy([2.1], [1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n var unionBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.union` except that it accepts `comparator` which\n * is invoked to compare elements of `arrays`. Result values are chosen from\n * the first array in which the value occurs. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.unionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var unionWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);\n });\n\n /**\n * Creates a duplicate-free version of an array, using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons, in which only the first occurrence of each element\n * is kept. The order of result values is determined by the order they occur\n * in the array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniq([2, 1, 2]);\n * // => [2, 1]\n */\n function uniq(array) {\n return (array && array.length) ? baseUniq(array) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `iteratee` which is\n * invoked for each element in `array` to generate the criterion by which\n * uniqueness is computed. The order of result values is determined by the\n * order they occur in the array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniqBy([2.1, 1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n function uniqBy(array, iteratee) {\n return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `comparator` which\n * is invoked to compare elements of `array`. The order of result values is\n * determined by the order they occur in the array.The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.uniqWith(objects, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]\n */\n function uniqWith(array, comparator) {\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return (array && array.length) ? baseUniq(array, undefined, comparator) : [];\n }\n\n /**\n * This method is like `_.zip` except that it accepts an array of grouped\n * elements and creates an array regrouping the elements to their pre-zip\n * configuration.\n *\n * @static\n * @memberOf _\n * @since 1.2.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n *\n * _.unzip(zipped);\n * // => [['a', 'b'], [1, 2], [true, false]]\n */\n function unzip(array) {\n if (!(array && array.length)) {\n return [];\n }\n var length = 0;\n array = arrayFilter(array, function(group) {\n if (isArrayLikeObject(group)) {\n length = nativeMax(group.length, length);\n return true;\n }\n });\n return baseTimes(length, function(index) {\n return arrayMap(array, baseProperty(index));\n });\n }\n\n /**\n * This method is like `_.unzip` except that it accepts `iteratee` to specify\n * how regrouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * regrouped values.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip([1, 2], [10, 20], [100, 200]);\n * // => [[1, 10, 100], [2, 20, 200]]\n *\n * _.unzipWith(zipped, _.add);\n * // => [3, 30, 300]\n */\n function unzipWith(array, iteratee) {\n if (!(array && array.length)) {\n return [];\n }\n var result = unzip(array);\n if (iteratee == null) {\n return result;\n }\n return arrayMap(result, function(group) {\n return apply(iteratee, undefined, group);\n });\n }\n\n /**\n * Creates an array excluding all given values using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.pull`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...*} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.xor\n * @example\n *\n * _.without([2, 1, 2, 3], 1, 2);\n * // => [3]\n */\n var without = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, values)\n : [];\n });\n\n /**\n * Creates an array of unique values that is the\n * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)\n * of the given arrays. The order of result values is determined by the order\n * they occur in the arrays.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.without\n * @example\n *\n * _.xor([2, 1], [2, 3]);\n * // => [1, 3]\n */\n var xor = baseRest(function(arrays) {\n return baseXor(arrayFilter(arrays, isArrayLikeObject));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which by which they're compared. The order of result values is determined\n * by the order they occur in the arrays. The iteratee is invoked with one\n * argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2, 3.4]\n *\n * // The `_.property` iteratee shorthand.\n * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var xorBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `comparator` which is\n * invoked to compare elements of `arrays`. The order of result values is\n * determined by the order they occur in the arrays. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.xorWith(objects, others, _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var xorWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);\n });\n\n /**\n * Creates an array of grouped elements, the first of which contains the\n * first elements of the given arrays, the second of which contains the\n * second elements of the given arrays, and so on.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n */\n var zip = baseRest(unzip);\n\n /**\n * This method is like `_.fromPairs` except that it accepts two arrays,\n * one of property identifiers and one of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 0.4.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObject(['a', 'b'], [1, 2]);\n * // => { 'a': 1, 'b': 2 }\n */\n function zipObject(props, values) {\n return baseZipObject(props || [], values || [], assignValue);\n }\n\n /**\n * This method is like `_.zipObject` except that it supports property paths.\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);\n * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }\n */\n function zipObjectDeep(props, values) {\n return baseZipObject(props || [], values || [], baseSet);\n }\n\n /**\n * This method is like `_.zip` except that it accepts `iteratee` to specify\n * how grouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * grouped values.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {\n * return a + b + c;\n * });\n * // => [111, 222]\n */\n var zipWith = baseRest(function(arrays) {\n var length = arrays.length,\n iteratee = length > 1 ? arrays[length - 1] : undefined;\n\n iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;\n return unzipWith(arrays, iteratee);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` wrapper instance that wraps `value` with explicit method\n * chain sequences enabled. The result of such sequences must be unwrapped\n * with `_#value`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Seq\n * @param {*} value The value to wrap.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'pebbles', 'age': 1 }\n * ];\n *\n * var youngest = _\n * .chain(users)\n * .sortBy('age')\n * .map(function(o) {\n * return o.user + ' is ' + o.age;\n * })\n * .head()\n * .value();\n * // => 'pebbles is 1'\n */\n function chain(value) {\n var result = lodash(value);\n result.__chain__ = true;\n return result;\n }\n\n /**\n * This method invokes `interceptor` and returns `value`. The interceptor\n * is invoked with one argument; (value). The purpose of this method is to\n * \"tap into\" a method chain sequence in order to modify intermediate results.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns `value`.\n * @example\n *\n * _([1, 2, 3])\n * .tap(function(array) {\n * // Mutate input array.\n * array.pop();\n * })\n * .reverse()\n * .value();\n * // => [2, 1]\n */\n function tap(value, interceptor) {\n interceptor(value);\n return value;\n }\n\n /**\n * This method is like `_.tap` except that it returns the result of `interceptor`.\n * The purpose of this method is to \"pass thru\" values replacing intermediate\n * results in a method chain sequence.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns the result of `interceptor`.\n * @example\n *\n * _(' abc ')\n * .chain()\n * .trim()\n * .thru(function(value) {\n * return [value];\n * })\n * .value();\n * // => ['abc']\n */\n function thru(value, interceptor) {\n return interceptor(value);\n }\n\n /**\n * This method is the wrapper version of `_.at`.\n *\n * @name at\n * @memberOf _\n * @since 1.0.0\n * @category Seq\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _(object).at(['a[0].b.c', 'a[1]']).value();\n * // => [3, 4]\n */\n var wrapperAt = flatRest(function(paths) {\n var length = paths.length,\n start = length ? paths[0] : 0,\n value = this.__wrapped__,\n interceptor = function(object) { return baseAt(object, paths); };\n\n if (length > 1 || this.__actions__.length ||\n !(value instanceof LazyWrapper) || !isIndex(start)) {\n return this.thru(interceptor);\n }\n value = value.slice(start, +start + (length ? 1 : 0));\n value.__actions__.push({\n 'func': thru,\n 'args': [interceptor],\n 'thisArg': undefined\n });\n return new LodashWrapper(value, this.__chain__).thru(function(array) {\n if (length && !array.length) {\n array.push(undefined);\n }\n return array;\n });\n });\n\n /**\n * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.\n *\n * @name chain\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 }\n * ];\n *\n * // A sequence without explicit chaining.\n * _(users).head();\n * // => { 'user': 'barney', 'age': 36 }\n *\n * // A sequence with explicit chaining.\n * _(users)\n * .chain()\n * .head()\n * .pick('user')\n * .value();\n * // => { 'user': 'barney' }\n */\n function wrapperChain() {\n return chain(this);\n }\n\n /**\n * Executes the chain sequence and returns the wrapped result.\n *\n * @name commit\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2];\n * var wrapped = _(array).push(3);\n *\n * console.log(array);\n * // => [1, 2]\n *\n * wrapped = wrapped.commit();\n * console.log(array);\n * // => [1, 2, 3]\n *\n * wrapped.last();\n * // => 3\n *\n * console.log(array);\n * // => [1, 2, 3]\n */\n function wrapperCommit() {\n return new LodashWrapper(this.value(), this.__chain__);\n }\n\n /**\n * Gets the next value on a wrapped object following the\n * [iterator protocol](https://mdn.io/iteration_protocols#iterator).\n *\n * @name next\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the next iterator value.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 1 }\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 2 }\n *\n * wrapped.next();\n * // => { 'done': true, 'value': undefined }\n */\n function wrapperNext() {\n if (this.__values__ === undefined) {\n this.__values__ = toArray(this.value());\n }\n var done = this.__index__ >= this.__values__.length,\n value = done ? undefined : this.__values__[this.__index__++];\n\n return { 'done': done, 'value': value };\n }\n\n /**\n * Enables the wrapper to be iterable.\n *\n * @name Symbol.iterator\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the wrapper object.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped[Symbol.iterator]() === wrapped;\n * // => true\n *\n * Array.from(wrapped);\n * // => [1, 2]\n */\n function wrapperToIterator() {\n return this;\n }\n\n /**\n * Creates a clone of the chain sequence planting `value` as the wrapped value.\n *\n * @name plant\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @param {*} value The value to plant.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2]).map(square);\n * var other = wrapped.plant([3, 4]);\n *\n * other.value();\n * // => [9, 16]\n *\n * wrapped.value();\n * // => [1, 4]\n */\n function wrapperPlant(value) {\n var result,\n parent = this;\n\n while (parent instanceof baseLodash) {\n var clone = wrapperClone(parent);\n clone.__index__ = 0;\n clone.__values__ = undefined;\n if (result) {\n previous.__wrapped__ = clone;\n } else {\n result = clone;\n }\n var previous = clone;\n parent = parent.__wrapped__;\n }\n previous.__wrapped__ = value;\n return result;\n }\n\n /**\n * This method is the wrapper version of `_.reverse`.\n *\n * **Note:** This method mutates the wrapped array.\n *\n * @name reverse\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _(array).reverse().value()\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function wrapperReverse() {\n var value = this.__wrapped__;\n if (value instanceof LazyWrapper) {\n var wrapped = value;\n if (this.__actions__.length) {\n wrapped = new LazyWrapper(this);\n }\n wrapped = wrapped.reverse();\n wrapped.__actions__.push({\n 'func': thru,\n 'args': [reverse],\n 'thisArg': undefined\n });\n return new LodashWrapper(wrapped, this.__chain__);\n }\n return this.thru(reverse);\n }\n\n /**\n * Executes the chain sequence to resolve the unwrapped value.\n *\n * @name value\n * @memberOf _\n * @since 0.1.0\n * @alias toJSON, valueOf\n * @category Seq\n * @returns {*} Returns the resolved unwrapped value.\n * @example\n *\n * _([1, 2, 3]).value();\n * // => [1, 2, 3]\n */\n function wrapperValue() {\n return baseWrapperValue(this.__wrapped__, this.__actions__);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the number of times the key was returned by `iteratee`. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.countBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': 1, '6': 2 }\n *\n * // The `_.property` iteratee shorthand.\n * _.countBy(['one', 'two', 'three'], 'length');\n * // => { '3': 2, '5': 1 }\n */\n var countBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n ++result[key];\n } else {\n baseAssignValue(result, key, 1);\n }\n });\n\n /**\n * Checks if `predicate` returns truthy for **all** elements of `collection`.\n * Iteration is stopped once `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * **Note:** This method returns `true` for\n * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because\n * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of\n * elements of empty collections.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n * @example\n *\n * _.every([true, 1, null, 'yes'], Boolean);\n * // => false\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.every(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.every(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.every(users, 'active');\n * // => false\n */\n function every(collection, predicate, guard) {\n var func = isArray(collection) ? arrayEvery : baseEvery;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning an array of all elements\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * **Note:** Unlike `_.remove`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.reject\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * _.filter(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.filter(users, { 'age': 36, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.filter(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.filter(users, 'active');\n * // => objects for ['barney']\n *\n * // Combining several predicates using `_.overEvery` or `_.overSome`.\n * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));\n * // => objects for ['fred', 'barney']\n */\n function filter(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning the first element\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false },\n * { 'user': 'pebbles', 'age': 1, 'active': true }\n * ];\n *\n * _.find(users, function(o) { return o.age < 40; });\n * // => object for 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.find(users, { 'age': 1, 'active': true });\n * // => object for 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.find(users, ['active', false]);\n * // => object for 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.find(users, 'active');\n * // => object for 'barney'\n */\n var find = createFind(findIndex);\n\n /**\n * This method is like `_.find` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=collection.length-1] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * _.findLast([1, 2, 3, 4], function(n) {\n * return n % 2 == 1;\n * });\n * // => 3\n */\n var findLast = createFind(findLastIndex);\n\n /**\n * Creates a flattened array of values by running each element in `collection`\n * thru `iteratee` and flattening the mapped results. The iteratee is invoked\n * with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [n, n];\n * }\n *\n * _.flatMap([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMap(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), 1);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results.\n *\n * @static\n * @memberOf _\n * @since 4.7.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDeep([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMapDeep(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), INFINITY);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.7.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDepth([1, 2], duplicate, 2);\n * // => [[1, 1], [2, 2]]\n */\n function flatMapDepth(collection, iteratee, depth) {\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(map(collection, iteratee), depth);\n }\n\n /**\n * Iterates over elements of `collection` and invokes `iteratee` for each element.\n * The iteratee is invoked with three arguments: (value, index|key, collection).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * **Note:** As with other \"Collections\" methods, objects with a \"length\"\n * property are iterated like arrays. To avoid this behavior use `_.forIn`\n * or `_.forOwn` for object iteration.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias each\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEachRight\n * @example\n *\n * _.forEach([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `1` then `2`.\n *\n * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forEach(collection, iteratee) {\n var func = isArray(collection) ? arrayEach : baseEach;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forEach` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @alias eachRight\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEach\n * @example\n *\n * _.forEachRight([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `2` then `1`.\n */\n function forEachRight(collection, iteratee) {\n var func = isArray(collection) ? arrayEachRight : baseEachRight;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The order of grouped values\n * is determined by the order they occur in `collection`. The corresponding\n * value of each key is an array of elements responsible for generating the\n * key. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.groupBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': [4.2], '6': [6.1, 6.3] }\n *\n * // The `_.property` iteratee shorthand.\n * _.groupBy(['one', 'two', 'three'], 'length');\n * // => { '3': ['one', 'two'], '5': ['three'] }\n */\n var groupBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n result[key].push(value);\n } else {\n baseAssignValue(result, key, [value]);\n }\n });\n\n /**\n * Checks if `value` is in `collection`. If `collection` is a string, it's\n * checked for a substring of `value`, otherwise\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * is used for equality comparisons. If `fromIndex` is negative, it's used as\n * the offset from the end of `collection`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {boolean} Returns `true` if `value` is found, else `false`.\n * @example\n *\n * _.includes([1, 2, 3], 1);\n * // => true\n *\n * _.includes([1, 2, 3], 1, 2);\n * // => false\n *\n * _.includes({ 'a': 1, 'b': 2 }, 1);\n * // => true\n *\n * _.includes('abcd', 'bc');\n * // => true\n */\n function includes(collection, value, fromIndex, guard) {\n collection = isArrayLike(collection) ? collection : values(collection);\n fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;\n\n var length = collection.length;\n if (fromIndex < 0) {\n fromIndex = nativeMax(length + fromIndex, 0);\n }\n return isString(collection)\n ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)\n : (!!length && baseIndexOf(collection, value, fromIndex) > -1);\n }\n\n /**\n * Invokes the method at `path` of each element in `collection`, returning\n * an array of the results of each invoked method. Any additional arguments\n * are provided to each invoked method. If `path` is a function, it's invoked\n * for, and `this` bound to, each element in `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array|Function|string} path The path of the method to invoke or\n * the function invoked per iteration.\n * @param {...*} [args] The arguments to invoke each method with.\n * @returns {Array} Returns the array of results.\n * @example\n *\n * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');\n * // => [[1, 5, 7], [1, 2, 3]]\n *\n * _.invokeMap([123, 456], String.prototype.split, '');\n * // => [['1', '2', '3'], ['4', '5', '6']]\n */\n var invokeMap = baseRest(function(collection, path, args) {\n var index = -1,\n isFunc = typeof path == 'function',\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value) {\n result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);\n });\n return result;\n });\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the last element responsible for generating the key. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * var array = [\n * { 'dir': 'left', 'code': 97 },\n * { 'dir': 'right', 'code': 100 }\n * ];\n *\n * _.keyBy(array, function(o) {\n * return String.fromCharCode(o.code);\n * });\n * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }\n *\n * _.keyBy(array, 'dir');\n * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }\n */\n var keyBy = createAggregator(function(result, value, key) {\n baseAssignValue(result, key, value);\n });\n\n /**\n * Creates an array of values by running each element in `collection` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n *\n * The guarded methods are:\n * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,\n * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,\n * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,\n * `template`, `trim`, `trimEnd`, `trimStart`, and `words`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * _.map([4, 8], square);\n * // => [16, 64]\n *\n * _.map({ 'a': 4, 'b': 8 }, square);\n * // => [16, 64] (iteration order is not guaranteed)\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * // The `_.property` iteratee shorthand.\n * _.map(users, 'user');\n * // => ['barney', 'fred']\n */\n function map(collection, iteratee) {\n var func = isArray(collection) ? arrayMap : baseMap;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.sortBy` except that it allows specifying the sort\n * orders of the iteratees to sort by. If `orders` is unspecified, all values\n * are sorted in ascending order. Otherwise, specify an order of \"desc\" for\n * descending or \"asc\" for ascending sort order of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @param {string[]} [orders] The sort orders of `iteratees`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 34 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'barney', 'age': 36 }\n * ];\n *\n * // Sort by `user` in ascending order and by `age` in descending order.\n * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]\n */\n function orderBy(collection, iteratees, orders, guard) {\n if (collection == null) {\n return [];\n }\n if (!isArray(iteratees)) {\n iteratees = iteratees == null ? [] : [iteratees];\n }\n orders = guard ? undefined : orders;\n if (!isArray(orders)) {\n orders = orders == null ? [] : [orders];\n }\n return baseOrderBy(collection, iteratees, orders);\n }\n\n /**\n * Creates an array of elements split into two groups, the first of which\n * contains elements `predicate` returns truthy for, the second of which\n * contains elements `predicate` returns falsey for. The predicate is\n * invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the array of grouped elements.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true },\n * { 'user': 'pebbles', 'age': 1, 'active': false }\n * ];\n *\n * _.partition(users, function(o) { return o.active; });\n * // => objects for [['fred'], ['barney', 'pebbles']]\n *\n * // The `_.matches` iteratee shorthand.\n * _.partition(users, { 'age': 1, 'active': false });\n * // => objects for [['pebbles'], ['barney', 'fred']]\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.partition(users, ['active', false]);\n * // => objects for [['barney', 'pebbles'], ['fred']]\n *\n * // The `_.property` iteratee shorthand.\n * _.partition(users, 'active');\n * // => objects for [['fred'], ['barney', 'pebbles']]\n */\n var partition = createAggregator(function(result, value, key) {\n result[key ? 0 : 1].push(value);\n }, function() { return [[], []]; });\n\n /**\n * Reduces `collection` to a value which is the accumulated result of running\n * each element in `collection` thru `iteratee`, where each successive\n * invocation is supplied the return value of the previous. If `accumulator`\n * is not given, the first element of `collection` is used as the initial\n * value. The iteratee is invoked with four arguments:\n * (accumulator, value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.reduce`, `_.reduceRight`, and `_.transform`.\n *\n * The guarded methods are:\n * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,\n * and `sortBy`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduceRight\n * @example\n *\n * _.reduce([1, 2], function(sum, n) {\n * return sum + n;\n * }, 0);\n * // => 3\n *\n * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * return result;\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)\n */\n function reduce(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduce : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);\n }\n\n /**\n * This method is like `_.reduce` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduce\n * @example\n *\n * var array = [[0, 1], [2, 3], [4, 5]];\n *\n * _.reduceRight(array, function(flattened, other) {\n * return flattened.concat(other);\n * }, []);\n * // => [4, 5, 2, 3, 0, 1]\n */\n function reduceRight(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduceRight : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);\n }\n\n /**\n * The opposite of `_.filter`; this method returns the elements of `collection`\n * that `predicate` does **not** return truthy for.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.filter\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true }\n * ];\n *\n * _.reject(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.reject(users, { 'age': 40, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.reject(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.reject(users, 'active');\n * // => objects for ['barney']\n */\n function reject(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, negate(getIteratee(predicate, 3)));\n }\n\n /**\n * Gets a random element from `collection`.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n * @example\n *\n * _.sample([1, 2, 3, 4]);\n * // => 2\n */\n function sample(collection) {\n var func = isArray(collection) ? arraySample : baseSample;\n return func(collection);\n }\n\n /**\n * Gets `n` random elements at unique keys from `collection` up to the\n * size of `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @param {number} [n=1] The number of elements to sample.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the random elements.\n * @example\n *\n * _.sampleSize([1, 2, 3], 2);\n * // => [3, 1]\n *\n * _.sampleSize([1, 2, 3], 4);\n * // => [2, 3, 1]\n */\n function sampleSize(collection, n, guard) {\n if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n var func = isArray(collection) ? arraySampleSize : baseSampleSize;\n return func(collection, n);\n }\n\n /**\n * Creates an array of shuffled values, using a version of the\n * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n * @example\n *\n * _.shuffle([1, 2, 3, 4]);\n * // => [4, 1, 3, 2]\n */\n function shuffle(collection) {\n var func = isArray(collection) ? arrayShuffle : baseShuffle;\n return func(collection);\n }\n\n /**\n * Gets the size of `collection` by returning its length for array-like\n * values or the number of own enumerable string keyed properties for objects.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @returns {number} Returns the collection size.\n * @example\n *\n * _.size([1, 2, 3]);\n * // => 3\n *\n * _.size({ 'a': 1, 'b': 2 });\n * // => 2\n *\n * _.size('pebbles');\n * // => 7\n */\n function size(collection) {\n if (collection == null) {\n return 0;\n }\n if (isArrayLike(collection)) {\n return isString(collection) ? stringSize(collection) : collection.length;\n }\n var tag = getTag(collection);\n if (tag == mapTag || tag == setTag) {\n return collection.size;\n }\n return baseKeys(collection).length;\n }\n\n /**\n * Checks if `predicate` returns truthy for **any** element of `collection`.\n * Iteration is stopped once `predicate` returns truthy. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n * @example\n *\n * _.some([null, 0, 'yes', false], Boolean);\n * // => true\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.some(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.some(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.some(users, 'active');\n * // => true\n */\n function some(collection, predicate, guard) {\n var func = isArray(collection) ? arraySome : baseSome;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Creates an array of elements, sorted in ascending order by the results of\n * running each element in a collection thru each iteratee. This method\n * performs a stable sort, that is, it preserves the original sort order of\n * equal elements. The iteratees are invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {...(Function|Function[])} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 30 },\n * { 'user': 'barney', 'age': 34 }\n * ];\n *\n * _.sortBy(users, [function(o) { return o.user; }]);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]\n *\n * _.sortBy(users, ['user', 'age']);\n * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]\n */\n var sortBy = baseRest(function(collection, iteratees) {\n if (collection == null) {\n return [];\n }\n var length = iteratees.length;\n if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {\n iteratees = [];\n } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {\n iteratees = [iteratees[0]];\n }\n return baseOrderBy(collection, baseFlatten(iteratees, 1), []);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\n var now = ctxNow || function() {\n return root.Date.now();\n };\n\n /*------------------------------------------------------------------------*/\n\n /**\n * The opposite of `_.before`; this method creates a function that invokes\n * `func` once it's called `n` or more times.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {number} n The number of calls before `func` is invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var saves = ['profile', 'settings'];\n *\n * var done = _.after(saves.length, function() {\n * console.log('done saving!');\n * });\n *\n * _.forEach(saves, function(type) {\n * asyncSave({ 'type': type, 'complete': done });\n * });\n * // => Logs 'done saving!' after the two async saves have completed.\n */\n function after(n, func) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n < 1) {\n return func.apply(this, arguments);\n }\n };\n }\n\n /**\n * Creates a function that invokes `func`, with up to `n` arguments,\n * ignoring any additional arguments.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @param {number} [n=func.length] The arity cap.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.ary(parseInt, 1));\n * // => [6, 8, 10]\n */\n function ary(func, n, guard) {\n n = guard ? undefined : n;\n n = (func && n == null) ? func.length : n;\n return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);\n }\n\n /**\n * Creates a function that invokes `func`, with the `this` binding and arguments\n * of the created function, while it's called less than `n` times. Subsequent\n * calls to the created function return the result of the last `func` invocation.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {number} n The number of calls at which `func` is no longer invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * jQuery(element).on('click', _.before(5, addContactToList));\n * // => Allows adding up to 4 contacts to the list.\n */\n function before(n, func) {\n var result;\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n > 0) {\n result = func.apply(this, arguments);\n }\n if (n <= 1) {\n func = undefined;\n }\n return result;\n };\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of `thisArg`\n * and `partials` prepended to the arguments it receives.\n *\n * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for partially applied arguments.\n *\n * **Note:** Unlike native `Function#bind`, this method doesn't set the \"length\"\n * property of bound functions.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to bind.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * function greet(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n *\n * var object = { 'user': 'fred' };\n *\n * var bound = _.bind(greet, object, 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bind(greet, object, _, '!');\n * bound('hi');\n * // => 'hi fred!'\n */\n var bind = baseRest(function(func, thisArg, partials) {\n var bitmask = WRAP_BIND_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bind));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(func, bitmask, thisArg, partials, holders);\n });\n\n /**\n * Creates a function that invokes the method at `object[key]` with `partials`\n * prepended to the arguments it receives.\n *\n * This method differs from `_.bind` by allowing bound functions to reference\n * methods that may be redefined or don't yet exist. See\n * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)\n * for more details.\n *\n * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Function\n * @param {Object} object The object to invoke the method on.\n * @param {string} key The key of the method.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * var object = {\n * 'user': 'fred',\n * 'greet': function(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n * };\n *\n * var bound = _.bindKey(object, 'greet', 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * object.greet = function(greeting, punctuation) {\n * return greeting + 'ya ' + this.user + punctuation;\n * };\n *\n * bound('!');\n * // => 'hiya fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bindKey(object, 'greet', _, '!');\n * bound('hi');\n * // => 'hiya fred!'\n */\n var bindKey = baseRest(function(object, key, partials) {\n var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bindKey));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(key, bitmask, object, partials, holders);\n });\n\n /**\n * Creates a function that accepts arguments of `func` and either invokes\n * `func` returning its result, if at least `arity` number of arguments have\n * been provided, or returns a function that accepts the remaining `func`\n * arguments, and so on. The arity of `func` may be specified if `func.length`\n * is not sufficient.\n *\n * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curry(abc);\n *\n * curried(1)(2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(1)(_, 3)(2);\n * // => [1, 2, 3]\n */\n function curry(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curry.placeholder;\n return result;\n }\n\n /**\n * This method is like `_.curry` except that arguments are applied to `func`\n * in the manner of `_.partialRight` instead of `_.partial`.\n *\n * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curryRight(abc);\n *\n * curried(3)(2)(1);\n * // => [1, 2, 3]\n *\n * curried(2, 3)(1);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(3)(1, _)(2);\n * // => [1, 2, 3]\n */\n function curryRight(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curryRight.placeholder;\n return result;\n }\n\n /**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\n function debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n }\n\n /**\n * Defers invoking the `func` until the current call stack has cleared. Any\n * additional arguments are provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to defer.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function(text) {\n * console.log(text);\n * }, 'deferred');\n * // => Logs 'deferred' after one millisecond.\n */\n var defer = baseRest(function(func, args) {\n return baseDelay(func, 1, args);\n });\n\n /**\n * Invokes `func` after `wait` milliseconds. Any additional arguments are\n * provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.delay(function(text) {\n * console.log(text);\n * }, 1000, 'later');\n * // => Logs 'later' after one second.\n */\n var delay = baseRest(function(func, wait, args) {\n return baseDelay(func, toNumber(wait) || 0, args);\n });\n\n /**\n * Creates a function that invokes `func` with arguments reversed.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to flip arguments for.\n * @returns {Function} Returns the new flipped function.\n * @example\n *\n * var flipped = _.flip(function() {\n * return _.toArray(arguments);\n * });\n *\n * flipped('a', 'b', 'c', 'd');\n * // => ['d', 'c', 'b', 'a']\n */\n function flip(func) {\n return createWrap(func, WRAP_FLIP_FLAG);\n }\n\n /**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\n function memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n }\n\n // Expose `MapCache`.\n memoize.Cache = MapCache;\n\n /**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\n function negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n }\n\n /**\n * Creates a function that is restricted to invoking `func` once. Repeat calls\n * to the function return the value of the first invocation. The `func` is\n * invoked with the `this` binding and arguments of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var initialize = _.once(createApplication);\n * initialize();\n * initialize();\n * // => `createApplication` is invoked once\n */\n function once(func) {\n return before(2, func);\n }\n\n /**\n * Creates a function that invokes `func` with its arguments transformed.\n *\n * @static\n * @since 4.0.0\n * @memberOf _\n * @category Function\n * @param {Function} func The function to wrap.\n * @param {...(Function|Function[])} [transforms=[_.identity]]\n * The argument transforms.\n * @returns {Function} Returns the new function.\n * @example\n *\n * function doubled(n) {\n * return n * 2;\n * }\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var func = _.overArgs(function(x, y) {\n * return [x, y];\n * }, [square, doubled]);\n *\n * func(9, 3);\n * // => [81, 6]\n *\n * func(10, 5);\n * // => [100, 10]\n */\n var overArgs = castRest(function(func, transforms) {\n transforms = (transforms.length == 1 && isArray(transforms[0]))\n ? arrayMap(transforms[0], baseUnary(getIteratee()))\n : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));\n\n var funcsLength = transforms.length;\n return baseRest(function(args) {\n var index = -1,\n length = nativeMin(args.length, funcsLength);\n\n while (++index < length) {\n args[index] = transforms[index].call(this, args[index]);\n }\n return apply(func, this, args);\n });\n });\n\n /**\n * Creates a function that invokes `func` with `partials` prepended to the\n * arguments it receives. This method is like `_.bind` except it does **not**\n * alter the `this` binding.\n *\n * The `_.partial.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 0.2.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var sayHelloTo = _.partial(greet, 'hello');\n * sayHelloTo('fred');\n * // => 'hello fred'\n *\n * // Partially applied with placeholders.\n * var greetFred = _.partial(greet, _, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n */\n var partial = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partial));\n return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);\n });\n\n /**\n * This method is like `_.partial` except that partially applied arguments\n * are appended to the arguments it receives.\n *\n * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var greetFred = _.partialRight(greet, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n *\n * // Partially applied with placeholders.\n * var sayHelloTo = _.partialRight(greet, 'hello', _);\n * sayHelloTo('fred');\n * // => 'hello fred'\n */\n var partialRight = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partialRight));\n return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);\n });\n\n /**\n * Creates a function that invokes `func` with arguments arranged according\n * to the specified `indexes` where the argument value at the first index is\n * provided as the first argument, the argument value at the second index is\n * provided as the second argument, and so on.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to rearrange arguments for.\n * @param {...(number|number[])} indexes The arranged argument indexes.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var rearged = _.rearg(function(a, b, c) {\n * return [a, b, c];\n * }, [2, 0, 1]);\n *\n * rearged('b', 'c', 'a')\n * // => ['a', 'b', 'c']\n */\n var rearg = flatRest(function(func, indexes) {\n return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);\n });\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * created function and arguments from `start` and beyond provided as\n * an array.\n *\n * **Note:** This method is based on the\n * [rest parameter](https://mdn.io/rest_parameters).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.rest(function(what, names) {\n * return what + ' ' + _.initial(names).join(', ') +\n * (_.size(names) > 1 ? ', & ' : '') + _.last(names);\n * });\n *\n * say('hello', 'fred', 'barney', 'pebbles');\n * // => 'hello fred, barney, & pebbles'\n */\n function rest(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start === undefined ? start : toInteger(start);\n return baseRest(func, start);\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * create function and an array of arguments much like\n * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).\n *\n * **Note:** This method is based on the\n * [spread operator](https://mdn.io/spread_operator).\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Function\n * @param {Function} func The function to spread arguments over.\n * @param {number} [start=0] The start position of the spread.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.spread(function(who, what) {\n * return who + ' says ' + what;\n * });\n *\n * say(['fred', 'hello']);\n * // => 'fred says hello'\n *\n * var numbers = Promise.all([\n * Promise.resolve(40),\n * Promise.resolve(36)\n * ]);\n *\n * numbers.then(_.spread(function(x, y) {\n * return x + y;\n * }));\n * // => a Promise of 76\n */\n function spread(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start == null ? 0 : nativeMax(toInteger(start), 0);\n return baseRest(function(args) {\n var array = args[start],\n otherArgs = castSlice(args, 0, start);\n\n if (array) {\n arrayPush(otherArgs, array);\n }\n return apply(func, this, otherArgs);\n });\n }\n\n /**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the throttled function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\n function throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n return debounce(func, wait, {\n 'leading': leading,\n 'maxWait': wait,\n 'trailing': trailing\n });\n }\n\n /**\n * Creates a function that accepts up to one argument, ignoring any\n * additional arguments.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.unary(parseInt));\n * // => [6, 8, 10]\n */\n function unary(func) {\n return ary(func, 1);\n }\n\n /**\n * Creates a function that provides `value` to `wrapper` as its first\n * argument. Any additional arguments provided to the function are appended\n * to those provided to the `wrapper`. The wrapper is invoked with the `this`\n * binding of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {*} value The value to wrap.\n * @param {Function} [wrapper=identity] The wrapper function.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var p = _.wrap(_.escape, function(func, text) {\n * return '

    ' + func(text) + '

    ';\n * });\n *\n * p('fred, barney, & pebbles');\n * // => '

    fred, barney, & pebbles

    '\n */\n function wrap(value, wrapper) {\n return partial(castFunction(wrapper), value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Casts `value` as an array if it's not one.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Lang\n * @param {*} value The value to inspect.\n * @returns {Array} Returns the cast array.\n * @example\n *\n * _.castArray(1);\n * // => [1]\n *\n * _.castArray({ 'a': 1 });\n * // => [{ 'a': 1 }]\n *\n * _.castArray('abc');\n * // => ['abc']\n *\n * _.castArray(null);\n * // => [null]\n *\n * _.castArray(undefined);\n * // => [undefined]\n *\n * _.castArray();\n * // => []\n *\n * var array = [1, 2, 3];\n * console.log(_.castArray(array) === array);\n * // => true\n */\n function castArray() {\n if (!arguments.length) {\n return [];\n }\n var value = arguments[0];\n return isArray(value) ? value : [value];\n }\n\n /**\n * Creates a shallow clone of `value`.\n *\n * **Note:** This method is loosely based on the\n * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)\n * and supports cloning arrays, array buffers, booleans, date objects, maps,\n * numbers, `Object` objects, regexes, sets, strings, symbols, and typed\n * arrays. The own enumerable properties of `arguments` objects are cloned\n * as plain objects. An empty object is returned for uncloneable values such\n * as error objects, functions, DOM nodes, and WeakMaps.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to clone.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeep\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var shallow = _.clone(objects);\n * console.log(shallow[0] === objects[0]);\n * // => true\n */\n function clone(value) {\n return baseClone(value, CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.clone` except that it accepts `customizer` which\n * is invoked to produce the cloned value. If `customizer` returns `undefined`,\n * cloning is handled by the method instead. The `customizer` is invoked with\n * up to four arguments; (value [, index|key, object, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeepWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(false);\n * }\n * }\n *\n * var el = _.cloneWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 0\n */\n function cloneWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\n function cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.cloneWith` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the deep cloned value.\n * @see _.cloneWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(true);\n * }\n * }\n *\n * var el = _.cloneDeepWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 20\n */\n function cloneDeepWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * Checks if `object` conforms to `source` by invoking the predicate\n * properties of `source` with the corresponding property values of `object`.\n *\n * **Note:** This method is equivalent to `_.conforms` when `source` is\n * partially applied.\n *\n * @static\n * @memberOf _\n * @since 4.14.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 1; } });\n * // => true\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 2; } });\n * // => false\n */\n function conformsTo(object, source) {\n return source == null || baseConformsTo(object, source, keys(source));\n }\n\n /**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\n function eq(value, other) {\n return value === other || (value !== value && other !== other);\n }\n\n /**\n * Checks if `value` is greater than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n * @see _.lt\n * @example\n *\n * _.gt(3, 1);\n * // => true\n *\n * _.gt(3, 3);\n * // => false\n *\n * _.gt(1, 3);\n * // => false\n */\n var gt = createRelationalOperation(baseGt);\n\n /**\n * Checks if `value` is greater than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than or equal to\n * `other`, else `false`.\n * @see _.lte\n * @example\n *\n * _.gte(3, 1);\n * // => true\n *\n * _.gte(3, 3);\n * // => true\n *\n * _.gte(1, 3);\n * // => false\n */\n var gte = createRelationalOperation(function(value, other) {\n return value >= other;\n });\n\n /**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\n var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n };\n\n /**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\n var isArray = Array.isArray;\n\n /**\n * Checks if `value` is classified as an `ArrayBuffer` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n * @example\n *\n * _.isArrayBuffer(new ArrayBuffer(2));\n * // => true\n *\n * _.isArrayBuffer(new Array(2));\n * // => false\n */\n var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;\n\n /**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\n function isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n }\n\n /**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\n function isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n }\n\n /**\n * Checks if `value` is classified as a boolean primitive or object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.\n * @example\n *\n * _.isBoolean(false);\n * // => true\n *\n * _.isBoolean(null);\n * // => false\n */\n function isBoolean(value) {\n return value === true || value === false ||\n (isObjectLike(value) && baseGetTag(value) == boolTag);\n }\n\n /**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\n var isBuffer = nativeIsBuffer || stubFalse;\n\n /**\n * Checks if `value` is classified as a `Date` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n * @example\n *\n * _.isDate(new Date);\n * // => true\n *\n * _.isDate('Mon April 23 2012');\n * // => false\n */\n var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;\n\n /**\n * Checks if `value` is likely a DOM element.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.\n * @example\n *\n * _.isElement(document.body);\n * // => true\n *\n * _.isElement('');\n * // => false\n */\n function isElement(value) {\n return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);\n }\n\n /**\n * Checks if `value` is an empty object, collection, map, or set.\n *\n * Objects are considered empty if they have no own enumerable string keyed\n * properties.\n *\n * Array-like values such as `arguments` objects, arrays, buffers, strings, or\n * jQuery-like collections are considered empty if they have a `length` of `0`.\n * Similarly, maps and sets are considered empty if they have a `size` of `0`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is empty, else `false`.\n * @example\n *\n * _.isEmpty(null);\n * // => true\n *\n * _.isEmpty(true);\n * // => true\n *\n * _.isEmpty(1);\n * // => true\n *\n * _.isEmpty([1, 2, 3]);\n * // => false\n *\n * _.isEmpty({ 'a': 1 });\n * // => false\n */\n function isEmpty(value) {\n if (value == null) {\n return true;\n }\n if (isArrayLike(value) &&\n (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||\n isBuffer(value) || isTypedArray(value) || isArguments(value))) {\n return !value.length;\n }\n var tag = getTag(value);\n if (tag == mapTag || tag == setTag) {\n return !value.size;\n }\n if (isPrototype(value)) {\n return !baseKeys(value).length;\n }\n for (var key in value) {\n if (hasOwnProperty.call(value, key)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\n function isEqual(value, other) {\n return baseIsEqual(value, other);\n }\n\n /**\n * This method is like `_.isEqual` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with up to\n * six arguments: (objValue, othValue [, index|key, object, other, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, othValue) {\n * if (isGreeting(objValue) && isGreeting(othValue)) {\n * return true;\n * }\n * }\n *\n * var array = ['hello', 'goodbye'];\n * var other = ['hi', 'goodbye'];\n *\n * _.isEqualWith(array, other, customizer);\n * // => true\n */\n function isEqualWith(value, other, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n var result = customizer ? customizer(value, other) : undefined;\n return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;\n }\n\n /**\n * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,\n * `SyntaxError`, `TypeError`, or `URIError` object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an error object, else `false`.\n * @example\n *\n * _.isError(new Error);\n * // => true\n *\n * _.isError(Error);\n * // => false\n */\n function isError(value) {\n if (!isObjectLike(value)) {\n return false;\n }\n var tag = baseGetTag(value);\n return tag == errorTag || tag == domExcTag ||\n (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));\n }\n\n /**\n * Checks if `value` is a finite primitive number.\n *\n * **Note:** This method is based on\n * [`Number.isFinite`](https://mdn.io/Number/isFinite).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.\n * @example\n *\n * _.isFinite(3);\n * // => true\n *\n * _.isFinite(Number.MIN_VALUE);\n * // => true\n *\n * _.isFinite(Infinity);\n * // => false\n *\n * _.isFinite('3');\n * // => false\n */\n function isFinite(value) {\n return typeof value == 'number' && nativeIsFinite(value);\n }\n\n /**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\n function isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n }\n\n /**\n * Checks if `value` is an integer.\n *\n * **Note:** This method is based on\n * [`Number.isInteger`](https://mdn.io/Number/isInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an integer, else `false`.\n * @example\n *\n * _.isInteger(3);\n * // => true\n *\n * _.isInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isInteger(Infinity);\n * // => false\n *\n * _.isInteger('3');\n * // => false\n */\n function isInteger(value) {\n return typeof value == 'number' && value == toInteger(value);\n }\n\n /**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\n function isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\n function isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n }\n\n /**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\n function isObjectLike(value) {\n return value != null && typeof value == 'object';\n }\n\n /**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\n var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\n /**\n * Performs a partial deep comparison between `object` and `source` to\n * determine if `object` contains equivalent property values.\n *\n * **Note:** This method is equivalent to `_.matches` when `source` is\n * partially applied.\n *\n * Partial comparisons will match empty array and empty object `source`\n * values against any array or object value, respectively. See `_.isEqual`\n * for a list of supported value comparisons.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.isMatch(object, { 'b': 2 });\n * // => true\n *\n * _.isMatch(object, { 'b': 1 });\n * // => false\n */\n function isMatch(object, source) {\n return object === source || baseIsMatch(object, source, getMatchData(source));\n }\n\n /**\n * This method is like `_.isMatch` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with five\n * arguments: (objValue, srcValue, index|key, object, source).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, srcValue) {\n * if (isGreeting(objValue) && isGreeting(srcValue)) {\n * return true;\n * }\n * }\n *\n * var object = { 'greeting': 'hello' };\n * var source = { 'greeting': 'hi' };\n *\n * _.isMatchWith(object, source, customizer);\n * // => true\n */\n function isMatchWith(object, source, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseIsMatch(object, source, getMatchData(source), customizer);\n }\n\n /**\n * Checks if `value` is `NaN`.\n *\n * **Note:** This method is based on\n * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as\n * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for\n * `undefined` and other non-number values.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n * @example\n *\n * _.isNaN(NaN);\n * // => true\n *\n * _.isNaN(new Number(NaN));\n * // => true\n *\n * isNaN(undefined);\n * // => true\n *\n * _.isNaN(undefined);\n * // => false\n */\n function isNaN(value) {\n // An `NaN` primitive is the only value that is not equal to itself.\n // Perform the `toStringTag` check first to avoid errors with some\n // ActiveX objects in IE.\n return isNumber(value) && value != +value;\n }\n\n /**\n * Checks if `value` is a pristine native function.\n *\n * **Note:** This method can't reliably detect native functions in the presence\n * of the core-js package because core-js circumvents this kind of detection.\n * Despite multiple requests, the core-js maintainer has made it clear: any\n * attempt to fix the detection will be obstructed. As a result, we're left\n * with little choice but to throw an error. Unfortunately, this also affects\n * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),\n * which rely on core-js.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n * @example\n *\n * _.isNative(Array.prototype.push);\n * // => true\n *\n * _.isNative(_);\n * // => false\n */\n function isNative(value) {\n if (isMaskable(value)) {\n throw new Error(CORE_ERROR_TEXT);\n }\n return baseIsNative(value);\n }\n\n /**\n * Checks if `value` is `null`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `null`, else `false`.\n * @example\n *\n * _.isNull(null);\n * // => true\n *\n * _.isNull(void 0);\n * // => false\n */\n function isNull(value) {\n return value === null;\n }\n\n /**\n * Checks if `value` is `null` or `undefined`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is nullish, else `false`.\n * @example\n *\n * _.isNil(null);\n * // => true\n *\n * _.isNil(void 0);\n * // => true\n *\n * _.isNil(NaN);\n * // => false\n */\n function isNil(value) {\n return value == null;\n }\n\n /**\n * Checks if `value` is classified as a `Number` primitive or object.\n *\n * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are\n * classified as numbers, use the `_.isFinite` method.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a number, else `false`.\n * @example\n *\n * _.isNumber(3);\n * // => true\n *\n * _.isNumber(Number.MIN_VALUE);\n * // => true\n *\n * _.isNumber(Infinity);\n * // => true\n *\n * _.isNumber('3');\n * // => false\n */\n function isNumber(value) {\n return typeof value == 'number' ||\n (isObjectLike(value) && baseGetTag(value) == numberTag);\n }\n\n /**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\n function isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n }\n\n /**\n * Checks if `value` is classified as a `RegExp` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n * @example\n *\n * _.isRegExp(/abc/);\n * // => true\n *\n * _.isRegExp('/abc/');\n * // => false\n */\n var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;\n\n /**\n * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754\n * double precision number which isn't the result of a rounded unsafe integer.\n *\n * **Note:** This method is based on\n * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.\n * @example\n *\n * _.isSafeInteger(3);\n * // => true\n *\n * _.isSafeInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isSafeInteger(Infinity);\n * // => false\n *\n * _.isSafeInteger('3');\n * // => false\n */\n function isSafeInteger(value) {\n return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\n var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\n /**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\n function isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n }\n\n /**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\n function isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n }\n\n /**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\n var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n /**\n * Checks if `value` is `undefined`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\n function isUndefined(value) {\n return value === undefined;\n }\n\n /**\n * Checks if `value` is classified as a `WeakMap` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.\n * @example\n *\n * _.isWeakMap(new WeakMap);\n * // => true\n *\n * _.isWeakMap(new Map);\n * // => false\n */\n function isWeakMap(value) {\n return isObjectLike(value) && getTag(value) == weakMapTag;\n }\n\n /**\n * Checks if `value` is classified as a `WeakSet` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.\n * @example\n *\n * _.isWeakSet(new WeakSet);\n * // => true\n *\n * _.isWeakSet(new Set);\n * // => false\n */\n function isWeakSet(value) {\n return isObjectLike(value) && baseGetTag(value) == weakSetTag;\n }\n\n /**\n * Checks if `value` is less than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n * @see _.gt\n * @example\n *\n * _.lt(1, 3);\n * // => true\n *\n * _.lt(3, 3);\n * // => false\n *\n * _.lt(3, 1);\n * // => false\n */\n var lt = createRelationalOperation(baseLt);\n\n /**\n * Checks if `value` is less than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than or equal to\n * `other`, else `false`.\n * @see _.gte\n * @example\n *\n * _.lte(1, 3);\n * // => true\n *\n * _.lte(3, 3);\n * // => true\n *\n * _.lte(3, 1);\n * // => false\n */\n var lte = createRelationalOperation(function(value, other) {\n return value <= other;\n });\n\n /**\n * Converts `value` to an array.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Array} Returns the converted array.\n * @example\n *\n * _.toArray({ 'a': 1, 'b': 2 });\n * // => [1, 2]\n *\n * _.toArray('abc');\n * // => ['a', 'b', 'c']\n *\n * _.toArray(1);\n * // => []\n *\n * _.toArray(null);\n * // => []\n */\n function toArray(value) {\n if (!value) {\n return [];\n }\n if (isArrayLike(value)) {\n return isString(value) ? stringToArray(value) : copyArray(value);\n }\n if (symIterator && value[symIterator]) {\n return iteratorToArray(value[symIterator]());\n }\n var tag = getTag(value),\n func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);\n\n return func(value);\n }\n\n /**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\n function toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n }\n\n /**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\n function toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n }\n\n /**\n * Converts `value` to an integer suitable for use as the length of an\n * array-like object.\n *\n * **Note:** This method is based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toLength(3.2);\n * // => 3\n *\n * _.toLength(Number.MIN_VALUE);\n * // => 0\n *\n * _.toLength(Infinity);\n * // => 4294967295\n *\n * _.toLength('3.2');\n * // => 3\n */\n function toLength(value) {\n return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;\n }\n\n /**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\n function toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = baseTrim(value);\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n }\n\n /**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\n function toPlainObject(value) {\n return copyObject(value, keysIn(value));\n }\n\n /**\n * Converts `value` to a safe integer. A safe integer can be compared and\n * represented correctly.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toSafeInteger(3.2);\n * // => 3\n *\n * _.toSafeInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toSafeInteger(Infinity);\n * // => 9007199254740991\n *\n * _.toSafeInteger('3.2');\n * // => 3\n */\n function toSafeInteger(value) {\n return value\n ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)\n : (value === 0 ? value : 0);\n }\n\n /**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\n function toString(value) {\n return value == null ? '' : baseToString(value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Assigns own enumerable string keyed properties of source objects to the\n * destination object. Source objects are applied from left to right.\n * Subsequent sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object` and is loosely based on\n * [`Object.assign`](https://mdn.io/Object/assign).\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assignIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assign({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'c': 3 }\n */\n var assign = createAssigner(function(object, source) {\n if (isPrototype(source) || isArrayLike(source)) {\n copyObject(source, keys(source), object);\n return;\n }\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n assignValue(object, key, source[key]);\n }\n }\n });\n\n /**\n * This method is like `_.assign` except that it iterates over own and\n * inherited source properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extend\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assign\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assignIn({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }\n */\n var assignIn = createAssigner(function(object, source) {\n copyObject(source, keysIn(source), object);\n });\n\n /**\n * This method is like `_.assignIn` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extendWith\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignInWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keysIn(source), object, customizer);\n });\n\n /**\n * This method is like `_.assign` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignInWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keys(source), object, customizer);\n });\n\n /**\n * Creates an array of values corresponding to `paths` of `object`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Array} Returns the picked values.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _.at(object, ['a[0].b.c', 'a[1]']);\n * // => [3, 4]\n */\n var at = flatRest(baseAt);\n\n /**\n * Creates an object that inherits from the `prototype` object. If a\n * `properties` object is given, its own enumerable string keyed properties\n * are assigned to the created object.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Object\n * @param {Object} prototype The object to inherit from.\n * @param {Object} [properties] The properties to assign to the object.\n * @returns {Object} Returns the new object.\n * @example\n *\n * function Shape() {\n * this.x = 0;\n * this.y = 0;\n * }\n *\n * function Circle() {\n * Shape.call(this);\n * }\n *\n * Circle.prototype = _.create(Shape.prototype, {\n * 'constructor': Circle\n * });\n *\n * var circle = new Circle;\n * circle instanceof Circle;\n * // => true\n *\n * circle instanceof Shape;\n * // => true\n */\n function create(prototype, properties) {\n var result = baseCreate(prototype);\n return properties == null ? result : baseAssign(result, properties);\n }\n\n /**\n * Assigns own and inherited enumerable string keyed properties of source\n * objects to the destination object for all destination properties that\n * resolve to `undefined`. Source objects are applied from left to right.\n * Once a property is set, additional values of the same property are ignored.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaultsDeep\n * @example\n *\n * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var defaults = baseRest(function(object, sources) {\n object = Object(object);\n\n var index = -1;\n var length = sources.length;\n var guard = length > 2 ? sources[2] : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n length = 1;\n }\n\n while (++index < length) {\n var source = sources[index];\n var props = keysIn(source);\n var propsIndex = -1;\n var propsLength = props.length;\n\n while (++propsIndex < propsLength) {\n var key = props[propsIndex];\n var value = object[key];\n\n if (value === undefined ||\n (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n object[key] = source[key];\n }\n }\n }\n\n return object;\n });\n\n /**\n * This method is like `_.defaults` except that it recursively assigns\n * default properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaults\n * @example\n *\n * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });\n * // => { 'a': { 'b': 2, 'c': 3 } }\n */\n var defaultsDeep = baseRest(function(args) {\n args.push(undefined, customDefaultsMerge);\n return apply(mergeWith, undefined, args);\n });\n\n /**\n * This method is like `_.find` except that it returns the key of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findKey(users, function(o) { return o.age < 40; });\n * // => 'barney' (iteration order is not guaranteed)\n *\n * // The `_.matches` iteratee shorthand.\n * _.findKey(users, { 'age': 1, 'active': true });\n * // => 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findKey(users, 'active');\n * // => 'barney'\n */\n function findKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);\n }\n\n /**\n * This method is like `_.findKey` except that it iterates over elements of\n * a collection in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findLastKey(users, function(o) { return o.age < 40; });\n * // => returns 'pebbles' assuming `_.findKey` returns 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastKey(users, { 'age': 36, 'active': true });\n * // => 'barney'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastKey(users, 'active');\n * // => 'pebbles'\n */\n function findLastKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);\n }\n\n /**\n * Iterates over own and inherited enumerable string keyed properties of an\n * object and invokes `iteratee` for each property. The iteratee is invoked\n * with three arguments: (value, key, object). Iteratee functions may exit\n * iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forInRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forIn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).\n */\n function forIn(object, iteratee) {\n return object == null\n ? object\n : baseFor(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * This method is like `_.forIn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forInRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.\n */\n function forInRight(object, iteratee) {\n return object == null\n ? object\n : baseForRight(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * Iterates over own enumerable string keyed properties of an object and\n * invokes `iteratee` for each property. The iteratee is invoked with three\n * arguments: (value, key, object). Iteratee functions may exit iteration\n * early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forOwnRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forOwn(object, iteratee) {\n return object && baseForOwn(object, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forOwn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forOwn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwnRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.\n */\n function forOwnRight(object, iteratee) {\n return object && baseForOwnRight(object, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an array of function property names from own enumerable properties\n * of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functionsIn\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functions(new Foo);\n * // => ['a', 'b']\n */\n function functions(object) {\n return object == null ? [] : baseFunctions(object, keys(object));\n }\n\n /**\n * Creates an array of function property names from own and inherited\n * enumerable properties of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functions\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functionsIn(new Foo);\n * // => ['a', 'b', 'c']\n */\n function functionsIn(object) {\n return object == null ? [] : baseFunctions(object, keysIn(object));\n }\n\n /**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\n function get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n }\n\n /**\n * Checks if `path` is a direct property of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = { 'a': { 'b': 2 } };\n * var other = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b');\n * // => true\n *\n * _.has(object, ['a', 'b']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\n function has(object, path) {\n return object != null && hasPath(object, path, baseHas);\n }\n\n /**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\n function hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]\n */\n var invoke = baseRest(baseInvoke);\n\n /**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\n function keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n }\n\n /**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\n function keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n }\n\n /**\n * The opposite of `_.mapValues`; this method creates an object with the\n * same values as `object` and keys generated by running each own enumerable\n * string keyed property of `object` thru `iteratee`. The iteratee is invoked\n * with three arguments: (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapValues\n * @example\n *\n * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {\n * return key + value;\n * });\n * // => { 'a1': 1, 'b2': 2 }\n */\n function mapKeys(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, iteratee(value, key, object), value);\n });\n return result;\n }\n\n /**\n * Creates an object with the same keys as `object` and values generated\n * by running each own enumerable string keyed property of `object` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapKeys\n * @example\n *\n * var users = {\n * 'fred': { 'user': 'fred', 'age': 40 },\n * 'pebbles': { 'user': 'pebbles', 'age': 1 }\n * };\n *\n * _.mapValues(users, function(o) { return o.age; });\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n *\n * // The `_.property` iteratee shorthand.\n * _.mapValues(users, 'age');\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n */\n function mapValues(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, key, iteratee(value, key, object));\n });\n return result;\n }\n\n /**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\n var merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n });\n\n /**\n * This method is like `_.merge` except that it accepts `customizer` which\n * is invoked to produce the merged values of the destination and source\n * properties. If `customizer` returns `undefined`, merging is handled by the\n * method instead. The `customizer` is invoked with six arguments:\n * (objValue, srcValue, key, object, source, stack).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} customizer The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function customizer(objValue, srcValue) {\n * if (_.isArray(objValue)) {\n * return objValue.concat(srcValue);\n * }\n * }\n *\n * var object = { 'a': [1], 'b': [2] };\n * var other = { 'a': [3], 'b': [4] };\n *\n * _.mergeWith(object, other, customizer);\n * // => { 'a': [1, 3], 'b': [2, 4] }\n */\n var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {\n baseMerge(object, source, srcIndex, customizer);\n });\n\n /**\n * The opposite of `_.pick`; this method creates an object composed of the\n * own and inherited enumerable property paths of `object` that are not omitted.\n *\n * **Note:** This method is considerably slower than `_.pick`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to omit.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omit(object, ['a', 'c']);\n * // => { 'b': '2' }\n */\n var omit = flatRest(function(object, paths) {\n var result = {};\n if (object == null) {\n return result;\n }\n var isDeep = false;\n paths = arrayMap(paths, function(path) {\n path = castPath(path, object);\n isDeep || (isDeep = path.length > 1);\n return path;\n });\n copyObject(object, getAllKeysIn(object), result);\n if (isDeep) {\n result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);\n }\n var length = paths.length;\n while (length--) {\n baseUnset(result, paths[length]);\n }\n return result;\n });\n\n /**\n * The opposite of `_.pickBy`; this method creates an object composed of\n * the own and inherited enumerable string keyed properties of `object` that\n * `predicate` doesn't return truthy for. The predicate is invoked with two\n * arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omitBy(object, _.isNumber);\n * // => { 'b': '2' }\n */\n function omitBy(object, predicate) {\n return pickBy(object, negate(getIteratee(predicate)));\n }\n\n /**\n * Creates an object composed of the picked `object` properties.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pick(object, ['a', 'c']);\n * // => { 'a': 1, 'c': 3 }\n */\n var pick = flatRest(function(object, paths) {\n return object == null ? {} : basePick(object, paths);\n });\n\n /**\n * Creates an object composed of the `object` properties `predicate` returns\n * truthy for. The predicate is invoked with two arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pickBy(object, _.isNumber);\n * // => { 'a': 1, 'c': 3 }\n */\n function pickBy(object, predicate) {\n if (object == null) {\n return {};\n }\n var props = arrayMap(getAllKeysIn(object), function(prop) {\n return [prop];\n });\n predicate = getIteratee(predicate);\n return basePickBy(object, props, function(value, path) {\n return predicate(value, path[0]);\n });\n }\n\n /**\n * This method is like `_.get` except that if the resolved value is a\n * function it's invoked with the `this` binding of its parent object and\n * its result is returned.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to resolve.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };\n *\n * _.result(object, 'a[0].b.c1');\n * // => 3\n *\n * _.result(object, 'a[0].b.c2');\n * // => 4\n *\n * _.result(object, 'a[0].b.c3', 'default');\n * // => 'default'\n *\n * _.result(object, 'a[0].b.c3', _.constant('default'));\n * // => 'default'\n */\n function result(object, path, defaultValue) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length;\n\n // Ensure the loop is entered when path is empty.\n if (!length) {\n length = 1;\n object = undefined;\n }\n while (++index < length) {\n var value = object == null ? undefined : object[toKey(path[index])];\n if (value === undefined) {\n index = length;\n value = defaultValue;\n }\n object = isFunction(value) ? value.call(object) : value;\n }\n return object;\n }\n\n /**\n * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n * it's created. Arrays are created for missing index properties while objects\n * are created for all other missing properties. Use `_.setWith` to customize\n * `path` creation.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.set(object, 'a[0].b.c', 4);\n * console.log(object.a[0].b.c);\n * // => 4\n *\n * _.set(object, ['x', '0', 'y', 'z'], 5);\n * console.log(object.x[0].y.z);\n * // => 5\n */\n function set(object, path, value) {\n return object == null ? object : baseSet(object, path, value);\n }\n\n /**\n * This method is like `_.set` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.setWith(object, '[0][1]', 'a', Object);\n * // => { '0': { '1': 'a' } }\n */\n function setWith(object, path, value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseSet(object, path, value, customizer);\n }\n\n /**\n * Creates an array of own enumerable string keyed-value pairs for `object`\n * which can be consumed by `_.fromPairs`. If `object` is a map or set, its\n * entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entries\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairs(new Foo);\n * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)\n */\n var toPairs = createToPairs(keys);\n\n /**\n * Creates an array of own and inherited enumerable string keyed-value pairs\n * for `object` which can be consumed by `_.fromPairs`. If `object` is a map\n * or set, its entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entriesIn\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairsIn(new Foo);\n * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)\n */\n var toPairsIn = createToPairs(keysIn);\n\n /**\n * An alternative to `_.reduce`; this method transforms `object` to a new\n * `accumulator` object which is the result of running each of its own\n * enumerable string keyed properties thru `iteratee`, with each invocation\n * potentially mutating the `accumulator` object. If `accumulator` is not\n * provided, a new object with the same `[[Prototype]]` will be used. The\n * iteratee is invoked with four arguments: (accumulator, value, key, object).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The custom accumulator value.\n * @returns {*} Returns the accumulated value.\n * @example\n *\n * _.transform([2, 3, 4], function(result, n) {\n * result.push(n *= n);\n * return n % 2 == 0;\n * }, []);\n * // => [4, 9]\n *\n * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] }\n */\n function transform(object, iteratee, accumulator) {\n var isArr = isArray(object),\n isArrLike = isArr || isBuffer(object) || isTypedArray(object);\n\n iteratee = getIteratee(iteratee, 4);\n if (accumulator == null) {\n var Ctor = object && object.constructor;\n if (isArrLike) {\n accumulator = isArr ? new Ctor : [];\n }\n else if (isObject(object)) {\n accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};\n }\n else {\n accumulator = {};\n }\n }\n (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {\n return iteratee(accumulator, value, index, object);\n });\n return accumulator;\n }\n\n /**\n * Removes the property at `path` of `object`.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 7 } }] };\n * _.unset(object, 'a[0].b.c');\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n *\n * _.unset(object, ['a', '0', 'b', 'c']);\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n */\n function unset(object, path) {\n return object == null ? true : baseUnset(object, path);\n }\n\n /**\n * This method is like `_.set` except that accepts `updater` to produce the\n * value to set. Use `_.updateWith` to customize `path` creation. The `updater`\n * is invoked with one argument: (value).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.update(object, 'a[0].b.c', function(n) { return n * n; });\n * console.log(object.a[0].b.c);\n * // => 9\n *\n * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });\n * console.log(object.x[0].y.z);\n * // => 0\n */\n function update(object, path, updater) {\n return object == null ? object : baseUpdate(object, path, castFunction(updater));\n }\n\n /**\n * This method is like `_.update` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.updateWith(object, '[0][1]', _.constant('a'), Object);\n * // => { '0': { '1': 'a' } }\n */\n function updateWith(object, path, updater, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);\n }\n\n /**\n * Creates an array of the own enumerable string keyed property values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.values(new Foo);\n * // => [1, 2] (iteration order is not guaranteed)\n *\n * _.values('hi');\n * // => ['h', 'i']\n */\n function values(object) {\n return object == null ? [] : baseValues(object, keys(object));\n }\n\n /**\n * Creates an array of the own and inherited enumerable string keyed property\n * values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.valuesIn(new Foo);\n * // => [1, 2, 3] (iteration order is not guaranteed)\n */\n function valuesIn(object) {\n return object == null ? [] : baseValues(object, keysIn(object));\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Clamps `number` within the inclusive `lower` and `upper` bounds.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Number\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n * @example\n *\n * _.clamp(-10, -5, 5);\n * // => -5\n *\n * _.clamp(10, -5, 5);\n * // => 5\n */\n function clamp(number, lower, upper) {\n if (upper === undefined) {\n upper = lower;\n lower = undefined;\n }\n if (upper !== undefined) {\n upper = toNumber(upper);\n upper = upper === upper ? upper : 0;\n }\n if (lower !== undefined) {\n lower = toNumber(lower);\n lower = lower === lower ? lower : 0;\n }\n return baseClamp(toNumber(number), lower, upper);\n }\n\n /**\n * Checks if `n` is between `start` and up to, but not including, `end`. If\n * `end` is not specified, it's set to `start` with `start` then set to `0`.\n * If `start` is greater than `end` the params are swapped to support\n * negative ranges.\n *\n * @static\n * @memberOf _\n * @since 3.3.0\n * @category Number\n * @param {number} number The number to check.\n * @param {number} [start=0] The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n * @see _.range, _.rangeRight\n * @example\n *\n * _.inRange(3, 2, 4);\n * // => true\n *\n * _.inRange(4, 8);\n * // => true\n *\n * _.inRange(4, 2);\n * // => false\n *\n * _.inRange(2, 2);\n * // => false\n *\n * _.inRange(1.2, 2);\n * // => true\n *\n * _.inRange(5.2, 4);\n * // => false\n *\n * _.inRange(-3, -2, -6);\n * // => true\n */\n function inRange(number, start, end) {\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n number = toNumber(number);\n return baseInRange(number, start, end);\n }\n\n /**\n * Produces a random number between the inclusive `lower` and `upper` bounds.\n * If only one argument is provided a number between `0` and the given number\n * is returned. If `floating` is `true`, or either `lower` or `upper` are\n * floats, a floating-point number is returned instead of an integer.\n *\n * **Note:** JavaScript follows the IEEE-754 standard for resolving\n * floating-point values which can produce unexpected results.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Number\n * @param {number} [lower=0] The lower bound.\n * @param {number} [upper=1] The upper bound.\n * @param {boolean} [floating] Specify returning a floating-point number.\n * @returns {number} Returns the random number.\n * @example\n *\n * _.random(0, 5);\n * // => an integer between 0 and 5\n *\n * _.random(5);\n * // => also an integer between 0 and 5\n *\n * _.random(5, true);\n * // => a floating-point number between 0 and 5\n *\n * _.random(1.2, 5.2);\n * // => a floating-point number between 1.2 and 5.2\n */\n function random(lower, upper, floating) {\n if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {\n upper = floating = undefined;\n }\n if (floating === undefined) {\n if (typeof upper == 'boolean') {\n floating = upper;\n upper = undefined;\n }\n else if (typeof lower == 'boolean') {\n floating = lower;\n lower = undefined;\n }\n }\n if (lower === undefined && upper === undefined) {\n lower = 0;\n upper = 1;\n }\n else {\n lower = toFinite(lower);\n if (upper === undefined) {\n upper = lower;\n lower = 0;\n } else {\n upper = toFinite(upper);\n }\n }\n if (lower > upper) {\n var temp = lower;\n lower = upper;\n upper = temp;\n }\n if (floating || lower % 1 || upper % 1) {\n var rand = nativeRandom();\n return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);\n }\n return baseRandom(lower, upper);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the camel cased string.\n * @example\n *\n * _.camelCase('Foo Bar');\n * // => 'fooBar'\n *\n * _.camelCase('--foo-bar--');\n * // => 'fooBar'\n *\n * _.camelCase('__FOO_BAR__');\n * // => 'fooBar'\n */\n var camelCase = createCompounder(function(result, word, index) {\n word = word.toLowerCase();\n return result + (index ? capitalize(word) : word);\n });\n\n /**\n * Converts the first character of `string` to upper case and the remaining\n * to lower case.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to capitalize.\n * @returns {string} Returns the capitalized string.\n * @example\n *\n * _.capitalize('FRED');\n * // => 'Fred'\n */\n function capitalize(string) {\n return upperFirst(toString(string).toLowerCase());\n }\n\n /**\n * Deburrs `string` by converting\n * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n * letters to basic Latin letters and removing\n * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('déjà vu');\n * // => 'deja vu'\n */\n function deburr(string) {\n string = toString(string);\n return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n }\n\n /**\n * Checks if `string` ends with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=string.length] The position to search up to.\n * @returns {boolean} Returns `true` if `string` ends with `target`,\n * else `false`.\n * @example\n *\n * _.endsWith('abc', 'c');\n * // => true\n *\n * _.endsWith('abc', 'b');\n * // => false\n *\n * _.endsWith('abc', 'b', 2);\n * // => true\n */\n function endsWith(string, target, position) {\n string = toString(string);\n target = baseToString(target);\n\n var length = string.length;\n position = position === undefined\n ? length\n : baseClamp(toInteger(position), 0, length);\n\n var end = position;\n position -= target.length;\n return position >= 0 && string.slice(position, end) == target;\n }\n\n /**\n * Converts the characters \"&\", \"<\", \">\", '\"', and \"'\" in `string` to their\n * corresponding HTML entities.\n *\n * **Note:** No other characters are escaped. To escape additional\n * characters use a third-party library like [_he_](https://mths.be/he).\n *\n * Though the \">\" character is escaped for symmetry, characters like\n * \">\" and \"/\" don't need escaping in HTML and have no special meaning\n * unless they're part of a tag or unquoted attribute value. See\n * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)\n * (under \"semi-related fun fact\") for more details.\n *\n * When working with HTML you should always\n * [quote attribute values](http://wonko.com/post/html-escaping) to reduce\n * XSS vectors.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escape('fred, barney, & pebbles');\n * // => 'fred, barney, & pebbles'\n */\n function escape(string) {\n string = toString(string);\n return (string && reHasUnescapedHtml.test(string))\n ? string.replace(reUnescapedHtml, escapeHtmlChar)\n : string;\n }\n\n /**\n * Escapes the `RegExp` special characters \"^\", \"$\", \"\\\", \".\", \"*\", \"+\",\n * \"?\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", and \"|\" in `string`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escapeRegExp('[lodash](https://lodash.com/)');\n * // => '\\[lodash\\]\\(https://lodash\\.com/\\)'\n */\n function escapeRegExp(string) {\n string = toString(string);\n return (string && reHasRegExpChar.test(string))\n ? string.replace(reRegExpChar, '\\\\$&')\n : string;\n }\n\n /**\n * Converts `string` to\n * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the kebab cased string.\n * @example\n *\n * _.kebabCase('Foo Bar');\n * // => 'foo-bar'\n *\n * _.kebabCase('fooBar');\n * // => 'foo-bar'\n *\n * _.kebabCase('__FOO_BAR__');\n * // => 'foo-bar'\n */\n var kebabCase = createCompounder(function(result, word, index) {\n return result + (index ? '-' : '') + word.toLowerCase();\n });\n\n /**\n * Converts `string`, as space separated words, to lower case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the lower cased string.\n * @example\n *\n * _.lowerCase('--Foo-Bar--');\n * // => 'foo bar'\n *\n * _.lowerCase('fooBar');\n * // => 'foo bar'\n *\n * _.lowerCase('__FOO_BAR__');\n * // => 'foo bar'\n */\n var lowerCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + word.toLowerCase();\n });\n\n /**\n * Converts the first character of `string` to lower case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.lowerFirst('Fred');\n * // => 'fred'\n *\n * _.lowerFirst('FRED');\n * // => 'fRED'\n */\n var lowerFirst = createCaseFirst('toLowerCase');\n\n /**\n * Pads `string` on the left and right sides if it's shorter than `length`.\n * Padding characters are truncated if they can't be evenly divided by `length`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.pad('abc', 8);\n * // => ' abc '\n *\n * _.pad('abc', 8, '_-');\n * // => '_-abc_-_'\n *\n * _.pad('abc', 3);\n * // => 'abc'\n */\n function pad(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n if (!length || strLength >= length) {\n return string;\n }\n var mid = (length - strLength) / 2;\n return (\n createPadding(nativeFloor(mid), chars) +\n string +\n createPadding(nativeCeil(mid), chars)\n );\n }\n\n /**\n * Pads `string` on the right side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padEnd('abc', 6);\n * // => 'abc '\n *\n * _.padEnd('abc', 6, '_-');\n * // => 'abc_-_'\n *\n * _.padEnd('abc', 3);\n * // => 'abc'\n */\n function padEnd(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (string + createPadding(length - strLength, chars))\n : string;\n }\n\n /**\n * Pads `string` on the left side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padStart('abc', 6);\n * // => ' abc'\n *\n * _.padStart('abc', 6, '_-');\n * // => '_-_abc'\n *\n * _.padStart('abc', 3);\n * // => 'abc'\n */\n function padStart(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (createPadding(length - strLength, chars) + string)\n : string;\n }\n\n /**\n * Converts `string` to an integer of the specified radix. If `radix` is\n * `undefined` or `0`, a `radix` of `10` is used unless `value` is a\n * hexadecimal, in which case a `radix` of `16` is used.\n *\n * **Note:** This method aligns with the\n * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category String\n * @param {string} string The string to convert.\n * @param {number} [radix=10] The radix to interpret `value` by.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.parseInt('08');\n * // => 8\n *\n * _.map(['6', '08', '10'], _.parseInt);\n * // => [6, 8, 10]\n */\n function parseInt(string, radix, guard) {\n if (guard || radix == null) {\n radix = 0;\n } else if (radix) {\n radix = +radix;\n }\n return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);\n }\n\n /**\n * Repeats the given string `n` times.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to repeat.\n * @param {number} [n=1] The number of times to repeat the string.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {string} Returns the repeated string.\n * @example\n *\n * _.repeat('*', 3);\n * // => '***'\n *\n * _.repeat('abc', 2);\n * // => 'abcabc'\n *\n * _.repeat('abc', 0);\n * // => ''\n */\n function repeat(string, n, guard) {\n if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n return baseRepeat(toString(string), n);\n }\n\n /**\n * Replaces matches for `pattern` in `string` with `replacement`.\n *\n * **Note:** This method is based on\n * [`String#replace`](https://mdn.io/String/replace).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to modify.\n * @param {RegExp|string} pattern The pattern to replace.\n * @param {Function|string} replacement The match replacement.\n * @returns {string} Returns the modified string.\n * @example\n *\n * _.replace('Hi Fred', 'Fred', 'Barney');\n * // => 'Hi Barney'\n */\n function replace() {\n var args = arguments,\n string = toString(args[0]);\n\n return args.length < 3 ? string : string.replace(args[1], args[2]);\n }\n\n /**\n * Converts `string` to\n * [snake case](https://en.wikipedia.org/wiki/Snake_case).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the snake cased string.\n * @example\n *\n * _.snakeCase('Foo Bar');\n * // => 'foo_bar'\n *\n * _.snakeCase('fooBar');\n * // => 'foo_bar'\n *\n * _.snakeCase('--FOO-BAR--');\n * // => 'foo_bar'\n */\n var snakeCase = createCompounder(function(result, word, index) {\n return result + (index ? '_' : '') + word.toLowerCase();\n });\n\n /**\n * Splits `string` by `separator`.\n *\n * **Note:** This method is based on\n * [`String#split`](https://mdn.io/String/split).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to split.\n * @param {RegExp|string} separator The separator pattern to split by.\n * @param {number} [limit] The length to truncate results to.\n * @returns {Array} Returns the string segments.\n * @example\n *\n * _.split('a-b-c', '-', 2);\n * // => ['a', 'b']\n */\n function split(string, separator, limit) {\n if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {\n separator = limit = undefined;\n }\n limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;\n if (!limit) {\n return [];\n }\n string = toString(string);\n if (string && (\n typeof separator == 'string' ||\n (separator != null && !isRegExp(separator))\n )) {\n separator = baseToString(separator);\n if (!separator && hasUnicode(string)) {\n return castSlice(stringToArray(string), 0, limit);\n }\n }\n return string.split(separator, limit);\n }\n\n /**\n * Converts `string` to\n * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).\n *\n * @static\n * @memberOf _\n * @since 3.1.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the start cased string.\n * @example\n *\n * _.startCase('--foo-bar--');\n * // => 'Foo Bar'\n *\n * _.startCase('fooBar');\n * // => 'Foo Bar'\n *\n * _.startCase('__FOO_BAR__');\n * // => 'FOO BAR'\n */\n var startCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + upperFirst(word);\n });\n\n /**\n * Checks if `string` starts with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=0] The position to search from.\n * @returns {boolean} Returns `true` if `string` starts with `target`,\n * else `false`.\n * @example\n *\n * _.startsWith('abc', 'a');\n * // => true\n *\n * _.startsWith('abc', 'b');\n * // => false\n *\n * _.startsWith('abc', 'b', 1);\n * // => true\n */\n function startsWith(string, target, position) {\n string = toString(string);\n position = position == null\n ? 0\n : baseClamp(toInteger(position), 0, string.length);\n\n target = baseToString(target);\n return string.slice(position, position + target.length) == target;\n }\n\n /**\n * Creates a compiled template function that can interpolate data properties\n * in \"interpolate\" delimiters, HTML-escape interpolated data properties in\n * \"escape\" delimiters, and execute JavaScript in \"evaluate\" delimiters. Data\n * properties may be accessed as free variables in the template. If a setting\n * object is given, it takes precedence over `_.templateSettings` values.\n *\n * **Note:** In the development build `_.template` utilizes\n * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)\n * for easier debugging.\n *\n * For more information on precompiling templates see\n * [lodash's custom builds documentation](https://lodash.com/custom-builds).\n *\n * For more information on Chrome extension sandboxes see\n * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The template string.\n * @param {Object} [options={}] The options object.\n * @param {RegExp} [options.escape=_.templateSettings.escape]\n * The HTML \"escape\" delimiter.\n * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]\n * The \"evaluate\" delimiter.\n * @param {Object} [options.imports=_.templateSettings.imports]\n * An object to import into the template as free variables.\n * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]\n * The \"interpolate\" delimiter.\n * @param {string} [options.sourceURL='lodash.templateSources[n]']\n * The sourceURL of the compiled template.\n * @param {string} [options.variable='obj']\n * The data object variable name.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the compiled template function.\n * @example\n *\n * // Use the \"interpolate\" delimiter to create a compiled template.\n * var compiled = _.template('hello <%= user %>!');\n * compiled({ 'user': 'fred' });\n * // => 'hello fred!'\n *\n * // Use the HTML \"escape\" delimiter to escape data property values.\n * var compiled = _.template('<%- value %>');\n * compiled({ 'value': '